From fe10db6d82eb8162e10b8244a8c6d7a76a2d80e4 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 5 May 2022 17:57:58 +0200 Subject: [PATCH 001/110] better parsing of type sigs --- .../org/enso/compiler/codegen/AstToIr.scala | 27 ++++++ .../compiler/context/SuggestionBuilder.scala | 67 +++++++-------- .../scala/org/enso/compiler/core/IR.scala | 82 +++++++++++++++++++ .../pass/analyse/DataflowAnalysis.scala | 15 ++++ .../test/semantic/TypeSignaturesTest.scala | 69 ++++++++++++++++ 5 files changed, 223 insertions(+), 37 deletions(-) create mode 100644 engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala index a7ab0421d398..7dc7181469c0 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala @@ -890,6 +890,11 @@ object AstToIr { hasDefaultsSuspended, getIdentifiedLocation(callable) ) + case AST.App.Infix(l, AST.Ident.Opr("->"), r) if insideTypeAscription => + translateFunctionType( + List(translateExpression(l, insideTypeSignature = true)), + r + ) case AstView.Lambda(args, body) => if (args.length > 1) { Error.Syntax( @@ -948,6 +953,28 @@ object AstToIr { } } + @tailrec + private def translateFunctionType( + argsAcc: List[Expression], + next: AST + ): Expression = + skipParens(next) match { + case AST.App.Infix(nextArg, AST.Ident.Opr("->"), next) => + translateFunctionType( + argsAcc :+ translateExpression(nextArg, insideTypeSignature = true), + next + ) + case other => + IR.Type.Function( + argsAcc, + translateExpression(other, insideTypeSignature = true), + None + ) + } + + private def skipParens(ast: AST): AST = + AstView.MaybeManyParensed.unapply(ast).getOrElse(ast) + /** Translates an operator section from its [[AST]] representation into the * [[IR]] representation. * 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 d835caf487e4..b41c73996070 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 @@ -378,38 +378,32 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { bindings: Option[BindingAnalysis.Metadata], typeExpr: IR.Expression ): Vector[TypeArg] = { - def go(typeExpr: IR.Expression, args: Vector[TypeArg]): Vector[TypeArg] = - typeExpr match { - case IR.Application.Operator.Binary(left, op, right, _, _, _) => - val arg = for { - leftArg <- go(left.value, Vector()).headOption - rightArg <- go(right.value, Vector()).headOption - } yield TypeArg.Binary(leftArg, rightArg, op.name) - args :++ arg - case IR.Function.Lambda(List(targ), body, _, _, _, _) => - val typeName = targ.name.name - val tdef = resolveTypeName(bindings, typeName) - .getOrElse(TypeArg.Value(QualifiedName.simpleName(typeName))) - go(body, args :+ tdef) - case IR.Application.Prefix(tfun, targs, _, _, _, _) => - val appFunction = go(tfun, Vector()).head - val appArgs = targs.flatMap(arg => go(arg.value, Vector())) - args :+ TypeArg.Application(appFunction, appArgs.toVector) - case tname: IR.Name => - val typeName = tname.name - val tdef = resolveTypeName(bindings, typeName) - .getOrElse(TypeArg.Value(QualifiedName.simpleName(typeName))) - args :+ tdef - case _ => - args - } - - typeExpr match { - case IR.Application.Operator.Binary(left, _, right, _, _, _) => - val arg = TypeArg.Function(go(left.value, Vector())) - go(right.value, Vector(arg)) - case expr => - go(expr, Vector()) + def go(expr: IR.Expression): TypeArg = expr match { + case fn: IR.Type.Function => + TypeArg.Function(fn.args.map(go).toVector, go(fn.result)) + case app: IR.Application.Prefix => + TypeArg.Application( + go(app.function), + app.arguments.map(c => go(c.value)).toVector + ) + case bin: IR.Application.Operator.Binary => + TypeArg.Binary( + go(bin.left.value), + go(bin.right.value), + bin.operator.name + ) + case tname: IR.Name => + val typeName = tname.name + val tdef = resolveTypeName(bindings, typeName) + .getOrElse(TypeArg.Value(QualifiedName.simpleName(typeName))) + tdef + case _ => + TypeArg.Value(QualifiedName.fromString(Any)) + } + val r = go(typeExpr) + r match { + case fn: TypeArg.Function => fn.arguments :+ fn.result + case _ => Vector(r) } } @@ -544,10 +538,8 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { def go(targ: TypeArg, level: Int): String = targ match { case TypeArg.Value(name) => name.toString - case TypeArg.Function(Vector(typeArg)) => - val typeName = go(typeArg, level) - if (level > 0) s"($typeName)" else typeName - case TypeArg.Function(types) => + case TypeArg.Function(args, ret) => + val types = args :+ ret val typeList = types.map(go(_, level + 1)) if (level > 0) typeList.mkString("(", " -> ", ")") else typeList.mkString(" -> ") @@ -668,7 +660,8 @@ object SuggestionBuilder { * * @param signature the list of types defining the function */ - case class Function(signature: Vector[TypeArg]) extends TypeArg + case class Function(arguments: Vector[TypeArg], result: TypeArg) + extends TypeArg /** Binary operator, like `A | B` * 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 144f0cffa13f..8cd06ddaaab7 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 @@ -2990,6 +2990,88 @@ object IR { val name: String } + sealed case class Function( + args: List[Expression], + result: Expression, + override val location: Option[IdentifiedLocation], + override val passData: MetadataStorage = MetadataStorage(), + override val diagnostics: DiagnosticStorage = DiagnosticStorage() + ) extends Type { + override protected var id: Identifier = randomId + + def copy( + args: List[Expression] = args, + result: Expression = result, + location: Option[IdentifiedLocation] = location, + passData: MetadataStorage = passData, + diagnostics: DiagnosticStorage = diagnostics, + id: Identifier = id + ): Function = { + val res = Function(args, result, location, passData, diagnostics) + res.id = id + res + } + + /** @inheritdoc */ + override def duplicate( + keepLocations: Boolean = true, + keepMetadata: Boolean = true, + keepDiagnostics: Boolean = true, + keepIdentifiers: Boolean = false + ): Function = + copy( + args = args.map( + _.duplicate( + keepLocations, + keepMetadata, + keepDiagnostics, + keepIdentifiers + ) + ), + result = result.duplicate( + keepLocations, + keepMetadata, + keepDiagnostics, + keepIdentifiers + ), + location = if (keepLocations) location else None, + passData = + if (keepMetadata) passData.duplicate else MetadataStorage(), + diagnostics = + if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(), + id = if (keepIdentifiers) id else randomId + ) + + /** @inheritdoc */ + override def setLocation( + location: Option[IdentifiedLocation] + ): Function = copy(location = location) + + /** @inheritdoc */ + override def mapExpressions(fn: Expression => Expression): Function = { + copy(args = args.map(fn), result = fn(result)) + } + + /** @inheritdoc */ + override def toString: String = + s"""IR.Type.Function( + |args = $args, + |result = $result, + |location = $location, + |passData = ${this.showPassData}, + |diagnostics = $diagnostics, + |id = $id + |) + |""".toSingleLine + + /** @inheritdoc */ + override def children: List[IR] = args :+ result + + /** @inheritdoc */ + override def showCode(indent: Int): String = + s"${args.map(_.showCode()).mkString(" -> ")} -> ${result.showCode()}" + } + /** The ascription of a type to a value. * * @param typed the expression being ascribed a type diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala index 729b43935fb4..0a3841966dcc 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala @@ -367,6 +367,21 @@ case object DataflowAnalysis extends IRPass { signature = analyseExpression(signature, info) ) .updateMetadata(this -->> info) + + case fun @ IR.Type.Function(args, result, _, _, _) => + val funDep = asStatic(fun) + val argDeps = args.map(asStatic) + val resDep = asStatic(result) + argDeps.foreach(info.dependents.updateAt(_, Set(funDep))) + info.dependents.updateAt(resDep, Set(funDep)) + info.dependencies.updateAt(funDep, Set(resDep :: argDeps: _*)) + + fun + .copy( + args = args.map(analyseExpression(_, info)), + result = analyseExpression(result, info) + ) + .updateMetadata(this -->> info) case ctx @ IR.Type.Context(typed, context, _, _, _) => val ctxDep = asStatic(ctx) val typedDep = asStatic(typed) diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala new file mode 100644 index 000000000000..4f3fbd0ebd8e --- /dev/null +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala @@ -0,0 +1,69 @@ +package org.enso.compiler.test.semantic + +import org.enso.compiler.core.IR +import org.enso.compiler.pass.resolve.TypeSignatures +import org.enso.interpreter.runtime +import org.enso.interpreter.runtime.Context +import org.enso.interpreter.test.InterpreterContext +import org.enso.pkg.QualifiedName +import org.enso.polyglot.{LanguageInfo, MethodNames} +import org.scalatest.matchers.should.Matchers +import org.scalatest.wordspec.AnyWordSpecLike + +class TypeSignaturesTest extends AnyWordSpecLike with Matchers { + private val ctx = new InterpreterContext() + private val langCtx = ctx.ctx + .getBindings(LanguageInfo.ID) + .invokeMember(MethodNames.TopScope.LEAK_CONTEXT) + .asHostObject[Context]() + + private val Module = QualifiedName(List("Unnamed"), "Test") + + implicit private class PreprocessModule(code: String) { + def preprocessModule: IR.Module = { + val module = new runtime.Module(Module, null, code) + langCtx.getCompiler.run(module) + module.getIr + } + } + + sealed private trait Sig { + def ->(that: Sig): Sig = that match { + case Fn(args, r) => Fn(this :: args, r) + case _ => Fn(List(this), that) + } + } + private case class Name(name: String) extends Sig + private case class Fn(args: List[Sig], result: Sig) extends Sig + private case class Unknown(ir: IR.Expression) extends Sig + + implicit private def toName(str: String): Name = Name(str) + + private def simpl(expr: IR.Expression): Sig = expr match { + case fn: IR.Type.Function => Fn(fn.args.map(simpl), simpl(fn.result)) + case n: IR.Name => Name(n.name) + case _ => Unknown(expr) + } + + private def getSignature(module: IR.Module, methodName: String): Sig = { + val m = module.bindings.find { + case m: IR.Module.Scope.Definition.Method => + m.methodName.name == methodName + case _ => false + }.get + val sig = m.unsafeGetMetadata(TypeSignatures, "come on").signature + simpl(sig) + } + + "Type Signatures" should { + "be parsed in a simple scenario" in { + val code = + """ + |foo : Text -> Number + |foo a = 42""".stripMargin + val module = code.preprocessModule + getSignature(module, "foo") shouldEqual ("Text" -> "Number") + } + } + +} From 084cdab525943399245b6bd9660d51afc57c29ba Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 6 May 2022 12:52:31 +0200 Subject: [PATCH 002/110] testing facilities --- .../test/semantic/TypeSignaturesTest.scala | 61 ++++++++++++++----- 1 file changed, 47 insertions(+), 14 deletions(-) diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala index 4f3fbd0ebd8e..5855eb2e5810 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala @@ -7,6 +7,7 @@ import org.enso.interpreter.runtime.Context import org.enso.interpreter.test.InterpreterContext import org.enso.pkg.QualifiedName import org.enso.polyglot.{LanguageInfo, MethodNames} +import org.scalatest.matchers.{MatchResult, Matcher} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike @@ -27,32 +28,64 @@ class TypeSignaturesTest extends AnyWordSpecLike with Matchers { } } - sealed private trait Sig { + def typeAs(sig: Sig): TypeMatcher = TypeMatcher(sig) + + case class TypeMatcher(sig: Sig) extends Matcher[IR.Expression] { + private def findInequalityWitness( + sig: Sig, + expr: IR.Expression + ): Option[(Sig, IR.Expression)] = (sig, expr) match { + case (Name(n), t: IR.Name.Literal) if n == t.name => None + case (Fn(args, res), t: IR.Type.Function) => + if (args.length != t.args.length) { + return Some((sig, expr)) + } + args + .lazyZip(t.args) + .flatMap(findInequalityWitness) + .headOption + .orElse(findInequalityWitness(res, t.result)) + case _ => Some((sig, expr)) + } + + override def apply(left: IR.Expression): MatchResult = { + findInequalityWitness(sig, left) match { + case Some((s, t)) => + MatchResult( + matches = false, + s""" + |$left does not match $sig. + |Analysis: + |sub-expression $t did not match fragment $s. + |""".stripMargin, + "The type matched the matcher, but it should not." + ) + case _ => MatchResult(matches = true, "", "") + } + } + } + + sealed trait Sig { def ->(that: Sig): Sig = that match { case Fn(args, r) => Fn(this :: args, r) case _ => Fn(List(this), that) } } - private case class Name(name: String) extends Sig - private case class Fn(args: List[Sig], result: Sig) extends Sig - private case class Unknown(ir: IR.Expression) extends Sig + case class Name(name: String) extends Sig + case class Fn(args: List[Sig], result: Sig) extends Sig implicit private def toName(str: String): Name = Name(str) - private def simpl(expr: IR.Expression): Sig = expr match { - case fn: IR.Type.Function => Fn(fn.args.map(simpl), simpl(fn.result)) - case n: IR.Name => Name(n.name) - case _ => Unknown(expr) - } - - private def getSignature(module: IR.Module, methodName: String): Sig = { + private def getSignature( + module: IR.Module, + methodName: String + ): IR.Expression = { val m = module.bindings.find { case m: IR.Module.Scope.Definition.Method => m.methodName.name == methodName case _ => false }.get - val sig = m.unsafeGetMetadata(TypeSignatures, "come on").signature - simpl(sig) + m.unsafeGetMetadata(TypeSignatures, "come on").signature } "Type Signatures" should { @@ -62,7 +95,7 @@ class TypeSignaturesTest extends AnyWordSpecLike with Matchers { |foo : Text -> Number |foo a = 42""".stripMargin val module = code.preprocessModule - getSignature(module, "foo") shouldEqual ("Text" -> "Number") + getSignature(module, "foo") should typeAs("Text" -> "Number") } } From 2d99f1a43147b66ebb24e15c9b8bc5ae871cbfb7 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 6 May 2022 13:21:28 +0200 Subject: [PATCH 003/110] resolution testing --- .../org/enso/compiler/data/BindingsMap.scala | 46 +++++++++- .../compiler/pass/resolve/TypeNames.scala | 86 +++++++++++++++++++ .../test/semantic/TypeSignaturesTest.scala | 66 ++++++++++++-- 3 files changed, 188 insertions(+), 10 deletions(-) create mode 100644 engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala 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 3de9dedf2d3a..49f083be2f04 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 @@ -783,6 +783,8 @@ object BindingsMap { * @return `this`, converted to concrete form */ def toConcrete(moduleMap: ModuleMap): Option[ResolvedTypeName] + + def qualifiedName: QualifiedName } /** A name resolved to a sum type. @@ -813,7 +815,8 @@ object BindingsMap { module.toConcrete(moduleMap).map(module => this.copy(module = module)) } - def qualifiedName: QualifiedName = module.getName.createChild(tp.name) + override def qualifiedName: QualifiedName = + module.getName.createChild(tp.name) } /** A result of successful name resolution. @@ -854,7 +857,8 @@ object BindingsMap { module.toConcrete(moduleMap).map(module => this.copy(module = module)) } - def qualifiedName: QualifiedName = module.getName.createChild(cons.name) + override def qualifiedName: QualifiedName = + module.getName.createChild(cons.name) } /** A representation of a name being resolved to a module. @@ -874,6 +878,8 @@ object BindingsMap { ): Option[ResolvedModule] = { module.toConcrete(moduleMap).map(module => this.copy(module = module)) } + + override def qualifiedName: QualifiedName = module.getName } /** A representation of a name being resolved to a method call. @@ -912,6 +918,9 @@ object BindingsMap { def unsafeGetIr(missingMessage: String): IR.Module.Scope.Definition = getIr.getOrElse(throw new CompilerError(missingMessage)) + + override def qualifiedName: QualifiedName = + module.getName.createChild(method.name) } /** A representation of a name being resolved to a polyglot symbol. @@ -934,6 +943,9 @@ object BindingsMap { ): Option[ResolvedPolyglotSymbol] = { module.toConcrete(moduleMap).map(module => this.copy(module = module)) } + + override def qualifiedName: QualifiedName = + module.getName.createChild(symbol.name) } /** A representation of an error during name resolution. @@ -951,6 +963,36 @@ object BindingsMap { */ case object ResolutionNotFound extends ResolutionError + /** A metadata-friendly storage for resolutions */ + case class TypeResolution(target: ResolvedTypeName) extends IRPass.Metadata { + + /** The name of the metadata as a string. */ + override val metadataName: String = "Resolution" + + /** @inheritdoc */ + override def prepareForSerialization(compiler: Compiler): TypeResolution = + this.copy(target = this.target.toAbstract) + + /** @inheritdoc */ + override def restoreFromSerialization( + compiler: Compiler + ): Option[TypeResolution] = { + val moduleMap = compiler.context.getPackageRepository.getModuleMap + this.target.toConcrete(moduleMap).map(t => this.copy(target = t)) + } + + /** Creates a duplicate of this metadata if applicable. + * + * This method should employ deep-copy semantics where appropriate. It may + * return None to indicate that this metadata should not be preserved + * during duplication. + * + * @return Some duplicate of this metadata or None if this metadata should + * not be preserved + */ + override def duplicate(): Option[IRPass.Metadata] = Some(this) + } + /** A metadata-friendly storage for resolutions */ case class Resolution(target: ResolvedName) extends IRPass.Metadata { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala new file mode 100644 index 000000000000..bfc7bf92f2dd --- /dev/null +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala @@ -0,0 +1,86 @@ +package org.enso.compiler.pass.resolve + +import org.enso.compiler.context.{FreshNameSupply, InlineContext, ModuleContext} +import org.enso.compiler.core.IR +import org.enso.compiler.core.ir.MetadataStorage.ToPair +import org.enso.compiler.data.BindingsMap +import org.enso.compiler.data.BindingsMap.{Resolution, ResolvedConstructor, ResolvedMethod} +import org.enso.compiler.exception.CompilerError +import org.enso.compiler.pass.IRPass +import org.enso.compiler.pass.analyse.{AliasAnalysis, BindingAnalysis} +import org.enso.interpreter.Constants + +import scala.annotation.unused + +/** Resolves and desugars referent name occurences in non-pattern contexts. + * + * 1. Attaches resolution metadata to encountered constructors, modules, + * and polygot symbols. + * 2. Desugars encountered method references into proper applications. + * 3. Resolves qualified calls to constructors, i.e. a call of the form + * `KnownModule.consName a b c` is transformed into `KnownCons a b c`, + * if `consName` refers to a constructor and `KnownModule` was successfully + * resolved to a module. + */ +case object TypeNames extends IRPass { + + /** The type of the metadata object that the pass writes to the IR. */ + override type Metadata = BindingsMap.TypeResolution + + /** The type of configuration for the pass. */ + override type Config = IRPass.Configuration.Default + + /** The passes that this pass depends _directly_ on to run. */ + override val precursorPasses: Seq[IRPass] = + Seq(BindingAnalysis) + + /** The passes that are invalidated by running this pass. */ + override val invalidatedPasses: Seq[IRPass] = Seq() + + /** Executes the pass on the provided `ir`, and returns a possibly transformed + * or annotated version of `ir`. + * + * @param ir the Enso IR to process + * @param moduleContext a context object that contains the information needed + * to process a module + * @return `ir`, possibly having made transformations or annotations to that + * IR. + */ + override def runModule( + ir: IR.Module, + moduleContext: ModuleContext + ): IR.Module = { + ??? + } + + /** Executes the pass on the provided `ir`, and returns a possibly transformed + * or annotated version of `ir` in an inline context. + * + * @param ir the Enso IR to process + * @param inlineContext a context object that contains the information needed + * for inline evaluation + * @return `ir`, possibly having made transformations or annotations to that + * IR. + */ + override def runExpression( + ir: IR.Expression, + inlineContext: InlineContext + ): IR.Expression = { + val scopeMap = inlineContext.module.getIr.unsafeGetMetadata( + BindingAnalysis, + "No binding analysis on the module" + ) + val freshNameSupply = inlineContext.freshNameSupply.getOrElse( + throw new CompilerError( + "No fresh name supply passed to UppercaseNames resolver." + ) + ) + ??? + } + + /** @inheritdoc */ + override def updateMetadataInDuplicate[T <: IR]( + @unused sourceIr: T, + copyOfIr: T + ): T = copyOfIr +} diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala index 5855eb2e5810..ebcef6a5def8 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala @@ -1,7 +1,7 @@ package org.enso.compiler.test.semantic import org.enso.compiler.core.IR -import org.enso.compiler.pass.resolve.TypeSignatures +import org.enso.compiler.pass.resolve.{TypeNames, TypeSignatures} import org.enso.interpreter.runtime import org.enso.interpreter.runtime.Context import org.enso.interpreter.test.InterpreterContext @@ -34,29 +34,60 @@ class TypeSignaturesTest extends AnyWordSpecLike with Matchers { private def findInequalityWitness( sig: Sig, expr: IR.Expression - ): Option[(Sig, IR.Expression)] = (sig, expr) match { - case (Name(n), t: IR.Name.Literal) if n == t.name => None + ): Option[(Sig, IR.Expression, String)] = (sig, expr) match { + case (Name(n), t: IR.Name.Literal) if n == t.name => + if (n == t.name) { + None + } else { + Some(sig, expr, "names do not match") + } + case (AnyQualName(n), _) => + val meta = expr.getMetadata(TypeNames) + if (meta.isEmpty) { + return Some((sig, expr, "the expression does not have a resolution")) + } + meta match { + case None => + Some((sig, expr, "the expression does not have a resolution")) + case Some(resolution) => + if (resolution.target.qualifiedName == n) { + None + } else { + Some( + ( + sig, + expr, + s"The resolution is ${resolution.target.qualifiedName}, but expected ${n}" + ) + ) + } + } case (Fn(args, res), t: IR.Type.Function) => if (args.length != t.args.length) { - return Some((sig, expr)) + return Some((sig, expr, "arity does not match")) } args .lazyZip(t.args) .flatMap(findInequalityWitness) .headOption .orElse(findInequalityWitness(res, t.result)) - case _ => Some((sig, expr)) + case _ => Some((sig, expr, "constructors are incompatible")) } override def apply(left: IR.Expression): MatchResult = { findInequalityWitness(sig, left) match { - case Some((s, t)) => + case Some((s, t, r)) => MatchResult( matches = false, s""" |$left does not match $sig. |Analysis: - |sub-expression $t did not match fragment $s. + | sub-expression + | ${t.showCode()} + | ($t) + | did not match fragment $s + | because $r. + | |""".stripMargin, "The type matched the matcher, but it should not." ) @@ -72,9 +103,14 @@ class TypeSignaturesTest extends AnyWordSpecLike with Matchers { } } case class Name(name: String) extends Sig + case class AnyQualName(name: QualifiedName) extends Sig case class Fn(args: List[Sig], result: Sig) extends Sig - implicit private def toName(str: String): Name = Name(str) + implicit private def fromString(str: String): Sig = { + if (str.contains(".")) { + AnyQualName(QualifiedName.fromString(str)) + } else { Name(str) } + } private def getSignature( module: IR.Module, @@ -97,6 +133,20 @@ class TypeSignaturesTest extends AnyWordSpecLike with Matchers { val module = code.preprocessModule getSignature(module, "foo") should typeAs("Text" -> "Number") } + + "resolve local names" in { + val code = + """ + |type A + |type B + | + |foo : A -> B + |foo a = 42""".stripMargin + val module = code.preprocessModule + getSignature(module, "foo") should typeAs( + "Unnamed.Test.A" -> "Unnamed.Test.B" + ) + } } } From 1b3457bd2758fd366b1be6b3bba5c99677a4634d Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 6 May 2022 13:40:35 +0200 Subject: [PATCH 004/110] plug in basic resolution --- .../main/scala/org/enso/compiler/Passes.scala | 1 + .../compiler/pass/resolve/TypeNames.scala | 44 ++++++++++++------- .../test/semantic/TypeSignaturesTest.scala | 25 +++++++---- 3 files changed, 45 insertions(+), 25 deletions(-) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/Passes.scala b/engine/runtime/src/main/scala/org/enso/compiler/Passes.scala index 614fb096a0a3..82828a128e08 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/Passes.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/Passes.scala @@ -57,6 +57,7 @@ class Passes( ExpressionAnnotations, AliasAnalysis, UppercaseNames, + TypeNames, MethodCalls, VectorLiterals, FullyAppliedFunctionUses, diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala index bfc7bf92f2dd..e43ed4c9534c 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala @@ -1,14 +1,12 @@ package org.enso.compiler.pass.resolve -import org.enso.compiler.context.{FreshNameSupply, InlineContext, ModuleContext} +import org.enso.compiler.context.{InlineContext, ModuleContext} import org.enso.compiler.core.IR import org.enso.compiler.core.ir.MetadataStorage.ToPair import org.enso.compiler.data.BindingsMap -import org.enso.compiler.data.BindingsMap.{Resolution, ResolvedConstructor, ResolvedMethod} -import org.enso.compiler.exception.CompilerError +import org.enso.compiler.data.BindingsMap.TypeResolution import org.enso.compiler.pass.IRPass -import org.enso.compiler.pass.analyse.{AliasAnalysis, BindingAnalysis} -import org.enso.interpreter.Constants +import org.enso.compiler.pass.analyse.BindingAnalysis import scala.annotation.unused @@ -50,9 +48,32 @@ case object TypeNames extends IRPass { ir: IR.Module, moduleContext: ModuleContext ): IR.Module = { - ??? + val bindingsMap = + ir.unsafeGetMetadata(BindingAnalysis, "bindings analysis did not run") + ir.copy(bindings = ir.bindings.map { d => + d.getMetadata(TypeSignatures) + .map(s => + d.updateMetadata( + TypeSignatures -->> TypeSignatures.Signature( + resolveSignature(bindingsMap, s.signature) + ) + ) + ) + .getOrElse(d) + }) } + private def resolveSignature( + bindingsMap: BindingsMap, + expression: IR.Expression + ): IR.Expression = + expression.transformExpressions { case n: IR.Name.Literal => + bindingsMap + .resolveTypeName(n.name) + .map(res => n.updateMetadata(this -->> TypeResolution(res))) + .getOrElse(n) + } + /** Executes the pass on the provided `ir`, and returns a possibly transformed * or annotated version of `ir` in an inline context. * @@ -66,16 +87,7 @@ case object TypeNames extends IRPass { ir: IR.Expression, inlineContext: InlineContext ): IR.Expression = { - val scopeMap = inlineContext.module.getIr.unsafeGetMetadata( - BindingAnalysis, - "No binding analysis on the module" - ) - val freshNameSupply = inlineContext.freshNameSupply.getOrElse( - throw new CompilerError( - "No fresh name supply passed to UppercaseNames resolver." - ) - ) - ??? + ir } /** @inheritdoc */ diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala index ebcef6a5def8..866179579ac6 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala @@ -39,7 +39,7 @@ class TypeSignaturesTest extends AnyWordSpecLike with Matchers { if (n == t.name) { None } else { - Some(sig, expr, "names do not match") + Some((sig, expr, "names do not match")) } case (AnyQualName(n), _) => val meta = expr.getMetadata(TypeNames) @@ -80,7 +80,10 @@ class TypeSignaturesTest extends AnyWordSpecLike with Matchers { MatchResult( matches = false, s""" - |$left does not match $sig. + |${left.showCode()} + |($left) + |does not match + |$sig. |Analysis: | sub-expression | ${t.showCode()} @@ -97,9 +100,9 @@ class TypeSignaturesTest extends AnyWordSpecLike with Matchers { } sealed trait Sig { - def ->(that: Sig): Sig = that match { - case Fn(args, r) => Fn(this :: args, r) - case _ => Fn(List(this), that) + def ->:(that: Sig): Sig = this match { + case Fn(args, r) => Fn(that :: args, r) + case _ => Fn(List(that), this) } } case class Name(name: String) extends Sig @@ -131,20 +134,24 @@ class TypeSignaturesTest extends AnyWordSpecLike with Matchers { |foo : Text -> Number |foo a = 42""".stripMargin val module = code.preprocessModule - getSignature(module, "foo") should typeAs("Text" -> "Number") + getSignature(module, "foo") should typeAs("Text" ->: "Number") } - "resolve local names" in { + "resolve locally defined names" in { val code = """ |type A |type B | - |foo : A -> B + |type C + | type X + | type D + | + |foo : A -> B -> C -> X -> D |foo a = 42""".stripMargin val module = code.preprocessModule getSignature(module, "foo") should typeAs( - "Unnamed.Test.A" -> "Unnamed.Test.B" + "Unnamed.Test.A" ->: "Unnamed.Test.B" ->: "Unnamed.Test.C" ->: "Unnamed.Test.X" ->: "Unnamed.Test.D" ) } } From aeb2b28a8a58c1c3398eccfcedc087cdb2f96e37 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 6 May 2022 16:08:37 +0200 Subject: [PATCH 005/110] resolution of imported atoms --- .../runtime/scope/TopLevelScope.java | 7 ++ .../org/enso/compiler/PackageRepository.scala | 8 ++ .../org/enso/compiler/data/BindingsMap.scala | 3 +- .../test/semantic/TypeSignaturesTest.scala | 87 +++++++++++++------ 4 files changed, 76 insertions(+), 29 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java index 72744005450c..b71a93d98e29 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java @@ -70,6 +70,13 @@ public Module createModule(QualifiedName name, Package pkg, Truffle return module; } + public Module createModule(QualifiedName name, Package pkg, String source) { + Module module = new Module(name, pkg, source); + packageRepository.registerModuleCreatedInRuntime(module); + return module; + } + + /** * Returns the builtins module. * diff --git a/engine/runtime/src/main/scala/org/enso/compiler/PackageRepository.scala b/engine/runtime/src/main/scala/org/enso/compiler/PackageRepository.scala index fc7f1a324d10..1e417e4101d0 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/PackageRepository.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/PackageRepository.scala @@ -92,6 +92,8 @@ trait PackageRepository { */ def registerModuleCreatedInRuntime(module: Module): Unit + def registerSyntheticPackage(namespace: String, name: String): Unit + /** Removes a module with the given name from the list of loaded modules. */ def deregisterModule(qualifiedName: String): Unit @@ -457,6 +459,12 @@ object PackageRepository { override def registerModuleCreatedInRuntime(module: Module): Unit = registerModule(module) + override def registerSyntheticPackage( + namespace: String, + name: String + ): Unit = + loadedPackages.put(LibraryName(namespace, name), None) + private def registerModule(module: Module): Unit = loadedModules.put(module.getName.toString, module) 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 49f083be2f04..5034dbbdd7b3 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 @@ -211,12 +211,11 @@ case class BindingsMap( */ def resolveTypeName( name: String - ): Either[ResolutionError, ResolvedTypeName] = { + ): Either[ResolutionError, ResolvedTypeName] = types.find(_.name == name) match { case Some(value) => Right(ResolvedType(currentModule, value)) case None => resolveUppercaseName(name) } - } /** Resolves a name in the context of current module. * diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala index 866179579ac6..619d92c74f2f 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala @@ -11,22 +11,22 @@ import org.scalatest.matchers.{MatchResult, Matcher} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike -class TypeSignaturesTest extends AnyWordSpecLike with Matchers { - private val ctx = new InterpreterContext() - private val langCtx = ctx.ctx - .getBindings(LanguageInfo.ID) - .invokeMember(MethodNames.TopScope.LEAK_CONTEXT) - .asHostObject[Context]() - - private val Module = QualifiedName(List("Unnamed"), "Test") - - implicit private class PreprocessModule(code: String) { - def preprocessModule: IR.Module = { - val module = new runtime.Module(Module, null, code) - langCtx.getCompiler.run(module) - module.getIr +trait TypeMatchers { + sealed trait Sig { + def ->:(that: Sig): Sig = this match { + case Fn(args, r) => Fn(that :: args, r) + case _ => Fn(List(that), this) } } + case class Name(name: String) extends Sig + case class AnyQualName(name: QualifiedName) extends Sig + case class Fn(args: List[Sig], result: Sig) extends Sig + + implicit def fromString(str: String): Sig = { + if (str.contains(".")) { + AnyQualName(QualifiedName.fromString(str)) + } else { Name(str) } + } def typeAs(sig: Sig): TypeMatcher = TypeMatcher(sig) @@ -98,21 +98,41 @@ class TypeSignaturesTest extends AnyWordSpecLike with Matchers { } } } +} - sealed trait Sig { - def ->:(that: Sig): Sig = this match { - case Fn(args, r) => Fn(that :: args, r) - case _ => Fn(List(that), this) - } - } - case class Name(name: String) extends Sig - case class AnyQualName(name: QualifiedName) extends Sig - case class Fn(args: List[Sig], result: Sig) extends Sig +class TypeSignaturesTest + extends AnyWordSpecLike + with Matchers + with TypeMatchers { - implicit private def fromString(str: String): Sig = { - if (str.contains(".")) { - AnyQualName(QualifiedName.fromString(str)) - } else { Name(str) } + private val ctx = new InterpreterContext() + private val langCtx = ctx.ctx + .getBindings(LanguageInfo.ID) + .invokeMember(MethodNames.TopScope.LEAK_CONTEXT) + .asHostObject[Context]() + + private val Module = QualifiedName.fromString("Unnamed.Test") + + langCtx.getPackageRepository.registerSyntheticPackage("my_pkg", "My_Lib") + langCtx.getTopScope.createModule( + QualifiedName.fromString("my_pkg.My_Lib.Util"), + null, + s""" + |type Util_1 + |type Util_2 + | + |type Util_Sum + | type Util_Sum_1 + | type Util_Sum_2 + |""".stripMargin + ) + + implicit private class PreprocessModule(code: String) { + def preprocessModule: IR.Module = { + val module = new runtime.Module(Module, null, code) + langCtx.getCompiler.run(module) + module.getIr + } } private def getSignature( @@ -154,6 +174,19 @@ class TypeSignaturesTest extends AnyWordSpecLike with Matchers { "Unnamed.Test.A" ->: "Unnamed.Test.B" ->: "Unnamed.Test.C" ->: "Unnamed.Test.X" ->: "Unnamed.Test.D" ) } + + "resolve imported names" in { + val code = """ + |from my_pkg.My_Lib.Util import all + | + |foo : Util_1 -> Util_2 + |foo a = 23 + |""".stripMargin + val module = code.preprocessModule + getSignature(module, "foo") should typeAs( + "my_pkg.My_Lib.Util.Util_1" ->: "my_pkg.My_Lib.Util.Util_2" + ) + } } } From 8745762108af688500377ad7e9bff9176de8d6e3 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 6 May 2022 17:54:26 +0200 Subject: [PATCH 006/110] make types exportable --- .../scala/org/enso/compiler/core/IR.scala | 4 +- .../org/enso/compiler/data/BindingsMap.scala | 110 +++++++++++++----- .../compiler/phase/ExportsResolution.scala | 20 +++- .../enso/compiler/phase/StubIrBuilder.scala | 3 +- .../test/semantic/TypeSignaturesTest.scala | 13 +++ 5 files changed, 117 insertions(+), 33 deletions(-) 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 8cd06ddaaab7..820d501cafbb 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 @@ -6991,13 +6991,15 @@ object IR { definitionModule, cons ) => - s" Type ${cons.name} defined in module ${definitionModule.getName};" + s" Constructor ${cons.name} defined in module ${definitionModule.getName};" case BindingsMap.ResolvedModule(module) => s" The module ${module.getName};" case BindingsMap.ResolvedPolyglotSymbol(_, symbol) => s" The imported polyglot symbol ${symbol.name};" case BindingsMap.ResolvedMethod(module, symbol) => s" The method ${symbol.name} defined in module ${module.getName}" + case BindingsMap.ResolvedType(module, typ) => + s" Type ${typ.name} defined in module ${module.getName}" } (firstLine :: lines).mkString("\n") case BindingsMap.ResolutionNotFound => 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 5034dbbdd7b3..889905149aab 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 @@ -46,6 +46,10 @@ case class BindingsMap( */ var exportedSymbols: Map[String, List[ResolvedName]] = Map() + /** Symbols exported by [[currentModule]]. + */ + var allExportedSymbols: Map[String, List[ResolvedTypeName]] = Map() + /** @inheritdoc */ override def prepareForSerialization( compiler: Compiler @@ -72,6 +76,9 @@ case class BindingsMap( copy.exportedSymbols = this.exportedSymbols.map { case (key, value) => key -> value.map(name => name.toAbstract) } + copy.allExportedSymbols = this.allExportedSymbols.map { case (key, value) => + key -> value.map(_.toAbstract) + } copy } @@ -108,7 +115,7 @@ case class BindingsMap( } val withSymbols: Option[BindingsMap] = withExports.flatMap { bindings => - val newSymbols = this.exportedSymbols.map { case (key, value) => + val newSymbols = this.allExportedSymbols.map { case (key, value) => val newValue = value.map(_.toConcrete(moduleMap)) if (newValue.exists(_.isEmpty)) { key -> None @@ -120,7 +127,16 @@ case class BindingsMap( if (newSymbols.exists { case (_, v) => v.isEmpty }) { None } else { - bindings.exportedSymbols = newSymbols.map { case (k, v) => k -> v.get } + bindings.allExportedSymbols = newSymbols.map { case (k, v) => + k -> v.get + } + bindings.exportedSymbols = bindings.allExportedSymbols.flatMap { + case (k, v) => + v.collect { case v: ResolvedName => v } match { + case List() => None + case other => Some((k, other)) + } + } Some(bindings) } } @@ -128,6 +144,10 @@ case class BindingsMap( withSymbols } + private def findTypeCandidates(name: String): List[ResolvedType] = { + types.filter(_.name == name).map(ResolvedType(currentModule, _)) + } + private def findConstructorCandidates( name: String ): List[ResolvedConstructor] = { @@ -150,7 +170,18 @@ case class BindingsMap( .map(ResolvedMethod(currentModule, _)) } - private def findLocalCandidates(name: String): List[ResolvedName] = { + private def findLocalCandidates( + name: String, + includeTypes: Boolean + ): List[ResolvedTypeName] = { + if (includeTypes) { + val types = findTypeCandidates(name) + if (types.nonEmpty) { + // If types are included – they take precedence. + // Remove this logic when sum types get proper runtime meaning. + return types + } + } val conses = findConstructorCandidates(name) val polyglot = findPolyglotCandidates(name) val methods = findMethodCandidates(name) @@ -169,8 +200,9 @@ case class BindingsMap( } private def findExportedCandidatesInImports( - name: String - ): List[ResolvedName] = { + name: String, + includeTypes: Boolean + ): List[ResolvedTypeName] = { resolvedImports .flatMap { imp => @@ -182,7 +214,7 @@ case class BindingsMap( BindingAnalysis, "Wrong pass ordering. Running resolution on an unparsed module." ) - .findExportedSymbolsFor(name) + .findExportedSymbolsFor(name, includeTypes) case ModuleReference.Abstract(name) => throw new CompilerError( s"Cannot find export candidates for abstract module reference $name." @@ -192,9 +224,9 @@ case class BindingsMap( } } - private def handleAmbiguity( - candidates: List[ResolvedName] - ): Either[ResolutionError, ResolvedName] = { + private def handleAmbiguity[A <: ResolvedTypeName]( + candidates: List[A] + ): Either[ResolutionError, A] = { candidates.distinct match { case List() => Left(ResolutionNotFound) case List(it) => Right(it) @@ -212,10 +244,7 @@ case class BindingsMap( def resolveTypeName( name: String ): Either[ResolutionError, ResolvedTypeName] = - types.find(_.name == name) match { - case Some(value) => Right(ResolvedType(currentModule, value)) - case None => resolveUppercaseName(name) - } + resolveUppercaseName(name, includeTypes = true) /** Resolves a name in the context of current module. * @@ -225,8 +254,14 @@ case class BindingsMap( */ def resolveUppercaseName( name: String - ): Either[ResolutionError, ResolvedName] = { - val local = findLocalCandidates(name) + ): Either[ResolutionError, ResolvedName] = + narrowResolution(resolveUppercaseName(name, includeTypes = false)) + + def resolveUppercaseName( + name: String, + includeTypes: Boolean + ): Either[ResolutionError, ResolvedTypeName] = { + val local = findLocalCandidates(name, includeTypes = includeTypes) if (local.nonEmpty) { return handleAmbiguity(local) } @@ -234,7 +269,9 @@ case class BindingsMap( if (qualifiedImps.nonEmpty) { return handleAmbiguity(qualifiedImps) } - handleAmbiguity(findExportedCandidatesInImports(name)) + handleAmbiguity( + findExportedCandidatesInImports(name, includeTypes = includeTypes) + ) } /** Resolves a qualified name to a symbol in the context of this module. @@ -271,9 +308,22 @@ case class BindingsMap( } private def findExportedSymbolsFor( - name: String - ): List[ResolvedName] = { - exportedSymbols.getOrElse(name.toLowerCase, List()) + name: String, + includeTypes: Boolean + ): List[ResolvedTypeName] = { + if (includeTypes) { + allExportedSymbols.getOrElse(name.toLowerCase, List()) + } else { + exportedSymbols.getOrElse(name.toLowerCase, List()) + } + } + + private def narrowResolution( + resolution: Either[ResolutionError, ResolvedTypeName] + ): Either[ResolutionError, ResolvedName] = resolution match { + case Right(value: ResolvedName) => Right(value) + case Right(_) => Left(ResolutionNotFound) + case Left(err) => Left(err) } /** Resolves a name exported by this module. @@ -284,7 +334,9 @@ case class BindingsMap( def resolveExportedName( name: String ): Either[ResolutionError, ResolvedName] = { - handleAmbiguity(findExportedSymbolsFor(name)) + narrowResolution( + handleAmbiguity(findExportedSymbolsFor(name, includeTypes = false)) + ) } /** Dumps the export statements from this module into a structure ready for @@ -370,7 +422,7 @@ object BindingsMap { * @param resolution the particular resolution of `symbol` * @return whether access to the symbol is permitted by this restriction. */ - def canAccess(symbol: String, resolution: ResolvedName): Boolean + def canAccess(symbol: String, resolution: ResolvedTypeName): Boolean /** Performs static optimizations on the restriction, simplifying * common patterns. @@ -414,7 +466,7 @@ object BindingsMap { * @param resolution `symbol`'s resolution * @return `true` if the symbol is visible, `false` otherwise */ - def allows(symbol: String, resolution: ResolvedName): Boolean = { + def allows(symbol: String, resolution: ResolvedTypeName): Boolean = { val symbolMatch = this.symbol == symbol.toLowerCase val resolutionMatch = this.resolution.isEmpty || this.resolution.get == resolution @@ -452,7 +504,7 @@ object BindingsMap { /** @inheritdoc */ override def canAccess( symbol: String, - resolution: ResolvedName + resolution: ResolvedTypeName ): Boolean = symbols.exists(_.allows(symbol, resolution)) /** @inheritdoc */ @@ -482,7 +534,7 @@ object BindingsMap { /** @inheritdoc */ override def canAccess( symbol: String, - resolution: ResolvedName + resolution: ResolvedTypeName ): Boolean = !symbols.contains(symbol.toLowerCase) /** @inheritdoc */ @@ -502,7 +554,7 @@ object BindingsMap { /** @inheritdoc */ override def canAccess( symbol: String, - resolution: ResolvedName + resolution: ResolvedTypeName ): Boolean = true /** @inheritdoc */ @@ -524,7 +576,7 @@ object BindingsMap { /** @inheritdoc */ override def canAccess( symbol: String, - resolution: ResolvedName + resolution: ResolvedTypeName ): Boolean = false /** @inheritdoc */ @@ -550,7 +602,7 @@ object BindingsMap { /** @inheritdoc */ override def canAccess( symbol: String, - resolution: ResolvedName + resolution: ResolvedTypeName ): Boolean = restrictions.forall(_.canAccess(symbol, resolution)) /** @inheritdoc */ @@ -612,7 +664,7 @@ object BindingsMap { /** @inheritdoc */ override def canAccess( symbol: String, - resolution: ResolvedName + resolution: ResolvedTypeName ): Boolean = restrictions.exists(_.canAccess(symbol, resolution)) /** @inheritdoc */ @@ -955,7 +1007,7 @@ object BindingsMap { * * @param candidates all the possible resolutions for the name. */ - case class ResolutionAmbiguous(candidates: List[ResolvedName]) + case class ResolutionAmbiguous(candidates: List[ResolvedTypeName]) extends ResolutionError /** A resolution error due to the symbol not being found. diff --git a/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala b/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala index e655cdc59cae..fc193e8816d2 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala @@ -7,7 +7,9 @@ import org.enso.compiler.data.BindingsMap.{ ResolvedConstructor, ResolvedMethod, ResolvedModule, + ResolvedName, ResolvedPolyglotSymbol, + ResolvedType, SymbolRestriction } import org.enso.compiler.pass.analyse.BindingAnalysis @@ -165,6 +167,11 @@ class ExportsResolution { private def resolveExportedSymbols(modules: List[Module]): Unit = { modules.foreach { module => val bindings = getBindings(module) + val ownTypes = bindings.types.map { tp => + val name = tp.name.toLowerCase + val sym = List(ResolvedType(ModuleReference.Concrete(module), tp)) + (name, sym) + } val ownMethods = bindings.moduleMethods.map { method => val name = method.name.toLowerCase val syms = @@ -188,7 +195,7 @@ class ExportsResolution { (name.toLowerCase, List(ResolvedModule(mod))) } val reExportedSymbols = bindings.resolvedExports.flatMap { export => - getBindings(export.module.unsafeAsModule()).exportedSymbols.toList + getBindings(export.module.unsafeAsModule()).allExportedSymbols.toList .flatMap { case (sym, resolutions) => val allowedResolutions = resolutions.filter(res => export.symbols.canAccess(sym, res)) @@ -196,7 +203,8 @@ class ExportsResolution { else Some((sym, allowedResolutions)) } } - bindings.exportedSymbols = List( + bindings.allExportedSymbols = List( + ownTypes, ownMethods, ownConstructors, ownPolyglotBindings, @@ -205,6 +213,14 @@ class ExportsResolution { ).flatten.groupBy(_._1).map { case (m, names) => (m, names.flatMap(_._2).distinct) } + + bindings.exportedSymbols = bindings.allExportedSymbols.flatMap { + case (k, v) => + v.collect { case v: ResolvedName => v } match { + case List() => None + case other => Some((k, other)) + } + } } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala b/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala index 4e8cfcbcef11..5f984ee6d16d 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala @@ -57,7 +57,8 @@ object StubIrBuilder { moduleMethods, ModuleReference.Concrete(module) ) - meta.exportedSymbols = exportedBindings.toMap + meta.exportedSymbols = exportedBindings.toMap + meta.allExportedSymbols = meta.exportedSymbols ir.updateMetadata(BindingAnalysis -->> meta) } } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala index 619d92c74f2f..ff6fe65439cc 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala @@ -187,6 +187,19 @@ class TypeSignaturesTest "my_pkg.My_Lib.Util.Util_1" ->: "my_pkg.My_Lib.Util.Util_2" ) } + + "resolve imported union type names" in { + val code = """ + |from my_pkg.My_Lib.Util import all + | + |foo : Util_Sum -> Util_2 + |foo a = 23 + |""".stripMargin + val module = code.preprocessModule + getSignature(module, "foo") should typeAs( + "my_pkg.My_Lib.Util.Util_Sum" ->: "my_pkg.My_Lib.Util.Util_2" + ) + } } } From 683cd046bb581bd3d30cbd452e61d22ae45c4676 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 26 May 2022 20:25:25 +0200 Subject: [PATCH 007/110] use sigs in suggestion builder --- .../compiler/context/SuggestionBuilder.scala | 112 +++++------------- .../compiler/pass/resolve/TypeNames.scala | 31 +++-- 2 files changed, 51 insertions(+), 92 deletions(-) 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 b41c73996070..f3248e2ab0e1 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 @@ -2,10 +2,10 @@ package org.enso.compiler.context import org.enso.compiler.core.IR import org.enso.compiler.data.BindingsMap -import org.enso.compiler.pass.analyse.BindingAnalysis import org.enso.compiler.pass.resolve.{ DocumentationComments, MethodDefinitions, + TypeNames, TypeSignatures } import org.enso.pkg.QualifiedName @@ -34,7 +34,6 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { def build(module: QualifiedName, ir: IR): Tree.Root[Suggestion] = { type TreeBuilder = mutable.Builder[Tree.Node[Suggestion], Vector[Tree.Node[Suggestion]]] - val bindings = ir.getMetadata(BindingAnalysis) def go(tree: TreeBuilder, scope: Scope): Vector[Tree.Node[Suggestion]] = { if (scope.queue.isEmpty) { @@ -45,7 +44,7 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { ir match { case IR.Module.Scope.Definition.Atom(name, arguments, _, _, _) => val suggestions = - buildAtom(bindings, module, name.name, arguments, doc) + buildAtom(module, name.name, arguments, doc) go(tree ++= suggestions.map(Tree.Node(_, Vector())), scope) case IR.Module.Scope.Definition.Method @@ -59,7 +58,7 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { val typeSignature = ir.getMetadata(TypeSignatures) val selfTypeOpt = typePtr .getMetadata(MethodDefinitions) - .flatMap(buildSelfType) + .map(_.target.qualifiedName) val methodOpt = selfTypeOpt.map { selfType => buildMethod( body.getExternalId, @@ -68,8 +67,7 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { selfType, args, doc, - typeSignature, - bindings + typeSignature ) } val subforest = go( @@ -94,8 +92,7 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { args, sourceTypeName, doc, - typeSignature, - bindings + typeSignature ) go(tree += Tree.Node(conversion, Vector()), scope) @@ -113,8 +110,7 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { name, args, scope.location.get, - typeSignature, - bindings + typeSignature ) val subforest = go( Vector.newBuilder, @@ -130,8 +126,7 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { module, name.name, scope.location.get, - typeSignature, - bindings + typeSignature ) val subforest = go( Vector.newBuilder, @@ -167,10 +162,9 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { selfType: QualifiedName, args: Seq[IR.DefinitionArgument], doc: Option[String], - typeSignature: Option[TypeSignatures.Metadata], - bindings: Option[BindingAnalysis.Metadata] + typeSignature: Option[TypeSignatures.Metadata] ): Suggestion.Method = { - val typeSig = buildTypeSignatureFromMetadata(typeSignature, bindings) + val typeSig = buildTypeSignatureFromMetadata(typeSignature) val (methodArgs, returnTypeDef) = buildMethodArguments(args, typeSig, selfType) Suggestion.Method( @@ -191,10 +185,9 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { args: Seq[IR.DefinitionArgument], sourceTypeName: String, doc: Option[String], - typeSignature: Option[TypeSignatures.Metadata], - bindings: Option[BindingAnalysis.Metadata] + typeSignature: Option[TypeSignatures.Metadata] ): Suggestion.Conversion = { - val typeSig = buildTypeSignatureFromMetadata(typeSignature, bindings) + val typeSig = buildTypeSignatureFromMetadata(typeSignature) val (methodArgs, returnTypeDef) = buildFunctionArguments(args, typeSig) Suggestion.Conversion( @@ -214,10 +207,9 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { name: IR.Name, args: Seq[IR.DefinitionArgument], location: Location, - typeSignature: Option[TypeSignatures.Metadata], - bindings: Option[BindingAnalysis.Metadata] + typeSignature: Option[TypeSignatures.Metadata] ): Suggestion.Function = { - val typeSig = buildTypeSignatureFromMetadata(typeSignature, bindings) + val typeSig = buildTypeSignatureFromMetadata(typeSignature) val (methodArgs, returnTypeDef) = buildFunctionArguments(args, typeSig) Suggestion.Function( @@ -236,10 +228,9 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { module: QualifiedName, name: String, location: Location, - typeSignature: Option[TypeSignatures.Metadata], - bindings: Option[BindingAnalysis.Metadata] + typeSignature: Option[TypeSignatures.Metadata] ): Suggestion.Local = { - val typeSig = buildTypeSignatureFromMetadata(typeSignature, bindings) + val typeSig = buildTypeSignatureFromMetadata(typeSignature) val (_, returnTypeDef) = buildFunctionArguments(Seq(), typeSig) Suggestion.Local( externalId, @@ -262,14 +253,13 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { /** Build suggestions for an atom definition. */ private def buildAtom( - bindings: Option[BindingAnalysis.Metadata], module: QualifiedName, name: String, arguments: Seq[IR.DefinitionArgument], doc: Option[String] ): Seq[Suggestion] = buildAtomConstructor(module, name, arguments, doc) +: - buildAtomGetters(bindings, module, name, arguments) + buildAtomGetters(module, name, arguments) /** Build an atom constructor. */ private def buildAtomConstructor( @@ -289,7 +279,6 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { /** Build getter methods from atom arguments. */ private def buildAtomGetters( - bindings: Option[BindingAnalysis.Metadata], module: QualifiedName, name: String, arguments: Seq[IR.DefinitionArgument] @@ -309,46 +298,17 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { selfType = module.createChild(name), args = Seq(thisArg), doc = None, - typeSignature = None, - bindings = bindings + typeSignature = None ) } - /** Build self type from the method definitions metadata. - * - * @param metadata the result of successful name resolution - * @return the qualified type name - */ - private def buildSelfType( - metadata: MethodDefinitions.Metadata - ): Option[QualifiedName] = - buildResolvedTypeName(metadata.target) - - /** Build type name from the resolved name. - * - * @param resolvedName the result of successful name resolution - * @return the qualified type name - */ - private def buildResolvedTypeName( - resolvedName: BindingsMap.ResolvedName - ): Option[QualifiedName] = { - resolvedName match { - case BindingsMap.ResolvedModule(module) => - Some(module.getName) - case cons: BindingsMap.ResolvedConstructor => - Some(cons.qualifiedName) - case _ => - None - } - } - private def buildResolvedUnionTypeName( resolvedName: BindingsMap.ResolvedTypeName - ): Option[TypeArg] = resolvedName match { + ): TypeArg = resolvedName match { case tp: BindingsMap.ResolvedType => - Some(TypeArg.Sum(tp.qualifiedName, tp.getVariants.map(_.qualifiedName))) - case other: BindingsMap.ResolvedName => - buildResolvedTypeName(other).map(TypeArg.Value) + TypeArg.Sum(tp.qualifiedName, tp.getVariants.map(_.qualifiedName)) + case _: BindingsMap.ResolvedName => + TypeArg.Value(resolvedName.qualifiedName) } /** Build type signature from the ir metadata. @@ -358,12 +318,11 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { * @return the list of type arguments */ private def buildTypeSignatureFromMetadata( - typeSignature: Option[TypeSignatures.Metadata], - bindings: Option[BindingAnalysis.Metadata] + typeSignature: Option[TypeSignatures.Metadata] ): Vector[TypeArg] = typeSignature match { case Some(TypeSignatures.Signature(typeExpr)) => - buildTypeSignature(bindings, typeExpr) + buildTypeSignature(typeExpr) case _ => Vector() } @@ -375,7 +334,6 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { * @return the list of type arguments */ private def buildTypeSignature( - bindings: Option[BindingAnalysis.Metadata], typeExpr: IR.Expression ): Vector[TypeArg] = { def go(expr: IR.Expression): TypeArg = expr match { @@ -393,10 +351,11 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { bin.operator.name ) case tname: IR.Name => - val typeName = tname.name - val tdef = resolveTypeName(bindings, typeName) - .getOrElse(TypeArg.Value(QualifiedName.simpleName(typeName))) - tdef + tname + .getMetadata(TypeNames) + .map(t => buildResolvedUnionTypeName(t.target)) + .getOrElse(TypeArg.Value(QualifiedName.simpleName(tname.name))) + case _ => TypeArg.Value(QualifiedName.fromString(Any)) } @@ -407,21 +366,6 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { } } - /** Resolve unqualified type name. - * - * @param bindings the binding analysis metadata - * @param name the unqualified type name - * @return the resolved qualified type name - */ - private def resolveTypeName( - bindings: Option[BindingAnalysis.Metadata], - name: String - ): Option[TypeArg] = { - bindings - .flatMap(_.resolveTypeName(name).toOption) - .flatMap(buildResolvedUnionTypeName) - } - /** Build arguments of a method. * * @param vargs the list of value arguments diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala index e43ed4c9534c..028ee275d3a6 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala @@ -51,16 +51,31 @@ case object TypeNames extends IRPass { val bindingsMap = ir.unsafeGetMetadata(BindingAnalysis, "bindings analysis did not run") ir.copy(bindings = ir.bindings.map { d => - d.getMetadata(TypeSignatures) - .map(s => - d.updateMetadata( - TypeSignatures -->> TypeSignatures.Signature( - resolveSignature(bindingsMap, s.signature) - ) + val mapped = d.mapExpressions(resolveExpression(bindingsMap, _)) + doResolveType(bindingsMap, mapped) + }) + } + + private def resolveExpression( + bindingsMap: BindingsMap, + ir: IR.Expression + ): IR.Expression = { + def go(ir: IR.Expression): IR.Expression = { + doResolveType(bindingsMap, ir.mapExpressions(go)) + } + go(ir) + } + + private def doResolveType[T <: IR](bindingsMap: BindingsMap, ir: T): T = { + ir.getMetadata(TypeSignatures) + .map { s => + ir.updateMetadata( + TypeSignatures -->> TypeSignatures.Signature( + resolveSignature(bindingsMap, s.signature) ) ) - .getOrElse(d) - }) + } + .getOrElse(ir) } private def resolveSignature( From 2997cdcc0281c443de5a786263ff30fec6bcb114 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 27 May 2022 15:51:40 +0200 Subject: [PATCH 008/110] fix union types --- .../compiler/context/SuggestionBuilder.scala | 3 + .../scala/org/enso/compiler/core/IR.scala | 38 +++++------- .../pass/analyse/DataflowAnalysis.scala | 16 ++--- .../pass/desugar/OperatorToFunction.scala | 18 +++--- .../compiler/pass/resolve/TypeFunctions.scala | 58 +++++++++++-------- 5 files changed, 66 insertions(+), 67 deletions(-) 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 f3248e2ab0e1..a6f373508020 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 @@ -339,6 +339,9 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { def go(expr: IR.Expression): TypeArg = expr match { case fn: IR.Type.Function => TypeArg.Function(fn.args.map(go).toVector, go(fn.result)) +// case _: IR.Type.Set.Union => +// println("foun a union!!!!") +// ??? case app: IR.Application.Prefix => TypeArg.Application( go(app.function), 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 820d501cafbb..e04fabcf2653 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 @@ -3827,15 +3827,13 @@ object IR { /** The typeset union operator `|`. * - * @param left the left operand - * @param right the right operand + * @param operands the operands * @param location the source location that the node corresponds to * @param passData the pass metadata associated with this node * @param diagnostics compiler diagnostics for this node */ sealed case class Union( - left: Expression, - right: Expression, + operands: List[Expression], override val location: Option[IdentifiedLocation], override val passData: MetadataStorage = MetadataStorage(), override val diagnostics: DiagnosticStorage = DiagnosticStorage() @@ -3854,14 +3852,13 @@ object IR { * @return a copy of `this`, updated with the specified values */ def copy( - left: Expression = left, - right: Expression = right, + operands: List[Expression] = operands, location: Option[IdentifiedLocation] = location, passData: MetadataStorage = passData, diagnostics: DiagnosticStorage = diagnostics, id: Identifier = id ): Union = { - val res = Union(left, right, location, passData, diagnostics) + val res = Union(operands, location, passData, diagnostics) res.id = id res } @@ -3874,17 +3871,13 @@ object IR { keepIdentifiers: Boolean = false ): Union = copy( - left = left.duplicate( - keepLocations, - keepMetadata, - keepDiagnostics, - keepIdentifiers - ), - right = right.duplicate( - keepLocations, - keepMetadata, - keepDiagnostics, - keepIdentifiers + operands = operands.map( + _.duplicate( + keepLocations, + keepMetadata, + keepDiagnostics, + keepIdentifiers + ) ), location = if (keepLocations) location else None, passData = @@ -3900,15 +3893,14 @@ object IR { /** @inheritdoc */ override def mapExpressions(fn: Expression => Expression): Union = { - copy(left = fn(left), right = fn(right)) + copy(operands = operands.map(fn)) } /** @inheritdoc */ override def toString: String = s""" |IR.Type.Set.Union( - |left = $left, - |right = $right, + |operands = $operands, |location = $location, |passData = ${this.showPassData}, |diagnostics = $diagnostics, @@ -3916,11 +3908,11 @@ object IR { |""".toSingleLine /** @inheritdoc */ - override def children: List[IR] = List(left, right) + override def children: List[IR] = operands.toList /** @inheritdoc */ override def showCode(indent: Int): String = - s"(${left.showCode(indent)} | ${right.showCode(indent)})" + operands.map(_.showCode(indent)).toList.mkString(" | ") } object Union extends Info { override val name: String = "|" diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala index 0a3841966dcc..eb69b5cafa86 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala @@ -464,19 +464,13 @@ case object DataflowAnalysis extends IRPass { right = analyseExpression(right, info) ) .updateMetadata(this -->> info) - case union @ IR.Type.Set.Union(left, right, _, _, _) => + case union @ IR.Type.Set.Union(operands, _, _, _) => val unionDep = asStatic(union) - val leftDep = asStatic(left) - val rightDep = asStatic(right) - info.dependents.updateAt(leftDep, Set(unionDep)) - info.dependents.updateAt(rightDep, Set(unionDep)) - info.dependencies.updateAt(unionDep, Set(leftDep, rightDep)) - + val opDeps = operands.map(asStatic) + opDeps.foreach(info.dependents.updateAt(_, Set(unionDep))) + info.dependencies.updateAt(unionDep, opDeps.toSet) union - .copy( - left = analyseExpression(left, info), - right = analyseExpression(right, info) - ) + .copy(operands = operands.map(analyseExpression(_, info))) .updateMetadata(this -->> info) case subsumption @ IR.Type.Set.Subsumption(left, right, _, _, _) => val subDep = asStatic(subsumption) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/OperatorToFunction.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/OperatorToFunction.scala index bd07c78e8312..0a478972a6fd 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/OperatorToFunction.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/OperatorToFunction.scala @@ -45,18 +45,16 @@ case object OperatorToFunction extends IRPass { ir: IR.Module, moduleContext: ModuleContext ): IR.Module = { - val new_bindings = ir.bindings.map { - case asc: IR.Type.Ascription => asc - case a => - a.mapExpressions( - runExpression( - _, - new InlineContext( - moduleContext.module, - compilerConfig = moduleContext.compilerConfig - ) + val new_bindings = ir.bindings.map { a => + a.mapExpressions( + runExpression( + _, + new InlineContext( + moduleContext.module, + compilerConfig = moduleContext.compilerConfig ) ) + ) } ir.copy(bindings = new_bindings) } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeFunctions.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeFunctions.scala index 72b37f41d55c..d82b5fa93029 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeFunctions.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeFunctions.scala @@ -2,7 +2,7 @@ package org.enso.compiler.pass.resolve import org.enso.compiler.context.{InlineContext, ModuleContext} import org.enso.compiler.core.IR -import org.enso.compiler.core.IR.Application +import org.enso.compiler.core.IR.{Application, IdentifiedLocation} import org.enso.compiler.core.ir.MetadataStorage._ import org.enso.compiler.exception.CompilerError import org.enso.compiler.pass.IRPass @@ -55,10 +55,7 @@ case object TypeFunctions extends IRPass { ir: IR.Module, @unused moduleContext: ModuleContext ): IR.Module = { - val new_bindings = ir.bindings.map { - case asc: IR.Type.Ascription => asc - case a => a.mapExpressions(resolveExpression) - } + val new_bindings = ir.bindings.map(_.mapExpressions(resolveExpression)) ir.copy(bindings = new_bindings) } @@ -125,8 +122,11 @@ case object TypeFunctions extends IRPass { app match { case pre @ Application.Prefix(fn, arguments, _, _, _, _) => fn match { + case name: IR.Name if name.name == IR.Type.Set.Union.name => + val members = flattenUnion(app).map(resolveExpression) + IR.Type.Set.Union(members, app.location) case name: IR.Name if knownTypingFunctions.contains(name.name) => - resolveKnownFunction(pre) + resolveKnownFunction(name, pre.arguments, pre.location, pre) case _ => pre.copy( function = resolveExpression(fn), @@ -150,42 +150,54 @@ case object TypeFunctions extends IRPass { } } + def flattenUnion(expr: IR.Expression): List[IR.Expression] = { + expr match { + case Application.Prefix(n: IR.Name, args, _, _, _, _) + if n.name == IR.Type.Set.Union.name => + args.flatMap(arg => flattenUnion(arg.value)) + case _ => List(expr) + } + } + /** Resolves a known typing function to its IR node. * * @param prefix the application to resolve * @return the IR node representing `prefix` */ - def resolveKnownFunction(prefix: IR.Application.Prefix): IR.Expression = { + def resolveKnownFunction( + name: IR.Name, + arguments: List[IR.CallArgument], + location: Option[IdentifiedLocation], + originalIR: IR + ): IR.Expression = { val expectedNumArgs = 2 - val lengthIsValid = prefix.arguments.length == expectedNumArgs - val argsAreValid = prefix.arguments.forall(isValidCallArg) + val lengthIsValid = arguments.length == expectedNumArgs + val argsAreValid = arguments.forall(isValidCallArg) if (lengthIsValid && argsAreValid) { - val leftArg = resolveExpression(prefix.arguments.head.value) - val rightArg = resolveExpression(prefix.arguments.last.value) + val leftArg = resolveExpression(arguments.head.value) + val rightArg = resolveExpression(arguments.last.value) - prefix.function.asInstanceOf[IR.Name].name match { + name.name match { case IR.Type.Ascription.name => - IR.Type.Ascription(leftArg, rightArg, prefix.location) + IR.Type.Ascription(leftArg, rightArg, location) case IR.Type.Context.name => - IR.Type.Context(leftArg, rightArg, prefix.location) + IR.Type.Context(leftArg, rightArg, location) case IR.Type.Error.name => - IR.Type.Error(leftArg, rightArg, prefix.location) + IR.Type.Error(leftArg, rightArg, location) case IR.Type.Set.Concat.name => - IR.Type.Set.Concat(leftArg, rightArg, prefix.location) + IR.Type.Set.Concat(leftArg, rightArg, location) case IR.Type.Set.Subsumption.name => - IR.Type.Set.Subsumption(leftArg, rightArg, prefix.location) + IR.Type.Set.Subsumption(leftArg, rightArg, location) case IR.Type.Set.Equality.name => - IR.Type.Set.Equality(leftArg, rightArg, prefix.location) - case IR.Type.Set.Union.name => - IR.Type.Set.Union(leftArg, rightArg, prefix.location) + IR.Type.Set.Equality(leftArg, rightArg, location) case IR.Type.Set.Intersection.name => - IR.Type.Set.Intersection(leftArg, rightArg, prefix.location) + IR.Type.Set.Intersection(leftArg, rightArg, location) case IR.Type.Set.Subtraction.name => - IR.Type.Set.Subtraction(leftArg, rightArg, prefix.location) + IR.Type.Set.Subtraction(leftArg, rightArg, location) } } else { - IR.Error.InvalidIR(prefix) + IR.Error.InvalidIR(originalIR) } } From a0cdbe3a4a982c41b59a82ea24819ff22e8619e3 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 27 May 2022 18:41:19 +0200 Subject: [PATCH 009/110] fix the suggestion builder to use sum types --- .../compiler/context/SuggestionBuilder.scala | 26 ++- .../test/context/SuggestionBuilderTest.scala | 159 +++++++++++------- 2 files changed, 117 insertions(+), 68 deletions(-) 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 a6f373508020..86c0d0b73d17 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 @@ -306,7 +306,10 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { resolvedName: BindingsMap.ResolvedTypeName ): TypeArg = resolvedName match { case tp: BindingsMap.ResolvedType => - TypeArg.Sum(tp.qualifiedName, tp.getVariants.map(_.qualifiedName)) + TypeArg.Sum( + Some(tp.qualifiedName), + tp.getVariants.map(r => TypeArg.Value(r.qualifiedName)) + ) case _: BindingsMap.ResolvedName => TypeArg.Value(resolvedName.qualifiedName) } @@ -339,9 +342,8 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { def go(expr: IR.Expression): TypeArg = expr match { case fn: IR.Type.Function => TypeArg.Function(fn.args.map(go).toVector, go(fn.result)) -// case _: IR.Type.Set.Union => -// println("foun a union!!!!") -// ??? + case union: IR.Type.Set.Union => + TypeArg.Sum(None, union.operands.map(go)) case app: IR.Application.Prefix => TypeArg.Application( go(app.function), @@ -471,11 +473,17 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { hasDefault = varg.defaultValue.isDefined, defaultValue = varg.defaultValue.flatMap(buildDefaultValue), tagValues = targ match { - case TypeArg.Sum(_, variants) => Some(variants.map(_.toString)) - case _ => None + case s: TypeArg.Sum => Some(pluckVariants(s)) + case _ => None } ) + private def pluckVariants(arg: TypeArg): Seq[String] = arg match { + case TypeArg.Sum(_, variants) => variants.flatMap(pluckVariants) + case TypeArg.Value(n) => Seq(n.toString) + case _ => Seq() + } + /** Build the name of type argument. * * @param targ the type argument @@ -499,7 +507,9 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { val argsList = args.map(go(_, level + 1)).mkString(" ") val typeName = s"$funText $argsList" if (level > 0) s"($typeName)" else typeName - case TypeArg.Sum(n, _) => n.toString + case TypeArg.Sum(Some(n), _) => n.toString + case TypeArg.Sum(None, variants) => + variants.map(go(_, level + 1)).mkString(" | ") } go(targ, 0) @@ -594,7 +604,7 @@ object SuggestionBuilder { * @param name the qualified name of the type. * @param variants the qualified names of constituent atoms. */ - case class Sum(name: QualifiedName, variants: Seq[QualifiedName]) + case class Sum(name: Option[QualifiedName], variants: Seq[TypeArg]) extends TypeArg /** Type with the name, like `A`. diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/context/SuggestionBuilderTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/context/SuggestionBuilderTest.scala index b796615119ac..82f546d09aa4 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/context/SuggestionBuilderTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/context/SuggestionBuilderTest.scala @@ -27,7 +27,6 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module.getIr } } -// implicit val passManager: PassManager = new Passes(defaultConfig).passManager private val Module = QualifiedName(List("Unnamed"), "Test") private val ModuleNode = Tree.Node( @@ -62,7 +61,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -92,7 +91,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -123,7 +122,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = "Number", @@ -152,7 +151,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = "Foo.Bar", @@ -181,7 +180,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None), + Suggestion.Argument("this", "Unnamed.Test", false, false, None), Suggestion.Argument("a", "Text", false, false, None) ), selfType = "Unnamed.Test", @@ -211,7 +210,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None), + Suggestion.Argument("this", "Unnamed.Test", false, false, None), Suggestion.Argument( "a", "Either (Vector Number) Text", @@ -248,7 +247,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = "Foo.Bar Baz", @@ -279,7 +278,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None), + Suggestion.Argument("this", "Unnamed.Test", false, false, None), Suggestion .Argument("a", SuggestionBuilder.Any, false, false, None), Suggestion @@ -332,7 +331,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None), + Suggestion.Argument("this", "Unnamed.Test", false, false, None), Suggestion .Argument("a", SuggestionBuilder.Any, false, true, Some("0")) ), @@ -376,7 +375,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "bar", arguments = Seq( Suggestion - .Argument("self", "Unnamed.Test.MyType", false, false, None), + .Argument("this", "Unnamed.Test.MyType", false, false, None), Suggestion .Argument("a", SuggestionBuilder.Any, false, false, None), Suggestion @@ -433,7 +432,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "bar", arguments = Seq( Suggestion - .Argument("self", "Unnamed.Test.MyAtom", false, false, None), + .Argument("this", "Unnamed.Test.MyAtom", false, false, None), Suggestion.Argument("a", "Number", false, false, None), Suggestion.Argument("b", "Number", false, false, None) ), @@ -453,7 +452,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { """type MyAtom | |MyAtom.apply : (Number -> Number) -> Number - |MyAtom.apply f = f self + |MyAtom.apply f = f this |""".stripMargin val module = code.preprocessModule @@ -478,7 +477,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "apply", arguments = Seq( Suggestion - .Argument("self", "Unnamed.Test.MyAtom", false, false, None), + .Argument("this", "Unnamed.Test.MyAtom", false, false, None), Suggestion.Argument("f", "Number -> Number", false, false, None) ), selfType = "Unnamed.Test.MyAtom", @@ -494,10 +493,14 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { "build method with union type signature" in { val code = - """type MyAtom + """type My_Atom + | type Variant_1 + | type Variant_2 + | + |type Other_Atom | - |MyAtom.apply : (Number | Text | MyAtom) -> Number - |MyAtom.apply f = f self + |Other_Atom.apply : (Number | Other_Atom | My_Atom) -> Number + |Other_Atom.apply f = f this |""".stripMargin val module = code.preprocessModule @@ -508,9 +511,31 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { Suggestion.Atom( externalId = None, module = "Unnamed.Test", - name = "MyAtom", + name = "Variant_1", arguments = Seq(), - returnType = "Unnamed.Test.MyAtom", + returnType = "Unnamed.Test.Variant_1", + documentation = None + ), + Vector() + ), + Tree.Node( + Suggestion.Atom( + externalId = None, + module = "Unnamed.Test", + name = "Variant_2", + arguments = Seq(), + returnType = "Unnamed.Test.Variant_2", + documentation = None + ), + Vector() + ), + Tree.Node( + Suggestion.Atom( + externalId = None, + module = "Unnamed.Test", + name = "Other_Atom", + arguments = Seq(), + returnType = "Unnamed.Test.Other_Atom", documentation = None ), Vector() @@ -522,16 +547,30 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "apply", arguments = Seq( Suggestion - .Argument("self", "Unnamed.Test.MyAtom", false, false, None), + .Argument( + "this", + "Unnamed.Test.Other_Atom", + false, + false, + None + ), Suggestion.Argument( "f", - "Number | Text | Unnamed.Test.MyAtom", + "Number | Unnamed.Test.Other_Atom | Unnamed.Test.My_Atom", false, false, - None + None, + Some( + Seq( + "Number", + "Unnamed.Test.Other_Atom", + "Unnamed.Test.Variant_1", + "Unnamed.Test.Variant_2" + ) + ) ) ), - selfType = "Unnamed.Test.MyAtom", + selfType = "Unnamed.Test.Other_Atom", returnType = "Number", documentation = None ), @@ -556,7 +595,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None), + Suggestion.Argument("this", "Unnamed.Test", false, false, None), Suggestion .Argument("a", SuggestionBuilder.Any, true, false, None) ), @@ -599,7 +638,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None), + Suggestion.Argument("this", "Unnamed.Test", false, false, None), Suggestion.Argument("a", "Unnamed.Test.A", false, false, None) ), selfType = "Unnamed.Test", @@ -648,7 +687,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.MyType", false, false, None) + .Argument("this", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -714,7 +753,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.MyMaybe", false, false, None) + .Argument("this", "Unnamed.Test.MyMaybe", false, false, None) ), selfType = "Unnamed.Test.MyMaybe", returnType = SuggestionBuilder.Any, @@ -754,7 +793,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "x", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.Newtype", false, false, None) + .Argument("this", "Unnamed.Test.Newtype", false, false, None) ), selfType = "Unnamed.Test.NewType", returnType = SuggestionBuilder.Any, @@ -797,7 +836,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -846,7 +885,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -908,7 +947,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -968,7 +1007,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1015,7 +1054,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1060,7 +1099,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1118,7 +1157,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1175,7 +1214,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1232,7 +1271,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.MyType", false, false, None) + .Argument("this", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -1247,7 +1286,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "b", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.MyType", false, false, None) + .Argument("this", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -1294,7 +1333,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.MyType", false, false, None) + .Argument("this", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -1309,7 +1348,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "b", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.MyType", false, false, None) + .Argument("this", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -1364,7 +1403,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.Just", false, false, None) + .Argument("this", "Unnamed.Test.Just", false, false, None) ), selfType = "Unnamed.Test.Just", returnType = SuggestionBuilder.Any, @@ -1424,7 +1463,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.Just", false, false, None) + .Argument("this", "Unnamed.Test.Just", false, false, None) ), selfType = "Unnamed.Test.Just", returnType = SuggestionBuilder.Any, @@ -1482,7 +1521,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "empty", arguments = Seq( Suggestion - .Argument("self", "Unnamed.Test.Cons", false, false, None) + .Argument("this", "Unnamed.Test.Cons", false, false, None) ), selfType = "Unnamed.Test.Cons", returnType = "Unnamed.Test.List", @@ -1497,7 +1536,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "empty", arguments = Seq( Suggestion - .Argument("self", "Unnamed.Test.Nil", false, false, None) + .Argument("this", "Unnamed.Test.Nil", false, false, None) ), selfType = "Unnamed.Test.Nil", returnType = "Unnamed.Test.List", @@ -1515,7 +1554,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { | type Nothing | type Just a | - | map f = case self of + | map f = case this of | Just a -> Just (f a) | Nothing -> Nothing""".stripMargin val module = code.preprocessModule @@ -1555,7 +1594,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.Just", false, false, None) + .Argument("this", "Unnamed.Test.Just", false, false, None) ), selfType = "Unnamed.Test.Just", returnType = SuggestionBuilder.Any, @@ -1570,7 +1609,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "map", arguments = Seq( Suggestion - .Argument("self", "Unnamed.Test.Nothing", false, false, None), + .Argument("this", "Unnamed.Test.Nothing", false, false, None), Suggestion .Argument("f", SuggestionBuilder.Any, false, false, None) ), @@ -1587,7 +1626,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "map", arguments = Seq( Suggestion - .Argument("self", "Unnamed.Test.Just", false, false, None), + .Argument("this", "Unnamed.Test.Just", false, false, None), Suggestion .Argument("f", SuggestionBuilder.Any, false, false, None) ), @@ -1634,7 +1673,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.MyType", false, false, None) + .Argument("this", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -1649,7 +1688,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "b", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.MyType", false, false, None) + .Argument("this", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -1663,7 +1702,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1706,7 +1745,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.Test", false, false, None) + .Argument("this", "Unnamed.Test.Test", false, false, None) ), selfType = "Unnamed.Test.Test", returnType = SuggestionBuilder.Any, @@ -1720,7 +1759,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1769,7 +1808,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "quux", arguments = Vector( Suggestion - .Argument("self", "Unnamed.Test.A", false, false, None), + .Argument("this", "Unnamed.Test.A", false, false, None), Suggestion.Argument( "x", "Unnamed.Test.A", @@ -1791,7 +1830,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "quux", arguments = Vector( - Suggestion.Argument("self", "Unnamed.Test", false, false, None), + Suggestion.Argument("this", "Unnamed.Test", false, false, None), Suggestion.Argument( "x", "Unnamed.Test.A", @@ -1813,7 +1852,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = List( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1846,7 +1885,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1880,7 +1919,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1934,7 +1973,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1986,7 +2025,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("self", "Unnamed.Test", false, false, None) + Suggestion.Argument("this", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, From dde6c8c684df706f3a883cc0a7877126ae632443 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 27 May 2022 18:57:20 +0200 Subject: [PATCH 010/110] write proper level tests for unions --- .../test/semantic/TypeSignaturesTest.scala | 55 +++++++++++++++---- 1 file changed, 43 insertions(+), 12 deletions(-) diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala index ff6fe65439cc..d3c70fc9d5e2 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala @@ -17,10 +17,19 @@ trait TypeMatchers { case Fn(args, r) => Fn(that :: args, r) case _ => Fn(List(that), this) } + + def |(that: Sig): Sig = { + def toUnion(sig: Sig): List[Sig] = sig match { + case Union(items) => items + case other => List(other) + } + Union(toUnion(this) ++ toUnion(that)) + } } case class Name(name: String) extends Sig case class AnyQualName(name: QualifiedName) extends Sig case class Fn(args: List[Sig], result: Sig) extends Sig + case class Union(items: List[Sig]) extends Sig implicit def fromString(str: String): Sig = { if (str.contains(".")) { @@ -71,6 +80,11 @@ trait TypeMatchers { .flatMap(findInequalityWitness) .headOption .orElse(findInequalityWitness(res, t.result)) + case (Union(items), t: IR.Type.Set.Union) => + if (items.length != t.operands.length) { + return Some((sig, expr, "number of items does not match")) + } + items.lazyZip(t.operands).flatMap(findInequalityWitness).headOption case _ => Some((sig, expr, "constructors are incompatible")) } @@ -176,12 +190,13 @@ class TypeSignaturesTest } "resolve imported names" in { - val code = """ - |from my_pkg.My_Lib.Util import all - | - |foo : Util_1 -> Util_2 - |foo a = 23 - |""".stripMargin + val code = + """ + |from my_pkg.My_Lib.Util import all + | + |foo : Util_1 -> Util_2 + |foo a = 23 + |""".stripMargin val module = code.preprocessModule getSignature(module, "foo") should typeAs( "my_pkg.My_Lib.Util.Util_1" ->: "my_pkg.My_Lib.Util.Util_2" @@ -189,17 +204,33 @@ class TypeSignaturesTest } "resolve imported union type names" in { - val code = """ - |from my_pkg.My_Lib.Util import all - | - |foo : Util_Sum -> Util_2 - |foo a = 23 - |""".stripMargin + val code = + """ + |from my_pkg.My_Lib.Util import all + | + |foo : Util_Sum -> Util_2 + |foo a = 23 + |""".stripMargin val module = code.preprocessModule getSignature(module, "foo") should typeAs( "my_pkg.My_Lib.Util.Util_Sum" ->: "my_pkg.My_Lib.Util.Util_2" ) } + + "resolve anonymous sum types" in { + val code = + """from my_pkg.My_Lib.Util import all + | + |type Foo + | + |baz : Foo | Util_2 | Util_Sum -> Foo + |baz a = 123 + |""".stripMargin + val module = code.preprocessModule + getSignature(module, "baz") should typeAs( + ("Unnamed.Test.Foo" | "my_pkg.My_Lib.Util.Util_2" | "my_pkg.My_Lib.Util.Util_Sum") ->: "Unnamed.Test.Foo" + ) + } } } From 6a83655491c0d75b61095b42f970a595b74c9100 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Sat, 4 Jun 2022 21:45:36 +0200 Subject: [PATCH 011/110] fix all tests --- .../org/enso/compiler/data/BindingsMap.scala | 10 +++++- .../pass/resolve/SuspendedArguments.scala | 12 +------ .../compiler/test/codegen/AstToIrTest.scala | 25 +++----------- .../test/semantic/TypeSignaturesTest.scala | 33 ++++++++++++++++++- 4 files changed, 46 insertions(+), 34 deletions(-) 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 889905149aab..949d5fb39328 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 @@ -312,7 +312,15 @@ case class BindingsMap( includeTypes: Boolean ): List[ResolvedTypeName] = { if (includeTypes) { - allExportedSymbols.getOrElse(name.toLowerCase, List()) + val allSymbols = allExportedSymbols.getOrElse(name.toLowerCase, List()) + val onlyTypes = allSymbols.collect { case t: ResolvedType => + t + } + if (onlyTypes.nonEmpty) { + onlyTypes + } else { + allSymbols + } } else { exportedSymbols.getOrElse(name.toLowerCase, List()) } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala index 09a1a0b0639d..07f9012de5c6 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala @@ -239,17 +239,7 @@ case object SuspendedArguments extends IRPass { */ def toSegments(signature: IR.Expression): List[IR.Expression] = { signature match { - case IR.Application.Operator.Binary( - l, - IR.Name.Literal("->", _, _, _, _, _), - r, - _, - _, - _ - ) => - l.value :: toSegments(r.value) - case IR.Function.Lambda(args, body, _, _, _, _) => - args.map(_.name) ::: toSegments(body) + case IR.Type.Function(args, ret, _, _, _) => args :+ ret case _ => List(signature) } } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala index 89628dd97944..60001193f873 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala @@ -899,9 +899,8 @@ class AstToIrTest extends CompilerTest with Inside { .asInstanceOf[IR.Application.Operator.Binary] ir.right.value - .asInstanceOf[IR.Application.Operator.Binary] - .left - .value shouldBe an[IR.Name.Qualified] + .asInstanceOf[IR.Type.Function] + .args(0) shouldBe an[IR.Name.Qualified] } "work inside type bodies" in { @@ -952,21 +951,6 @@ class AstToIrTest extends CompilerTest with Inside { .expression shouldBe an[IR.Application.Operator.Binary] } - "properly support nested ascriptions" in { - val ir = - """ - |x : (a : Type) -> (b : Type -> Type) -> (c : Type) - |""".stripMargin.toIrExpression.get - .asInstanceOf[IR.Application.Operator.Binary] - - ir.right.value shouldBe an[IR.Function.Lambda] - ir.right.value - .asInstanceOf[IR.Function.Lambda] - .arguments - .head - .ascribedType shouldBe defined - } - // TODO [AA] Syntax error with `f a ->` "properly support dotted operators in ascriptions" in { @@ -976,9 +960,8 @@ class AstToIrTest extends CompilerTest with Inside { .asInstanceOf[IR.Application.Operator.Binary] ir.right.value - .asInstanceOf[IR.Application.Operator.Binary] - .left - .value shouldBe an[IR.Name.Qualified] + .asInstanceOf[IR.Type.Function] + .args(0) shouldBe an[IR.Name.Qualified] } "properly support the `in` context ascription operator" in { diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala index d3c70fc9d5e2..89c86428c1f9 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala @@ -158,7 +158,10 @@ class TypeSignaturesTest m.methodName.name == methodName case _ => false }.get - m.unsafeGetMetadata(TypeSignatures, "come on").signature + m.unsafeGetMetadata( + TypeSignatures, + s"expected a type signature on method $methodName" + ).signature } "Type Signatures" should { @@ -231,6 +234,34 @@ class TypeSignaturesTest ("Unnamed.Test.Foo" | "my_pkg.My_Lib.Util.Util_2" | "my_pkg.My_Lib.Util.Util_Sum") ->: "Unnamed.Test.Foo" ) } + + "resolve bare return types in local functions" in { + val code = + """ + |type Number + | @Builtin_Type + | type Number + | + |baz = + | x : Number + | x = 1334 + |""".stripMargin + + val module = code.preprocessModule + println( + module + .bindings(1) + .asInstanceOf[IR.Module.Scope.Definition.Method.Explicit] + .body + .asInstanceOf[IR.Function.Lambda] + .body + .asInstanceOf[IR.Expression.Block] + .returnValue + .unsafeGetMetadata(TypeSignatures, "must have a signature") + .signature + .unsafeGetMetadata(TypeNames, "must have a resolution") + ) + } } } From 37ca55d0eb36fcc5c8ac38a29ddf9a105e0c4eb6 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Sat, 4 Jun 2022 22:12:05 +0200 Subject: [PATCH 012/110] fix docs & tests --- .../compiler/pass/resolve/TypeNames.scala | 11 +------- .../test/semantic/TypeSignaturesTest.scala | 28 ------------------- 2 files changed, 1 insertion(+), 38 deletions(-) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala index 028ee275d3a6..e35d80978c67 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala @@ -9,16 +9,7 @@ import org.enso.compiler.pass.IRPass import org.enso.compiler.pass.analyse.BindingAnalysis import scala.annotation.unused - -/** Resolves and desugars referent name occurences in non-pattern contexts. - * - * 1. Attaches resolution metadata to encountered constructors, modules, - * and polygot symbols. - * 2. Desugars encountered method references into proper applications. - * 3. Resolves qualified calls to constructors, i.e. a call of the form - * `KnownModule.consName a b c` is transformed into `KnownCons a b c`, - * if `consName` refers to a constructor and `KnownModule` was successfully - * resolved to a module. +/** Resolves and desugars referent name occurences in type positions. */ case object TypeNames extends IRPass { diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala index 89c86428c1f9..637908ddfaee 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala @@ -234,34 +234,6 @@ class TypeSignaturesTest ("Unnamed.Test.Foo" | "my_pkg.My_Lib.Util.Util_2" | "my_pkg.My_Lib.Util.Util_Sum") ->: "Unnamed.Test.Foo" ) } - - "resolve bare return types in local functions" in { - val code = - """ - |type Number - | @Builtin_Type - | type Number - | - |baz = - | x : Number - | x = 1334 - |""".stripMargin - - val module = code.preprocessModule - println( - module - .bindings(1) - .asInstanceOf[IR.Module.Scope.Definition.Method.Explicit] - .body - .asInstanceOf[IR.Function.Lambda] - .body - .asInstanceOf[IR.Expression.Block] - .returnValue - .unsafeGetMetadata(TypeSignatures, "must have a signature") - .signature - .unsafeGetMetadata(TypeNames, "must have a resolution") - ) - } } } From d4e76502fd83f39e7ba2abeb460a04fe3d4add00 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Sat, 4 Jun 2022 22:32:52 +0200 Subject: [PATCH 013/110] fix formatting --- .../org/enso/compiler/pass/resolve/SuspendedArguments.scala | 2 +- .../main/scala/org/enso/compiler/pass/resolve/TypeNames.scala | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala index 07f9012de5c6..fe0c2d19eb80 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala @@ -240,7 +240,7 @@ case object SuspendedArguments extends IRPass { def toSegments(signature: IR.Expression): List[IR.Expression] = { signature match { case IR.Type.Function(args, ret, _, _, _) => args :+ ret - case _ => List(signature) + case _ => List(signature) } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala index e35d80978c67..ce42ba06c367 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala @@ -9,6 +9,7 @@ import org.enso.compiler.pass.IRPass import org.enso.compiler.pass.analyse.BindingAnalysis import scala.annotation.unused + /** Resolves and desugars referent name occurences in type positions. */ case object TypeNames extends IRPass { From 1237536219277c57a68bb2424e40b93e8f7582c7 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Sat, 4 Jun 2022 22:40:37 +0200 Subject: [PATCH 014/110] fmt & doc --- CHANGELOG.md | 2 ++ .../java/org/enso/interpreter/runtime/scope/TopLevelScope.java | 1 - 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 47c8e6e9b54a..7442822a254a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -255,6 +255,7 @@ - [Drop Core implementation of IR][3512] - [Replace `this` with `self`][3524] - [Introduce a smaller version of the standard library, just for testing][3531] +- [Read and resolve type signatures][3511] [3227]: https://github.com/enso-org/enso/pull/3227 [3248]: https://github.com/enso-org/enso/pull/3248 @@ -286,6 +287,7 @@ [3512]: https://github.com/enso-org/enso/pull/3512 [3524]: https://github.com/enso-org/enso/pull/3524 [3531]: https://github.com/enso-org/enso/pull/3531 +[3511]: https://github.com/enso-org/enso/pull/3511 # Enso 2.0.0-alpha.18 (2021-10-12) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java index b71a93d98e29..9f1703e8033e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java @@ -76,7 +76,6 @@ public Module createModule(QualifiedName name, Package pkg, String return module; } - /** * Returns the builtins module. * From e7bbb26055cf28a44797f6f9be4cbd9ad63e0a5a Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 28 Jun 2022 16:26:48 +0200 Subject: [PATCH 015/110] keep moving towards actual tycons --- .../enso/compiler/codegen/IrToTruffle.scala | 10 ++ .../compiler/context/SuggestionBuilder.scala | 2 +- .../scala/org/enso/compiler/core/IR.scala | 11 ++ .../org/enso/compiler/data/BindingsMap.scala | 159 ++++-------------- .../pass/resolve/MethodDefinitions.scala | 2 + .../enso/compiler/pass/resolve/Patterns.scala | 12 ++ .../compiler/pass/resolve/TypeNames.scala | 2 +- .../compiler/phase/ExportsResolution.scala | 13 +- .../enso/compiler/phase/StubIrBuilder.scala | 1 - .../Standard/Base/0.0.0-dev/src/Data/Any.enso | 2 +- .../Base/0.0.0-dev/src/Data/Array.enso | 2 +- .../Base/0.0.0-dev/src/Data/Boolean.enso | 2 +- .../Base/0.0.0-dev/src/Data/Numbers.enso | 4 +- .../Base/0.0.0-dev/src/Data/Text.enso | 2 +- .../Base/0.0.0-dev/src/Data/Time/Date.enso | 10 +- .../Base/0.0.0-dev/src/Error/Common.enso | 6 +- .../Standard/Base/0.0.0-dev/src/Nothing.enso | 2 +- .../Standard/Base/0.0.0-dev/src/Polyglot.enso | 2 +- .../Base/0.0.0-dev/src/Runtime/Resource.enso | 2 +- 19 files changed, 92 insertions(+), 154 deletions(-) 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 e6a4356b0ea9..2e90e8dca04f 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 @@ -259,6 +259,8 @@ class IrToTruffle( .getMetadata(MethodDefinitions) .map { res => res.target match { + case _: BindingsMap.ResolvedType => + throw new CompilerError("todo") case BindingsMap.ResolvedModule(module) => module.unsafeAsModule().getScope.getAssociatedType case BindingsMap.ResolvedConstructor(definitionModule, cons) => @@ -455,6 +457,7 @@ class IrToTruffle( private def getConstructorResolution(expr: IR): Option[AtomConstructor] = expr.getMetadata(MethodDefinitions).map { res => res.target match { + case _: BindingsMap.ResolvedType => throw new CompilerError("todo") case BindingsMap.ResolvedModule(module) => module.unsafeAsModule().getScope.getAssociatedType case BindingsMap.ResolvedConstructor(definitionModule, cons) => @@ -556,6 +559,7 @@ class IrToTruffle( case (name, resolution :: _) => if (resolution.module.unsafeAsModule() != moduleScope.getModule) { resolution match { + case _: BindingsMap.ResolvedType => throw new CompilerError("todo") case BindingsMap.ResolvedConstructor(definitionModule, cons) => val runtimeCons = definitionModule .unsafeAsModule() @@ -857,6 +861,10 @@ class IrToTruffle( Right( mod.unsafeAsModule().getScope.getConstructors.get(cons.name) ) + case Some( + BindingsMap.Resolution(BindingsMap.ResolvedType(_, _)) + ) => + throw new CompilerError("todo") case Some( BindingsMap.Resolution( BindingsMap.ResolvedPolyglotSymbol(_, _) @@ -1060,6 +1068,8 @@ class IrToTruffle( } else if (global.isDefined) { val resolution = global.get.target resolution match { + case _: BindingsMap.ResolvedType => + throw new CompilerError("todo") case BindingsMap.ResolvedConstructor(definitionModule, cons) => ConstructorNode.build( definitionModule 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 86c0d0b73d17..21fe760c2df5 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 @@ -303,7 +303,7 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { } private def buildResolvedUnionTypeName( - resolvedName: BindingsMap.ResolvedTypeName + resolvedName: BindingsMap.ResolvedName ): TypeArg = resolvedName match { case tp: BindingsMap.ResolvedType => TypeArg.Sum( 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 e04fabcf2653..46105d7d280d 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 @@ -6955,6 +6955,17 @@ object IR { s"but methods are not allowed in $context." } + /** An error coming from an unexpected occurence of a type. + * + * @param context the description of a context in which the error + * happened. + */ + case class UnexpectedType(context: String) extends Reason { + override def explain(originalName: Name): String = + s"The name ${originalName.name} resolved to a type, " + + s"but types are not allowed in $context." + } + /** An error coming from usage of an undefined variable name. */ case object VariableNotInScope extends Reason { 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 949d5fb39328..f06c0d4dac44 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 @@ -46,10 +46,6 @@ case class BindingsMap( */ var exportedSymbols: Map[String, List[ResolvedName]] = Map() - /** Symbols exported by [[currentModule]]. - */ - var allExportedSymbols: Map[String, List[ResolvedTypeName]] = Map() - /** @inheritdoc */ override def prepareForSerialization( compiler: Compiler @@ -76,10 +72,6 @@ case class BindingsMap( copy.exportedSymbols = this.exportedSymbols.map { case (key, value) => key -> value.map(name => name.toAbstract) } - copy.allExportedSymbols = this.allExportedSymbols.map { case (key, value) => - key -> value.map(_.toAbstract) - } - copy } @@ -115,7 +107,7 @@ case class BindingsMap( } val withSymbols: Option[BindingsMap] = withExports.flatMap { bindings => - val newSymbols = this.allExportedSymbols.map { case (key, value) => + val newSymbols = this.exportedSymbols.map { case (key, value) => val newValue = value.map(_.toConcrete(moduleMap)) if (newValue.exists(_.isEmpty)) { key -> None @@ -127,16 +119,9 @@ case class BindingsMap( if (newSymbols.exists { case (_, v) => v.isEmpty }) { None } else { - bindings.allExportedSymbols = newSymbols.map { case (k, v) => + bindings.exportedSymbols = newSymbols.map { case (k, v) => k -> v.get } - bindings.exportedSymbols = bindings.allExportedSymbols.flatMap { - case (k, v) => - v.collect { case v: ResolvedName => v } match { - case List() => None - case other => Some((k, other)) - } - } Some(bindings) } } @@ -170,22 +155,12 @@ case class BindingsMap( .map(ResolvedMethod(currentModule, _)) } - private def findLocalCandidates( - name: String, - includeTypes: Boolean - ): List[ResolvedTypeName] = { - if (includeTypes) { - val types = findTypeCandidates(name) - if (types.nonEmpty) { - // If types are included – they take precedence. - // Remove this logic when sum types get proper runtime meaning. - return types - } - } + private def findLocalCandidates(name: String): List[ResolvedName] = { + val types = findTypeCandidates(name) val conses = findConstructorCandidates(name) val polyglot = findPolyglotCandidates(name) val methods = findMethodCandidates(name) - val all = conses ++ polyglot ++ methods + val all = types ++ conses ++ polyglot ++ methods if (all.isEmpty && currentModule.getName.item == name) { List(ResolvedModule(currentModule)) } else { all } @@ -200,9 +175,8 @@ case class BindingsMap( } private def findExportedCandidatesInImports( - name: String, - includeTypes: Boolean - ): List[ResolvedTypeName] = { + name: String + ): List[ResolvedName] = { resolvedImports .flatMap { imp => @@ -214,7 +188,7 @@ case class BindingsMap( BindingAnalysis, "Wrong pass ordering. Running resolution on an unparsed module." ) - .findExportedSymbolsFor(name, includeTypes) + .findExportedSymbolsFor(name) case ModuleReference.Abstract(name) => throw new CompilerError( s"Cannot find export candidates for abstract module reference $name." @@ -224,9 +198,9 @@ case class BindingsMap( } } - private def handleAmbiguity[A <: ResolvedTypeName]( - candidates: List[A] - ): Either[ResolutionError, A] = { + private def handleAmbiguity( + candidates: List[ResolvedName] + ): Either[ResolutionError, ResolvedName] = { candidates.distinct match { case List() => Left(ResolutionNotFound) case List(it) => Right(it) @@ -234,18 +208,6 @@ case class BindingsMap( } } - /** Resolves a name as a type. - * - * NB: This should be removed when sum types become proper runtime values. - * - * @param name the type name to resolve. - * @return the resolution - */ - def resolveTypeName( - name: String - ): Either[ResolutionError, ResolvedTypeName] = - resolveUppercaseName(name, includeTypes = true) - /** Resolves a name in the context of current module. * * @param name the name to resolve. @@ -254,14 +216,8 @@ case class BindingsMap( */ def resolveUppercaseName( name: String - ): Either[ResolutionError, ResolvedName] = - narrowResolution(resolveUppercaseName(name, includeTypes = false)) - - def resolveUppercaseName( - name: String, - includeTypes: Boolean - ): Either[ResolutionError, ResolvedTypeName] = { - val local = findLocalCandidates(name, includeTypes = includeTypes) + ): Either[ResolutionError, ResolvedName] = { + val local = findLocalCandidates(name) if (local.nonEmpty) { return handleAmbiguity(local) } @@ -270,7 +226,7 @@ case class BindingsMap( return handleAmbiguity(qualifiedImps) } handleAmbiguity( - findExportedCandidatesInImports(name, includeTypes = includeTypes) + findExportedCandidatesInImports(name) ) } @@ -308,30 +264,9 @@ case class BindingsMap( } private def findExportedSymbolsFor( - name: String, - includeTypes: Boolean - ): List[ResolvedTypeName] = { - if (includeTypes) { - val allSymbols = allExportedSymbols.getOrElse(name.toLowerCase, List()) - val onlyTypes = allSymbols.collect { case t: ResolvedType => - t - } - if (onlyTypes.nonEmpty) { - onlyTypes - } else { - allSymbols - } - } else { - exportedSymbols.getOrElse(name.toLowerCase, List()) - } - } - - private def narrowResolution( - resolution: Either[ResolutionError, ResolvedTypeName] - ): Either[ResolutionError, ResolvedName] = resolution match { - case Right(value: ResolvedName) => Right(value) - case Right(_) => Left(ResolutionNotFound) - case Left(err) => Left(err) + name: String + ): List[ResolvedName] = { + exportedSymbols.getOrElse(name.toLowerCase, List()) } /** Resolves a name exported by this module. @@ -342,9 +277,7 @@ case class BindingsMap( def resolveExportedName( name: String ): Either[ResolutionError, ResolvedName] = { - narrowResolution( - handleAmbiguity(findExportedSymbolsFor(name, includeTypes = false)) - ) + handleAmbiguity(findExportedSymbolsFor(name)) } /** Dumps the export statements from this module into a structure ready for @@ -430,7 +363,7 @@ object BindingsMap { * @param resolution the particular resolution of `symbol` * @return whether access to the symbol is permitted by this restriction. */ - def canAccess(symbol: String, resolution: ResolvedTypeName): Boolean + def canAccess(symbol: String, resolution: ResolvedName): Boolean /** Performs static optimizations on the restriction, simplifying * common patterns. @@ -474,7 +407,7 @@ object BindingsMap { * @param resolution `symbol`'s resolution * @return `true` if the symbol is visible, `false` otherwise */ - def allows(symbol: String, resolution: ResolvedTypeName): Boolean = { + def allows(symbol: String, resolution: ResolvedName): Boolean = { val symbolMatch = this.symbol == symbol.toLowerCase val resolutionMatch = this.resolution.isEmpty || this.resolution.get == resolution @@ -512,7 +445,7 @@ object BindingsMap { /** @inheritdoc */ override def canAccess( symbol: String, - resolution: ResolvedTypeName + resolution: ResolvedName ): Boolean = symbols.exists(_.allows(symbol, resolution)) /** @inheritdoc */ @@ -542,7 +475,7 @@ object BindingsMap { /** @inheritdoc */ override def canAccess( symbol: String, - resolution: ResolvedTypeName + resolution: ResolvedName ): Boolean = !symbols.contains(symbol.toLowerCase) /** @inheritdoc */ @@ -562,7 +495,7 @@ object BindingsMap { /** @inheritdoc */ override def canAccess( symbol: String, - resolution: ResolvedTypeName + resolution: ResolvedName ): Boolean = true /** @inheritdoc */ @@ -584,7 +517,7 @@ object BindingsMap { /** @inheritdoc */ override def canAccess( symbol: String, - resolution: ResolvedTypeName + resolution: ResolvedName ): Boolean = false /** @inheritdoc */ @@ -610,7 +543,7 @@ object BindingsMap { /** @inheritdoc */ override def canAccess( symbol: String, - resolution: ResolvedTypeName + resolution: ResolvedName ): Boolean = restrictions.forall(_.canAccess(symbol, resolution)) /** @inheritdoc */ @@ -672,7 +605,7 @@ object BindingsMap { /** @inheritdoc */ override def canAccess( symbol: String, - resolution: ResolvedTypeName + resolution: ResolvedName ): Boolean = restrictions.exists(_.canAccess(symbol, resolution)) /** @inheritdoc */ @@ -822,37 +755,13 @@ object BindingsMap { */ case class ModuleMethod(name: String) - /** Represents a resolved name on typelevel. - * - * NB: should be unified with `ResolvedName` and removed, once sum types get - * a proper runtime meaning. - */ - sealed trait ResolvedTypeName { - def module: ModuleReference - - /** Convert the resolved name to abstract form. - * - * @return `this`, converted to abstract form - */ - def toAbstract: ResolvedTypeName - - /** Convert the resolved name to concrete form. - * - * @param moduleMap the mapping from qualified names to modules - * @return `this`, converted to concrete form - */ - def toConcrete(moduleMap: ModuleMap): Option[ResolvedTypeName] - - def qualifiedName: QualifiedName - } - /** A name resolved to a sum type. * * @param module the module defining the type * @param tp a representation for the type */ case class ResolvedType(override val module: ModuleReference, tp: Type) - extends ResolvedTypeName { + extends ResolvedName { def getVariants: Seq[ResolvedConstructor] = { val bindingsMap = getBindingsFrom(module) tp.members.flatMap(m => @@ -880,20 +789,24 @@ object BindingsMap { /** A result of successful name resolution. */ - sealed trait ResolvedName extends ResolvedTypeName { + sealed trait ResolvedName { + + def module: ModuleReference + + def qualifiedName: QualifiedName /** Convert the resolved name to abstract form. * * @return `this`, converted to abstract form */ - override def toAbstract: ResolvedName + def toAbstract: ResolvedName /** Convert the resolved name to concrete form. * * @param moduleMap the mapping from qualified names to modules * @return `this`, converted to concrete form */ - override def toConcrete(moduleMap: ModuleMap): Option[ResolvedName] + def toConcrete(moduleMap: ModuleMap): Option[ResolvedName] } /** A representation of a name being resolved to a constructor. @@ -1015,7 +928,7 @@ object BindingsMap { * * @param candidates all the possible resolutions for the name. */ - case class ResolutionAmbiguous(candidates: List[ResolvedTypeName]) + case class ResolutionAmbiguous(candidates: List[ResolvedName]) extends ResolutionError /** A resolution error due to the symbol not being found. @@ -1023,7 +936,7 @@ object BindingsMap { case object ResolutionNotFound extends ResolutionError /** A metadata-friendly storage for resolutions */ - case class TypeResolution(target: ResolvedTypeName) extends IRPass.Metadata { + case class TypeResolution(target: ResolvedName) extends IRPass.Metadata { /** The name of the metadata as a string. */ override val metadataName: String = "Resolution" diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala index 1aec13fc1fd9..dcc83f766849 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala @@ -133,6 +133,8 @@ case object MethodDefinitions extends IRPass { "a method definition target" ) ) + case Right(_: BindingsMap.ResolvedType) => + throw new CompilerError("todo") } case tp: IR.Error.Resolution => tp case _ => diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/Patterns.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/Patterns.scala index 7bb58111002c..10f0edcfe536 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/Patterns.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/Patterns.scala @@ -114,6 +114,13 @@ object Patterns extends IRPass { "a pattern match" ) ) + case Right(_: BindingsMap.ResolvedType) => + IR.Error.Resolution( + consName, + IR.Error.Resolution.UnexpectedType( + "a pattern match" + ) + ) } .getOrElse(consName) @@ -130,6 +137,11 @@ object Patterns extends IRPass { throw new CompilerError( "Impossible, should be transformed into an error before." ) + case BindingsMap.ResolvedType(_, _) => + throw new CompilerError( + "Impossible, should be transformed into an error before." + ) + } } expectedArity match { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala index ce42ba06c367..409d60e26339 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala @@ -76,7 +76,7 @@ case object TypeNames extends IRPass { ): IR.Expression = expression.transformExpressions { case n: IR.Name.Literal => bindingsMap - .resolveTypeName(n.name) + .resolveUppercaseName(n.name) .map(res => n.updateMetadata(this -->> TypeResolution(res))) .getOrElse(n) } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala b/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala index fc193e8816d2..32e5e85143f1 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala @@ -7,7 +7,6 @@ import org.enso.compiler.data.BindingsMap.{ ResolvedConstructor, ResolvedMethod, ResolvedModule, - ResolvedName, ResolvedPolyglotSymbol, ResolvedType, SymbolRestriction @@ -195,7 +194,7 @@ class ExportsResolution { (name.toLowerCase, List(ResolvedModule(mod))) } val reExportedSymbols = bindings.resolvedExports.flatMap { export => - getBindings(export.module.unsafeAsModule()).allExportedSymbols.toList + getBindings(export.module.unsafeAsModule()).exportedSymbols.toList .flatMap { case (sym, resolutions) => val allowedResolutions = resolutions.filter(res => export.symbols.canAccess(sym, res)) @@ -203,7 +202,7 @@ class ExportsResolution { else Some((sym, allowedResolutions)) } } - bindings.allExportedSymbols = List( + bindings.exportedSymbols = List( ownTypes, ownMethods, ownConstructors, @@ -213,14 +212,6 @@ class ExportsResolution { ).flatten.groupBy(_._1).map { case (m, names) => (m, names.flatMap(_._2).distinct) } - - bindings.exportedSymbols = bindings.allExportedSymbols.flatMap { - case (k, v) => - v.collect { case v: ResolvedName => v } match { - case List() => None - case other => Some((k, other)) - } - } } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala b/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala index 5f984ee6d16d..0dc3cdea9fea 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala @@ -58,7 +58,6 @@ object StubIrBuilder { ModuleReference.Concrete(module) ) meta.exportedSymbols = exportedBindings.toMap - meta.allExportedSymbols = meta.exportedSymbols ir.updateMetadata(BindingAnalysis -->> meta) } } diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso index 3ecca84d2874..4d8d3d2d65a5 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso @@ -1,3 +1,3 @@ -type Any +type Any_Tp @Builtin_Type type Any diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso index d0ea4bed7534..d352cfc5c9db 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso @@ -1,4 +1,4 @@ -type Array +type Array_Tp @Builtin_Type type Array diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso index 104dbe50555a..697e638aea56 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso @@ -1,4 +1,4 @@ -type Boolean +type Boolean_Tp @Builtin_Type type Boolean diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso index 6d7bd76076f2..acac8402aef4 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso @@ -1,7 +1,7 @@ -type Number +type Number_Tp @Builtin_Type type Number -type Integer +type Integer_Tp @Builtin_Type type Integer diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso index 67444c677b4d..c905ed6e639c 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso @@ -1,3 +1,3 @@ -type Text +type Text_Tp @Builtin_Type type Text diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso index 1d9a30992a8e..6196570ea51b 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso @@ -3,9 +3,9 @@ polyglot java import java.time.format.DateTimeFormatter new year (month = 1) (day = 1) = LocalDate.of year month day -type Date +type Date_Tp type Date internal_local_date - year = self . internal_local_date . getYear - month = self . internal_local_date . getMonthValue - day = self . internal_local_date . getDayOfMonth - to_text = DateTimeFormatter.ISO_LOCAL_DATE.format self.internal_local_date + year = this . internal_local_date . getYear + month = this . internal_local_date . getMonthValue + day = this . internal_local_date . getDayOfMonth + to_text = DateTimeFormatter.ISO_LOCAL_DATE.format this.internal_local_date diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index 5581271f4f57..53b454b2188b 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso @@ -1,4 +1,4 @@ -type Panic +type Panic_Tp @Builtin_Type type Panic throw payload = @Builtin_Method "Panic.throw" @@ -19,9 +19,9 @@ type Inexhaustive_Pattern_Match_Error scrutinee @Builtin_Type type Arity_Error expected_min expected_max actual -type Error +type Error_Tp @Builtin_Type type Error throw payload = @Builtin_Method "Error.throw" catch_primitive handler = @Builtin_Method "Error.catch_primitive" - catch (handler = x->x) = self.catch_primitive handler + catch (handler = x->x) = this.catch_primitive handler diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso index 45f26b23b6a5..c1fbf60c406e 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso @@ -1,3 +1,3 @@ -type Nothing +type Nothing_Tp @Builtin_Type type Nothing diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso index 78a4b2a4de39..1d64051cde4f 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso @@ -1,4 +1,4 @@ -type Polyglot +type Polyglot_Tp @Builtin_Type type Polyglot get_array_size array = @Builtin_Method "Polyglot.get_array_size" diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso index b4b41e846658..0bd076aedb43 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso @@ -1,7 +1,7 @@ bracket : Any -> (Any -> Nothing) -> (Any -> Any) -> Any bracket ~constructor ~destructor ~action = @Builtin_Method "Resource.bracket" -type Managed_Resource +type Managed_Resource_Tp @Builtin_Type type Managed_Resource register resource function = @Builtin_Method "Managed_Resource.register" From 675fb78854c4a8c73b328e3fbc3f439aefcc94a4 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 29 Jun 2022 17:38:44 +0200 Subject: [PATCH 016/110] mega awesome fix --- .../enso/compiler/codegen/IrToTruffle.scala | 2 +- .../test/context/SuggestionBuilderTest.scala | 98 +++++++++---------- .../Base/0.0.0-dev/src/Data/Time/Date.enso | 8 +- .../Base/0.0.0-dev/src/Error/Common.enso | 2 +- 4 files changed, 55 insertions(+), 55 deletions(-) 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 2e90e8dca04f..861e99eec45e 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 @@ -559,7 +559,7 @@ class IrToTruffle( case (name, resolution :: _) => if (resolution.module.unsafeAsModule() != moduleScope.getModule) { resolution match { - case _: BindingsMap.ResolvedType => throw new CompilerError("todo") + case _: BindingsMap.ResolvedType => //throw new CompilerError("todo") case BindingsMap.ResolvedConstructor(definitionModule, cons) => val runtimeCons = definitionModule .unsafeAsModule() diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/context/SuggestionBuilderTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/context/SuggestionBuilderTest.scala index 82f546d09aa4..189eab7b0933 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/context/SuggestionBuilderTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/context/SuggestionBuilderTest.scala @@ -61,7 +61,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -91,7 +91,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -122,7 +122,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = "Number", @@ -151,7 +151,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = "Foo.Bar", @@ -180,7 +180,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None), + Suggestion.Argument("self", "Unnamed.Test", false, false, None), Suggestion.Argument("a", "Text", false, false, None) ), selfType = "Unnamed.Test", @@ -210,7 +210,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None), + Suggestion.Argument("self", "Unnamed.Test", false, false, None), Suggestion.Argument( "a", "Either (Vector Number) Text", @@ -247,7 +247,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = "Foo.Bar Baz", @@ -278,7 +278,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None), + Suggestion.Argument("self", "Unnamed.Test", false, false, None), Suggestion .Argument("a", SuggestionBuilder.Any, false, false, None), Suggestion @@ -331,7 +331,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None), + Suggestion.Argument("self", "Unnamed.Test", false, false, None), Suggestion .Argument("a", SuggestionBuilder.Any, false, true, Some("0")) ), @@ -375,7 +375,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "bar", arguments = Seq( Suggestion - .Argument("this", "Unnamed.Test.MyType", false, false, None), + .Argument("self", "Unnamed.Test.MyType", false, false, None), Suggestion .Argument("a", SuggestionBuilder.Any, false, false, None), Suggestion @@ -432,7 +432,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "bar", arguments = Seq( Suggestion - .Argument("this", "Unnamed.Test.MyAtom", false, false, None), + .Argument("self", "Unnamed.Test.MyAtom", false, false, None), Suggestion.Argument("a", "Number", false, false, None), Suggestion.Argument("b", "Number", false, false, None) ), @@ -477,7 +477,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "apply", arguments = Seq( Suggestion - .Argument("this", "Unnamed.Test.MyAtom", false, false, None), + .Argument("self", "Unnamed.Test.MyAtom", false, false, None), Suggestion.Argument("f", "Number -> Number", false, false, None) ), selfType = "Unnamed.Test.MyAtom", @@ -548,7 +548,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { arguments = Seq( Suggestion .Argument( - "this", + "self", "Unnamed.Test.Other_Atom", false, false, @@ -595,7 +595,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None), + Suggestion.Argument("self", "Unnamed.Test", false, false, None), Suggestion .Argument("a", SuggestionBuilder.Any, true, false, None) ), @@ -638,7 +638,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None), + Suggestion.Argument("self", "Unnamed.Test", false, false, None), Suggestion.Argument("a", "Unnamed.Test.A", false, false, None) ), selfType = "Unnamed.Test", @@ -687,7 +687,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.MyType", false, false, None) + .Argument("self", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -753,7 +753,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.MyMaybe", false, false, None) + .Argument("self", "Unnamed.Test.MyMaybe", false, false, None) ), selfType = "Unnamed.Test.MyMaybe", returnType = SuggestionBuilder.Any, @@ -793,7 +793,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "x", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.Newtype", false, false, None) + .Argument("self", "Unnamed.Test.Newtype", false, false, None) ), selfType = "Unnamed.Test.NewType", returnType = SuggestionBuilder.Any, @@ -836,7 +836,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -885,7 +885,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -947,7 +947,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1007,7 +1007,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1054,7 +1054,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1099,7 +1099,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1157,7 +1157,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1214,7 +1214,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1271,7 +1271,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.MyType", false, false, None) + .Argument("self", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -1286,7 +1286,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "b", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.MyType", false, false, None) + .Argument("self", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -1333,7 +1333,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.MyType", false, false, None) + .Argument("self", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -1348,7 +1348,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "b", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.MyType", false, false, None) + .Argument("self", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -1403,7 +1403,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.Just", false, false, None) + .Argument("self", "Unnamed.Test.Just", false, false, None) ), selfType = "Unnamed.Test.Just", returnType = SuggestionBuilder.Any, @@ -1463,7 +1463,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.Just", false, false, None) + .Argument("self", "Unnamed.Test.Just", false, false, None) ), selfType = "Unnamed.Test.Just", returnType = SuggestionBuilder.Any, @@ -1521,7 +1521,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "empty", arguments = Seq( Suggestion - .Argument("this", "Unnamed.Test.Cons", false, false, None) + .Argument("self", "Unnamed.Test.Cons", false, false, None) ), selfType = "Unnamed.Test.Cons", returnType = "Unnamed.Test.List", @@ -1536,7 +1536,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "empty", arguments = Seq( Suggestion - .Argument("this", "Unnamed.Test.Nil", false, false, None) + .Argument("self", "Unnamed.Test.Nil", false, false, None) ), selfType = "Unnamed.Test.Nil", returnType = "Unnamed.Test.List", @@ -1594,7 +1594,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.Just", false, false, None) + .Argument("self", "Unnamed.Test.Just", false, false, None) ), selfType = "Unnamed.Test.Just", returnType = SuggestionBuilder.Any, @@ -1609,7 +1609,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "map", arguments = Seq( Suggestion - .Argument("this", "Unnamed.Test.Nothing", false, false, None), + .Argument("self", "Unnamed.Test.Nothing", false, false, None), Suggestion .Argument("f", SuggestionBuilder.Any, false, false, None) ), @@ -1626,7 +1626,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "map", arguments = Seq( Suggestion - .Argument("this", "Unnamed.Test.Just", false, false, None), + .Argument("self", "Unnamed.Test.Just", false, false, None), Suggestion .Argument("f", SuggestionBuilder.Any, false, false, None) ), @@ -1673,7 +1673,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.MyType", false, false, None) + .Argument("self", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -1688,7 +1688,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "b", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.MyType", false, false, None) + .Argument("self", "Unnamed.Test.MyType", false, false, None) ), selfType = "Unnamed.Test.MyType", returnType = SuggestionBuilder.Any, @@ -1702,7 +1702,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1745,7 +1745,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("this", "Unnamed.Test.Test", false, false, None) + .Argument("self", "Unnamed.Test.Test", false, false, None) ), selfType = "Unnamed.Test.Test", returnType = SuggestionBuilder.Any, @@ -1759,7 +1759,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1808,7 +1808,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "quux", arguments = Vector( Suggestion - .Argument("this", "Unnamed.Test.A", false, false, None), + .Argument("self", "Unnamed.Test.A", false, false, None), Suggestion.Argument( "x", "Unnamed.Test.A", @@ -1830,7 +1830,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "quux", arguments = Vector( - Suggestion.Argument("this", "Unnamed.Test", false, false, None), + Suggestion.Argument("self", "Unnamed.Test", false, false, None), Suggestion.Argument( "x", "Unnamed.Test.A", @@ -1852,7 +1852,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = List( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1885,7 +1885,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1919,7 +1919,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -1973,7 +1973,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "main", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, @@ -2025,7 +2025,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "foo", arguments = Seq( - Suggestion.Argument("this", "Unnamed.Test", false, false, None) + Suggestion.Argument("self", "Unnamed.Test", false, false, None) ), selfType = "Unnamed.Test", returnType = SuggestionBuilder.Any, diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso index 6196570ea51b..d2486efa28e2 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso @@ -5,7 +5,7 @@ new year (month = 1) (day = 1) = LocalDate.of year month day type Date_Tp type Date internal_local_date - year = this . internal_local_date . getYear - month = this . internal_local_date . getMonthValue - day = this . internal_local_date . getDayOfMonth - to_text = DateTimeFormatter.ISO_LOCAL_DATE.format this.internal_local_date + year = self . internal_local_date . getYear + month = self . internal_local_date . getMonthValue + day = self . internal_local_date . getDayOfMonth + to_text = DateTimeFormatter.ISO_LOCAL_DATE.format self.internal_local_date diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index 53b454b2188b..df87b49f6ca9 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso @@ -24,4 +24,4 @@ type Error_Tp type Error throw payload = @Builtin_Method "Error.throw" catch_primitive handler = @Builtin_Method "Error.catch_primitive" - catch (handler = x->x) = this.catch_primitive handler + catch (handler = x->x) = self.catch_primitive handler From abe1a4a47ddf021551baaf9b97b75eaa614b3062 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 13 Jul 2022 16:39:09 +0200 Subject: [PATCH 017/110] checkpoint --- .../interpreter/runtime/builtin/Bool.java | 18 +-- .../builtin/BuiltinAtomConstructor.java | 32 ----- .../runtime/builtin/BuiltinType.java | 32 +++++ .../interpreter/runtime/builtin/Builtins.java | 85 +++++++------ .../interpreter/runtime/builtin/Error.java | 76 +++++------ .../interpreter/runtime/builtin/Number.java | 30 ++--- .../interpreter/runtime/builtin/Ordering.java | 24 ++-- .../interpreter/runtime/builtin/System.java | 4 +- .../enso/interpreter/runtime/data/Type.java | 22 ++++ .../runtime/scope/ModuleScope.java | 113 ++++++++++------- .../org/enso/compiler/codegen/AstToIr.scala | 19 ++- .../org/enso/compiler/codegen/AstView.scala | 2 + .../enso/compiler/codegen/IrToTruffle.scala | 23 ++-- .../compiler/context/SuggestionBuilder.scala | 2 +- .../scala/org/enso/compiler/core/IR.scala | 101 ++++++++------- .../compiler/pass/analyse/AliasAnalysis.scala | 25 +++- .../pass/analyse/BindingAnalysis.scala | 25 ++-- .../analyse/CachePreferenceAnalysis.scala | 10 +- .../pass/analyse/DataflowAnalysis.scala | 17 +-- .../enso/compiler/pass/analyse/TailCall.scala | 10 +- .../compiler/pass/desugar/ComplexType.scala | 69 +++++----- .../pass/desugar/FunctionBinding.scala | 6 +- .../pass/resolve/DocumentationComments.scala | 28 ++-- .../pass/resolve/MethodDefinitions.scala | 5 +- .../pass/resolve/ModuleAnnotations.scala | 4 +- .../pass/resolve/OverloadsResolution.scala | 20 +-- .../pass/resolve/SuspendedArguments.scala | 9 +- .../pass/resolve/TypeSignatures.scala | 9 +- .../org/enso/compiler/test/CompilerTest.scala | 28 ++-- .../compiler/test/codegen/AstToIrTest.scala | 40 +++--- .../test/pass/analyse/AliasAnalysisTest.scala | 6 +- .../pass/analyse/GatherDiagnosticsTest.scala | 120 +++++++++--------- .../test/pass/desugar/ComplexTypeTest.scala | 16 +-- .../pass/desugar/OperatorToFunctionTest.scala | 12 +- .../resolve/DocumentationCommentsTest.scala | 4 +- .../resolve/GenerateDocumentationTest.scala | 4 +- .../pass/resolve/ModuleAnnotationsTest.scala | 22 ++-- .../resolve/OverloadsResolutionTest.scala | 14 +- ...t.scala => SugaredTypeFunctionsTest.scala} | 2 +- .../pass/resolve/TypeSignaturesTest.scala | 2 +- 40 files changed, 566 insertions(+), 524 deletions(-) delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinAtomConstructor.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java rename engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/{TypeFunctionsTest.scala => SugaredTypeFunctionsTest.scala} (98%) 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 bea8de6b5fd4..242ba19d07b3 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 @@ -6,29 +6,29 @@ /** A container class for all Boolean-related stdlib builtins. */ public class Bool { - private final BuiltinAtomConstructor tru; - private final BuiltinAtomConstructor fls; - private final BuiltinAtomConstructor bool; + private final BuiltinType tru; + private final BuiltinType fls; + private final BuiltinType bool; /** 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); + bool = new BuiltinType(builtins, Boolean.class); + tru = new BuiltinType(builtins, True.class); + fls = new BuiltinType(builtins, False.class); } /** @return the atom constructor for {@code True}. */ public AtomConstructor getTrue() { - return tru.constructor(); + return tru.getType(); } /** @return the atom constructor for {@code False}. */ public AtomConstructor getFalse() { - return fls.constructor(); + return fls.getType(); } /** @return the atom constructor for {@code Boolean}. */ public AtomConstructor getBool() { - return bool.constructor(); + return bool.getType(); } } 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 deleted file mode 100644 index 8f87dc329b14..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinAtomConstructor.java +++ /dev/null @@ -1,32 +0,0 @@ -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/BuiltinType.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java new file mode 100644 index 000000000000..3525bbf105aa --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.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.data.Type; + +import static com.oracle.truffle.api.CompilerDirectives.transferToInterpreterAndInvalidate; + +public class BuiltinType { + private final Builtins builtins; + private final Class clazz; + + @CompilerDirectives.CompilationFinal Type type; + + public BuiltinType(Builtins builtins, Class clazz) { + this.builtins = builtins; + this.clazz = clazz; + } + + public Type getType() { + if (type == null) { + transferToInterpreterAndInvalidate(); + type = builtins.getBuiltinType(type); + } + return type; + } + +// Atom newInstance(Object... args) { +// return getType().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 8ae974074917..eee6d09d9083 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 @@ -33,6 +33,7 @@ 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.data.Type; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.interpreter.runtime.type.TypesFromProxy; import org.enso.pkg.QualifiedName; @@ -51,7 +52,7 @@ public static class Debug { } private final Map>> builtinMethodNodes; - private final Map builtins; + private final Map builtins; private final Error error; private final Module module; @@ -63,19 +64,19 @@ public static class Debug { 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; - private final BuiltinAtomConstructor file; - private final BuiltinAtomConstructor warning; + private final BuiltinType any; + private final BuiltinType nothing; + private final BuiltinType function; + private final BuiltinType polyglot; + private final BuiltinType text; + private final BuiltinType array; + private final BuiltinType dataflowError; + private final BuiltinType ref; + private final BuiltinType managedResource; + private final BuiltinType debug; + private final BuiltinType projectDescription; + private final BuiltinType file; + private final BuiltinType warning; /** * Creates an instance with builtin methods installed. @@ -98,23 +99,23 @@ public Builtins(Context context) { number = new Number(this); bool = new Bool(this); - any = new BuiltinAtomConstructor(this, Any.class); - nothing = new BuiltinAtomConstructor(this, Nothing.class); + any = new BuiltinType(this, Any.class); + nothing = new BuiltinType(this, Nothing.class); function = - new BuiltinAtomConstructor( + new BuiltinType( 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); + polyglot = new BuiltinType(this, Polyglot.class); + text = new BuiltinType(this, Text.class); + array = new BuiltinType(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); - file = new BuiltinAtomConstructor(this, File.class); + new BuiltinType(this, org.enso.interpreter.node.expression.builtin.Error.class); + ref = new BuiltinType(this, Ref.class); + managedResource = new BuiltinType(this, ManagedResource.class); + debug = new BuiltinType(this, Debug.class); + projectDescription = new BuiltinType(this, ProjectDescription.class); + file = new BuiltinType(this, File.class); special = new Special(language); - warning = new BuiltinAtomConstructor(this, Warning.class); + warning = new BuiltinType(this, Warning.class); } /** @@ -311,9 +312,9 @@ private Map>> readBuiltinMethodsMetad * builtin method was ever registerd */ public Optional getBuiltinFunction( - AtomConstructor atom, String methodName, Language language) { + Type type, String methodName, Language language) { // TODO: move away from String mapping once Builtins is gone - Map> atomNodes = builtinMethodNodes.get(atom.getName()); + Map> atomNodes = builtinMethodNodes.get(type.getName()); if (atomNodes == null) return Optional.empty(); Class clazz = atomNodes.get(methodName); if (clazz == null) return Optional.empty(); @@ -341,7 +342,7 @@ public AtomConstructor getBuiltinType(String name) { * @return the {@code Nothing} atom constructor */ public AtomConstructor nothing() { - return nothing.constructor(); + return nothing.getType(); } /** @@ -350,7 +351,7 @@ public AtomConstructor nothing() { * @return the {@code Text} part of builtins. */ public AtomConstructor text() { - return text.constructor(); + return text.getType(); } /** @@ -359,7 +360,7 @@ public AtomConstructor text() { * @return the {@code Function} atom constructor */ public AtomConstructor function() { - return function.constructor(); + return function.getType(); } /** @@ -378,7 +379,7 @@ public Bool bool() { /** @return the ManagedResource constructor. */ public AtomConstructor managedResource() { - return managedResource.constructor(); + return managedResource.getType(); } /** @return the builtin Error types container. */ @@ -392,7 +393,7 @@ public Error error() { * @return the {@code Any} atom constructor */ public AtomConstructor any() { - return any.constructor(); + return any.getType(); } /** @@ -401,7 +402,7 @@ public AtomConstructor any() { * @return the {@code Warning} atom constructor */ public AtomConstructor warning() { - return warning.constructor(); + return warning.getType(); } /** @@ -410,7 +411,7 @@ public AtomConstructor warning() { * @return the {@code File} atom constructor */ public AtomConstructor file() { - return file.constructor(); + return file.getType(); } /** @@ -420,12 +421,12 @@ public AtomConstructor file() { * @return the {@code Debug} atom constructor */ public AtomConstructor debug() { - return debug.constructor(); + return debug.getType(); } /** @return the {@code Project_Description} atom constructor */ public AtomConstructor getProjectDescription() { - return projectDescription.constructor(); + return projectDescription.getType(); } /** @return the {@code System} atom constructor. */ @@ -435,17 +436,17 @@ public System system() { /** @return the Array constructor. */ public AtomConstructor array() { - return array.constructor(); + return array.getType(); } /** @return the Ref constructor. */ public AtomConstructor ref() { - return ref.constructor(); + return ref.getType(); } /** @return the container for polyglot-related builtins. */ public AtomConstructor polyglot() { - return polyglot.constructor(); + return polyglot.getType(); } /** @return the {@code Caught_Panic} atom constructor */ @@ -465,7 +466,7 @@ public Ordering ordering() { /** @return the container for the dataflow error-related builtins */ public AtomConstructor dataflowError() { - return dataflowError.constructor(); + return dataflowError.getType(); } public Special special() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Error.java index 018a635f2235..ec2001cc73fb 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 @@ -15,24 +15,24 @@ /** Container for builtin Error types */ public class Error { - 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; + private final BuiltinType syntaxError; + private final BuiltinType typeError; + private final BuiltinType compileError; + private final BuiltinType inexhaustivePatternMatchError; + private final BuiltinType uninitializedState; + private final BuiltinType noSuchMethodError; + private final BuiltinType noSuchConversionError; + private final BuiltinType polyglotError; + private final BuiltinType moduleNotInPackageError; + private final BuiltinType arithmeticError; + private final BuiltinType invalidArrayIndexError; + private final BuiltinType arityError; + private final BuiltinType unsupportedArgumentsError; + private final BuiltinType moduleDoesNotExistError; + private final BuiltinType notInvokableError; + private final BuiltinType invalidConversionTargetError; + private final BuiltinType panic; + private final BuiltinType caughtPanic; @CompilerDirectives.CompilationFinal private Atom arithmeticErrorShiftTooBig; @@ -43,27 +43,27 @@ public class Error { /** 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); + syntaxError = new BuiltinType(builtins, SyntaxError.class); + typeError = new BuiltinType(builtins, TypeError.class); + compileError = new BuiltinType(builtins, CompileError.class); inexhaustivePatternMatchError = - new BuiltinAtomConstructor(builtins, InexhaustivePatternMatchError.class); - uninitializedState = new BuiltinAtomConstructor(builtins, UninitializedState.class); - noSuchMethodError = new BuiltinAtomConstructor(builtins, NoSuchMethodError.class); - noSuchConversionError = new BuiltinAtomConstructor(builtins, NoSuchConversionError.class); - polyglotError = new BuiltinAtomConstructor(builtins, PolyglotError.class); - moduleNotInPackageError = new BuiltinAtomConstructor(builtins, ModuleNotInPackageError.class); - arithmeticError = new BuiltinAtomConstructor(builtins, ArithmeticError.class); - invalidArrayIndexError = new BuiltinAtomConstructor(builtins, InvalidArrayIndexError.class); - arityError = new BuiltinAtomConstructor(builtins, ArityError.class); + new BuiltinType(builtins, InexhaustivePatternMatchError.class); + uninitializedState = new BuiltinType(builtins, UninitializedState.class); + noSuchMethodError = new BuiltinType(builtins, NoSuchMethodError.class); + noSuchConversionError = new BuiltinType(builtins, NoSuchConversionError.class); + polyglotError = new BuiltinType(builtins, PolyglotError.class); + moduleNotInPackageError = new BuiltinType(builtins, ModuleNotInPackageError.class); + arithmeticError = new BuiltinType(builtins, ArithmeticError.class); + invalidArrayIndexError = new BuiltinType(builtins, InvalidArrayIndexError.class); + arityError = new BuiltinType(builtins, ArityError.class); unsupportedArgumentsError = - new BuiltinAtomConstructor(builtins, UnsupportedArgumentTypes.class); - moduleDoesNotExistError = new BuiltinAtomConstructor(builtins, ModuleDoesNotExist.class); - notInvokableError = new BuiltinAtomConstructor(builtins, NotInvokableError.class); + new BuiltinType(builtins, UnsupportedArgumentTypes.class); + moduleDoesNotExistError = new BuiltinType(builtins, ModuleDoesNotExist.class); + notInvokableError = new BuiltinType(builtins, NotInvokableError.class); invalidConversionTargetError = - new BuiltinAtomConstructor(builtins, InvalidConversionTargetError.class); - panic = new BuiltinAtomConstructor(builtins, Panic.class); - caughtPanic = new BuiltinAtomConstructor(builtins, CaughtPanic.class); + new BuiltinType(builtins, InvalidConversionTargetError.class); + panic = new BuiltinType(builtins, Panic.class); + caughtPanic = new BuiltinType(builtins, CaughtPanic.class); } public Atom makeSyntaxError(Object message) { @@ -87,11 +87,11 @@ public Atom makeModuleNotInPackageError() { } public AtomConstructor panic() { - return panic.constructor(); + return panic.getType(); } public AtomConstructor caughtPanic() { - return caughtPanic.constructor(); + return caughtPanic.getType(); } /** 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 b1f0dfeb1c86..da0c5963999a 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 @@ -8,45 +8,45 @@ /** A container for all number-related builtins. */ public class Number { - private final BuiltinAtomConstructor smallInteger; - private final BuiltinAtomConstructor bigInteger; - private final BuiltinAtomConstructor integer; - private final BuiltinAtomConstructor number; - private final BuiltinAtomConstructor decimal; + private final BuiltinType smallInteger; + private final BuiltinType bigInteger; + private final BuiltinType integer; + private final BuiltinType number; + private final BuiltinType 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); + smallInteger = new BuiltinType(builtins, SmallInteger.class); + bigInteger = new BuiltinType(builtins, BigInteger.class); + integer = new BuiltinType(builtins, Integer.class); number = - new BuiltinAtomConstructor( + new BuiltinType( builtins, org.enso.interpreter.node.expression.builtin.number.Number.class); - decimal = new BuiltinAtomConstructor(builtins, Decimal.class); + decimal = new BuiltinType(builtins, Decimal.class); } /** @return the Int64 atom constructor. */ public AtomConstructor getSmallInteger() { - return smallInteger.constructor(); + return smallInteger.getType(); } /** @return the Big_Integer atom constructor. */ public AtomConstructor getBigInteger() { - return bigInteger.constructor(); + return bigInteger.getType(); } /** @return the Integer atom constructor */ public AtomConstructor getInteger() { - return integer.constructor(); + return integer.getType(); } /** @return the Number atom constructor */ public AtomConstructor getNumber() { - return number.constructor(); + return number.getType(); } /** @return the Decimal atom constructor */ public AtomConstructor getDecimal() { - return decimal.constructor(); + return decimal.getType(); } } 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 6c5f44b4354e..29192d1aa540 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 @@ -9,18 +9,18 @@ /** A container for builtin ordering types. */ public class Ordering { - private final BuiltinAtomConstructor ordering; - private final BuiltinAtomConstructor less; - private final BuiltinAtomConstructor equal; - private final BuiltinAtomConstructor greater; + private final BuiltinType ordering; + private final BuiltinType less; + private final BuiltinType equal; + private final BuiltinType greater; public Ordering(Builtins builtins) { ordering = - new BuiltinAtomConstructor( + new BuiltinType( 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); + less = new BuiltinType(builtins, Less.class); + equal = new BuiltinType(builtins, Equal.class); + greater = new BuiltinType(builtins, Greater.class); } /** @@ -56,21 +56,21 @@ public Atom newGreater() { /** @return the Ordering constructor. */ public AtomConstructor ordering() { - return ordering.constructor(); + return ordering.getType(); } /** @return the Less constructor */ public AtomConstructor less() { - return less.constructor(); + return less.getType(); } /** @return the Equal constructor */ public AtomConstructor equal() { - return equal.constructor(); + return equal.getType(); } /** @return the Greater constructor */ public AtomConstructor greater() { - return greater.constructor(); + return greater.getType(); } } 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 3d868c19242f..47073e7ab9be 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 @@ -6,11 +6,11 @@ /** A container class for all System-related stdlib builtins. */ public class System { - private final BuiltinAtomConstructor systemProcessResult; + private final BuiltinType systemProcessResult; /** Create builders for all {@code System} atom constructors. */ public System(Builtins builtins) { - systemProcessResult = new BuiltinAtomConstructor(builtins, SystemProcessResult.class); + systemProcessResult = new BuiltinType(builtins, SystemProcessResult.class); } /** @return the atom constructor for {@code Process_Result}. */ diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java new file mode 100644 index 000000000000..f0df3eea8990 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -0,0 +1,22 @@ +package org.enso.interpreter.runtime.data; + +import com.oracle.truffle.api.interop.TruffleObject; +import org.enso.interpreter.runtime.scope.ModuleScope; + +public class Type implements TruffleObject { + private final String name; + private final ModuleScope definitionScope; + + public Type(String name, ModuleScope definitionScope) { + this.name = name; + this.definitionScope = definitionScope; + } + + public String getName() { + return name; + } + + public ModuleScope getDefinitionScope() { + return definitionScope; + } +} 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 88a5194da210..2a6f50609f80 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 @@ -8,17 +8,19 @@ import org.enso.interpreter.runtime.Module; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.error.RedefinedMethodException; import org.enso.interpreter.runtime.error.RedefinedConversionException; /** A representation of Enso's per-file top-level scope. */ public class ModuleScope implements TruffleObject { - private final AtomConstructor associatedType; + private final Type associatedType; private final Module module; private Map polyglotSymbols = new HashMap<>(); private Map constructors = new HashMap<>(); - private Map> methods = new HashMap<>(); - private Map> conversions = new HashMap<>(); + private Map types = new HashMap<>(); + private Map> methods = new HashMap<>(); + private Map> conversions = new HashMap<>(); private Set imports = new HashSet<>(); private Set exports = new HashSet<>(); @@ -29,7 +31,7 @@ public class ModuleScope implements TruffleObject { */ public ModuleScope(Module module) { this.module = module; - this.associatedType = new AtomConstructor(module.getName().item(), this).initializeFields(); + this.associatedType = new Type(module.getName().item(), this); } /** @@ -41,17 +43,23 @@ public void registerConstructor(AtomConstructor constructor) { constructors.put(constructor.getName(), constructor); } - /** @return the associated type of this module. */ - public AtomConstructor getAssociatedType() { + /** + * @return the associated type of this module. + */ + public Type getAssociatedType() { return associatedType; } - /** @return the module associated with this scope. */ + /** + * @return the module associated with this scope. + */ public Module getModule() { return module; } - /** @return the set of modules imported by this module. */ + /** + * @return the set of modules imported by this module. + */ public Set getImports() { return imports; } @@ -63,9 +71,9 @@ public Set getImports() { * @return the atom constructor associated with {@code name}, or {@link Optional#empty()} */ public Optional getLocalConstructor(String name) { - if (associatedType.getName().equals(name)) { - return Optional.of(associatedType); - } + // if (associatedType.getName().equals(name)) { + // return Optional.of(associatedType); + // } return Optional.ofNullable(this.constructors.get(name)); } @@ -88,15 +96,15 @@ public Optional getConstructor(String name) { /** * Returns a map of methods defined in this module for a given constructor. * - * @param cons the constructor for which method map is requested + * @param type the type for which method map is requested * @return a map containing all the defined methods by name */ - private Map ensureMethodMapFor(AtomConstructor cons) { - return methods.computeIfAbsent(cons, k -> new HashMap<>()); + private Map ensureMethodMapFor(Type type) { + return methods.computeIfAbsent(type, k -> new HashMap<>()); } - private Map getMethodMapFor(AtomConstructor cons) { - Map result = methods.get(cons); + private Map getMethodMapFor(Type type) { + Map result = methods.get(type); if (result == null) { return new HashMap<>(); } @@ -106,18 +114,18 @@ private Map getMethodMapFor(AtomConstructor cons) { /** * Registers a method defined for a given type. * - * @param atom type the method was defined for + * @param type the type the method was defined for * @param method method name * @param function the {@link Function} associated with this definition */ - public void registerMethod(AtomConstructor atom, String method, Function function) { + public void registerMethod(Type type, String method, Function function) { method = method.toLowerCase(); - Map methodMap = ensureMethodMapFor(atom); + Map methodMap = ensureMethodMapFor(type); if (methodMap.containsKey(method)) { // Builtin types will have double definition because of // BuiltinMethod and that's OK - throw new RedefinedMethodException(atom.getName(), method); + throw new RedefinedMethodException(type.getName(), method); } else { methodMap.put(method, function); } @@ -126,15 +134,15 @@ public void registerMethod(AtomConstructor atom, String method, Function functio /** * Returns a list of the conversion methods defined in this module for a given constructor. * - * @param cons the constructor for which method map is requested + * @param type the type for which method map is requested * @return a list containing all the defined conversions in definition order */ - private Map ensureConversionsFor(AtomConstructor cons) { - return conversions.computeIfAbsent(cons, k -> new HashMap<>()); + private Map ensureConversionsFor(Type type) { + return conversions.computeIfAbsent(type, k -> new HashMap<>()); } - private Map getConversionsFor(AtomConstructor cons) { - Map result = conversions.get(cons); + private Map getConversionsFor(Type type) { + var result = conversions.get(type); if (result == null) { return new HashMap<>(); } @@ -148,9 +156,8 @@ private Map getConversionsFor(AtomConstructor cons) { * @param fromType type the conversion was defined from * @param function the {@link Function} associated with this definition */ - public void registerConversionMethod( - AtomConstructor toType, AtomConstructor fromType, Function function) { - Map sourceMap = ensureConversionsFor(toType); + public void registerConversionMethod(Type toType, Type fromType, Function function) { + var sourceMap = ensureConversionsFor(toType); if (sourceMap.containsKey(fromType)) { throw new RedefinedConversionException(toType.getName(), fromType.getName()); } else { @@ -185,66 +192,66 @@ public Optional lookupPolyglotSymbol(String name) { * site (i.e. non-overloads), then looks for methods defined in this scope and finally tries to * resolve the method in all dependencies of this module. * - * @param atom type to lookup the method for. + * @param type type to lookup the method for. * @param name the method name. * @return the matching method definition or null if not found. */ @CompilerDirectives.TruffleBoundary - public Function lookupMethodDefinition(AtomConstructor atom, String name) { + public Function lookupMethodDefinition(Type type, String name) { String lowerName = name.toLowerCase(); - Function definedWithAtom = atom.getDefinitionScope().getMethodMapFor(atom).get(lowerName); + Function definedWithAtom = type.getDefinitionScope().getMethodMapFor(type).get(lowerName); if (definedWithAtom != null) { return definedWithAtom; } - Function definedHere = getMethodMapFor(atom).get(lowerName); + Function definedHere = getMethodMapFor(type).get(lowerName); if (definedHere != null) { return definedHere; } return imports.stream() - .map(scope -> scope.getExportedMethod(atom, name)) + .map(scope -> scope.getExportedMethod(type, name)) .filter(Objects::nonNull) .findFirst() .orElse(null); } @CompilerDirectives.TruffleBoundary - public Function lookupConversionDefinition(AtomConstructor atom, AtomConstructor target) { - Function definedWithAtom = atom.getDefinitionScope().getConversionsFor(target).get(atom); + public Function lookupConversionDefinition(Type type, Type target) { + Function definedWithAtom = type.getDefinitionScope().getConversionsFor(target).get(type); if (definedWithAtom != null) { return definedWithAtom; } - Function definedHere = getConversionsFor(target).get(atom); + Function definedHere = getConversionsFor(target).get(type); if (definedHere != null) { return definedHere; } return imports.stream() - .map(scope -> scope.getExportedConversion(atom, target)) + .map(scope -> scope.getExportedConversion(type, target)) .filter(Objects::nonNull) .findFirst() .orElse(null); } - private Function getExportedMethod(AtomConstructor atom, String name) { - Function here = getMethodMapFor(atom).get(name); + private Function getExportedMethod(Type type, String name) { + Function here = getMethodMapFor(type).get(name); if (here != null) { return here; } return exports.stream() - .map(scope -> scope.getMethodMapFor(atom).get(name)) + .map(scope -> scope.getMethodMapFor(type).get(name)) .filter(Objects::nonNull) .findFirst() .orElse(null); } - private Function getExportedConversion(AtomConstructor atom, AtomConstructor target) { - Function here = getConversionsFor(target).get(atom); + private Function getExportedConversion(Type type, Type target) { + Function here = getConversionsFor(target).get(type); if (here != null) { return here; } return exports.stream() - .map(scope -> scope.getConversionsFor(target).get(atom)) + .map(scope -> scope.getConversionsFor(target).get(type)) .filter(Objects::nonNull) .findFirst() .orElse(null); @@ -272,17 +279,27 @@ public Map getConstructors() { return constructors; } - /** @return the raw method map held by this module */ - public Map> getMethods() { + public Map getTypes() { + return types; + } + + /** + * @return the raw method map held by this module + */ + public Map> getMethods() { return methods; } - /** @return the raw conversions map held by this module */ - public Map> getConversions() { + /** + * @return the raw conversions map held by this module + */ + public Map> getConversions() { return conversions; } - /** @return the polyglot symbols imported into this scope. */ + /** + * @return the polyglot symbols imported into this scope. + */ public Map getPolyglotSymbols() { return polyglotSymbols; } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala index 7dc7181469c0..2b30d194951d 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala @@ -146,23 +146,24 @@ object AstToIr { .head Error.Syntax(ast, Error.Syntax.SuspendedArgInAtom) } else { - Module.Scope.Definition.Atom( + Module.Scope.Definition.SugaredType( buildName(consName), newArgs, + List(), getIdentifiedLocation(inputAst) ) } case AstView.TypeDef(typeName, args, body) => val translatedBody = translateTypeBody(body) val containsAtomDefOrInclude = translatedBody.exists { - case _: IR.Module.Scope.Definition.Atom => true + case _: IR.Module.Scope.Definition.Data => true case _: IR.Name.Literal => true case _ => false } val hasArgs = args.nonEmpty if (containsAtomDefOrInclude && !hasArgs) { - Module.Scope.Definition.Type( + Module.Scope.Definition.SugaredType( buildName(typeName), args.map(translateArgumentDefinition(_)), translatedBody, @@ -317,10 +318,18 @@ object AstToIr { .getOrElse(maybeParensedInput) inputAst match { + case AST.Ident.Cons.any(cons) => + IR.Module.Scope.Definition + .Data(buildName(cons), List(), getIdentifiedLocation(inputAst)) + case AstView.SpacedList(AST.Ident.Cons.any(cons) :: args) => + IR.Module.Scope.Definition + .Data( + buildName(cons), + args.map(translateArgumentDefinition(_)), + getIdentifiedLocation(inputAst) + ) case AST.Ident.Annotation.any(ann) => IR.Name.Annotation(ann.name, getIdentifiedLocation(ann)) - case AST.Ident.Cons.any(include) => translateIdent(include) - case atom @ AstView.Atom(_, _) => translateModuleSymbol(atom) case AstView.FunctionSugar( AST.Ident.Var("foreign"), header, diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala index 601c53d82ea6..8df4aa4228fc 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala @@ -479,6 +479,8 @@ object AstView { } } + + /** A union type for application matchers. */ sealed trait MethodOrExpr 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 861e99eec45e..fdc8d1d1690e 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 @@ -156,8 +156,9 @@ class IrToTruffle( moduleScope.addExport(exp.module.unsafeAsModule().getScope) } val imports = module.imports - val atomDefs = module.bindings.collect { - case atom: IR.Module.Scope.Definition.Atom => atom + val atomDefs = module.bindings.flatMap { + case tp: IR.Module.Scope.Definition.Type => tp.members + case _ => List() } val methodDefs = module.bindings.collect { case method: IR.Module.Scope.Definition.Method.Explicit => method @@ -259,16 +260,14 @@ class IrToTruffle( .getMetadata(MethodDefinitions) .map { res => res.target match { - case _: BindingsMap.ResolvedType => - throw new CompilerError("todo") + case BindingsMap.ResolvedType(module, tp) => + module.unsafeAsModule().getScope.getTypes.get(tp.name) case BindingsMap.ResolvedModule(module) => module.unsafeAsModule().getScope.getAssociatedType - case BindingsMap.ResolvedConstructor(definitionModule, cons) => - definitionModule - .unsafeAsModule() - .getScope - .getConstructors - .get(cons.name) + case BindingsMap.ResolvedConstructor(_, _) => + throw new CompilerError( + "Impossible, should be caught by MethodDefinitions pass" + ) case BindingsMap.ResolvedPolyglotSymbol(_, _) => throw new CompilerError( "Impossible polyglot symbol, should be caught by MethodDefinitions pass." @@ -1079,7 +1078,7 @@ class IrToTruffle( .get(cons.name) ) case BindingsMap.ResolvedModule(module) => - ConstructorNode.build( + ConstantObjectNode.build( module.unsafeAsModule().getScope.getAssociatedType ) case BindingsMap.ResolvedPolyglotSymbol(module, symbol) => @@ -1195,7 +1194,7 @@ class IrToTruffle( context.getBuiltins .error() .makeCompileError(Text.create(err.message)) - case err: Error.Redefined.Atom => + case err: Error.Redefined.Type => context.getBuiltins .error() .makeCompileError(Text.create(err.message)) 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 21fe760c2df5..9082039b6f7f 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 @@ -42,7 +42,7 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { val ir = scope.queue.dequeue() val doc = ir.getMetadata(DocumentationComments).map(_.documentation) ir match { - case IR.Module.Scope.Definition.Atom(name, arguments, _, _, _) => + case IR.Module.Scope.Definition.Data(name, arguments, _, _, _) => val suggestions = buildAtom(module, name.name, arguments, doc) go(tree ++= suggestions.map(Tree.Node(_, Vector())), scope) 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 46105d7d280d..4f76b87fe491 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 @@ -953,9 +953,10 @@ object IR { * @param passData the pass metadata associated with this node * @param diagnostics compiler diagnostics for this node */ - sealed case class UnionType( + sealed case class Type( name: IR.Name, - members: List[IR.Name], + params: List[IR.DefinitionArgument], + members: List[IR.Module.Scope.Definition.Data], override val location: Option[IdentifiedLocation], override val passData: MetadataStorage = MetadataStorage(), override val diagnostics: DiagnosticStorage = DiagnosticStorage() @@ -964,14 +965,16 @@ object IR { override protected var id: Identifier = randomId def copy( - name: IR.Name = name, - members: List[IR.Name] = members, - location: Option[IdentifiedLocation] = location, - passData: MetadataStorage = passData, - diagnostics: DiagnosticStorage = diagnostics, - id: Identifier = id - ): UnionType = { - val res = UnionType(name, members, location, passData, diagnostics) + name: IR.Name = name, + params: List[IR.DefinitionArgument] = params, + members: List[IR.Module.Scope.Definition.Data] = members, + location: Option[IdentifiedLocation] = location, + passData: MetadataStorage = passData, + diagnostics: DiagnosticStorage = diagnostics, + id: Identifier = id + ): Type = { + val res = + Type(name, params, members, location, passData, diagnostics) res.id = id res } @@ -982,7 +985,7 @@ object IR { keepMetadata: Boolean = true, keepDiagnostics: Boolean = true, keepIdentifiers: Boolean = false - ): UnionType = + ): Type = copy( name = name.duplicate( keepLocations, @@ -1009,18 +1012,22 @@ object IR { /** @inheritdoc */ override def setLocation( location: Option[IdentifiedLocation] - ): UnionType = + ): Type = copy(location = location) /** @inheritdoc */ - override def mapExpressions(fn: Expression => Expression): UnionType = - this + override def mapExpressions(fn: Expression => Expression): Type = + copy( + params = params.map(_.mapExpressions(fn)), + members = members.map(_.mapExpressions(fn)) + ) /** @inheritdoc */ override def toString: String = s""" |IR.Module.Scope.Definition.UnionType( |name = $name, + |params = $params, |members = $members, |location = $location, |passData = ${this.showPassData}, @@ -1030,7 +1037,7 @@ object IR { |""".toSingleLine /** @inheritdoc */ - override def children: List[IR] = name :: members + override def children: List[IR] = name :: (params :++ members) /** @inheritdoc */ override def showCode(indent: Int): String = { @@ -1048,13 +1055,13 @@ object IR { * @param passData the pass metadata associated with this node * @param diagnostics compiler diagnostics for this node */ - sealed case class Atom( + sealed case class Data( name: IR.Name, arguments: List[DefinitionArgument], override val location: Option[IdentifiedLocation], override val passData: MetadataStorage = MetadataStorage(), override val diagnostics: DiagnosticStorage = DiagnosticStorage() - ) extends Definition + ) extends IR with IRKind.Primitive { override protected var id: Identifier = randomId @@ -1075,8 +1082,8 @@ object IR { passData: MetadataStorage = passData, diagnostics: DiagnosticStorage = diagnostics, id: Identifier = id - ): Atom = { - val res = Atom(name, arguments, location, passData, diagnostics) + ): Data = { + val res = Data(name, arguments, location, passData, diagnostics) res.id = id res } @@ -1087,7 +1094,7 @@ object IR { keepMetadata: Boolean = true, keepDiagnostics: Boolean = true, keepIdentifiers: Boolean = false - ): Atom = + ): Data = copy( name = name.duplicate( keepLocations, @@ -1112,11 +1119,11 @@ object IR { ) /** @inheritdoc */ - override def setLocation(location: Option[IdentifiedLocation]): Atom = + override def setLocation(location: Option[IdentifiedLocation]): Data = copy(location = location) /** @inheritdoc */ - override def mapExpressions(fn: Expression => Expression): Atom = { + override def mapExpressions(fn: Expression => Expression): Data = { copy( name = name.mapExpressions(fn), arguments = arguments.map(_.mapExpressions(fn)) @@ -1157,7 +1164,7 @@ object IR { * @param passData the pass metadata associated with this node * @param diagnostics compiler diagnostics for this node */ - sealed case class Type( + sealed case class SugaredType( name: IR.Name, arguments: List[DefinitionArgument], body: List[IR], @@ -1187,8 +1194,8 @@ object IR { passData: MetadataStorage = passData, diagnostics: DiagnosticStorage = diagnostics, id: Identifier = id - ): Type = { - val res = Type( + ): SugaredType = { + val res = SugaredType( name, arguments, body, @@ -1206,7 +1213,7 @@ object IR { keepMetadata: Boolean = true, keepDiagnostics: Boolean = true, keepIdentifiers: Boolean = false - ): Type = + ): SugaredType = copy( name = name.duplicate( keepLocations, @@ -1239,13 +1246,15 @@ object IR { ) /** @inheritdoc */ - override def mapExpressions(fn: Expression => Expression): Type = + override def mapExpressions( + fn: Expression => Expression + ): SugaredType = copy(body = body.map(_.mapExpressions(fn))) /** @inheritdoc */ override def setLocation( location: Option[IdentifiedLocation] - ): Type = copy(location = location) + ): SugaredType = copy(location = location) /** @inheritdoc */ override def toString: String = @@ -4463,7 +4472,7 @@ object IR { object DefinitionArgument { /** The representation of an argument from a [[Function]] or - * [[IR.Module.Scope.Definition.Atom]] definition site. + * [[IR.Module.Scope.Definition.Data]] definition site. * * To create an ignored argument, the argument name should be an * [[IR.Name.Blank]]. @@ -6963,7 +6972,7 @@ object IR { case class UnexpectedType(context: String) extends Reason { override def explain(originalName: Name): String = s"The name ${originalName.name} resolved to a type, " + - s"but types are not allowed in $context." + s"but types are not allowed in $context." } /** An error coming from usage of an undefined variable name. @@ -7875,14 +7884,14 @@ object IR { /** An error representing the redefinition of an atom in a given module. * - * @param atomName the name of the atom being redefined + * @param typeName the name of the atom being redefined * @param location the location in the source to which this error * corresponds * @param passData the pass metadata for the error * @param diagnostics any diagnostics associated with this error. */ - sealed case class Atom( - atomName: IR.Name, + sealed case class Type( + typeName: IR.Name, override val location: Option[IdentifiedLocation], override val passData: MetadataStorage = MetadataStorage(), override val diagnostics: DiagnosticStorage = DiagnosticStorage() @@ -7892,7 +7901,7 @@ object IR { with IRKind.Primitive { override protected var id: Identifier = randomId - /** Creates a copy of `this`. + /** Creates a copy of `this`. * * @param atomName the name of the atom the method was being redefined * on @@ -7904,14 +7913,14 @@ object IR { * @return a copy of `this`, updated with the specified values */ def copy( - atomName: IR.Name = atomName, + atomName: IR.Name = typeName, location: Option[IdentifiedLocation] = location, passData: MetadataStorage = passData, diagnostics: DiagnosticStorage = diagnostics, id: Identifier = id - ): Atom = { + ): Type = { val res = - Atom(atomName, location, passData, diagnostics) + Type(atomName, location, passData, diagnostics) res.id = id res } @@ -7922,9 +7931,9 @@ object IR { keepMetadata: Boolean = true, keepDiagnostics: Boolean = true, keepIdentifiers: Boolean = false - ): Atom = + ): Type = copy( - atomName = atomName.duplicate( + atomName = typeName.duplicate( keepLocations, keepMetadata, keepDiagnostics, @@ -7939,24 +7948,24 @@ object IR { ) /** @inheritdoc */ - override def setLocation(location: Option[IdentifiedLocation]): Atom = + override def setLocation(location: Option[IdentifiedLocation]): Type = copy(location = location) /** @inheritdoc */ override def message: String = - s"Redefining atoms is not supported: ${atomName.name} is " + + s"Redefining atoms is not supported: ${typeName.name} is " + s"defined multiple times in this module." - override def diagnosticKeys(): Array[Any] = Array(atomName.name) + override def diagnosticKeys(): Array[Any] = Array(typeName.name) /** @inheritdoc */ - override def mapExpressions(fn: Expression => Expression): Atom = this + override def mapExpressions(fn: Expression => Expression): Type = this /** @inheritdoc */ override def toString: String = s""" |IR.Error.Redefined.Atom( - |atomName = $atomName, + |atomName = $typeName, |location = $location, |passData = ${this.showPassData}, |diagnostics = $diagnostics, @@ -7965,11 +7974,11 @@ object IR { |""".stripMargin /** @inheritdoc */ - override def children: List[IR] = List(atomName) + override def children: List[IR] = List(typeName) /** @inheritdoc */ override def showCode(indent: Int): String = - s"(Redefined (Atom $atomName))" + s"(Redefined (Atom $typeName))" } /** An error representing the redefinition of a binding in a given scope. diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala index 09075a9c3a5d..3d050f182318 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala @@ -227,12 +227,24 @@ case object AliasAnalysis extends IRPass { throw new CompilerError( "Method definition sugar should not occur during alias analysis." ) - case a @ IR.Module.Scope.Definition.Atom(_, args, _, _, _) => - a.copy( - arguments = - analyseArgumentDefs(args, topLevelGraph, topLevelGraph.rootScope) + case t: IR.Module.Scope.Definition.Type => + t.copy( + params = analyseArgumentDefs( + t.params, + topLevelGraph, + topLevelGraph.rootScope + ), + members = t.members.map(d => + d.copy(arguments = + analyseArgumentDefs( + d.arguments, + topLevelGraph, + topLevelGraph.rootScope + ) + ).updateMetadata(this -->> Info.Scope.Root(topLevelGraph)) + ) ).updateMetadata(this -->> Info.Scope.Root(topLevelGraph)) - case _: IR.Module.Scope.Definition.Type => + case _: IR.Module.Scope.Definition.SugaredType => throw new CompilerError( "Complex type definitions should not be present during " + "alias analysis." @@ -251,8 +263,7 @@ case object AliasAnalysis extends IRPass { "Annotations should already be associated by the point of alias " + "analysis." ) - case err: IR.Error => err - case ut: IR.Module.Scope.Definition.UnionType => ut + case err: IR.Error => err } } 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 1a995844fc48..1a8f6bc59503 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 @@ -51,22 +51,25 @@ case object BindingAnalysis extends IRPass { moduleContext: ModuleContext ): IR.Module = { val definedSumTypes = ir.bindings.collect { - case sumType: IR.Module.Scope.Definition.UnionType => - BindingsMap.Type(sumType.name.name, sumType.members.map(_.name)) + case sumType: IR.Module.Scope.Definition.Type => + BindingsMap.Type(sumType.name.name, sumType.members.map(_.name.name)) } - val definedConstructors = ir.bindings.collect { - case cons: IR.Module.Scope.Definition.Atom => + val definedConstructors = ir.bindings.flatMap { + case tp: IR.Module.Scope.Definition.Type => // FIXME: move to a different pass - val isBuiltinType = cons + val isBuiltinType = tp .getMetadata(ModuleAnnotations) .exists(_.annotations.exists(_.name == "@Builtin_Type")) - BindingsMap.Cons( - cons.name.name, - cons.arguments.length, - cons.arguments.forall(_.defaultValue.isDefined), - isBuiltinType - ) + tp.members.map { cons => + BindingsMap.Cons( + cons.name.name, + cons.arguments.length, + cons.arguments.forall(_.defaultValue.isDefined), + isBuiltinType + ) + } + case _ => List() } val importedPolyglot = ir.imports.collect { case poly: IR.Module.Scope.Import.Polyglot => diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/CachePreferenceAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/CachePreferenceAnalysis.scala index 2e4179edae2d..98f170dc1029 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/CachePreferenceAnalysis.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/CachePreferenceAnalysis.scala @@ -87,13 +87,7 @@ case object CachePreferenceAnalysis extends IRPass { weights: WeightInfo ): IR.Module.Scope.Definition = binding match { - case atom @ IR.Module.Scope.Definition.Atom(_, arguments, _, _, _) => - atom - .copy(arguments = - arguments.map(analyseDefinitionArgument(_, weights)) - ) - .updateMetadata(this -->> weights) - case _: IR.Module.Scope.Definition.UnionType => binding + case _: IR.Module.Scope.Definition.Type => binding case method: Method.Conversion => method .copy(body = analyseExpression(method.body, weights)) @@ -108,7 +102,7 @@ case object CachePreferenceAnalysis extends IRPass { "Sugared method definitions should not occur during cache " + "preference analysis." ) - case _: IR.Module.Scope.Definition.Type => + case _: IR.Module.Scope.Definition.SugaredType => throw new CompilerError( "Complex type definitions should not be present during cache " + "preference analysis." diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala index eb69b5cafa86..66f3cee320bc 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala @@ -119,19 +119,6 @@ case object DataflowAnalysis extends IRPass { info: DependencyInfo ): IR.Module.Scope.Definition = { binding match { - case atom @ IR.Module.Scope.Definition.Atom(_, arguments, _, _, _) => - arguments.foreach(arg => { - val argDep = asStatic(arg) - val atomDep = asStatic(atom) - info.dependents.updateAt(argDep, Set(atomDep)) - info.dependencies.updateAt(atomDep, Set(argDep)) - }) - - atom - .copy( - arguments = arguments.map(analyseDefinitionArgument(_, info)) - ) - .updateMetadata(this -->> info) case m: Method.Conversion => val bodyDep = asStatic(m.body) val methodDep = asStatic(m) @@ -154,13 +141,13 @@ case object DataflowAnalysis extends IRPass { method .copy(body = analyseExpression(body, info)) .updateMetadata(this -->> info) - case _: IR.Module.Scope.Definition.UnionType => binding + case _: IR.Module.Scope.Definition.Type => binding case _: IR.Module.Scope.Definition.Method.Binding => throw new CompilerError( "Sugared method definitions should not occur during dataflow " + "analysis." ) - case _: IR.Module.Scope.Definition.Type => + case _: IR.Module.Scope.Definition.SugaredType => throw new CompilerError( "Complex type definitions should not be present during " + "dataflow analysis." diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/TailCall.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/TailCall.scala index de605e270fa5..39fb9dcb6c58 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/TailCall.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/TailCall.scala @@ -109,14 +109,8 @@ case object TailCall extends IRPass { "Sugared method definitions should not occur during tail call " + "analysis." ) - case atom @ IR.Module.Scope.Definition.Atom(_, args, _, _, _) => - atom - .copy( - arguments = args.map(analyseDefArgument) - ) - .updateMetadata(this -->> TailPosition.Tail) - case _: IR.Module.Scope.Definition.UnionType => definition - case _: IR.Module.Scope.Definition.Type => + case _: IR.Module.Scope.Definition.Type => definition + case _: IR.Module.Scope.Definition.SugaredType => throw new CompilerError( "Complex type definitions should not be present during " + "tail call analysis." 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 b18e3c095819..01ed3451aedd 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 @@ -75,8 +75,8 @@ case object ComplexType extends IRPass { ): IR.Module = ir.copy( bindings = ir.bindings.flatMap { - case typ: Definition.Type => desugarComplexType(typ) - case b => List(b) + case typ: Definition.SugaredType => desugarComplexType(typ) + case b => List(b) } ) @@ -107,11 +107,12 @@ case object ComplexType extends IRPass { * @return the top-level definitions corresponding to the desugaring of `typ` */ def desugarComplexType( - typ: IR.Module.Scope.Definition.Type + typ: IR.Module.Scope.Definition.SugaredType ): List[IR.Module.Scope.Definition] = { val annotations = typ.getMetadata(ModuleAnnotations) val atomDefs = typ.body - .collect { case d: IR.Module.Scope.Definition.Atom => d } + .collect { case d: IR.Module.Scope.Definition.Data => d } + // TODO[MK] this is probably removable .map(atom => annotations .map(ann => { @@ -125,12 +126,9 @@ case object ComplexType extends IRPass { }) .getOrElse(atom) ) - val atomIncludes = typ.body.collect { case n: IR.Name => n } - val namesToDefineMethodsOn = atomIncludes ++ atomDefs.map(_.name) val remainingEntities = typ.body.filterNot { - case _: IR.Module.Scope.Definition.Atom => true - case _: IR.Name => true + case _: IR.Module.Scope.Definition.Data => true case _ => false } @@ -169,7 +167,7 @@ case object ComplexType extends IRPass { val unusedList: List[Definition] = unusedSig.toList unusedList ::: genMethodDef( defn, - namesToDefineMethodsOn, + typ.name, sig ) } @@ -189,11 +187,14 @@ case object ComplexType extends IRPass { } val allEntities = entityResults ::: lastSignature.toList - val includedNames = atomDefs.map(_.name) - val sumType = IR.Module.Scope.Definition - .UnionType(typ.name, includedNames, typ.location) + val sumType = IR.Module.Scope.Definition.Type( + typ.name, + typ.arguments, + atomDefs, + typ.location + ) - sumType :: atomDefs ::: allEntities + sumType :: allEntities } /** Generates a method definition from a definition in complex type def body. @@ -207,7 +208,7 @@ case object ComplexType extends IRPass { */ def genMethodDef( ir: IR, - names: List[IR.Name], + typeName: IR.Name, signature: Option[IR.Type.Ascription] ): List[IR.Module.Scope.Definition] = { ir match { @@ -218,17 +219,15 @@ case object ComplexType extends IRPass { case _ => expr } - names.flatMap( - genForName( - _, - name, - List(), - realExpr, - location, - passData, - diagnostics, - signature - ) + genForName( + typeName, + name, + List(), + realExpr, + location, + passData, + diagnostics, + signature ) case IR.Function.Binding( name, @@ -239,17 +238,15 @@ case object ComplexType extends IRPass { passData, diagnostics ) => - names.flatMap( - genForName( - _, - name, - args, - body, - location, - passData, - diagnostics, - signature - ) + genForName( + typeName, + name, + args, + body, + location, + passData, + diagnostics, + signature ) case _ => throw new CompilerError( diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/FunctionBinding.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/FunctionBinding.scala index a63b8ec1f527..2d2a853b71e2 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/FunctionBinding.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/desugar/FunctionBinding.scala @@ -128,9 +128,7 @@ case object FunctionBinding extends IRPass { definition: IR.Module.Scope.Definition ): IR.Module.Scope.Definition = { definition match { - case a @ Definition.Atom(_, arguments, _, _, _) => - a.copy(arguments = arguments.map(_.mapExpressions(desugarExpression))) - case _: Definition.UnionType => definition + case _: Definition.Type => definition.mapExpressions(desugarExpression) case _: Method.Explicit => throw new CompilerError( "Explicit method definitions should not exist during function " + @@ -227,7 +225,7 @@ case object FunctionBinding extends IRPass { } } } - case _: IR.Module.Scope.Definition.Type => + case _: IR.Module.Scope.Definition.SugaredType => throw new CompilerError( "Complex type definitions should not be present during " + "function binding desugaring." diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/DocumentationComments.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/DocumentationComments.scala index e9943d05fb17..b53630a441ce 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/DocumentationComments.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/DocumentationComments.scala @@ -148,7 +148,7 @@ case object DocumentationComments extends IRPass { "Conversion methods should not yet be present in the compiler " + "pipeline." ) - case _: IR.Module.Scope.Definition.UnionType => + case _: IR.Module.Scope.Definition.Type => throw new CompilerError( "Union types should not yet be present in the compiler pipeline." ) @@ -156,12 +156,11 @@ case object DocumentationComments extends IRPass { method.copy(body = resolveExpression(method.body)) case method: IR.Module.Scope.Definition.Method.Explicit => method.copy(body = resolveExpression(method.body)) - case tpe: IR.Module.Scope.Definition.Type => + case tpe: IR.Module.Scope.Definition.SugaredType => tpe.copy(body = resolveList(tpe.body).map(resolveIr)) - case d: IR.Module.Scope.Definition.Atom => d - case doc: IR.Comment.Documentation => doc - case tySig: IR.Type.Ascription => tySig - case err: IR.Error => err + case doc: IR.Comment.Documentation => doc + case tySig: IR.Type.Ascription => tySig + case err: IR.Error => err case _: IR.Name.Annotation => throw new CompilerError( "Annotations should already be associated by the point of " + @@ -208,14 +207,15 @@ case object DocumentationComments extends IRPass { */ private def resolveIr(ir: IR): IR = ir match { - case module: IR.Module => resolveModule(module) - case expr: IR.Expression => resolveExpression(expr) - case df: IR.Module.Scope.Definition => resolveDefinition(df) - case imp: IR.Module.Scope.Import => imp - case exp: IR.Module.Scope.Export.Module => exp - case arg: IR.CallArgument => arg - case arg: IR.DefinitionArgument => arg - case pat: IR.Pattern => pat + case module: IR.Module => resolveModule(module) + case expr: IR.Expression => resolveExpression(expr) + case df: IR.Module.Scope.Definition => resolveDefinition(df) + case data: IR.Module.Scope.Definition.Data => data + case imp: IR.Module.Scope.Import => imp + case exp: IR.Module.Scope.Export.Module => exp + case arg: IR.CallArgument => arg + case arg: IR.DefinitionArgument => arg + case pat: IR.Pattern => pat } // === Metadata ============================================================= diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala index dcc83f766849..5b8a7a322162 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala @@ -119,6 +119,8 @@ case object MethodDefinitions extends IRPass { typePointer.updateMetadata( this -->> BindingsMap.Resolution(value) ) + case Right(value: BindingsMap.ResolvedType) => + typePointer.updateMetadata(this -->> BindingsMap.Resolution(value)) case Right(_: BindingsMap.ResolvedPolyglotSymbol) => IR.Error.Resolution( typePointer, @@ -133,8 +135,7 @@ case object MethodDefinitions extends IRPass { "a method definition target" ) ) - case Right(_: BindingsMap.ResolvedType) => - throw new CompilerError("todo") + } case tp: IR.Error.Resolution => tp case _ => diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/ModuleAnnotations.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/ModuleAnnotations.scala index 92083260090d..479aff80c1e0 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/ModuleAnnotations.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/ModuleAnnotations.scala @@ -48,7 +48,7 @@ case object ModuleAnnotations extends IRPass { lastAnnotations :+= ann None case comment: IR.Comment => Some(comment) - case typ: Definition.Type => + case typ: Definition.SugaredType => val res = Some( resolveComplexType(typ).updateMetadata( this -->> Annotations(lastAnnotations) @@ -72,7 +72,7 @@ case object ModuleAnnotations extends IRPass { * @param typ the type in which to resolve annotations * @return `typ` with all top-level annotations resolved */ - def resolveComplexType(typ: Definition.Type): Definition.Type = { + def resolveComplexType(typ: Definition.SugaredType): Definition.SugaredType = { var lastAnnotations: Seq[IR.Name.Annotation] = Seq() val newBodyElems = typ.body.flatMap { case ann: Name.Annotation => diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala index c4b323de16ea..4cc60082e71c 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala @@ -47,19 +47,19 @@ case object OverloadsResolution extends IRPass { ir: IR.Module, @unused moduleContext: ModuleContext ): IR.Module = { - var seenAtoms: Set[String] = Set() + var seenTypes: Set[String] = Set() var seenMethods: Map[String, Set[String]] = Map() - val atoms = ir.bindings.collect { - case atom: IR.Module.Scope.Definition.Atom => atom + val types = ir.bindings.collect { + case tp: IR.Module.Scope.Definition.Type => tp } - val newAtoms: List[IR.Module.Scope.Definition] = atoms.map(atom => { - if (seenAtoms.contains(atom.name.name)) { - IR.Error.Redefined.Atom(atom.name, atom.location) + val newTypes: List[IR.Module.Scope.Definition] = types.map(tp => { + if (seenTypes.contains(tp.name.name)) { + IR.Error.Redefined.Type(tp.name, tp.location) } else { - seenAtoms = seenAtoms + atom.name.name - atom + seenTypes = seenTypes + tp.name.name + tp } }) @@ -74,7 +74,7 @@ case object OverloadsResolution extends IRPass { IR.Error.Redefined .Method(method.typeName, method.methodName, method.location) } else { - atoms.find(_.name.name.equalsIgnoreCase(method.methodName.name)) match { + types.find(_.name.name.equalsIgnoreCase(method.methodName.name)) match { case Some(clashedAtom) if method.typeName.isInstanceOf[IR.Name.Here] => IR.Error.Redefined.MethodClashWithAtom( @@ -119,7 +119,7 @@ case object OverloadsResolution extends IRPass { } ir.copy( - bindings = newAtoms ::: newMethods ::: conversions ::: diagnostics + bindings = newTypes ::: newMethods ::: conversions ::: diagnostics ) } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala index fe0c2d19eb80..ef72c87a5a68 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/SuspendedArguments.scala @@ -174,11 +174,10 @@ case object SuspendedArguments extends IRPass { "Method bodies must be lambdas at this point." ) } - case _: Method.Binding => throw new CompilerError("") - case atom: Definition.Atom => atom - case _: Definition.UnionType => binding - case err: IR.Error => err - case _: Definition.Type => + case _: Method.Binding => throw new CompilerError("") + case _: Definition.Type => binding + case err: IR.Error => err + case _: Definition.SugaredType => throw new CompilerError( "Complex type definitions should not be present." ) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeSignatures.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeSignatures.scala index e757e0567678..6cbac253ebc9 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeSignatures.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeSignatures.scala @@ -135,11 +135,10 @@ case object TypeSignatures extends IRPass { lastSignature = None res - case atom: IR.Module.Scope.Definition.Atom => - Some(atom.mapExpressions(resolveExpression)) - case ut: IR.Module.Scope.Definition.UnionType => Some(ut) - case err: IR.Error => Some(err) - case _: IR.Module.Scope.Definition.Type => + case ut: IR.Module.Scope.Definition.Type => + Some(ut.mapExpressions(resolveExpression)) + case err: IR.Error => Some(err) + case _: IR.Module.Scope.Definition.SugaredType => throw new CompilerError( "Complex type definitions should not be present during type " + "signature resolution." diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala index 1b55831db82e..e3c027e09cf0 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala @@ -198,8 +198,8 @@ trait CompilerRunner { * * @return an atom with one argument `arg` with default value `ir` */ - def asAtomDefaultArg: IR.Module.Scope.Definition.Atom = { - IR.Module.Scope.Definition.Atom( + def asAtomDefaultArg: IR.Module.Scope.Definition.Data = { + IR.Module.Scope.Definition.Data( IR.Name.Literal("TestAtom", isReferent = true, isMethod = false, None), List( IR.DefinitionArgument @@ -216,18 +216,18 @@ trait CompilerRunner { ) } - /** Creates a module containing both an atom and a method that use the - * provided expression. - * - * The expression is used in the default for an atom argument, as in - * [[asAtomDefaultArg()]], and in the body of a method, as in - * [[asMethod()]]. - * - * @return a module containing an atom def and method def using `expr` - */ - def asModuleDefs: IR.Module = { - IR.Module(List(), List(), List(ir.asAtomDefaultArg, ir.asMethod), None) - } +// /** Creates a module containing both an atom and a method that use the +// * provided expression. +// * +// * The expression is used in the default for an atom argument, as in +// * [[asAtomDefaultArg()]], and in the body of a method, as in +// * [[asMethod()]]. +// * +// * @return a module containing an atom def and method def using `expr` +// */ +// def asModuleDefs: IR.Module = { +// IR.Module(List(), List(), List(ir.asAtomDefaultArg, ir.asMethod), None) +// } } /** Builds a module context with a mocked module for testing purposes. diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala index 60001193f873..5a0c814042a4 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala @@ -502,8 +502,8 @@ class AstToIrTest extends CompilerTest with Inside { |type My_Type |""".stripMargin.toIrModule - ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Atom] - val atom = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Atom] + ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Data] + val atom = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Data] atom.name.name shouldEqual "My_Type" } @@ -513,8 +513,8 @@ class AstToIrTest extends CompilerTest with Inside { |type My_Type a b c |""".stripMargin.toIrModule - ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Atom] - val atom = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Atom] + ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Data] + val atom = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Data] atom.name.name shouldEqual "My_Type" val args = atom.arguments args.length shouldEqual 3 @@ -529,8 +529,8 @@ class AstToIrTest extends CompilerTest with Inside { |type My_Type (a = 1) |""".stripMargin.toIrModule - ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Atom] - val atom = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Atom] + ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Data] + val atom = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Data] atom.name.name shouldEqual "My_Type" val args = atom.arguments args.length shouldEqual 1 @@ -558,8 +558,8 @@ class AstToIrTest extends CompilerTest with Inside { |type My_Type a:b (c : d = 1) |""".stripMargin.toIrModule - ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Atom] - val atom = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Atom] + ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Data] + val atom = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Data] atom.name.name shouldEqual "My_Type" val args = atom.arguments args.length shouldEqual 2 @@ -607,7 +607,7 @@ class AstToIrTest extends CompilerTest with Inside { |type MyAtom a b |""".stripMargin.toIrModule.bindings.head - ir shouldBe an[IR.Module.Scope.Definition.Atom] + ir shouldBe an[IR.Module.Scope.Definition.Data] } "translate complex type defs properly" in { @@ -624,15 +624,15 @@ class AstToIrTest extends CompilerTest with Inside { | fn a b = a + b |""".stripMargin.toIrModule.bindings.head - ir shouldBe an[IR.Module.Scope.Definition.Type] + ir shouldBe an[IR.Module.Scope.Definition.SugaredType] - val typeDef = ir.asInstanceOf[IR.Module.Scope.Definition.Type] + val typeDef = ir.asInstanceOf[IR.Module.Scope.Definition.SugaredType] typeDef.name.name shouldEqual "Maybe" typeDef.arguments.length shouldEqual 0 typeDef.body.head shouldBe an[IR.Name.Literal] - typeDef.body(1) shouldBe an[IR.Module.Scope.Definition.Atom] + typeDef.body(1) shouldBe an[IR.Module.Scope.Definition.Data] typeDef.body(2) shouldBe an[IR.Expression.Binding] typeDef.body(3) shouldBe an[IR.Function.Binding] } @@ -652,9 +652,9 @@ class AstToIrTest extends CompilerTest with Inside { | fn a b = a + b |""".stripMargin.toIrModule.bindings.head - ir shouldBe an[IR.Module.Scope.Definition.Type] + ir shouldBe an[IR.Module.Scope.Definition.SugaredType] - val typeDef = ir.asInstanceOf[IR.Module.Scope.Definition.Type] + val typeDef = ir.asInstanceOf[IR.Module.Scope.Definition.SugaredType] typeDef.body(2) shouldBe an[IR.Error.Syntax] typeDef @@ -704,7 +704,7 @@ class AstToIrTest extends CompilerTest with Inside { | + : My -> My | + that = My this.a+that.a |""".stripMargin.toIrModule.bindings.head - .asInstanceOf[IR.Module.Scope.Definition.Type] + .asInstanceOf[IR.Module.Scope.Definition.SugaredType] .body body(1) shouldBe an[IR.Type.Ascription] @@ -912,7 +912,7 @@ class AstToIrTest extends CompilerTest with Inside { | foo : this -> integer | foo = 0 |""".stripMargin.toIrModule.bindings.head - .asInstanceOf[IR.Module.Scope.Definition.Type] + .asInstanceOf[IR.Module.Scope.Definition.SugaredType] ir.body.length shouldEqual 3 ir.body(1) shouldBe an[IR.Type.Ascription] @@ -1002,7 +1002,7 @@ class AstToIrTest extends CompilerTest with Inside { |""".stripMargin.toIrModule ir.bindings.head shouldBe an[IR.Name.Annotation] - ir.bindings(1) shouldBe an[IR.Module.Scope.Definition.Atom] + ir.bindings(1) shouldBe an[IR.Module.Scope.Definition.Data] } "support annotations inside complex type bodies" in { @@ -1015,9 +1015,9 @@ class AstToIrTest extends CompilerTest with Inside { | add a = this + a |""".stripMargin.toIrModule - ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Type] + ir.bindings.head shouldBe an[IR.Module.Scope.Definition.SugaredType] val complexType = - ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Type] + ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.SugaredType] complexType.body.head shouldBe an[IR.Name.Annotation] complexType.body(2) shouldBe an[IR.Name.Annotation] @@ -1100,7 +1100,7 @@ class AstToIrTest extends CompilerTest with Inside { | (() |""".stripMargin.toIrModule inside(ir.bindings.head) { - case definition: IR.Module.Scope.Definition.Type => + case definition: IR.Module.Scope.Definition.SugaredType => inside(definition.body(2)) { case error: IR.Error.Syntax => error.reason shouldBe IR.Error.Syntax.UnexpectedDeclarationInType } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/AliasAnalysisTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/AliasAnalysisTest.scala index 8ec030757361..17d9cf7d6ee3 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/AliasAnalysisTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/AliasAnalysisTest.scala @@ -3,7 +3,7 @@ package org.enso.compiler.test.pass.analyse import org.enso.compiler.Passes import org.enso.compiler.context.{FreshNameSupply, InlineContext, ModuleContext} import org.enso.compiler.core.IR -import org.enso.compiler.core.IR.Module.Scope.Definition.{Atom, Method} +import org.enso.compiler.core.IR.Module.Scope.Definition.{Data, Method} import org.enso.compiler.core.IR.Pattern import org.enso.compiler.pass.PassConfiguration._ import org.enso.compiler.pass.analyse.AliasAnalysis @@ -401,7 +401,7 @@ class AliasAnalysisTest extends CompilerTest { """ |type MyAtom a b (c=a) |""".stripMargin.preprocessModule.analyse.bindings.head - .asInstanceOf[Atom] + .asInstanceOf[Data] val goodMeta = goodAtom.getMetadata(AliasAnalysis) val goodGraph = goodMeta.get.unsafeAs[AliasAnalysis.Info.Scope.Root].graph @@ -409,7 +409,7 @@ class AliasAnalysisTest extends CompilerTest { """ |type MyAtom a=b b |""".stripMargin.preprocessModule.analyse.bindings.head - .asInstanceOf[Atom] + .asInstanceOf[Data] val badMeta = badAtom.getMetadata(AliasAnalysis) val badGraph = badMeta.get.unsafeAs[AliasAnalysis.Info.Scope.Root].graph diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/GatherDiagnosticsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/GatherDiagnosticsTest.scala index 73ceb513ab6d..e8ac9f7fff72 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/GatherDiagnosticsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/GatherDiagnosticsTest.scala @@ -49,66 +49,66 @@ class GatherDiagnosticsTest extends CompilerTest { errors.toSet shouldEqual Set(error1) } - "work with module flow" in { - val error2 = IR.Error.Syntax( - AST.Invalid.Unexpected("whoa, that was not expected", List()), - IR.Error.Syntax.UnexpectedExpression - ) - - val error3 = IR.Error.Syntax( - AST.Invalid.Unexpected("whoa, that was also not expected", List()), - IR.Error.Syntax.AmbiguousExpression - ) - - val typeName = - IR.Name.Literal("Foo", isReferent = false, isMethod = false, None) - val method1Name = - IR.Name.Literal("bar", isReferent = false, isMethod = false, None) - val method2Name = - IR.Name.Literal("baz", isReferent = false, isMethod = false, None) - val fooName = - IR.Name.Literal("foo", isReferent = false, isMethod = false, None) - - val method1Ref = - IR.Name.MethodReference( - IR.Name.Qualified(List(typeName), None), - method1Name, - None - ) - val method2Ref = - IR.Name.MethodReference( - IR.Name.Qualified(List(typeName), None), - method2Name, - None - ) - - val module = IR.Module( - List(), - List(), - List( - IR.Module.Scope.Definition.Atom( - typeName, - List( - IR.DefinitionArgument - .Specified(fooName, None, Some(error2), suspended = false, None) - ), - None - ), - IR.Module.Scope.Definition.Method - .Explicit(method1Ref, lam, None), - IR.Module.Scope.Definition.Method - .Explicit(method2Ref, error3, None) - ), - None - ) - - val result = GatherDiagnostics.runModule(module, buildModuleContext()) - val errors = result - .unsafeGetMetadata(GatherDiagnostics, "Impossible") - .diagnostics - - errors.toSet shouldEqual Set(error1, error2, error3) - } +// "work with module flow" in { +// val error2 = IR.Error.Syntax( +// AST.Invalid.Unexpected("whoa, that was not expected", List()), +// IR.Error.Syntax.UnexpectedExpression +// ) +// +// val error3 = IR.Error.Syntax( +// AST.Invalid.Unexpected("whoa, that was also not expected", List()), +// IR.Error.Syntax.AmbiguousExpression +// ) +// +// val typeName = +// IR.Name.Literal("Foo", isReferent = false, isMethod = false, None) +// val method1Name = +// IR.Name.Literal("bar", isReferent = false, isMethod = false, None) +// val method2Name = +// IR.Name.Literal("baz", isReferent = false, isMethod = false, None) +// val fooName = +// IR.Name.Literal("foo", isReferent = false, isMethod = false, None) +// +// val method1Ref = +// IR.Name.MethodReference( +// IR.Name.Qualified(List(typeName), None), +// method1Name, +// None +// ) +// val method2Ref = +// IR.Name.MethodReference( +// IR.Name.Qualified(List(typeName), None), +// method2Name, +// None +// ) +// +// val module = IR.Module( +// List(), +// List(), +// List( +// IR.Module.Scope.Definition.Data( +// typeName, +// List( +// IR.DefinitionArgument +// .Specified(fooName, None, Some(error2), suspended = false, None) +// ), +// None +// ), +// IR.Module.Scope.Definition.Method +// .Explicit(method1Ref, lam, None), +// IR.Module.Scope.Definition.Method +// .Explicit(method2Ref, error3, None) +// ), +// None +// ) +// +// val result = GatherDiagnostics.runModule(module, buildModuleContext()) +// val errors = result +// .unsafeGetMetadata(GatherDiagnostics, "Impossible") +// .diagnostics +// +// errors.toSet shouldEqual Set(error1, error2, error3) +// } "avoid duplication" in { implicit val passManager: PassManager = diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala index a1ade19e6b0b..90e49aa3ce27 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala @@ -80,13 +80,13 @@ class ComplexTypeTest extends CompilerTest { | type Bar |""".stripMargin.preprocessModule.desugar - exactly(2, ir.bindings) shouldBe a[Definition.Atom] + exactly(2, ir.bindings) shouldBe a[Definition.Data] ir.bindings(0) - .asInstanceOf[Definition.UnionType] + .asInstanceOf[Definition.Type] .name .name shouldEqual "MyType" - ir.bindings(1).asInstanceOf[Definition.Atom].name.name shouldEqual "Foo" - ir.bindings(2).asInstanceOf[Definition.Atom].name.name shouldEqual "Bar" + ir.bindings(1).asInstanceOf[Definition.Data].name.name shouldEqual "Foo" + ir.bindings(2).asInstanceOf[Definition.Data].name.name shouldEqual "Bar" } "have annotations on the type desugared to annotations on the defined" in { @@ -97,9 +97,9 @@ class ComplexTypeTest extends CompilerTest { | type Bar |""".stripMargin.preprocessModule.desugar - exactly(1, ir.bindings) shouldBe a[Definition.Atom] + exactly(1, ir.bindings) shouldBe a[Definition.Data] ir.bindings(1) - .asInstanceOf[Definition.Atom] + .asInstanceOf[Definition.Data] .unsafeGetMetadata(ModuleAnnotations, "") .annotations .head @@ -229,8 +229,8 @@ class ComplexTypeTest extends CompilerTest { |""".stripMargin.preprocessModule.desugar "have their types translated untouched" in { - ir.bindings(1) shouldBe a[Definition.Atom] - val atom = ir.bindings(1).asInstanceOf[Definition.Atom] + ir.bindings(1) shouldBe a[Definition.Data] + val atom = ir.bindings(1).asInstanceOf[Definition.Data] atom.name.name shouldEqual "Baz" } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/OperatorToFunctionTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/OperatorToFunctionTest.scala index 88600209e17c..f2c80fdb06e4 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/OperatorToFunctionTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/OperatorToFunctionTest.scala @@ -60,12 +60,12 @@ class OperatorToFunctionTest extends CompilerTest { OperatorToFunction.runExpression(operator, ctx) shouldEqual operatorFn } - "be translated in module contexts" in { - val moduleInput = operator.asModuleDefs - val moduleOutput = operatorFn.asModuleDefs - - OperatorToFunction.runModule(moduleInput, modCtx) shouldEqual moduleOutput - } +// "be translated in module contexts" in { +// val moduleInput = operator.asModuleDefs +// val moduleOutput = operatorFn.asModuleDefs +// +// OperatorToFunction.runModule(moduleInput, modCtx) shouldEqual moduleOutput +// } "be translated recursively" in { val recursiveIR = diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala index ded12908b5e9..c074b7365b23 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala @@ -95,7 +95,7 @@ class DocumentationCommentsTest extends CompilerTest with Inside { "be associated with atoms and methods" in { ir.bindings.length shouldEqual 2 - ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Atom] + ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Data] ir.bindings(1) shouldBe an[IR.Module.Scope.Definition.Method] getDoc(ir.bindings.head) shouldEqual " This is doc for My_Atom" @@ -279,7 +279,7 @@ class DocumentationCommentsTest extends CompilerTest with Inside { | ## the return | 0 |""".stripMargin.preprocessModule.resolve - val tp = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Type] + val tp = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.SugaredType] getDoc(tp) shouldEqual " the type Foo" val t1 = tp.body.head getDoc(t1) shouldEqual " the constructor Bar" diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GenerateDocumentationTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GenerateDocumentationTest.scala index 386c6833f980..a0130182e85f 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GenerateDocumentationTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GenerateDocumentationTest.scala @@ -97,7 +97,7 @@ class GenerateDocumentationTest extends CompilerTest with Inside { |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 2 - ir.bindings(0) shouldBe an[IR.Module.Scope.Definition.Atom] + ir.bindings(0) shouldBe an[IR.Module.Scope.Definition.Data] ir.bindings(1) shouldBe an[IR.Module.Scope.Definition.Method] getDoc(ir.bindings(0)) shouldEqual DocParserWrapper.runOnPureDoc( @@ -191,7 +191,7 @@ class GenerateDocumentationTest extends CompilerTest with Inside { | ## the return | 0 |""".stripMargin.preprocessModule.resolve - val tp = ir.bindings(0).asInstanceOf[IR.Module.Scope.Definition.Type] + val tp = ir.bindings(0).asInstanceOf[IR.Module.Scope.Definition.SugaredType] getDoc(tp) shouldEqual DocParserWrapper.runOnPureDoc( " the type Foo" ) diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/ModuleAnnotationsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/ModuleAnnotationsTest.scala index fdeee0fc7b34..068c28fa029a 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/ModuleAnnotationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/ModuleAnnotationsTest.scala @@ -60,7 +60,7 @@ class ModuleAnnotationsTest extends CompilerTest { |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 1 - ir.bindings.head shouldBe a[Definition.Atom] + ir.bindings.head shouldBe a[Definition.Data] val anns = ir.bindings.head.unsafeGetMetadata(ModuleAnnotations, "").annotations anns.length shouldEqual 2 @@ -77,7 +77,7 @@ class ModuleAnnotationsTest extends CompilerTest { |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 1 - ir.bindings.head shouldBe a[Definition.Type] + ir.bindings.head shouldBe a[Definition.SugaredType] val anns = ir.bindings.head.unsafeGetMetadata(ModuleAnnotations, "").annotations anns.length shouldEqual 2 @@ -109,7 +109,7 @@ class ModuleAnnotationsTest extends CompilerTest { |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 2 - ir.bindings(1) shouldBe a[Definition.Atom] + ir.bindings(1) shouldBe a[Definition.Data] val anns = ir.bindings(1).unsafeGetMetadata(ModuleAnnotations, "").annotations anns.length shouldEqual 1 @@ -129,10 +129,10 @@ class ModuleAnnotationsTest extends CompilerTest { |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 1 - ir.bindings.head shouldBe a[Definition.Type] - val typ = ir.bindings.head.asInstanceOf[Definition.Type] + ir.bindings.head shouldBe a[Definition.SugaredType] + val typ = ir.bindings.head.asInstanceOf[Definition.SugaredType] typ.body.length shouldEqual 1 - typ.body.head shouldBe a[Definition.Atom] + typ.body.head shouldBe a[Definition.Data] typ.body.head .unsafeGetMetadata(ModuleAnnotations, "") .annotations @@ -151,8 +151,8 @@ class ModuleAnnotationsTest extends CompilerTest { |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 1 - ir.bindings.head shouldBe a[Definition.Type] - val typ = ir.bindings.head.asInstanceOf[Definition.Type] + ir.bindings.head shouldBe a[Definition.SugaredType] + val typ = ir.bindings.head.asInstanceOf[Definition.SugaredType] typ.body.length shouldEqual 2 typ.body(1) shouldBe an[IR.Function.Binding] typ @@ -174,11 +174,11 @@ class ModuleAnnotationsTest extends CompilerTest { |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 1 - ir.bindings.head shouldBe a[Definition.Type] - val typ = ir.bindings.head.asInstanceOf[Definition.Type] + ir.bindings.head shouldBe a[Definition.SugaredType] + val typ = ir.bindings.head.asInstanceOf[Definition.SugaredType] typ.body.length shouldEqual 2 typ.body.head shouldBe an[IR.Comment] - typ.body(1) shouldBe a[Definition.Atom] + typ.body(1) shouldBe a[Definition.Data] typ .body(1) .unsafeGetMetadata(ModuleAnnotations, "") diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/OverloadsResolutionTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/OverloadsResolutionTest.scala index efbc15405acc..844744f03296 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/OverloadsResolutionTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/OverloadsResolutionTest.scala @@ -121,19 +121,19 @@ class OverloadsResolutionTest extends CompilerTest { |""".stripMargin.preprocessModule.resolve "detect overloads within a given module" in { - exactly(2, ir.bindings) shouldBe an[IR.Error.Redefined.Atom] + exactly(2, ir.bindings) shouldBe an[IR.Error.Redefined.Type] } "replace all overloads by an error node" in { - ir.bindings(1) shouldBe an[IR.Error.Redefined.Atom] + ir.bindings(1) shouldBe an[IR.Error.Redefined.Type] ir.bindings(1) - .asInstanceOf[IR.Error.Redefined.Atom] - .atomName + .asInstanceOf[IR.Error.Redefined.Type] + .typeName .name shouldEqual atomName - ir.bindings(2) shouldBe an[IR.Error.Redefined.Atom] + ir.bindings(2) shouldBe an[IR.Error.Redefined.Type] ir.bindings(2) - .asInstanceOf[IR.Error.Redefined.Atom] - .atomName + .asInstanceOf[IR.Error.Redefined.Type] + .typeName .name shouldEqual atomName } } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/TypeFunctionsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/SugaredTypeFunctionsTest.scala similarity index 98% rename from engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/TypeFunctionsTest.scala rename to engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/SugaredTypeFunctionsTest.scala index 926728e400ae..8b895f8f4326 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/TypeFunctionsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/SugaredTypeFunctionsTest.scala @@ -7,7 +7,7 @@ import org.enso.compiler.pass.resolve.TypeFunctions import org.enso.compiler.pass.{PassConfiguration, PassGroup, PassManager} import org.enso.compiler.test.CompilerTest -class TypeFunctionsTest extends CompilerTest { +class SugaredTypeFunctionsTest extends CompilerTest { // === Test Setup =========================================================== diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/TypeSignaturesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/TypeSignaturesTest.scala index 36d578d2c60e..e48c2f01a9e8 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/TypeSignaturesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/TypeSignaturesTest.scala @@ -162,7 +162,7 @@ class TypeSignaturesTest extends CompilerTest { |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 4 - ir.bindings(1) shouldBe an[IR.Module.Scope.Definition.Atom] + ir.bindings(1) shouldBe an[IR.Module.Scope.Definition.Data] ir.bindings(2) shouldBe an[IR.Module.Scope.Definition.Method] ir.bindings(2).getMetadata(TypeSignatures) shouldBe defined ir.bindings(2).getMetadata(DocumentationComments) shouldBe defined From 5a6d7494b4ed706ed2e9214d2657c2c81780837e Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 14 Jul 2022 18:43:40 +0200 Subject: [PATCH 018/110] checkpoint --- .../instrument/IdExecutionService.java | 2 +- .../enso/interpreter/node/MethodRootNode.java | 26 +-- .../node/expression/builtin/Any.java | 6 - .../org/enso/interpreter/runtime/Context.java | 3 +- .../org/enso/interpreter/runtime/Module.java | 64 +++++--- .../runtime/builtin/BuiltinType.java | 2 +- .../interpreter/runtime/builtin/Builtins.java | 150 ++++++++++-------- .../callable/atom/AtomConstructor.java | 17 -- .../enso/interpreter/runtime/data/Type.java | 52 +++++- .../runtime/scope/ModuleScope.java | 7 +- .../enso/compiler/codegen/IrToTruffle.scala | 51 +++--- .../codegen/RuntimeStubsGenerator.scala | 2 +- 12 files changed, 233 insertions(+), 149 deletions(-) delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/instrument/IdExecutionService.java b/engine/runtime/src/main/java/org/enso/interpreter/instrument/IdExecutionService.java index 5660b6c49958..e55947c57ee4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/instrument/IdExecutionService.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/instrument/IdExecutionService.java @@ -216,7 +216,7 @@ public FunctionCallInfo(FunctionCallInstrumentationNode.FunctionCall call) { if (rootNode instanceof MethodRootNode) { MethodRootNode methodNode = (MethodRootNode) rootNode; moduleName = methodNode.getModuleScope().getModule().getName(); - typeName = methodNode.getAtomConstructor().getQualifiedName(); + typeName = methodNode.getType().getQualifiedName(); functionName = methodNode.getMethodName(); } else if (rootNode instanceof EnsoRootNode) { moduleName = ((EnsoRootNode) rootNode).getModuleScope().getModule().getName(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/MethodRootNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/MethodRootNode.java index 1ba06ce71965..a200ff469dc3 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/MethodRootNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/MethodRootNode.java @@ -7,7 +7,7 @@ import com.oracle.truffle.api.source.SourceSection; import java.util.function.Supplier; import org.enso.interpreter.Language; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.scope.LocalScope; import org.enso.interpreter.runtime.scope.ModuleScope; @@ -15,7 +15,7 @@ @NodeInfo(shortName = "Method", description = "A root node for Enso methods.") public class MethodRootNode extends ClosureRootNode { - private final AtomConstructor atomConstructor; + private final Type type; private final String methodName; private MethodRootNode( @@ -24,15 +24,15 @@ private MethodRootNode( ModuleScope moduleScope, ExpressionNode body, SourceSection section, - AtomConstructor atomConstructor, + Type type, String methodName) { super(language, localScope, moduleScope, body, section, - shortName(atomConstructor.getName(), methodName), null, false); - this.atomConstructor = atomConstructor; + shortName(type.getName(), methodName), null, false); + this.type = type; this.methodName = methodName; } @@ -48,7 +48,7 @@ private static String shortName(String atomName, String methodName) { * @param moduleScope a description of the module scope * @param body the program provider to be executed * @param section a mapping from {@code provider} to the program source - * @param atomConstructor the constructor this method is defined for + * @param type the type this method is defined for * @param methodName the name of this method * @return a node representing the specified closure */ @@ -58,7 +58,7 @@ public static MethodRootNode build( ModuleScope moduleScope, Supplier body, SourceSection section, - AtomConstructor atomConstructor, + Type type, String methodName) { return build( language, @@ -66,7 +66,7 @@ public static MethodRootNode build( moduleScope, new LazyBodyNode(body), section, - atomConstructor, + type, methodName); } @@ -76,10 +76,10 @@ public static MethodRootNode build( ModuleScope moduleScope, ExpressionNode body, SourceSection section, - AtomConstructor atomConstructor, + Type type, String methodName) { return new MethodRootNode( - language, localScope, moduleScope, body, section, atomConstructor, methodName); + language, localScope, moduleScope, body, section, type, methodName); } /** @@ -93,14 +93,14 @@ public static MethodRootNode build( public String getQualifiedName() { return getModuleScope().getModule().getName().toString() + "::" - + atomConstructor.getQualifiedName().toString() + + type.getQualifiedName().toString() + "::" + methodName; } /** @return the constructor this method was defined for */ - public AtomConstructor getAtomConstructor() { - return atomConstructor; + public Type getType() { + return type; } /** @return the method name */ 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 deleted file mode 100644 index ad28f12ee774..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java +++ /dev/null @@ -1,6 +0,0 @@ -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/runtime/Context.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/Context.java index b02cb9322df0..49a94ae61cf5 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/Context.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/Context.java @@ -18,6 +18,7 @@ import org.enso.interpreter.instrument.NotificationHandler; import org.enso.interpreter.runtime.builtin.Builtins; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.scope.TopLevelScope; import org.enso.interpreter.runtime.util.TruffleFileSystem; import org.enso.interpreter.util.ScalaConversions; @@ -374,7 +375,7 @@ public TopLevelScope getTopScope() { * * @return the builtin {@code Nothing} atom constructor */ - public AtomConstructor getNothing() { + public Type getNothing() { return getBuiltins().nothing(); } 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 36564b9bc6d9..bd1e0aa4c1d6 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 @@ -29,9 +29,11 @@ import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.Array; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.data.text.Text; import org.enso.interpreter.runtime.scope.LocalScope; import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.interpreter.runtime.state.data.EmptyMap; import org.enso.interpreter.runtime.type.Types; import org.enso.pkg.Package; import org.enso.pkg.QualifiedName; @@ -184,7 +186,9 @@ public void unsetLiteralSource() { this.compilationStage = CompilationStage.INITIAL; } - /** @return the literal source of this module. */ + /** + * @return the literal source of this module. + */ public Rope getLiteralSource() { return sources.rope(); } @@ -254,7 +258,9 @@ private void disposeInteractive() { } } - /** @return the location of this module. */ + /** + * @return the location of this module. + */ public String getPath() { return sources.getPath(); } @@ -339,12 +345,16 @@ private void compile(Context context) throws IOException { context.getCompiler().run(this); } - /** @return IR defined by this module. */ + /** + * @return IR defined by this module. + */ public IR.Module getIr() { return ir; } - /** @return the current compilation stage of this module. */ + /** + * @return the current compilation stage of this module. + */ public CompilationStage getCompilationStage() { return compilationStage; } @@ -373,12 +383,16 @@ public void unsafeSetIr(IR.Module ir) { this.ir = ir; } - /** @return the runtime scope of this module. */ + /** + * @return the runtime scope of this module. + */ public ModuleScope getScope() { return scope; } - /** @return the qualified name of this module. */ + /** + * @return the qualified name of this module. + */ public QualifiedName getName() { return name; } @@ -396,7 +410,9 @@ public void renameProject(String newName) { this.name = name.renameProject(newName); } - /** @return the indexed flag. */ + /** + * @return the indexed flag. + */ public boolean isIndexed() { return isIndexed; } @@ -406,12 +422,16 @@ public void setIndexed(boolean indexed) { isIndexed = indexed; } - /** @return the source file of this module. */ + /** + * @return the source file of this module. + */ public TruffleFile getSourceFile() { return sources.file(); } - /** @return {@code true} if the module is interactive, {@code false} otherwise */ + /** + * @return {@code true} if the module is interactive, {@code false} otherwise + */ public boolean isInteractive() { return patchedValues != null; } @@ -426,17 +446,23 @@ public void unsafeBuildIrStub() { compilationStage = CompilationStage.AFTER_CODEGEN; } - /** @return the cache for this module */ + /** + * @return the cache for this module + */ public ModuleCache getCache() { return cache; } - /** @return {@code true} if the module was loaded from the cache, {@code false} otherwise */ + /** + * @return {@code true} if the module was loaded from the cache, {@code false} otherwise + */ public boolean wasLoadedFromCache() { return wasLoadedFromCache; } - /** @param wasLoadedFromCache whether or not the module was loaded from the cache */ + /** + * @param wasLoadedFromCache whether or not the module was loaded from the cache + */ public void setLoadedFromCache(boolean wasLoadedFromCache) { this.wasLoadedFromCache = wasLoadedFromCache; } @@ -449,7 +475,9 @@ public boolean hasCrossModuleLinks() { return hasCrossModuleLinks; } - /** @param hasCrossModuleLinks whether or not the module has cross-module links restored */ + /** + * @param hasCrossModuleLinks whether or not the module has cross-module links restored + */ public void setHasCrossModuleLinks(boolean hasCrossModuleLinks) { this.hasCrossModuleLinks = hasCrossModuleLinks; } @@ -516,8 +544,7 @@ private static Module setSourceFile(Module module, Object[] args, Context contex return module; } - private static AtomConstructor getAssociatedConstructor(ModuleScope scope, Object[] args) - throws ArityException { + private static Type getAssociatedType(ModuleScope scope, Object[] args) throws ArityException { Types.extractArguments(args); return scope.getAssociatedType(); } @@ -533,10 +560,9 @@ private static Object evalExpression( builtins.debug(), Builtins.MethodNames.Debug.EVAL, context.getLanguage()) .orElseThrow(); CallerInfo callerInfo = new CallerInfo(null, LocalScope.root(), scope); - Object state = context.getBuiltins().nothing().newInstance(); return callOptimiserNode .executeDispatch( - eval, callerInfo, state, new Object[] {builtins.debug(), Text.create(expr)}) + eval, callerInfo, EmptyMap.create(), new Object[] {builtins.debug(), Text.create(expr)}) .getValue(); } @@ -564,7 +590,7 @@ static Object doInvoke( case MethodNames.Module.GET_METHOD: scope = module.compileScope(context); Function result = getMethod(scope, arguments); - return result == null ? context.getBuiltins().nothing().newInstance() : result; + return result == null ? context.getBuiltins().nothing() : result; case MethodNames.Module.GET_CONSTRUCTOR: scope = module.compileScope(context); return getConstructor(scope, arguments); @@ -580,7 +606,7 @@ static Object doInvoke( return setSourceFile(module, arguments, context); case MethodNames.Module.GET_ASSOCIATED_CONSTRUCTOR: scope = module.compileScope(context); - return getAssociatedConstructor(scope, arguments); + return getAssociatedType(scope, arguments); case MethodNames.Module.EVAL_EXPRESSION: scope = module.compileScope(context); return evalExpression(scope, arguments, context, callOptimiserNode); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java index 3525bbf105aa..1436f7ff8f52 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java @@ -21,7 +21,7 @@ public BuiltinType(Builtins builtins, Class clazz) { public Type getType() { if (type == null) { transferToInterpreterAndInvalidate(); - type = builtins.getBuiltinType(type); + type = builtins.getBuiltinType(clazz); } return type; } 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 eee6d09d9083..68b98ee10142 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 @@ -64,7 +64,7 @@ public static class Debug { private final Special special; // Builtin types - private final BuiltinType any; + private final Type any; private final BuiltinType nothing; private final BuiltinType function; private final BuiltinType polyglot; @@ -89,7 +89,8 @@ public Builtins(Context context) { scope = module.compileScope(context); builtins = new HashMap<>(); - List builtinTypes = readBuiltinTypesMetadata(scope); + any = new Type("Any", scope, true); + var builtinTypes = readBuiltinTypesMetadata(scope); builtinMethodNodes = readBuiltinMethodsMetadata(scope); registerBuiltinMethods(builtinTypes, scope, language); @@ -99,16 +100,13 @@ public Builtins(Context context) { number = new Number(this); bool = new Bool(this); - any = new BuiltinType(this, Any.class); nothing = new BuiltinType(this, Nothing.class); function = - new BuiltinType( - this, org.enso.interpreter.node.expression.builtin.function.Function.class); + new BuiltinType(this, org.enso.interpreter.node.expression.builtin.function.Function.class); polyglot = new BuiltinType(this, Polyglot.class); text = new BuiltinType(this, Text.class); array = new BuiltinType(this, Array.class); - dataflowError = - new BuiltinType(this, org.enso.interpreter.node.expression.builtin.Error.class); + dataflowError = new BuiltinType(this, org.enso.interpreter.node.expression.builtin.Error.class); ref = new BuiltinType(this, Ref.class); managedResource = new BuiltinType(this, ManagedResource.class); debug = new BuiltinType(this, Debug.class); @@ -127,11 +125,10 @@ public Builtins(Context context) { * @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); + private void registerBuiltinMethods(List builtins, ModuleScope scope, Language language) { + for (Type type : builtins) { + String tpeName = type.getName(); + this.builtins.put(tpeName, type); Map> methods = builtinMethodNodes.get(tpeName); if (methods != null) { methods.forEach( @@ -144,13 +141,15 @@ private void registerBuiltinMethods( e.printStackTrace(); fun = Optional.empty(); } - fun.ifPresent(f -> scope.registerMethod(atom, methodName, f)); + fun.ifPresent(f -> scope.registerMethod(type, methodName, f)); }); } } } - /** @return {@code true} if the IR has been initialized, otherwise {@code false} */ + /** + * @return {@code true} if the IR has been initialized, otherwise {@code false} + */ public boolean isIrInitialized() { return this.module.getIr() != null; } @@ -189,7 +188,7 @@ public void initializeBuiltinsIr(FreshNameSupply freshNameSupply, Passes passes) * * @param scope Builtins scope */ - private List readBuiltinTypesMetadata(ModuleScope scope) { + private List readBuiltinTypesMetadata(ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); List lines; try (InputStream resource = classLoader.getResourceAsStream(TypeProcessor.META_PATH)) { @@ -210,25 +209,25 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { 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; + return new Type(builtinMeta[0], scope, true); }) - .filter(b -> b != null) + // 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; + // }) .collect(Collectors.toList()); } @@ -305,14 +304,13 @@ private Map>> readBuiltinMethodsMetad /** * Returns a builtin method for the provided Atom Constructor and the name, if it exists. * - * @param atom Atom Constructor owner of the function + * @param type 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( - Type type, String methodName, Language language) { + public Optional getBuiltinFunction(Type type, String methodName, Language language) { // TODO: move away from String mapping once Builtins is gone Map> atomNodes = builtinMethodNodes.get(type.getName()); if (atomNodes == null) return Optional.empty(); @@ -327,12 +325,12 @@ public Optional getBuiltinFunction( } } - public AtomConstructor getBuiltinType(Class clazz) { + public Type getBuiltinType(Class clazz) { String snakeCaseName = clazz.getSimpleName().replaceAll("([^_A-Z])([A-Z])", "$1_$2"); return getBuiltinType(snakeCaseName); } - public AtomConstructor getBuiltinType(String name) { + public Type getBuiltinType(String name) { return builtins.get(name); } @@ -341,7 +339,7 @@ public AtomConstructor getBuiltinType(String name) { * * @return the {@code Nothing} atom constructor */ - public AtomConstructor nothing() { + public Type nothing() { return nothing.getType(); } @@ -350,7 +348,7 @@ public AtomConstructor nothing() { * * @return the {@code Text} part of builtins. */ - public AtomConstructor text() { + public Type text() { return text.getType(); } @@ -359,7 +357,7 @@ public AtomConstructor text() { * * @return the {@code Function} atom constructor */ - public AtomConstructor function() { + public Type function() { return function.getType(); } @@ -372,17 +370,23 @@ public Number number() { return number; } - /** @return the container for boolean constructors. */ + /** + * @return the container for boolean constructors. + */ public Bool bool() { return bool; } - /** @return the ManagedResource constructor. */ - public AtomConstructor managedResource() { + /** + * @return the ManagedResource constructor. + */ + public Type managedResource() { return managedResource.getType(); } - /** @return the builtin Error types container. */ + /** + * @return the builtin Error types container. + */ public Error error() { return error; } @@ -392,8 +396,8 @@ public Error error() { * * @return the {@code Any} atom constructor */ - public AtomConstructor any() { - return any.getType(); + public Type any() { + return any; } /** @@ -401,7 +405,7 @@ public AtomConstructor any() { * * @return the {@code Warning} atom constructor */ - public AtomConstructor warning() { + public Type warning() { return warning.getType(); } @@ -410,7 +414,7 @@ public AtomConstructor warning() { * * @return the {@code File} atom constructor */ - public AtomConstructor file() { + public Type file() { return file.getType(); } @@ -420,52 +424,70 @@ public AtomConstructor file() { * * @return the {@code Debug} atom constructor */ - public AtomConstructor debug() { + public Type debug() { return debug.getType(); } - /** @return the {@code Project_Description} atom constructor */ - public AtomConstructor getProjectDescription() { + /** + * @return the {@code Project_Description} atom constructor + */ + public Type getProjectDescription() { return projectDescription.getType(); } - /** @return the {@code System} atom constructor. */ + /** + * @return the {@code System} atom constructor. + */ public System system() { return system; } - /** @return the Array constructor. */ - public AtomConstructor array() { + /** + * @return the Array constructor. + */ + public Type array() { return array.getType(); } - /** @return the Ref constructor. */ - public AtomConstructor ref() { + /** + * @return the Ref constructor. + */ + public Type ref() { return ref.getType(); } - /** @return the container for polyglot-related builtins. */ - public AtomConstructor polyglot() { + /** + * @return the container for polyglot-related builtins. + */ + public Type polyglot() { return polyglot.getType(); } - /** @return the {@code Caught_Panic} atom constructor */ + /** + * @return the {@code Caught_Panic} atom constructor + */ public AtomConstructor caughtPanic() { return this.error.caughtPanic(); } - /** @return the {@code Panic} atom constructor */ + /** + * @return the {@code Panic} atom constructor + */ public AtomConstructor panic() { return this.error.panic(); } - /** @return the container for ordering-related builtins */ + /** + * @return the container for ordering-related builtins + */ public Ordering ordering() { return ordering; } - /** @return the container for the dataflow error-related builtins */ - public AtomConstructor dataflowError() { + /** + * @return the container for the dataflow error-related builtins + */ + public Type dataflowError() { return dataflowError.getType(); } 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 446d804c78e7..246451a94f9b 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 @@ -78,23 +78,6 @@ 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"); - } - } - /** * Generates a constructor function for this {@link AtomConstructor}. Note that such manually * constructed argument definitions must not have default arguments. diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index f0df3eea8990..1e02672b61de 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -1,15 +1,59 @@ package org.enso.interpreter.runtime.data; +import com.oracle.truffle.api.CompilerAsserts; +import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.interop.TruffleObject; +import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.scope.ModuleScope; +import org.enso.pkg.QualifiedName; + +import java.util.Map; public class Type implements TruffleObject { private final String name; - private final ModuleScope definitionScope; + private @CompilerDirectives.CompilationFinal ModuleScope definitionScope; + private final boolean builtin; - public Type(String name, ModuleScope definitionScope) { + public Type(String name, ModuleScope definitionScope, boolean builtin) { this.name = name; this.definitionScope = definitionScope; + this.builtin = builtin; + } + // + // public static Type create( + // String name, ModuleScope definitionScope, Type supertype, Type eigentype, boolean builtin) + // { + // return new Type(name, definitionScope, supertype, eigentype, builtin); + // } + + // public static Type createSingleton(String name, ModuleScope definitionScope, Type supertype, + // Type eigentype, boolean builtin) { + // + // } + + public QualifiedName getQualifiedName() { + if (this == this.getDefinitionScope().getAssociatedType()) { + return definitionScope.getModule().getName(); + } else { + return definitionScope.getModule().getName().createChild(getName()); + } + } + + 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"); + } } public String getName() { @@ -19,4 +63,8 @@ public String getName() { public ModuleScope getDefinitionScope() { return definitionScope; } + + public boolean isBuiltin() { + return builtin; + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/ModuleScope.java index 2a6f50609f80..79728166a85f 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 @@ -31,7 +31,7 @@ public class ModuleScope implements TruffleObject { */ public ModuleScope(Module module) { this.module = module; - this.associatedType = new Type(module.getName().item(), this); + this.associatedType = new Type(module.getName().item(), this, false); } /** @@ -43,6 +43,11 @@ public void registerConstructor(AtomConstructor constructor) { constructors.put(constructor.getName(), constructor); } + public void registerType(Type type) { + types.put(type.getName(), type); + } + + /** * @return the associated type of this module. */ 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 fdc8d1d1690e..3e5c4835aac1 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 @@ -71,6 +71,7 @@ import org.enso.interpreter.{Constants, Language} import java.math.BigInteger import org.enso.compiler.core.IR.Name.Special +import org.enso.interpreter.runtime.data.Type import scala.collection.mutable import scala.collection.mutable.ArrayBuffer @@ -374,8 +375,8 @@ class IrToTruffle( ) val toOpt = - getConstructorResolution(methodDef.methodReference.typePointer) - val fromOpt = getConstructorResolution(methodDef.sourceTypeName) + getTypeResolution(methodDef.methodReference.typePointer) + val fromOpt = getTypeResolution(methodDef.sourceTypeName) toOpt.zip(fromOpt).foreach { case (toType, fromType) => val expressionProcessor = new ExpressionProcessor( toType.getName ++ Constants.SCOPE_SEPARATOR ++ methodDef.methodName.name, @@ -453,18 +454,17 @@ class IrToTruffle( .getOrElse(source.createUnavailableSection()) } - private def getConstructorResolution(expr: IR): Option[AtomConstructor] = + private def getTypeResolution(expr: IR): Option[Type] = expr.getMetadata(MethodDefinitions).map { res => res.target match { - case _: BindingsMap.ResolvedType => throw new CompilerError("todo") + case BindingsMap.ResolvedType(definitionModule, tp) => + definitionModule.unsafeAsModule().getScope.getTypes.get(tp) case BindingsMap.ResolvedModule(module) => module.unsafeAsModule().getScope.getAssociatedType - case BindingsMap.ResolvedConstructor(definitionModule, cons) => - definitionModule - .unsafeAsModule() - .getScope - .getConstructors - .get(cons.name) + case BindingsMap.ResolvedConstructor(_, _) => + throw new CompilerError( + "Impossible here, should be caught by MethodDefinitions pass." + ) case BindingsMap.ResolvedPolyglotSymbol(_, _) => throw new CompilerError( "Impossible polyglot symbol, should be caught by MethodDefinitions pass." @@ -571,15 +571,16 @@ class IrToTruffle( name, fun ) - case BindingsMap.ResolvedModule(module) => - val runtimeCons = - module.unsafeAsModule().getScope.getAssociatedType - val fun = mkConsGetter(runtimeCons) - moduleScope.registerMethod( - moduleScope.getAssociatedType, - name, - fun - ) + case BindingsMap.ResolvedModule( /*module*/ _) => + throw new CompilerError("todo") +// val runtimeCons = +// module.unsafeAsModule().getScope.getAssociatedType +// val fun = mkConsGetter(runtimeCons) +// moduleScope.registerMethod( +// moduleScope.getAssociatedType, +// name, +// fun +// ) case BindingsMap.ResolvedMethod(module, method) => val actualModule = module.unsafeAsModule() val fun = actualModule.getScope.getMethods @@ -849,9 +850,12 @@ class IrToTruffle( case None => Left(BadPatternMatch.NonVisibleConstructor(constructor.name)) case Some( - BindingsMap.Resolution(BindingsMap.ResolvedModule(mod)) + BindingsMap.Resolution( + BindingsMap.ResolvedModule(_ /*mod*/ ) + ) ) => - Right(mod.unsafeAsModule().getScope.getAssociatedType) + throw new CompilerError("todo") + //Right(mod.unsafeAsModule().getScope.getAssociatedType) case Some( BindingsMap.Resolution( BindingsMap.ResolvedConstructor(mod, cons) @@ -915,7 +919,8 @@ class IrToTruffle( branchCodeNode.getCallTarget ) } else if (atomCons == text) { - TextBranchNode.build(text, branchCodeNode.getCallTarget) + throw new CompilerError("todo") +// TextBranchNode.build(text, branchCodeNode.getCallTarget) } else if (atomCons == number.getInteger) { IntegerBranchNode.build(number, branchCodeNode.getCallTarget) } else if (atomCons == number.getDecimal) { @@ -1102,7 +1107,7 @@ class IrToTruffle( ) } case IR.Name.Here(_, _, _) => - ConstructorNode.build(moduleScope.getAssociatedType) + ConstantObjectNode.build(moduleScope.getAssociatedType) case IR.Name.Self(location, passData, _) => processName( IR.Name.Literal( 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 1391ba780fa1..07626045f9e5 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 @@ -29,7 +29,7 @@ class RuntimeStubsGenerator(builtins: Builtins) { if (builtinType == null) { throw new CompilerError("Unknown @BuiltinType " + tp.name) } - scope.registerConstructor(builtinType) + scope.registerType(builtinType) builtinType.setShadowDefinitions(scope) } else { val constructor = new AtomConstructor(tp.name, scope) From e3bbaaa72b19a43e29577295a8d21f77b804e3e0 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 28 Jul 2022 14:34:43 +0200 Subject: [PATCH 019/110] checkpoint --- .../controlflow/caseexpr/ArrayBranchNode.java | 3 +- .../BooleanConstructorBranchNode.java | 31 ++--- .../caseexpr/DecimalBranchNode.java | 3 +- .../controlflow/caseexpr/FileBranchNode.java | 3 +- .../caseexpr/PolyglotBranchNode.java | 17 ++- .../controlflow/caseexpr/TextBranchNode.java | 9 +- .../builtin/bool/CompareToNode.java | 2 +- .../expression/builtin/bool/IfThenNode.java | 2 +- .../expression/builtin/mutable/CopyNode.java | 6 +- .../builtin/number/bigInteger/LessNode.java | 2 +- .../number/bigInteger/MultiplyNode.java | 2 +- .../builtin/number/bigInteger/PowNode.java | 2 +- .../number/bigInteger/SubtractNode.java | 2 +- .../builtin/number/decimal/AddNode.java | 2 +- .../builtin/number/decimal/CompareToNode.java | 2 +- .../builtin/number/decimal/DivideNode.java | 2 +- .../builtin/number/decimal/EqualsNode.java | 13 +- .../builtin/number/decimal/GreaterNode.java | 2 +- .../number/decimal/GreaterOrEqualNode.java | 2 +- .../builtin/number/decimal/LessNode.java | 3 +- .../number/decimal/LessOrEqualNode.java | 2 +- .../builtin/number/decimal/ModNode.java | 2 +- .../builtin/number/decimal/MultiplyNode.java | 2 +- .../builtin/number/decimal/PowNode.java | 2 +- .../builtin/number/decimal/SubtractNode.java | 2 +- .../builtin/number/smallInteger/AddNode.java | 2 +- .../number/smallInteger/BitAndNode.java | 9 +- .../number/smallInteger/BitNotNode.java | 2 +- .../number/smallInteger/BitShiftNode.java | 19 +-- .../smallInteger/BitShiftRightNode.java | 13 +- .../builtin/number/smallInteger/DivNode.java | 2 +- .../number/smallInteger/DivideNode.java | 2 +- .../number/smallInteger/EqualsNode.java | 12 -- .../number/smallInteger/GreaterNode.java | 2 +- .../smallInteger/GreaterOrEqualNode.java | 2 +- .../builtin/number/smallInteger/LessNode.java | 2 +- .../interpreter/runtime/builtin/Bool.java | 3 +- .../interpreter/runtime/builtin/Number.java | 11 +- .../callable/UnresolvedConversion.java | 11 +- .../runtime/callable/UnresolvedSymbol.java | 13 +- .../runtime/callable/atom/Atom.java | 33 ++--- .../callable/atom/AtomConstructor.java | 26 ++-- .../runtime/callable/function/Function.java | 22 +-- .../enso/interpreter/runtime/data/Array.java | 10 +- .../enso/interpreter/runtime/data/Type.java | 8 +- .../interpreter/runtime/data/text/Text.java | 30 +++-- .../runtime/error/DataflowError.java | 9 +- .../dispatch/DefaultBooleanExports.java | 37 +++-- .../dispatch/DefaultDoubleExports.java | 15 +-- .../library/dispatch/DefaultLongExports.java | 22 +-- .../dispatch/MethodDispatchLibrary.java | 3 +- .../runtime/library/types/TypesLibrary.java | 28 ++++ .../runtime/number/EnsoBigInteger.java | 27 ++-- .../enso/compiler/codegen/IrToTruffle.scala | 126 +++++++++--------- 54 files changed, 302 insertions(+), 319 deletions(-) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/library/types/TypesLibrary.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ArrayBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ArrayBranchNode.java index a39edcf3cf75..606e2d87a39a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ArrayBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ArrayBranchNode.java @@ -11,6 +11,7 @@ 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.Type; @NodeInfo(shortName = "ArrayMatch", description = "Allows matching on the Array type.") public abstract class ArrayBranchNode extends BranchNode { @@ -29,7 +30,7 @@ public abstract class ArrayBranchNode extends BranchNode { * @param branch the code to execute in this case * @return an array branch node */ - public static ArrayBranchNode build(AtomConstructor array, RootCallTarget branch) { + public static ArrayBranchNode build(Type array, RootCallTarget branch) { return ArrayBranchNodeGen.create(array, branch); } 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 fb4aa049f787..50af8628b3d9 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,23 +8,16 @@ import com.oracle.truffle.api.profiles.ConditionProfile; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; @NodeInfo(shortName = "BooleanConsMatch", description = "Match using the Boolean constructor.") public abstract class BooleanConstructorBranchNode extends BranchNode { - private final AtomConstructor boolCons; - private final AtomConstructor trueCons; - private final AtomConstructor falseCons; + private final Type boolTp; private final ConditionProfile profile = ConditionProfile.createCountingProfile(); - BooleanConstructorBranchNode( - AtomConstructor bool, - AtomConstructor trueAtom, - AtomConstructor falseAtom, - RootCallTarget branch) { + BooleanConstructorBranchNode(Type bool, RootCallTarget branch) { super(branch); - this.boolCons = bool; - this.trueCons = trueAtom; - this.falseCons = falseAtom; + this.boolTp = bool; } /** @@ -34,21 +27,13 @@ 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( - AtomConstructor bool, - AtomConstructor trueAtom, - AtomConstructor falseAtom, - RootCallTarget branch) { - return BooleanConstructorBranchNodeGen.create(bool, trueAtom, falseAtom, branch); + public static BooleanConstructorBranchNode build(Type bool, RootCallTarget branch) { + return BooleanConstructorBranchNodeGen.create(bool, branch); } @Specialization - void doConstructor(VirtualFrame frame, Object state, Atom target) { - var shouldMatch = - (target.getConstructor() == boolCons) - || (target.getConstructor() == falseCons) - || (target.getConstructor() == trueCons); - if (profile.profile(shouldMatch)) { + void doConstructor(VirtualFrame frame, Object state, Type target) { + if (profile.profile(target == boolTp)) { accept(frame, state, new Object[0]); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/DecimalBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/DecimalBranchNode.java index 11339220daed..de52265461c6 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/DecimalBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/DecimalBranchNode.java @@ -8,6 +8,7 @@ import com.oracle.truffle.api.profiles.ConditionProfile; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; @NodeInfo(shortName = "TextMatch", description = "Allows matching on the Decimal type.") public abstract class DecimalBranchNode extends BranchNode { @@ -26,7 +27,7 @@ public abstract class DecimalBranchNode extends BranchNode { * @param branch the code to execute in this case * @return a decimal branch node */ - public static DecimalBranchNode build(AtomConstructor decimal, RootCallTarget branch) { + public static DecimalBranchNode build(Type decimal, RootCallTarget branch) { return DecimalBranchNodeGen.create(decimal, branch); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/FileBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/FileBranchNode.java index 41087a424490..86b3e4baf201 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/FileBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/FileBranchNode.java @@ -9,6 +9,7 @@ import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.data.EnsoFile; +import org.enso.interpreter.runtime.data.Type; @NodeInfo(shortName = "FileMatch", description = "Allows matching on the File type.") public abstract class FileBranchNode extends BranchNode { @@ -27,7 +28,7 @@ public abstract class FileBranchNode extends BranchNode { * @param branch the code to execute in this case * @return a file branch node */ - public static FileBranchNode build(AtomConstructor file, RootCallTarget branch) { + public static FileBranchNode build(Type file, RootCallTarget branch) { return FileBranchNodeGen.create(file, branch); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/PolyglotBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/PolyglotBranchNode.java index 578473838cb4..312f7f42b086 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/PolyglotBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/PolyglotBranchNode.java @@ -9,14 +9,15 @@ import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; @NodeInfo(shortName = "PolyglotMatch", description = "Allows matching on polyglot objects.") public abstract class PolyglotBranchNode extends BranchNode { - private final AtomConstructor polyglot; + private final Type polyglot; private final ConditionProfile constructorProfile = ConditionProfile.createCountingProfile(); private final ConditionProfile polyglotProfile = ConditionProfile.createCountingProfile(); - PolyglotBranchNode(AtomConstructor polyglot, RootCallTarget branch) { + PolyglotBranchNode(Type polyglot, RootCallTarget branch) { super(branch); this.polyglot = polyglot; } @@ -28,22 +29,20 @@ public abstract class PolyglotBranchNode extends BranchNode { * @param branch the code to execute * @return an integer branch node */ - public static PolyglotBranchNode build(AtomConstructor polyglot, RootCallTarget branch) { + public static PolyglotBranchNode build(Type polyglot, RootCallTarget branch) { return PolyglotBranchNodeGen.create(polyglot, branch); } @Specialization - void doConstructor(VirtualFrame frame, Object state, Atom target) { - if (constructorProfile.profile(polyglot == target.getConstructor())) { - accept(frame, state, target.getFields()); + void doType(VirtualFrame frame, Object state, Type target) { + if (constructorProfile.profile(polyglot == target)) { + accept(frame, state, new Object[0]); } } @Specialization(guards = "isPolyglotObject(obj)") void doLiteral(VirtualFrame frame, Object state, Object obj) { - if (polyglotProfile.profile(isPolyglotObject(obj))) { - accept(frame, state, new Object[0]); - } + accept(frame, state, new Object[0]); } @Fallback diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/TextBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/TextBranchNode.java index d8e614457f66..60a274599d87 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/TextBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/TextBranchNode.java @@ -10,13 +10,14 @@ import com.oracle.truffle.api.profiles.ConditionProfile; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; @NodeInfo(shortName = "TextMatch", description = "Allows matching on the Text type.") public abstract class TextBranchNode extends BranchNode { - private final AtomConstructor text; + private final Type text; private final ConditionProfile profile = ConditionProfile.createCountingProfile(); - TextBranchNode(AtomConstructor text, RootCallTarget branch) { + TextBranchNode(Type text, RootCallTarget branch) { super(branch); this.text = text; } @@ -28,13 +29,13 @@ public abstract class TextBranchNode extends BranchNode { * @param branch the expression to be executed if (@code matcher} matches * @return a node for matching on text in a case expression */ - public static TextBranchNode build(AtomConstructor text, RootCallTarget branch) { + public static TextBranchNode build(Type text, RootCallTarget branch) { return TextBranchNodeGen.create(text, branch); } @Specialization void doConstructor(VirtualFrame frame, Object state, Atom target) { - if (profile.profile(text == target.getConstructor())) { + if (profile.profile(text == target.getConstructor().getType())) { accept(frame, state, target.getFields()); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java index 61a1248a4759..e6667511e5c7 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java @@ -32,7 +32,7 @@ Atom doBoolean(Boolean self, Boolean that) { @Specialization Atom doOther(Boolean self, Object that) { CompilerDirectives.transferToInterpreter(); - var bool = Context.get(this).getBuiltins().bool().getBool().newInstance(); + var bool = Context.get(this).getBuiltins().bool().getBool(); var typeError = Context.get(this).getBuiltins().error().makeTypeError(that, bool, "that"); throw new PanicException(typeError, this); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/IfThenNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/IfThenNode.java index bbe1f9f9f234..4593f6b94aaa 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/IfThenNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/IfThenNode.java @@ -30,7 +30,7 @@ Stateful doExecute(Object state, boolean self, Object if_true) { if (condProfile.profile(self)) { return leftThunkExecutorNode.executeThunk(if_true, state, BaseNode.TailStatus.TAIL_DIRECT); } else { - return new Stateful(state, Context.get(this).getNothing().newInstance()); + return new Stateful(state, Context.get(this).getNothing()); } } } 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 5021c5d67cc5..4d95f116a943 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 @@ -30,7 +30,7 @@ Object doArray( Object self, Array src, long source_index, Array dest, long dest_index, long count) { System.arraycopy( src.getItems(), (int) source_index, dest.getItems(), (int) dest_index, (int) count); - return Context.get(this).getBuiltins().nothing().newInstance(); + return Context.get(this).getBuiltins().nothing(); } @Specialization(guards = "arrays.hasArrayElements(src)") @@ -58,7 +58,7 @@ Object doPolyglotArray( .makeInvalidArrayIndexError(src, e.getInvalidIndex()), this); } - return Context.get(this).getBuiltins().nothing().newInstance(); + return Context.get(this).getBuiltins().nothing(); } @Fallback @@ -66,6 +66,6 @@ Object doOther( Object self, 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.array().newInstance(), src, "src"), this); + builtins.error().makeTypeError(builtins.array(), src, "src"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/LessNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/LessNode.java index 0f804e34ff05..997067c04542 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/LessNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/LessNode.java @@ -38,7 +38,7 @@ boolean doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { @Fallback boolean doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/MultiplyNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/MultiplyNode.java index 350cdf7891a8..bf9c79d8258f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/MultiplyNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/MultiplyNode.java @@ -40,7 +40,7 @@ Object doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { @Fallback Object doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/PowNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/PowNode.java index 6f48c4d73aed..364ad9aa0cc5 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/PowNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/PowNode.java @@ -53,7 +53,7 @@ Object doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { @Fallback Object doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/SubtractNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/SubtractNode.java index 3790694c0f33..9b684e13f7dd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/SubtractNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/SubtractNode.java @@ -40,7 +40,7 @@ Object doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { @Fallback Object doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/AddNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/AddNode.java index 314c092506bc..287e6cc35769 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/AddNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/AddNode.java @@ -37,7 +37,7 @@ static AddNode build() { @Fallback double doOther(double self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java index 8a369f094ecd..69bff1d72070 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java @@ -50,7 +50,7 @@ Atom doDecimal(double self, double that) { @Specialization Atom doOther(double self, Object that) { CompilerDirectives.transferToInterpreter(); - var number = Context.get(this).getBuiltins().number().getNumber().newInstance(); + var number = Context.get(this).getBuiltins().number().getNumber(); var typeError = Context.get(this).getBuiltins().error().makeTypeError(that, number, "that"); throw new PanicException(typeError, this); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/DivideNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/DivideNode.java index 216bca52f3bf..a379f3c142bc 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/DivideNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/DivideNode.java @@ -37,7 +37,7 @@ static DivideNode build() { @Fallback double doOther(double self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/EqualsNode.java index a80879e72291..b9431931ef7b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/EqualsNode.java @@ -9,6 +9,7 @@ import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.number.EnsoBigInteger; @BuiltinMethod(type = "Decimal", name = "==", description = "Equality on numbers.") @@ -34,20 +35,8 @@ boolean doBigInteger(double self, EnsoBigInteger that) { return self == BigIntegerOps.toDouble(that.getValue()); } - @Specialization - boolean doAtom( - Atom self, Atom that, @Cached("getDecimalConstructor()") AtomConstructor decimalCons) { - var thatCons = that.getConstructor(); - var thisCons = self.getConstructor(); - return (thatCons == decimalCons) && (thisCons == thatCons); - } - @Fallback boolean doOther(Object self, Object that) { return false; } - - AtomConstructor getDecimalConstructor() { - return Context.get(this).getBuiltins().number().getDecimal(); - } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/GreaterNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/GreaterNode.java index 15f92cc7b58d..1a8b64ca86b3 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/GreaterNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/GreaterNode.java @@ -38,7 +38,7 @@ boolean doBigInteger(double self, EnsoBigInteger that) { @Fallback boolean doOther(double self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/GreaterOrEqualNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/GreaterOrEqualNode.java index 156b7003d415..ee74ae7f3d44 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/GreaterOrEqualNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/GreaterOrEqualNode.java @@ -38,7 +38,7 @@ boolean doBigInteger(double self, EnsoBigInteger that) { @Fallback boolean doOther(double self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/LessNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/LessNode.java index d3096f3ac242..4574eafab589 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/LessNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/LessNode.java @@ -8,6 +8,7 @@ import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.builtin.Builtins; import org.enso.interpreter.runtime.callable.atom.Atom; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.error.PanicException; import org.enso.interpreter.runtime.number.EnsoBigInteger; @@ -38,7 +39,7 @@ boolean doBigInteger(double self, EnsoBigInteger that) { @Fallback boolean doOther(double self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/LessOrEqualNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/LessOrEqualNode.java index 47937506e992..5aa5b6fdd450 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/LessOrEqualNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/LessOrEqualNode.java @@ -38,7 +38,7 @@ boolean doBigInteger(double self, EnsoBigInteger that) { @Fallback boolean doOther(double self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/ModNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/ModNode.java index 7373b1129e07..f3325bdf6976 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/ModNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/ModNode.java @@ -38,7 +38,7 @@ static ModNode build() { @Fallback double doOther(double self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/MultiplyNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/MultiplyNode.java index 611e91cac8f1..e8329225b67f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/MultiplyNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/MultiplyNode.java @@ -37,7 +37,7 @@ static MultiplyNode build() { @Fallback double doOther(double self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/PowNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/PowNode.java index 3855b5cc479b..1b5c91d43bde 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/PowNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/PowNode.java @@ -37,7 +37,7 @@ static PowNode build() { @Fallback double doOther(double self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/SubtractNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/SubtractNode.java index c847308dbdaf..8dd7149f0abc 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/SubtractNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/SubtractNode.java @@ -37,7 +37,7 @@ static SubtractNode build() { @Fallback double doOther(double self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/AddNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/AddNode.java index 3c9b97c10d33..b88280062eed 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/AddNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/AddNode.java @@ -45,7 +45,7 @@ Object doBigInteger(long self, EnsoBigInteger that) { @Fallback Object doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitAndNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitAndNode.java index 17f62c99c6b8..17e859b8b58b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitAndNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitAndNode.java @@ -32,17 +32,10 @@ Object doBigInteger(long self, EnsoBigInteger that) { return toEnsoNumberNode.execute(BigIntegerOps.bitAnd(self, that.getValue())); } - @Specialization - Object doAtomThis(Atom self, Object that) { - Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); - throw new PanicException(builtins.error().makeTypeError(integer, self, "this"), this); - } - @Fallback Object doOther(Object self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitNotNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitNotNode.java index 6c1b1800b6a1..a142b8a76701 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitNotNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitNotNode.java @@ -25,7 +25,7 @@ long doLong(long self) { @Fallback Object doOther(Object self) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, self, "this"), this); } } 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 d16b624db528..feb48018ef17 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 @@ -30,7 +30,7 @@ public abstract class BitShiftNode extends Node { private final ConditionProfile rightShiftExceedsLongWidth = ConditionProfile.createCountingProfile(); - abstract Object execute(Object self, Object that); + abstract Object execute(long self, Object that); static BitShiftNode build() { return BitShiftNodeGen.create(); @@ -82,23 +82,10 @@ Object doBigInteger(long self, EnsoBigInteger that) { } } - /* Note [Well-Formed BigIntegers] - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * As EnsoBigInteger should only be encountered when the integral value cannot be represented in - * a standard `long`, we can safely rule out that the shift width is zero. - */ - - @Specialization - Object doAtomThis(Atom self, Object that) { - Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); - throw new PanicException(builtins.error().makeTypeError(integer, that, "this"), this); - } - @Fallback - Object doOther(Object self, Object that) { + Object doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, that, "that"), this); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitShiftRightNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitShiftRightNode.java index b522cdba9d9a..7758bc2e6edb 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitShiftRightNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitShiftRightNode.java @@ -14,7 +14,7 @@ @BuiltinMethod(type = "Small_Integer", name = "bit_shift_r", description = "Bitwise right-shift.") public abstract class BitShiftRightNode extends Node { - abstract Object execute(Object self, Object that); + abstract Object execute(long self, Object that); static BitShiftRightNode build() { return BitShiftRightNodeGen.create(); @@ -31,17 +31,10 @@ Object doBigInteger( return bitShiftNode.execute(self, new EnsoBigInteger(BigIntegerOps.negate(that.getValue()))); } - @Specialization - Object doAtomThis(Atom self, Object that) { - Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); - throw new PanicException(builtins.error().makeTypeError(integer, self, "this"), this); - } - @Fallback - Object doOther(Object self, Object that) { + Object doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/DivNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/DivNode.java index 8d81b59eeaec..4e24321133a8 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/DivNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/DivNode.java @@ -38,7 +38,7 @@ Object doBigInteger(long self, EnsoBigInteger that) { @Fallback Object doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/DivideNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/DivideNode.java index adf343115b33..eea7d129b2dd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/DivideNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/DivideNode.java @@ -37,7 +37,7 @@ static DivideNode build() { @Fallback double doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/EqualsNode.java index c61438ee0220..9e73c568491b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/EqualsNode.java @@ -28,20 +28,8 @@ boolean doDouble(long self, double that) { return (double) self == that; } - @Specialization - boolean doAtom( - Atom self, Atom that, @Cached("getSmallIntegerConstructor()") AtomConstructor smallIntCons) { - var thisCons = self.getConstructor(); - var thatCons = that.getConstructor(); - return (thatCons == smallIntCons) && (thisCons == thatCons); - } - @Fallback boolean doOther(Object self, Object that) { return false; } - - AtomConstructor getSmallIntegerConstructor() { - return Context.get(this).getBuiltins().number().getBigInteger(); - } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/GreaterNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/GreaterNode.java index 81c1f5276d72..f303bb94cb7a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/GreaterNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/GreaterNode.java @@ -37,7 +37,7 @@ boolean doBigInteger(long self, EnsoBigInteger that) { @Fallback boolean doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/GreaterOrEqualNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/GreaterOrEqualNode.java index 730df837bca3..2e105cbdb414 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/GreaterOrEqualNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/GreaterOrEqualNode.java @@ -37,7 +37,7 @@ boolean doBigInteger(long self, EnsoBigInteger that) { @Fallback boolean doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/LessNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/LessNode.java index bac3d2893914..4aba14985a27 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/LessNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/LessNode.java @@ -37,7 +37,7 @@ boolean doBigInteger(long self, EnsoBigInteger that) { @Fallback boolean doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } 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 242ba19d07b3..d7bee9127dad 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 @@ -3,6 +3,7 @@ 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.data.Type; /** A container class for all Boolean-related stdlib builtins. */ public class Bool { @@ -28,7 +29,7 @@ public AtomConstructor getFalse() { } /** @return the atom constructor for {@code Boolean}. */ - public AtomConstructor getBool() { + public Type getBool() { return bool.getType(); } } 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 da0c5963999a..158cd3a87a79 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 @@ -5,6 +5,7 @@ import org.enso.interpreter.node.expression.builtin.number.Integer; import org.enso.interpreter.node.expression.builtin.number.SmallInteger; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; /** A container for all number-related builtins. */ public class Number { @@ -26,27 +27,27 @@ public Number(Builtins builtins) { } /** @return the Int64 atom constructor. */ - public AtomConstructor getSmallInteger() { + public Type getSmallInteger() { return smallInteger.getType(); } /** @return the Big_Integer atom constructor. */ - public AtomConstructor getBigInteger() { + public Type getBigInteger() { return bigInteger.getType(); } /** @return the Integer atom constructor */ - public AtomConstructor getInteger() { + public Type getInteger() { return integer.getType(); } /** @return the Number atom constructor */ - public AtomConstructor getNumber() { + public Type getNumber() { return number.getType(); } /** @return the Decimal atom constructor */ - public AtomConstructor getDecimal() { + public Type getDecimal() { return decimal.getType(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedConversion.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedConversion.java index 9c5503789f6f..64a5641974b9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedConversion.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedConversion.java @@ -10,6 +10,7 @@ import org.enso.interpreter.node.callable.InteropConversionCallNode; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.interpreter.runtime.state.data.EmptyMap; @@ -42,11 +43,14 @@ public ModuleScope getScope() { * @param constructors the constructors hierarchy for which this symbol should be resolved * @return the resolved function definition, or null if not found */ - public Function resolveFor(AtomConstructor into, AtomConstructor... constructors) { - for (AtomConstructor constructor : constructors) { - Function candidate = scope.lookupConversionDefinition(constructor, into); + public Function resolveFor(Type into, Type from) { + Type current = from; + while (current != null) { + Function candidate = scope.lookupConversionDefinition(current, into); if (candidate != null) { return candidate; + } else { + current = current.getSupertype(); } } return null; @@ -65,7 +69,6 @@ String toDisplayString(boolean allowSideEffects) { /** * Creates an instance of this node. * - * @param name the name that is unresolved * @param scope the scope in which the lookup will occur * @return a node representing an unresolved symbol {@code name} in {@code scope} */ diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedSymbol.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedSymbol.java index 621b33d5d0e0..c9194b4d2646 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedSymbol.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedSymbol.java @@ -10,6 +10,7 @@ import org.enso.interpreter.node.callable.InteropMethodCallNode; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.interpreter.runtime.state.data.EmptyMap; @@ -39,7 +40,9 @@ public String getName() { return name; } - /** @return the scope this symbol was used in. */ + /** + * @return the scope this symbol was used in. + */ public ModuleScope getScope() { return scope; } @@ -54,12 +57,14 @@ public ModuleScope getScope() { * @param constructors the constructors hierarchy for which this symbol should be resolved * @return the resolved function definition, or null if not found */ - public Function resolveFor(AtomConstructor... constructors) { - for (AtomConstructor constructor : constructors) { - Function candidate = scope.lookupMethodDefinition(constructor, name); + public Function resolveFor(Type type) { + Type current = type; + while (current != null) { + Function candidate = scope.lookupMethodDefinition(type, name); if (candidate != null) { return candidate; } + current = current.getSupertype(); } return null; } 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 f9093aa0c9d0..2093a07eae97 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 @@ -16,6 +16,7 @@ import org.enso.interpreter.runtime.callable.UnresolvedSymbol; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.Array; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.data.text.Text; import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; import org.enso.interpreter.runtime.type.TypesGen; @@ -197,7 +198,7 @@ Text toDisplayString(boolean allowSideEffects, @CachedLibrary("this") InteropLib @ExportMessage boolean isNull() { - return this.getConstructor() == Context.get(null).getBuiltins().nothing(); + return this.getConstructor().getType() == Context.get(null).getBuiltins().nothing(); } @ExportMessage @@ -226,8 +227,8 @@ static class GetFunctionalDispatch { static final int CACHE_SIZE = 10; @CompilerDirectives.TruffleBoundary - static Function doResolve(AtomConstructor cons, UnresolvedSymbol symbol) { - return symbol.resolveFor(cons, getContext().getBuiltins().any()); + static Function doResolve(Type type, UnresolvedSymbol symbol) { + return symbol.resolveFor(type); } static Context getContext() { @@ -238,7 +239,7 @@ static Context getContext() { guards = { "!getContext().isInlineCachingDisabled()", "cachedSymbol == symbol", - "self.constructor == cachedConstructor", + "self.constructor.getType() == cachedType", "function != null" }, limit = "CACHE_SIZE") @@ -246,15 +247,15 @@ static Function resolveCached( Atom self, UnresolvedSymbol symbol, @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("self.constructor") AtomConstructor cachedConstructor, - @Cached("doResolve(cachedConstructor, cachedSymbol)") Function function) { + @Cached("self.constructor.getType()") Type cachedType, + @Cached("doResolve(cachedType, cachedSymbol)") Function function) { return function; } @Specialization(replaces = "resolveCached") static Function resolve(Atom self, UnresolvedSymbol symbol) throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(self.constructor, symbol); + Function function = doResolve(self.constructor.getType(), symbol); if (function == null) { throw new MethodDispatchLibrary.NoSuchMethodException(); } @@ -274,8 +275,8 @@ static class GetConversionFunction { @CompilerDirectives.TruffleBoundary static Function doResolve( - AtomConstructor cons, AtomConstructor target, UnresolvedConversion conversion) { - return conversion.resolveFor(target, cons, getContext().getBuiltins().any()); + Type type, Type target, UnresolvedConversion conversion) { + return conversion.resolveFor(target, type); } static Context getContext() { @@ -287,25 +288,25 @@ static Context getContext() { "!getContext().isInlineCachingDisabled()", "cachedConversion == conversion", "cachedTarget == target", - "self.constructor == cachedConstructor", + "self.constructor.getType() == cachedType", "function != null" }, limit = "CACHE_SIZE") static Function resolveCached( Atom self, - AtomConstructor target, + Type target, UnresolvedConversion conversion, @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("self.constructor") AtomConstructor cachedConstructor, - @Cached("target") AtomConstructor cachedTarget, - @Cached("doResolve(cachedConstructor, cachedTarget, cachedConversion)") Function function) { + @Cached("self.constructor.getType()") Type cachedType, + @Cached("target") Type cachedTarget, + @Cached("doResolve(cachedType, cachedTarget, cachedConversion)") Function function) { return function; } @Specialization(replaces = "resolveCached") - static Function resolve(Atom self, AtomConstructor target, UnresolvedConversion conversion) + static Function resolve(Atom self, Type target, UnresolvedConversion conversion) throws MethodDispatchLibrary.NoSuchConversionException { - Function function = doResolve(self.constructor, target, conversion); + Function function = doResolve(self.constructor.getType(), target, conversion); if (function == null) { throw new MethodDispatchLibrary.NoSuchConversionException(); } 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 246451a94f9b..052abd3aadc8 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 @@ -25,6 +25,7 @@ import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.callable.function.FunctionSchema; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; import org.enso.interpreter.runtime.scope.LocalScope; import org.enso.interpreter.runtime.scope.ModuleScope; @@ -43,6 +44,8 @@ public final class AtomConstructor implements TruffleObject { private @CompilerDirectives.CompilationFinal Atom cachedInstance; private @CompilerDirectives.CompilationFinal Function constructorFunction; + private final Type type; + /** * Creates a new Atom constructor for a given name. The constructor is not valid until {@link * AtomConstructor#initializeFields(LocalScope,ExpressionNode[],ExpressionNode[],ArgumentDefinition...)} @@ -288,6 +291,10 @@ public ArgumentDefinition[] getFields() { return constructorFunction.getSchema().getArgumentInfos(); } + public Type getType() { + return type; + } + @ExportMessage boolean hasFunctionalDispatch() { return true; @@ -345,8 +352,8 @@ static class GetConversionFunction { @CompilerDirectives.TruffleBoundary static Function doResolve( - AtomConstructor cons, AtomConstructor target, UnresolvedConversion conversion) { - return conversion.resolveFor(target, cons, getContext().getBuiltins().any()); + Type self, Type target, UnresolvedConversion conversion) { + return conversion.resolveFor(target, self); } static Context getContext() { @@ -358,30 +365,31 @@ static Context getContext() { "!getContext().isInlineCachingDisabled()", "cachedConversion == conversion", "cachedTarget == target", - "self == cachedConstructor", + "self.getType() == cachedType", "function != null" }, limit = "CACHE_SIZE") static Function resolveCached( AtomConstructor self, - AtomConstructor target, + Type target, UnresolvedConversion conversion, @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") AtomConstructor cachedTarget, - @Cached("self") AtomConstructor cachedConstructor, - @Cached("doResolve(cachedConstructor, cachedTarget, cachedConversion)") Function function) { + @Cached("target") Type cachedTarget, + @Cached("self.getType()") Type cachedType, + @Cached("doResolve(cachedType, cachedTarget, cachedConversion)") Function function) { return function; } @Specialization(replaces = "resolveCached") static Function resolve( - AtomConstructor self, AtomConstructor target, UnresolvedConversion conversion) + AtomConstructor self, Type target, UnresolvedConversion conversion) throws MethodDispatchLibrary.NoSuchConversionException { - Function function = doResolve(self, target, conversion); + Function function = doResolve(self.type, target, conversion); if (function == null) { throw new MethodDispatchLibrary.NoSuchConversionException(); } return function; } } + } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/Function.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/Function.java index b182bb561b3d..a42005bbf67a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/Function.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/Function.java @@ -25,6 +25,7 @@ import org.enso.interpreter.runtime.callable.UnresolvedSymbol; import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; import org.enso.interpreter.runtime.state.data.EmptyMap; import org.enso.interpreter.runtime.data.Array; @@ -121,12 +122,16 @@ public RootCallTarget getCallTarget() { return callTarget; } - /** @return the name of this function. */ + /** + * @return the name of this function. + */ public String getName() { return getCallTarget().getRootNode().getName(); } - /** @return the source section this function was defined in. */ + /** + * @return the source section this function was defined in. + */ public SourceSection getSourceSection() { return getCallTarget().getRootNode().getSourceSection(); } @@ -377,7 +382,7 @@ static class GetFunctionalDispatch { @CompilerDirectives.TruffleBoundary static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().function(), context.getBuiltins().any()); + return symbol.resolveFor(context.getBuiltins().function()); } static Context getContext() { @@ -421,10 +426,9 @@ static class GetConversionFunction { static final int CACHE_SIZE = 10; @CompilerDirectives.TruffleBoundary - static Function doResolve(AtomConstructor target, UnresolvedConversion conversion) { + static Function doResolve(Type target, UnresolvedConversion conversion) { Context context = getContext(); - return conversion.resolveFor( - target, context.getBuiltins().function(), context.getBuiltins().any()); + return conversion.resolveFor(target, context.getBuiltins().function()); } static Context getContext() { @@ -441,16 +445,16 @@ static Context getContext() { limit = "CACHE_SIZE") static Function resolveCached( Function self, - AtomConstructor target, + Type target, UnresolvedConversion conversion, @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") AtomConstructor cachedTarget, + @Cached("target") Type cachedTarget, @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { return function; } @Specialization(replaces = "resolveCached") - static Function resolve(Function self, AtomConstructor target, UnresolvedConversion conversion) + static Function resolve(Function self, Type target, UnresolvedConversion conversion) throws MethodDispatchLibrary.NoSuchConversionException { Function function = doResolve(target, conversion); if (function == null) { 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 1ae760753a8a..679bae95e1ac 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 @@ -205,10 +205,10 @@ static class GetConversionFunction { static final int CACHE_SIZE = 10; @CompilerDirectives.TruffleBoundary - static Function doResolve(AtomConstructor target, UnresolvedConversion conversion) { + static Function doResolve(Type target, UnresolvedConversion conversion) { Context context = getContext(); return conversion.resolveFor( - target, context.getBuiltins().array(), context.getBuiltins().any()); + target, context.getBuiltins().array()); } static Context getContext() { @@ -225,16 +225,16 @@ static Context getContext() { limit = "CACHE_SIZE") static Function resolveCached( Array self, - AtomConstructor target, + Type target, UnresolvedConversion conversion, @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") AtomConstructor cachedTarget, + @Cached("target") Type cachedTarget, @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { return function; } @Specialization(replaces = "resolveCached") - static Function resolve(Array self, AtomConstructor target, UnresolvedConversion conversion) + static Function resolve(Array self, Type target, UnresolvedConversion conversion) throws MethodDispatchLibrary.NoSuchConversionException { Function function = doResolve(target, conversion); if (function == null) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index 1e02672b61de..8563a6d8a3f0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -13,10 +13,12 @@ public class Type implements TruffleObject { private final String name; private @CompilerDirectives.CompilationFinal ModuleScope definitionScope; private final boolean builtin; + private final Type supertype; - public Type(String name, ModuleScope definitionScope, boolean builtin) { + public Type(String name, ModuleScope definitionScope, Type supertype, boolean builtin) { this.name = name; this.definitionScope = definitionScope; + this.supertype = supertype; this.builtin = builtin; } // @@ -67,4 +69,8 @@ public ModuleScope getDefinitionScope() { public boolean isBuiltin() { return builtin; } + + public Type getSupertype() { + return supertype; + } } 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 702ab04f35fe..50c2aae2d918 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 @@ -13,6 +13,7 @@ import org.enso.interpreter.runtime.callable.UnresolvedSymbol; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; import java.util.concurrent.locks.Lock; @@ -139,17 +140,23 @@ String toDisplayString( return "'" + replaced + "'"; } - /** @return true if this text wraps a string literal and does not require any optimization. */ + /** + * @return true if this text wraps a string literal and does not require any optimization. + */ public boolean isFlat() { return isFlat; } - /** @param flat the new value of the isFlat flag. */ + /** + * @param flat the new value of the isFlat flag. + */ public void setFlat(boolean flat) { isFlat = flat; } - /** @return the contents of this text. */ + /** + * @return the contents of this text. + */ public Object getContents() { return contents; } @@ -163,7 +170,9 @@ public void setContents(Object contents) { this.contents = contents; } - /** @return the lock required for modification of this text. */ + /** + * @return the lock required for modification of this text. + */ public Lock getLock() { return lock; } @@ -190,7 +199,7 @@ static class GetFunctionalDispatch { @CompilerDirectives.TruffleBoundary static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().text(), context.getBuiltins().any()); + return symbol.resolveFor(context.getBuiltins().text()); } static Context getContext() { @@ -239,10 +248,9 @@ static class GetConversionFunction { static final int CACHE_SIZE = 10; @CompilerDirectives.TruffleBoundary - static Function doResolve(AtomConstructor target, UnresolvedConversion conversion) { + static Function doResolve(Type target, UnresolvedConversion conversion) { Context context = getContext(); - return conversion.resolveFor( - target, context.getBuiltins().text(), context.getBuiltins().any()); + return conversion.resolveFor(target, context.getBuiltins().text()); } static Context getContext() { @@ -259,16 +267,16 @@ static Context getContext() { limit = "CACHE_SIZE") static Function resolveCached( Text self, - AtomConstructor target, + Type target, UnresolvedConversion conversion, - @Cached("target") AtomConstructor cachedTarget, + @Cached("target") Type cachedTarget, @Cached("conversion") UnresolvedConversion cachedConversion, @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { return function; } @Specialization(replaces = "resolveCached") - static Function resolve(Text self, AtomConstructor target, UnresolvedConversion conversion) + static Function resolve(Text self, Type target, UnresolvedConversion conversion) throws MethodDispatchLibrary.NoSuchConversionException { Function function = doResolve(target, conversion); if (function == null) { 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 c99dbb8734db..1286e3fdf232 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 @@ -15,6 +15,7 @@ import org.enso.interpreter.runtime.callable.UnresolvedConversion; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; /** @@ -114,7 +115,7 @@ static class GetConversionFunction { static final int CACHE_SIZE = 10; @CompilerDirectives.TruffleBoundary - static Function doResolve(AtomConstructor target, UnresolvedConversion conversion) { + static Function doResolve(Type target, UnresolvedConversion conversion) { Context context = getContext(); return conversion.resolveFor(target, context.getBuiltins().dataflowError()); } @@ -133,17 +134,17 @@ static Context getContext() { limit = "CACHE_SIZE") static Function resolveCached( DataflowError self, - AtomConstructor target, + Type target, UnresolvedConversion conversion, @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") AtomConstructor cachedTarget, + @Cached("target") Type cachedTarget, @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { return function; } @Specialization(replaces = "resolveCached") static Function resolve( - DataflowError self, AtomConstructor target, UnresolvedConversion conversion) + DataflowError self, Type target, UnresolvedConversion conversion) throws MethodDispatchLibrary.NoSuchConversionException { Function function = doResolve(target, conversion); if (function == null) { 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 923cfc3d7b4a..8c6bab266758 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 @@ -11,6 +11,7 @@ import org.enso.interpreter.runtime.callable.UnresolvedSymbol; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; @ExportLibrary(value = MethodDispatchLibrary.class, receiverType = Boolean.class) public class DefaultBooleanExports { @@ -32,13 +33,13 @@ static class GetFunctionalDispatch { static Function resolveMethodOnPrimBoolean(UnresolvedSymbol symbol) { Context context = getContext(); Builtins builtins = context.getBuiltins(); - if (symbol.resolveFor(builtins.bool().getFalse()) != null) { + if (symbol.resolveFor(builtins.bool().getFalse().getType()) != null) { return null; } - if (symbol.resolveFor(builtins.bool().getTrue()) != null) { + if (symbol.resolveFor(builtins.bool().getTrue().getType()) != null) { return null; } - return symbol.resolveFor(builtins.bool().getBool(), context.getBuiltins().any()); + return symbol.resolveFor(builtins.bool().getBool()); } @CompilerDirectives.TruffleBoundary @@ -46,7 +47,7 @@ static Function resolveMethodOnBool(boolean self, UnresolvedSymbol symbol) { Context context = getContext(); Builtins builtins = context.getBuiltins(); AtomConstructor cons = self ? builtins.bool().getTrue() : builtins.bool().getFalse(); - return symbol.resolveFor(cons, builtins.bool().getBool(), context.getBuiltins().any()); + return symbol.resolveFor(cons.getType()); } static Context getContext() { @@ -126,27 +127,25 @@ public static boolean hasSpecialConversion(Boolean receiver) { @ExportMessage static class GetConversionFunction { @CompilerDirectives.TruffleBoundary - static Function resolveMethodOnPrimBoolean( - AtomConstructor target, UnresolvedConversion conversion) { + static Function resolveMethodOnPrimBoolean(Type target, UnresolvedConversion conversion) { Context context = Context.get(null); Builtins builtins = context.getBuiltins(); - if (conversion.resolveFor(target, builtins.bool().getFalse()) != null) { + if (conversion.resolveFor(target, builtins.bool().getFalse().getType()) != null) { return null; } - if (conversion.resolveFor(target, builtins.bool().getTrue()) != null) { + if (conversion.resolveFor(target, builtins.bool().getTrue().getType()) != null) { return null; } - return conversion.resolveFor(target, builtins.bool().getBool(), context.getBuiltins().any()); + return conversion.resolveFor(target, builtins.bool().getBool()); } @CompilerDirectives.TruffleBoundary static Function resolveMethodOnBool( - boolean self, AtomConstructor target, UnresolvedConversion conversion) { + boolean self, Type target, UnresolvedConversion conversion) { Context context = Context.get(null); Builtins builtins = context.getBuiltins(); AtomConstructor cons = self ? builtins.bool().getTrue() : builtins.bool().getFalse(); - return conversion.resolveFor( - target, cons, builtins.bool().getBool(), context.getBuiltins().any()); + return conversion.resolveFor(target, cons.getType()); } static Context getContext() { @@ -163,10 +162,10 @@ static Context getContext() { limit = "CACHE_SIZE") static Function resolveCached( Boolean self, - AtomConstructor target, + Type target, UnresolvedConversion conversion, @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") AtomConstructor cachedTarget, + @Cached("target") Type cachedTarget, @Cached("resolveMethodOnPrimBoolean(cachedTarget, cachedConversion)") Function function) { return function; } @@ -183,9 +182,9 @@ static Function resolveCached( replaces = "resolveCached") static Function resolveTrueCached( Boolean self, - AtomConstructor target, + Type target, UnresolvedConversion conversion, - @Cached("target") AtomConstructor cachedTarget, + @Cached("target") Type cachedTarget, @Cached("conversion") UnresolvedConversion cachedConversion, @Cached("resolveMethodOnBool(self, cachedTarget, cachedConversion)") Function function) { return function; @@ -203,16 +202,16 @@ static Function resolveTrueCached( replaces = "resolveCached") static Function resolveFalseCached( Boolean self, - AtomConstructor target, + Type target, UnresolvedConversion conversion, @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") AtomConstructor cachedTarget, + @Cached("target") Type cachedTarget, @Cached("resolveMethodOnBool(self, cachedTarget, cachedConversion)") Function function) { return function; } @Specialization(replaces = {"resolveTrueCached", "resolveFalseCached"}) - static Function resolve(Boolean self, AtomConstructor target, UnresolvedConversion symbol) + static Function resolve(Boolean self, Type target, UnresolvedConversion symbol) throws MethodDispatchLibrary.NoSuchConversionException { Function function = resolveMethodOnBool(self, target, symbol); if (function == null) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultDoubleExports.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultDoubleExports.java index f281c4b07970..0df0904c78cb 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultDoubleExports.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultDoubleExports.java @@ -11,6 +11,7 @@ import org.enso.interpreter.runtime.callable.UnresolvedSymbol; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; @ExportLibrary(value = MethodDispatchLibrary.class, receiverType = Double.class) public class DefaultDoubleExports { @@ -25,8 +26,7 @@ static class GetFunctionalDispatch { static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); Number number = context.getBuiltins().number(); - return symbol.resolveFor( - number.getDecimal(), number.getNumber(), context.getBuiltins().any()); + return symbol.resolveFor(number.getDecimal()); } static Context getContext() { @@ -74,11 +74,10 @@ public static boolean hasSpecialConversion(Double receiver) { @ExportMessage static class GetConversionFunction { @CompilerDirectives.TruffleBoundary - static Function doResolve(AtomConstructor target, UnresolvedConversion conversion) { + static Function doResolve(Type target, UnresolvedConversion conversion) { Context context = getContext(); Number number = context.getBuiltins().number(); - return conversion.resolveFor( - target, number.getDecimal(), number.getNumber(), context.getBuiltins().any()); + return conversion.resolveFor(target, number.getDecimal()); } static Context getContext() { @@ -97,16 +96,16 @@ static Context getContext() { limit = "CACHE_SIZE") static Function resolveCached( Double self, - AtomConstructor target, + Type target, UnresolvedConversion conversion, @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") AtomConstructor cachedTarget, + @Cached("target") Type cachedTarget, @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { return function; } @Specialization(replaces = "resolveCached") - static Function resolve(Double self, AtomConstructor target, UnresolvedConversion conversion) + static Function resolve(Double self, Type target, UnresolvedConversion conversion) throws MethodDispatchLibrary.NoSuchConversionException { Function function = doResolve(target, conversion); if (function == null) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultLongExports.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultLongExports.java index d06677713417..a2e03a7da835 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultLongExports.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultLongExports.java @@ -11,6 +11,7 @@ import org.enso.interpreter.runtime.callable.UnresolvedSymbol; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; @ExportLibrary(value = MethodDispatchLibrary.class, receiverType = Long.class) public class DefaultLongExports { @@ -25,11 +26,7 @@ static class GetFunctionalDispatch { static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); Number number = context.getBuiltins().number(); - return symbol.resolveFor( - number.getSmallInteger(), - number.getInteger(), - number.getNumber(), - context.getBuiltins().any()); + return symbol.resolveFor(number.getSmallInteger()); } static Context getContext() { @@ -77,15 +74,10 @@ public static boolean hasSpecialConversion(Long receiver) { @ExportMessage static class GetConversionFunction { @CompilerDirectives.TruffleBoundary - static Function doResolve(AtomConstructor target, UnresolvedConversion conversion) { + static Function doResolve(Type target, UnresolvedConversion conversion) { Context context = getContext(); Number number = context.getBuiltins().number(); - return conversion.resolveFor( - target, - number.getSmallInteger(), - number.getInteger(), - number.getNumber(), - context.getBuiltins().any()); + return conversion.resolveFor(target, number.getSmallInteger()); } static Context getContext() { @@ -104,16 +96,16 @@ static Context getContext() { limit = "CACHE_SIZE") static Function resolveCached( Long self, - AtomConstructor target, + Type target, UnresolvedConversion conversion, @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") AtomConstructor cachedTarget, + @Cached("target") Type cachedTarget, @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { return function; } @Specialization(replaces = "resolveCached") - static Function resolve(Long self, AtomConstructor target, UnresolvedConversion conversion) + static Function resolve(Long self, Type target, UnresolvedConversion conversion) throws MethodDispatchLibrary.NoSuchConversionException { Function function = doResolve(target, conversion); if (function == null) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/MethodDispatchLibrary.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/MethodDispatchLibrary.java index 85c9e7d6ef3f..ced33a1d4c88 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/MethodDispatchLibrary.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/MethodDispatchLibrary.java @@ -7,6 +7,7 @@ import org.enso.interpreter.runtime.callable.UnresolvedSymbol; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; /** * A library used for equipping data structures with Enso-style (fully unapplied) method dispatch. @@ -94,7 +95,7 @@ public boolean hasSpecialConversion(Object receiver) { @GenerateLibrary.Abstract(ifExported = {"canConvertFrom"}) public Function getConversionFunction( - Object receiver, AtomConstructor target, UnresolvedConversion symbol) + Object receiver, Type target, UnresolvedConversion symbol) throws MethodDispatchLibrary.NoSuchConversionException { throw new MethodDispatchLibrary.NoSuchConversionException(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/types/TypesLibrary.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/types/TypesLibrary.java new file mode 100644 index 000000000000..cc96afbe2d2b --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/types/TypesLibrary.java @@ -0,0 +1,28 @@ +package org.enso.interpreter.runtime.library.types; + +import com.oracle.truffle.api.library.GenerateLibrary; +import com.oracle.truffle.api.library.Library; +import com.oracle.truffle.api.library.LibraryFactory; +import org.enso.interpreter.runtime.data.Type; + +@GenerateLibrary +public abstract class TypesLibrary extends Library { + public static LibraryFactory getFactory() { + return FACTORY; + } + + public static TypesLibrary getUncached() { + return FACTORY.getUncached(); + } + + private static final LibraryFactory FACTORY = + LibraryFactory.resolve(TypesLibrary.class); + + public Type getType(Object receiver) { + return null; + } + + public boolean hasSpecialMethodDispatch(Object receiver) { + return false; + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/number/EnsoBigInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/number/EnsoBigInteger.java index 11642cf68f95..a4576b295da1 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/number/EnsoBigInteger.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/number/EnsoBigInteger.java @@ -13,6 +13,7 @@ import org.enso.interpreter.runtime.callable.UnresolvedSymbol; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; import java.math.BigInteger; @@ -32,7 +33,9 @@ public EnsoBigInteger(BigInteger value) { this.value = value; } - /** @return the contained {@link BigInteger}. */ + /** + * @return the contained {@link BigInteger}. + */ public BigInteger getValue() { return value; } @@ -62,11 +65,7 @@ static class GetFunctionalDispatch { static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); Number number = context.getBuiltins().number(); - return symbol.resolveFor( - number.getBigInteger(), - number.getInteger(), - number.getNumber(), - context.getBuiltins().any()); + return symbol.resolveFor(number.getBigInteger()); } static Context getContext() { @@ -110,15 +109,10 @@ static class GetConversionFunction { static final int CACHE_SIZE = 10; @CompilerDirectives.TruffleBoundary - static Function doResolve(AtomConstructor target, UnresolvedConversion conversion) { + static Function doResolve(Type target, UnresolvedConversion conversion) { Context context = getContext(); Number number = context.getBuiltins().number(); - return conversion.resolveFor( - target, - number.getBigInteger(), - number.getInteger(), - number.getNumber(), - context.getBuiltins().any()); + return conversion.resolveFor(target, number.getBigInteger()); } static Context getContext() { @@ -135,17 +129,16 @@ static Context getContext() { limit = "CACHE_SIZE") static Function resolveCached( EnsoBigInteger self, - AtomConstructor target, + Type target, UnresolvedConversion conversion, @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") AtomConstructor cachedTarget, + @Cached("target") Type cachedTarget, @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { return function; } @Specialization(replaces = "resolveCached") - static Function resolve( - EnsoBigInteger self, AtomConstructor target, UnresolvedConversion conversion) + static Function resolve(EnsoBigInteger self, Type target, UnresolvedConversion conversion) throws MethodDispatchLibrary.NoSuchConversionException { Function function = doResolve(target, conversion); if (function == null) { 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 3e5c4835aac1..d35818d2836e 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 @@ -842,7 +842,16 @@ class IrToTruffle( ) } - val runtimeConsOpt = constructor match { + val fieldNames = cons.unsafeFieldsAsNamed + val fieldsAsArgs = fieldNames.map(genArgFromMatchField) + + val branchCodeNode = childProcessor.processFunctionBody( + fieldsAsArgs, + branch.expression, + branch.location + ) + + constructor match { case err: IR.Error.Resolution => Left(BadPatternMatch.NonVisibleConstructor(err.name)) case _ => @@ -861,13 +870,59 @@ class IrToTruffle( BindingsMap.ResolvedConstructor(mod, cons) ) ) => - Right( + val atomCons = mod.unsafeAsModule().getScope.getConstructors.get(cons.name) - ) + val r = if (atomCons == context.getBuiltins.bool().getTrue) { + BooleanBranchNode.build(true, branchCodeNode.getCallTarget) + } else if (atomCons == context.getBuiltins.bool().getFalse) { + BooleanBranchNode.build(false, branchCodeNode.getCallTarget) + } else { + ConstructorBranchNode.build( + atomCons, + branchCodeNode.getCallTarget + ) + } + Right(r) case Some( - BindingsMap.Resolution(BindingsMap.ResolvedType(_, _)) + BindingsMap.Resolution(BindingsMap.ResolvedType(mod, tp)) ) => - throw new CompilerError("todo") + val tpe = + mod.unsafeAsModule().getScope.getTypes.get(tp.name) + val any = context.getBuiltins.any + val array = context.getBuiltins.array + val file = context.getBuiltins.file + val builtinBool = context.getBuiltins.bool.getBool + val number = context.getBuiltins.number + val polyglot = context.getBuiltins.polyglot + val text = context.getBuiltins.text + val branch = if (tpe == builtinBool) { + BooleanConstructorBranchNode.build( + builtinBool, + branchCodeNode.getCallTarget + ) + } else if (tpe == text) { + TextBranchNode.build(text, branchCodeNode.getCallTarget) + } else if (tpe == number.getInteger) { + IntegerBranchNode.build( + number, + branchCodeNode.getCallTarget + ) + } else if (tpe == number.getDecimal) { + DecimalBranchNode.build(tpe, branchCodeNode.getCallTarget) + } else if (tpe == number.getNumber) { + NumberBranchNode.build(number, branchCodeNode.getCallTarget) + } else if (tpe == array) { + ArrayBranchNode.build(tpe, branchCodeNode.getCallTarget) + } else if (tpe == file) { + FileBranchNode.build(tpe, branchCodeNode.getCallTarget) + } else if (tpe == polyglot) { + PolyglotBranchNode.build(tpe, branchCodeNode.getCallTarget) + } else if (tpe == any) { + CatchAllBranchNode.build(branchCodeNode.getCallTarget) + } else { + throw new CompilerError("think about this") + } + Right(branch) case Some( BindingsMap.Resolution( BindingsMap.ResolvedPolyglotSymbol(_, _) @@ -886,67 +941,6 @@ class IrToTruffle( ) } } - - val fieldNames = cons.unsafeFieldsAsNamed - val fieldsAsArgs = fieldNames.map(genArgFromMatchField) - - val branchCodeNode = childProcessor.processFunctionBody( - fieldsAsArgs, - branch.expression, - branch.location - ) - - runtimeConsOpt.map { atomCons => - val any = context.getBuiltins.any - val array = context.getBuiltins.array - val file = context.getBuiltins.file - 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 == builtinTrue) { - BooleanBranchNode.build(true, branchCodeNode.getCallTarget) - } else if (atomCons == builtinFalse) { - BooleanBranchNode.build(false, branchCodeNode.getCallTarget) - } else if (atomCons == builtinBool) { - BooleanConstructorBranchNode.build( - builtinBool, - builtinTrue, - builtinFalse, - branchCodeNode.getCallTarget - ) - } else if (atomCons == text) { - throw new CompilerError("todo") -// TextBranchNode.build(text, branchCodeNode.getCallTarget) - } else if (atomCons == number.getInteger) { - IntegerBranchNode.build(number, branchCodeNode.getCallTarget) - } else if (atomCons == number.getDecimal) { - DecimalBranchNode.build( - number.getDecimal, - branchCodeNode.getCallTarget - ) - } else if (atomCons == number.getNumber) { - NumberBranchNode.build(number, branchCodeNode.getCallTarget) - } else if (atomCons == array) { - ArrayBranchNode.build(atomCons, branchCodeNode.getCallTarget) - } else if (atomCons == file) { - FileBranchNode.build(atomCons, branchCodeNode.getCallTarget) - } else if (atomCons == polyglot) { - PolyglotBranchNode.build(atomCons, branchCodeNode.getCallTarget) - } else if (atomCons == any) { - CatchAllBranchNode.build(branchCodeNode.getCallTarget) - } else { - ConstructorBranchNode.build( - atomCons, - branchCodeNode.getCallTarget - ) - } - - branchNode - } case _: Pattern.Documentation => throw new CompilerError( "Branch documentation should be desugared at an earlier stage." From 9310fc74c7351a6c7007a0ac97cde5693c3cf3b3 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 29 Jul 2022 15:22:44 +0200 Subject: [PATCH 020/110] builtin dsl changes --- .../controlflow/caseexpr/ArrayBranchNode.java | 12 +- .../caseexpr/DecimalBranchNode.java | 10 +- .../controlflow/caseexpr/FileBranchNode.java | 10 +- .../caseexpr/IntegerBranchNode.java | 16 +- .../caseexpr/NumberBranchNode.java | 25 +-- .../node/expression/builtin/Any.java | 11 ++ .../node/expression/builtin/Builtin.java | 70 ++++++++- .../expression/builtin/bool/EqualsNode.java | 16 +- .../builtin/debug/DebugBreakpointNode.java | 2 +- .../expression/builtin/error/ArityError.java | 4 +- .../builtin/error/ThrowPanicNode.java | 2 +- .../expression/builtin/io/PrintErrNode.java | 4 +- .../expression/builtin/io/PrintlnNode.java | 2 +- .../expression/builtin/mutable/SortNode.java | 4 +- .../builtin/number/bigInteger/AddNode.java | 2 +- .../builtin/number/bigInteger/BitAndNode.java | 9 +- .../builtin/number/bigInteger/BitNotNode.java | 2 +- .../builtin/number/bigInteger/BitOrNode.java | 9 +- .../number/bigInteger/BitShiftNode.java | 9 +- .../number/bigInteger/BitShiftRightNode.java | 13 +- .../builtin/number/bigInteger/BitXorNode.java | 13 +- .../number/bigInteger/CompareToNode.java | 2 +- .../builtin/number/bigInteger/DivNode.java | 2 +- .../builtin/number/bigInteger/DivideNode.java | 2 +- .../builtin/number/bigInteger/EqualsNode.java | 15 +- .../number/bigInteger/GreaterNode.java | 2 +- .../number/bigInteger/GreaterOrEqualNode.java | 2 +- .../number/bigInteger/LessOrEqualNode.java | 2 +- .../builtin/number/bigInteger/ModNode.java | 2 +- .../number/smallInteger/BitOrNode.java | 13 +- .../number/smallInteger/BitXorNode.java | 13 +- .../number/smallInteger/CompareToNode.java | 2 +- .../number/smallInteger/LessOrEqualNode.java | 2 +- .../builtin/number/smallInteger/ModNode.java | 2 +- .../number/smallInteger/MultiplyNode.java | 2 +- .../builtin/number/smallInteger/PowNode.java | 2 +- .../number/smallInteger/SubtractNode.java | 2 +- .../expression/builtin/runtime/GCNode.java | 2 +- .../node/scope/AssignmentNode.java | 4 +- .../interpreter/runtime/builtin/Builtins.java | 146 +++++++++--------- .../interpreter/runtime/builtin/Error.java | 5 +- .../interpreter/runtime/data/EnsoFile.java | 2 +- .../enso/interpreter/runtime/data/Ref.java | 2 +- .../runtime/scope/ModuleScope.java | 7 +- .../runtime/type/TypesFromProxy.java | 31 ++-- .../interpreter/service/ExecutionService.java | 15 +- .../enso/interpreter/dsl/TypeProcessor.java | 17 +- .../builtins/ExecuteMethodImplGenerator.java | 2 +- .../builtins/SpecializedMethodsGenerator.java | 2 +- 49 files changed, 275 insertions(+), 272 deletions(-) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ArrayBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ArrayBranchNode.java index 606e2d87a39a..b4bd857dd7f9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ArrayBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ArrayBranchNode.java @@ -15,10 +15,10 @@ @NodeInfo(shortName = "ArrayMatch", description = "Allows matching on the Array type.") public abstract class ArrayBranchNode extends BranchNode { - private final AtomConstructor array; + private final Type array; private final ConditionProfile profile = ConditionProfile.createCountingProfile(); - ArrayBranchNode(AtomConstructor array, RootCallTarget branch) { + ArrayBranchNode(Type array, RootCallTarget branch) { super(branch); this.array = array; } @@ -31,13 +31,13 @@ public abstract class ArrayBranchNode extends BranchNode { * @return an array branch node */ public static ArrayBranchNode build(Type array, RootCallTarget branch) { - return ArrayBranchNodeGen.create(array, branch); + return ArrayBranchNodeGen.create(array, branch); } @Specialization - void doConstructor(VirtualFrame frame, Object state, Atom target) { - if (profile.profile(array == target.getConstructor())) { - accept(frame, state, target.getFields()); + void doType(VirtualFrame frame, Object state, Type target) { + if (profile.profile(array == target)) { + accept(frame, state, new Object[0]); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/DecimalBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/DecimalBranchNode.java index de52265461c6..2a3124aaf01c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/DecimalBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/DecimalBranchNode.java @@ -12,10 +12,10 @@ @NodeInfo(shortName = "TextMatch", description = "Allows matching on the Decimal type.") public abstract class DecimalBranchNode extends BranchNode { - private final AtomConstructor decimal; + private final Type decimal; private final ConditionProfile profile = ConditionProfile.createCountingProfile(); - DecimalBranchNode(AtomConstructor decimal, RootCallTarget branch) { + DecimalBranchNode(Type decimal, RootCallTarget branch) { super(branch); this.decimal = decimal; } @@ -32,9 +32,9 @@ public static DecimalBranchNode build(Type decimal, RootCallTarget branch) { } @Specialization - void doConstructor(VirtualFrame frame, Object state, Atom target) { - if (profile.profile(decimal == target.getConstructor())) { - accept(frame, state, target.getFields()); + void doType(VirtualFrame frame, Object state, Type target) { + if (profile.profile(decimal == target)) { + accept(frame, state, new Object[0]); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/FileBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/FileBranchNode.java index 86b3e4baf201..640ab7b522c7 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/FileBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/FileBranchNode.java @@ -13,10 +13,10 @@ @NodeInfo(shortName = "FileMatch", description = "Allows matching on the File type.") public abstract class FileBranchNode extends BranchNode { - private final AtomConstructor file; + private final Type file; private final ConditionProfile profile = ConditionProfile.createCountingProfile(); - FileBranchNode(AtomConstructor file, RootCallTarget branch) { + FileBranchNode(Type file, RootCallTarget branch) { super(branch); this.file = file; } @@ -33,9 +33,9 @@ public static FileBranchNode build(Type file, RootCallTarget branch) { } @Specialization - void doConstructor(VirtualFrame frame, Object state, Atom target) { - if (profile.profile(file == target.getConstructor())) { - accept(frame, state, target.getFields()); + void doType(VirtualFrame frame, Object state, Type target) { + if (profile.profile(file == target)) { + accept(frame, state, new Object[0]); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/IntegerBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/IntegerBranchNode.java index 2d25a307ebb1..fd9f4d41fce3 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/IntegerBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/IntegerBranchNode.java @@ -9,13 +9,14 @@ import org.enso.interpreter.runtime.builtin.Number; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.number.EnsoBigInteger; @NodeInfo(shortName = "IntegerMatch", description = "Allows matching on the Integer type.") public abstract class IntegerBranchNode extends BranchNode { - private final AtomConstructor integer; - private final AtomConstructor smallInteger; - private final AtomConstructor bigInteger; + private final Type integer; + private final Type smallInteger; + private final Type bigInteger; private final ConditionProfile profile = ConditionProfile.createCountingProfile(); public IntegerBranchNode(Number number, RootCallTarget branch) { @@ -37,13 +38,10 @@ public static IntegerBranchNode build(Number number, RootCallTarget branch) { } @Specialization - void doConstructor(VirtualFrame frame, Object state, Atom target) { - var shouldMatch = - (integer == target.getConstructor()) - || (smallInteger == target.getConstructor()) - || (bigInteger == target.getConstructor()); + void doType(VirtualFrame frame, Object state, Type target) { + var shouldMatch = (integer == target) || (smallInteger == target) || (bigInteger == target); if (profile.profile(shouldMatch)) { - accept(frame, state, target.getFields()); + accept(frame, state, new Object[0]); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/NumberBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/NumberBranchNode.java index c39b966bc9e6..06854deca4c6 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/NumberBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/NumberBranchNode.java @@ -9,15 +9,16 @@ import org.enso.interpreter.runtime.builtin.Number; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.number.EnsoBigInteger; @NodeInfo(shortName = "NumberMatch", description = "Allows matching on the Number type.") public abstract class NumberBranchNode extends BranchNode { - private final AtomConstructor number; - private final AtomConstructor integer; - private final AtomConstructor bigInteger; - private final AtomConstructor smallInteger; - private final AtomConstructor decimal; + private final Type number; + private final Type integer; + private final Type bigInteger; + private final Type smallInteger; + private final Type decimal; private final ConditionProfile profile = ConditionProfile.createCountingProfile(); NumberBranchNode(Number number, RootCallTarget branch) { @@ -41,15 +42,15 @@ public static NumberBranchNode build(Number number, RootCallTarget branch) { } @Specialization - void doConstructor(VirtualFrame frame, Object state, Atom target) { + void doType(VirtualFrame frame, Object state, Type target) { var shouldMatch = - (target.getConstructor() == number) - || (target.getConstructor() == integer) - || (target.getConstructor() == bigInteger) - || (target.getConstructor() == smallInteger) - || (target.getConstructor() == decimal); + (target == number) + || (target == integer) + || (target == bigInteger) + || (target == smallInteger) + || (target == decimal); if (profile.profile(shouldMatch)) { - accept(frame, state, target.getFields()); + accept(frame, state, new Object[0]); } } 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..c06321696074 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Any.java @@ -0,0 +1,11 @@ +package org.enso.interpreter.node.expression.builtin; + +import org.enso.interpreter.dsl.BuiltinType; + +@BuiltinType(name = "Standard.Base.Any.Any") +public class Any extends Builtin { + @Override + public Class getSuperType() { + return null; + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java index d1bf8e73475b..6167156b3f3e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java @@ -1,4 +1,72 @@ package org.enso.interpreter.node.expression.builtin; +import com.oracle.truffle.api.CompilerDirectives; +import org.enso.interpreter.runtime.callable.argument.ArgumentDefinition; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; +import org.enso.interpreter.runtime.scope.ModuleScope; + +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + /** A base class for all classes annotated with @BuiltinType */ -public abstract class Builtin {} +public abstract class Builtin { + public record Cons(String name, List params) { + private AtomConstructor build(ModuleScope scope) { + var res = new AtomConstructor(name, scope, true); + res.initializeFields( + IntStream.range(0, params.size()) + .mapToObj( + i -> + new ArgumentDefinition( + i, params.get(i), ArgumentDefinition.ExecutionMode.EXECUTE)) + .toArray(ArgumentDefinition[]::new)); + return res; + } + } + + private String name; + + private @CompilerDirectives.CompilationFinal Type type; + private @CompilerDirectives.CompilationFinal(dimensions = 1) AtomConstructor[] constructors; + + public final void setName(String name) { + this.name = name; + } + + protected Class getSuperType() { + return Any.class; + } + + protected List getDeclaredConstructors() { + return List.of(); + } + + public final void initialize(ModuleScope scope, Map, Builtin> builtins) { + if (type == null) { + Type supertype = null; + if (getSuperType() != null) { + var s = builtins.get(getSuperType()); + s.initialize(scope, builtins); + supertype = s.getType(); + } + type = new Type(name, scope, supertype, true); + } + if (constructors == null) { + var conses = getDeclaredConstructors(); + constructors = new AtomConstructor[conses.size()]; + for (int i = 0; i < constructors.length; i++) { + constructors[i] = conses.get(i).build(scope); + } + } + } + + public Type getType() { + return type; + } + + public AtomConstructor[] getConstructors() { + return constructors; + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java index 60ff9a311dbd..03529b2c59e5 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java @@ -11,7 +11,7 @@ @BuiltinMethod(type = "Boolean", name = "==", description = "Computes the equality of two booleans") public abstract class EqualsNode extends Node { - abstract boolean execute(Object self, Object that); + abstract boolean execute(boolean self, Object that); static EqualsNode build() { return EqualsNodeGen.create(); @@ -22,20 +22,8 @@ boolean doBoolean(boolean self, boolean that) { return self == that; } - @Specialization - boolean doAtom( - Atom self, Atom that, @Cached("getBooleanConstructor()") AtomConstructor boolCons) { - var thisCons = self.getConstructor(); - var thatCons = that.getConstructor(); - return (thatCons == boolCons) && (thisCons == thatCons); - } - @Fallback - boolean doOther(Object self, Object that) { + boolean doOther(boolean self, Object that) { return false; } - - AtomConstructor getBooleanConstructor() { - return Context.get(this).getBuiltins().bool().getBool(); - } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/DebugBreakpointNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/DebugBreakpointNode.java index d5360de1fe90..e887e60e0aa0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/DebugBreakpointNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/debug/DebugBreakpointNode.java @@ -41,7 +41,7 @@ abstract Stateful execute( @Specialization Stateful doExecute(VirtualFrame frame, CallerInfo callerInfo, Object state, Object self) { - return new Stateful(state, Context.get(this).getNothing().newInstance()); + return new Stateful(state, Context.get(this).getNothing()); } /** diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java index 648857beb36f..7e5a87a5b598 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java @@ -4,4 +4,6 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = {"expected_min", "expected_max", "actual"}) -public class ArityError extends Builtin {} +public class ArityError extends Builtin { +// @BuiltinData(params = {""}) +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ThrowPanicNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ThrowPanicNode.java index c4b1ff5d7bc1..a408568275bb 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ThrowPanicNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ThrowPanicNode.java @@ -30,7 +30,7 @@ Context getContext() { return Context.get(this); } - @Specialization(guards = {"payload.getConstructor() == getContext().getBuiltins().caughtPanic()"}) + @Specialization(guards = {"payload.getConstructor().getType() == getContext().getBuiltins().caughtPanic()"}) Stateful doCaughtPanic( Object self, Atom payload, diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintErrNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintErrNode.java index 670f73f39bcb..73f35a2e3ec7 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintErrNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintErrNode.java @@ -45,7 +45,7 @@ Stateful doPrintText( } catch (UnsupportedMessageException e) { throw new IllegalStateException("Impossible. self is guaranteed to be a string"); } - return new Stateful(state, ctx.getNothing().newInstance()); + return new Stateful(state, ctx.getNothing()); } @Specialization(guards = "!strings.isString(message)") @@ -61,7 +61,7 @@ Stateful doPrint( Stateful str = invokeCallableNode.execute(symbol, frame, state, new Object[] {message}); Context ctx = Context.get(this); print(ctx.getErr(), expectStringNode.execute(str.getValue())); - return new Stateful(str.getState(), ctx.getNothing().newInstance()); + return new Stateful(str.getState(), ctx.getNothing()); } @CompilerDirectives.TruffleBoundary diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintlnNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintlnNode.java index b2fa70926947..e2b80cb6033e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintlnNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintlnNode.java @@ -60,7 +60,7 @@ Stateful doPrint( Stateful str = invokeCallableNode.execute(symbol, frame, state, new Object[] {message}); Context ctx = Context.get(this); print(ctx.getOut(), expectStringNode.execute(str.getValue())); - return new Stateful(str.getState(), ctx.getNothing().newInstance()); + return new Stateful(str.getState(), ctx.getNothing()); } boolean isText(Object o) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/SortNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/SortNode.java index 86c051f28851..fcd7cb2b6f23 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/SortNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/SortNode.java @@ -46,13 +46,13 @@ Object doSortCallable(VirtualFrame frame, Array self, Object comparator) { @Specialization Object doAtomThis(VirtualFrame frame, Atom self, Object that) { - return Context.get(this).getBuiltins().nothing().newInstance(); + return Context.get(this).getBuiltins().nothing(); } Object runSort(Comparator compare, Array self, Context context) { doSort(self.getItems(), compare); LoopNode.reportLoopCount(this, (int) self.length()); - return context.getBuiltins().nothing().newInstance(); + return context.getBuiltins().nothing(); } @TruffleBoundary diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/AddNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/AddNode.java index 6de37e948d3e..7cdf6ed77d27 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/AddNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/AddNode.java @@ -40,7 +40,7 @@ Object doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { @Fallback Object doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitAndNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitAndNode.java index f6bddd8875d8..f33e8ca33ea4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitAndNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitAndNode.java @@ -32,17 +32,10 @@ Object doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { return toEnsoNumberNode.execute(BigIntegerOps.bitAnd(self.getValue(), that.getValue())); } - @Specialization - Object doAtomThis(Atom self, Object that) { - Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); - throw new PanicException(builtins.error().makeTypeError(integer, self, "this"), this); - } - @Fallback Object doOther(Object self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitNotNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitNotNode.java index 7889e4b8f882..a8179a78f0bb 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitNotNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitNotNode.java @@ -26,7 +26,7 @@ EnsoBigInteger doLong(EnsoBigInteger self) { @Fallback Object doOther(Object self) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, self, "this"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitOrNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitOrNode.java index 89c4e64ecca7..a3fcd15c02b1 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitOrNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitOrNode.java @@ -32,17 +32,10 @@ Object doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { return toEnsoNumberNode.execute(BigIntegerOps.bitOr(self.getValue(), that.getValue())); } - @Specialization - Object doAtomThis(Atom self, Object that) { - Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); - throw new PanicException(builtins.error().makeTypeError(integer, self, "this"), this); - } - @Fallback Object doOther(Object self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, that, "that"), this); } } 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 374d64007ec3..2038e400a662 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 @@ -74,17 +74,10 @@ Object doBigIntThat(EnsoBigInteger self, EnsoBigInteger that) { } } - @Specialization - Object doAtomThis(Atom self, Object that) { - Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); - throw new PanicException(builtins.error().makeTypeError(integer, self, "this"), this); - } - @Fallback Object doOther(Object self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftRightNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftRightNode.java index 313df14105ac..9fa0f7225f8d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftRightNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitShiftRightNode.java @@ -14,7 +14,7 @@ @BuiltinMethod(type = "Big_Integer", name = "bit_shift_r", description = "Bitwise right-shift.") public abstract class BitShiftRightNode extends Node { - abstract Object execute(Object self, Object that); + abstract Object execute(EnsoBigInteger self, Object that); static BitShiftRightNode build() { return BitShiftRightNodeGen.create(); @@ -32,17 +32,10 @@ Object doBigInteger( return bitShiftNode.execute(self, new EnsoBigInteger(BigIntegerOps.negate(that.getValue()))); } - @Specialization - Object doAtomThis(Atom self, Object that) { - Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); - throw new PanicException(builtins.error().makeTypeError(integer, self, "this"), this); - } - @Fallback - Object doOther(Object self, Object that) { + Object doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitXorNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitXorNode.java index ee890805ecb4..8516a8bb2390 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitXorNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/BitXorNode.java @@ -16,7 +16,7 @@ public abstract class BitXorNode extends Node { private @Child ToEnsoNumberNode toEnsoNumberNode = ToEnsoNumberNode.build(); - abstract Object execute(Object self, Object that); + abstract Object execute(EnsoBigInteger self, Object that); static BitXorNode build() { return BitXorNodeGen.create(); @@ -32,17 +32,10 @@ Object doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { return toEnsoNumberNode.execute(BigIntegerOps.bitXor(self.getValue(), that.getValue())); } - @Specialization - Object doAtomThis(Atom self, Object that) { - Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); - throw new PanicException(builtins.error().makeTypeError(integer, self, "this"), this); - } - @Fallback - Object doOther(Object self, Object that) { + Object doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java index 2261c960b6e5..56fc8c16220b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java @@ -41,7 +41,7 @@ Atom doDecimal(EnsoBigInteger self, double that) { @Specialization Atom doOther(EnsoBigInteger self, Object that) { CompilerDirectives.transferToInterpreter(); - var number = Context.get(this).getBuiltins().number().getNumber().newInstance(); + var number = Context.get(this).getBuiltins().number().getNumber(); var typeError = Context.get(this).getBuiltins().error().makeTypeError(that, number, "that"); throw new PanicException(typeError, this); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/DivNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/DivNode.java index 68bceb947758..9b76fbd407fc 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/DivNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/DivNode.java @@ -42,7 +42,7 @@ Object doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { @Fallback Object doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/DivideNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/DivideNode.java index 9695bb51173f..7f01d1eab63d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/DivideNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/DivideNode.java @@ -37,7 +37,7 @@ static DivideNode build() { @Fallback double doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/EqualsNode.java index 2577fb835b17..bcf5ce4639cc 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/EqualsNode.java @@ -14,7 +14,7 @@ @BuiltinMethod(type = "Big_Integer", name = "==", description = "Big integer equality.") public abstract class EqualsNode extends Node { - abstract boolean execute(Object self, Object that); + abstract boolean execute(EnsoBigInteger self, Object that); static EqualsNode build() { return EqualsNodeGen.create(); @@ -30,20 +30,9 @@ boolean doDouble(EnsoBigInteger self, double that) { return BigIntegerOps.toDouble(self.getValue()) == that; } - @Specialization - boolean doAtom( - Atom self, Atom that, @Cached("getBigIntegerConstructor()") AtomConstructor bigIntCons) { - var thisCons = self.getConstructor(); - var thatCons = that.getConstructor(); - return (thatCons == bigIntCons) && (thisCons == thatCons); - } - @Fallback - boolean doOther(Object self, Object that) { + boolean doOther(EnsoBigInteger self, Object that) { return false; } - AtomConstructor getBigIntegerConstructor() { - return Context.get(this).getBuiltins().number().getBigInteger(); - } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/GreaterNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/GreaterNode.java index d9226b563383..d0fa830261ca 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/GreaterNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/GreaterNode.java @@ -38,7 +38,7 @@ boolean doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { @Fallback boolean doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/GreaterOrEqualNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/GreaterOrEqualNode.java index 331b4c59fc2b..06dc9d39fbb6 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/GreaterOrEqualNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/GreaterOrEqualNode.java @@ -38,7 +38,7 @@ boolean doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { @Fallback boolean doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/LessOrEqualNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/LessOrEqualNode.java index ef39eeb1198a..1c1b3c9ab2d9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/LessOrEqualNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/LessOrEqualNode.java @@ -38,7 +38,7 @@ boolean doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { @Fallback boolean doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/ModNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/ModNode.java index 7446717a266f..6f5b98da261f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/ModNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/ModNode.java @@ -49,7 +49,7 @@ Object doBigInteger(EnsoBigInteger self, EnsoBigInteger that) { @Fallback Object doOther(EnsoBigInteger self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitOrNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitOrNode.java index 4ef52e898b8e..d9e42fda6a29 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitOrNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitOrNode.java @@ -16,7 +16,7 @@ public abstract class BitOrNode extends Node { private @Child ToEnsoNumberNode toEnsoNumberNode = ToEnsoNumberNode.build(); - abstract Object execute(Object self, Object that); + abstract Object execute(long self, Object that); static BitOrNode build() { return BitOrNodeGen.create(); @@ -32,17 +32,10 @@ Object doBigInteger(long self, EnsoBigInteger that) { return toEnsoNumberNode.execute(BigIntegerOps.bitOr(self, that.getValue())); } - @Specialization - Object doAtomThis(Atom self, Object that) { - Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); - throw new PanicException(builtins.error().makeTypeError(integer, self, "this"), this); - } - @Fallback - Object doOther(Object self, Object that) { + Object doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitXorNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitXorNode.java index 3234879b3267..350e1915c69a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitXorNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/BitXorNode.java @@ -16,7 +16,7 @@ public abstract class BitXorNode extends Node { private @Child ToEnsoNumberNode toEnsoNumberNode = ToEnsoNumberNode.build(); - abstract Object execute(Object self, Object that); + abstract Object execute(long self, Object that); static BitXorNode build() { return BitXorNodeGen.create(); @@ -32,17 +32,10 @@ Object doBigInteger(long self, EnsoBigInteger that) { return toEnsoNumberNode.execute(BigIntegerOps.bitXor(self, that.getValue())); } - @Specialization - Object doAtomThis(Atom self, Object that) { - Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); - throw new PanicException(builtins.error().makeTypeError(integer, self, "this"), this); - } - @Fallback - Object doOther(Object self, Object that) { + Object doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom integer = builtins.number().getInteger().newInstance(); + var integer = builtins.number().getInteger(); throw new PanicException(builtins.error().makeTypeError(integer, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java index dd8dc6c379df..512f9dbd9be1 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java @@ -53,7 +53,7 @@ Atom doDecimal(long self, double that) { @Specialization Atom doOther(long self, Object that) { CompilerDirectives.transferToInterpreter(); - var number = Context.get(this).getBuiltins().number().getNumber().newInstance(); + var number = Context.get(this).getBuiltins().number().getNumber(); var typeError = Context.get(this).getBuiltins().error().makeTypeError(that, number, "that"); throw new PanicException(typeError, this); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/LessOrEqualNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/LessOrEqualNode.java index 4fea24584819..f5326df967dc 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/LessOrEqualNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/LessOrEqualNode.java @@ -37,7 +37,7 @@ boolean doBigInteger(long self, EnsoBigInteger that) { @Fallback boolean doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/ModNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/ModNode.java index 03b8e8999545..9256348516b5 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/ModNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/ModNode.java @@ -45,7 +45,7 @@ long doBigInteger(long self, EnsoBigInteger that) { @Fallback Object doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/MultiplyNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/MultiplyNode.java index 84a230dcb625..6c728b2fcf8d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/MultiplyNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/MultiplyNode.java @@ -45,7 +45,7 @@ Object doBigInteger(long self, EnsoBigInteger that) { @Fallback Object doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/PowNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/PowNode.java index 6b327f69a03d..72b18f80ef5c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/PowNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/PowNode.java @@ -74,7 +74,7 @@ Object doBigInteger(long self, EnsoBigInteger that) { @Fallback Object doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/SubtractNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/SubtractNode.java index 5e84212bf1d5..e67dd27aa5d8 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/SubtractNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/SubtractNode.java @@ -45,7 +45,7 @@ Object doBigInteger(long self, EnsoBigInteger that) { @Fallback Object doOther(long self, Object that) { Builtins builtins = Context.get(this).getBuiltins(); - Atom number = builtins.number().getNumber().newInstance(); + var number = builtins.number().getNumber(); throw new PanicException(builtins.error().makeTypeError(number, that, "that"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/runtime/GCNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/runtime/GCNode.java index c3278b01b7df..79339af559d8 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/runtime/GCNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/runtime/GCNode.java @@ -19,7 +19,7 @@ public static GCNode build() { @Specialization Object doGc(Object self) { runGC(); - return Context.get(this).getBuiltins().nothing().newInstance(); + return Context.get(this).getBuiltins().nothing(); } @CompilerDirectives.TruffleBoundary diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/scope/AssignmentNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/scope/AssignmentNode.java index 0a520b25c8c6..9ff6b0284ffb 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/scope/AssignmentNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/scope/AssignmentNode.java @@ -40,7 +40,7 @@ protected Object writeLong(VirtualFrame frame, long value) { frame.getFrameDescriptor().setFrameSlotKind(getFrameSlot(), FrameSlotKind.Long); frame.setLong(getFrameSlot(), value); - return Context.get(this).getNothing().newInstance(); + return Context.get(this).getNothing(); } /** @@ -55,7 +55,7 @@ protected Object writeObject(VirtualFrame frame, Object value) { frame.getFrameDescriptor().setFrameSlotKind(getFrameSlot(), FrameSlotKind.Object); frame.setObject(getFrameSlot(), value); - return Context.get(this).getNothing().newInstance(); + return Context.get(this).getNothing(); } boolean isLongOrIllegal(VirtualFrame frame) { 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 68b98ee10142..e0933545f93a 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 @@ -6,6 +6,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.util.*; @@ -52,7 +53,8 @@ public static class Debug { } private final Map>> builtinMethodNodes; - private final Map builtins; + private final Map, Builtin> builtins; + private final Map builtinsByName; private final Error error; private final Module module; @@ -64,19 +66,19 @@ public static class Debug { private final Special special; // Builtin types - private final Type any; - private final BuiltinType nothing; - private final BuiltinType function; - private final BuiltinType polyglot; - private final BuiltinType text; - private final BuiltinType array; - private final BuiltinType dataflowError; - private final BuiltinType ref; - private final BuiltinType managedResource; - private final BuiltinType debug; - private final BuiltinType projectDescription; - private final BuiltinType file; - private final BuiltinType warning; + private final Builtin any; + private final Builtin nothing; + private final Builtin function; + private final Builtin polyglot; + private final Builtin text; + private final Builtin array; + private final Builtin dataflowError; + private final Builtin ref; + private final Builtin managedResource; + private final Builtin debug; + private final Builtin projectDescription; + private final Builtin file; + private final Builtin warning; /** * Creates an instance with builtin methods installed. @@ -88,11 +90,11 @@ public Builtins(Context context) { module = Module.empty(QualifiedName.fromString(MODULE_NAME), null); scope = module.compileScope(context); - builtins = new HashMap<>(); - any = new Type("Any", scope, true); - var builtinTypes = readBuiltinTypesMetadata(scope); + builtins = readBuiltinTypesMetadata(scope); + builtinsByName = + builtins.values().stream().collect(Collectors.toMap(v -> v.getType().getName(), v -> v)); builtinMethodNodes = readBuiltinMethodsMetadata(scope); - registerBuiltinMethods(builtinTypes, scope, language); + registerBuiltinMethods(scope, language); error = new Error(this); ordering = new Ordering(this); @@ -100,20 +102,20 @@ public Builtins(Context context) { number = new Number(this); bool = new Bool(this); - nothing = new BuiltinType(this, Nothing.class); - function = - new BuiltinType(this, org.enso.interpreter.node.expression.builtin.function.Function.class); - polyglot = new BuiltinType(this, Polyglot.class); - text = new BuiltinType(this, Text.class); - array = new BuiltinType(this, Array.class); - dataflowError = new BuiltinType(this, org.enso.interpreter.node.expression.builtin.Error.class); - ref = new BuiltinType(this, Ref.class); - managedResource = new BuiltinType(this, ManagedResource.class); - debug = new BuiltinType(this, Debug.class); - projectDescription = new BuiltinType(this, ProjectDescription.class); - file = new BuiltinType(this, File.class); + any = builtins.get(Any.class); + nothing = builtins.get(Nothing.class); + function = builtins.get(org.enso.interpreter.node.expression.builtin.function.Function.class); + polyglot = builtins.get(Polyglot.class); + text = builtins.get(Text.class); + array = builtins.get(Array.class); + dataflowError = builtins.get(org.enso.interpreter.node.expression.builtin.Error.class); + ref = builtins.get(Ref.class); + managedResource = builtins.get(ManagedResource.class); + debug = builtins.get(Debug.class); + projectDescription = builtins.get(ProjectDescription.class); + file = builtins.get(File.class); special = new Special(language); - warning = new BuiltinType(this, Warning.class); + warning = builtins.get(Warning.class); } /** @@ -121,14 +123,13 @@ public Builtins(Context context) { * "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 (Type type : builtins) { + private void registerBuiltinMethods(ModuleScope scope, Language language) { + for (Builtin builtin : builtins.values()) { + var type = builtin.getType(); String tpeName = type.getName(); - this.builtins.put(tpeName, type); Map> methods = builtinMethodNodes.get(tpeName); if (methods != null) { methods.forEach( @@ -188,7 +189,7 @@ public void initializeBuiltinsIr(FreshNameSupply freshNameSupply, Passes passes) * * @param scope Builtins scope */ - private List readBuiltinTypesMetadata(ModuleScope scope) { + private Map, Builtin> readBuiltinTypesMetadata(ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); List lines; try (InputStream resource = classLoader.getResourceAsStream(TypeProcessor.META_PATH)) { @@ -201,34 +202,32 @@ private List readBuiltinTypesMetadata(ModuleScope scope) { 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); - } - - return new Type(builtinMeta[0], scope, true); - }) - // 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; - // }) - .collect(Collectors.toList()); + Map, Builtin> builtins = + lines.stream() + .map( + line -> { + String[] builtinMeta = line.split(":"); + if (builtinMeta.length != 3) { + throw new CompilerError("Invalid builtin metadata in: " + line); + } + try { + @SuppressWarnings("unchecked") + var cls = (Class) Class.forName(builtinMeta[1]); + var builtin = cls.getConstructor().newInstance(); + builtin.setName(builtinMeta[0]); + return builtin; + } catch (NoSuchMethodException + | InstantiationException + | IllegalAccessException + | InvocationTargetException + | ClassNotFoundException e) { + e.printStackTrace(); + throw new CompilerError("Invalid builtin type entry: " + builtinMeta[1]); + } + }) + .collect(Collectors.toMap(Builtin::getClass, b -> b)); + builtins.values().forEach(b -> b.initialize(scope, builtins)); + return builtins; } /** @@ -325,13 +324,12 @@ public Optional getBuiltinFunction(Type type, String methodName, Langu } } - public Type getBuiltinType(Class clazz) { - String snakeCaseName = clazz.getSimpleName().replaceAll("([^_A-Z])([A-Z])", "$1_$2"); - return getBuiltinType(snakeCaseName); + public Builtin getBuiltinType(Class clazz) { + return builtins.get(clazz); } - public Type getBuiltinType(String name) { - return builtins.get(name); + public Builtin getBuiltinType(String name) { + return builtinsByName.get(name); } /** @@ -397,7 +395,7 @@ public Error error() { * @return the {@code Any} atom constructor */ public Type any() { - return any; + return any.getType(); } /** @@ -466,14 +464,14 @@ public Type polyglot() { /** * @return the {@code Caught_Panic} atom constructor */ - public AtomConstructor caughtPanic() { + public Type caughtPanic() { return this.error.caughtPanic(); } /** * @return the {@code Panic} atom constructor */ - public AtomConstructor panic() { + public Type panic() { return this.error.panic(); } @@ -509,13 +507,13 @@ public Module getModule() { } /** - * Convert from type-system type names to atoms. + * Convert from type-system type names to types. * * @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) { + public Type fromTypeSystem(String typeName) { return TypesFromProxy.fromTypeSystem(this, typeName); } } 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 ec2001cc73fb..668522199cf7 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 @@ -8,6 +8,7 @@ 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.Type; import org.enso.interpreter.runtime.data.text.Text; import static com.oracle.truffle.api.CompilerDirectives.transferToInterpreterAndInvalidate; @@ -86,11 +87,11 @@ public Atom makeModuleNotInPackageError() { return moduleNotInPackageError.newInstance(); } - public AtomConstructor panic() { + public Type panic() { return panic.getType(); } - public AtomConstructor caughtPanic() { + public Type caughtPanic() { return caughtPanic.getType(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoFile.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoFile.java index 824345f57a2c..a64325a55373 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoFile.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoFile.java @@ -192,7 +192,7 @@ static class GetFunctionalDispatch { @CompilerDirectives.TruffleBoundary static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().file(), context.getBuiltins().any()); + return symbol.resolveFor(context.getBuiltins().file()); } static Context getContext() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Ref.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Ref.java index e318ba51befb..f782cc01ab74 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Ref.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Ref.java @@ -59,7 +59,7 @@ static class GetFunctionalDispatch { @CompilerDirectives.TruffleBoundary static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().ref(), context.getBuiltins().any()); + return symbol.resolveFor(context.getBuiltins().ref()); } 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 79728166a85f..2b7a5ec084fb 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 @@ -47,7 +47,6 @@ public void registerType(Type type) { types.put(type.getName(), type); } - /** * @return the associated type of this module. */ @@ -288,7 +287,11 @@ public Map getTypes() { return types; } - /** + public Optional getType(String name) { + return Optional.ofNullable(types.get(name)); + } + + /** * @return the raw method map held by this module */ public Map> getMethods() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java index ef70b97b891b..51d783ab2899 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java @@ -3,6 +3,7 @@ import org.enso.compiler.exception.CompilerError; import org.enso.interpreter.runtime.builtin.Builtins; import org.enso.interpreter.runtime.callable.atom.Atom; +import org.enso.interpreter.runtime.data.Type; /** * TypesFromProxy provides a single static method `fromTypeSystem` which converts from type-system @@ -26,36 +27,36 @@ public class TypesFromProxy { * @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) { + public static Type fromTypeSystem(Builtins builtins, String typeName) { switch (typeName) { case ConstantsGen.ANY: - return builtins.any().newInstance(); + return builtins.any(); case ConstantsGen.ARRAY: - return builtins.array().newInstance(); + return builtins.array(); case ConstantsGen.BOOLEAN: - return builtins.bool().getBool().newInstance(); + return builtins.bool().getBool(); case ConstantsGen.DECIMAL: - return builtins.number.getDecimal().newInstance(); + return builtins.number.getDecimal(); case ConstantsGen.ERROR: - return builtins.dataflowError().newInstance(); + return builtins.dataflowError(); case ConstantsGen.FUNCTION: - return builtins.function().newInstance(); + return builtins.function(); case ConstantsGen.FILE: - return builtins.file().newInstance(); + return builtins.file(); case ConstantsGen.INTEGER: - return builtins.number.getInteger().newInstance(); + return builtins.number.getInteger(); case ConstantsGen.MANAGED_RESOURCE: - return builtins.managedResource().newInstance(); + return builtins.managedResource(); case ConstantsGen.NOTHING: - return builtins.nothing().newInstance(); + return builtins.nothing(); case ConstantsGen.NUMBER: - return builtins.number.getNumber().newInstance(); + return builtins.number.getNumber(); case ConstantsGen.PANIC: - return builtins.panic().newInstance(); + return builtins.panic(); case ConstantsGen.REF: - return builtins.ref().newInstance(); + return builtins.ref(); case ConstantsGen.TEXT: - return builtins.text().newInstance(); + return builtins.text(); default: throw new CompilerError("Invalid builtin type " + typeName); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java b/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java index cf48c92f4693..217b12aa6f06 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java @@ -29,6 +29,7 @@ import org.enso.interpreter.runtime.Module; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.error.PanicException; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.interpreter.runtime.state.data.EmptyMap; @@ -91,20 +92,20 @@ public TruffleLogger getLogger() { } private FunctionCallInstrumentationNode.FunctionCall prepareFunctionCall( - Module module, String consName, String methodName) + Module module, String typeName, String methodName) throws ConstructorNotFoundException, MethodNotFoundException { ModuleScope scope = module.compileScope(context); - AtomConstructor atomConstructor = + Type type = scope - .getConstructor(consName) + .getType(typeName) .orElseThrow( - () -> new ConstructorNotFoundException(module.getName().toString(), consName)); - Function function = scope.lookupMethodDefinition(atomConstructor, methodName); + () -> new ConstructorNotFoundException(module.getName().toString(), typeName)); + Function function = scope.lookupMethodDefinition(type, methodName); if (function == null) { - throw new MethodNotFoundException(module.getName().toString(), atomConstructor, methodName); + throw new MethodNotFoundException(module.getName().toString(), type, methodName); } return new FunctionCallInstrumentationNode.FunctionCall( - function, EmptyMap.create(), new Object[] {atomConstructor.newInstance()}); + function, EmptyMap.create(), new Object[] {type}); } public void initializeLanguageServerConnection(Endpoint endpoint) { diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java index 23581daa2705..992be7857476 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -24,12 +24,10 @@ public class TypeProcessor extends BuiltinsMetadataProcessor pastE + ":" + constr.getTpeName() + ":" - + StringUtils.join(Arrays.asList(constr.getParamNames()), ",") - + ":" + constr.getFullName() + "\n"); if (pastEntries.containsKey(entry.getKey())) { @@ -154,13 +145,13 @@ protected void storeMetadata(Writer writer, Map pastE } protected void registerBuiltinType( - Filer f, String name, String clazzName, String fullName, String[] params) { + Filer f, String name, String clazzName, String fullName) { Map classes = builtinTypes.get(f); if (classes == null) { classes = new HashMap<>(); builtinTypes.put(f, classes); } - classes.put(name, new BuiltinTypeConstr(clazzName, fullName, params)); + classes.put(name, new BuiltinTypeConstr(clazzName, fullName)); } @Override diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/ExecuteMethodImplGenerator.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/ExecuteMethodImplGenerator.java index 3b380491fb6b..5043024d887f 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/ExecuteMethodImplGenerator.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/ExecuteMethodImplGenerator.java @@ -104,7 +104,7 @@ private String[] bodyBase(String name, String owner, List param case VOID: return new String[] { " " + qual + "." + name + "(" + paramsApplied + ");", - " return Context.get(this).getBuiltins().nothing().newInstance();" + " return Context.get(this).getBuiltins().nothing();" }; case ARRAY: return new String[] { diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializedMethodsGenerator.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializedMethodsGenerator.java index 74847d6243ca..3f6c09cd8613 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializedMethodsGenerator.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializedMethodsGenerator.java @@ -272,7 +272,7 @@ protected List specialize( switch (returnTpe.kind()) { case VOID: methodBody.add(" " + qual + "." + name + "(" + paramsApplied + ");"); - methodBody.add(" return Context.get(this).getBuiltins().nothing().newInstance();"); + methodBody.add(" return Context.get(this).getBuiltins().nothing();"); break; case ARRAY: methodBody.add( From 2ce6fd2cdfad21ac993f4d8cac394376969488f7 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 29 Jul 2022 15:52:07 +0200 Subject: [PATCH 021/110] keep fighting the compiler --- .../node/expression/builtin/Builtin.java | 14 ++ .../builtin/bool/CompareToNode.java | 1 - .../builtin/error/CatchPanicNode.java | 3 +- .../builtin/error/ThrowPanicNode.java | 5 +- .../expression/builtin/io/PrintlnNode.java | 2 +- .../builtin/meta/ProjectDescription.java | 11 +- .../builtin/mutable/ComparatorNode.java | 1 - .../number/bigInteger/CompareToNode.java | 1 - .../builtin/number/decimal/CompareToNode.java | 1 - .../number/smallInteger/CompareToNode.java | 1 - .../expression/builtin/ordering/Ordering.java | 69 +++++++++- .../expression/constant/EnsoProjectNode.java | 7 +- .../runtime/builtin/BuiltinType.java | 8 +- .../interpreter/runtime/builtin/Builtins.java | 22 ++-- .../interpreter/runtime/builtin/Error.java | 120 +++++++++--------- .../interpreter/runtime/builtin/Ordering.java | 76 ----------- .../interpreter/runtime/builtin/System.java | 11 +- .../runtime/data/ManagedResource.java | 11 +- 18 files changed, 194 insertions(+), 170 deletions(-) delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java index 6167156b3f3e..b72bec513d8d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java @@ -2,10 +2,12 @@ import com.oracle.truffle.api.CompilerDirectives; 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.Type; import org.enso.interpreter.runtime.scope.ModuleScope; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.IntStream; @@ -13,6 +15,10 @@ /** A base class for all classes annotated with @BuiltinType */ public abstract class Builtin { public record Cons(String name, List params) { + public Cons(String name, String... params) { + this(name, Arrays.asList(params)); + } + private AtomConstructor build(ModuleScope scope) { var res = new AtomConstructor(name, scope, true); res.initializeFields( @@ -30,6 +36,7 @@ private AtomConstructor build(ModuleScope scope) { private @CompilerDirectives.CompilationFinal Type type; private @CompilerDirectives.CompilationFinal(dimensions = 1) AtomConstructor[] constructors; + private @CompilerDirectives.CompilationFinal AtomConstructor uniqueConstructor; public final void setName(String name) { this.name = name; @@ -59,6 +66,9 @@ public final void initialize(ModuleScope scope, Map, Bu for (int i = 0; i < constructors.length; i++) { constructors[i] = conses.get(i).build(scope); } + if (constructors.length == 1) { + uniqueConstructor = constructors[0]; + } } } @@ -69,4 +79,8 @@ public Type getType() { public AtomConstructor[] getConstructors() { return constructors; } + + public AtomConstructor getUniqueConstructor() { + return uniqueConstructor; + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java index e6667511e5c7..c5e8956f80a1 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java @@ -5,7 +5,6 @@ import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.builtin.Ordering; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.error.PanicException; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CatchPanicNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CatchPanicNode.java index 84598e24edb4..b3fd5e039259 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CatchPanicNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CatchPanicNode.java @@ -77,7 +77,8 @@ private Stateful executeCallback( Object payload, AbstractTruffleException originalException) { Builtins builtins = Context.get(this).getBuiltins(); - Atom caughtPanic = builtins.caughtPanic().newInstance(payload, originalException); + Atom caughtPanic = + builtins.caughtPanic().getUniqueConstructor().newInstance(payload, originalException); return invokeCallableNode.execute(handler, frame, state, new Object[] {caughtPanic}); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ThrowPanicNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ThrowPanicNode.java index a408568275bb..846960f34fe2 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ThrowPanicNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ThrowPanicNode.java @@ -30,7 +30,10 @@ Context getContext() { return Context.get(this); } - @Specialization(guards = {"payload.getConstructor().getType() == getContext().getBuiltins().caughtPanic()"}) + @Specialization( + guards = { + "payload.getConstructor().getType() == getContext().getBuiltins().caughtPanic().getType()" + }) Stateful doCaughtPanic( Object self, Atom payload, diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintlnNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintlnNode.java index e2b80cb6033e..cc1ced8ecc25 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintlnNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/io/PrintlnNode.java @@ -44,7 +44,7 @@ Stateful doPrintText( } catch (UnsupportedMessageException e) { throw new IllegalStateException("Impossible. self is guaranteed to be a string"); } - return new Stateful(state, ctx.getNothing().newInstance()); + return new Stateful(state, ctx.getNothing()); } @Specialization(guards = "!strings.isString(message)") diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java index 07900116447f..9ad7d6ffdb6f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java @@ -3,5 +3,12 @@ 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 {} +import java.util.List; + +@BuiltinType +public class ProjectDescription extends Builtin { + @Override + protected List getDeclaredConstructors() { + return List.of(new Cons("Make_Project_Description", List.of("prim_root_file", "prim_config"))); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/ComparatorNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/ComparatorNode.java index 9d23643bf847..18304133d49e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/ComparatorNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/ComparatorNode.java @@ -8,7 +8,6 @@ import org.enso.interpreter.node.callable.InvokeCallableNode.ArgumentsExecutionMode; import org.enso.interpreter.node.callable.InvokeCallableNode.DefaultsExecutionMode; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.builtin.Ordering; import org.enso.interpreter.runtime.callable.argument.CallArgumentInfo; import org.enso.interpreter.runtime.error.PanicException; import org.enso.interpreter.runtime.state.Stateful; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java index 56fc8c16220b..d43da4454672 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java @@ -6,7 +6,6 @@ import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.node.expression.builtin.number.utils.BigIntegerOps; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.builtin.Ordering; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.error.PanicException; import org.enso.interpreter.runtime.number.EnsoBigInteger; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java index 69bff1d72070..23114c4c662a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java @@ -6,7 +6,6 @@ import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.node.expression.builtin.number.utils.BigIntegerOps; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.builtin.Ordering; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.error.PanicException; import org.enso.interpreter.runtime.number.EnsoBigInteger; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java index 512f9dbd9be1..e16080f37c80 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java @@ -6,7 +6,6 @@ import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.node.expression.builtin.number.utils.BigIntegerOps; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.builtin.Ordering; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.error.PanicException; import org.enso.interpreter.runtime.number.EnsoBigInteger; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java index fb569d2939bd..10c98a32fb3d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java @@ -3,6 +3,73 @@ import org.enso.interpreter.node.expression.builtin.Builtin; import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.Atom; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; + +import java.util.List; @BuiltinType -public class Ordering extends Builtin {} +public class Ordering extends Builtin { + @Override + protected List getDeclaredConstructors() { + return List.of(new Cons("Less"), new Cons("Equal"), new Cons("Greater")); + } + + /** + * Convert the java notion of ordering to the Enso notion of ordering. + * + * @param ord the java ordering + * @return the Enso ordering corresponding to {@code ord} + */ + public Atom fromJava(int ord) { + if (ord == 0) { + return newEqual(); + } else if (ord > 0) { + return newGreater(); + } else { + return newLess(); + } + } + + /** + * @return the Less constructor + */ + public AtomConstructor less() { + return getConstructors()[0]; + } + + /** + * @return the Equal constructor + */ + public AtomConstructor equal() { + return getConstructors()[1]; + } + + /** + * @return the Greater constructor + */ + public AtomConstructor greater() { + return getConstructors()[2]; + } + + /** + * @return a new instance of Less + */ + public Atom newLess() { + return less().newInstance(); + } + + /** + * @return a new instance of Equal + */ + public Atom newEqual() { + return equal().newInstance(); + } + + /** + * @return a new instance of Greater + */ + public Atom newGreater() { + return greater().newInstance(); + } +} 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 da70045b7a07..bf3161349613 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 @@ -25,7 +25,12 @@ public EnsoProjectNode( Package pkg = pkgOpt.get(); EnsoFile rootPath = new EnsoFile(pkg.root().normalize()); Object cfg = context.getEnvironment().asGuestValue(pkg.config()); - result = context.getBuiltins().getProjectDescription().newInstance(rootPath, cfg); + result = + context + .getBuiltins() + .getProjectDescription() + .getUniqueConstructor() + .newInstance(rootPath, cfg); } else { result = DataflowError.withoutTrace( diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java index 1436f7ff8f52..604047286b7a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java @@ -21,12 +21,12 @@ public BuiltinType(Builtins builtins, Class clazz) { public Type getType() { if (type == null) { transferToInterpreterAndInvalidate(); - type = builtins.getBuiltinType(clazz); + type = builtins.getBuiltinType(clazz).getType(); } return type; } -// Atom newInstance(Object... args) { -// return getType().newInstance(args); -// } + // Atom newInstance(Object... args) { + // return getType().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 e0933545f93a..dac391da186d 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 @@ -26,13 +26,11 @@ 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.ordering.Ordering; 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.data.Type; import org.enso.interpreter.runtime.scope.ModuleScope; @@ -97,7 +95,7 @@ public Builtins(Context context) { registerBuiltinMethods(scope, language); error = new Error(this); - ordering = new Ordering(this); + ordering = getBuiltinType(Ordering.class); system = new System(this); number = new Number(this); bool = new Bool(this); @@ -324,12 +322,14 @@ public Optional getBuiltinFunction(Type type, String methodName, Langu } } - public Builtin getBuiltinType(Class clazz) { - return builtins.get(clazz); + public T getBuiltinType(Class clazz) { + @SuppressWarnings("unchecked") + T t = (T) builtins.get(clazz); + return t; } - public Builtin getBuiltinType(String name) { - return builtinsByName.get(name); + public Type getBuiltinType(String name) { + return builtinsByName.get(name).getType(); } /** @@ -429,8 +429,8 @@ public Type debug() { /** * @return the {@code Project_Description} atom constructor */ - public Type getProjectDescription() { - return projectDescription.getType(); + public Builtin getProjectDescription() { + return projectDescription; } /** @@ -464,7 +464,7 @@ public Type polyglot() { /** * @return the {@code Caught_Panic} atom constructor */ - public Type caughtPanic() { + public Builtin caughtPanic() { return this.error.caughtPanic(); } 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 668522199cf7..58120659db69 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,6 +1,7 @@ package org.enso.interpreter.runtime.builtin; import com.oracle.truffle.api.CompilerDirectives; +import org.enso.interpreter.node.expression.builtin.Builtin; import org.enso.interpreter.node.expression.builtin.error.*; import org.enso.interpreter.node.expression.builtin.error.NoSuchMethodError; import org.enso.interpreter.runtime.callable.UnresolvedConversion; @@ -16,24 +17,24 @@ /** Container for builtin Error types */ public class Error { - private final BuiltinType syntaxError; - private final BuiltinType typeError; - private final BuiltinType compileError; - private final BuiltinType inexhaustivePatternMatchError; - private final BuiltinType uninitializedState; - private final BuiltinType noSuchMethodError; - private final BuiltinType noSuchConversionError; - private final BuiltinType polyglotError; - private final BuiltinType moduleNotInPackageError; - private final BuiltinType arithmeticError; - private final BuiltinType invalidArrayIndexError; - private final BuiltinType arityError; - private final BuiltinType unsupportedArgumentsError; - private final BuiltinType moduleDoesNotExistError; - private final BuiltinType notInvokableError; - private final BuiltinType invalidConversionTargetError; - private final BuiltinType panic; - private final BuiltinType caughtPanic; + private final Builtin syntaxError; + private final Builtin typeError; + private final Builtin compileError; + private final Builtin inexhaustivePatternMatchError; + private final Builtin uninitializedState; + private final Builtin noSuchMethodError; + private final Builtin noSuchConversionError; + private final Builtin polyglotError; + private final Builtin moduleNotInPackageError; + private final Builtin arithmeticError; + private final Builtin invalidArrayIndexError; + private final Builtin arityError; + private final Builtin unsupportedArgumentsError; + private final Builtin moduleDoesNotExistError; + private final Builtin notInvokableError; + private final Builtin invalidConversionTargetError; + private final Builtin panic; + private final Builtin caughtPanic; @CompilerDirectives.CompilationFinal private Atom arithmeticErrorShiftTooBig; @@ -44,55 +45,52 @@ public class Error { /** Creates builders for error Atom Constructors. */ public Error(Builtins builtins) { - syntaxError = new BuiltinType(builtins, SyntaxError.class); - typeError = new BuiltinType(builtins, TypeError.class); - compileError = new BuiltinType(builtins, CompileError.class); - inexhaustivePatternMatchError = - new BuiltinType(builtins, InexhaustivePatternMatchError.class); - uninitializedState = new BuiltinType(builtins, UninitializedState.class); - noSuchMethodError = new BuiltinType(builtins, NoSuchMethodError.class); - noSuchConversionError = new BuiltinType(builtins, NoSuchConversionError.class); - polyglotError = new BuiltinType(builtins, PolyglotError.class); - moduleNotInPackageError = new BuiltinType(builtins, ModuleNotInPackageError.class); - arithmeticError = new BuiltinType(builtins, ArithmeticError.class); - invalidArrayIndexError = new BuiltinType(builtins, InvalidArrayIndexError.class); - arityError = new BuiltinType(builtins, ArityError.class); - unsupportedArgumentsError = - new BuiltinType(builtins, UnsupportedArgumentTypes.class); - moduleDoesNotExistError = new BuiltinType(builtins, ModuleDoesNotExist.class); - notInvokableError = new BuiltinType(builtins, NotInvokableError.class); - invalidConversionTargetError = - new BuiltinType(builtins, InvalidConversionTargetError.class); - panic = new BuiltinType(builtins, Panic.class); - caughtPanic = new BuiltinType(builtins, CaughtPanic.class); + syntaxError = builtins.getBuiltinType(SyntaxError.class); + typeError = builtins.getBuiltinType(TypeError.class); + compileError = builtins.getBuiltinType(CompileError.class); + inexhaustivePatternMatchError = builtins.getBuiltinType(InexhaustivePatternMatchError.class); + uninitializedState = builtins.getBuiltinType(UninitializedState.class); + noSuchMethodError = builtins.getBuiltinType(NoSuchMethodError.class); + noSuchConversionError = builtins.getBuiltinType(NoSuchConversionError.class); + polyglotError = builtins.getBuiltinType(PolyglotError.class); + moduleNotInPackageError = builtins.getBuiltinType(ModuleNotInPackageError.class); + arithmeticError = builtins.getBuiltinType(ArithmeticError.class); + invalidArrayIndexError = builtins.getBuiltinType(InvalidArrayIndexError.class); + arityError = builtins.getBuiltinType(ArityError.class); + unsupportedArgumentsError = builtins.getBuiltinType(UnsupportedArgumentTypes.class); + moduleDoesNotExistError = builtins.getBuiltinType(ModuleDoesNotExist.class); + notInvokableError = builtins.getBuiltinType(NotInvokableError.class); + invalidConversionTargetError = builtins.getBuiltinType(InvalidConversionTargetError.class); + panic = builtins.getBuiltinType(Panic.class); + caughtPanic = builtins.getBuiltinType(CaughtPanic.class); } public Atom makeSyntaxError(Object message) { - return syntaxError.newInstance(message); + return syntaxError.getUniqueConstructor().newInstance(message); } public Atom makeCompileError(Object message) { - return compileError.newInstance(message); + return compileError.getUniqueConstructor().newInstance(message); } public Atom makeInexhaustivePatternMatchError(Object message) { - return inexhaustivePatternMatchError.newInstance(message); + return inexhaustivePatternMatchError.getUniqueConstructor().newInstance(message); } public Atom makeUninitializedStateError(Object key) { - return uninitializedState.newInstance(key); + return uninitializedState.getUniqueConstructor().newInstance(key); } public Atom makeModuleNotInPackageError() { - return moduleNotInPackageError.newInstance(); + return moduleNotInPackageError.getUniqueConstructor().newInstance(); } public Type panic() { return panic.getType(); } - public Type caughtPanic() { - return caughtPanic.getType(); + public Builtin caughtPanic() { + return caughtPanic; } /** @@ -103,16 +101,16 @@ public Type caughtPanic() { * @return a runtime representation of the error */ public Atom makeNoSuchMethodError(Object target, UnresolvedSymbol symbol) { - return noSuchMethodError.newInstance(target, symbol); + return noSuchMethodError.getUniqueConstructor().newInstance(target, symbol); } public Atom makeNoSuchConversionError( Object target, Object that, UnresolvedConversion conversion) { - return noSuchConversionError.newInstance(target, that, conversion); + return noSuchConversionError.getUniqueConstructor().newInstance(target, that, conversion); } public Atom makeInvalidConversionTargetError(Object target) { - return invalidConversionTargetError.newInstance(target); + return invalidConversionTargetError.getUniqueConstructor().newInstance(target); } /** @@ -124,7 +122,7 @@ public Atom makeInvalidConversionTargetError(Object target) { * @return a runtime representation of the error. */ public Atom makeTypeError(Object expected, Object actual, String name) { - return typeError.newInstance(expected, actual, Text.create(name)); + return typeError.getUniqueConstructor().newInstance(expected, actual, Text.create(name)); } /** @@ -134,7 +132,7 @@ public Atom makeTypeError(Object expected, Object actual, String name) { * @return a runtime representation of the polyglot error. */ public Atom makePolyglotError(Object cause) { - return polyglotError.newInstance(cause); + return polyglotError.getUniqueConstructor().newInstance(cause); } /** @@ -144,10 +142,12 @@ public Atom makePolyglotError(Object cause) { * @return a runtime representation of the arithmetic error */ private Atom makeArithmeticError(Text reason) { - return arithmeticError.newInstance(reason); + return arithmeticError.getUniqueConstructor().newInstance(reason); } - /** @return An arithmetic error representing a too-large shift for the bit shift. */ + /** + * @return An arithmetic error representing a too-large shift for the bit shift. + */ public Atom getShiftAmountTooLargeError() { if (arithmeticErrorShiftTooBig == null) { transferToInterpreterAndInvalidate(); @@ -156,7 +156,9 @@ public Atom getShiftAmountTooLargeError() { return arithmeticErrorShiftTooBig; } - /** @return An Arithmetic error representing a division by zero. */ + /** + * @return An Arithmetic error representing a division by zero. + */ public Atom getDivideByZeroError() { if (arithmeticErrorDivideByZero == null) { transferToInterpreterAndInvalidate(); @@ -171,7 +173,7 @@ public Atom getDivideByZeroError() { * @return An error representing that the {@code index} is not valid in {@code array} */ public Atom makeInvalidArrayIndexError(Object array, Object index) { - return invalidArrayIndexError.newInstance(array, index); + return invalidArrayIndexError.getUniqueConstructor().newInstance(array, index); } /** @@ -181,7 +183,7 @@ public Atom makeInvalidArrayIndexError(Object array, Object index) { * @return an error informing about the arity being mismatched */ public Atom makeArityError(long expected_min, long expected_max, long actual) { - return arityError.newInstance(expected_min, expected_max, actual); + return arityError.getUniqueConstructor().newInstance(expected_min, expected_max, actual); } /** @@ -190,7 +192,7 @@ public Atom makeArityError(long expected_min, long expected_max, long actual) { * given method callp */ public Atom makeUnsupportedArgumentsError(Object[] args) { - return unsupportedArgumentsError.newInstance(new Array(args)); + return unsupportedArgumentsError.getUniqueConstructor().newInstance(new Array(args)); } /** @@ -198,7 +200,7 @@ public Atom makeUnsupportedArgumentsError(Object[] args) { * @return a module does not exist error */ public Atom makeModuleDoesNotExistError(String name) { - return moduleDoesNotExistError.newInstance(Text.create(name)); + return moduleDoesNotExistError.getUniqueConstructor().newInstance(Text.create(name)); } /** @@ -206,6 +208,6 @@ public Atom makeModuleDoesNotExistError(String name) { * @return a not invokable error */ public Atom makeNotInvokableError(Object target) { - return notInvokableError.newInstance(target); + return notInvokableError.getUniqueConstructor().newInstance(target); } } 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 deleted file mode 100644 index 29192d1aa540..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Ordering.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.enso.interpreter.runtime.builtin; - -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; - -/** A container for builtin ordering types. */ -public class Ordering { - - private final BuiltinType ordering; - private final BuiltinType less; - private final BuiltinType equal; - private final BuiltinType greater; - - public Ordering(Builtins builtins) { - ordering = - new BuiltinType( - builtins, org.enso.interpreter.node.expression.builtin.ordering.Ordering.class); - less = new BuiltinType(builtins, Less.class); - equal = new BuiltinType(builtins, Equal.class); - greater = new BuiltinType(builtins, Greater.class); - } - - /** - * Convert the java notion of ordering to the Enso notion of ordering. - * - * @param ord the java ordering - * @return the Enso ordering corresponding to {@code ord} - */ - public Atom fromJava(int ord) { - if (ord == 0) { - return newEqual(); - } else if (ord > 0) { - return newGreater(); - } else { - return newLess(); - } - } - - /** @return a new instance of Less */ - public Atom newLess() { - return less().newInstance(); - } - - /** @return a new instance of Equal */ - public Atom newEqual() { - return equal().newInstance(); - } - - /** @return a new instance of Greater */ - public Atom newGreater() { - return greater().newInstance(); - } - - /** @return the Ordering constructor. */ - public AtomConstructor ordering() { - return ordering.getType(); - } - - /** @return the Less constructor */ - public AtomConstructor less() { - return less.getType(); - } - - /** @return the Equal constructor */ - public AtomConstructor equal() { - return equal.getType(); - } - - /** @return the Greater constructor */ - public AtomConstructor greater() { - return greater.getType(); - } -} 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 47073e7ab9be..ef0795d7219d 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,20 +1,23 @@ package org.enso.interpreter.runtime.builtin; +import org.enso.interpreter.node.expression.builtin.Builtin; import org.enso.interpreter.node.expression.builtin.system.*; import org.enso.interpreter.runtime.callable.atom.Atom; /** A container class for all System-related stdlib builtins. */ public class System { - private final BuiltinType systemProcessResult; + private final Builtin systemProcessResult; /** Create builders for all {@code System} atom constructors. */ public System(Builtins builtins) { - systemProcessResult = new BuiltinType(builtins, SystemProcessResult.class); + systemProcessResult = builtins.getBuiltinType(SystemProcessResult.class); } - /** @return the atom constructor for {@code Process_Result}. */ + /** + * @return the atom constructor for {@code Process_Result}. + */ public Atom makeSystemResult(Object exitCode, Object stdout, Object stderr) { - return systemProcessResult.newInstance(exitCode, stdout, stderr); + return systemProcessResult.getUniqueConstructor().newInstance(exitCode, stdout, stderr); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/ManagedResource.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/ManagedResource.java index 971d52368e40..13c3bbbd4e3c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/ManagedResource.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/ManagedResource.java @@ -31,12 +31,16 @@ public ManagedResource(Object resource) { this.phantomReference = null; } - /** @return the underlying resource */ + /** + * @return the underlying resource + */ public Object getResource() { return resource; } - /** @return the phantom reference tracking this managed resource */ + /** + * @return the phantom reference tracking this managed resource + */ public PhantomReference getPhantomReference() { return phantomReference; } @@ -89,8 +93,7 @@ static class GetFunctionalDispatch { @CompilerDirectives.TruffleBoundary static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); - return symbol.resolveFor( - context.getBuiltins().managedResource(), context.getBuiltins().any()); + return symbol.resolveFor(context.getBuiltins().managedResource()); } static Context getContext() { From ff0f6a08728590c0f24326b9843b053714ce6736 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 29 Jul 2022 17:52:01 +0200 Subject: [PATCH 022/110] holy cow it compiled --- .../IndirectInvokeConversionNode.java | 25 +--- .../node/callable/InvokeConversionNode.java | 19 +-- .../node/expression/builtin/Boolean.java | 21 ++- .../node/expression/builtin/Builtin.java | 6 +- .../builtin/bool/CompareToNode.java | 3 +- .../node/expression/builtin/bool/False.java | 7 - .../node/expression/builtin/bool/True.java | 7 - .../interop/syntax/HostValueToEnsoNode.java | 4 +- .../builtin/mutable/ComparatorNode.java | 3 +- .../expression/builtin/mutable/SortNode.java | 2 +- .../number/bigInteger/CompareToNode.java | 1 + .../builtin/number/decimal/CompareToNode.java | 1 + .../number/smallInteger/CompareToNode.java | 1 + .../expression/builtin/ordering/Equal.java | 8 -- .../expression/builtin/ordering/Greater.java | 8 -- .../expression/builtin/ordering/Less.java | 8 -- .../interpreter/runtime/builtin/Bool.java | 35 ----- .../interpreter/runtime/builtin/Builtins.java | 10 +- .../callable/atom/AtomConstructor.java | 44 +++---- .../enso/interpreter/runtime/data/Array.java | 2 +- .../interpreter/runtime/error/Warning.java | 2 +- .../dispatch/DefaultBooleanExports.java | 123 ++---------------- .../runtime/scope/ModuleScope.java | 4 +- .../runtime/scope/TopLevelScope.java | 2 +- .../runtime/type/TypesFromProxy.java | 2 +- .../enso/compiler/codegen/IrToTruffle.scala | 2 +- .../codegen/RuntimeStubsGenerator.scala | 11 +- .../org/enso/compiler/data/BindingsMap.scala | 5 +- .../pass/analyse/BindingAnalysis.scala | 15 ++- 29 files changed, 105 insertions(+), 276 deletions(-) delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Equal.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Greater.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Less.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeConversionNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeConversionNode.java index 7a671e08a039..840aa6741ac4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeConversionNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeConversionNode.java @@ -26,7 +26,9 @@ @ImportStatic({HostMethodCallNode.PolyglotCallType.class, HostMethodCallNode.class}) public abstract class IndirectInvokeConversionNode extends Node { - /** @return a new indirect method invocation node */ + /** + * @return a new indirect method invocation node + */ public static IndirectInvokeConversionNode build() { return IndirectInvokeConversionNodeGen.create(); } @@ -58,16 +60,11 @@ Stateful doConvertFrom( BaseNode.TailStatus isTail, int thatArgumentPosition, @CachedLibrary(limit = "10") MethodDispatchLibrary dispatch, - @Cached ConditionProfile atomProfile, - @Cached ConditionProfile atomConstructorProfile, @Cached IndirectInvokeFunctionNode indirectInvokeFunctionNode) { try { Function function = dispatch.getConversionFunction( - that, - InvokeConversionNode.extractConstructor( - this, self, atomConstructorProfile, atomProfile), - conversion); + that, InvokeConversionNode.extractConstructor(this, self), conversion); return indirectInvokeFunctionNode.execute( function, frame, @@ -99,16 +96,11 @@ Stateful doDataflowError( int thatArgumentPosition, @CachedLibrary(limit = "10") MethodDispatchLibrary dispatch, @Cached BranchProfile profile, - @Cached ConditionProfile atomProfile, - @Cached ConditionProfile atomConstructorProfile, @Cached IndirectInvokeFunctionNode indirectInvokeFunctionNode) { try { Function function = dispatch.getConversionFunction( - that, - InvokeConversionNode.extractConstructor( - this, self, atomConstructorProfile, atomProfile), - conversion); + that, InvokeConversionNode.extractConstructor(this, self), conversion); return indirectInvokeFunctionNode.execute( function, frame, @@ -188,18 +180,13 @@ Stateful doConvertText( @CachedLibrary(limit = "10") MethodDispatchLibrary methods, @CachedLibrary(limit = "1") MethodDispatchLibrary textDispatch, @CachedLibrary(limit = "10") InteropLibrary interop, - @Cached ConditionProfile atomProfile, - @Cached ConditionProfile atomConstructorProfile, @Cached IndirectInvokeFunctionNode indirectInvokeFunctionNode) { try { String str = interop.asString(that); Text txt = Text.create(str); Function function = textDispatch.getConversionFunction( - txt, - InvokeConversionNode.extractConstructor( - this, self, atomConstructorProfile, atomProfile), - conversion); + txt, InvokeConversionNode.extractConstructor(this, self), conversion); arguments[0] = txt; return indirectInvokeFunctionNode.execute( function, diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeConversionNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeConversionNode.java index 8326697dbd29..7270d0c3a33e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeConversionNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeConversionNode.java @@ -19,6 +19,7 @@ import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.ArrayRope; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.data.text.Text; import org.enso.interpreter.runtime.error.*; import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; @@ -30,8 +31,6 @@ public abstract class InvokeConversionNode extends BaseNode { private @Child InvokeFunctionNode invokeFunctionNode; private @Child InvokeConversionNode childDispatch; - private final ConditionProfile atomProfile = ConditionProfile.createCountingProfile(); - private final ConditionProfile atomConstructorProfile = ConditionProfile.createCountingProfile(); private final int thatArgumentPosition; /** @@ -75,15 +74,9 @@ public abstract Stateful execute( Object that, Object[] arguments); - static AtomConstructor extractConstructor( - Node thisNode, - Object self, - ConditionProfile atomConstructorProfile, - ConditionProfile atomProfile) { - if (atomConstructorProfile.profile(self instanceof AtomConstructor)) { - return (AtomConstructor) self; - } else if (atomProfile.profile(self instanceof Atom)) { - return ((Atom) self).getConstructor(); + static Type extractConstructor(Node thisNode, Object self) { + if (self instanceof Type) { + return (Type) self; } else { throw new PanicException( Context.get(thisNode).getBuiltins().error().makeInvalidConversionTargetError(self), @@ -91,8 +84,8 @@ static AtomConstructor extractConstructor( } } - AtomConstructor extractConstructor(Object self) { - return extractConstructor(this, self, atomConstructorProfile, atomProfile); + Type extractConstructor(Object self) { + return extractConstructor(this, self); } @Specialization(guards = "dispatch.canConvertFrom(that)") diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java index 457a9c6492f2..38527e588b15 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Boolean.java @@ -1,12 +1,27 @@ package org.enso.interpreter.node.expression.builtin; import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -// Note that Boolean BuiltinType cannot be moved to `.expression.builtin.bool` package along with -// True and False +import java.util.List; + +// Note that Boolean BuiltinType cannot be moved to `.expression.builtin.bool` // 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 {} +public class Boolean extends Builtin { + @Override + protected List getDeclaredConstructors() { + return List.of(new Cons("False"), new Cons("True")); + } + + public AtomConstructor getFalse() { + return getConstructors()[0]; + } + + public AtomConstructor getTrue() { + return getConstructors()[1]; + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java index b72bec513d8d..b151cc71beb4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java @@ -19,8 +19,8 @@ public Cons(String name, String... params) { this(name, Arrays.asList(params)); } - private AtomConstructor build(ModuleScope scope) { - var res = new AtomConstructor(name, scope, true); + private AtomConstructor build(ModuleScope scope, Type type) { + var res = new AtomConstructor(name, scope, type,true); res.initializeFields( IntStream.range(0, params.size()) .mapToObj( @@ -64,7 +64,7 @@ public final void initialize(ModuleScope scope, Map, Bu var conses = getDeclaredConstructors(); constructors = new AtomConstructor[conses.size()]; for (int i = 0; i < constructors.length; i++) { - constructors[i] = conses.get(i).build(scope); + constructors[i] = conses.get(i).build(scope, type); } if (constructors.length == 1) { uniqueConstructor = constructors[0]; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java index c5e8956f80a1..af39fd998cbe 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/CompareToNode.java @@ -4,6 +4,7 @@ import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.dsl.BuiltinMethod; +import org.enso.interpreter.node.expression.builtin.ordering.Ordering; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.error.PanicException; @@ -31,7 +32,7 @@ Atom doBoolean(Boolean self, Boolean that) { @Specialization Atom doOther(Boolean self, Object that) { CompilerDirectives.transferToInterpreter(); - var bool = Context.get(this).getBuiltins().bool().getBool(); + var bool = Context.get(this).getBuiltins().bool().getType(); var typeError = Context.get(this).getBuiltins().error().makeTypeError(that, bool, "that"); throw new PanicException(typeError, this); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java deleted file mode 100644 index 7860b38b8c0f..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/False.java +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 9e6b7d3c54fe..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/True.java +++ /dev/null @@ -1,7 +0,0 @@ -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/interop/syntax/HostValueToEnsoNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/syntax/HostValueToEnsoNode.java index 8a9c23d06a6b..8e52cc8c5d2a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/syntax/HostValueToEnsoNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/interop/syntax/HostValueToEnsoNode.java @@ -58,8 +58,8 @@ Text doString(String txt) { } @Specialization(guards = {"o != null", "nulls.isNull(o)"}) - Atom doNull(Object o, @CachedLibrary(limit = "3") InteropLibrary nulls) { - return Context.get(this).getBuiltins().nothing().newInstance(); + Object doNull(Object o, @CachedLibrary(limit = "3") InteropLibrary nulls) { + return Context.get(this).getBuiltins().nothing(); } @Fallback diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/ComparatorNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/ComparatorNode.java index 18304133d49e..10941762ab5f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/ComparatorNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/ComparatorNode.java @@ -7,6 +7,7 @@ import org.enso.interpreter.node.callable.InvokeCallableNode; import org.enso.interpreter.node.callable.InvokeCallableNode.ArgumentsExecutionMode; import org.enso.interpreter.node.callable.InvokeCallableNode.DefaultsExecutionMode; +import org.enso.interpreter.node.expression.builtin.ordering.Ordering; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.argument.CallArgumentInfo; import org.enso.interpreter.runtime.error.PanicException; @@ -45,7 +46,7 @@ public int execute(VirtualFrame frame, Object comparator, Object l, Object r) { return 1; } else { CompilerDirectives.transferToInterpreter(); - var ordering = getOrdering().ordering(); + var ordering = getOrdering().getType(); throw new PanicException( Context.get(this).getBuiltins().error().makeTypeError(ordering, atom, "comparator"), this); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/SortNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/SortNode.java index fcd7cb2b6f23..2eb2978b2dd0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/SortNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/mutable/SortNode.java @@ -98,7 +98,7 @@ private int convertResult(Object res) { return 1; } else { resultProfile.enter(); - var ordering = context.getBuiltins().ordering().ordering(); + var ordering = context.getBuiltins().ordering().getType(); throw new PanicException( context.getBuiltins().error().makeTypeError(ordering, res, "result"), outerThis); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java index d43da4454672..d43dac7dea18 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/CompareToNode.java @@ -5,6 +5,7 @@ import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.node.expression.builtin.number.utils.BigIntegerOps; +import org.enso.interpreter.node.expression.builtin.ordering.Ordering; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.error.PanicException; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java index 23114c4c662a..245c0924422a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/CompareToNode.java @@ -5,6 +5,7 @@ import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.node.expression.builtin.number.utils.BigIntegerOps; +import org.enso.interpreter.node.expression.builtin.ordering.Ordering; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.error.PanicException; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java index e16080f37c80..97ec7bab629a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/CompareToNode.java @@ -5,6 +5,7 @@ import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.node.expression.builtin.number.utils.BigIntegerOps; +import org.enso.interpreter.node.expression.builtin.ordering.Ordering; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.error.PanicException; 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 deleted file mode 100644 index 5209451ae159..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Equal.java +++ /dev/null @@ -1,8 +0,0 @@ -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 deleted file mode 100644 index a6fe2d5b277f..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Greater.java +++ /dev/null @@ -1,8 +0,0 @@ -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 deleted file mode 100644 index c502f085bd63..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Less.java +++ /dev/null @@ -1,8 +0,0 @@ -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/runtime/builtin/Bool.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java deleted file mode 100644 index d7bee9127dad..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Bool.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.enso.interpreter.runtime.builtin; - -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.data.Type; - -/** A container class for all Boolean-related stdlib builtins. */ -public class Bool { - private final BuiltinType tru; - private final BuiltinType fls; - private final BuiltinType bool; - - /** Creates builders for all the boolean constructors. */ - public Bool(Builtins builtins) { - bool = new BuiltinType(builtins, Boolean.class); - tru = new BuiltinType(builtins, True.class); - fls = new BuiltinType(builtins, False.class); - } - - /** @return the atom constructor for {@code True}. */ - public AtomConstructor getTrue() { - return tru.getType(); - } - - /** @return the atom constructor for {@code False}. */ - public AtomConstructor getFalse() { - return fls.getType(); - } - - /** @return the atom constructor for {@code Boolean}. */ - public Type getBool() { - return bool.getType(); - } -} 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 dac391da186d..064685e526bc 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 @@ -20,6 +20,7 @@ import org.enso.interpreter.dsl.TypeProcessor; import org.enso.interpreter.dsl.model.MethodDefinition; import org.enso.interpreter.node.expression.builtin.*; +import org.enso.interpreter.node.expression.builtin.Boolean; import org.enso.interpreter.node.expression.builtin.debug.Debug; import org.enso.interpreter.node.expression.builtin.error.Warning; import org.enso.interpreter.node.expression.builtin.io.File; @@ -58,7 +59,7 @@ public static class Debug { private final Module module; private final ModuleScope scope; public final Number number; - private final Bool bool; + private final Boolean bool; private final Ordering ordering; private final System system; private final Special special; @@ -98,7 +99,7 @@ public Builtins(Context context) { ordering = getBuiltinType(Ordering.class); system = new System(this); number = new Number(this); - bool = new Bool(this); + bool = this.getBuiltinType(Boolean.class); any = builtins.get(Any.class); nothing = builtins.get(Nothing.class); @@ -205,7 +206,8 @@ private Map, Builtin> readBuiltinTypesMetadata(ModuleSc .map( line -> { String[] builtinMeta = line.split(":"); - if (builtinMeta.length != 3) { + if (builtinMeta.length < 2 || builtinMeta.length > 3) { + java.lang.System.out.println(Arrays.toString(builtinMeta)); throw new CompilerError("Invalid builtin metadata in: " + line); } try { @@ -371,7 +373,7 @@ public Number number() { /** * @return the container for boolean constructors. */ - public Bool bool() { + public Boolean bool() { return bool; } 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 052abd3aadc8..5964156e3cee 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 @@ -54,8 +54,8 @@ public final class AtomConstructor implements TruffleObject { * @param name the name of the Atom constructor * @param definitionScope the scope in which this constructor was defined */ - public AtomConstructor(String name, ModuleScope definitionScope) { - this(name, definitionScope, false); + public AtomConstructor(String name, ModuleScope definitionScope, Type type) { + this(name, definitionScope, type, false); } /** @@ -67,9 +67,10 @@ public AtomConstructor(String name, ModuleScope definitionScope) { * @param definitionScope the scope in which this constructor was defined * @param builtin if true, the constructor refers to a builtin type (annotated with @BuiltinType */ - public AtomConstructor(String name, ModuleScope definitionScope, boolean builtin) { + public AtomConstructor(String name, ModuleScope definitionScope, Type type, boolean builtin) { this.name = name; this.definitionScope = definitionScope; + this.type = type; this.builtin = builtin; } @@ -157,9 +158,9 @@ private Function buildConstructorFunction( private void generateMethods(ArgumentDefinition[] args) { generateQualifiedAccessor(); - for (ArgumentDefinition arg : args) { - definitionScope.registerMethod(this, arg.getName(), generateGetter(arg.getPosition())); - } + // for (ArgumentDefinition arg : args) { + // definitionScope.registerMethod(this, arg.getName(), generateGetter(arg.getPosition())); + // } } private void generateQualifiedAccessor() { @@ -277,16 +278,16 @@ String toDisplayString(boolean allowSideEffects) { return "Constructor<" + name + ">"; } - /** @return the fully qualified name of this constructor. */ + /** + * @return the fully qualified name of this constructor. + */ public QualifiedName getQualifiedName() { - if (this == this.getDefinitionScope().getAssociatedType()) { - return definitionScope.getModule().getName(); - } else { - return definitionScope.getModule().getName().createChild(getName()); - } + return definitionScope.getModule().getName().createChild(getName()); } - /** @return the fields defined by this constructor. */ + /** + * @return the fields defined by this constructor. + */ public ArgumentDefinition[] getFields() { return constructorFunction.getSchema().getArgumentInfos(); } @@ -305,8 +306,8 @@ static class GetFunctionalDispatch { static final int CACHE_SIZE = 10; @CompilerDirectives.TruffleBoundary - static Function doResolve(AtomConstructor cons, UnresolvedSymbol symbol) { - return symbol.resolveFor(cons, getContext().getBuiltins().any()); + static Function doResolve(UnresolvedSymbol symbol) { + return symbol.resolveFor(getContext().getBuiltins().function()); } static Context getContext() { @@ -317,7 +318,6 @@ static Context getContext() { guards = { "!getContext().isInlineCachingDisabled()", "cachedSymbol == symbol", - "self == cachedConstructor", "function != null" }, limit = "CACHE_SIZE") @@ -325,15 +325,14 @@ static Function resolveCached( AtomConstructor self, UnresolvedSymbol symbol, @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("self") AtomConstructor cachedConstructor, - @Cached("doResolve(cachedConstructor, cachedSymbol)") Function function) { + @Cached("doResolve(cachedSymbol)") Function function) { return function; } @Specialization(replaces = "resolveCached") static Function resolve(AtomConstructor self, UnresolvedSymbol symbol) throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(self, symbol); + Function function = doResolve(symbol); if (function == null) { throw new MethodDispatchLibrary.NoSuchMethodException(); } @@ -351,8 +350,7 @@ static class GetConversionFunction { static final int CACHE_SIZE = 10; @CompilerDirectives.TruffleBoundary - static Function doResolve( - Type self, Type target, UnresolvedConversion conversion) { + static Function doResolve(Type self, Type target, UnresolvedConversion conversion) { return conversion.resolveFor(target, self); } @@ -381,8 +379,7 @@ static Function resolveCached( } @Specialization(replaces = "resolveCached") - static Function resolve( - AtomConstructor self, Type target, UnresolvedConversion conversion) + static Function resolve(AtomConstructor self, Type target, UnresolvedConversion conversion) throws MethodDispatchLibrary.NoSuchConversionException { Function function = doResolve(self.type, target, conversion); if (function == null) { @@ -391,5 +388,4 @@ static Function resolve( return function; } } - } 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 679bae95e1ac..c69a5314c8b8 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 @@ -162,7 +162,7 @@ static class GetFunctionalDispatch { @CompilerDirectives.TruffleBoundary static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().array(), context.getBuiltins().any()); + return symbol.resolveFor(context.getBuiltins().array()); } static Context getContext() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/Warning.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/Warning.java index 9291204fd14d..76a15bea3e2f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/Warning.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/Warning.java @@ -186,7 +186,7 @@ static class GetFunctionalDispatch { @CompilerDirectives.TruffleBoundary static Function doResolve(UnresolvedSymbol symbol) { Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().warning(), context.getBuiltins().any()); + return symbol.resolveFor(context.getBuiltins().warning()); } 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 8c6bab266758..20ab2e4670ac 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 @@ -30,24 +30,10 @@ static boolean hasFunctionalDispatch(Boolean receiver) { @ExportMessage static class GetFunctionalDispatch { @CompilerDirectives.TruffleBoundary - static Function resolveMethodOnPrimBoolean(UnresolvedSymbol symbol) { + static Function resolveMethodOnBool(UnresolvedSymbol symbol) { Context context = getContext(); Builtins builtins = context.getBuiltins(); - if (symbol.resolveFor(builtins.bool().getFalse().getType()) != null) { - return null; - } - if (symbol.resolveFor(builtins.bool().getTrue().getType()) != null) { - return null; - } - return symbol.resolveFor(builtins.bool().getBool()); - } - - @CompilerDirectives.TruffleBoundary - static Function resolveMethodOnBool(boolean self, UnresolvedSymbol symbol) { - Context context = getContext(); - Builtins builtins = context.getBuiltins(); - AtomConstructor cons = self ? builtins.bool().getTrue() : builtins.bool().getFalse(); - return symbol.resolveFor(cons.getType()); + return symbol.resolveFor(builtins.bool().getType()); } static Context getContext() { @@ -65,48 +51,14 @@ static Function resolveCached( Boolean self, UnresolvedSymbol symbol, @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("resolveMethodOnPrimBoolean(cachedSymbol)") Function function) { - return function; - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "unbox(self)", - "function != null" - }, - limit = "CACHE_SIZE", - replaces = "resolveCached") - static Function resolveTrueCached( - Boolean self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("resolveMethodOnBool(self, cachedSymbol)") Function function) { + @Cached("resolveMethodOnBool(cachedSymbol)") Function function) { return function; } - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "!unbox(self)", - "function != null" - }, - limit = "CACHE_SIZE", - replaces = "resolveCached") - static Function resolveFalseCached( - Boolean self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("resolveMethodOnBool(self, cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = {"resolveTrueCached", "resolveFalseCached"}) + @Specialization(replaces = {"resolveCached"}) static Function resolve(Boolean self, UnresolvedSymbol symbol) throws MethodDispatchLibrary.NoSuchMethodException { - Function function = resolveMethodOnBool(self, symbol); + Function function = resolveMethodOnBool(symbol); if (function == null) { throw new MethodDispatchLibrary.NoSuchMethodException(); } @@ -127,25 +79,10 @@ public static boolean hasSpecialConversion(Boolean receiver) { @ExportMessage static class GetConversionFunction { @CompilerDirectives.TruffleBoundary - static Function resolveMethodOnPrimBoolean(Type target, UnresolvedConversion conversion) { - Context context = Context.get(null); - Builtins builtins = context.getBuiltins(); - if (conversion.resolveFor(target, builtins.bool().getFalse().getType()) != null) { - return null; - } - if (conversion.resolveFor(target, builtins.bool().getTrue().getType()) != null) { - return null; - } - return conversion.resolveFor(target, builtins.bool().getBool()); - } - - @CompilerDirectives.TruffleBoundary - static Function resolveMethodOnBool( - boolean self, Type target, UnresolvedConversion conversion) { + static Function resolveMethodOnBool(Type target, UnresolvedConversion conversion) { Context context = Context.get(null); Builtins builtins = context.getBuiltins(); - AtomConstructor cons = self ? builtins.bool().getTrue() : builtins.bool().getFalse(); - return conversion.resolveFor(target, cons.getType()); + return conversion.resolveFor(target, builtins.bool().getType()); } static Context getContext() { @@ -166,54 +103,14 @@ static Function resolveCached( UnresolvedConversion conversion, @Cached("conversion") UnresolvedConversion cachedConversion, @Cached("target") Type cachedTarget, - @Cached("resolveMethodOnPrimBoolean(cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedConversion == conversion", - "cachedTarget == target", - "unbox(self)", - "function != null" - }, - limit = "CACHE_SIZE", - replaces = "resolveCached") - static Function resolveTrueCached( - Boolean self, - Type target, - UnresolvedConversion conversion, - @Cached("target") Type cachedTarget, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("resolveMethodOnBool(self, cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedConversion == conversion", - "cachedTarget == target", - "!unbox(self)", - "function != null" - }, - limit = "CACHE_SIZE", - replaces = "resolveCached") - static Function resolveFalseCached( - Boolean self, - Type target, - UnresolvedConversion conversion, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") Type cachedTarget, - @Cached("resolveMethodOnBool(self, cachedTarget, cachedConversion)") Function function) { + @Cached("resolveMethodOnBool(cachedTarget, cachedConversion)") Function function) { return function; } - @Specialization(replaces = {"resolveTrueCached", "resolveFalseCached"}) + @Specialization(replaces = {"resolveCached"}) static Function resolve(Boolean self, Type target, UnresolvedConversion symbol) throws MethodDispatchLibrary.NoSuchConversionException { - Function function = resolveMethodOnBool(self, target, symbol); + Function function = resolveMethodOnBool(target, symbol); if (function == null) { throw new MethodDispatchLibrary.NoSuchConversionException(); } 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 2b7a5ec084fb..a5fc8faffedb 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 @@ -31,7 +31,7 @@ public class ModuleScope implements TruffleObject { */ public ModuleScope(Module module) { this.module = module; - this.associatedType = new Type(module.getName().item(), this, false); + this.associatedType = new Type(module.getName().item(), this, null, false); } /** @@ -291,7 +291,7 @@ public Optional getType(String name) { return Optional.ofNullable(types.get(name)); } - /** + /** * @return the raw method map held by this module */ public Map> getMethods() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java index 9f1703e8033e..148a88e053ac 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java @@ -149,7 +149,7 @@ private static Object unregisterModule(TopLevelScope scope, Object[] arguments, throws ArityException, UnsupportedTypeException { String name = Types.extractArguments(arguments, String.class); scope.packageRepository.deregisterModule(name); - return context.getNothing().newInstance(); + return context.getNothing(); } private static Object leakContext(Context context) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java index 51d783ab2899..e032c12f0578 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java @@ -34,7 +34,7 @@ public static Type fromTypeSystem(Builtins builtins, String typeName) { case ConstantsGen.ARRAY: return builtins.array(); case ConstantsGen.BOOLEAN: - return builtins.bool().getBool(); + return builtins.bool().getType(); case ConstantsGen.DECIMAL: return builtins.number.getDecimal(); case ConstantsGen.ERROR: diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index d35818d2836e..f68e372ed5ee 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 @@ -891,7 +891,7 @@ class IrToTruffle( val any = context.getBuiltins.any val array = context.getBuiltins.array val file = context.getBuiltins.file - val builtinBool = context.getBuiltins.bool.getBool + val builtinBool = context.getBuiltins.bool.getType val number = context.getBuiltins.number val polyglot = context.getBuiltins.polyglot val text = context.getBuiltins.text 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 07626045f9e5..f673765bbeed 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 @@ -5,6 +5,7 @@ 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 +import org.enso.interpreter.runtime.data.Type /** Generates stubs of runtime representations of atom constructors, to allow * [[IrToTruffle the code generator]] to refer to constructors that are not @@ -23,7 +24,7 @@ class RuntimeStubsGenerator(builtins: Builtins) { BindingAnalysis, "Non-parsed module used in stubs generator" ) - localBindings.constructors.foreach { tp => + localBindings.types.foreach { tp => if (tp.builtinType) { val builtinType = builtins.getBuiltinType(tp.name) if (builtinType == null) { @@ -32,8 +33,12 @@ class RuntimeStubsGenerator(builtins: Builtins) { scope.registerType(builtinType) builtinType.setShadowDefinitions(scope) } else { - val constructor = new AtomConstructor(tp.name, scope) - scope.registerConstructor(constructor) + val rtp = new Type(tp.name, scope, builtins.any(), false) + scope.registerType(rtp) + tp.members.foreach { name => + val constructor = new AtomConstructor(name, scope, rtp) + scope.registerConstructor(constructor) + } } } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala b/engine/runtime/src/main/scala/org/enso/compiler/data/BindingsMap.scala index f06c0d4dac44..18e8e8e1f78f 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 @@ -732,8 +732,7 @@ object BindingsMap { case class Cons( name: String, arity: Int, - allFieldsDefaulted: Boolean, - builtinType: Boolean = false + allFieldsDefaulted: Boolean ) /** A representation of a sum type @@ -741,7 +740,7 @@ object BindingsMap { * @param name the type name * @param members the member names */ - case class Type(name: String, members: Seq[String]) + case class Type(name: String, members: Seq[String], builtinType: Boolean) /** A representation of an imported polyglot symbol. * diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/BindingAnalysis.scala index 1a8f6bc59503..be186da4aa2f 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 @@ -52,21 +52,24 @@ case object BindingAnalysis extends IRPass { ): IR.Module = { val definedSumTypes = ir.bindings.collect { case sumType: IR.Module.Scope.Definition.Type => - BindingsMap.Type(sumType.name.name, sumType.members.map(_.name.name)) + val isBuiltinType = sumType + .getMetadata(ModuleAnnotations) + .exists(_.annotations.exists(_.name == "@Builtin_Type")) + BindingsMap.Type( + sumType.name.name, + sumType.members.map(_.name.name), + isBuiltinType + ) } val definedConstructors = ir.bindings.flatMap { case tp: IR.Module.Scope.Definition.Type => // FIXME: move to a different pass - val isBuiltinType = tp - .getMetadata(ModuleAnnotations) - .exists(_.annotations.exists(_.name == "@Builtin_Type")) tp.members.map { cons => BindingsMap.Cons( cons.name.name, cons.arguments.length, - cons.arguments.forall(_.defaultValue.isDefined), - isBuiltinType + cons.arguments.forall(_.defaultValue.isDefined) ) } case _ => List() From 29f0bd07428e78deeae1f5a3a1f17d7618168072 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 29 Jul 2022 23:02:53 +0200 Subject: [PATCH 023/110] actually have some tests pass! --- .../node/expression/builtin/Builtin.java | 6 +- .../builtin/error/ArithmeticError.java | 4 +- .../error/ModuleNotInPackageError.java | 9 +- .../builtin/error/NoSuchMethodError.java | 11 +- .../text/util/TypeToDisplayTextNode.java | 2 + .../org/enso/interpreter/runtime/Module.java | 8 +- .../enso/interpreter/runtime/data/Type.java | 117 ++++++++++++++++-- .../enso/interpreter/runtime/type/Types.java | 10 +- .../Standard/Base/0.0.0-dev/src/Nothing.enso | 5 +- 9 files changed, 142 insertions(+), 30 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java index b151cc71beb4..180ef11a7c7a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java @@ -72,15 +72,15 @@ public final void initialize(ModuleScope scope, Map, Bu } } - public Type getType() { + public final Type getType() { return type; } - public AtomConstructor[] getConstructors() { + public final AtomConstructor[] getConstructors() { return constructors; } - public AtomConstructor getUniqueConstructor() { + public final AtomConstructor getUniqueConstructor() { return uniqueConstructor; } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java index 34e56329520d..6351fc7ebbcd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java @@ -4,4 +4,6 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = {"message"}) -public class ArithmeticError extends Builtin {} +public class ArithmeticError extends Builtin { + +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java index ec8ad7784a37..0f244f383017 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java @@ -3,5 +3,12 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import java.util.List; + @BuiltinType -public class ModuleNotInPackageError extends Builtin {} +public class ModuleNotInPackageError extends Builtin { + @Override + protected List getDeclaredConstructors() { + return List.of(new Cons("Make_Module_Not_In_Package_Error")); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java index 0fe5b29d9c9b..4439d9796b5b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java @@ -3,5 +3,12 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"target", "symbol"}) -public class NoSuchMethodError extends Builtin {} +import java.util.List; + +@BuiltinType +public class NoSuchMethodError extends Builtin { + @Override + protected List getDeclaredConstructors() { + return List.of(new Cons("Make_No_Such_Method_Error", "target", "symbol")); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/TypeToDisplayTextNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/TypeToDisplayTextNode.java index 34eff81d4b06..ffd6377cf2eb 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/TypeToDisplayTextNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/TypeToDisplayTextNode.java @@ -50,6 +50,8 @@ String doDisplay( return TypesGen.asAtom(value).getConstructor().getName(); } else if (TypesGen.isAtomConstructor(value)) { return TypesGen.asAtomConstructor(value).getName(); + } else if (TypesGen.isType(value)) { + return TypesGen.asType(value).getName(); } else if (TypesGen.isDataflowError(value)) { return "Error"; } else if (TypesGen.isUnresolvedSymbol(value)) { 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 bd1e0aa4c1d6..2af450990f89 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 @@ -495,13 +495,13 @@ public void setHasCrossModuleLinks(boolean hasCrossModuleLinks) { abstract static class InvokeMember { private static Function getMethod(ModuleScope scope, Object[] args) throws ArityException, UnsupportedTypeException { - Types.Pair arguments = - Types.extractArguments(args, AtomConstructor.class, String.class); - AtomConstructor cons = arguments.getFirst(); + Types.Pair arguments = + Types.extractArguments(args, Type.class, String.class); + Type type = arguments.getFirst(); String name = arguments.getSecond(); try { - return scope.getMethods().get(cons).get(name.toLowerCase()); + return scope.getMethods().get(type).get(name.toLowerCase()); } catch (NullPointerException npe) { TruffleLogger logger = TruffleLogger.getLogger(LanguageInfo.ID, Module.class); logger.log( diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index 8563a6d8a3f0..e4a68e292005 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -2,13 +2,23 @@ import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.dsl.Cached; +import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.TruffleObject; +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.callable.UnresolvedConversion; +import org.enso.interpreter.runtime.callable.UnresolvedSymbol; +import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.pkg.QualifiedName; import java.util.Map; +@ExportLibrary(MethodDispatchLibrary.class) public class Type implements TruffleObject { private final String name; private @CompilerDirectives.CompilationFinal ModuleScope definitionScope; @@ -21,17 +31,6 @@ public Type(String name, ModuleScope definitionScope, Type supertype, boolean bu this.supertype = supertype; this.builtin = builtin; } - // - // public static Type create( - // String name, ModuleScope definitionScope, Type supertype, Type eigentype, boolean builtin) - // { - // return new Type(name, definitionScope, supertype, eigentype, builtin); - // } - - // public static Type createSingleton(String name, ModuleScope definitionScope, Type supertype, - // Type eigentype, boolean builtin) { - // - // } public QualifiedName getQualifiedName() { if (this == this.getDefinitionScope().getAssociatedType()) { @@ -73,4 +72,100 @@ public boolean isBuiltin() { public Type getSupertype() { return supertype; } + + @ExportMessage + boolean hasFunctionalDispatch() { + return true; + } + + @ExportMessage + static class GetFunctionalDispatch { + static final int CACHE_SIZE = 10; + + @CompilerDirectives.TruffleBoundary + static Function doResolve(Type type, UnresolvedSymbol symbol) { + return symbol.resolveFor(type); + } + + static Context getContext() { + return Context.get(null); + } + + @Specialization( + guards = { + "!getContext().isInlineCachingDisabled()", + "cachedSymbol == symbol", + "self == cachedType", + "function != null" + }, + limit = "CACHE_SIZE") + static Function resolveCached( + Type self, + UnresolvedSymbol symbol, + @Cached("symbol") UnresolvedSymbol cachedSymbol, + @Cached("self") Type cachedType, + @Cached("doResolve(cachedType, cachedSymbol)") Function function) { + return function; + } + + @Specialization(replaces = "resolveCached") + static Function resolve(Type self, UnresolvedSymbol symbol) + throws MethodDispatchLibrary.NoSuchMethodException { + Function function = doResolve(self, symbol); + if (function == null) { + throw new MethodDispatchLibrary.NoSuchMethodException(); + } + return function; + } + } + + @ExportMessage + boolean canConvertFrom() { + return true; + } + + @ExportMessage + static class GetConversionFunction { + + static final int CACHE_SIZE = 10; + + @CompilerDirectives.TruffleBoundary + static Function doResolve(Type type, Type target, UnresolvedConversion conversion) { + return conversion.resolveFor(target, type); + } + + static Context getContext() { + return Context.get(null); + } + + @Specialization( + guards = { + "!getContext().isInlineCachingDisabled()", + "cachedConversion == conversion", + "cachedTarget == target", + "self == cachedType", + "function != null" + }, + limit = "CACHE_SIZE") + static Function resolveCached( + Type self, + Type target, + UnresolvedConversion conversion, + @Cached("conversion") UnresolvedConversion cachedConversion, + @Cached("self") Type cachedType, + @Cached("target") Type cachedTarget, + @Cached("doResolve(cachedType, cachedTarget, cachedConversion)") Function function) { + return function; + } + + @Specialization(replaces = "resolveCached") + static Function resolve(Type self, Type target, UnresolvedConversion conversion) + throws MethodDispatchLibrary.NoSuchConversionException { + Function function = doResolve(self, target, conversion); + if (function == null) { + throw new MethodDispatchLibrary.NoSuchConversionException(); + } + return function; + } + } } 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 68f63cd9e893..6f523c911c3b 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 @@ -9,10 +9,7 @@ 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.data.Array; -import org.enso.interpreter.runtime.data.EnsoFile; -import org.enso.interpreter.runtime.data.ManagedResource; -import org.enso.interpreter.runtime.data.Ref; +import org.enso.interpreter.runtime.data.*; import org.enso.interpreter.runtime.data.text.Text; import org.enso.interpreter.runtime.error.DataflowError; import org.enso.interpreter.runtime.error.PanicException; @@ -40,6 +37,7 @@ Function.class, Atom.class, AtomConstructor.class, + Type.class, DataflowError.class, UnresolvedConversion.class, UnresolvedSymbol.class, @@ -203,7 +201,9 @@ public static Pair extractArguments(Object[] arguments, Class cl return new Pair<>((A) arguments[0], (B) arguments[1]); } - /** @return the language type hierarchy */ + /** + * @return the language type hierarchy + */ public static TypeGraph getTypeHierarchy() { return typeHierarchy; } diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso index c1fbf60c406e..1a21011d4fc2 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso @@ -1,3 +1,2 @@ -type Nothing_Tp - @Builtin_Type - type Nothing +@Builtin_Type +type Nothing From 7c54ab84159decf8ba5f2a840f28a34d5ba72973 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 3 Aug 2022 16:23:22 +0200 Subject: [PATCH 024/110] fix dataflow analysis --- .../builtin/error/NotInvokableError.java | 11 ++++++-- .../enso/compiler/codegen/IrToTruffle.scala | 6 ++-- .../pass/analyse/DataflowAnalysis.scala | 28 ++++++++++++++++++- .../resources/TestSimpleImports/src/Atom.enso | 3 +- .../resources/TestSimpleImports/src/Main.enso | 2 +- 5 files changed, 43 insertions(+), 7 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java index cf93a27632a2..f65ad1f70c52 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java @@ -3,5 +3,12 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"target"}) -public class NotInvokableError extends Builtin {} +import java.util.List; + +@BuiltinType +public class NotInvokableError extends Builtin { + @Override + protected List getDeclaredConstructors() { + return List.of(new Cons("Make_Not_Invokable_Error", "target")); + } +} diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala index f68e372ed5ee..67a894d4612d 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 @@ -1066,8 +1066,10 @@ class IrToTruffle( } else if (global.isDefined) { val resolution = global.get.target resolution match { - case _: BindingsMap.ResolvedType => - throw new CompilerError("todo") + case tp: BindingsMap.ResolvedType => + ConstantObjectNode.build( + tp.module.unsafeAsModule().getScope.getTypes.get(tp.tp.name) + ) case BindingsMap.ResolvedConstructor(definitionModule, cons) => ConstructorNode.build( definitionModule diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala index 66f3cee320bc..ac125630c575 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/DataflowAnalysis.scala @@ -141,7 +141,33 @@ case object DataflowAnalysis extends IRPass { method .copy(body = analyseExpression(body, info)) .updateMetadata(this -->> info) - case _: IR.Module.Scope.Definition.Type => binding + case tp @ IR.Module.Scope.Definition.Type(_, params, members, _, _, _) => + val tpDep = asStatic(tp) + val newParams = params.map { param => + val paramDep = asStatic(param) + info.dependents.updateAt(paramDep, Set(tpDep)) + info.dependencies.updateAt(tpDep, Set(paramDep)) + analyseDefinitionArgument(param, info) + } + val newMembers = members.map { + case data @ IR.Module.Scope.Definition.Data(_, arguments, _, _, _) => + val dataDep = asStatic(data) + info.dependents.updateAt(dataDep, Set(tpDep)) + info.dependencies.updateAt(tpDep, Set(dataDep)) + arguments.foreach(arg => { + val argDep = asStatic(arg) + info.dependents.updateAt(argDep, Set(dataDep)) + info.dependencies.updateAt(dataDep, Set(argDep)) + }) + + data + .copy( + arguments = arguments.map(analyseDefinitionArgument(_, info)) + ) + .updateMetadata(this -->> info) + } + tp.copy(params = newParams, members = newMembers) + .updateMetadata(this -->> info) case _: IR.Module.Scope.Definition.Method.Binding => throw new CompilerError( "Sugared method definitions should not occur during dataflow " + diff --git a/engine/runtime/src/test/resources/TestSimpleImports/src/Atom.enso b/engine/runtime/src/test/resources/TestSimpleImports/src/Atom.enso index 93bafe3a52b1..c2912155335b 100644 --- a/engine/runtime/src/test/resources/TestSimpleImports/src/Atom.enso +++ b/engine/runtime/src/test/resources/TestSimpleImports/src/Atom.enso @@ -1,3 +1,4 @@ -type X a +type X + Mk_X a X.method = 20 diff --git a/engine/runtime/src/test/resources/TestSimpleImports/src/Main.enso b/engine/runtime/src/test/resources/TestSimpleImports/src/Main.enso index d17c5b49c745..00b954e04a3e 100644 --- a/engine/runtime/src/test/resources/TestSimpleImports/src/Main.enso +++ b/engine/runtime/src/test/resources/TestSimpleImports/src/Main.enso @@ -1,3 +1,3 @@ from local.TestSimpleImports.Atom import all -main = (X 1).method +main = (Mk_X 1).method From 64fbd07bc658c2b35eafe27e71de5a95e34deefc Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 3 Aug 2022 16:34:33 +0200 Subject: [PATCH 025/110] testing progress --- .../test/resources/TestNonImportedOverloads/src/Main.enso | 2 +- .../test/resources/TestNonImportedOverloads/src/Util.enso | 3 ++- .../test/resources/TestNonImportedOwnMethods/src/Main.enso | 5 +++-- .../src/test/resources/Test_Hiding_Success/src/Atom.enso | 6 ++++-- .../src/test/resources/Test_Hiding_Success/src/Main.enso | 2 +- .../src/test/resources/Test_Qualified_Error/src/Atom.enso | 3 ++- .../src/test/resources/Test_Qualified_Error/src/Main.enso | 2 +- engine/runtime/src/test/resources/Test_Rename/src/Atom.enso | 2 +- engine/runtime/src/test/resources/Test_Rename/src/Main.enso | 2 +- .../org/enso/interpreter/test/semantic/ImportsTest.scala | 4 ++-- 10 files changed, 18 insertions(+), 13 deletions(-) diff --git a/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Main.enso b/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Main.enso index 0ffaf89e0a3c..f0b98b74e2c6 100644 --- a/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Main.enso +++ b/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Main.enso @@ -3,4 +3,4 @@ from local.TestNonImportedOverloads.Util import all X.method = 10 -main = Nothing.util (X 1) +main = Nothing.util (Mk_X 1) diff --git a/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Util.enso b/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Util.enso index e717ae274a19..f472d9cc77bc 100644 --- a/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Util.enso +++ b/engine/runtime/src/test/resources/TestNonImportedOverloads/src/Util.enso @@ -1,5 +1,6 @@ import Standard.Base.Nothing -type X a +type X + Mk_X a Nothing.util = x -> x.method diff --git a/engine/runtime/src/test/resources/TestNonImportedOwnMethods/src/Main.enso b/engine/runtime/src/test/resources/TestNonImportedOwnMethods/src/Main.enso index d63614273be9..d280ccd74154 100644 --- a/engine/runtime/src/test/resources/TestNonImportedOwnMethods/src/Main.enso +++ b/engine/runtime/src/test/resources/TestNonImportedOwnMethods/src/Main.enso @@ -1,8 +1,9 @@ import Standard.Base.Nothing import local.TestNonImportedOwnMethods.Util -type X a +type X + Mk_X a X.method = 10 -main = Nothing.util (X 1) +main = Nothing.util (Mk_X 1) diff --git a/engine/runtime/src/test/resources/Test_Hiding_Success/src/Atom.enso b/engine/runtime/src/test/resources/Test_Hiding_Success/src/Atom.enso index e2517c9b9500..ea10264b11d6 100644 --- a/engine/runtime/src/test/resources/Test_Hiding_Success/src/Atom.enso +++ b/engine/runtime/src/test/resources/Test_Hiding_Success/src/Atom.enso @@ -1,5 +1,7 @@ -type X a +type X + Mk_X a -type Y b +type Y + Mk_Y b X.method = 20 diff --git a/engine/runtime/src/test/resources/Test_Hiding_Success/src/Main.enso b/engine/runtime/src/test/resources/Test_Hiding_Success/src/Main.enso index eb46f25da4b5..5987ce2de1cf 100644 --- a/engine/runtime/src/test/resources/Test_Hiding_Success/src/Main.enso +++ b/engine/runtime/src/test/resources/Test_Hiding_Success/src/Main.enso @@ -1,3 +1,3 @@ from local.Test_Hiding_Success.Atom import all hiding Y -main = (X 1).method +main = (Mk_X 1).method diff --git a/engine/runtime/src/test/resources/Test_Qualified_Error/src/Atom.enso b/engine/runtime/src/test/resources/Test_Qualified_Error/src/Atom.enso index 93bafe3a52b1..c2912155335b 100644 --- a/engine/runtime/src/test/resources/Test_Qualified_Error/src/Atom.enso +++ b/engine/runtime/src/test/resources/Test_Qualified_Error/src/Atom.enso @@ -1,3 +1,4 @@ -type X a +type X + Mk_X a X.method = 20 diff --git a/engine/runtime/src/test/resources/Test_Qualified_Error/src/Main.enso b/engine/runtime/src/test/resources/Test_Qualified_Error/src/Main.enso index af2195e6a9bf..a348a15b05bb 100644 --- a/engine/runtime/src/test/resources/Test_Qualified_Error/src/Main.enso +++ b/engine/runtime/src/test/resources/Test_Qualified_Error/src/Main.enso @@ -1,3 +1,3 @@ import local.Test_Qualified_Error.Atom -main = (X 1).method +main = (Mk_X 1).method diff --git a/engine/runtime/src/test/resources/Test_Rename/src/Atom.enso b/engine/runtime/src/test/resources/Test_Rename/src/Atom.enso index 93bafe3a52b1..ebc14bd103da 100644 --- a/engine/runtime/src/test/resources/Test_Rename/src/Atom.enso +++ b/engine/runtime/src/test/resources/Test_Rename/src/Atom.enso @@ -1,3 +1,3 @@ -type X a +type X X.method = 20 diff --git a/engine/runtime/src/test/resources/Test_Rename/src/Main.enso b/engine/runtime/src/test/resources/Test_Rename/src/Main.enso index 7a5a727055e6..d7da37a7a8f6 100644 --- a/engine/runtime/src/test/resources/Test_Rename/src/Main.enso +++ b/engine/runtime/src/test/resources/Test_Rename/src/Main.enso @@ -1,3 +1,3 @@ import local.Test_Rename.Atom as Def -main = (Def.X 1).method +main = Def.X.method diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ImportsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ImportsTest.scala index 0c3196c176f0..15f8861e225e 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ImportsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ImportsTest.scala @@ -14,7 +14,7 @@ class ImportsTest extends PackageTest { "Overloaded methods" should "not be visible when not imported" in { the[InterpreterException] thrownBy evalTestProject( "TestNonImportedOverloads" - ) should have message "Method `method` of X could not be found." + ) should have message "Method `method` of Mk_X could not be found." } "Import statements" should "report errors when they cannot be resolved" in { @@ -39,7 +39,7 @@ class ImportsTest extends PackageTest { consumeOut .filterNot(_.contains("Compiler encountered")) .filterNot(_.contains("In module")) - .head should include("The name X could not be found.") + .head should include("The name Mk_X could not be found.") } "Symbols from imported modules" should "not be visible when hidden" in { From c7a81ee074cf29d54d5a7e02d77daaa36637048a Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 3 Aug 2022 17:07:51 +0200 Subject: [PATCH 026/110] another undeniable success --- .../node/expression/builtin/error/CompileError.java | 11 +++++++++-- .../node/expression/builtin/number/BigInteger.java | 7 ++++++- .../node/expression/builtin/number/Decimal.java | 7 ++++++- .../node/expression/builtin/number/Integer.java | 7 ++++++- .../node/expression/builtin/number/SmallInteger.java | 7 ++++++- .../runtime/callable/UnresolvedSymbol.java | 2 +- .../org/enso/compiler/pass/desugar/ComplexType.scala | 6 +++++- .../lib/Standard/Base/0.0.0-dev/src/Data/List.enso | 4 ++-- .../lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso | 10 ++++------ 9 files changed, 45 insertions(+), 16 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java index d1a1a2092b00..5494e7ab67a6 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java @@ -3,5 +3,12 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"message"}) -public class CompileError extends Builtin {} +import java.util.List; + +@BuiltinType +public class CompileError extends Builtin { + @Override + protected List getDeclaredConstructors() { + return List.of(new Cons("Make_Compile_Error", "message")); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java index 86f820b79ea0..6d8787459c9b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java @@ -4,4 +4,9 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class BigInteger extends Builtin {} +public class BigInteger extends Builtin { + @Override + protected Class getSuperType() { + return Integer.class; + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java index 18cbf5359637..19c98922a357 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java @@ -4,4 +4,9 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(name = "Standard.Base.Data.Numbers.Decimal") -public class Decimal extends Builtin {} +public class Decimal extends Builtin { + @Override + protected Class getSuperType() { + return Number.class; + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java index 318bbd3fcda3..66e233968901 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java @@ -4,4 +4,9 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(name = "Standard.Base.Data.Numbers.Integer") -public class Integer extends Builtin {} +public class Integer extends Builtin { + @Override + protected Class getSuperType() { + return Number.class; + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java index b5c255042261..e832ac5391d9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java @@ -4,4 +4,9 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType -public class SmallInteger extends Builtin {} +public class SmallInteger extends Builtin { + @Override + protected Class getSuperType() { + return Integer.class; + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedSymbol.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedSymbol.java index c9194b4d2646..2fc272f3f9ea 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedSymbol.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedSymbol.java @@ -60,7 +60,7 @@ public ModuleScope getScope() { public Function resolveFor(Type type) { Type current = type; while (current != null) { - Function candidate = scope.lookupMethodDefinition(type, name); + Function candidate = scope.lookupMethodDefinition(current, name); if (candidate != null) { return candidate; } 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 01ed3451aedd..2c3a943591b0 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 @@ -194,7 +194,11 @@ case object ComplexType extends IRPass { typ.location ) - sumType :: allEntities + val withAnnotations = annotations + .map(ann => sumType.updateMetadata(ModuleAnnotations -->> ann)) + .getOrElse(sumType) + + withAnnotations :: allEntities } /** Generates a method definition from a definition in complex type def body. diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso index 4a3a918b2d61..201374a63835 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/List.enso @@ -1,3 +1,3 @@ type List - type Nil - type Cons x xs + Nil + Cons x xs diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso index acac8402aef4..c730e78b4682 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Numbers.enso @@ -1,7 +1,5 @@ -type Number_Tp - @Builtin_Type - type Number +@Builtin_Type +type Number -type Integer_Tp - @Builtin_Type - type Integer +@Builtin_Type +type Integer From 6d95c4a2bca8bae93d43fa2e24df4e11880ebe0c Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 3 Aug 2022 17:44:48 +0200 Subject: [PATCH 027/110] more painstaking fixing --- .../org/enso/compiler/codegen/AstToIr.scala | 24 +++++------------ .../scala/org/enso/compiler/core/IR.scala | 5 ---- .../compiler/test/codegen/AstToIrTest.scala | 14 ---------- .../test/semantic/RuntimeManagementTest.scala | 27 ++++++++++--------- .../interpreter/test/semantic/TextTest.scala | 7 ++--- .../Base/0.0.0-dev/src/Runtime/Resource.enso | 5 ++-- 6 files changed, 27 insertions(+), 55 deletions(-) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala index 2b30d194951d..3902beb666c9 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstToIr.scala @@ -155,25 +155,13 @@ object AstToIr { } case AstView.TypeDef(typeName, args, body) => val translatedBody = translateTypeBody(body) - val containsAtomDefOrInclude = translatedBody.exists { - case _: IR.Module.Scope.Definition.Data => true - case _: IR.Name.Literal => true - case _ => false - } - val hasArgs = args.nonEmpty + Module.Scope.Definition.SugaredType( + buildName(typeName), + args.map(translateArgumentDefinition(_)), + translatedBody, + getIdentifiedLocation(inputAst) + ) - if (containsAtomDefOrInclude && !hasArgs) { - Module.Scope.Definition.SugaredType( - buildName(typeName), - args.map(translateArgumentDefinition(_)), - translatedBody, - getIdentifiedLocation(inputAst) - ) - } else if (!containsAtomDefOrInclude) { - Error.Syntax(inputAst, Error.Syntax.InterfaceDefinition) - } else { - Error.Syntax(inputAst, Error.Syntax.InvalidTypeDefinition) - } case AstView.MethodDefinition(targetPath, name, args, definition) => val nameId: AST.Ident = name match { case AST.Ident.Var.any(name) => name 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 4f76b87fe491..5954f968ce52 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 @@ -7289,11 +7289,6 @@ object IR { "Invalid definition of a type." } - case object InterfaceDefinition extends Reason { - override def explanation: String = - "Interface definitions are not supported yet." - } - case class TypeDefinedInline(typeName: String) extends Reason { override def explanation: String = s"Cannot define $typeName, type definitions are not supported " + diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala index 5a0c814042a4..c5b72c83d03f 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala @@ -681,20 +681,6 @@ class AstToIrTest extends CompilerTest with Inside { .reason shouldBe an[IR.Error.Syntax.InvalidTypeDefinition.type] } - "disallow definitions that do not define or include an atom" in { - val ir = - """ - |type Maybe - | is_just = case this of - | Just _ -> True - | Nothing -> False - |""".stripMargin.toIrModule.bindings.head - - ir shouldBe an[IR.Error.Syntax] - ir.asInstanceOf[IR.Error.Syntax] - .reason shouldBe an[IR.Error.Syntax.InterfaceDefinition.type] - } - "allow defining methods with operator names" in { val body = """ 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 290ea01d9948..220122964476 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 @@ -80,12 +80,13 @@ class RuntimeManagementTest extends InterpreterTest { |from Standard.Base.Runtime.Resource import Managed_Resource |from Standard.Base.IO import all | - |type Mock_File i + |type Mock_File + | Mk_Mock_File i | |free_resource r = IO.println ("Freeing: " + r.to_text) | |create_resource i = - | c = Mock_File i + | c = Mk_Mock_File i | r = Managed_Resource.register c here.free_resource | r . with f-> IO.println ("Accessing: " + f.to_text) | @@ -107,8 +108,8 @@ class RuntimeManagementTest extends InterpreterTest { totalOut ++= consumeOut } - def mkAccessStr(i: Int): String = s"Accessing: (Mock_File $i)" - def mkFreeStr(i: Int): String = s"Freeing: (Mock_File $i)" + def mkAccessStr(i: Int): String = s"Accessing: (Mk_Mock_File $i)" + def mkFreeStr(i: Int): String = s"Freeing: (Mk_Mock_File $i)" def all = 0.to(4).map(mkAccessStr) ++ 0.to(4).map(mkFreeStr) totalOut should contain theSameElementsAs all } @@ -120,12 +121,13 @@ class RuntimeManagementTest extends InterpreterTest { |from Standard.Base.IO import all |import Standard.Base.Nothing | - |type Mock_File i + |type Mock_File + | Mk_Mock_File i | |free_resource r = IO.println ("Freeing: " + r.to_text) | |create_resource i = - | c = Mock_File i + | c = Mk_Mock_File i | r = Managed_Resource.register c here.free_resource | r . with f-> IO.println ("Accessing: " + f.to_text) | if i % 2 == 0 then r.finalize else Nothing @@ -148,8 +150,8 @@ class RuntimeManagementTest extends InterpreterTest { totalOut ++= consumeOut } - def mkAccessStr(i: Int): String = s"Accessing: (Mock_File $i)" - def mkFreeStr(i: Int): String = s"Freeing: (Mock_File $i)" + def mkAccessStr(i: Int): String = s"Accessing: (Mk_Mock_File $i)" + def mkFreeStr(i: Int): String = s"Freeing: (Mk_Mock_File $i)" def all = 0.to(4).map(mkAccessStr) ++ 0.to(4).map(mkFreeStr) totalOut should contain theSameElementsAs all } @@ -161,12 +163,13 @@ class RuntimeManagementTest extends InterpreterTest { |from Standard.Base.IO import all |import Standard.Base.Nothing | - |type Mock_File i + |type Mock_File + | Mk_Mock_File i | |free_resource r = IO.println ("Freeing: " + r.to_text) | |create_resource i = - | c = Mock_File i + | c = Mk_Mock_File i | r = Managed_Resource.register c here.free_resource | r . with f-> IO.println ("Accessing: " + f.to_text) | if i % 2 == 0 then r.take else Nothing @@ -189,8 +192,8 @@ class RuntimeManagementTest extends InterpreterTest { totalOut ++= consumeOut } - def mkAccessStr(i: Int): String = s"Accessing: (Mock_File $i)" - def mkFreeStr(i: Int): String = s"Freeing: (Mock_File $i)" + def mkAccessStr(i: Int): String = s"Accessing: (Mk_Mock_File $i)" + def mkFreeStr(i: Int): String = s"Freeing: (Mk_Mock_File $i)" def all = 0.to(4).map(mkAccessStr) ++ List(1, 3).map(mkFreeStr) totalOut should contain theSameElementsAs all } 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 6cedc163591a..4ad2d7c8d60f 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 @@ -37,15 +37,16 @@ class TextTest extends InterpreterTest { val code = """import Standard.Base.IO | - |type My_Type a + |type My_Type + | Mk_My_Type a | |main = | IO.println 5 - | IO.println (My_Type (My_Type 10)) + | IO.println (Mk_My_Type (Mk_My_Type 10)) | IO.println "123" |""".stripMargin eval(code) - consumeOut shouldEqual List("5", "(My_Type (My_Type 10))", "123") + consumeOut shouldEqual List("5", "(Mk_My_Type (Mk_My_Type 10))", "123") } "support text creation with raw block literals" in { diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso index 0bd076aedb43..5a2475926ddc 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso @@ -1,9 +1,8 @@ bracket : Any -> (Any -> Nothing) -> (Any -> Any) -> Any bracket ~constructor ~destructor ~action = @Builtin_Method "Resource.bracket" -type Managed_Resource_Tp - @Builtin_Type - type Managed_Resource +@Builtin_Type +type Managed_Resource register resource function = @Builtin_Method "Managed_Resource.register" finalize = @Builtin_Method "Managed_Resource.finalize" with ~action = @Builtin_Method "Managed_Resource.with" From f19c994b3dd913116a10c0a01d9fc46f63349737 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 3 Aug 2022 18:33:55 +0200 Subject: [PATCH 028/110] keep going, try not to cry --- .../caseexpr/ObjectEqualityBranchNode.java | 24 ++++++++++++ .../org/enso/interpreter/runtime/Module.java | 16 ++++---- .../interpreter/runtime/builtin/Builtins.java | 2 +- .../runtime/scope/ModuleScope.java | 11 +++++- .../runtime/scope/TopLevelScope.java | 2 +- .../scala/org/enso/compiler/Compiler.scala | 4 +- .../enso/compiler/codegen/IrToTruffle.scala | 5 ++- .../enso/compiler/pass/resolve/Patterns.scala | 17 +++------ .../org/enso/compiler/test/CompilerTest.scala | 4 +- .../test/semantic/MethodsTest.scala | 38 ++----------------- .../Standard/Base/0.0.0-dev/src/Data/Any.enso | 5 +-- 11 files changed, 62 insertions(+), 66 deletions(-) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ObjectEqualityBranchNode.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ObjectEqualityBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ObjectEqualityBranchNode.java new file mode 100644 index 000000000000..81b3a2bb67b4 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ObjectEqualityBranchNode.java @@ -0,0 +1,24 @@ +package org.enso.interpreter.node.controlflow.caseexpr; + +import com.oracle.truffle.api.RootCallTarget; +import com.oracle.truffle.api.frame.VirtualFrame; + +public class ObjectEqualityBranchNode extends BranchNode { + private final Object expected; + + public static BranchNode build(RootCallTarget branch, Object expected) { + return new ObjectEqualityBranchNode(branch, expected); + } + + private ObjectEqualityBranchNode(RootCallTarget branch, Object expected) { + super(branch); + this.expected = expected; + } + + @Override + public void execute(VirtualFrame frame, Object state, Object target) { + if (target == expected) { + accept(frame, state, new Object[0]); + } + } +} 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 2af450990f89..b1cd299a99a2 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 @@ -156,10 +156,10 @@ public Module(QualifiedName name, Package pkg, Rope literalSource) * @param pkg the package this module belongs to. May be {@code null}, if the module does not * belong to a package. */ - private Module(QualifiedName name, Package pkg) { + private Module(QualifiedName name, Package pkg, Context context) { this.sources = ModuleSources.NONE; this.name = name; - this.scope = new ModuleScope(this); + this.scope = new ModuleScope(this, context); this.pkg = pkg; this.compilationStage = CompilationStage.AFTER_CODEGEN; this.cache = new ModuleCache(this); @@ -175,8 +175,8 @@ private Module(QualifiedName name, Package pkg) { * belong to a package. * @return the module with empty scope. */ - public static Module empty(QualifiedName name, Package pkg) { - return new Module(name, pkg); + public static Module empty(QualifiedName name, Package pkg, Context context) { + return new Module(name, pkg, context); } /** Clears any literal source set for this module. */ @@ -272,7 +272,7 @@ public String getPath() { * @return the scope defined by this module */ public ModuleScope compileScope(Context context) { - ensureScopeExists(); + ensureScopeExists(context); if (!compilationStage.isAtLeast(CompilationStage.AFTER_CODEGEN)) { try { compile(context); @@ -283,9 +283,9 @@ public ModuleScope compileScope(Context context) { } /** Create scope if it does not exist. */ - public void ensureScopeExists() { + public void ensureScopeExists(Context context) { if (scope == null) { - scope = new ModuleScope(this); + scope = new ModuleScope(this, context); compilationStage = CompilationStage.INITIAL; } } @@ -337,7 +337,7 @@ public final boolean isModuleSource(Source s) { } private void compile(Context context) throws IOException { - ensureScopeExists(); + ensureScopeExists(context); Source source = getSource(); if (source == null) return; scope.reset(); 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 064685e526bc..139b989fc90e 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 @@ -86,7 +86,7 @@ public static class Debug { */ public Builtins(Context context) { Language language = context.getLanguage(); - module = Module.empty(QualifiedName.fromString(MODULE_NAME), null); + module = Module.empty(QualifiedName.fromString(MODULE_NAME), null, null); scope = module.compileScope(context); builtins = readBuiltinTypesMetadata(scope); 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 a5fc8faffedb..b167307f032e 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 @@ -5,6 +5,7 @@ import java.util.*; import com.oracle.truffle.api.interop.TruffleObject; +import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.Module; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; @@ -28,10 +29,16 @@ public class ModuleScope implements TruffleObject { * Creates a new object of this class. * * @param module the module related to the newly created scope. + * @param context the current langauge context */ - public ModuleScope(Module module) { + public ModuleScope(Module module, Context context) { this.module = module; - this.associatedType = new Type(module.getName().item(), this, null, false); + this.associatedType = + new Type( + module.getName().item(), + this, + context == null ? null : context.getBuiltins().any(), + false); } /** diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java index 148a88e053ac..a7991639e764 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/scope/TopLevelScope.java @@ -131,7 +131,7 @@ private static Module getModule(TopLevelScope scope, Object[] arguments) private static Module createModule(TopLevelScope scope, Object[] arguments, Context context) throws ArityException, UnsupportedTypeException { String moduleName = Types.extractArguments(arguments, String.class); - return Module.empty(QualifiedName.simpleName(moduleName), null); + return Module.empty(QualifiedName.simpleName(moduleName), null, context); } private static Module registerModule(TopLevelScope scope, Object[] arguments, Context context) 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 ac102b1babc6..c3fcab830653 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala @@ -394,7 +394,7 @@ class Compiler( Compiler.defaultLogLevel, s"Parsing the module [${module.getName}]." ) - module.ensureScopeExists() + module.ensureScopeExists(context) module.getScope.reset() if (irCachingEnabled && !module.isInteractive) { @@ -412,7 +412,7 @@ class Compiler( Compiler.defaultLogLevel, s"Loading module `${module.getName}` from source." ) - module.ensureScopeExists() + module.ensureScopeExists(context) module.getScope.reset() val moduleContext = ModuleContext( 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 67a894d4612d..3abc803d4ffd 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 @@ -920,7 +920,10 @@ class IrToTruffle( } else if (tpe == any) { CatchAllBranchNode.build(branchCodeNode.getCallTarget) } else { - throw new CompilerError("think about this") + ObjectEqualityBranchNode.build( + branchCodeNode.getCallTarget, + tpe + ) } Right(branch) case Some( diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/Patterns.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/Patterns.scala index 10f0edcfe536..6a586a8124a8 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/Patterns.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/Patterns.scala @@ -100,6 +100,10 @@ object Patterns extends IRPass { consName.updateMetadata( this -->> BindingsMap.Resolution(value) ) + case Right(value: BindingsMap.ResolvedType) => + consName.updateMetadata( + this -->> BindingsMap.Resolution(value) + ) case Right(_: BindingsMap.ResolvedPolyglotSymbol) => IR.Error.Resolution( consName, @@ -114,13 +118,6 @@ object Patterns extends IRPass { "a pattern match" ) ) - case Right(_: BindingsMap.ResolvedType) => - IR.Error.Resolution( - consName, - IR.Error.Resolution.UnexpectedType( - "a pattern match" - ) - ) } .getOrElse(consName) @@ -137,11 +134,7 @@ object Patterns extends IRPass { throw new CompilerError( "Impossible, should be transformed into an error before." ) - case BindingsMap.ResolvedType(_, _) => - throw new CompilerError( - "Impossible, should be transformed into an error before." - ) - + case BindingsMap.ResolvedType(_, _) => 0 } } expectedArity match { diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala index e3c027e09cf0..35e18e7c06e1 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala @@ -245,7 +245,7 @@ trait CompilerRunner { isGeneratingDocs: Boolean = false ): ModuleContext = { ModuleContext( - module = Module.empty(moduleName, null), + module = Module.empty(moduleName, null, null), freshNameSupply = freshNameSupply, passConfiguration = passConfiguration, compilerConfig = compilerConfig, @@ -269,7 +269,7 @@ trait CompilerRunner { passConfiguration: Option[PassConfiguration] = None, compilerConfig: CompilerConfig = defaultConfig ): InlineContext = { - val mod = Module.empty(QualifiedName.simpleName("Test_Module"), null) + val mod = Module.empty(QualifiedName.simpleName("Test_Module"), null, null) mod.unsafeBuildIrStub() InlineContext( module = mod, 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 5db01fe20be4..4752e4308017 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 @@ -100,20 +100,6 @@ class MethodsTest extends InterpreterTest { eval(code) shouldEqual 19 } - "be dispatched to the proper constructor" in { - val code = - """from Standard.Base.Data.List import all - | - |Nil.sum = acc -> acc - |Cons.sum = acc -> case self of - | Cons h t -> t.sum (h + acc) - | - |main = Cons 1 (Cons 2 Nil) . sum 0 - |""".stripMargin - - eval(code) shouldEqual 3 - } - "throw an exception when non-existent" in { val code = """ @@ -135,10 +121,10 @@ class MethodsTest extends InterpreterTest { |type Baz | |Any.Any.method = case self of - | Foo -> 1 - | Bar -> 2 - | Baz -> 3 - | _ -> 0 + | Foo -> 1 + | Bar -> 2 + | Baz -> 3 + | _ -> 0 | |main = | IO.println Foo.method @@ -165,21 +151,5 @@ class MethodsTest extends InterpreterTest { //eval(code) shouldEqual 1 pending } - - "work as expected when defined across different constructors" in { - val code = - """from Standard.Base.Data.List import all - | - |Nil.sum = 0 - |Cons.sum = case self of - | Cons h t -> h + t.sum - | - |main = - | myList = Cons 1 (Cons 2 (Cons 3 Nil)) - | myList.sum - |""".stripMargin - - eval(code) shouldEqual 6 - } } } diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso index 4d8d3d2d65a5..5b0f4405ab21 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso @@ -1,3 +1,2 @@ -type Any_Tp - @Builtin_Type - type Any +@Builtin_Type +type Any From 63b61f47a52ac0d1b669e8ace1ae2e92ed380377 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 4 Aug 2022 01:02:32 +0200 Subject: [PATCH 029/110] more progress --- .../node/expression/atom/ConstantNode.java | 33 +++++ .../node/expression/builtin/Builtin.java | 2 + .../error/InexhaustivePatternMatchError.java | 11 +- .../enso/interpreter/runtime/data/Type.java | 46 ++++++ .../enso/compiler/codegen/IrToTruffle.scala | 131 ++++++++++-------- .../test/semantic/ConstructorsTest.scala | 3 +- .../test/semantic/ConversionMethodsTest.scala | 15 +- .../test/semantic/PatternMatchTest.scala | 29 ++-- .../Base/0.0.0-dev/src/Error/Common.enso | 10 +- 9 files changed, 193 insertions(+), 87 deletions(-) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/ConstantNode.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/ConstantNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/ConstantNode.java new file mode 100644 index 000000000000..0779c0bda6c9 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/ConstantNode.java @@ -0,0 +1,33 @@ +package org.enso.interpreter.node.expression.atom; + +import com.oracle.truffle.api.TruffleLanguage; +import com.oracle.truffle.api.frame.VirtualFrame; +import com.oracle.truffle.api.nodes.RootNode; +import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.state.Stateful; + +public class ConstantNode extends RootNode { + private final Object constant; + + /** + * Creates a new instance of this node. + * + * @param language the current language instance. + * @param atomConstructor the constructor to return. + */ + public ConstantNode(TruffleLanguage language, Object constant) { + super(language); + this.constant = constant; + } + + /** + * Executes the node, returning the predefined constructor. + * + * @param frame current execution frame + * @return the constant constructor + */ + public Stateful execute(VirtualFrame frame) { + Object state = Function.ArgumentsHelper.getState(frame.getArguments()); + return new Stateful(state, constant); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java index 180ef11a7c7a..066af4e263c3 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java @@ -7,6 +7,7 @@ import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.scope.ModuleScope; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -70,6 +71,7 @@ public final void initialize(ModuleScope scope, Map, Bu uniqueConstructor = constructors[0]; } } + type.generateGetters(Arrays.asList(constructors)); } public final Type getType() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java index 78cad5219e70..32a53adc121d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java @@ -3,5 +3,12 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"scrutinee"}) -public class InexhaustivePatternMatchError extends Builtin {} +import java.util.List; + +@BuiltinType +public class InexhaustivePatternMatchError extends Builtin { + @Override + protected List getDeclaredConstructors() { + return List.of(new Cons("Make_Inexhaustive_Pattern_Match_Error", "scrutinee")); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index e4a68e292005..e4ac86a37ef4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -2,20 +2,31 @@ import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.RootCallTarget; +import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; +import com.oracle.truffle.api.nodes.RootNode; +import org.enso.interpreter.node.expression.atom.ConstantNode; +import org.enso.interpreter.node.expression.atom.GetFieldNode; +import org.enso.interpreter.node.expression.atom.QualifiedAccessorNode; import org.enso.interpreter.runtime.Context; 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.callable.function.Function; +import org.enso.interpreter.runtime.callable.function.FunctionSchema; import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.pkg.QualifiedName; +import java.util.Arrays; +import java.util.List; import java.util.Map; @ExportLibrary(MethodDispatchLibrary.class) @@ -24,12 +35,27 @@ public class Type implements TruffleObject { private @CompilerDirectives.CompilationFinal ModuleScope definitionScope; private final boolean builtin; private final Type supertype; + private boolean gettersGenerated; public Type(String name, ModuleScope definitionScope, Type supertype, boolean builtin) { this.name = name; this.definitionScope = definitionScope; this.supertype = supertype; this.builtin = builtin; + generateQualifiedAccessor(); + } + + private void generateQualifiedAccessor() { + var node = new ConstantNode(null, this); + var callTarget = Truffle.getRuntime().createCallTarget(node); + var function = + new Function( + callTarget, + null, + new FunctionSchema( + new ArgumentDefinition(0, "this", ArgumentDefinition.ExecutionMode.EXECUTE))); + definitionScope.registerMethod( + definitionScope.getAssociatedType(), this.name.toLowerCase(), function); // TODO lowercase remove when merge } public QualifiedName getQualifiedName() { @@ -73,6 +99,26 @@ public Type getSupertype() { return supertype; } + public void generateGetters(List constructors) { + if (gettersGenerated) return; + if (constructors.size() != 1) return; // TODO + var cons = constructors.get(0); + Arrays.stream(cons.getFields()) + .forEach( + field -> { + GetFieldNode node = new GetFieldNode(null, field.getPosition()); + RootCallTarget callTarget = Truffle.getRuntime().createCallTarget(node); + var f = + new Function( + callTarget, + null, + new FunctionSchema( + new ArgumentDefinition( + 0, "this", ArgumentDefinition.ExecutionMode.EXECUTE))); + definitionScope.registerMethod(this, field.getName(), f); + }); + } + @ExportMessage boolean hasFunctionalDispatch() { return true; 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 3abc803d4ffd..90b7f95c65c3 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 @@ -76,6 +76,7 @@ import org.enso.interpreter.runtime.data.Type import scala.collection.mutable import scala.collection.mutable.ArrayBuffer import scala.jdk.OptionConverters._ +import scala.jdk.CollectionConverters._ /** This is an implementation of a codegeneration pass that lowers the Enso * [[IR]] into the truffle [[org.enso.compiler.core.Core.Node]] structures that @@ -157,10 +158,6 @@ class IrToTruffle( moduleScope.addExport(exp.module.unsafeAsModule().getScope) } val imports = module.imports - val atomDefs = module.bindings.flatMap { - case tp: IR.Module.Scope.Definition.Type => tp.members - case _ => List() - } val methodDefs = module.bindings.collect { case method: IR.Module.Scope.Definition.Method.Explicit => method } @@ -179,68 +176,76 @@ class IrToTruffle( case _: Error => } - // Register the atoms and their constructors in scope - val atomConstructors = - atomDefs.map(cons => moduleScope.getConstructors.get(cons.name.name)) - - atomConstructors - .zip(atomDefs) - .foreach { case (atomCons, atomDefn) => - val scopeInfo = atomDefn - .unsafeGetMetadata( - AliasAnalysis, - "No root scope on an atom definition." - ) - .unsafeAs[AliasAnalysis.Info.Scope.Root] - - val dataflowInfo = atomDefn.unsafeGetMetadata( - DataflowAnalysis, - "No dataflow information associated with an atom." - ) - val localScope = new LocalScope( - None, - scopeInfo.graph, - scopeInfo.graph.rootScope, - dataflowInfo - ) + val typeDefs = module.bindings.collect { + case tp: IR.Module.Scope.Definition.Type => tp + } - val argFactory = - new DefinitionArgumentProcessor( - scope = localScope - ) - val argDefs = - new Array[ArgumentDefinition](atomDefn.arguments.size) - val argumentExpressions = - new ArrayBuffer[(RuntimeExpression, RuntimeExpression)] - - for (idx <- atomDefn.arguments.indices) { - val unprocessedArg = atomDefn.arguments(idx) - val arg = argFactory.run(unprocessedArg, idx) - val occInfo = unprocessedArg + typeDefs.foreach { tpDef => + // Register the atoms and their constructors in scope + val atomDefs = tpDef.members + val atomConstructors = + atomDefs.map(cons => moduleScope.getConstructors.get(cons.name.name)) + atomConstructors + .zip(atomDefs) + .foreach { case (atomCons, atomDefn) => + val scopeInfo = atomDefn .unsafeGetMetadata( AliasAnalysis, - "No occurrence on an argument definition." + "No root scope on an atom definition." ) - .unsafeAs[AliasAnalysis.Info.Occurrence] - val slot = localScope.createVarSlot(occInfo.id) - argDefs(idx) = arg - val readArg = - ReadArgumentNode.build(idx, arg.getDefaultValue.orElse(null)) - val assignmentArg = AssignmentNode.build(readArg, slot) - val argRead = ReadLocalVariableNode.build(new FramePointer(0, slot)) - argumentExpressions.append((assignmentArg, argRead)) - } + .unsafeAs[AliasAnalysis.Info.Scope.Root] - val (assignments, reads) = argumentExpressions.unzip - if (!atomCons.isInitialized) { - atomCons.initializeFields( - localScope, - assignments.toArray, - reads.toArray, - argDefs: _* + val dataflowInfo = atomDefn.unsafeGetMetadata( + DataflowAnalysis, + "No dataflow information associated with an atom." ) + val localScope = new LocalScope( + None, + scopeInfo.graph, + scopeInfo.graph.rootScope, + dataflowInfo + ) + + val argFactory = + new DefinitionArgumentProcessor( + scope = localScope + ) + val argDefs = + new Array[ArgumentDefinition](atomDefn.arguments.size) + val argumentExpressions = + new ArrayBuffer[(RuntimeExpression, RuntimeExpression)] + + for (idx <- atomDefn.arguments.indices) { + val unprocessedArg = atomDefn.arguments(idx) + val arg = argFactory.run(unprocessedArg, idx) + val occInfo = unprocessedArg + .unsafeGetMetadata( + AliasAnalysis, + "No occurrence on an argument definition." + ) + .unsafeAs[AliasAnalysis.Info.Occurrence] + val slot = localScope.createVarSlot(occInfo.id) + argDefs(idx) = arg + val readArg = + ReadArgumentNode.build(idx, arg.getDefaultValue.orElse(null)) + val assignmentArg = AssignmentNode.build(readArg, slot) + val argRead = ReadLocalVariableNode.build(new FramePointer(0, slot)) + argumentExpressions.append((assignmentArg, argRead)) + } + + val (assignments, reads) = argumentExpressions.unzip + if (!atomCons.isInitialized) { + atomCons.initializeFields( + localScope, + assignments.toArray, + reads.toArray, + argDefs: _* + ) + } } - } + val tp = moduleScope.getType(tpDef.name.name).get() + tp.generateGetters(atomConstructors.asJava) + } // Register the method definitions in scope methodDefs.foreach(methodDef => { @@ -458,7 +463,13 @@ class IrToTruffle( expr.getMetadata(MethodDefinitions).map { res => res.target match { case BindingsMap.ResolvedType(definitionModule, tp) => - definitionModule.unsafeAsModule().getScope.getTypes.get(tp) + definitionModule + .unsafeAsModule() + .getScope + .getType(tp.name) + .orElseGet(() => + throw new CompilerError(s"Type ${tp.name} not found in codegen.") + ) case BindingsMap.ResolvedModule(module) => module.unsafeAsModule().getScope.getAssociatedType case BindingsMap.ResolvedConstructor(_, _) => 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 53a805c38fa0..665a3d48bbb0 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 @@ -88,7 +88,8 @@ class ConstructorsTest extends InterpreterTest { """import Standard.Base.Nothing |from Standard.Base.Data.List import all | - |type Cons2 a b + |type C2 + | Cons2 a b | |Nothing.genList = i -> if i == 0 then Nil2 else Cons2 i (Nothing.genList (i - 1)) | diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConversionMethodsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConversionMethodsTest.scala index 8d0505fad0a2..673d38a24334 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConversionMethodsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ConversionMethodsTest.scala @@ -11,14 +11,17 @@ class ConversionMethodsTest extends InterpreterTest { "be defined in the global scope and dispatched to" in { val code = """ - |type Foo foo - |type Bar bar - |type Baz baz + |type Foo + | Mk_Foo foo + |type Bar + | Mk_Bar bar + |type Baz + | Mk_Baz baz | - |Foo.from (that:Bar) = Foo that.bar - |Foo.from (that:Baz) = Foo that.baz + |Foo.from (that:Bar) = Mk_Foo that.bar + |Foo.from (that:Baz) = Mk_Foo that.baz | - |main = (Foo.from (Baz 10)).foo + (Foo.from (Bar 20)).foo + |main = (Foo.from (Mk_Baz 10)).foo + (Foo.from (Mk_Bar 20)).foo |""".stripMargin eval(code) shouldEqual 30 } 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 1b165b2147cb..856bce13d55c 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 @@ -33,14 +33,15 @@ class PatternMatchTest extends InterpreterTest { val code = """from Standard.Base.Data.List import all | - |type MyAtom a + |type My_Atom + | Mk_My_Atom a | |main = | f = case _ of - | MyAtom a -> a + | Mk_My_Atom a -> a | _ -> -100 | - | f (MyAtom 50) + f Nil + | f (Mk_My_Atom 50) + f Nil |""".stripMargin eval(code) shouldEqual -50 @@ -49,14 +50,15 @@ class PatternMatchTest extends InterpreterTest { "work for named catch-all patterns" in { val code = """ - |type MyAtom a + |type My_Atom + | Mk_My_Atom a | |main = | f = case _ of - | MyAtom a -> a + | Mk_My_Atom a -> a | a -> a + 5 | - | f (MyAtom 50) + f 30 + | f (Mk_My_Atom 50) + f 30 |""".stripMargin eval(code) shouldEqual 85 @@ -137,18 +139,21 @@ class PatternMatchTest extends InterpreterTest { val code = """from Standard.Base.Data.List import all | - |type MyAtom a - |type One a - |type Two a + |type My_Atom + | Mk_My_Atom a + |type One + | Mk_One a + |type Two + | Mk_Two a | |main = | f = case _ of - | MyAtom a -> case a of - | One Nil -> 50 + | Mk_My_Atom a -> case a of + | Mk_One Nil -> 50 | _ -> 30 | _ -> 20 | - | f (MyAtom (One Nil)) + | f (Mk_My_Atom (Mk_One Nil)) |""".stripMargin eval(code) shouldEqual 50 diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index df87b49f6ca9..c9264247c8a6 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso @@ -1,6 +1,5 @@ -type Panic_Tp - @Builtin_Type - type Panic +@Builtin_Type +type Panic throw payload = @Builtin_Method "Panic.throw" catch_primitive ~action handler = @Builtin_Method "Panic.catch_primitive" @@ -19,9 +18,8 @@ type Inexhaustive_Pattern_Match_Error scrutinee @Builtin_Type type Arity_Error expected_min expected_max actual -type Error_Tp - @Builtin_Type - type Error +@Builtin_Type +type Error throw payload = @Builtin_Method "Error.throw" catch_primitive handler = @Builtin_Method "Error.catch_primitive" catch (handler = x->x) = self.catch_primitive handler From 0d23124d75e284fd6914be6e17c832c778967b78 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 4 Aug 2022 01:33:33 +0200 Subject: [PATCH 030/110] keep em passing --- .../expression/builtin/error/CaughtPanic.java | 4 +++- .../builtin/system/SystemProcessResult.java | 11 +++++++++-- .../interpreter/runtime/builtin/Builtins.java | 4 ++-- .../enso/interpreter/runtime/data/Type.java | 11 ++++++++++- .../codegen/RuntimeStubsGenerator.scala | 5 +++-- .../test/semantic/NamedArgumentsTest.scala | 19 ++++++++++++------- .../Base/0.0.0-dev/src/Data/Boolean.enso | 18 +++++++++--------- .../Base/0.0.0-dev/src/Data/Text.enso | 5 ++--- .../Base/0.0.0-dev/src/Data/Time/Date.enso | 2 +- 9 files changed, 51 insertions(+), 28 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java index 743932d947da..387b081c4da4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java @@ -4,4 +4,6 @@ import org.enso.interpreter.node.expression.builtin.Builtin; @BuiltinType(params = {"payload", "internal_original_exception"}) -public class CaughtPanic extends Builtin {} +public class CaughtPanic extends Builtin { + +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java index 88be18a52123..c49ac522dcd1 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java @@ -3,5 +3,12 @@ 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 {} +import java.util.List; + +@BuiltinType +public class SystemProcessResult extends Builtin { + @Override + protected List getDeclaredConstructors() { + return List.of(new Cons("Make_System_Process_Result", "exit_code", "stdout", "stderr")); + } +} 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 139b989fc90e..e879e2da8bc9 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 @@ -330,8 +330,8 @@ public T getBuiltinType(Class clazz) { return t; } - public Type getBuiltinType(String name) { - return builtinsByName.get(name).getType(); + public Builtin getBuiltinType(String name) { + return builtinsByName.get(name); } /** diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index e4ac86a37ef4..bee6a7a2bb15 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -6,6 +6,7 @@ import com.oracle.truffle.api.Truffle; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Specialization; +import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; @@ -30,6 +31,7 @@ import java.util.Map; @ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(InteropLibrary.class) public class Type implements TruffleObject { private final String name; private @CompilerDirectives.CompilationFinal ModuleScope definitionScope; @@ -55,7 +57,9 @@ private void generateQualifiedAccessor() { new FunctionSchema( new ArgumentDefinition(0, "this", ArgumentDefinition.ExecutionMode.EXECUTE))); definitionScope.registerMethod( - definitionScope.getAssociatedType(), this.name.toLowerCase(), function); // TODO lowercase remove when merge + definitionScope.getAssociatedType(), + this.name.toLowerCase(), + function); // TODO lowercase remove when merge } public QualifiedName getQualifiedName() { @@ -214,4 +218,9 @@ static Function resolve(Type self, Type target, UnresolvedConversion conversion) return function; } } + + @ExportMessage + String toDisplayString(boolean allowSideEffects) { + return name; + } } 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 f673765bbeed..915dfaa9f6f8 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 @@ -30,8 +30,9 @@ class RuntimeStubsGenerator(builtins: Builtins) { if (builtinType == null) { throw new CompilerError("Unknown @BuiltinType " + tp.name) } - scope.registerType(builtinType) - builtinType.setShadowDefinitions(scope) + builtinType.getConstructors.foreach(scope.registerConstructor) + scope.registerType(builtinType.getType) + builtinType.getType.setShadowDefinitions(scope) } else { val rtp = new Type(tp.name, scope, builtins.any(), false) scope.registerType(rtp) 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 23b25a91ea48..f2f4c3ba8239 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 @@ -194,7 +194,8 @@ class NamedArgumentsTest extends InterpreterTest { "be usable with constructors" in { val code = """ - |type Cons2 head rest + |type C2 + | Cons2 head rest |type Nil2 | |main = @@ -214,7 +215,8 @@ class NamedArgumentsTest extends InterpreterTest { val code = """ |type Nil2 - |type Cons2 head (rest = Nil2) + |type C2 + | Cons2 head (rest = Nil2) | |main = | gen_list = i -> if i == 0 then Nil2 else Cons2 (rest = gen_list i-1) head=i @@ -232,7 +234,8 @@ class NamedArgumentsTest extends InterpreterTest { "be resolved dynamically in constructors" in { val code = """ - |type Cons2 head (rest = Nil2) + |type C2 + | Cons2 head (rest = Nil2) |type Nil2 | |main = Cons2 5 @@ -245,7 +248,8 @@ class NamedArgumentsTest extends InterpreterTest { val code = """import Standard.Base.Nothing | - |type Cons2 head (rest = Nil2) + |type C2 + | Cons2 head (rest = Nil2) |type Nil2 | |Nothing.sum_list = list -> case list of @@ -263,12 +267,13 @@ class NamedArgumentsTest extends InterpreterTest { """ |import Standard.Base.IO | - |type My_Tp a=10 b="hello" + |type My_Tp + | Mk_My_Tp a=10 b="hello" | - |main = IO.println My_Tp + |main = IO.println Mk_My_Tp |""".stripMargin eval(code) - consumeOut should equal(List("(My_Tp 10 'hello')")) + consumeOut should equal(List("(Mk_My_Tp 10 'hello')")) } } } diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso index 697e638aea56..c132f9b4a148 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso @@ -1,11 +1,11 @@ -type Boolean_Tp - @Builtin_Type - type Boolean - - if_then_else ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else" - @Builtin_Type -type True +type Boolean + True + False + if_then_else ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else" -@Builtin_Type -type False +#@Builtin_Type +#type True +# +#@Builtin_Type +#type False diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso index c905ed6e639c..98c9e6791f2c 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso @@ -1,3 +1,2 @@ -type Text_Tp - @Builtin_Type - type Text +@Builtin_Type +type Text diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso index d2486efa28e2..4c04f3f4d38a 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso @@ -4,7 +4,7 @@ polyglot java import java.time.format.DateTimeFormatter new year (month = 1) (day = 1) = LocalDate.of year month day type Date_Tp - type Date internal_local_date + Date internal_local_date year = self . internal_local_date . getYear month = self . internal_local_date . getMonthValue day = self . internal_local_date . getDayOfMonth From 6e5fa1686407397e42db99f2ef916c0acdeec22a Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 4 Aug 2022 15:13:27 +0200 Subject: [PATCH 031/110] checkpoint --- .../expression/builtin/error/CaughtPanic.java | 9 ++- .../builtin/error/PolyglotError.java | 11 +++- .../expression/builtin/error/SyntaxError.java | 11 +++- .../enso/interpreter/runtime/data/Type.java | 1 + .../enso/compiler/codegen/IrToTruffle.scala | 62 ++++++++++++++----- .../ComplexTypeDefinitionSugarTest.scala | 12 ++-- .../test/semantic/DataflowErrorsTest.scala | 30 +++++---- .../test/semantic/MixfixFunctionsTest.scala | 14 +++-- .../test/semantic/PanicsTest.scala | 6 +- .../Base/0.0.0-dev/src/Data/Array.enso | 5 +- .../Base/0.0.0-dev/src/Data/Boolean.enso | 6 -- .../Base/0.0.0-dev/src/Error/Common.enso | 3 +- .../Standard/Base/0.0.0-dev/src/Polyglot.enso | 5 +- 13 files changed, 111 insertions(+), 64 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java index 387b081c4da4..0aa4a042fc2d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java @@ -3,7 +3,12 @@ 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 { +import java.util.List; +@BuiltinType +public class CaughtPanic extends Builtin { + @Override + protected List getDeclaredConstructors() { + return List.of(new Cons("Make_Caught_Panic", "payload", "internal_original_exception")); + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java index afedbf4da69d..e990cd4c7bc0 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java @@ -3,5 +3,12 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"cause"}) -public class PolyglotError extends Builtin {} +import java.util.List; + +@BuiltinType +public class PolyglotError extends Builtin { + @Override + protected List getDeclaredConstructors() { + return List.of(new Cons("Make_Polyglot_Error", "cause")); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java index d097110a9583..8f30eba00086 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java @@ -3,5 +3,12 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; -@BuiltinType(params = {"message"}) -public class SyntaxError extends Builtin {} +import java.util.List; + +@BuiltinType +public class SyntaxError extends Builtin { + @Override + protected List getDeclaredConstructors() { + return List.of(new Cons("Make_Syntax_Error", "message")); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index bee6a7a2bb15..5ea572d8fa17 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -105,6 +105,7 @@ public Type getSupertype() { public void generateGetters(List constructors) { if (gettersGenerated) return; + gettersGenerated = true; if (constructors.size() != 1) return; // TODO var cons = constructors.get(0); Arrays.stream(cons.getFields()) 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 90b7f95c65c3..0f0825754945 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/IrToTruffle.scala @@ -36,7 +36,10 @@ import org.enso.interpreter.node.callable.{ SequenceLiteralNode } import org.enso.interpreter.node.controlflow.caseexpr._ -import org.enso.interpreter.node.expression.atom.QualifiedAccessorNode +import org.enso.interpreter.node.expression.atom.{ + ConstantNode, + QualifiedAccessorNode +} import org.enso.interpreter.node.expression.constant._ import org.enso.interpreter.node.expression.foreign.ForeignMethodCallNode import org.enso.interpreter.node.expression.literal.LiteralNode @@ -561,6 +564,22 @@ class IrToTruffle( ) } + def mkTypeGetter(tp: Type): RuntimeFunction = { + new RuntimeFunction( + Truffle.getRuntime.createCallTarget( + new ConstantNode(language, tp) + ), + null, + new FunctionSchema( + new ArgumentDefinition( + 0, + Constants.Names.SELF_ARGUMENT, + ArgumentDefinition.ExecutionMode.EXECUTE + ) + ) + ) + } + val bindingsMap = module.unsafeGetMetadata( BindingAnalysis, "No binding analysis at the point of codegen." @@ -569,7 +588,15 @@ class IrToTruffle( case (name, resolution :: _) => if (resolution.module.unsafeAsModule() != moduleScope.getModule) { resolution match { - case _: BindingsMap.ResolvedType => //throw new CompilerError("todo") + case BindingsMap.ResolvedType(module, tp) => + val runtimeTp = + module.unsafeAsModule().getScope.getType(tp.name).get() + val fun = mkTypeGetter(runtimeTp) + moduleScope.registerMethod( + moduleScope.getAssociatedType, + name, + fun + ) case BindingsMap.ResolvedConstructor(definitionModule, cons) => val runtimeCons = definitionModule .unsafeAsModule() @@ -582,16 +609,15 @@ class IrToTruffle( name, fun ) - case BindingsMap.ResolvedModule( /*module*/ _) => - throw new CompilerError("todo") -// val runtimeCons = -// module.unsafeAsModule().getScope.getAssociatedType -// val fun = mkConsGetter(runtimeCons) -// moduleScope.registerMethod( -// moduleScope.getAssociatedType, -// name, -// fun -// ) + case BindingsMap.ResolvedModule(module) => + val runtimeCons = + module.unsafeAsModule().getScope.getAssociatedType + val fun = mkTypeGetter(runtimeCons) + moduleScope.registerMethod( + moduleScope.getAssociatedType, + name, + fun + ) case BindingsMap.ResolvedMethod(module, method) => val actualModule = module.unsafeAsModule() val fun = actualModule.getScope.getMethods @@ -870,12 +896,14 @@ class IrToTruffle( case None => Left(BadPatternMatch.NonVisibleConstructor(constructor.name)) case Some( - BindingsMap.Resolution( - BindingsMap.ResolvedModule(_ /*mod*/ ) - ) + BindingsMap.Resolution(BindingsMap.ResolvedModule(mod)) ) => - throw new CompilerError("todo") - //Right(mod.unsafeAsModule().getScope.getAssociatedType) + Right( + ObjectEqualityBranchNode.build( + branchCodeNode.getCallTarget, + mod.unsafeAsModule().getScope.getAssociatedType + ) + ) case Some( BindingsMap.Resolution( BindingsMap.ResolvedConstructor(mod, cons) 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 f969ba1d1683..a1f0fbcd6d74 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 @@ -14,8 +14,8 @@ class ComplexTypeDefinitionSugarTest extends InterpreterTest { val code = """ |type My_Type - | type Atom_One - | type Atom_Two + | Atom_One + | Atom_Two | | is_atom_one = case self of | Atom_One -> 10 @@ -34,8 +34,8 @@ class ComplexTypeDefinitionSugarTest extends InterpreterTest { val code = """ |type My_Type - | type Atom_One - | type Atom_Two + | Atom_One + | Atom_Two | | is_atom_one n = case self of | Atom_One -> 10 + n @@ -54,7 +54,7 @@ class ComplexTypeDefinitionSugarTest extends InterpreterTest { val code = """ |type My_Type - | type My_Atom a + | My_Atom a | | is_equal n = case self of | My_Atom a -> n - a @@ -71,7 +71,7 @@ class ComplexTypeDefinitionSugarTest extends InterpreterTest { """import Standard.Base.IO | |type Foo - | type Bar + | Bar | x = | IO.println "foobar" | 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 20f75396fde0..591ee3cb42e0 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 @@ -67,14 +67,15 @@ class DataflowErrorsTest extends InterpreterTest { |from Standard.Base.Error.Common import all |import Standard.Base.IO | - |type MyCons err + |type My_Cons + | Mk_My_Cons err | |main = | unitErr = Error.throw Nothing - | IO.println (unitErr.catch_primitive MyCons) + | IO.println (unitErr.catch_primitive Mk_My_Cons) |""".stripMargin eval(code) - consumeOut shouldEqual List("(MyCons Nothing)") + consumeOut shouldEqual List("(Mk_My_Cons Nothing)") } "accept a method handle in catch function" in { @@ -82,18 +83,20 @@ class DataflowErrorsTest extends InterpreterTest { """from Standard.Base.Error.Common import all |import Standard.Base.IO | - |type MyRecovered x - |type MyError x + |type My_Recovered + | Mk_My_Recovered x + |type My_Error + | Mk_My_Error x | - |MyError.recover = case self of - | MyError x -> MyRecovered x + |My_Error.recover = case self of + | Mk_My_Error x -> Mk_My_Recovered x | |main = - | myErr = Error.throw (MyError 20) + | myErr = Error.throw (Mk_My_Error 20) | IO.println(myErr.catch_primitive .recover) |""".stripMargin eval(code) - consumeOut shouldEqual List("(MyRecovered 20)") + consumeOut shouldEqual List("(Mk_My_Recovered 20)") } "make the catch method an identity for non-error values" in { @@ -106,12 +109,13 @@ class DataflowErrorsTest extends InterpreterTest { """from Standard.Base.Error.Common import all |import Standard.Base.IO | - |type My_Atom a + |type My_Atom + | Mk_My_Atom a |type My_Error | |main = | broken_val = Error.throw My_Error - | atom = My_Atom broken_val + | atom = Mk_My_Atom broken_val | | IO.println atom |""".stripMargin @@ -200,8 +204,8 @@ class DataflowErrorsTest extends InterpreterTest { |""".stripMargin eval(code) consumeOut shouldEqual List( - "(Error: (Syntax_Error 'Unrecognized token.'))", - "(Syntax_Error 'Unrecognized token.')" + "(Error: (Make_Syntax_Error 'Unrecognized token.'))", + "(Make_Syntax_Error 'Unrecognized token.')" ) } } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MixfixFunctionsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MixfixFunctionsTest.scala index bc7f99fde55c..8c1dd058c8a1 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MixfixFunctionsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MixfixFunctionsTest.scala @@ -12,12 +12,13 @@ class MixfixFunctionsTest extends InterpreterTest { "be able to be defined as a method" in { val code = """ - |type Foo a + |type Foo + | Mk_Foo a | |Foo.if_then = x -> case self of - | Foo a -> a + x + | Mk_Foo a -> a + x | - |main = if Foo 2 then 8 + |main = if Mk_Foo 2 then 8 |""".stripMargin eval(code) shouldEqual 10 @@ -26,12 +27,13 @@ class MixfixFunctionsTest extends InterpreterTest { "easily support multiple arguments" in { val code = """ - |type Foo a b + |type Foo + | Mk_Foo a b | |Foo.if_then_else = a -> b -> case self of - | Foo x y -> x + y + a + b + | Mk_Foo x y -> x + y + a + b | - |main = if (Foo 1 2) then 3 else 4 + |main = if (Mk_Foo 1 2) then 3 else 4 |""".stripMargin eval(code) shouldEqual 10 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 d762030376a5..84db3c8a84b0 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 @@ -26,7 +26,6 @@ class PanicsTest extends InterpreterTest { | Panic.throw Bar | IO.println Baz |""".stripMargin - val exception = the[InterpreterException] thrownBy eval(code) exception.isGuestException shouldEqual true exception.getGuestObject.toString shouldEqual "Bar" @@ -45,6 +44,7 @@ class PanicsTest extends InterpreterTest { | IO.println caught |""".stripMargin + eval(code) noException shouldBe thrownBy(eval(code)) consumeOut shouldEqual List("(Error: MyError)") } @@ -58,7 +58,7 @@ class PanicsTest extends InterpreterTest { | caught = Panic.catch_primitive (Long.parseLong "oops") .convert_to_dataflow_error | IO.println caught | cause = caught.catch_primitive e-> case e of - | Polyglot_Error err -> err + | Make_Polyglot_Error err -> err | _ -> "fail" | IO.println cause | message = cause.getMessage @@ -66,7 +66,7 @@ class PanicsTest extends InterpreterTest { |""".stripMargin eval(code) consumeOut shouldEqual List( - """(Error: (Polyglot_Error java.lang.NumberFormatException: For input string: "oops"))""", + """(Error: (Make_Polyglot_Error java.lang.NumberFormatException: For input string: "oops"))""", """java.lang.NumberFormatException: For input string: "oops"""", """For input string: "oops"""" ) diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso index d352cfc5c9db..0b85d9cffc5c 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Array.enso @@ -1,6 +1,5 @@ -type Array_Tp - @Builtin_Type - type Array +@Builtin_Type +type Array new_1 item_1 = @Builtin_Method "Array.new_1" new_2 item_1 item_2 = @Builtin_Method "Array.new_2" diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso index c132f9b4a148..56a60f299bac 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Data/Boolean.enso @@ -3,9 +3,3 @@ type Boolean True False if_then_else ~on_true ~on_false = @Builtin_Method "Boolean.if_then_else" - -#@Builtin_Type -#type True -# -#@Builtin_Type -#type False diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index c9264247c8a6..a1cd877c3b8d 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso @@ -6,7 +6,8 @@ type Panic @Builtin_Type type Syntax_Error message @Builtin_Type -type Polyglot_Error cause +type Polyglot_Error + Make_Polyglot_Error cause @Builtin_Type type Arithmetic_Error message @Builtin_Type diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso index 1d64051cde4f..c7be2a4722db 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso @@ -1,6 +1,5 @@ -type Polyglot_Tp - @Builtin_Type - type Polyglot +@Builtin_Type +type Polyglot get_array_size array = @Builtin_Method "Polyglot.get_array_size" execute callable arguments = @Builtin_Method "Polyglot.execute" get_member object member_name = @Builtin_Method "Polyglot.get_member" From 5f06fda88dd54f13136181d13bf5746fbb89c2cb Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 4 Aug 2022 18:15:39 +0200 Subject: [PATCH 032/110] post-merge fix --- .../org/enso/interpreter/runtime/Module.java | 27 ++++++++++++------- .../interpreter/runtime/builtin/Builtins.java | 4 +-- .../interpreter/runtime/data/EnsoDate.java | 2 +- .../enso/interpreter/runtime/data/Type.java | 5 +--- .../org/enso/compiler/PackageRepository.scala | 3 ++- .../compiler/context/SuggestionBuilder.scala | 2 +- .../pass/lint/ModuleNameConflicts.scala | 2 +- .../compiler/pass/resolve/TypeNames.scala | 2 +- .../compiler/phase/ExportsResolution.scala | 3 +-- .../org/enso/compiler/test/CompilerTest.scala | 2 +- .../pass/analyse/GatherDiagnosticsTest.scala | 3 ++- 11 files changed, 31 insertions(+), 24 deletions(-) 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 5bfcb6106916..30e78f19c45e 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 @@ -164,7 +164,11 @@ public Module(QualifiedName name, Package pkg, Rope literalSource) * belong to a package. */ private Module( - QualifiedName name, Package pkg, boolean synthetic, Rope literalSource) { + QualifiedName name, + Package pkg, + boolean synthetic, + Rope literalSource, + Context context) { this.sources = literalSource == null ? ModuleSources.NONE : ModuleSources.NONE.newWith(literalSource); this.name = name; @@ -185,8 +189,8 @@ private Module( * belong to a package. * @return the module with empty scope. */ - public static Module empty(QualifiedName name, Package pkg) { - return new Module(name, pkg, false, null); + public static Module empty(QualifiedName name, Package pkg, Context context) { + return new Module(name, pkg, false, null, context); } /** @@ -198,8 +202,9 @@ public static Module empty(QualifiedName name, Package pkg) { * @param source source of the module declaring exports of the desired modules * @return the synthetic module */ - public static Module synthetic(QualifiedName name, Package pkg, Rope source) { - return new Module(name, pkg, true, source); + public static Module synthetic( + QualifiedName name, Package pkg, Rope source, Context context) { + return new Module(name, pkg, true, source, context); } /** Clears any literal source set for this module. */ @@ -216,7 +221,9 @@ public Rope getLiteralSource() { return sources.rope(); } - /** @return true if this module represents a synthetic (compiler-generated) module */ + /** + * @return true if this module represents a synthetic (compiler-generated) module + */ public boolean isSynthetic() { return synthetic; } @@ -545,8 +552,7 @@ public void setHasCrossModuleLinks(boolean hasCrossModuleLinks) { abstract static class InvokeMember { private static Function getMethod(ModuleScope scope, Object[] args) throws ArityException, UnsupportedTypeException { - Types.Pair arguments = - Types.extractArguments(args, Type.class, String.class); + Types.Pair arguments = Types.extractArguments(args, Type.class, String.class); Type type = arguments.getFirst(); String name = arguments.getSecond(); @@ -612,7 +618,10 @@ private static Object evalExpression( CallerInfo callerInfo = new CallerInfo(null, LocalScope.root(), scope); return callOptimiserNode .executeDispatch( - eval, callerInfo, EmptyMap.create(), new Object[] {builtins.debug(), Text.create(expr)}) + eval, + callerInfo, + EmptyMap.create(), + new Object[] {builtins.debug(), Text.create(expr)}) .getValue(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java index 88d1af546e74..81fe6732cdd2 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 @@ -425,8 +425,8 @@ public Type file() { * * @return the {@code Date} atom constructor */ - public AtomConstructor date() { - return date.constructor(); + public Type date() { + return date.getType(); } /** diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDate.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDate.java index 45d3bf17c22c..135a098a61ab 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDate.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDate.java @@ -91,7 +91,7 @@ static class GetFunctionalDispatch { @CompilerDirectives.TruffleBoundary static Function doResolve(InteropLibrary my, UnresolvedSymbol symbol) { Context context = Context.get(my); - return symbol.resolveFor(context.getBuiltins().date(), context.getBuiltins().any()); + return symbol.resolveFor(context.getBuiltins().date()); } @Specialization( diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index 5ea572d8fa17..a5b7949b126f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -56,10 +56,7 @@ private void generateQualifiedAccessor() { null, new FunctionSchema( new ArgumentDefinition(0, "this", ArgumentDefinition.ExecutionMode.EXECUTE))); - definitionScope.registerMethod( - definitionScope.getAssociatedType(), - this.name.toLowerCase(), - function); // TODO lowercase remove when merge + definitionScope.registerMethod(definitionScope.getAssociatedType(), this.name, function); } public QualifiedName getQualifiedName() { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/PackageRepository.scala b/engine/runtime/src/main/scala/org/enso/compiler/PackageRepository.scala index 97dbdd738d9a..da63bfc42a3b 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/PackageRepository.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/PackageRepository.scala @@ -302,7 +302,8 @@ object PackageRepository { Module.synthetic( qName, pkg, - Rope(source) + Rope(source), + context ), modulesWithSources.map(_._1) ) 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 dafa94014088..b471e0918d38 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 @@ -60,7 +60,7 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { case Some(typePtr) => typePtr.getMetadata(MethodDefinitions).map(_.target.qualifiedName) case None => - Some(module.qualifiedName) + Some(module) } val methodOpt = selfTypeOpt.map { selfType => buildMethod( diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/ModuleNameConflicts.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/ModuleNameConflicts.scala index 8201d2079b56..84a5179652b3 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/ModuleNameConflicts.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/lint/ModuleNameConflicts.scala @@ -94,7 +94,7 @@ case object ModuleNameConflicts extends IRPass { val exports = syntheticExports.map(e => (e.name.parts.last.name, e)).toMap binding match { - case cons: IR.Module.Scope.Definition.Atom + case cons: IR.Module.Scope.Definition.Type if exports.contains(cons.name.name) => val atomName = cons.name.name val `export` = exports(atomName) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala index 409d60e26339..4f1ca4e2e436 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala @@ -76,7 +76,7 @@ case object TypeNames extends IRPass { ): IR.Expression = expression.transformExpressions { case n: IR.Name.Literal => bindingsMap - .resolveUppercaseName(n.name) + .resolveName(n.name) .map(res => n.updateMetadata(this -->> TypeResolution(res))) .getOrElse(n) } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala b/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala index 97053fe90769..7793e672ba8c 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala @@ -167,9 +167,8 @@ class ExportsResolution { modules.foreach { module => val bindings = getBindings(module) val ownTypes = bindings.types.map { tp => - val name = tp.name.toLowerCase val sym = List(ResolvedType(ModuleReference.Concrete(module), tp)) - (name, sym) + (tp.name, sym) } val ownMethods = bindings.moduleMethods.map { method => val name = method.name diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala index 334007852eab..10aedc9f7486 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/CompilerTest.scala @@ -192,7 +192,7 @@ trait CompilerRunner { * @return an atom with one argument `arg` with default value `ir` */ def asAtomDefaultArg: IR.Module.Scope.Definition.Data = { - IR.Module.Scope.Definition.Atom( + IR.Module.Scope.Definition.Data( IR.Name.Literal("TestAtom", isMethod = false, None), List( IR.DefinitionArgument diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/GatherDiagnosticsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/GatherDiagnosticsTest.scala index f84e0b277134..cd2bf9bf5da9 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/GatherDiagnosticsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/GatherDiagnosticsTest.scala @@ -86,12 +86,13 @@ class GatherDiagnosticsTest extends CompilerTest { List(), List(), List( - IR.Module.Scope.Definition.Atom( + IR.Module.Scope.Definition.Type( typeName, List( IR.DefinitionArgument .Specified(fooName, None, Some(error2), suspended = false, None) ), + List(), None ), IR.Module.Scope.Definition.Method From 847fffa3ac1fdec954dce240200d2613b30db4b4 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 4 Aug 2022 21:07:54 +0200 Subject: [PATCH 033/110] error refactoring --- .../node/expression/builtin/Builtin.java | 25 +- .../builtin/UniquelyConstructibleBuiltin.java | 31 +++ .../builtin/error/ArithmeticError.java | 10 +- .../expression/builtin/error/ArityError.java | 12 +- .../builtin/error/CatchPanicNode.java | 2 +- .../expression/builtin/error/CaughtPanic.java | 7 +- .../builtin/error/CompileError.java | 12 +- .../error/InexhaustivePatternMatchError.java | 7 +- .../builtin/error/InvalidArrayIndexError.java | 20 +- .../error/InvalidConversionTargetError.java | 12 +- .../builtin/error/ModuleDoesNotExist.java | 11 +- .../error/ModuleNotInPackageError.java | 8 +- .../builtin/error/NoSuchConversionError.java | 11 +- .../builtin/error/NoSuchMethodError.java | 7 +- .../builtin/error/NotInvokableError.java | 7 +- .../builtin/error/PolyglotError.java | 33 ++- .../expression/builtin/error/SyntaxError.java | 11 +- .../expression/builtin/error/TypeError.java | 12 +- .../builtin/error/UninitializedState.java | 12 +- .../error/UnsupportedArgumentTypes.java | 12 +- .../builtin/meta/ProjectDescription.java | 7 +- .../builtin/system/SystemProcessResult.java | 7 +- .../interpreter/runtime/builtin/Builtins.java | 13 +- .../interpreter/runtime/builtin/Error.java | 222 ++++-------------- .../interpreter/runtime/builtin/System.java | 4 +- .../enso/interpreter/runtime/data/Array.java | 48 +++- .../interpreter/runtime/data/EnsoDate.java | 4 +- .../interpreter/runtime/data/EnsoFile.java | 20 +- .../interpreter/runtime/system/System.java | 5 +- .../org/enso/interpreter/dsl/Builtin.java | 6 - .../org/enso/interpreter/dsl/BuiltinType.java | 7 - .../interpreter/dsl/BuiltinsProcessor.java | 58 +---- .../enso/interpreter/dsl/TypeProcessor.java | 9 +- .../builtins/ExecuteMethodImplGenerator.java | 5 +- .../dsl/builtins/MethodGenerator.java | 16 +- .../builtins/MethodNodeClassGenerator.java | 7 +- .../NoSpecializationClassGenerator.java | 10 +- .../dsl/builtins/SafeWrapException.java | 52 +--- .../SpecializationClassGenerator.java | 5 +- .../builtins/SpecializedMethodsGenerator.java | 16 +- 40 files changed, 343 insertions(+), 440 deletions(-) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/UniquelyConstructibleBuiltin.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java index 066af4e263c3..2fada37bd6eb 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java @@ -33,16 +33,16 @@ private AtomConstructor build(ModuleScope scope, Type type) { } } - private String name; + private final String name; - private @CompilerDirectives.CompilationFinal Type type; - private @CompilerDirectives.CompilationFinal(dimensions = 1) AtomConstructor[] constructors; - private @CompilerDirectives.CompilationFinal AtomConstructor uniqueConstructor; + public Builtin() { + name = this.getClass().getSimpleName().replaceAll("([^_A-Z])([A-Z])", "$1_$2"); - public final void setName(String name) { - this.name = name; } + private @CompilerDirectives.CompilationFinal Type type; + private @CompilerDirectives.CompilationFinal(dimensions = 1) AtomConstructor[] constructors; + protected Class getSuperType() { return Any.class; } @@ -67,11 +67,15 @@ public final void initialize(ModuleScope scope, Map, Bu for (int i = 0; i < constructors.length; i++) { constructors[i] = conses.get(i).build(scope, type); } - if (constructors.length == 1) { - uniqueConstructor = constructors[0]; - } } type.generateGetters(Arrays.asList(constructors)); + postInitialize(); + } + + protected void postInitialize() {} + + protected String getName() { + return name; } public final Type getType() { @@ -82,7 +86,4 @@ public final AtomConstructor[] getConstructors() { return constructors; } - public final AtomConstructor getUniqueConstructor() { - return uniqueConstructor; - } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/UniquelyConstructibleBuiltin.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/UniquelyConstructibleBuiltin.java new file mode 100644 index 000000000000..91ae7719245c --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/UniquelyConstructibleBuiltin.java @@ -0,0 +1,31 @@ +package org.enso.interpreter.node.expression.builtin; + +import com.oracle.truffle.api.CompilerDirectives; +import org.enso.interpreter.runtime.callable.atom.Atom; +import org.enso.interpreter.runtime.callable.atom.AtomConstructor; + +import java.util.List; + +public abstract class UniquelyConstructibleBuiltin extends Builtin { + private @CompilerDirectives.CompilationFinal AtomConstructor uniqueConstructor; + + public final AtomConstructor getUniqueConstructor() { + return uniqueConstructor; + } + + @Override + protected final List getDeclaredConstructors() { + return List.of(new Cons("Make_" + getName(), getConstructorParamNames())); + } + + protected abstract List getConstructorParamNames(); + + @Override + protected void postInitialize() { + uniqueConstructor = getConstructors()[0]; + } + + public final Atom newInstance(Object... params) { + return uniqueConstructor.newInstance(params); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java index 6351fc7ebbcd..a72ca192557a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArithmeticError.java @@ -2,8 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; -@BuiltinType(params = {"message"}) -public class ArithmeticError extends Builtin { +import java.util.List; +@BuiltinType +public class ArithmeticError extends UniquelyConstructibleBuiltin { + @Override + protected List getConstructorParamNames() { + return List.of("message"); + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java index 7e5a87a5b598..fed3a9a14513 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ArityError.java @@ -2,8 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; -@BuiltinType(params = {"expected_min", "expected_max", "actual"}) -public class ArityError extends Builtin { -// @BuiltinData(params = {""}) +import java.util.List; + +@BuiltinType +public class ArityError extends UniquelyConstructibleBuiltin { + @Override + protected List getConstructorParamNames() { + return List.of("expected_min", "expected_max", "actual"); + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CatchPanicNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CatchPanicNode.java index b58147dd7b35..a00aad9057f5 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CatchPanicNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CatchPanicNode.java @@ -60,7 +60,7 @@ Stateful doExecute( } catch (AbstractTruffleException e) { otherExceptionBranchProfile.enter(); Builtins builtins = Context.get(this).getBuiltins(); - Object payload = builtins.error().makePolyglotError(e); + Object payload = builtins.error().getPolyglotError().wrap(e); return executeCallback(frame, state, handler, payload, e); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java index 0aa4a042fc2d..8a00a98ecd2f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CaughtPanic.java @@ -2,13 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; import java.util.List; @BuiltinType -public class CaughtPanic extends Builtin { +public class CaughtPanic extends UniquelyConstructibleBuiltin { @Override - protected List getDeclaredConstructors() { - return List.of(new Cons("Make_Caught_Panic", "payload", "internal_original_exception")); + protected List getConstructorParamNames() { + return List.of("payload", "internal_original_exception"); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java index 5494e7ab67a6..c065c7870d99 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/CompileError.java @@ -2,13 +2,15 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; import java.util.List; @BuiltinType -public class CompileError extends Builtin { - @Override - protected List getDeclaredConstructors() { - return List.of(new Cons("Make_Compile_Error", "message")); - } +public class CompileError extends UniquelyConstructibleBuiltin { + + @Override + protected List getConstructorParamNames() { + return List.of("message"); + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java index 32a53adc121d..56c1685554ec 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InexhaustivePatternMatchError.java @@ -2,13 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; import java.util.List; @BuiltinType -public class InexhaustivePatternMatchError extends Builtin { +public class InexhaustivePatternMatchError extends UniquelyConstructibleBuiltin { @Override - protected List getDeclaredConstructors() { - return List.of(new Cons("Make_Inexhaustive_Pattern_Match_Error", "scrutinee")); + protected List getConstructorParamNames() { + return List.of("scrutinee"); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java index a3d94f379e74..5df6628cb068 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidArrayIndexError.java @@ -1,7 +1,21 @@ package org.enso.interpreter.node.expression.builtin.error; import org.enso.interpreter.dsl.BuiltinType; -import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; +import org.enso.interpreter.runtime.Context; +import org.enso.interpreter.runtime.callable.atom.Atom; +import org.enso.interpreter.runtime.data.Array; -@BuiltinType(params = {"array", "index"}) -public class InvalidArrayIndexError extends Builtin {} +import java.util.List; + +@BuiltinType +public class InvalidArrayIndexError extends UniquelyConstructibleBuiltin { + @Override + protected List getConstructorParamNames() { + return List.of("array", "index"); + } + + public Atom wrap(Context c, Array.InvalidIndexException e) { + return newInstance(e.getArray(), e.getIndex()); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java index 231b5eec4e5b..ad90c7193d6f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/InvalidConversionTargetError.java @@ -2,6 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; -@BuiltinType(params = {"target"}) -public class InvalidConversionTargetError extends Builtin {} +import java.util.List; + +@BuiltinType +public class InvalidConversionTargetError extends UniquelyConstructibleBuiltin { + @Override + protected List getConstructorParamNames() { + return List.of("target"); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java index 5c5b372e9437..2f429c53df83 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java @@ -2,6 +2,13 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; -@BuiltinType(params = {"name"}) -public class ModuleDoesNotExist extends Builtin {} +import java.util.List; + +public class ModuleDoesNotExist extends UniquelyConstructibleBuiltin { + @Override + protected List getConstructorParamNames() { + return List.of("name"); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java index 0f244f383017..605b1340cbf1 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleNotInPackageError.java @@ -2,13 +2,9 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; import java.util.List; @BuiltinType -public class ModuleNotInPackageError extends Builtin { - @Override - protected List getDeclaredConstructors() { - return List.of(new Cons("Make_Module_Not_In_Package_Error")); - } -} +public class ModuleNotInPackageError extends Builtin {} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java index 7fa5d73a7c5a..0ead0203f2c3 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java @@ -2,6 +2,13 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; -@BuiltinType(params = {"target", "that", "conversion"}) -public class NoSuchConversionError extends Builtin {} +import java.util.List; + +public class NoSuchConversionError extends UniquelyConstructibleBuiltin { + @Override + protected List getConstructorParamNames() { + return List.of("target", "that", "conversion"); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java index 4439d9796b5b..1fcb41c04a57 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchMethodError.java @@ -2,13 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; import java.util.List; @BuiltinType -public class NoSuchMethodError extends Builtin { +public class NoSuchMethodError extends UniquelyConstructibleBuiltin { @Override - protected List getDeclaredConstructors() { - return List.of(new Cons("Make_No_Such_Method_Error", "target", "symbol")); + protected List getConstructorParamNames() { + return List.of("target", "symbol"); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java index f65ad1f70c52..9d6cabe25af9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NotInvokableError.java @@ -2,13 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; import java.util.List; @BuiltinType -public class NotInvokableError extends Builtin { +public class NotInvokableError extends UniquelyConstructibleBuiltin { @Override - protected List getDeclaredConstructors() { - return List.of(new Cons("Make_Not_Invokable_Error", "target")); + protected List getConstructorParamNames() { + return List.of("target"); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java index e990cd4c7bc0..2a6de4edce0f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/PolyglotError.java @@ -1,14 +1,37 @@ package org.enso.interpreter.node.expression.builtin.error; +import com.oracle.truffle.api.exception.AbstractTruffleException; import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; +import org.enso.interpreter.runtime.Context; +import org.enso.interpreter.runtime.callable.atom.Atom; +import java.io.IOException; +import java.time.DateTimeException; +import java.time.format.DateTimeParseException; import java.util.List; @BuiltinType -public class PolyglotError extends Builtin { - @Override - protected List getDeclaredConstructors() { - return List.of(new Cons("Make_Polyglot_Error", "cause")); - } +public class PolyglotError extends UniquelyConstructibleBuiltin { + @Override + protected List getConstructorParamNames() { + return List.of("cause"); + } + + public Atom wrap(AbstractTruffleException e) { + return newInstance(e); + } + + public Atom wrap(Context c, IOException e) { + return newInstance(c.getEnvironment().asGuestValue(e)); + } + + public Atom wrap(Context c, DateTimeException e) { + return newInstance(c.getEnvironment().asGuestValue(e)); + } + + public Atom wrap(Context c, DateTimeParseException e) { + return newInstance(c.getEnvironment().asGuestValue(e)); + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java index 8f30eba00086..21576bc8261b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/SyntaxError.java @@ -2,13 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; import java.util.List; @BuiltinType -public class SyntaxError extends Builtin { - @Override - protected List getDeclaredConstructors() { - return List.of(new Cons("Make_Syntax_Error", "message")); - } +public class SyntaxError extends UniquelyConstructibleBuiltin { + @Override + protected List getConstructorParamNames() { + return List.of("message"); + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java index 6ec0284ad7e9..7e97b770892e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/TypeError.java @@ -2,6 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; -@BuiltinType(params = {"expected", "actual", "name"}) -public class TypeError extends Builtin {} +import java.util.List; + +@BuiltinType +public class TypeError extends UniquelyConstructibleBuiltin { + @Override + protected List getConstructorParamNames() { + return List.of("expected", "actual", "name"); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java index 43c08797f6ed..7831848fa049 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UninitializedState.java @@ -2,6 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; -@BuiltinType(params = {"key"}) -public class UninitializedState extends Builtin {} +import java.util.List; + +@BuiltinType +public class UninitializedState extends UniquelyConstructibleBuiltin { + @Override + protected List getConstructorParamNames() { + return List.of("key"); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java index 49c6e118a38d..89bc1f5b7619 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/UnsupportedArgumentTypes.java @@ -2,6 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; -@BuiltinType(params = {"arguments"}) -public class UnsupportedArgumentTypes extends Builtin {} +import java.util.List; + +@BuiltinType +public class UnsupportedArgumentTypes extends UniquelyConstructibleBuiltin { + @Override + protected List getConstructorParamNames() { + return List.of("arguments"); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java index 9ad7d6ffdb6f..b87dbae84fd8 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/ProjectDescription.java @@ -2,13 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; import java.util.List; @BuiltinType -public class ProjectDescription extends Builtin { +public class ProjectDescription extends UniquelyConstructibleBuiltin { @Override - protected List getDeclaredConstructors() { - return List.of(new Cons("Make_Project_Description", List.of("prim_root_file", "prim_config"))); + protected List getConstructorParamNames() { + return List.of("prim_root_file", "prim_config"); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java index c49ac522dcd1..71bd375dde3c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/system/SystemProcessResult.java @@ -2,13 +2,14 @@ import org.enso.interpreter.dsl.BuiltinType; import org.enso.interpreter.node.expression.builtin.Builtin; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; import java.util.List; @BuiltinType -public class SystemProcessResult extends Builtin { +public class SystemProcessResult extends UniquelyConstructibleBuiltin { @Override - protected List getDeclaredConstructors() { - return List.of(new Cons("Make_System_Process_Result", "exit_code", "stdout", "stderr")); + protected List getConstructorParamNames() { + return List.of("exit_code", "stdout", "stderr"); } } 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 81fe6732cdd2..caf988a1ce97 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -22,6 +22,7 @@ import org.enso.interpreter.node.expression.builtin.*; import org.enso.interpreter.node.expression.builtin.Boolean; import org.enso.interpreter.node.expression.builtin.debug.Debug; +import org.enso.interpreter.node.expression.builtin.error.CaughtPanic; import org.enso.interpreter.node.expression.builtin.error.Warning; import org.enso.interpreter.node.expression.builtin.io.File; import org.enso.interpreter.node.expression.builtin.meta.ProjectDescription; @@ -75,7 +76,7 @@ public static class Debug { private final Builtin ref; private final Builtin managedResource; private final Builtin debug; - private final Builtin projectDescription; + private final ProjectDescription projectDescription; private final Builtin file; private final Builtin date; private final Builtin warning; @@ -112,7 +113,7 @@ public Builtins(Context context) { ref = builtins.get(Ref.class); managedResource = builtins.get(ManagedResource.class); debug = builtins.get(Debug.class); - projectDescription = builtins.get(ProjectDescription.class); + projectDescription = getBuiltinType(ProjectDescription.class); file = builtins.get(File.class); date = builtins.get(org.enso.interpreter.node.expression.builtin.date.Date.class); special = new Special(language); @@ -215,9 +216,7 @@ private Map, Builtin> readBuiltinTypesMetadata(ModuleSc try { @SuppressWarnings("unchecked") var cls = (Class) Class.forName(builtinMeta[1]); - var builtin = cls.getConstructor().newInstance(); - builtin.setName(builtinMeta[0]); - return builtin; + return cls.getConstructor().newInstance(); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException @@ -442,7 +441,7 @@ public Type debug() { /** * @return the {@code Project_Description} atom constructor */ - public Builtin getProjectDescription() { + public ProjectDescription getProjectDescription() { return projectDescription; } @@ -477,7 +476,7 @@ public Type polyglot() { /** * @return the {@code Caught_Panic} atom constructor */ - public Builtin caughtPanic() { + public CaughtPanic caughtPanic() { return this.error.caughtPanic(); } 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 95b180cec253..f0f8d78f306b 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,51 +1,39 @@ package org.enso.interpreter.runtime.builtin; import com.oracle.truffle.api.CompilerDirectives; -import org.enso.interpreter.node.expression.builtin.Builtin; 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.atom.Atom; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.data.Array; import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.data.text.Text; import static com.oracle.truffle.api.CompilerDirectives.transferToInterpreterAndInvalidate; -import com.oracle.truffle.api.exception.AbstractTruffleException; -import com.oracle.truffle.api.interop.ArityException; -import com.oracle.truffle.api.interop.InteropLibrary; -import com.oracle.truffle.api.interop.TruffleObject; -import com.oracle.truffle.api.interop.UnknownIdentifierException; -import com.oracle.truffle.api.interop.UnsupportedMessageException; -import com.oracle.truffle.api.interop.UnsupportedTypeException; -import com.oracle.truffle.api.library.CachedLibrary; -import com.oracle.truffle.api.library.ExportLibrary; -import com.oracle.truffle.api.library.ExportMessage; import org.enso.interpreter.runtime.Context; /** Container for builtin Error types */ public class Error { private final Context context; - private final Builtin syntaxError; - private final Builtin typeError; - private final Builtin compileError; - private final Builtin inexhaustivePatternMatchError; - private final Builtin uninitializedState; - private final Builtin noSuchMethodError; - private final Builtin noSuchConversionError; - private final Builtin polyglotError; - private final Builtin moduleNotInPackageError; - private final Builtin arithmeticError; - private final Builtin invalidArrayIndexError; - private final Builtin arityError; - private final Builtin unsupportedArgumentsError; - private final Builtin moduleDoesNotExistError; - private final Builtin notInvokableError; - private final Builtin invalidConversionTargetError; - private final Builtin panic; - private final Builtin caughtPanic; + private final SyntaxError syntaxError; + private final TypeError typeError; + private final CompileError compileError; + private final InexhaustivePatternMatchError inexhaustivePatternMatchError; + private final UninitializedState uninitializedState; + private final NoSuchMethodError noSuchMethodError; + private final NoSuchConversionError noSuchConversionError; + private final PolyglotError polyglotError; + private final ModuleNotInPackageError moduleNotInPackageError; + private final ArithmeticError arithmeticError; + private final InvalidArrayIndexError invalidArrayIndexError; + private final ArityError arityError; + private final UnsupportedArgumentTypes unsupportedArgumentsError; + private final ModuleDoesNotExist moduleDoesNotExistError; + private final NotInvokableError notInvokableError; + private final InvalidConversionTargetError invalidConversionTargetError; + private final Panic panic; + private final CaughtPanic caughtPanic; @CompilerDirectives.CompilationFinal private Atom arithmeticErrorShiftTooBig; @@ -78,30 +66,30 @@ public Error(Builtins builtins, Context context) { } public Atom makeSyntaxError(Object message) { - return syntaxError.getUniqueConstructor().newInstance(message); + return syntaxError.newInstance(message); } public Atom makeCompileError(Object message) { - return compileError.getUniqueConstructor().newInstance(message); + return compileError.newInstance(message); } public Atom makeInexhaustivePatternMatchError(Object message) { - return inexhaustivePatternMatchError.getUniqueConstructor().newInstance(message); + return inexhaustivePatternMatchError.newInstance(message); } public Atom makeUninitializedStateError(Object key) { - return uninitializedState.getUniqueConstructor().newInstance(key); + return uninitializedState.newInstance(key); } - public Atom makeModuleNotInPackageError() { - return moduleNotInPackageError.getUniqueConstructor().newInstance(); + public Type makeModuleNotInPackageError() { + return moduleNotInPackageError.getType(); } public Type panic() { return panic.getType(); } - public Builtin caughtPanic() { + public CaughtPanic caughtPanic() { return caughtPanic; } @@ -113,16 +101,16 @@ public Builtin caughtPanic() { * @return a runtime representation of the error */ public Atom makeNoSuchMethodError(Object target, UnresolvedSymbol symbol) { - return noSuchMethodError.getUniqueConstructor().newInstance(target, symbol); + return noSuchMethodError.newInstance(target, symbol); } public Atom makeNoSuchConversionError( Object target, Object that, UnresolvedConversion conversion) { - return noSuchConversionError.getUniqueConstructor().newInstance(target, that, conversion); + return noSuchConversionError.newInstance(target, that, conversion); } public Atom makeInvalidConversionTargetError(Object target) { - return invalidConversionTargetError.getUniqueConstructor().newInstance(target); + return invalidConversionTargetError.newInstance(target); } /** @@ -134,17 +122,11 @@ public Atom makeInvalidConversionTargetError(Object target) { * @return a runtime representation of the error. */ public Atom makeTypeError(Object expected, Object actual, String name) { - return typeError.getUniqueConstructor().newInstance(expected, actual, Text.create(name)); + return typeError.newInstance(expected, actual, Text.create(name)); } - /** - * Creates an instance of the runtime representation of a {@code Polyglot_Error}. - * - * @param cause the cause of the error. - * @return a runtime representation of the polyglot error. - */ - public Atom makePolyglotError(Throwable cause) { - return polyglotError.getUniqueConstructor().newInstance(WrapPlainException.wrap(cause, context)); + public PolyglotError getPolyglotError() { + return polyglotError; } /** @@ -154,7 +136,7 @@ public Atom makePolyglotError(Throwable cause) { * @return a runtime representation of the arithmetic error */ private Atom makeArithmeticError(Text reason) { - return arithmeticError.getUniqueConstructor().newInstance(reason); + return arithmeticError.newInstance(reason); } /** @@ -185,7 +167,11 @@ public Atom getDivideByZeroError() { * @return An error representing that the {@code index} is not valid in {@code array} */ public Atom makeInvalidArrayIndexError(Object array, Object index) { - return invalidArrayIndexError.getUniqueConstructor().newInstance(array, index); + return invalidArrayIndexError.newInstance(array, index); + } + + public InvalidArrayIndexError getInvalidArrayIndexError() { + return invalidArrayIndexError; } /** @@ -195,7 +181,7 @@ public Atom makeInvalidArrayIndexError(Object array, Object index) { * @return an error informing about the arity being mismatched */ public Atom makeArityError(long expected_min, long expected_max, long actual) { - return arityError.getUniqueConstructor().newInstance(expected_min, expected_max, actual); + return arityError.newInstance(expected_min, expected_max, actual); } /** @@ -204,7 +190,7 @@ public Atom makeArityError(long expected_min, long expected_max, long actual) { * given method callp */ public Atom makeUnsupportedArgumentsError(Object[] args) { - return unsupportedArgumentsError.getUniqueConstructor().newInstance(new Array(args)); + return unsupportedArgumentsError.newInstance(new Array(args)); } /** @@ -212,7 +198,7 @@ public Atom makeUnsupportedArgumentsError(Object[] args) { * @return a module does not exist error */ public Atom makeModuleDoesNotExistError(String name) { - return moduleDoesNotExistError.getUniqueConstructor().newInstance(Text.create(name)); + return moduleDoesNotExistError.newInstance(Text.create(name)); } /** @@ -220,133 +206,7 @@ public Atom makeModuleDoesNotExistError(String name) { * @return a not invokable error */ public Atom makeNotInvokableError(Object target) { - return notInvokableError.getUniqueConstructor().newInstance(target); + return notInvokableError.newInstance(target); } - /** Represents plain Java exception as a {@link TruffleObject}. - */ - @ExportLibrary(InteropLibrary.class) - static final class WrapPlainException extends AbstractTruffleException { - private final AbstractTruffleException prototype; - private final Throwable original; - - private WrapPlainException(Throwable cause) { - super(cause.getMessage(), cause, AbstractTruffleException.UNLIMITED_STACK_TRACE, null); - this.prototype = null; - this.original = cause; - } - - private WrapPlainException(AbstractTruffleException prototype, Throwable original) { - super(prototype); - this.prototype = prototype; - this.original = original; - } - - static AbstractTruffleException wrap(Throwable cause, Context ctx) { - var env = ctx.getEnvironment(); - if (env.isHostException(cause)) { - var orig = env.asHostException(cause); - return new WrapPlainException((AbstractTruffleException) cause, orig); - } else if (cause instanceof AbstractTruffleException truffleEx) { - return truffleEx; - } else { - return new WrapPlainException(cause); - } - } - - @ExportMessage - boolean hasExceptionMessage() { - return true; - } - - @ExportMessage - public Object getExceptionMessage() { - if (getMessage() != null) { - return Text.create(getMessage()); - } else { - return Text.create(original.getClass().getName()); - } - } - - @ExportMessage - String toDisplayString(boolean sideEffects) { - return original.toString(); - } - - @ExportMessage - Object getMembers(boolean includeInternal) { - return Array.empty(); - } - - @ExportMessage - boolean hasMembers() { - return true; - } - - @ExportMessage - boolean isMemberInvocable(String member, @CachedLibrary(limit="1") InteropLibrary delegate) { - boolean knownMembers = "is_a".equals(member) || "getMessage".equals(member); - return knownMembers || (prototype != null && delegate.isMemberInvocable(prototype, member)); - } - - @ExportMessage - Object invokeMember(String name, Object[] args, @CachedLibrary(limit="2") InteropLibrary iop) throws ArityException, UnknownIdentifierException, UnsupportedTypeException, UnsupportedMessageException { - if ("is_a".equals(name)) { - if (args.length != 1) { - throw ArityException.create(1,1, args.length); - } - Object meta; - if (iop.isString(args[0])) { - meta = args[0]; - } else { - try { - meta = iop.getMetaQualifiedName(args[0]); - } catch (UnsupportedMessageException e) { - meta = args[0]; - } - } - if (!iop.isString(meta)) { - throw UnsupportedTypeException.create(args, "Provide class or fully qualified name of class to check"); - } - - return hasType(iop.asString(meta), original.getClass()); - } - if ("getMessage".equals(name)) { - return getExceptionMessage(); - } - return iop.invokeMember(this.prototype, name, args); - } - - @ExportMessage - boolean isMemberReadable(String member, @CachedLibrary(limit="1") InteropLibrary delegate) { - if (prototype == null) { - return false; - } - return delegate.isMemberReadable(prototype, member); - } - - @ExportMessage - Object readMember(String name, @CachedLibrary(limit="2") InteropLibrary iop) throws UnsupportedMessageException, UnknownIdentifierException { - return iop.readMember(this.prototype, name); - } - - @CompilerDirectives.TruffleBoundary - private static boolean hasType(String fqn, Class type) { - if (type == null) { - return false; - } - if (type.getName().equals(fqn)) { - return true; - } - if (hasType(fqn, type.getSuperclass())) { - return true; - } - for (Class interfaceType : type.getInterfaces()) { - if (hasType(fqn, interfaceType)) { - return true; - } - } - return false; - } - } } 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 ef0795d7219d..47d511891951 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 @@ -7,7 +7,7 @@ /** A container class for all System-related stdlib builtins. */ public class System { - private final Builtin systemProcessResult; + private final SystemProcessResult systemProcessResult; /** Create builders for all {@code System} atom constructors. */ public System(Builtins builtins) { @@ -18,6 +18,6 @@ public System(Builtins builtins) { * @return the atom constructor for {@code Process_Result}. */ public Atom makeSystemResult(Object exitCode, Object stdout, Object stderr) { - return systemProcessResult.getUniqueConstructor().newInstance(exitCode, stdout, stderr); + return systemProcessResult.newInstance(exitCode, stdout, stderr); } } 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 944d223d5332..5476d2dbec1a 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 @@ -14,7 +14,6 @@ import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.UnresolvedConversion; import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; @@ -25,6 +24,24 @@ @ExportLibrary(MethodDispatchLibrary.class) @Builtin(pkg = "mutable", stdlibName = "Standard.Base.Data.Array.Array") public class Array implements TruffleObject { + public static class InvalidIndexException extends RuntimeException { + private final long index; + private final Array array; + + public InvalidIndexException(long index, Array array) { + this.index = index; + this.array = array; + } + + public long getIndex() { + return index; + } + + public Array getArray() { + return array; + } + } + private final Object[] items; /** @@ -47,7 +64,9 @@ public Array(long size) { this.items = new Object[(int) size]; } - /** @return the elements of this array as a java array. */ + /** + * @return the elements of this array as a java array. + */ public Object[] getItems() { return items; } @@ -77,19 +96,25 @@ public Object readArrayElement(long index) throws InvalidArrayIndexException { return items[(int) index]; } - /** @return the size of this array */ + /** + * @return the size of this array + */ @Builtin.Method(description = "Returns the size of this array.") public long length() { return this.getItems().length; } - /** @return an empty array */ + /** + * @return an empty array + */ @Builtin.Method(description = "Creates an empty Array") public static Object empty() { return new Array(); } - /** @return an identity array */ + /** + * @return an identity array + */ @Builtin.Method(description = "Identity on arrays, implemented for protocol completeness.") public Object toArray() { return this; @@ -106,14 +131,20 @@ long getArraySize() { } @Builtin.Method(name = "at", description = "Gets an array element at the given index.") - @Builtin.WrapException(from = IndexOutOfBoundsException.class, to = InvalidArrayIndexError.class) + @Builtin.WrapException(from = InvalidIndexException.class, to = InvalidArrayIndexError.class) public Object get(long index) { + if (index < 0 || index >= items.length) { + throw new InvalidIndexException(index, this); + } return getItems()[(int) index]; } @Builtin.Method(name = "setAt", description = "Gets an array element at the given index.") - @Builtin.WrapException(from = IndexOutOfBoundsException.class, to = InvalidArrayIndexError.class) + @Builtin.WrapException(from = InvalidIndexException.class, to = InvalidArrayIndexError.class) public Object set(long index, @AcceptsError Object value) { + if (index < 0 || index >= items.length) { + throw new InvalidIndexException(index, this); + } getItems()[(int) index] = value; return this; } @@ -212,8 +243,7 @@ static class GetConversionFunction { @CompilerDirectives.TruffleBoundary static Function doResolve(Type target, UnresolvedConversion conversion) { Context context = getContext(); - return conversion.resolveFor( - target, context.getBuiltins().array()); + return conversion.resolveFor(target, context.getBuiltins().array()); } static Context getContext() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDate.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDate.java index 135a098a61ab..205505282f90 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDate.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDate.java @@ -39,7 +39,7 @@ public static EnsoDate now() { @Builtin.Method(name = "internal_parse", description = "Constructs a new Date from text with optional pattern") @Builtin.Specialize - @Builtin.WrapException(from = DateTimeParseException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = DateTimeParseException.class, to = PolyglotError.class) public static EnsoDate parse(Text text, Object noneOrPattern) { var str = text.getContents().toString(); if (noneOrPattern instanceof Text pattern) { @@ -51,7 +51,7 @@ public static EnsoDate parse(Text text, Object noneOrPattern) { } @Builtin.Method(name = "internal_new", description = "Constructs a new Date from a year, month, and day") - @Builtin.WrapException(from = DateTimeException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = DateTimeException.class, to = PolyglotError.class) public static EnsoDate create(long year, long month, long day) { return new EnsoDate(LocalDate.of(Math.toIntExact(year), Math.toIntExact(month), Math.toIntExact(day))); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoFile.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoFile.java index 8151db480f90..6ffa9fbee246 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoFile.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoFile.java @@ -41,21 +41,21 @@ public EnsoFile(TruffleFile truffleFile) { } @Builtin.Method - @Builtin.WrapException(from = IOException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = IOException.class, to = PolyglotError.class) @Builtin.ReturningGuestObject public OutputStream outputStream(OpenOption[] opts) throws IOException { return this.truffleFile.newOutputStream(opts); } @Builtin.Method - @Builtin.WrapException(from = IOException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = IOException.class, to = PolyglotError.class) @Builtin.ReturningGuestObject public InputStream inputStream(OpenOption[] opts) throws IOException { return this.truffleFile.newInputStream(opts); } @Builtin.Method(name = "read_last_bytes_builtin") - @Builtin.WrapException(from = IOException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = IOException.class, to = PolyglotError.class) public ArrayOverBuffer readLastBytes(long n) throws IOException { try (SeekableByteChannel channel = this.truffleFile.newByteChannel(Set.of(StandardOpenOption.READ))) { @@ -89,21 +89,21 @@ public boolean exists() { } @Builtin.Method(name = "creation_time_builtin") - @Builtin.WrapException(from = IOException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = IOException.class, to = PolyglotError.class) @Builtin.ReturningGuestObject public ZonedDateTime getCreationTime() throws IOException { return ZonedDateTime.ofInstant(truffleFile.getCreationTime().toInstant(), ZoneOffset.UTC); } @Builtin.Method(name = "last_modified_time_builtin") - @Builtin.WrapException(from = IOException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = IOException.class, to = PolyglotError.class) @Builtin.ReturningGuestObject public ZonedDateTime getLastModifiedTime() throws IOException { return ZonedDateTime.ofInstant(truffleFile.getLastModifiedTime().toInstant(), ZoneOffset.UTC); } @Builtin.Method(name = "posix_permissions_builtin") - @Builtin.WrapException(from = IOException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = IOException.class, to = PolyglotError.class) @Builtin.ReturningGuestObject public Set getPosixPermissions() throws IOException { return truffleFile.getPosixPermissions(); @@ -144,7 +144,7 @@ public void createDirectories() { } @Builtin.Method(name = "list_immediate_children_array") - @Builtin.WrapException(from = IOException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = IOException.class, to = PolyglotError.class) public EnsoFile[] list() throws IOException { return this.truffleFile.list().stream().map(EnsoFile::new).toArray(EnsoFile[]::new); } @@ -178,19 +178,19 @@ public EnsoFile normalize() { } @Builtin.Method(name = "delete_builtin") - @Builtin.WrapException(from = IOException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = IOException.class, to = PolyglotError.class) public void delete() throws IOException { truffleFile.delete(); } @Builtin.Method(name = "copy_builtin", description = "Copy this file to a target destination") - @Builtin.WrapException(from = IOException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = IOException.class, to = PolyglotError.class) public void copy(EnsoFile target, CopyOption[] options) throws IOException { truffleFile.copy(target.truffleFile, options); } @Builtin.Method(name = "move_builtin", description = "Move this file to a target destination") - @Builtin.WrapException(from = IOException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = IOException.class, to = PolyglotError.class) public void move(EnsoFile target, CopyOption[] options) throws IOException { truffleFile.move(target.truffleFile, options); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/system/System.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/system/System.java index b24d1e921524..75d425a836f6 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/system/System.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/system/System.java @@ -50,11 +50,10 @@ public static void exit(long code) { @Builtin.Specialize @Builtin.Method(description = "Create a system process, returning the exit code.") - @Builtin.WrapException(from = IOException.class, to = PanicException.class, propagate = true) + @Builtin.WrapException(from = IOException.class, to = PanicException.class) @Builtin.WrapException( from = InterruptedException.class, - to = PanicException.class, - propagate = true) + to = PanicException.class) @CompilerDirectives.TruffleBoundary public static Atom createProcess( Context ctx, diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/Builtin.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/Builtin.java index 7045f2a11ab7..6a5a898ad9af 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/Builtin.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/Builtin.java @@ -232,12 +232,6 @@ Class from(); /** @return Class of Enso's builtin (error) type to throw instead. */ Class to(); - - /** - * @return true, if the original exception should only be wrapped. Otherwise we pass parameters - * from the method when creating the new exception. - */ - boolean propagate() default false; } /** diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java index 3b8225421e29..615d68161763 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinType.java @@ -12,11 +12,4 @@ /** 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/BuiltinsProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsProcessor.java index b8bd802f8099..ccc0331097c7 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/BuiltinsProcessor.java @@ -142,8 +142,6 @@ public void handleMethodElement(Element element, RoundEnvironment roundEnv) thro Builtin.Method annotation = element.getAnnotation(Builtin.Method.class); boolean isConstructor = method.getKind() == ElementKind.CONSTRUCTOR; - Map parameterCounts = builtinTypesParametersCount(roundEnv); - if (annotation.expandVarargs() != 0) { if (annotation.expandVarargs() < 0) throw new RuntimeException( @@ -170,12 +168,7 @@ public void handleMethodElement(Element element, RoundEnvironment roundEnv) thro try { MethodNodeClassGenerator classGenerator = new NoSpecializationClassGenerator( - method, - builtinMethodNode, - ownerClass, - stdLibOwnerClass, - i, - parameterCounts); + method, builtinMethodNode, ownerClass, stdLibOwnerClass, i); classGenerator.generate( processingEnv, methodName, @@ -228,7 +221,7 @@ public void handleMethodElement(Element element, RoundEnvironment roundEnv) thro if (encountered.size() == expected) { MethodNodeClassGenerator classGenerator = new SpecializationClassGenerator( - encountered, builtinMethodNode, ownerClass, stdLibOwnerClass, parameterCounts); + encountered, builtinMethodNode, ownerClass, stdLibOwnerClass); classGenerator.generate( processingEnv, builtinMethodName, @@ -241,7 +234,7 @@ public void handleMethodElement(Element element, RoundEnvironment roundEnv) thro MethodNodeClassGenerator classGenerator = new NoSpecializationClassGenerator( - method, builtinMethodNode, ownerClass, stdLibOwnerClass, parameterCounts); + method, builtinMethodNode, ownerClass, stdLibOwnerClass); classGenerator.generate( processingEnv, builtinMethodName, @@ -281,51 +274,6 @@ private int specializationsCount(Element owner, String builtinMethodName) { .count(); } - /** - * Returns a map of builtin types and the number of their parameters. The information is used to - * generate try/catch clauses and propagate exceptions via dataflow errors, with appropriate - * constructor arguments. - * - *

The method takes into account the possibility of separate compilation by reading entries - * from metadate, if any. - * - * @param roundEnv current round environment - * @return a map from a builtin type name to the number of its parameters - */ - private Map builtinTypesParametersCount(RoundEnvironment roundEnv) { - // For separate compilation we need to read that information from BuiltinTypes metadata file - Map pastEntries; - try { - FileObject existingFile = - processingEnv - .getFiler() - .getResource(StandardLocation.CLASS_OUTPUT, "", TypeProcessor.META_PATH); - - try (InputStream resource = existingFile.openInputStream()) { - pastEntries = - new BufferedReader(new InputStreamReader(resource, StandardCharsets.UTF_8)) - .lines() - .map(l -> TypeProcessor.fromStringToMetadataEntry(l)) - .collect( - Collectors.toMap(e -> e.key().replaceAll("_", ""), e -> e.paramNames().length)); - } - } catch (IOException e) { - // Ignore, this is a clean run - pastEntries = new HashMap<>(); - } - - Map currentRoundEntries = - roundEnv.getElementsAnnotatedWith(BuiltinType.class).stream() - .collect( - Collectors.toMap( - e -> e.getSimpleName().toString(), - e -> e.getAnnotation(BuiltinType.class).params().length)); - - pastEntries.forEach((k, v) -> currentRoundEntries.merge(k, v, (v1, v2) -> v1)); - - return currentRoundEntries; - } - private final List typeNecessaryImports = Arrays.asList( "org.enso.interpreter.dsl.BuiltinType", diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java index 992be7857476..b9533f5012cf 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/TypeProcessor.java @@ -173,11 +173,11 @@ public SourceVersion getSupportedSourceVersion() { return SourceVersion.latest(); } - public record TypeMetadataEntry(String ensoName, String clazzName, String[] paramNames, Optional stdlibName) implements MetadataEntry { + public record TypeMetadataEntry(String ensoName, String clazzName, Optional stdlibName) implements MetadataEntry { @Override public String toString() { - return ensoName + ":" + clazzName + ":" + StringUtils.join(paramNames, ",") + ":" + stdlibName.orElse(""); + return ensoName + ":" + clazzName + ":" + stdlibName.orElse(""); } @Override @@ -194,8 +194,7 @@ protected TypeMetadataEntry toMetadataEntry(String line) { public static TypeMetadataEntry fromStringToMetadataEntry(String line) { String[] elements = line.split(":"); if (elements.length < 2) throw new RuntimeException("invalid builtin metadata entry: " + line); - String[] params = elements.length >= 3 ? elements[2].split(",") : new String[0]; - Optional stdLibName = elements.length == 4 ? Optional.of(elements[3]) : Optional.empty(); - return new TypeMetadataEntry(elements[0], elements[1], params, stdLibName); + Optional stdLibName = elements.length == 3 ? Optional.of(elements[2]) : Optional.empty(); + return new TypeMetadataEntry(elements[0], elements[1], stdLibName); } } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/ExecuteMethodImplGenerator.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/ExecuteMethodImplGenerator.java index 5043024d887f..b9eed95b8ae5 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/ExecuteMethodImplGenerator.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/ExecuteMethodImplGenerator.java @@ -139,8 +139,7 @@ private boolean needsContext(List params) { public List generate( ProcessingEnvironment processingEnv, String name, - String owner, - Map builtinTypesParameterCounts) { + String owner) { SafeWrapException[] exceptionWrappers = wrapExceptions(processingEnv, method); boolean wrapsExceptions = exceptionWrappers.length != 0; @@ -170,7 +169,7 @@ public List generate( method.add(" " + statement); } for (int i = 0; i < exceptionWrappers.length; i++) { - method.addAll(exceptionWrappers[i].toCatchClause(params, builtinTypesParameterCounts)); + method.addAll(exceptionWrappers[i].toCatchClause()); } method.add(" }"); method.add("}"); diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodGenerator.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodGenerator.java index 1104bd88b5ae..558687b645b7 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodGenerator.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodGenerator.java @@ -44,10 +44,7 @@ public MethodGenerator( } public abstract List generate( - ProcessingEnvironment processingEnv, - String name, - String owner, - Map builtinTypesParameterCounts); + ProcessingEnvironment processingEnv, String name, String owner); /** * Generate node's `execute` method definition (return type and necessary parameters). ' @@ -142,7 +139,6 @@ private static class WrapExceptionExtractor { private static final String FromElementName = "from"; private static final String ToElementName = "to"; - private static final String PropagateElementName = "propagate"; private static final String ValueElementName = "value"; private Class wrapExceptionAnnotationClass; @@ -188,7 +184,6 @@ private SafeWrapException[] extractClassElementFromAnnotation( if (am.getAnnotationType().equals(builtinType)) { Attribute.Class valueFrom = null; Attribute.Class valueTo = null; - Attribute.Constant valuePropagate = null; for (Map.Entry entry : am.getElementValues().entrySet()) { Name key = entry.getKey().getSimpleName(); @@ -196,12 +191,10 @@ private SafeWrapException[] extractClassElementFromAnnotation( valueFrom = (Attribute.Class) (entry.getValue()); } else if (key.toString().equals(ToElementName)) { valueTo = (Attribute.Class) (entry.getValue()); - } else if (key.toString().equals(PropagateElementName)) { - valuePropagate = (Attribute.Constant) (entry.getValue()); } } if (valueFrom != null && valueTo != null) { - exceptionWrappers.add(new SafeWrapException(valueFrom, valueTo, valuePropagate)); + exceptionWrappers.add(new SafeWrapException(valueFrom, valueTo)); } } } @@ -226,7 +219,6 @@ private SafeWrapException[] extractClassElementFromAnnotationContainer( for (int i = 0; i < wrapExceptions.values.length; i++) { Attribute.Class valueFrom = null; Attribute.Class valueTo = null; - Attribute.Constant valuePropagate = null; Attribute.Compound attr = (Attribute.Compound) wrapExceptions.values[i]; for (Pair p : attr.values) { Name key = p.fst.getSimpleName(); @@ -234,13 +226,11 @@ private SafeWrapException[] extractClassElementFromAnnotationContainer( valueFrom = (Attribute.Class) p.snd; } else if (key.contentEquals(ToElementName)) { valueTo = (Attribute.Class) p.snd; - } else if (key.contentEquals(PropagateElementName)) { - valuePropagate = (Attribute.Constant) p.snd; } } if (valueFrom != null && valueTo != null) { SafeWrapException converted = - new SafeWrapException(valueFrom, valueTo, valuePropagate); + new SafeWrapException(valueFrom, valueTo); wrappedExceptions.add(converted); } } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodNodeClassGenerator.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodNodeClassGenerator.java index 6ca5f0632ada..a68ed5b57982 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodNodeClassGenerator.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodNodeClassGenerator.java @@ -17,17 +17,14 @@ public abstract class MethodNodeClassGenerator { ClassName builtinNode; ClassName ownerClazz; ClassName stdlibOwner; - Map builtinTypesParamCount; public MethodNodeClassGenerator( ClassName builtinNode, ClassName ownerClazz, - ClassName stdlibOwner, - Map builtinTypesParamCount) { + ClassName stdlibOwner) { this.builtinNode = builtinNode; this.ownerClazz = ownerClazz; this.stdlibOwner = stdlibOwner; - this.builtinTypesParamCount = builtinTypesParamCount; } /** @@ -82,7 +79,7 @@ public void generate( for (String line : methodsGen() .generate( - processingEnv, ownerMethodName, ownerClazz.name(), builtinTypesParamCount)) { + processingEnv, ownerMethodName, ownerClazz.name())) { out.println(" " + line); } out.println(); diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/NoSpecializationClassGenerator.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/NoSpecializationClassGenerator.java index d11cf85d3bda..5e8d1c8bc64c 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/NoSpecializationClassGenerator.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/NoSpecializationClassGenerator.java @@ -15,9 +15,8 @@ public NoSpecializationClassGenerator( ClassName builtinNode, ClassName ownerClazz, ClassName stdlibOwner, - int varArgExpansion, - Map builtinTypesParamCount) { - super(builtinNode, ownerClazz, stdlibOwner, builtinTypesParamCount); + int varArgExpansion) { + super(builtinNode, ownerClazz, stdlibOwner); this.origin = origin; this.varArgExpansion = varArgExpansion; } @@ -26,9 +25,8 @@ public NoSpecializationClassGenerator( ExecutableElement origin, ClassName builtinNode, ClassName ownerClazz, - ClassName stdlibOwner, - Map builtinTypesParamCount) { - this(origin, builtinNode, ownerClazz, stdlibOwner, 0, builtinTypesParamCount); + ClassName stdlibOwner) { + this(origin, builtinNode, ownerClazz, stdlibOwner, 0); } @Override diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SafeWrapException.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SafeWrapException.java index 332a27d958e3..6836826341a4 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SafeWrapException.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SafeWrapException.java @@ -13,52 +13,32 @@ * Wrapper around {@link Builtin.WrapException} annotation with all elements of Class type resolved. * extracted */ -public record SafeWrapException(Attribute.Class from, Attribute.Class to, Boolean passException) { +public record SafeWrapException(Attribute.Class from, Attribute.Class to) { private static final String PanicExceptionClassName = "PanicException"; - public SafeWrapException(Attribute.Class from, Attribute.Class to, Attribute.Constant propagate) { - this(from, to, propagate != null ? (Boolean) propagate.getValue() : false); - } - /** * Generate a catch-clause that catches `from`, wraps it into `to` Enso type and rethrows the latter - * @param methodParameters list of all method's parameters, potentially to be applied to `to` constructor - * @param builtinTypesParameterCounts a map from builtin errors to the number of parameters in their constructors * @return Lines representing the (unclosed) catch-clause catching the runtime `from` exception */ - List toCatchClause(List methodParameters, Map builtinTypesParameterCounts) { + List toCatchClause() { String from = fromAttributeToClassName(from(), true); String to = fromAttributeToClassName(to(), false); - if (passException) { - if (to.equals(PanicExceptionClassName)) { - return List.of( - " } catch (" + from + " e) {", - " Builtins builtins = Context.get(this).getBuiltins();", - " throw new PanicException(e.getMessage(), this);" - ); - } else { - return List.of( - " } catch (" + from + " e) {", - " Builtins builtins = Context.get(this).getBuiltins();", - " throw new PanicException(builtins.error().make" + to + "(e), this);" - ); - } + if (to.equals(PanicExceptionClassName)) { + return List.of( + " } catch (" + from + " e) {", + " Builtins builtins = Context.get(this).getBuiltins();", + " throw new PanicException(e.getMessage(), this);" + ); } else { - int toParamCount = errorParametersCount(to(), builtinTypesParameterCounts); - List errorParameters = - methodParameters - .stream() - .limit(toParamCount - 1) - .flatMap(x -> x.names(Optional.empty())) - .collect(Collectors.toList()); - String errorParameterCode = errorParameters.isEmpty() ? "" : ", " + StringUtils.join(errorParameters, ", "); return List.of( - " } catch (" + from + " e) {", - " Builtins builtins = Context.get(this).getBuiltins();", - " throw new PanicException(builtins.error().make" + to + "(self" + errorParameterCode + "), this);" + " } catch (" + from + " e) {", + " Context ctx = Context.get(this);", + " Builtins builtins = ctx.getBuiltins();", + " throw new PanicException(builtins.error().get" + to + "().wrap(ctx, e), this);" ); } + } private String fromAttributeToClassName(Attribute.Class clazz, Boolean fullName) { @@ -73,10 +53,4 @@ private String fromAttributeToClassName(Attribute.Class clazz, Boolean fullName) } } } - - private int errorParametersCount(Attribute.Class clazz, Map builtinTypesParameterCounts) { - String clazzSimple = fromAttributeToClassName(clazz, false); - // `this` counts as 1 - return builtinTypesParameterCounts.getOrDefault(clazzSimple, 1); - } } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializationClassGenerator.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializationClassGenerator.java index f6349a0744a8..c179e0608fe5 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializationClassGenerator.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializationClassGenerator.java @@ -17,9 +17,8 @@ public SpecializationClassGenerator( List methodElements, ClassName builtinNode, ClassName ownerClazz, - ClassName stdlibOwner, - Map parameterCounts) { - super(builtinNode, ownerClazz, stdlibOwner, parameterCounts); + ClassName stdlibOwner) { + super(builtinNode, ownerClazz, stdlibOwner); this.elements = methodElements; } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializedMethodsGenerator.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializedMethodsGenerator.java index b78ecc01d3db..482e705f87d5 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializedMethodsGenerator.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializedMethodsGenerator.java @@ -60,11 +60,7 @@ private boolean allEqual(Stream stream) { } @Override - public List generate( - ProcessingEnvironment processingEnv, - String name, - String owner, - Map builtinTypesParameterCounts) { + public List generate(ProcessingEnvironment processingEnv, String name, String owner) { SpecializationMeta meta = inferExecuteParameters(); List result = new ArrayList<>(); @@ -74,9 +70,7 @@ public List generate( paramsOfSpecializedMethods(processingEnv, meta.diffParam) .flatMap( specializeMethod -> - specialize( - owner, name, specializeMethod, meta.diffParam, builtinTypesParameterCounts) - .stream()) + specialize(owner, name, specializeMethod, meta.diffParam).stream()) .collect(Collectors.toList())); return result; } @@ -221,8 +215,7 @@ protected List specialize( String owner, String name, SpecializeMethodInfo methodInfo, - Optional specializedParam, - Map builtinTypesParameterCounts) { + Optional specializedParam) { List params1 = methodInfo.params().stream() .map(p -> SpecializedMethodParameter.paramOfSpecializedMethod(p, specializedParam)) @@ -288,8 +281,7 @@ protected List specialize( } for (int i = 0; i < methodInfo.exceptionWrappers.length; i++) { specializationDeclaration.addAll( - methodInfo.exceptionWrappers[i].toCatchClause( - methodInfo.params, builtinTypesParameterCounts)); + methodInfo.exceptionWrappers[i].toCatchClause()); } specializationDeclaration.add(" }"); } else { From 8ad6bf5d89cb75c40612cc516476738edac81878 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 4 Aug 2022 21:27:42 +0200 Subject: [PATCH 034/110] fix more tests --- .../test/resources/TestSubmodules/src/A/B.enso | 2 +- .../resources/TestSubmodules/src/A/B/C.enso | 4 ++-- .../resources/TestSubmodules/src/A/B/D.enso | 2 +- .../test/resources/TestSubmodules/src/A/E.enso | 2 +- .../resources/TestSubmodules/src/Main.enso | 4 ++-- .../test/resources/TestSubmodules/src/Meh.enso | 4 ++-- .../test/semantic/CompileDiagnosticsTest.scala | 8 ++++---- .../test/semantic/MixfixFunctionsTest.scala | 2 +- .../interpreter/test/semantic/TextTest.scala | 12 ++++++------ .../Base/0.0.0-dev/src/Error/Common.enso | 18 ++++++++++++------ 10 files changed, 32 insertions(+), 26 deletions(-) diff --git a/engine/runtime/src/test/resources/TestSubmodules/src/A/B.enso b/engine/runtime/src/test/resources/TestSubmodules/src/A/B.enso index 3cb08921be17..39da98ae7526 100644 --- a/engine/runtime/src/test/resources/TestSubmodules/src/A/B.enso +++ b/engine/runtime/src/test/resources/TestSubmodules/src/A/B.enso @@ -1,4 +1,4 @@ type Bar - type Bar x + Mk_Bar x bar_mod_method x = x+10 diff --git a/engine/runtime/src/test/resources/TestSubmodules/src/A/B/C.enso b/engine/runtime/src/test/resources/TestSubmodules/src/A/B/C.enso index cf5f2c8ffb13..a602c7ac31db 100644 --- a/engine/runtime/src/test/resources/TestSubmodules/src/A/B/C.enso +++ b/engine/runtime/src/test/resources/TestSubmodules/src/A/B/C.enso @@ -1,4 +1,4 @@ type C - type C x + Mk_C x -c_mod_method a = C 42+a +c_mod_method a = Mk_C 42+a diff --git a/engine/runtime/src/test/resources/TestSubmodules/src/A/B/D.enso b/engine/runtime/src/test/resources/TestSubmodules/src/A/B/D.enso index 748519e51c3c..e50a1b5e0a9f 100644 --- a/engine/runtime/src/test/resources/TestSubmodules/src/A/B/D.enso +++ b/engine/runtime/src/test/resources/TestSubmodules/src/A/B/D.enso @@ -1,2 +1,2 @@ type D - type D a + Mk_D a diff --git a/engine/runtime/src/test/resources/TestSubmodules/src/A/E.enso b/engine/runtime/src/test/resources/TestSubmodules/src/A/E.enso index 1d7cae4cce3e..6cee5be35f1a 100644 --- a/engine/runtime/src/test/resources/TestSubmodules/src/A/E.enso +++ b/engine/runtime/src/test/resources/TestSubmodules/src/A/E.enso @@ -1,2 +1,2 @@ type E - type E a + Mk_E a diff --git a/engine/runtime/src/test/resources/TestSubmodules/src/Main.enso b/engine/runtime/src/test/resources/TestSubmodules/src/Main.enso index cd41935d7106..e1829255e486 100644 --- a/engine/runtime/src/test/resources/TestSubmodules/src/Main.enso +++ b/engine/runtime/src/test/resources/TestSubmodules/src/Main.enso @@ -1,13 +1,13 @@ from Standard.Base import IO from project.Meh import all import project.A -from project.A.B.C import C +from project.A.B.C import Mk_C main = a = Foo 10 b = A.B.C.c_mod_method 10 c = A.B.bar_mod_method 10 - d = C 10 + d = Mk_C 10 IO.println a.to_text IO.println b.to_text diff --git a/engine/runtime/src/test/resources/TestSubmodules/src/Meh.enso b/engine/runtime/src/test/resources/TestSubmodules/src/Meh.enso index 2b95bc422780..28eb9bcb9d0e 100644 --- a/engine/runtime/src/test/resources/TestSubmodules/src/Meh.enso +++ b/engine/runtime/src/test/resources/TestSubmodules/src/Meh.enso @@ -1,5 +1,5 @@ type Meh - type Foo a - type Bar b + Foo a + Bar b create a = Bar a 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 5c7bb6ecc9b9..bdc23c40e04c 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 @@ -16,7 +16,7 @@ class CompileDiagnosticsTest extends InterpreterTest { | x = Panic.catch_primitive () .convert_to_dataflow_error | x.catch_primitive err-> | case err of - | Syntax_Error msg -> "Oopsie, it's a syntax error: " + msg + | Mk_Syntax_Error msg -> "Oopsie, it's a syntax error: " + msg |""".stripMargin eval( code @@ -31,7 +31,7 @@ class CompileDiagnosticsTest extends InterpreterTest { | x = Panic.catch_primitive @ caught_panic-> caught_panic.payload | x.to_text |""".stripMargin - eval(code) shouldEqual "(Syntax_Error 'Unrecognized token.')" + eval(code) shouldEqual "(Make_Syntax_Error 'Unrecognized token.')" } "surface redefinition errors in the language" in { @@ -44,7 +44,7 @@ class CompileDiagnosticsTest extends InterpreterTest { | |main = Panic.catch_primitive foo caught_panic->caught_panic.payload.to_text |""".stripMargin - eval(code) shouldEqual "(Compile_Error 'Variable x is being redefined.')" + eval(code) shouldEqual "(Make_Compile_Error 'Variable x is being redefined.')" } "surface non-existent variable errors in the language" in { @@ -59,7 +59,7 @@ class CompileDiagnosticsTest extends InterpreterTest { |""".stripMargin eval( code - ) shouldEqual "(Compile_Error 'The name `my_vra` could not be found.')" + ) shouldEqual "(Make_Compile_Error 'The name `my_vra` could not be found.')" } } } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MixfixFunctionsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MixfixFunctionsTest.scala index 80ae236b15da..bbf0811445bc 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MixfixFunctionsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/MixfixFunctionsTest.scala @@ -30,7 +30,7 @@ class MixfixFunctionsTest extends InterpreterTest { |type Foo | Mk_Foo a b | - |Foo.if_then_else = a -> b -> case self of + |Foo.if_then_else self = a -> b -> case self of | Mk_Foo x y -> x + y + a + b | |main = if (Mk_Foo 1 2) then 3 else 4 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 4ad2d7c8d60f..c819755087f7 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 @@ -113,14 +113,14 @@ class TextTest extends InterpreterTest { | |main = | IO.println (Cons Nothing Nothing).to_display_text - | IO.println (Syntax_Error "foo").to_display_text - | IO.println (Type_Error Nothing Nil "myvar").to_display_text - | IO.println (Compile_Error "error :(").to_display_text - | IO.println (Inexhaustive_Pattern_Match_Error 32).to_display_text - | IO.println (Arithmetic_Error "cannot frobnicate quaternions").to_display_text + | IO.println (Make_Syntax_Error "foo").to_display_text + | IO.println (Make_Type_Error Nothing Nil "myvar").to_display_text + | IO.println (Make_Compile_Error "error :(").to_display_text + | IO.println (Make_Inexhaustive_Pattern_Match_Error 32).to_display_text + | IO.println (Make_Arithmetic_Error "cannot frobnicate quaternions").to_display_text | IO.println ((Panic.catch_primitive (1 + "foo") .convert_to_dataflow_error).catch_primitive .to_display_text) | IO.println ((Panic.catch_primitive (7 1) .convert_to_dataflow_error).catch_primitive .to_display_text) - | IO.println (Arity_Error 10 10 20).to_display_text + | IO.println (Make_Arity_Error 10 10 20).to_display_text |""".stripMargin eval(code) consumeOut shouldEqual List( diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index ff7114d91928..047b18f66700 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso @@ -6,20 +6,26 @@ type Panic catch_primitive ~action handler = @Builtin_Method "Panic.catch_primitive" @Builtin_Type -type Syntax_Error message +type Syntax_Error + Make_Syntax_Error message @Builtin_Type type Polyglot_Error Make_Polyglot_Error cause @Builtin_Type -type Arithmetic_Error message +type Arithmetic_Error + Make_Arithmetic_Error message @Builtin_Type -type Type_Error expected actual name +type Type_Error + Make_Type_Error expected actual name @Builtin_Type -type Compile_Error message +type Compile_Error + Make_Compile_Error message @Builtin_Type -type Inexhaustive_Pattern_Match_Error scrutinee +type Inexhaustive_Pattern_Match_Error + Make_Inexhaustive_Pattern_Match_Error scrutinee @Builtin_Type -type Arity_Error expected_min expected_max actual +type Arity_Error + Make_Arity_Error expected_min expected_max actual @Builtin_Type type Error From 184b54cabdfc3a14e20f53fa6e3f3c3b1e4d52a3 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 9 Aug 2022 19:34:47 +0200 Subject: [PATCH 035/110] make the benchmarks compile --- .../benchmarks/semantic/AtomBenchmarks.java | 6 +++--- .../semantic/CallableBenchmarks.java | 2 +- .../NamedDefaultedArgumentBenchmarks.java | 2 +- .../semantic/RecursionBenchmarks.java | 4 ++-- .../fixtures/semantic/AtomFixtures.scala | 20 +++++++++---------- .../fixtures/semantic/CallableFixtures.scala | 12 +++++------ 6 files changed, 23 insertions(+), 23 deletions(-) diff --git a/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/AtomBenchmarks.java b/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/AtomBenchmarks.java index 57a9a4ad702d..f2c8f106e04b 100644 --- a/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/AtomBenchmarks.java +++ b/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/AtomBenchmarks.java @@ -22,17 +22,17 @@ public class AtomBenchmarks { @Benchmark public void benchGenerateList() { DefaultInterpreterRunner.MainMethod main = fixtures.generateList(); - main.mainFunction().value().execute(main.mainConstructor(), fixtures.million()); + main.mainFunction().value().execute(fixtures.million()); } @Benchmark public void benchGenerateListQualified() { DefaultInterpreterRunner.MainMethod main = fixtures.generateListQualified(); - main.mainFunction().value().execute(main.mainConstructor(), fixtures.million()); + main.mainFunction().value().execute(fixtures.million()); } private void benchOnList(DefaultInterpreterRunner.MainMethod main) { - main.mainFunction().value().execute(main.mainConstructor(), fixtures.millionElementList()); + main.mainFunction().value().execute(fixtures.millionElementList()); } @Benchmark diff --git a/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/CallableBenchmarks.java b/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/CallableBenchmarks.java index 006417e7e5d9..31a7f7ad6a04 100644 --- a/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/CallableBenchmarks.java +++ b/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/CallableBenchmarks.java @@ -22,7 +22,7 @@ public class CallableBenchmarks { new CallableFixtures(); private void runOnHundredMillion(DefaultInterpreterRunner.MainMethod main) { - main.mainFunction().value().execute(main.mainConstructor(), argumentFixtures.hundredMillion()); + main.mainFunction().value().execute(argumentFixtures.hundredMillion()); } @Benchmark diff --git a/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/NamedDefaultedArgumentBenchmarks.java b/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/NamedDefaultedArgumentBenchmarks.java index 86b7bbee5a02..8946f9b0b619 100644 --- a/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/NamedDefaultedArgumentBenchmarks.java +++ b/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/NamedDefaultedArgumentBenchmarks.java @@ -21,7 +21,7 @@ public class NamedDefaultedArgumentBenchmarks { new NamedDefaultedArgumentFixtures(); private void runOnHundredMillion(DefaultInterpreterRunner.MainMethod main) { - main.mainFunction().value().execute(main.mainConstructor(), argumentFixtures.hundredMillion()); + main.mainFunction().value().execute(argumentFixtures.hundredMillion()); } @Benchmark diff --git a/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/RecursionBenchmarks.java b/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/RecursionBenchmarks.java index c302efa68dbe..27ce3a3326cc 100644 --- a/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/RecursionBenchmarks.java +++ b/engine/runtime/src/bench/java/org/enso/interpreter/bench/benchmarks/semantic/RecursionBenchmarks.java @@ -15,7 +15,7 @@ public class RecursionBenchmarks { private static RecursionFixtures recursionFixtures = new RecursionFixtures(); private void runOnHundredMillion(DefaultInterpreterRunner.MainMethod main) { - main.mainFunction().value().execute(main.mainConstructor(), recursionFixtures.hundredMillion()); + main.mainFunction().value().execute(recursionFixtures.hundredMillion()); } @Benchmark @@ -36,7 +36,7 @@ public void benchSumTCOFoldLike() { @Benchmark public void benchSumRecursive() { DefaultInterpreterRunner.MainMethod main = recursionFixtures.sumRecursive(); - main.mainFunction().value().execute(main.mainConstructor(), recursionFixtures.hundred()); + main.mainFunction().value().execute(recursionFixtures.hundred()); } @Benchmark 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 7a4871a1e8e4..3bdc4b41893d 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 @@ -29,9 +29,9 @@ class AtomFixtures extends DefaultInterpreterRunner { """from Standard.Base.Data.List import all | |main = length -> - | generator = acc -> i -> if i == 0 then acc else @Tail_Call generator (List.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 List.nil length + | res = generator List.Nil length | res """.stripMargin val generateListQualified = getMain(generateListQualifiedCode) @@ -52,10 +52,10 @@ class AtomFixtures extends DefaultInterpreterRunner { val reverseListMethodsCode = """from Standard.Base.Data.List import all | - |Cons.rev = acc -> case self of + |Cons.rev self acc = case self of | Cons h t -> @Tail_Call t.rev (Cons h acc) | - |Nil.rev = acc -> acc + |Nil.rev self acc = acc | |main = list -> | res = list.rev Nil @@ -105,8 +105,8 @@ class AtomFixtures extends DefaultInterpreterRunner { val sumListMethodsCode = """from Standard.Base.Data.List import all | - |Nil.sum = acc -> acc - |Cons.sum = acc -> case self of + |Nil.sum self acc = acc + |Cons.sum self acc = case self of | Cons h t -> @Tail_Call t.sum h+acc | |main = list -> @@ -118,8 +118,8 @@ class AtomFixtures extends DefaultInterpreterRunner { val mapReverseListCode = """from Standard.Base.Data.List import all | - |Nil.mapReverse = f -> acc -> acc - |Cons.mapReverse = f -> acc -> case self of + |Nil.mapReverse self f acc = acc + |Cons.mapReverse self f acc = case self of | Cons h t -> @Tail_Call t.mapReverse f (Cons (f h) acc) | |main = list -> @@ -131,8 +131,8 @@ class AtomFixtures extends DefaultInterpreterRunner { val mapReverseListCurryCode = """from Standard.Base.Data.List import all | - |Nil.mapReverse = f -> acc -> acc - |Cons.mapReverse = f -> acc -> case self of + |Nil.mapReverse self f acc = acc + |Cons.mapReverse self f acc = case self of | Cons h t -> @Tail_Call t.mapReverse f (Cons (f h) acc) | |main = list -> 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 38c392d91c02..e569c0d3798d 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 @@ -24,10 +24,10 @@ class CallableFixtures extends DefaultInterpreterRunner { val sumTCOmethodCallCode = """ |summator = acc -> current -> - | if current == 0 then acc else @Tail_Call here.summator (acc + current) (current - 1) + | if current == 0 then acc else @Tail_Call summator (acc + current) (current - 1) | |main = sumTo -> - | res = here.summator 0 sumTo + | res = summator 0 sumTo | res |""".stripMargin val sumTCOmethodCall = getMain(sumTCOmethodCallCode) @@ -35,10 +35,10 @@ class CallableFixtures extends DefaultInterpreterRunner { val sumTCOmethodCallWithNamedArgumentsCode = """ |summator = acc -> current -> - | if current == 0 then acc else @Tail_Call here.summator (current = current - 1) (acc = acc + current) + | if current == 0 then acc else @Tail_Call summator (current = current - 1) (acc = acc + current) | |main = sumTo -> - | res = here.summator current=sumTo acc=0 + | res = summator current=sumTo acc=0 | res |""".stripMargin val sumTCOmethodCallWithNamedArguments = @@ -47,10 +47,10 @@ class CallableFixtures extends DefaultInterpreterRunner { val sumTCOmethodCallWithDefaultedArgumentsCode = """ |summator = (acc = 0) -> current -> - | if current == 0 then acc else @Tail_Call here.summator (current = current - 1) (acc = acc + current) + | if current == 0 then acc else @Tail_Call summator (current = current - 1) (acc = acc + current) | |main = sumTo -> - | res = here.summator current=sumTo + | res = summator current=sumTo | res |""".stripMargin val sumTCOmethodCallWithDefaultedArguments = From 2092fd6ad0a131f242366c027dffaf491979bcb6 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 9 Aug 2022 21:08:48 +0200 Subject: [PATCH 036/110] update benchmarks --- .../bench/fixtures/semantic/AtomFixtures.scala | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala index 3bdc4b41893d..3970af647c82 100644 --- a/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala +++ b/engine/runtime/src/bench/scala/org/enso/interpreter/bench/fixtures/semantic/AtomFixtures.scala @@ -52,10 +52,9 @@ class AtomFixtures extends DefaultInterpreterRunner { val reverseListMethodsCode = """from Standard.Base.Data.List import all | - |Cons.rev self acc = case self of + |List.List.rev self acc = case self of | Cons h t -> @Tail_Call t.rev (Cons h acc) - | - |Nil.rev self acc = acc + | _ -> acc | |main = list -> | res = list.rev Nil @@ -105,9 +104,9 @@ class AtomFixtures extends DefaultInterpreterRunner { val sumListMethodsCode = """from Standard.Base.Data.List import all | - |Nil.sum self acc = acc - |Cons.sum self acc = case self of + |List.List.sum self acc = case self of | Cons h t -> @Tail_Call t.sum h+acc + | _ -> acc | |main = list -> | res = list.sum 0 @@ -118,9 +117,9 @@ class AtomFixtures extends DefaultInterpreterRunner { val mapReverseListCode = """from Standard.Base.Data.List import all | - |Nil.mapReverse self f acc = acc - |Cons.mapReverse self f acc = case self of + |List.List.mapReverse self f acc = case self of | Cons h t -> @Tail_Call t.mapReverse f (Cons (f h) acc) + | _ -> acc | |main = list -> | res = list.mapReverse (x -> x + 1) Nil @@ -131,9 +130,9 @@ class AtomFixtures extends DefaultInterpreterRunner { val mapReverseListCurryCode = """from Standard.Base.Data.List import all | - |Nil.mapReverse self f acc = acc - |Cons.mapReverse self f acc = case self of + |List.List.mapReverse self f acc = case self of | Cons h t -> @Tail_Call t.mapReverse f (Cons (f h) acc) + | _ -> acc | |main = list -> | adder = x -> y -> x + y From 30d8e6e0a3e89ab00e2e7795c08564cdf7393ad7 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 10 Aug 2022 13:02:53 +0200 Subject: [PATCH 037/110] simplify dispatch --- .../IndirectInvokeConversionNode.java | 82 +++++++------ .../callable/IndirectInvokeMethodNode.java | 75 ++++++------ .../node/callable/InvokeConversionNode.java | 55 ++++----- .../node/callable/InvokeMethodNode.java | 85 +++++++------- .../callable/resolver/AnyResolverNode.java | 32 ----- .../callable/resolver/BaseResolverNode.java | 35 ------ .../resolver/ConversionResolverNode.java | 66 +++++++++++ .../resolver/DataflowErrorResolverNode.java | 32 ----- .../callable/resolver/MethodResolverNode.java | 60 ++++++++++ .../runtime/builtin/BuiltinType.java | 1 - .../interpreter/runtime/builtin/Builtins.java | 25 ++-- .../interpreter/runtime/builtin/Number.java | 43 ++++--- .../runtime/callable/atom/Atom.java | 97 +--------------- .../callable/atom/AtomConstructor.java | 98 ++-------------- .../runtime/callable/function/Function.java | 107 ++--------------- .../enso/interpreter/runtime/data/Array.java | 101 +--------------- .../interpreter/runtime/data/EnsoDate.java | 51 ++------ .../interpreter/runtime/data/EnsoFile.java | 52 +-------- .../runtime/data/ManagedResource.java | 51 +------- .../enso/interpreter/runtime/data/Ref.java | 56 ++------- .../enso/interpreter/runtime/data/Type.java | 100 +--------------- .../interpreter/runtime/data/text/Text.java | 107 +---------------- .../runtime/error/DataflowError.java | 57 +-------- .../runtime/error/PanicSentinel.java | 9 +- .../interpreter/runtime/error/Warning.java | 52 ++------- .../runtime/error/WithWarnings.java | 4 +- .../dispatch/DefaultBooleanExports.java | 109 +----------------- .../dispatch/DefaultDoubleExports.java | 106 +---------------- .../library/dispatch/DefaultLongExports.java | 107 +---------------- ...DispatchLibrary.java => TypesLibrary.java} | 49 ++------ .../runtime/number/EnsoBigInteger.java | 104 +---------------- .../runtime/type/TypesFromProxy.java | 6 +- 32 files changed, 425 insertions(+), 1589 deletions(-) delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/AnyResolverNode.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/BaseResolverNode.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/ConversionResolverNode.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/DataflowErrorResolverNode.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/MethodResolverNode.java rename engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/{MethodDispatchLibrary.java => TypesLibrary.java} (50%) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeConversionNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeConversionNode.java index 840aa6741ac4..0f5bbd21eb34 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeConversionNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeConversionNode.java @@ -7,9 +7,9 @@ import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.profiles.BranchProfile; -import com.oracle.truffle.api.profiles.ConditionProfile; import org.enso.interpreter.node.BaseNode; import org.enso.interpreter.node.callable.dispatch.IndirectInvokeFunctionNode; +import org.enso.interpreter.node.callable.resolver.ConversionResolverNode; import org.enso.interpreter.node.callable.resolver.HostMethodCallNode; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.UnresolvedConversion; @@ -18,7 +18,7 @@ import org.enso.interpreter.runtime.data.ArrayRope; import org.enso.interpreter.runtime.data.text.Text; import org.enso.interpreter.runtime.error.*; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import org.enso.interpreter.runtime.state.Stateful; @GenerateUncached @@ -46,7 +46,7 @@ public abstract Stateful execute( BaseNode.TailStatus isTail, int thatArgumentPosition); - @Specialization(guards = "dispatch.canConvertFrom(that)") + @Specialization(guards = {"dispatch.hasType(that)", "!dispatch.hasSpecialDispatch(that)"}) Stateful doConvertFrom( MaterializedFrame frame, Object state, @@ -59,26 +59,24 @@ Stateful doConvertFrom( InvokeCallableNode.ArgumentsExecutionMode argumentsExecutionMode, BaseNode.TailStatus isTail, int thatArgumentPosition, - @CachedLibrary(limit = "10") MethodDispatchLibrary dispatch, + @CachedLibrary(limit = "10") TypesLibrary dispatch, + @Cached ConversionResolverNode conversionResolverNode, @Cached IndirectInvokeFunctionNode indirectInvokeFunctionNode) { - try { - Function function = - dispatch.getConversionFunction( - that, InvokeConversionNode.extractConstructor(this, self), conversion); - return indirectInvokeFunctionNode.execute( - function, - frame, - state, - arguments, - schema, - defaultsExecutionMode, - argumentsExecutionMode, - isTail); - } catch (MethodDispatchLibrary.NoSuchConversionException e) { - throw new PanicException( - Context.get(this).getBuiltins().error().makeNoSuchConversionError(self, that, conversion), - this); - } + Function function = + conversionResolverNode.expectNonNull( + that, + InvokeConversionNode.extractConstructor(this, self), + dispatch.getType(that), + conversion); + return indirectInvokeFunctionNode.execute( + function, + frame, + state, + arguments, + schema, + defaultsExecutionMode, + argumentsExecutionMode, + isTail); } @Specialization @@ -94,13 +92,15 @@ Stateful doDataflowError( InvokeCallableNode.ArgumentsExecutionMode argumentsExecutionMode, BaseNode.TailStatus isTail, int thatArgumentPosition, - @CachedLibrary(limit = "10") MethodDispatchLibrary dispatch, - @Cached BranchProfile profile, - @Cached IndirectInvokeFunctionNode indirectInvokeFunctionNode) { - try { - Function function = - dispatch.getConversionFunction( - that, InvokeConversionNode.extractConstructor(this, self), conversion); + @CachedLibrary(limit = "10") TypesLibrary dispatch, + @Cached IndirectInvokeFunctionNode indirectInvokeFunctionNode, + @Cached ConversionResolverNode conversionResolverNode) { + Function function = + conversionResolverNode.execute( + InvokeConversionNode.extractConstructor(this, self), + Context.get(this).getBuiltins().dataflowError(), + conversion); + if (function != null) { return indirectInvokeFunctionNode.execute( function, frame, @@ -110,8 +110,7 @@ Stateful doDataflowError( defaultsExecutionMode, argumentsExecutionMode, isTail); - } catch (MethodDispatchLibrary.NoSuchConversionException e) { - profile.enter(); + } else { return new Stateful(state, that); } } @@ -177,16 +176,19 @@ Stateful doConvertText( InvokeCallableNode.ArgumentsExecutionMode argumentsExecutionMode, BaseNode.TailStatus isTail, int thatArgumentPosition, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, - @CachedLibrary(limit = "1") MethodDispatchLibrary textDispatch, + @CachedLibrary(limit = "10") TypesLibrary methods, @CachedLibrary(limit = "10") InteropLibrary interop, + @Cached ConversionResolverNode conversionResolverNode, @Cached IndirectInvokeFunctionNode indirectInvokeFunctionNode) { try { String str = interop.asString(that); Text txt = Text.create(str); Function function = - textDispatch.getConversionFunction( - txt, InvokeConversionNode.extractConstructor(this, self), conversion); + conversionResolverNode.expectNonNull( + txt, + InvokeConversionNode.extractConstructor(this, self), + Context.get(this).getBuiltins().text(), + conversion); arguments[0] = txt; return indirectInvokeFunctionNode.execute( function, @@ -199,18 +201,14 @@ Stateful doConvertText( isTail); } catch (UnsupportedMessageException e) { throw new IllegalStateException("Impossible, that is guaranteed to be a string."); - } catch (MethodDispatchLibrary.NoSuchConversionException e) { - throw new PanicException( - Context.get(this).getBuiltins().error().makeNoSuchConversionError(self, that, conversion), - this); } } @Specialization( guards = { - "!methods.canConvertFrom(that)", + "!methods.hasType(that)", "!interop.isString(that)", - "!methods.hasSpecialConversion(that)" + "!methods.hasSpecialDispatch(that)" }) Stateful doFallback( MaterializedFrame frame, @@ -224,7 +222,7 @@ Stateful doFallback( InvokeCallableNode.ArgumentsExecutionMode argumentsExecutionMode, BaseNode.TailStatus isTail, int thatArgumentPosition, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, + @CachedLibrary(limit = "10") TypesLibrary methods, @CachedLibrary(limit = "10") InteropLibrary interop) { throw new PanicException( Context.get(this).getBuiltins().error().makeNoSuchConversionError(self, that, conversion), diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeMethodNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeMethodNode.java index 2d963b0df278..a1b33c6c7ac9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeMethodNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeMethodNode.java @@ -23,7 +23,7 @@ import org.enso.interpreter.runtime.data.ArrayRope; import org.enso.interpreter.runtime.data.text.Text; import org.enso.interpreter.runtime.error.*; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import org.enso.interpreter.runtime.state.Stateful; @GenerateUncached @@ -31,7 +31,9 @@ @ImportStatic({HostMethodCallNode.PolyglotCallType.class, HostMethodCallNode.class}) public abstract class IndirectInvokeMethodNode extends Node { - /** @return a new indirect method invocation node */ + /** + * @return a new indirect method invocation node + */ public static IndirectInvokeMethodNode build() { return IndirectInvokeMethodNodeGen.create(); } @@ -48,7 +50,7 @@ public abstract Stateful execute( BaseNode.TailStatus isTail, int thisArgumentPosition); - @Specialization(guards = "dispatch.hasFunctionalDispatch(self)") + @Specialization(guards = {"dispatch.hasType(self)", "!dispatch.hasSpecialDispatch(self)"}) Stateful doFunctionalDispatch( MaterializedFrame frame, Object state, @@ -60,23 +62,19 @@ Stateful doFunctionalDispatch( InvokeCallableNode.ArgumentsExecutionMode argumentsExecutionMode, BaseNode.TailStatus isTail, int thisArgumentPosition, - @CachedLibrary(limit = "10") MethodDispatchLibrary dispatch, + @CachedLibrary(limit = "10") TypesLibrary dispatch, + @Cached MethodResolverNode methodResolverNode, @Cached IndirectInvokeFunctionNode invokeFunctionNode) { - try { - Function function = dispatch.getFunctionalDispatch(self, symbol); - return invokeFunctionNode.execute( - function, - frame, - state, - arguments, - schema, - defaultsExecutionMode, - argumentsExecutionMode, - isTail); - } catch (MethodDispatchLibrary.NoSuchMethodException e) { - throw new PanicException( - Context.get(this).getBuiltins().error().makeNoSuchMethodError(self, symbol), this); - } + Function function = methodResolverNode.expectNonNull(self, dispatch.getType(self), symbol); + return invokeFunctionNode.execute( + function, + frame, + state, + arguments, + schema, + defaultsExecutionMode, + argumentsExecutionMode, + isTail); } @Specialization @@ -91,10 +89,11 @@ Stateful doDataflowError( InvokeCallableNode.ArgumentsExecutionMode argumentsExecutionMode, BaseNode.TailStatus isTail, int thisArgumentPosition, - @Cached DataflowErrorResolverNode dataflowErrorResolverNode, + @Cached MethodResolverNode methodResolverNode, @Cached IndirectInvokeFunctionNode invokeFunctionNode, @Cached ConditionProfile profile) { - Function function = dataflowErrorResolverNode.execute(symbol, self); + Function function = + methodResolverNode.execute(Context.get(this).getBuiltins().dataflowError(), symbol); if (profile.profile(function == null)) { return new Stateful(state, self); } else { @@ -157,7 +156,7 @@ Stateful doPanicSentinel( @Specialization( guards = { - "!methods.hasFunctionalDispatch(self)", + "!methods.hasType(self)", "!methods.hasSpecialDispatch(self)", "polyglotCallType != NOT_SUPPORTED", "polyglotCallType != CONVERT_TO_TEXT" @@ -173,7 +172,7 @@ Stateful doPolyglot( InvokeCallableNode.ArgumentsExecutionMode argumentsExecutionMode, BaseNode.TailStatus isTail, int thisArgumentPosition, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, + @CachedLibrary(limit = "10") TypesLibrary methods, @CachedLibrary(limit = "10") InteropLibrary interop, @Bind("getPolyglotCallType(self, symbol.getName(), interop)") HostMethodCallNode.PolyglotCallType polyglotCallType, @@ -195,7 +194,7 @@ Stateful doPolyglot( @Specialization( guards = { - "!methods.hasFunctionalDispatch(self)", + "!methods.hasType(self)", "!methods.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == CONVERT_TO_TEXT" }) @@ -210,15 +209,17 @@ Stateful doConvertText( InvokeCallableNode.ArgumentsExecutionMode argumentsExecutionMode, BaseNode.TailStatus isTail, int thisArgumentPosition, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, - @CachedLibrary(limit = "1") MethodDispatchLibrary textDispatch, + @CachedLibrary(limit = "10") TypesLibrary methods, + @Cached MethodResolverNode methodResolverNode, @CachedLibrary(limit = "10") InteropLibrary interop, @Cached IndirectInvokeFunctionNode invokeFunctionNode) { try { - String str = interop.asString(self); - Text txt = Text.create(str); - Function function = textDispatch.getFunctionalDispatch(txt, symbol); - arguments[0] = txt; + var str = interop.asString(self); + var text = Text.create(str); + var ctx = Context.get(this); + var textType = ctx.getBuiltins().text(); + var function = methodResolverNode.expectNonNull(text, textType, symbol); + arguments[0] = text; return invokeFunctionNode.execute( function, frame, @@ -230,16 +231,13 @@ Stateful doConvertText( isTail); } catch (UnsupportedMessageException e) { throw new IllegalStateException("Impossible, self is guaranteed to be a string."); - } catch (MethodDispatchLibrary.NoSuchMethodException e) { - throw new PanicException( - Context.get(this).getBuiltins().error().makeNoSuchMethodError(self, symbol), this); } } @ExplodeLoop @Specialization( guards = { - "!methods.hasFunctionalDispatch(self)", + "!methods.hasType(self)", "!methods.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == NOT_SUPPORTED" }) @@ -254,15 +252,14 @@ Stateful doFallback( InvokeCallableNode.ArgumentsExecutionMode argumentsExecutionMode, BaseNode.TailStatus isTail, int thisArgumentPosition, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, + @CachedLibrary(limit = "10") TypesLibrary methods, @CachedLibrary(limit = "10") InteropLibrary interop, @Bind("getPolyglotCallType(self, symbol.getName(), interop)") HostMethodCallNode.PolyglotCallType polyglotCallType, - @Cached ThunkExecutorNode argExecutor, - @Cached AnyResolverNode anyResolverNode, - @Cached HostMethodCallNode hostMethodCallNode, + @Cached MethodResolverNode methodResolverNode, @Cached IndirectInvokeFunctionNode invokeFunctionNode) { - Function function = anyResolverNode.execute(symbol, self); + Function function = + methodResolverNode.expectNonNull(self, Context.get(this).getBuiltins().any(), symbol); return invokeFunctionNode.execute( function, frame, diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeConversionNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeConversionNode.java index 7270d0c3a33e..bc514c98832b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeConversionNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeConversionNode.java @@ -8,21 +8,19 @@ import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.nodes.Node; import com.oracle.truffle.api.profiles.BranchProfile; -import com.oracle.truffle.api.profiles.ConditionProfile; import com.oracle.truffle.api.source.SourceSection; import org.enso.interpreter.node.BaseNode; import org.enso.interpreter.node.callable.dispatch.InvokeFunctionNode; +import org.enso.interpreter.node.callable.resolver.ConversionResolverNode; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.UnresolvedConversion; import org.enso.interpreter.runtime.callable.argument.CallArgumentInfo; -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.data.ArrayRope; import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.data.text.Text; import org.enso.interpreter.runtime.error.*; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import org.enso.interpreter.runtime.state.Stateful; import java.util.UUID; @@ -88,7 +86,7 @@ Type extractConstructor(Object self) { return extractConstructor(this, self); } - @Specialization(guards = "dispatch.canConvertFrom(that)") + @Specialization(guards = {"dispatch.hasType(that)", "!dispatch.hasSpecialDispatch(that)"}) Stateful doConvertFrom( VirtualFrame frame, Object state, @@ -96,16 +94,12 @@ Stateful doConvertFrom( Object self, Object that, Object[] arguments, - @CachedLibrary(limit = "10") MethodDispatchLibrary dispatch) { - try { - Function function = - dispatch.getConversionFunction(that, extractConstructor(self), conversion); - return invokeFunctionNode.execute(function, frame, state, arguments); - } catch (MethodDispatchLibrary.NoSuchConversionException e) { - throw new PanicException( - Context.get(this).getBuiltins().error().makeNoSuchConversionError(self, that, conversion), - this); - } + @CachedLibrary(limit = "10") TypesLibrary dispatch, + @Cached ConversionResolverNode conversionResolverNode) { + Function function = + conversionResolverNode.expectNonNull( + that, extractConstructor(self), dispatch.getType(that), conversion); + return invokeFunctionNode.execute(function, frame, state, arguments); } @Specialization @@ -116,14 +110,14 @@ Stateful doDataflowError( Object self, DataflowError that, Object[] arguments, - @CachedLibrary(limit = "10") MethodDispatchLibrary dispatch, - @Cached BranchProfile profile) { - try { - Function function = - dispatch.getConversionFunction(that, extractConstructor(self), conversion); + @CachedLibrary(limit = "10") TypesLibrary dispatch, + @Cached ConversionResolverNode conversionResolverNode) { + Function function = + conversionResolverNode.execute( + extractConstructor(self), Context.get(this).getBuiltins().dataflowError(), conversion); + if (function != null) { return invokeFunctionNode.execute(function, frame, state, arguments); - } catch (MethodDispatchLibrary.NoSuchConversionException e) { - profile.enter(); + } else { return new Stateful(state, that); } } @@ -183,29 +177,26 @@ Stateful doConvertText( Object self, Object that, Object[] arguments, - @CachedLibrary(limit = "1") MethodDispatchLibrary textDispatch, - @CachedLibrary(limit = "10") InteropLibrary interop) { + @CachedLibrary(limit = "10") InteropLibrary interop, + @Cached ConversionResolverNode conversionResolverNode) { try { String str = interop.asString(that); Text txt = Text.create(str); Function function = - textDispatch.getConversionFunction(txt, extractConstructor(self), conversion); + conversionResolverNode.expectNonNull( + txt, extractConstructor(self), Context.get(this).getBuiltins().text(), conversion); arguments[0] = txt; return invokeFunctionNode.execute(function, frame, state, arguments); } catch (UnsupportedMessageException e) { throw new IllegalStateException("Impossible, that is guaranteed to be a string."); - } catch (MethodDispatchLibrary.NoSuchConversionException e) { - throw new PanicException( - Context.get(this).getBuiltins().error().makeNoSuchConversionError(self, that, conversion), - this); } } @Specialization( guards = { - "!methods.canConvertFrom(that)", + "!methods.hasType(that)", "!interop.isString(that)", - "!methods.hasSpecialConversion(that)" + "!methods.hasSpecialDispatch(that)" }) Stateful doFallback( VirtualFrame frame, @@ -214,7 +205,7 @@ Stateful doFallback( Object self, Object that, Object[] arguments, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, + @CachedLibrary(limit = "10") TypesLibrary methods, @CachedLibrary(limit = "10") InteropLibrary interop) { throw new PanicException( Context.get(this).getBuiltins().error().makeNoSuchConversionError(self, that, conversion), diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeMethodNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeMethodNode.java index 3a99484a5acc..262a7e42f2c5 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeMethodNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeMethodNode.java @@ -1,7 +1,10 @@ package org.enso.interpreter.node.callable; import com.oracle.truffle.api.CompilerDirectives; -import com.oracle.truffle.api.dsl.*; +import com.oracle.truffle.api.dsl.Bind; +import com.oracle.truffle.api.dsl.Cached; +import com.oracle.truffle.api.dsl.ImportStatic; +import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.UnsupportedMessageException; @@ -11,13 +14,10 @@ import com.oracle.truffle.api.profiles.BranchProfile; import com.oracle.truffle.api.profiles.ConditionProfile; import com.oracle.truffle.api.source.SourceSection; - -import java.util.UUID; -import java.util.concurrent.locks.Lock; - import org.enso.interpreter.node.BaseNode; import org.enso.interpreter.node.callable.dispatch.InvokeFunctionNode; -import org.enso.interpreter.node.callable.resolver.*; +import org.enso.interpreter.node.callable.resolver.HostMethodCallNode; +import org.enso.interpreter.node.callable.resolver.MethodResolverNode; import org.enso.interpreter.node.callable.thunk.ThunkExecutorNode; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.UnresolvedSymbol; @@ -27,9 +27,12 @@ import org.enso.interpreter.runtime.data.EnsoDate; import org.enso.interpreter.runtime.data.text.Text; import org.enso.interpreter.runtime.error.*; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import org.enso.interpreter.runtime.state.Stateful; +import java.util.UUID; +import java.util.concurrent.locks.Lock; + @ImportStatic({HostMethodCallNode.PolyglotCallType.class, HostMethodCallNode.class}) public abstract class InvokeMethodNode extends BaseNode { private @Child InvokeFunctionNode invokeFunctionNode; @@ -78,21 +81,17 @@ public void setTailStatus(TailStatus tailStatus) { public abstract Stateful execute( VirtualFrame frame, Object state, UnresolvedSymbol symbol, Object self, Object[] arguments); - @Specialization(guards = "dispatch.hasFunctionalDispatch(self)") + @Specialization(guards = {"dispatch.hasType(self)", "!dispatch.hasSpecialDispatch(self)"}) Stateful doFunctionalDispatch( VirtualFrame frame, Object state, UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit = "10") MethodDispatchLibrary dispatch) { - try { - Function function = dispatch.getFunctionalDispatch(self, symbol); - return invokeFunctionNode.execute(function, frame, state, arguments); - } catch (MethodDispatchLibrary.NoSuchMethodException e) { - throw new PanicException( - Context.get(this).getBuiltins().error().makeNoSuchMethodError(self, symbol), this); - } + @CachedLibrary(limit = "10") TypesLibrary dispatch, + @Cached MethodResolverNode methodResolverNode) { + Function function = methodResolverNode.expectNonNull(self, dispatch.getType(self), symbol); + return invokeFunctionNode.execute(function, frame, state, arguments); } @Specialization @@ -102,8 +101,9 @@ Stateful doDataflowError( UnresolvedSymbol symbol, DataflowError self, Object[] arguments, - @Cached DataflowErrorResolverNode dataflowErrorResolverNode) { - Function function = dataflowErrorResolverNode.execute(symbol, self); + @Cached MethodResolverNode methodResolverNode) { + Function function = + methodResolverNode.execute(Context.get(this).getBuiltins().dataflowError(), symbol); if (errorReceiverProfile.profile(function == null)) { return new Stateful(state, self); } else { @@ -159,7 +159,7 @@ Stateful doWarning( @ExplodeLoop @Specialization( guards = { - "!methods.hasFunctionalDispatch(self)", + "!methods.hasType(self)", "!methods.hasSpecialDispatch(self)", "polyglotCallType.isInteropLibrary()", }) @@ -169,7 +169,7 @@ Stateful doPolyglot( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, + @CachedLibrary(limit = "10") TypesLibrary methods, @CachedLibrary(limit = "10") InteropLibrary interop, @Bind("getPolyglotCallType(self, symbol.getName(), interop)") HostMethodCallNode.PolyglotCallType polyglotCallType, @@ -206,8 +206,8 @@ Stateful doPolyglot( @Specialization( guards = { - "!methods.hasFunctionalDispatch(self)", - "!methods.hasSpecialDispatch(self)", + "!types.hasType(self)", + "!types.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == CONVERT_TO_TEXT" }) Stateful doConvertText( @@ -216,26 +216,25 @@ Stateful doConvertText( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, - @CachedLibrary(limit = "1") MethodDispatchLibrary textDispatch, - @CachedLibrary(limit = "10") InteropLibrary interop) { + @CachedLibrary(limit = "10") InteropLibrary interop, + @CachedLibrary(limit = "10") TypesLibrary types, + @Cached MethodResolverNode methodResolverNode) { try { - String str = interop.asString(self); - Text txt = Text.create(str); - Function function = textDispatch.getFunctionalDispatch(txt, symbol); - arguments[0] = txt; + var str = interop.asString(self); + var text = Text.create(str); + var ctx = Context.get(this); + var textType = ctx.getBuiltins().text(); + var function = methodResolverNode.expectNonNull(text, textType, symbol); + arguments[0] = text; return invokeFunctionNode.execute(function, frame, state, arguments); } catch (UnsupportedMessageException e) { throw new IllegalStateException("Impossible, self is guaranteed to be a string."); - } catch (MethodDispatchLibrary.NoSuchMethodException e) { - throw new PanicException( - Context.get(this).getBuiltins().error().makeNoSuchMethodError(self, symbol), this); } } @Specialization( guards = { - "!methods.hasFunctionalDispatch(self)", + "!methods.hasType(self)", "!methods.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == CONVERT_TO_DATE" }) @@ -245,24 +244,25 @@ Stateful doConvertDate( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, - @CachedLibrary(limit = "1") MethodDispatchLibrary dateDispatch, - @CachedLibrary(limit = "10") InteropLibrary interop) { + @CachedLibrary(limit = "10") InteropLibrary interop, + @CachedLibrary(limit = "10") TypesLibrary methods, + @Cached MethodResolverNode methodResolverNode) { var ctx = Context.get(this); try { var hostLocalDate = interop.asDate(self); var date = new EnsoDate(hostLocalDate); - Function function = dateDispatch.getFunctionalDispatch(date, symbol); + Function function = methodResolverNode.expectNonNull(date, ctx.getBuiltins().date(), symbol); + arguments[0] = date; return invokeFunctionNode.execute(function, frame, state, arguments); - } catch (MethodDispatchLibrary.NoSuchMethodException | UnsupportedMessageException e) { + } catch (UnsupportedMessageException e) { throw new PanicException(ctx.getBuiltins().error().makeNoSuchMethodError(self, symbol), this); } } @Specialization( guards = { - "!methods.hasFunctionalDispatch(self)", + "!methods.hasType(self)", "!methods.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == NOT_SUPPORTED" }) @@ -272,10 +272,11 @@ Stateful doFallback( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, + @CachedLibrary(limit = "10") TypesLibrary methods, @CachedLibrary(limit = "10") InteropLibrary interop, - @Cached AnyResolverNode anyResolverNode) { - Function function = anyResolverNode.execute(symbol, self); + @Cached MethodResolverNode anyResolverNode) { + var ctx = Context.get(this); + Function function = anyResolverNode.expectNonNull(self, ctx.getBuiltins().any(), symbol); return invokeFunctionNode.execute(function, frame, state, arguments); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/AnyResolverNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/AnyResolverNode.java deleted file mode 100644 index cde777bafdc3..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/AnyResolverNode.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.enso.interpreter.node.callable.resolver; - -import com.oracle.truffle.api.dsl.*; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.function.Function; - -@GenerateUncached -@ReportPolymorphism -public abstract class AnyResolverNode extends BaseResolverNode { - - public abstract Function execute(UnresolvedSymbol symbol, Object self); - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - Function resolveCached( - UnresolvedSymbol symbol, - Object self, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("resolveMethodOnAny(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - Function resolve(UnresolvedSymbol symbol, Object self) { - return throwIfNull(resolveMethodOnAny(symbol), self, symbol); - } -} 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 deleted file mode 100644 index 4fc9c1a836ab..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/BaseResolverNode.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.enso.interpreter.node.callable.resolver; - -import com.oracle.truffle.api.CompilerDirectives; -import com.oracle.truffle.api.nodes.Node; -import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.function.Function; -import org.enso.interpreter.runtime.error.PanicException; - -public class BaseResolverNode extends Node { - protected static final int CACHE_SIZE = 10; - - protected Context getContext() { - return Context.get(this); - } - - protected Function throwIfNull(Function function, Object self, UnresolvedSymbol sym) { - if (function == null) { - CompilerDirectives.transferToInterpreter(); - throw new PanicException( - getContext().getBuiltins().error().makeNoSuchMethodError(self, sym), this); - } - return function; - } - - @CompilerDirectives.TruffleBoundary - Function resolveMethodOnError(UnresolvedSymbol symbol) { - return symbol.resolveFor(getContext().getBuiltins().dataflowError()); - } - - @CompilerDirectives.TruffleBoundary - Function resolveMethodOnAny(UnresolvedSymbol symbol) { - return symbol.resolveFor(getContext().getBuiltins().any()); - } -} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/ConversionResolverNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/ConversionResolverNode.java new file mode 100644 index 000000000000..3af29b5f1c52 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/ConversionResolverNode.java @@ -0,0 +1,66 @@ +package org.enso.interpreter.node.callable.resolver; + +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.dsl.Cached; +import com.oracle.truffle.api.dsl.GenerateUncached; +import com.oracle.truffle.api.dsl.ReportPolymorphism; +import com.oracle.truffle.api.dsl.Specialization; +import com.oracle.truffle.api.nodes.Node; +import org.enso.interpreter.runtime.Context; +import org.enso.interpreter.runtime.callable.UnresolvedConversion; +import org.enso.interpreter.runtime.callable.UnresolvedSymbol; +import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; +import org.enso.interpreter.runtime.error.PanicException; + +@GenerateUncached +@ReportPolymorphism +public abstract class ConversionResolverNode extends Node { + static final int CACHE_SIZE = 10; + + Context getContext() { + return Context.get(this); + } + + public abstract Function execute(Type target, Type self, UnresolvedConversion conversion); + + public Function expectNonNull( + Object self, Type target, Type type, UnresolvedConversion conversion) { + var result = execute(target, type, conversion); + if (result == null) { + throw new PanicException( + Context.get(this) + .getBuiltins() + .error() + .makeNoSuchConversionError(target, self, conversion), + this); + } + return result; + } + + @Specialization( + guards = { + "!getContext().isInlineCachingDisabled()", + "cachedConversion == conversion", + "cachedSelfType == selfType", + "cachedTarget == target" + }, + limit = "CACHE_SIZE") + Function resolveCached( + Type target, + Type selfType, + UnresolvedConversion conversion, + @Cached("conversion") UnresolvedConversion cachedConversion, + @Cached("selfType") Type cachedSelfType, + @Cached("target") Type cachedTarget, + @Cached("resolveUncached(cachedTarget, cachedSelfType, cachedConversion)") + Function function) { + return function; + } + + @Specialization(replaces = "resolveCached") + @CompilerDirectives.TruffleBoundary + Function resolveUncached(Type target, Type self, UnresolvedConversion conversion) { + return conversion.resolveFor(target, self); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/DataflowErrorResolverNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/DataflowErrorResolverNode.java deleted file mode 100644 index 86b4965a2395..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/DataflowErrorResolverNode.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.enso.interpreter.node.callable.resolver; - -import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.GenerateUncached; -import com.oracle.truffle.api.dsl.ReportPolymorphism; -import com.oracle.truffle.api.dsl.Specialization; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.function.Function; -import org.enso.interpreter.runtime.error.DataflowError; - -@GenerateUncached -@ReportPolymorphism -public abstract class DataflowErrorResolverNode extends BaseResolverNode { - - public abstract Function execute(UnresolvedSymbol symbol, DataflowError self); - - @Specialization( - guards = {"!getContext().isInlineCachingDisabled()", "cachedSymbol == symbol"}, - limit = "CACHE_SIZE") - Function resolveCached( - UnresolvedSymbol symbol, - DataflowError self, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("resolveMethodOnError(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - Function resolve(UnresolvedSymbol symbol, DataflowError self) { - return resolveMethodOnError(symbol); - } -} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/MethodResolverNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/MethodResolverNode.java new file mode 100644 index 000000000000..5d23416738b3 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/resolver/MethodResolverNode.java @@ -0,0 +1,60 @@ +package org.enso.interpreter.node.callable.resolver; + +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.dsl.Cached; +import com.oracle.truffle.api.dsl.GenerateUncached; +import com.oracle.truffle.api.dsl.ReportPolymorphism; +import com.oracle.truffle.api.dsl.Specialization; +import com.oracle.truffle.api.nodes.Node; +import org.checkerframework.checker.units.qual.C; +import org.enso.interpreter.runtime.Context; +import org.enso.interpreter.runtime.builtin.Number; +import org.enso.interpreter.runtime.callable.UnresolvedSymbol; +import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; +import org.enso.interpreter.runtime.error.PanicException; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; +import org.enso.interpreter.runtime.number.EnsoBigInteger; + +@GenerateUncached +@ReportPolymorphism +public abstract class MethodResolverNode extends Node { + protected static final int CACHE_SIZE = 10; + + Context getContext() { + return Context.get(this); + } + + public abstract Function execute(Type type, UnresolvedSymbol symbol); + + public Function expectNonNull(Object self, Type type, UnresolvedSymbol symbol) { + var result = execute(type, symbol); + if (result == null) { + throw new PanicException( + Context.get(this).getBuiltins().error().makeNoSuchMethodError(self, symbol), this); + } + return result; + } + + @Specialization( + guards = { + "!getContext().isInlineCachingDisabled()", + "cachedSymbol == symbol", + "cachedType == type" + }, + limit = "CACHE_SIZE") + Function resolveCached( + Type type, + UnresolvedSymbol symbol, + @Cached("symbol") UnresolvedSymbol cachedSymbol, + @Cached("type") Type cachedType, + @Cached("resolveUncached(cachedType, cachedSymbol)") Function function) { + return function; + } + + @Specialization(replaces = "resolveCached") + @CompilerDirectives.TruffleBoundary + Function resolveUncached(Type self, UnresolvedSymbol symbol) { + return symbol.resolveFor(self); + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java index 604047286b7a..1d9f3bcfff57 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java @@ -2,7 +2,6 @@ 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.data.Type; import static com.oracle.truffle.api.CompilerDirectives.transferToInterpreterAndInvalidate; 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 caf988a1ce97..11edbc171770 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Builtins.java @@ -1,17 +1,6 @@ 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.InvocationTargetException; -import java.lang.reflect.Method; -import java.nio.charset.StandardCharsets; -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; @@ -19,8 +8,8 @@ import org.enso.interpreter.Language; import org.enso.interpreter.dsl.TypeProcessor; import org.enso.interpreter.dsl.model.MethodDefinition; -import org.enso.interpreter.node.expression.builtin.*; import org.enso.interpreter.node.expression.builtin.Boolean; +import org.enso.interpreter.node.expression.builtin.*; import org.enso.interpreter.node.expression.builtin.debug.Debug; import org.enso.interpreter.node.expression.builtin.error.CaughtPanic; import org.enso.interpreter.node.expression.builtin.error.Warning; @@ -39,6 +28,16 @@ import org.enso.interpreter.runtime.type.TypesFromProxy; import org.enso.pkg.QualifiedName; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.stream.Collectors; + /** Container class for static predefined atoms, methods, and their containing scope. */ public class Builtins { public static final String PACKAGE_NAME = "Builtins"; @@ -59,7 +58,7 @@ public static class Debug { private final Error error; private final Module module; private final ModuleScope scope; - public final Number number; + private final Number number; private final Boolean bool; private final Ordering ordering; private final System system; 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 158cd3a87a79..dd762f25b903 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,52 +1,61 @@ package org.enso.interpreter.runtime.builtin; +import org.enso.interpreter.node.expression.builtin.Builtin; 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.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.data.Type; /** A container for all number-related builtins. */ public class Number { - private final BuiltinType smallInteger; - private final BuiltinType bigInteger; - private final BuiltinType integer; - private final BuiltinType number; - private final BuiltinType decimal; + private final Builtin smallInteger; + private final Builtin bigInteger; + private final Builtin integer; + private final Builtin number; + private final Builtin decimal; /** Creates builders for number Atom Constructors. */ public Number(Builtins builtins) { - smallInteger = new BuiltinType(builtins, SmallInteger.class); - bigInteger = new BuiltinType(builtins, BigInteger.class); - integer = new BuiltinType(builtins, Integer.class); + smallInteger = builtins.getBuiltinType(SmallInteger.class); + bigInteger = builtins.getBuiltinType(BigInteger.class); + integer = builtins.getBuiltinType(Integer.class); number = - new BuiltinType( - builtins, org.enso.interpreter.node.expression.builtin.number.Number.class); - decimal = new BuiltinType(builtins, Decimal.class); + builtins.getBuiltinType(org.enso.interpreter.node.expression.builtin.number.Number.class); + decimal = builtins.getBuiltinType(Decimal.class); } - /** @return the Int64 atom constructor. */ + /** + * @return the Int64 atom constructor. + */ public Type getSmallInteger() { return smallInteger.getType(); } - /** @return the Big_Integer atom constructor. */ + /** + * @return the Big_Integer atom constructor. + */ public Type getBigInteger() { return bigInteger.getType(); } - /** @return the Integer atom constructor */ + /** + * @return the Integer atom constructor + */ public Type getInteger() { return integer.getType(); } - /** @return the Number atom constructor */ + /** + * @return the Number atom constructor + */ public Type getNumber() { return number.getType(); } - /** @return the Decimal atom constructor */ + /** + * @return the Decimal atom constructor + */ public Type getDecimal() { return decimal.getType(); } 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 330835c968fb..c0747016eec7 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 @@ -17,14 +17,14 @@ import org.enso.interpreter.runtime.data.Array; import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.data.text.Text; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import org.enso.interpreter.runtime.type.TypesGen; import java.util.Map; /** A runtime representation of an Atom in Enso. */ @ExportLibrary(InteropLibrary.class) -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) public final class Atom implements TruffleObject { final AtomConstructor constructor; private final Object[] fields; @@ -199,99 +199,12 @@ boolean isNull() { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(Type type, UnresolvedSymbol symbol) { - return symbol.resolveFor(type); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "self.constructor.getType() == cachedType", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Atom self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("self.constructor.getType()") Type cachedType, - @Cached("doResolve(cachedType, cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Atom self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(self.constructor.getType(), symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } - } - - @ExportMessage - boolean canConvertFrom() { - return true; - } - - @ExportMessage - static class GetConversionFunction { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve( - Type type, Type target, UnresolvedConversion conversion) { - return conversion.resolveFor(target, type); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedConversion == conversion", - "cachedTarget == target", - "self.constructor.getType() == cachedType", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Atom self, - Type target, - UnresolvedConversion conversion, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("self.constructor.getType()") Type cachedType, - @Cached("target") Type cachedTarget, - @Cached("doResolve(cachedType, cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Atom self, Type target, UnresolvedConversion conversion) - throws MethodDispatchLibrary.NoSuchConversionException { - Function function = doResolve(self.constructor.getType(), target, conversion); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchConversionException(); - } - return function; - } + Type getType() { + return getConstructor().getType(); } } 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 fa4cd2b079fe..8d0db57e1d1f 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,6 +1,5 @@ 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; @@ -9,6 +8,7 @@ import com.oracle.truffle.api.interop.ArityException; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.TruffleObject; +import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.nodes.RootNode; @@ -26,16 +26,14 @@ import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.callable.function.FunctionSchema; import org.enso.interpreter.runtime.data.Type; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import org.enso.interpreter.runtime.scope.LocalScope; 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) +@ExportLibrary(TypesLibrary.class) public final class AtomConstructor implements TruffleObject { private final String name; @@ -291,100 +289,18 @@ public ArgumentDefinition[] getFields() { return constructorFunction.getSchema().getArgumentInfos(); } + @ExportMessage.Ignore public Type getType() { return type; } @ExportMessage - boolean hasFunctionalDispatch() { - return true; - } - - @ExportMessage - static class GetFunctionalDispatch { - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(UnresolvedSymbol symbol) { - return symbol.resolveFor(getContext().getBuiltins().function()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - AtomConstructor self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("doResolve(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(AtomConstructor self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } - } - - @ExportMessage - boolean canConvertFrom() { + boolean hasType() { return true; } @ExportMessage - static class GetConversionFunction { - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(Type self, Type target, UnresolvedConversion conversion) { - return conversion.resolveFor(target, self); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedConversion == conversion", - "cachedTarget == target", - "self.getType() == cachedType", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - AtomConstructor self, - Type target, - UnresolvedConversion conversion, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") Type cachedTarget, - @Cached("self.getType()") Type cachedType, - @Cached("doResolve(cachedType, cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(AtomConstructor self, Type target, UnresolvedConversion conversion) - throws MethodDispatchLibrary.NoSuchConversionException { - Function function = doResolve(self.type, target, conversion); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchConversionException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().function(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/Function.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/Function.java index a42005bbf67a..bac5f04dfbfa 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/Function.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/Function.java @@ -7,11 +7,8 @@ import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.frame.MaterializedFrame; -import com.oracle.truffle.api.interop.ArityException; -import com.oracle.truffle.api.interop.InteropLibrary; -import com.oracle.truffle.api.interop.TruffleObject; -import com.oracle.truffle.api.interop.UnknownIdentifierException; -import com.oracle.truffle.api.interop.UnsupportedTypeException; +import com.oracle.truffle.api.interop.*; +import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.nodes.RootNode; @@ -21,20 +18,17 @@ import org.enso.interpreter.node.expression.builtin.BuiltinRootNode; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.CallerInfo; -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.AtomConstructor; +import org.enso.interpreter.runtime.data.Array; import org.enso.interpreter.runtime.data.Type; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import org.enso.interpreter.runtime.state.data.EmptyMap; -import org.enso.interpreter.runtime.data.Array; import org.enso.interpreter.runtime.type.Types; import org.enso.polyglot.MethodNames; /** A runtime representation of a function object in Enso. */ @ExportLibrary(InteropLibrary.class) -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) public final class Function implements TruffleObject { private final RootCallTarget callTarget; private final MaterializedFrame scope; @@ -370,98 +364,13 @@ public static MaterializedFrame getLocalScope(Object[] arguments) { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(UnresolvedSymbol symbol) { - Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().function()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Function self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("doResolve(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Function self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } - } - - @ExportMessage - boolean canConvertFrom() { - return true; - } - - @ExportMessage - static class GetConversionFunction { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(Type target, UnresolvedConversion conversion) { - Context context = getContext(); - return conversion.resolveFor(target, context.getBuiltins().function()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedTarget == target", - "cachedConversion == conversion", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Function self, - Type target, - UnresolvedConversion conversion, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") Type cachedTarget, - @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Function self, Type target, UnresolvedConversion conversion) - throws MethodDispatchLibrary.NoSuchConversionException { - Function function = doResolve(target, conversion); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchConversionException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().function(); } public boolean isThunk() { 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 5476d2dbec1a..7ca5cd84072f 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 @@ -1,27 +1,22 @@ package org.enso.interpreter.runtime.data; -import com.oracle.truffle.api.CompilerDirectives; -import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.InvalidArrayIndexException; import com.oracle.truffle.api.interop.TruffleObject; +import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import org.enso.interpreter.dsl.AcceptsError; import org.enso.interpreter.dsl.Builtin; import org.enso.interpreter.node.expression.builtin.error.InvalidArrayIndexError; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.callable.UnresolvedConversion; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.function.Function; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import java.util.Arrays; /** A primitive boxed array type for use in the runtime. */ @ExportLibrary(InteropLibrary.class) -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) @Builtin(pkg = "mutable", stdlibName = "Standard.Base.Data.Array.Array") public class Array implements TruffleObject { public static class InvalidIndexException extends RuntimeException { @@ -186,96 +181,12 @@ public String toString() { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(UnresolvedSymbol symbol) { - Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().array()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Array self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("doResolve(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Array self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } - } - - @ExportMessage - static boolean canConvertFrom(Array receiver) { - return true; - } - - @ExportMessage - static class GetConversionFunction { - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(Type target, UnresolvedConversion conversion) { - Context context = getContext(); - return conversion.resolveFor(target, context.getBuiltins().array()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedConversion == conversion", - "cachedTarget == target", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Array self, - Type target, - UnresolvedConversion conversion, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") Type cachedTarget, - @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Array self, Type target, UnresolvedConversion conversion) - throws MethodDispatchLibrary.NoSuchConversionException { - Function function = doResolve(target, conversion); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchConversionException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().array(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDate.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDate.java index 205505282f90..f2ac5c7c211c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDate.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDate.java @@ -1,29 +1,23 @@ package org.enso.interpreter.runtime.data; -import com.oracle.truffle.api.CompilerDirectives; -import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; +import org.enso.interpreter.dsl.Builtin; +import org.enso.interpreter.node.expression.builtin.error.PolyglotError; +import org.enso.interpreter.runtime.Context; +import org.enso.interpreter.runtime.data.text.Text; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import java.time.DateTimeException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; -import org.enso.interpreter.dsl.Builtin; -import org.enso.interpreter.node.expression.builtin.error.PolyglotError; -import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.function.Function; -import org.enso.interpreter.runtime.data.text.Text; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; - @ExportLibrary(InteropLibrary.class) -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) @Builtin(pkg = "date", name = "Date") public final class EnsoDate implements TruffleObject { private final LocalDate date; @@ -82,40 +76,13 @@ LocalDate asDate() { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - @CompilerDirectives.TruffleBoundary - static Function doResolve(InteropLibrary my, UnresolvedSymbol symbol) { - Context context = Context.get(my); - return symbol.resolveFor(context.getBuiltins().date()); - } - - @Specialization( - guards = {"cachedSymbol == symbol", "function != null"}, - limit = "3") - static Function resolveCached( - EnsoDate self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @CachedLibrary("self") InteropLibrary mySelf, - @Cached("doResolve(mySelf, cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve( - EnsoDate self, UnresolvedSymbol symbol, @CachedLibrary("self") InteropLibrary mySelf) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(mySelf, symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().date(); } @ExportMessage diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoFile.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoFile.java index 6ffa9fbee246..c2f55f2df645 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoFile.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoFile.java @@ -1,18 +1,14 @@ package org.enso.interpreter.runtime.data; -import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.TruffleFile; -import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.TruffleObject; +import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import org.enso.interpreter.dsl.Builtin; import org.enso.interpreter.node.expression.builtin.error.PolyglotError; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.function.Function; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import java.io.IOException; import java.io.InputStream; @@ -31,7 +27,7 @@ * A wrapper for {@link TruffleFile} objects exposed to the language. For methods documentation * please refer to {@link TruffleFile}. */ -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) @Builtin(pkg = "io", name = "File", stdlibName = "Standard.Base.System.File.File") public class EnsoFile implements TruffleObject { private final TruffleFile truffleFile; @@ -231,48 +227,12 @@ public String toString() { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(UnresolvedSymbol symbol) { - Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().file()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - EnsoFile self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("doResolve(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(EnsoFile self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().file(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/ManagedResource.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/ManagedResource.java index 13c3bbbd4e3c..2f6a92304860 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/ManagedResource.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/ManagedResource.java @@ -1,21 +1,18 @@ package org.enso.interpreter.runtime.data; -import com.oracle.truffle.api.CompilerDirectives; -import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.TruffleObject; +import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import org.enso.interpreter.dsl.Builtin; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; import org.enso.interpreter.runtime.callable.function.Function; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import java.lang.ref.PhantomReference; /** A runtime representation of a managed resource. */ -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) @Builtin(pkg = "resource", stdlibName = "Standard.Base.Runtime.Resource.Managed_Resource") public class ManagedResource implements TruffleObject { private final Object resource; @@ -81,48 +78,12 @@ public void close(Context context) { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(UnresolvedSymbol symbol) { - Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().managedResource()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - ManagedResource self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("doResolve(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(ManagedResource self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().managedResource(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Ref.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Ref.java index f782cc01ab74..7ca86fbfc889 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Ref.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Ref.java @@ -1,19 +1,15 @@ package org.enso.interpreter.runtime.data; -import com.oracle.truffle.api.CompilerDirectives; -import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.TruffleObject; +import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import org.enso.interpreter.dsl.Builtin; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.function.Function; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; /** A mutable reference type. */ -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) @Builtin(pkg = "mutable", stdlibName = "Standard.Base.Data.Ref.Ref") public class Ref implements TruffleObject { private volatile Object value; @@ -28,7 +24,9 @@ public Ref(Object value) { this.value = value; } - /** @return the current value of the reference. */ + /** + * @return the current value of the reference. + */ @Builtin.Method(name = "get", description = "Gets the value stored in the reference") public Object getValue() { return value; @@ -47,48 +45,12 @@ public Object setValue(Object value) { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(UnresolvedSymbol symbol) { - Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().ref()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Ref self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("doResolve(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Ref self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().ref(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index a5b7949b126f..7bc2d08f8e6e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -10,19 +10,16 @@ import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; -import com.oracle.truffle.api.nodes.RootNode; import org.enso.interpreter.node.expression.atom.ConstantNode; import org.enso.interpreter.node.expression.atom.GetFieldNode; -import org.enso.interpreter.node.expression.atom.QualifiedAccessorNode; import org.enso.interpreter.runtime.Context; 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.callable.function.Function; import org.enso.interpreter.runtime.callable.function.FunctionSchema; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.pkg.QualifiedName; @@ -30,7 +27,7 @@ import java.util.List; import java.util.Map; -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) @ExportLibrary(InteropLibrary.class) public class Type implements TruffleObject { private final String name; @@ -122,99 +119,14 @@ public void generateGetters(List constructors) { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(Type type, UnresolvedSymbol symbol) { - return symbol.resolveFor(type); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "self == cachedType", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Type self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("self") Type cachedType, - @Cached("doResolve(cachedType, cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Type self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(self, symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } - } - - @ExportMessage - boolean canConvertFrom() { - return true; - } - - @ExportMessage - static class GetConversionFunction { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(Type type, Type target, UnresolvedConversion conversion) { - return conversion.resolveFor(target, type); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedConversion == conversion", - "cachedTarget == target", - "self == cachedType", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Type self, - Type target, - UnresolvedConversion conversion, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("self") Type cachedType, - @Cached("target") Type cachedTarget, - @Cached("doResolve(cachedType, cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Type self, Type target, UnresolvedConversion conversion) - throws MethodDispatchLibrary.NoSuchConversionException { - Function function = doResolve(self, target, conversion); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchConversionException(); - } - return function; - } + Type getType() { + // TODO[MK] make this the eigentype when implementing statics + return this; } @ExportMessage 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 50c2aae2d918..781c558b02e7 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/text/Text.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/text/Text.java @@ -1,27 +1,22 @@ package org.enso.interpreter.runtime.data.text; -import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.TruffleObject; +import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import org.enso.interpreter.node.expression.builtin.text.util.ToJavaStringNode; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.callable.UnresolvedConversion; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.Type; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** The main runtime type for Enso's Text. */ @ExportLibrary(InteropLibrary.class) -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) public class Text implements TruffleObject { private volatile Object contents; private volatile boolean isFlat; @@ -187,102 +182,12 @@ public String toString() { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(UnresolvedSymbol symbol) { - Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().text()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Text self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("doResolve(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Text self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } - } - - @ExportMessage - public static boolean canConvertFrom(Text receiver) { - return true; - } - - @ExportMessage - public static boolean hasSpecialConversion(Text receiver) { - return false; - } - - @ExportMessage - static class GetConversionFunction { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(Type target, UnresolvedConversion conversion) { - Context context = getContext(); - return conversion.resolveFor(target, context.getBuiltins().text()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedTarget == target", - "cachedConversion == conversion", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Text self, - Type target, - UnresolvedConversion conversion, - @Cached("target") Type cachedTarget, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Text self, Type target, UnresolvedConversion conversion) - throws MethodDispatchLibrary.NoSuchConversionException { - Function function = doResolve(target, conversion); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchConversionException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().text(); } } 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 1286e3fdf232..11ebdd1a93cb 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 @@ -1,9 +1,7 @@ package org.enso.interpreter.runtime.error; -import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.TruffleStackTrace; import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.exception.AbstractTruffleException; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.UnsupportedMessageException; @@ -12,11 +10,8 @@ import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.callable.UnresolvedConversion; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.Type; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; /** * A runtime object representing an arbitrary, user-created dataflow error. @@ -25,7 +20,7 @@ * they are handled. Another term used to describe these errors is "broken values". */ @ExportLibrary(InteropLibrary.class) -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) public class DataflowError extends AbstractTruffleException { private final Object payload; @@ -100,57 +95,17 @@ public String toDisplayString( } @ExportMessage - boolean hasSpecialDispatch() { + boolean hasType() { return true; } @ExportMessage - boolean hasSpecialConversion() { + boolean hasSpecialDispatch() { return true; } @ExportMessage - static class GetConversionFunction { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(Type target, UnresolvedConversion conversion) { - Context context = getContext(); - return conversion.resolveFor(target, context.getBuiltins().dataflowError()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedTarget == target", - "cachedConversion == conversion", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - DataflowError self, - Type target, - UnresolvedConversion conversion, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") Type cachedTarget, - @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve( - DataflowError self, Type target, UnresolvedConversion conversion) - throws MethodDispatchLibrary.NoSuchConversionException { - Function function = doResolve(target, conversion); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchConversionException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().dataflowError(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/PanicSentinel.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/PanicSentinel.java index 91d9b5e872d5..4cb62bfc6698 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/PanicSentinel.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/PanicSentinel.java @@ -4,7 +4,7 @@ import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.nodes.Node; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; /** * A sentinel value used to trace the propagation of panics through the program. @@ -12,7 +12,7 @@ *

This tracing is enabled by the active intervention of the runtime instrumentation, and does * not function in textual mode. */ -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) public class PanicSentinel extends AbstractTruffleException { final PanicException panic; @@ -45,9 +45,4 @@ public String getMessage() { boolean hasSpecialDispatch() { return true; } - - @ExportMessage - boolean hasSpecialConversion() { - return true; - } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/Warning.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/Warning.java index 76a15bea3e2f..e2e2ad80a6b8 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/Warning.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/Warning.java @@ -1,11 +1,10 @@ package org.enso.interpreter.runtime.error; -import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.interop.UnsupportedMessageException; +import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.nodes.Node; @@ -13,17 +12,16 @@ import com.oracle.truffle.api.source.SourceSection; import org.enso.interpreter.dsl.Builtin; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.Array; import org.enso.interpreter.runtime.data.ArrayRope; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.data.Type; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import java.util.Arrays; import java.util.Comparator; @Builtin(pkg = "error", stdlibName = "Standard.Base.Warning.Warning") -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) public class Warning implements TruffleObject { private final Object value; private final Object origin; @@ -174,48 +172,12 @@ public Warning reassign(Node location) { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(UnresolvedSymbol symbol) { - Context context = getContext(); - return symbol.resolveFor(context.getBuiltins().warning()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Warning self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("doResolve(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Warning self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().warning(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/WithWarnings.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/WithWarnings.java index 36f2b4053946..8a24a107b2bb 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/WithWarnings.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/error/WithWarnings.java @@ -5,9 +5,9 @@ import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.runtime.data.ArrayRope; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) public class WithWarnings implements TruffleObject { private final ArrayRope warnings; private final Object value; 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 20ab2e4670ac..9b2b558dd77a 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 @@ -1,120 +1,21 @@ package org.enso.interpreter.runtime.library.dispatch; -import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; +import com.oracle.truffle.api.library.CachedLibrary; 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.Builtins; -import org.enso.interpreter.runtime.callable.UnresolvedConversion; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.Type; -@ExportLibrary(value = MethodDispatchLibrary.class, receiverType = Boolean.class) +@ExportLibrary(value = TypesLibrary.class, receiverType = Boolean.class) public class DefaultBooleanExports { - - static final int CACHE_SIZE = 10; - - static boolean unbox(Boolean b) { - return b; - } - - @ExportMessage - static boolean hasFunctionalDispatch(Boolean receiver) { - return true; - } - - @ExportMessage - static class GetFunctionalDispatch { - @CompilerDirectives.TruffleBoundary - static Function resolveMethodOnBool(UnresolvedSymbol symbol) { - Context context = getContext(); - Builtins builtins = context.getBuiltins(); - return symbol.resolveFor(builtins.bool().getType()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Boolean self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("resolveMethodOnBool(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = {"resolveCached"}) - static Function resolve(Boolean self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = resolveMethodOnBool(symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } - } - @ExportMessage - public static boolean canConvertFrom(Boolean receiver) { + static boolean hasType(Boolean receiver) { return true; } @ExportMessage - public static boolean hasSpecialConversion(Boolean receiver) { - return false; - } - - @ExportMessage - static class GetConversionFunction { - @CompilerDirectives.TruffleBoundary - static Function resolveMethodOnBool(Type target, UnresolvedConversion conversion) { - Context context = Context.get(null); - Builtins builtins = context.getBuiltins(); - return conversion.resolveFor(target, builtins.bool().getType()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedConversion == conversion", - "cachedTarget == target", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Boolean self, - Type target, - UnresolvedConversion conversion, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") Type cachedTarget, - @Cached("resolveMethodOnBool(cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization(replaces = {"resolveCached"}) - static Function resolve(Boolean self, Type target, UnresolvedConversion symbol) - throws MethodDispatchLibrary.NoSuchConversionException { - Function function = resolveMethodOnBool(target, symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchConversionException(); - } - return function; - } + static Type getType(Boolean receiver, @CachedLibrary("receiver") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().bool().getType(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultDoubleExports.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultDoubleExports.java index 0df0904c78cb..475c95bbda45 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultDoubleExports.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultDoubleExports.java @@ -1,117 +1,21 @@ package org.enso.interpreter.runtime.library.dispatch; -import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; +import com.oracle.truffle.api.library.CachedLibrary; 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.Number; -import org.enso.interpreter.runtime.callable.UnresolvedConversion; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.Type; -@ExportLibrary(value = MethodDispatchLibrary.class, receiverType = Double.class) +@ExportLibrary(value = TypesLibrary.class, receiverType = Double.class) public class DefaultDoubleExports { @ExportMessage - static boolean hasFunctionalDispatch(Double receiver) { + static boolean hasType(Double receiver) { return true; } @ExportMessage - static class GetFunctionalDispatch { - @CompilerDirectives.TruffleBoundary - static Function doResolve(UnresolvedSymbol symbol) { - Context context = getContext(); - Number number = context.getBuiltins().number(); - return symbol.resolveFor(number.getDecimal()); - } - - static Context getContext() { - return Context.get(null); - } - - static final int CACHE_SIZE = 10; - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Double self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("doResolve(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Double self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } - } - - @ExportMessage - public static boolean canConvertFrom(Double receiver) { - return true; - } - - @ExportMessage - public static boolean hasSpecialConversion(Double receiver) { - return false; - } - - @ExportMessage - static class GetConversionFunction { - @CompilerDirectives.TruffleBoundary - static Function doResolve(Type target, UnresolvedConversion conversion) { - Context context = getContext(); - Number number = context.getBuiltins().number(); - return conversion.resolveFor(target, number.getDecimal()); - } - - static Context getContext() { - return Context.get(null); - } - - static final int CACHE_SIZE = 10; - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedConversion == conversion", - "cachedTarget == target", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Double self, - Type target, - UnresolvedConversion conversion, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") Type cachedTarget, - @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Double self, Type target, UnresolvedConversion conversion) - throws MethodDispatchLibrary.NoSuchConversionException { - Function function = doResolve(target, conversion); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchConversionException(); - } - return function; - } + static Type getType(Double receiver, @CachedLibrary("receiver") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().number().getDecimal(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultLongExports.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultLongExports.java index a2e03a7da835..f67548c34f23 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultLongExports.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/DefaultLongExports.java @@ -1,117 +1,20 @@ package org.enso.interpreter.runtime.library.dispatch; -import com.oracle.truffle.api.CompilerDirectives; -import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; +import com.oracle.truffle.api.library.CachedLibrary; 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.Number; -import org.enso.interpreter.runtime.callable.UnresolvedConversion; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.Type; -@ExportLibrary(value = MethodDispatchLibrary.class, receiverType = Long.class) +@ExportLibrary(value = TypesLibrary.class, receiverType = Long.class) public class DefaultLongExports { @ExportMessage - static boolean hasFunctionalDispatch(Long receiver) { + static boolean hasType(Long receiver) { return true; } @ExportMessage - static class GetFunctionalDispatch { - @CompilerDirectives.TruffleBoundary - static Function doResolve(UnresolvedSymbol symbol) { - Context context = getContext(); - Number number = context.getBuiltins().number(); - return symbol.resolveFor(number.getSmallInteger()); - } - - static Context getContext() { - return Context.get(null); - } - - static final int CACHE_SIZE = 10; - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Long self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("doResolve(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Long self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } - } - - @ExportMessage - public static boolean canConvertFrom(Long receiver) { - return true; - } - - @ExportMessage - public static boolean hasSpecialConversion(Long receiver) { - return false; - } - - @ExportMessage - static class GetConversionFunction { - @CompilerDirectives.TruffleBoundary - static Function doResolve(Type target, UnresolvedConversion conversion) { - Context context = getContext(); - Number number = context.getBuiltins().number(); - return conversion.resolveFor(target, number.getSmallInteger()); - } - - static Context getContext() { - return Context.get(null); - } - - static final int CACHE_SIZE = 10; - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedConversion == conversion", - "cachedTarget == target", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - Long self, - Type target, - UnresolvedConversion conversion, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") Type cachedTarget, - @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(Long self, Type target, UnresolvedConversion conversion) - throws MethodDispatchLibrary.NoSuchConversionException { - Function function = doResolve(target, conversion); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchConversionException(); - } - return function; - } + static Type getType(Long receiver, @CachedLibrary("receiver") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().number().getSmallInteger(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/MethodDispatchLibrary.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/TypesLibrary.java similarity index 50% rename from engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/MethodDispatchLibrary.java rename to engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/TypesLibrary.java index ced33a1d4c88..cebed2a59848 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/MethodDispatchLibrary.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/TypesLibrary.java @@ -3,10 +3,6 @@ import com.oracle.truffle.api.library.GenerateLibrary; import com.oracle.truffle.api.library.Library; import com.oracle.truffle.api.library.LibraryFactory; -import org.enso.interpreter.runtime.callable.UnresolvedConversion; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.Type; /** @@ -17,14 +13,14 @@ @GenerateLibrary.DefaultExport(DefaultLongExports.class) @GenerateLibrary.DefaultExport(DefaultDoubleExports.class) @GenerateLibrary.DefaultExport(DefaultBooleanExports.class) -public abstract class MethodDispatchLibrary extends Library { +public abstract class TypesLibrary extends Library { /** * Returns a resolved library factory for this library. * * @return a library factory instance */ - public static LibraryFactory getFactory() { + public static LibraryFactory getFactory() { return FACTORY; } @@ -33,15 +29,12 @@ public static LibraryFactory getFactory() { * * @return the uncached instance of this library */ - public static MethodDispatchLibrary getUncached() { + public static TypesLibrary getUncached() { return FACTORY.getUncached(); } - /** An exception thrown when the library cannot lookup the method definition. */ - public static class NoSuchMethodException extends Exception {} - - private static final LibraryFactory FACTORY = - LibraryFactory.resolve(MethodDispatchLibrary.class); + private static final LibraryFactory FACTORY = + LibraryFactory.resolve(TypesLibrary.class); /** * Checks if the receiver supports Enso-style method dispatch @@ -49,8 +42,8 @@ public static class NoSuchMethodException extends Exception {} * @param receiver the receiver to check * @return whether the receiver supports method dispatch through this library */ - @GenerateLibrary.Abstract(ifExported = {"getFunctionalDispatch"}) - public boolean hasFunctionalDispatch(Object receiver) { + @GenerateLibrary.Abstract(ifExported = {"getType"}) + public boolean hasType(Object receiver) { return false; } @@ -73,30 +66,8 @@ public boolean hasSpecialDispatch(Object receiver) { * @return the corresponding function definition * @throws NoSuchMethodException if the function definition could not be found */ - @GenerateLibrary.Abstract(ifExported = {"hasFunctionalDispatch"}) - public Function getFunctionalDispatch(Object receiver, UnresolvedSymbol symbol) - throws NoSuchMethodException { - throw new NoSuchMethodException(); - } - - /** Conversions */ - - /** An exception thrown when the library cannot lookup the conversion definition. */ - public static class NoSuchConversionException extends Exception {} - - // @GenerateLibrary.Abstract(ifExported = {"getConversionFunction"}) - public boolean canConvertFrom(Object receiver) { - return false; - } - - public boolean hasSpecialConversion(Object receiver) { - return false; - } - - @GenerateLibrary.Abstract(ifExported = {"canConvertFrom"}) - public Function getConversionFunction( - Object receiver, Type target, UnresolvedConversion symbol) - throws MethodDispatchLibrary.NoSuchConversionException { - throw new MethodDispatchLibrary.NoSuchConversionException(); + @GenerateLibrary.Abstract(ifExported = {"hasType"}) + public Type getType(Object receiver) { + return null; } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/number/EnsoBigInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/number/EnsoBigInteger.java index a4576b295da1..1cb876530a72 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/number/EnsoBigInteger.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/number/EnsoBigInteger.java @@ -2,25 +2,20 @@ import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.TruffleObject; +import com.oracle.truffle.api.library.CachedLibrary; 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.Number; -import org.enso.interpreter.runtime.callable.UnresolvedConversion; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; -import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.Type; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import java.math.BigInteger; /** Internal wrapper for a {@link BigInteger}. */ @ExportLibrary(InteropLibrary.class) -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) public class EnsoBigInteger implements TruffleObject { private final BigInteger value; @@ -52,99 +47,12 @@ String toDisplayString(boolean allowSideEffects) { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(UnresolvedSymbol symbol) { - Context context = getContext(); - Number number = context.getBuiltins().number(); - return symbol.resolveFor(number.getBigInteger()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedSymbol == symbol", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - EnsoBigInteger self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @Cached("doResolve(cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(EnsoBigInteger self, UnresolvedSymbol symbol) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } - } - - @ExportMessage - public static boolean canConvertFrom(EnsoBigInteger receiver) { - return true; - } - - @ExportMessage - static class GetConversionFunction { - - static final int CACHE_SIZE = 10; - - @CompilerDirectives.TruffleBoundary - static Function doResolve(Type target, UnresolvedConversion conversion) { - Context context = getContext(); - Number number = context.getBuiltins().number(); - return conversion.resolveFor(target, number.getBigInteger()); - } - - static Context getContext() { - return Context.get(null); - } - - @Specialization( - guards = { - "!getContext().isInlineCachingDisabled()", - "cachedTarget == target", - "cachedConversion == conversion", - "function != null" - }, - limit = "CACHE_SIZE") - static Function resolveCached( - EnsoBigInteger self, - Type target, - UnresolvedConversion conversion, - @Cached("conversion") UnresolvedConversion cachedConversion, - @Cached("target") Type cachedTarget, - @Cached("doResolve(cachedTarget, cachedConversion)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve(EnsoBigInteger self, Type target, UnresolvedConversion conversion) - throws MethodDispatchLibrary.NoSuchConversionException { - Function function = doResolve(target, conversion); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchConversionException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().number().getBigInteger(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java index e032c12f0578..7aa0ab569c94 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/type/TypesFromProxy.java @@ -36,7 +36,7 @@ public static Type fromTypeSystem(Builtins builtins, String typeName) { case ConstantsGen.BOOLEAN: return builtins.bool().getType(); case ConstantsGen.DECIMAL: - return builtins.number.getDecimal(); + return builtins.number().getDecimal(); case ConstantsGen.ERROR: return builtins.dataflowError(); case ConstantsGen.FUNCTION: @@ -44,13 +44,13 @@ public static Type fromTypeSystem(Builtins builtins, String typeName) { case ConstantsGen.FILE: return builtins.file(); case ConstantsGen.INTEGER: - return builtins.number.getInteger(); + return builtins.number().getInteger(); case ConstantsGen.MANAGED_RESOURCE: return builtins.managedResource(); case ConstantsGen.NOTHING: return builtins.nothing(); case ConstantsGen.NUMBER: - return builtins.number.getNumber(); + return builtins.number().getNumber(); case ConstantsGen.PANIC: return builtins.panic(); case ConstantsGen.REF: From e46fbc3ca7930b357aed404efc0be4c7b7133d51 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 10 Aug 2022 13:45:13 +0200 Subject: [PATCH 038/110] fix all semantic tests --- .../builtin/UniquelyConstructibleBuiltin.java | 2 +- .../org/enso/interpreter/runtime/data/Type.java | 5 +++++ .../compiler/codegen/RuntimeStubsGenerator.scala | 8 ++++++++ .../interpreter/test/CodeIdsTestInstrument.java | 4 ++++ .../TestSubmodulesNameConflict/src/A/B.enso | 4 ++-- .../TestSubmodulesNameConflict/src/A/B/C.enso | 4 ++-- .../enso/interpreter/test/InterpreterTest.scala | 3 ++- .../test/semantic/CompileDiagnosticsTest.scala | 8 ++++---- .../test/semantic/DataflowErrorsTest.scala | 4 ++-- .../enso/interpreter/test/semantic/EvalTest.scala | 7 ++++--- .../interpreter/test/semantic/ImportsTest.scala | 4 ++-- .../interpreter/test/semantic/PanicsTest.scala | 4 ++-- .../enso/interpreter/test/semantic/TextTest.scala | 12 ++++++------ .../Standard/Base/0.0.0-dev/src/Error/Common.enso | 14 +++++++------- .../lib/Standard/Base/0.0.0-dev/src/System.enso | 3 ++- 15 files changed, 53 insertions(+), 33 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/UniquelyConstructibleBuiltin.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/UniquelyConstructibleBuiltin.java index 91ae7719245c..1a31a388666d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/UniquelyConstructibleBuiltin.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/UniquelyConstructibleBuiltin.java @@ -15,7 +15,7 @@ public final AtomConstructor getUniqueConstructor() { @Override protected final List getDeclaredConstructors() { - return List.of(new Cons("Make_" + getName(), getConstructorParamNames())); + return List.of(new Cons( getName() + "_Data", getConstructorParamNames())); } protected abstract List getConstructorParamNames(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index 7bc2d08f8e6e..1ea3742daf40 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -133,4 +133,9 @@ Type getType() { String toDisplayString(boolean allowSideEffects) { return name; } + + @Override + public String toString() { + return toDisplayString(true); + } } 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 915dfaa9f6f8..d4583c6df5ba 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 @@ -30,6 +30,14 @@ class RuntimeStubsGenerator(builtins: Builtins) { if (builtinType == null) { throw new CompilerError("Unknown @BuiltinType " + tp.name) } + if ( + Set(tp.members: _*) != Set(builtinType.getConstructors.toIndexedSeq: _*) + .map(_.getName) + ) { + throw new CompilerError( + s"Wrong constructors declared in the builtin ${tp.name}." + ) + } builtinType.getConstructors.foreach(scope.registerConstructor) scope.registerType(builtinType.getType) builtinType.getType.setShadowDefinitions(scope) diff --git a/engine/runtime/src/test/java/org/enso/interpreter/test/CodeIdsTestInstrument.java b/engine/runtime/src/test/java/org/enso/interpreter/test/CodeIdsTestInstrument.java index 4c85f44b8197..8f349ad83c3a 100644 --- a/engine/runtime/src/test/java/org/enso/interpreter/test/CodeIdsTestInstrument.java +++ b/engine/runtime/src/test/java/org/enso/interpreter/test/CodeIdsTestInstrument.java @@ -61,6 +61,10 @@ public boolean isSuccessful() { return successful; } + public String getExpectedResult() { + return expectedResult; + } + @Override public void onEnter(EventContext context, VirtualFrame frame) {} diff --git a/engine/runtime/src/test/resources/TestSubmodulesNameConflict/src/A/B.enso b/engine/runtime/src/test/resources/TestSubmodulesNameConflict/src/A/B.enso index fa8038e04e03..9e1443b4721f 100644 --- a/engine/runtime/src/test/resources/TestSubmodulesNameConflict/src/A/B.enso +++ b/engine/runtime/src/test/resources/TestSubmodulesNameConflict/src/A/B.enso @@ -1,3 +1,3 @@ type C - type C a -bar_mod_method x = C x+10 + Mk_C a +bar_mod_method x = Mk_C x+10 diff --git a/engine/runtime/src/test/resources/TestSubmodulesNameConflict/src/A/B/C.enso b/engine/runtime/src/test/resources/TestSubmodulesNameConflict/src/A/B/C.enso index cf5f2c8ffb13..a602c7ac31db 100644 --- a/engine/runtime/src/test/resources/TestSubmodulesNameConflict/src/A/B/C.enso +++ b/engine/runtime/src/test/resources/TestSubmodulesNameConflict/src/A/B/C.enso @@ -1,4 +1,4 @@ type C - type C x + Mk_C x -c_mod_method a = C 42+a +c_mod_method a = Mk_C 42+a diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/InterpreterTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/InterpreterTest.scala index d7dab83ecd94..bd3cde99f274 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/InterpreterTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/InterpreterTest.scala @@ -66,7 +66,8 @@ case class IdsInstrumenter(instrument: CodeIdsTestInstrument) { val listener = binding.getElement if (!listener.isSuccessful) { Assertions.fail( - s"Node with id ${listener.getId} does not exist or did not return the correct value." + s"Node with id ${listener.getId} does not exist or did not return the" + + s" correct value (expected ${listener.getExpectedResult}." ) } } 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 bdc23c40e04c..8e019859acd9 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 @@ -16,7 +16,7 @@ class CompileDiagnosticsTest extends InterpreterTest { | x = Panic.catch_primitive () .convert_to_dataflow_error | x.catch_primitive err-> | case err of - | Mk_Syntax_Error msg -> "Oopsie, it's a syntax error: " + msg + | Syntax_Error_Data msg -> "Oopsie, it's a syntax error: " + msg |""".stripMargin eval( code @@ -31,7 +31,7 @@ class CompileDiagnosticsTest extends InterpreterTest { | x = Panic.catch_primitive @ caught_panic-> caught_panic.payload | x.to_text |""".stripMargin - eval(code) shouldEqual "(Make_Syntax_Error 'Unrecognized token.')" + eval(code) shouldEqual "(Syntax_Error_Data 'Unrecognized token.')" } "surface redefinition errors in the language" in { @@ -44,7 +44,7 @@ class CompileDiagnosticsTest extends InterpreterTest { | |main = Panic.catch_primitive foo caught_panic->caught_panic.payload.to_text |""".stripMargin - eval(code) shouldEqual "(Make_Compile_Error 'Variable x is being redefined.')" + eval(code) shouldEqual "(Compile_Error_Data 'Variable x is being redefined.')" } "surface non-existent variable errors in the language" in { @@ -59,7 +59,7 @@ class CompileDiagnosticsTest extends InterpreterTest { |""".stripMargin eval( code - ) shouldEqual "(Make_Compile_Error 'The name `my_vra` could not be found.')" + ) shouldEqual "(Compile_Error_Data 'The name `my_vra` could not be found.')" } } } 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 1243b88d5934..59e53602478a 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 @@ -204,8 +204,8 @@ class DataflowErrorsTest extends InterpreterTest { |""".stripMargin eval(code) consumeOut shouldEqual List( - "(Error: (Make_Syntax_Error 'Unrecognized token.'))", - "(Make_Syntax_Error 'Unrecognized token.')" + "(Error: (Syntax_Error_Data 'Unrecognized token.'))", + "(Syntax_Error_Data 'Unrecognized token.')" ) } } 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 eb957cf0476d..261456cdc4a3 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 @@ -41,15 +41,16 @@ class EvalTest extends InterpreterTest { s"""import Standard.Base.Runtime.Debug |import Standard.Base.IO | - |type MyType x + |type My_Type + | Mk_My_Type x | |main = | x = 10 | Debug.eval $rawTQ - | IO.println (MyType x) + | IO.println (Mk_My_Type x) |""".stripMargin eval(code) - consumeOut shouldEqual List("(MyType 10)") + consumeOut shouldEqual List("(Mk_My_Type 10)") } "return a value usable in the caller scope" in { diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ImportsTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ImportsTest.scala index 93867018b304..d415661e0bf1 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ImportsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/semantic/ImportsTest.scala @@ -82,9 +82,9 @@ class ImportsTest extends PackageTest { evalTestProject("TestSubmodules") shouldEqual 42 val outLines = consumeOut outLines(0) shouldEqual "(Foo 10)" - outLines(1) shouldEqual "(C 52)" + outLines(1) shouldEqual "(Mk_C 52)" outLines(2) shouldEqual "20" - outLines(3) shouldEqual "(C 10)" + outLines(3) shouldEqual "(Mk_C 10)" } "Compiler" should "detect name conflicts preventing users from importing submodules" in { 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 84db3c8a84b0..02aa6f73d2a5 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 @@ -58,7 +58,7 @@ class PanicsTest extends InterpreterTest { | caught = Panic.catch_primitive (Long.parseLong "oops") .convert_to_dataflow_error | IO.println caught | cause = caught.catch_primitive e-> case e of - | Make_Polyglot_Error err -> err + | Polyglot_Error_Data err -> err | _ -> "fail" | IO.println cause | message = cause.getMessage @@ -66,7 +66,7 @@ class PanicsTest extends InterpreterTest { |""".stripMargin eval(code) consumeOut shouldEqual List( - """(Error: (Make_Polyglot_Error java.lang.NumberFormatException: For input string: "oops"))""", + """(Error: (Polyglot_Error_Data java.lang.NumberFormatException: For input string: "oops"))""", """java.lang.NumberFormatException: For input string: "oops"""", """For input string: "oops"""" ) 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 c819755087f7..d9334c9cfeea 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 @@ -113,14 +113,14 @@ class TextTest extends InterpreterTest { | |main = | IO.println (Cons Nothing Nothing).to_display_text - | IO.println (Make_Syntax_Error "foo").to_display_text - | IO.println (Make_Type_Error Nothing Nil "myvar").to_display_text - | IO.println (Make_Compile_Error "error :(").to_display_text - | IO.println (Make_Inexhaustive_Pattern_Match_Error 32).to_display_text - | IO.println (Make_Arithmetic_Error "cannot frobnicate quaternions").to_display_text + | IO.println (Syntax_Error_Data "foo").to_display_text + | IO.println (Type_Error_Data Nothing Nil "myvar").to_display_text + | IO.println (Compile_Error_Data "error :(").to_display_text + | IO.println (Inexhaustive_Pattern_Match_Error_Data 32).to_display_text + | IO.println (Arithmetic_Error_Data "cannot frobnicate quaternions").to_display_text | IO.println ((Panic.catch_primitive (1 + "foo") .convert_to_dataflow_error).catch_primitive .to_display_text) | IO.println ((Panic.catch_primitive (7 1) .convert_to_dataflow_error).catch_primitive .to_display_text) - | IO.println (Make_Arity_Error 10 10 20).to_display_text + | IO.println (Arity_Error_Data 10 10 20).to_display_text |""".stripMargin eval(code) consumeOut shouldEqual List( diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index 047b18f66700..125108336d4f 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso @@ -7,25 +7,25 @@ type Panic @Builtin_Type type Syntax_Error - Make_Syntax_Error message + Syntax_Error_Data message @Builtin_Type type Polyglot_Error - Make_Polyglot_Error cause + Polyglot_Error_Data cause @Builtin_Type type Arithmetic_Error - Make_Arithmetic_Error message + Arithmetic_Error_Data message @Builtin_Type type Type_Error - Make_Type_Error expected actual name + Type_Error_Data expected actual name @Builtin_Type type Compile_Error - Make_Compile_Error message + Compile_Error_Data message @Builtin_Type type Inexhaustive_Pattern_Match_Error - Make_Inexhaustive_Pattern_Match_Error scrutinee + Inexhaustive_Pattern_Match_Error_Data scrutinee @Builtin_Type type Arity_Error - Make_Arity_Error expected_min expected_max actual + Arity_Error_Data expected_min expected_max actual @Builtin_Type type Error diff --git a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/System.enso b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/System.enso index 5677608c602d..7c03cd6ce55c 100644 --- a/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/System.enso +++ b/test/micro-distribution/lib/Standard/Base/0.0.0-dev/src/System.enso @@ -1,4 +1,5 @@ create_process command arguments input redirect_in redirect_out redirect_err = @Builtin_Method "System.create_process" @Builtin_Type -type System_Process_Result exit_code stdout stderr +type System_Process_Result + System_Process_Result_Data exit_code stdout stderr From b4f4531498de2f022789d9108c6905dbe27f53cc Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 10 Aug 2022 15:23:54 +0200 Subject: [PATCH 039/110] start fixing stdlib --- .../0.0.0-dev/src/Data/Index_Sub_Range.enso | 12 ++-- .../0.0.0-dev/src/Data/Interval/Bound.enso | 4 +- .../Base/0.0.0-dev/src/Data/Json.enso | 12 ++-- .../0.0.0-dev/src/Data/Json/Internal.enso | 12 ++-- .../Base/0.0.0-dev/src/Data/List.enso | 4 +- .../Standard/Base/0.0.0-dev/src/Data/Map.enso | 4 +- .../0.0.0-dev/src/Data/Noise/Generator.enso | 14 ----- .../Base/0.0.0-dev/src/Data/Numbers.enso | 56 ++++++++----------- .../Base/0.0.0-dev/src/Data/Ordering.enso | 10 ++-- .../src/Data/Ordering/Natural_Order.enso | 14 ++--- .../src/Data/Ordering/Sort_Direction.enso | 4 +- .../Base/0.0.0-dev/src/Data/Pair.enso | 4 +- .../Base/0.0.0-dev/src/Data/Regression.enso | 21 +++---- .../Base/0.0.0-dev/src/Data/Statistics.enso | 26 ++++----- .../0.0.0-dev/src/Data/Text/Matching.enso | 13 ++--- .../Base/0.0.0-dev/src/Data/Text/Span.enso | 32 +++++------ .../src/Data/Text/Text_Sub_Range.enso | 10 ++-- .../0.0.0-dev/src/Error/Problem_Behavior.enso | 6 +- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 2 +- .../lib/Standard/Base/0.0.0-dev/src/Meta.enso | 12 ++-- .../0.0.0-dev/src/Network/Http/Method.enso | 18 +++--- .../src/Network/Http/Request/Body.enso | 12 ++-- .../Base/0.0.0-dev/src/Network/URI.enso | 2 +- .../src/System/File/File_Permissions.enso | 10 ++-- .../0.0.0-dev/src/System/File/Option.enso | 20 +++---- .../Base/0.0.0-dev/src/System/Platform.enso | 8 +-- .../src/System/Process/Exit_Code.enso | 4 +- .../instrument/ReplDebuggerInstrument.java | 2 +- .../scala/org/enso/compiler/Compiler.scala | 2 + .../compiler/pass/analyse/AliasAnalysis.scala | 16 ++++-- 30 files changed, 171 insertions(+), 195 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Index_Sub_Range.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Index_Sub_Range.enso index 4198d4ea5cfc..ff4c5871c086 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Index_Sub_Range.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Index_Sub_Range.enso @@ -7,16 +7,16 @@ type Index_Sub_Range Selects no items if `count` is less than or equal to 0. Selects all items if `count` is greater than the length of the input. - type First (count : Integer = 1) + First (count : Integer = 1) ## Select the last `count` characters. Selects no items if `count` is less than or equal to 0. Selects all items if `count` is greater than the length of the input. - type Last (count : Integer = 1) + Last (count : Integer = 1) ## Select elements from the start while the predicate returns `True`. - type While (predicate : (Any -> Boolean)) + While (predicate : (Any -> Boolean)) ## Selects specific indexes (starting from 0) either as an `Integer` or a `Range`. @@ -28,13 +28,13 @@ type Index_Sub_Range Only ranges with positive step and positive indices are supported. Individual integer indices can be negative which allows for indexing from the end of the collection. - type By_Index (indexes : (Integer | Range | Vector (Integer | Range)) = [0]) + By_Index (indexes : (Integer | Range | Vector (Integer | Range)) = [0]) ## Gets a random sample of entries, without repetitions. If `count` is greater than the length of the input, a random permutation of all elements from the input is selected. - type Sample (count:Integer) (seed:Integer=Random.get_default_seed) + Sample (count:Integer) (seed:Integer=Random.get_default_seed) ## Gets every Nth entry. @@ -42,4 +42,4 @@ type Index_Sub_Range - step: The step between consecutive entries that are included. - first: The first entry to include. If it is outside of bounds of the input, an error is raised. - type Every (step:Integer) (first:Integer=0) + Every (step:Integer) (first:Integer=0) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Interval/Bound.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Interval/Bound.enso index a296bb18da95..e6dbbf66fb0e 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Interval/Bound.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Interval/Bound.enso @@ -16,7 +16,7 @@ type Bound import Standard.Base.Data.Interval.Bound example_bound_inclusive = Bound.Inclusive 2 - type Inclusive n + Inclusive n ## A bound that excludes the value `n`. @@ -29,4 +29,4 @@ type Bound import Standard.Base.Data.Interval.Bound example_bound_exclusive = Bound.Exclusive 2. - type Exclusive n + Exclusive n diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso index 3f1caa03f47e..e814e3089339 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso @@ -48,34 +48,34 @@ type Json Arguments: - fields: The fields of the JSON object. - type Object fields + Object fields ## A representation of a JSON array. Arguments: - items: The items in the JSON array. - type Array items + Array items ## A representation of a JSON string. Arguments: - value: The text contained in the JSON string. - type String value + String value ## A representation of a JSON number. Arguments: - value: The number contained in the JSON number. - type Number value + Number value ## A representation of a JSON boolean. Arguments: - value: The boolean contained in a JSON boolean. - type Boolean value + Boolean value ## A representation of a JSON null. - type Null + Null ## Marshalls this JSON into an arbitrary value described by `type_descriptor`. 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 e36cff0c3fd5..3e5e67411a86 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 @@ -23,7 +23,7 @@ type Consumer - value: The value being consumed. Conforms to the `org.enso.base.json.Parser.JsonConsumer` Java interface. - type Consumer child_consumer value + Consumer_Data child_consumer value ## PRIVATE @@ -144,7 +144,7 @@ type Array_Consumer Arguments: - builder: The builder for array values. - parent: The parent consumer. - type Array_Consumer builder parent + Array_Consumer_Data builder parent ## PRIVATE @@ -175,7 +175,7 @@ type Object_Consumer - last_key: The last object key that has been seen. - map: The map representing the object. - parent: The parent consumer. - type Object_Consumer last_key map parent + Object_Consumer_Data last_key map parent ## PRIVATE @@ -217,7 +217,7 @@ mk_object_consumer : Any -> Object_Consumer mk_object_consumer parent = k = Ref.new "" m = Ref.new Map.empty - Object_Consumer k m parent + Object_Consumer_Data k m parent ## PRIVATE @@ -228,7 +228,7 @@ mk_object_consumer parent = mk_array_consumer : Any -> Array_Consumer mk_array_consumer parent = bldr = Vector.new_builder - Array_Consumer bldr parent + Array_Consumer_Data bldr parent ## PRIVATE @@ -237,7 +237,7 @@ mk_consumer : Consumer mk_consumer = child = Ref.new Nil val = Ref.new Nothing - Consumer child val + Consumer_Data child val ## PRIVATE 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 49fabb8ef7d1..f9670e2e71a4 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 @@ -18,14 +18,14 @@ import Standard.Base.Runtime.Unsafe type List ## The type that indicates the end of a cons list. - type Nil + 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 + Cons x xs ## Computes the number of elements in the list. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso index c2dc4962e3e1..35cbdb33b124 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso @@ -49,7 +49,7 @@ type Map ## PRIVATE A key-value store. This type assumes all keys are pairwise comparable, using the `<`, `>` and `==` operators. - type Tip + Tip ## PRIVATE A key-value store. This type assumes all keys are pairwise comparable, @@ -61,7 +61,7 @@ type Map - value: The value stored at this node. - left: The left subtree. - right: The right subtree. - type Bin s key value left right + Bin s key value left right ## Checks if the map is empty. 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 5926c588deee..fbe7d109ecc3 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 @@ -12,12 +12,6 @@ polyglot java import java.util.Random To be a valid generator, it must provide the `step` method as described below. type Generator - - ## PRIVATE - - The basic generator type. - type Generator - ## PRIVATE Step the generator to produce the next value.. @@ -38,14 +32,6 @@ type Generator It produces what is commonly termed "white" noise, where any value in the range has an equal chance of occurring. type Deterministic_Random - - ## A deterministic random noise generator that performs a perturbation of the - input - - It produces what is commonly termed as "white" noise, where any value in - the range has an equal chance of occurring. - type Deterministic_Random - ## Step the generator to produce the next value. Arguments: 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 index 6627749c3fb5..996e0a200d97 100644 --- 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 @@ -13,15 +13,8 @@ from Standard.Base.Error.Common import Panic,Error,Illegal_Argument_Error If a Number is expected, then the program can provide either a Decimal or an Integer in its place. +@Builtin_Type 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. @@ -364,16 +357,13 @@ type Number if self < 0 then -1 else 0 -## Decimal numbers. -type Decimal - - ## Decimal is the type of decimal numbers in Enso. +## 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 + ? 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. @@ -609,24 +599,21 @@ type Decimal 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. +## 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. + ? 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 + ? 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. @@ -993,7 +980,8 @@ type Integer ## UNSTABLE A syntax error when parsing a double. -type Parse_Error text +type Parse_Error + Parse_Error_Data text ## UNSTABLE 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 969162564424..c77ac8f0dc7f 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 @@ -18,19 +18,17 @@ from_sign sign = if sign == 0 then Equal else The result should be returned in terms of how `self` orders in comparison to `that`. So, if `self` is greater than `that`, you should return `Greater.` +@Builtin_Type type Ordering ## A representation that the first value orders as less than the second. - @Builtin_Type - type Less + Less ## A representation that the first value orders as equal to the second. - @Builtin_Type - type Equal + Equal ## A representation that the first value orders as greater than the second. - @Builtin_Type - type Greater + 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/Ordering/Natural_Order.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Natural_Order.enso index 5a1652211f3c..0ae7218ca8e4 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Natural_Order.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Natural_Order.enso @@ -42,10 +42,10 @@ compare text1 text2 case_sensitive=True = ## Find end of number and return pair of index and flag if reached end loop text next iter = new_next = iter.next - if (new_next == -1) then (Pair next True) else + if (new_next == -1) then (Pair_Data next True) else substring = Text_Utils.substring text next new_next character = Text_Utils.get_chars substring . at 0 - if (is_digit character).not then (Pair next False) else + if (is_digit character).not then (Pair_Data next False) else @Tail_Call loop text new_next iter pair = loop text next iter @@ -64,11 +64,11 @@ compare text1 text2 case_sensitive=True = prev2 - index to start of current character in text2. next2 - index to start of next character (or -1 if finished) in text2. order prev1 next1 prev2 next2 = - case (Pair (next1 == -1) (next2 == -1)) of - Pair True True -> Ordering.Equal - Pair True False -> Ordering.Less - Pair False True -> Ordering.Greater - Pair False False -> + case (Pair_Data (next1 == -1) (next2 == -1)) of + Pair_Data True True -> Ordering.Equal + Pair_Data True False -> Ordering.Less + Pair_Data False True -> Ordering.Greater + Pair_Data False False -> substring1 = Text_Utils.substring text1 prev1 next1 first_char_1 = Text_Utils.get_chars substring1 . at 0 diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Sort_Direction.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Sort_Direction.enso index 9f2cdadeb85a..5cef3451ccb4 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Sort_Direction.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Sort_Direction.enso @@ -9,7 +9,7 @@ type Sort_Direction Create an ascending order. Sort_Direction.Ascending - type Ascending + Ascending ## Elements should be sorted in descending order. @@ -17,7 +17,7 @@ type Sort_Direction Create a descending order. Sort_Direction.Descending - type Descending + Descending ## Convert into the sign of the direction to_sign : Integer diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Pair.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Pair.enso index babb574f8766..c5ea4e2c2290 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Pair.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Pair.enso @@ -10,7 +10,7 @@ type Pair Arguments: - first: The first element. - second: The second element. - type Pair first second + Pair_Data first second ## UNSTABLE @@ -22,4 +22,4 @@ type Pair (Pair 1 2).map (+1) == (Pair 2 3) map : (Any -> Any) -> Pair map self fun = - Pair (fun self.first) (fun self.second) + Pair_Data (fun self.first) (fun self.second) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Regression.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Regression.enso index 183f87ba6e98..bda9f798dc0d 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Regression.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Regression.enso @@ -5,16 +5,16 @@ polyglot java import org.enso.base.statistics.FitError type Model ## Fit a line (y = A x + B) to the data with an optional fixed intercept. - type Linear_Model (intercept:Number|Nothing=Nothing) + Linear_Model (intercept:Number|Nothing=Nothing) ## Fit a exponential line (y = A exp(B x)) to the data with an optional fixed intercept. - type Exponential_Model (intercept:Number|Nothing=Nothing) + Exponential_Model (intercept:Number|Nothing=Nothing) ## Fit a logarithmic line (y = A log x + B) to the data. - type Logarithmic_Model + Logarithmic_Model ## Fit a power series (y = A x ^ B) to the data. - type Power_Model + Power_Model ## Use Least Squares to fit a line to the data. fit_least_squares : Vector -> Vector -> Model -> Fitted_Model ! Illegal_Argument_Error | Fit_Error @@ -42,16 +42,16 @@ fit_least_squares known_xs known_ys model=Linear_Model = type Fitted_Model ## Fitted line (y = slope x + intercept). - type Fitted_Linear_Model slope:Number intercept:Number r_squared:Number=0.0 + Fitted_Linear_Model slope:Number intercept:Number r_squared:Number=0.0 ## Fitted exponential line (y = a exp(b x)). - type Fitted_Exponential_Model a:Number b:Number r_squared:Number=0.0 + Fitted_Exponential_Model a:Number b:Number r_squared:Number=0.0 ## Fitted logarithmic line (y = a log x + b). - type Fitted_Logarithmic_Model a:Number b:Number r_squared:Number=0.0 + Fitted_Logarithmic_Model a:Number b:Number r_squared:Number=0.0 ## Fitted power series (y = a x ^ b). - type Fitted_Power_Model a:Number b:Number r_squared:Number=0.0 + Fitted_Power_Model a:Number b:Number r_squared:Number=0.0 ## Display the fitted line. to_text : Text @@ -95,7 +95,8 @@ ln_series xs series_name="Values" = Arguments: - message: The error message. -type Fit_Error message +type Fit_Error + Fit_Error_Data message ## PRIVATE @@ -105,4 +106,4 @@ Fit_Error.to_display_text self = "Could not fit the model: " + self.message.to_t ## PRIVATE Fit_Error.handle_java_exception = - Panic.catch_java FitError handler=(java_exception-> Error.throw (Fit_Error java_exception.getMessage)) + Panic.catch_java FitError handler=(java_exception-> Error.throw (Fit_Error_Data java_exception.getMessage)) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Statistics.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Statistics.enso index 36a59d6a1cd8..362a39c6fafe 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Statistics.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Statistics.enso @@ -28,62 +28,62 @@ type Statistic _ -> Nothing ## Count the number of non-Nothing and non-NaN values. - type Count + Count ## The minimum value. - type Minimum + Minimum ## The maximum value. - type Maximum + Maximum ## Sum the non-Nothing and non-NaN values. - type Sum + Sum ## The sample mean of the values. - type Mean + Mean ## The variance of the values. Arguments: - population: specifies if data is a sample or the population. - type Variance (population:Boolean=False) + Variance (population:Boolean=False) ## The standard deviation of the values. Arguments: - population: specifies if data is a sample or the population. - type Standard_Deviation (population:Boolean=False) + Standard_Deviation (population:Boolean=False) ## The skewness of the values. Arguments: - population: specifies if data is a sample or the population. - type Skew (population:Boolean=False) + Skew (population:Boolean=False) ## The sample kurtosis of the values. - type Kurtosis + Kurtosis ## Calculate the Covariance between data and series. Arguments: - series: the series to compute the covariance with. - type Covariance (series:Vector) + Covariance (series:Vector) ## Calculate the Pearson Correlation between data and series. Arguments: - series: the series to compute the correlation with. - type Pearson (series:Vector) + Pearson (series:Vector) ## Calculate the Spearman Rank Correlation between data and series. Arguments: - series: the series to compute the correlation with. - type Spearman (series:Vector) + Spearman (series:Vector) ## Calculate the coefficient of determination between data and predicted series. Arguments: - predicted: the series to compute the r_squared with. - type R_Squared (predicted:Vector) + R_Squared (predicted:Vector) ## Compute a single statistic on a vector like object. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso index 51490e11dbc6..e6d166b267a5 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso @@ -25,7 +25,8 @@ type Case_Insensitive locale=Locale.default Arguments: - case_sensitive: Case Sensitive if True. Otherwise, the comparison is case insensitive using the specified locale. -type Text_Matcher (case_sensitive : (True | Case_Insensitive) = True) +type Text_Matcher + Text_Matcher_Data (case_sensitive : (True | Case_Insensitive) = True) ## Represents regex matching mode. @@ -52,7 +53,8 @@ type Text_Matcher (case_sensitive : (True | Case_Insensitive) = True) preceded by an unescaped backslash, all characters from the leftmost such `#` to the end of the line are ignored. That is to say; they act as 'comments' in the regex. -type Regex_Matcher (case_sensitive : (True | Case_Insensitive) = True) (multiline : Boolean = False) (match_ascii : Boolean = False) (dot_matches_newline : Boolean = False) (comments : Boolean = False) +type Regex_Matcher + Regex_Matcher_Data (case_sensitive : (True | Case_Insensitive) = True) (multiline : Boolean = False) (match_ascii : Boolean = False) (dot_matches_newline : Boolean = False) (comments : Boolean = False) ## UNSTABLE Compiles a provided pattern according to the rules defined in this @@ -185,11 +187,6 @@ Text_Matcher.match_criteria self = match_criteria_implementation self Regex_Matcher.match_criteria : Vector Any -> Vector Text -> Boolean -> (Any -> Text) -> Problem_Behavior -> Vector Any ! No_Matches_Found Regex_Matcher.match_criteria self = match_criteria_implementation self -## A common supertype representing a matching strategy. -type Matcher - Text_Matcher - Regex_Matcher - ## PRIVATE match_criteria_implementation matcher objects criteria reorder=False name_mapper=(x->x) on_problems=Report_Warning = result = internal_match_criteria_implementation matcher objects criteria reorder name_mapper @@ -208,7 +205,7 @@ match_criteria_callback matcher objects criteria problem_callback reorder=False type Match_Matrix ## PRIVATE A helper type holding a matrix of matches. - type Match_Matrix matrix criteria objects + type Match_Matrix_Data matrix criteria objects # Checks if the ith object is matched by any criterion. is_object_matched_by_anything : Integer -> Boolean diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Span.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Span.enso index 864df394db0b..52f6871b6af8 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Span.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Span.enso @@ -7,7 +7,7 @@ example_span = text = "Hello!" - Span 0 3 text + Span_Data 0 3 text from Standard.Base import all @@ -38,8 +38,8 @@ type Span example_span = text = "Hello!" range = 0.up_to 3 - Span.Span range text - type Span (range : Range.Range) (text : Text) + Span.Span_Data range text + Span_Data (range : Range.Range) (text : Text) ## The index of the first character included in the span. @@ -76,10 +76,10 @@ type Span Find the span of code units corresponding to the span of extended grapheme clusters. text = 'ae\u{301}fz' - (Span (Range 1 3) text).to_utf_16_span == (Utf_16_Span (Range 1 4) text) + (Span_Data (Range 1 3) text).to_utf_16_span == (Utf_16_Span_Data (Range 1 4) text) to_utf_16_span : Utf_16_Span to_utf_16_span self = - Utf_16_Span (range_to_char_indices self.text self.range) self.text + Utf_16_Span_Data (range_to_char_indices self.text self.range) self.text type Utf_16_Span @@ -97,8 +97,8 @@ type Utf_16_Span example_span = text = 'a\u{301}bc' - Span.Utf_16_Span (Range 0 3) text - type Utf_16_Span (range : Range.Range) (text : Text) + Span.Utf_16_Span_Data (Range 0 3) text + Utf_16_Span_Data (range : Range.Range) (text : Text) ## The index of the first code unit included in the span. start : Integer @@ -126,17 +126,17 @@ type Utf_16_Span Convert a codepoint span to graphemes and back. text = 'a\u{301}e\u{302}o\u{303}' - span = Utf_16_Span (Range 1 5) text # The span contains the units [\u{301}, e, \u{302}, o]. + span = Utf_16_Span_Data (Range 1 5) text # The span contains the units [\u{301}, e, \u{302}, o]. extended = span.to_grapheme_span - extended == Span (Range 0 3) text # The span is extended to the whole string since it contained code units from every grapheme cluster. - extended.to_utf_16_span == Utf_16_Span (Range 0 6) text + extended == Span_Data (Range 0 3) text # The span is extended to the whole string since it contained code units from every grapheme cluster. + extended.to_utf_16_span == Utf_16_Span_Data (Range 0 6) text to_grapheme_span : Span to_grapheme_span self = if (self.start < 0) || (self.end > Text_Utils.char_length self.text) then Error.throw (Illegal_State_Error "Utf_16_Span indices are out of range of the associated text.") else if self.end < self.start then Error.throw (Illegal_State_Error "Utf_16_Span invariant violation: start <= end") else case self.start == self.end of True -> grapheme_ix = Text_Utils.utf16_index_to_grapheme_index self.text self.start - Span (Range grapheme_ix grapheme_ix) self.text + Span_Data (Range grapheme_ix grapheme_ix) self.text False -> grapheme_ixes = Text_Utils.utf16_indices_to_grapheme_indices self.text [self.start, self.end - 1].to_array grapheme_first = grapheme_ixes.at 0 @@ -146,7 +146,7 @@ type Utf_16_Span only a part of a grapheme were contained in our original span, the resulting span will be extended to contain this whole grapheme. grapheme_end = grapheme_last + 1 - Span (Range grapheme_first grapheme_end) self.text + Span_Data (Range grapheme_first grapheme_end) self.text ## PRIVATE Utility function taking a range pointing at grapheme clusters and converting @@ -158,10 +158,10 @@ range_to_char_indices text range = if range.step != 1 then Error.throw (Illegal_ end = if range.end == Nothing then len else (if range.end < 0 then range.end + len else range.end) is_valid = (Range 0 len+1).contains - case (Pair (is_valid start) (is_valid end)) of - Pair False _ -> Error.throw (Index_Out_Of_Bounds_Error range.start len) - Pair True False -> Error.throw (Index_Out_Of_Bounds_Error range.end len) - Pair True True -> + case (Pair_Data (is_valid start) (is_valid end)) of + Pair_Data False _ -> Error.throw (Index_Out_Of_Bounds_Error range.start len) + Pair_Data True False -> Error.throw (Index_Out_Of_Bounds_Error range.end len) + Pair_Data True True -> if start>=end then (Range 0 0) else iterator = BreakIterator.getCharacterInstance iterator.setText text diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso index 5d018cb37662..0123ce18425c 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso @@ -15,20 +15,20 @@ type Text_Sub_Range ## Select characters until the first instance of `delimiter`. Select an empty string if `delimiter` is empty. Select the entire string if the input does not contain `delimiter`. - type Before (delimiter : Text) + Before (delimiter : Text) ## Select characters until the last instance of `delimiter`. Select an empty string if `delimiter` is empty. Select the entire string if the input does not contain `delimiter`. - type Before_Last (delimiter : Text) + Before_Last (delimiter : Text) ## Select characters after the first instance of `delimiter`. Select an empty string if the input does not contain `delimiter`. - type After (delimiter : Text) + After (delimiter : Text) ## Select characters after the last instance of `delimiter`. Select an empty string if the input does not contain `delimiter`. - type After_Last (delimiter : Text) + After_Last (delimiter : Text) ## PRIVATE Finds code-point indices corresponding to the part of the input matching the @@ -109,7 +109,7 @@ type Codepoint_Ranges - ranges: the list of ranges. Each `Range` has `step` equal to 1. - is_sorted_and_distinct: A helper value specifying if the ranges are already sorted and non-intersecting. - type Codepoint_Ranges (ranges : Vector Range) (is_sorted_and_distinct : Boolean) + Codepoint_Ranges_Data (ranges : Vector Range) (is_sorted_and_distinct : Boolean) ## PRIVATE Returns a new sorted list of ranges where intersecting ranges have been diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Problem_Behavior.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Problem_Behavior.enso index 31957a171421..d45852b7e613 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Problem_Behavior.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Problem_Behavior.enso @@ -6,15 +6,15 @@ import Standard.Base.Warning type Problem_Behavior ## UNSTABLE Ignore the problem and attempt to complete the operation - type Ignore + Ignore ## UNSTABLE Report the problem as a warning and attempt to complete the operation - type Report_Warning + Report_Warning ## UNSTABLE Report the problem as a dataflow error and abort the operation - type Report_Error + Report_Error ## ADVANCED UNSTABLE 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 57d4a1d9d4b1..02267c98ae97 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 @@ -77,7 +77,7 @@ 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.Pair export Pair, Pair_Data 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 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 44510918ee74..8341ab748f89 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 @@ -18,7 +18,7 @@ type Meta Arguments: - value: The value of the atom in the meta representation. - type Atom value + Atom value ## UNSTABLE ADVANCED @@ -27,7 +27,7 @@ type Meta Arguments: - value: The value of the constructor in the meta representation. - type Constructor value + Constructor value ## UNSTABLE ADVANCED @@ -36,7 +36,7 @@ type Meta Arguments: - value: The value of the primitive object in the meta representation. - type Primitive value + Primitive value ## UNSTABLE ADVANCED @@ -45,7 +45,7 @@ type Meta Arguments: - value: The value of the unresolved symbol in the meta representation. - type Unresolved_Symbol value + Unresolved_Symbol value ## UNSTABLE ADVANCED @@ -54,7 +54,7 @@ type Meta Arguments: - value: The payload of the error. - type Error value + Error value ## UNSTABLE ADVANCED @@ -63,7 +63,7 @@ type Meta Arguments: - value: The polyglot value contained in the meta representation. - type Polyglot value + Polyglot value ## Atom methods diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Method.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Method.enso index 9e9cc24e03f9..ea381b635329 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Method.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Method.enso @@ -1,25 +1,25 @@ type Method ## The HTTP method "OPTIONS". - type Options + Options ## The HTTP method "GET". - type Get - + Get + ## The HTTP method "HEAD". - type Head + Head ## The HTTP method "POST". - type Post + Post ## The HTTP method "PUT". - type Put + Put ## The HTTP method "DELETE". - type Delete + Delete ## The HTTP method "TRACE". - type Trace + Trace ## The HTTP method "CONNECT". - type Connect + Connect diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Request/Body.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Request/Body.enso index d093a6ae86b7..c562314e056e 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Request/Body.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Request/Body.enso @@ -4,34 +4,34 @@ from Standard.Base import all type Body ## Empty request body. - type Empty + Empty ## Request body with text. Arguments: - text: The plain text in the request body. - type Text text + Text text ## Request body with JSON. Arguments: - json: The JSON in the request body. - type Json json + Json json ## Request body with form data. Arguments: - form: The form data in the request body. - type Form form + Form form ## Request body with file data. Arguments: - file: The file data in the request body. - type File file + File file ## Request body with binary. Arguments: - bytes: The binary data in the request body. - type Bytes bytes + Bytes bytes diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso index 7bccddff7a5c..460a6c1563d8 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso @@ -1,6 +1,6 @@ from Standard.Base import all -import Standard.Base.Network.URI.Internal +import Standard.Base.Network.Uri.Internal polyglot java import java.net.URI as Java_URI polyglot java import java.util.Optional diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/File_Permissions.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/File_Permissions.enso index f1854436f44f..42e8bba3c608 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/File_Permissions.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/File_Permissions.enso @@ -4,17 +4,17 @@ polyglot java import java.nio.file.attribute.PosixFilePermission type Permission ## Permission for read access for a given entity. - type Read + Read ## Permission for write access for a given entity. - type Write + Write ## Permission for execute access for a given entity. - type Execute + Execute type File_Permissions ## Access permissions for a file. - type File_Permissions (owner : Vector Permission) (group : Vector Permission) (others : Vector Permission) + File_Permissions_Data (owner : Vector Permission) (group : Vector Permission) (others : Vector Permission) ## Converts the Enso atom to its Java enum counterpart. to_java : Vector PosixFilePermission @@ -101,4 +101,4 @@ from_java_set java_set = if java_set.contains PosixFilePermission.OTHERS_EXECUTE then others.append Execute - File_Permissions owner.to_vector group.to_vector others.to_vector + File_Permissions_Data owner.to_vector group.to_vector others.to_vector diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/Option.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/Option.enso index bcda1df9201b..bfe91967b9d8 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/Option.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/Option.enso @@ -11,37 +11,37 @@ type Option ## If the file is opened for `Write` access then bytes will be written to the end of the file rather than the beginning. - type Append + Append ## Create a new file if it does not exist. - type Create + Create ## Create a new file, failing if the file already exists. - type Create_New + Create_New ## Delete the underlying file on closing the stream. - type Delete_On_Close + Delete_On_Close ## Requires that every update to the file's content be written synchronously to the underlying storage device. - type Dsync + Dsync ## Open for read access. - type Read + Read ## Sparse file. - type Sparse + Sparse ## Requires that every update to the file's content or metadata be written synchronously to the underlying storage device. - type Sync + Sync ## If the file already exists and is opened for `Write` access, the original contents will be removed. - type Truncate_Existing + Truncate_Existing ## Open file for write access. - type Write + Write ## PRIVATE 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 2079d08646c3..d4c6b7c10354 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 @@ -4,16 +4,16 @@ import Standard.Base.System type Os ## The Linux operating system. - type Linux + Linux ## The macOS operating system. - type Mac_OS + Mac_OS ## The Windows operating system. - type Windows + Windows ## An unknown operating system. - type Unknown + Unknown ## Return the type of operating system. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/Process/Exit_Code.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/Process/Exit_Code.enso index 745dc8cbd90d..87ae7e93c596 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/Process/Exit_Code.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/Process/Exit_Code.enso @@ -4,13 +4,13 @@ from Standard.Base import all type Exit_Code ## The process exited with a success. - type Exit_Success + Exit_Success ## The process exited with a failure. Arguments: - code: The exit code for the failure. - type Exit_Failure code + Exit_Failure code ## Convert exit code to a number. diff --git a/engine/runtime-instrument-repl-debugger/src/main/java/org/enso/interpreter/instrument/ReplDebuggerInstrument.java b/engine/runtime-instrument-repl-debugger/src/main/java/org/enso/interpreter/instrument/ReplDebuggerInstrument.java index 25cb501ccf7e..841d8fb80ca9 100644 --- a/engine/runtime-instrument-repl-debugger/src/main/java/org/enso/interpreter/instrument/ReplDebuggerInstrument.java +++ b/engine/runtime-instrument-repl-debugger/src/main/java/org/enso/interpreter/instrument/ReplDebuggerInstrument.java @@ -177,7 +177,7 @@ public void exit() { @Override protected void onEnter(VirtualFrame frame) { CallerInfo lastScope = Function.ArgumentsHelper.getCallerInfo(frame.getArguments()); - Object lastReturn = Context.get(this).getNothing().newInstance(); + Object lastReturn = Context.get(this).getNothing(); // Note [Safe Access to State in the Debugger Instrument] Object lastState = Function.ArgumentsHelper.getState(frame.getArguments()); nodeState = new ReplExecutionEventNodeState(lastReturn, lastState, lastScope); 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 71fd12c9b6c2..605db75911e9 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala @@ -724,6 +724,8 @@ class Compiler( List((module, errors)) } if (reportDiagnostics(diagnostics)) { + val count = diagnostics.map(_._2.collect { case e: IR.Error => e }.length).sum + println(s"Aborting due to ${count} errors.") throw new CompilationAbortedException } } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala index c3d8bf3bca3d..1981f55536fa 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala @@ -241,15 +241,16 @@ case object AliasAnalysis extends IRPass { topLevelGraph, topLevelGraph.rootScope ), - members = t.members.map(d => + members = t.members.map(d => { + val graph = new Graph d.copy(arguments = analyseArgumentDefs( d.arguments, - topLevelGraph, - topLevelGraph.rootScope + graph, + graph.rootScope ) - ).updateMetadata(this -->> Info.Scope.Root(topLevelGraph)) - ) + ).updateMetadata(this -->> Info.Scope.Root(graph)) + }) ).updateMetadata(this -->> Info.Scope.Root(topLevelGraph)) case _: IR.Module.Scope.Definition.SugaredType => throw new CompilerError( @@ -475,7 +476,10 @@ case object AliasAnalysis extends IRPass { .updateMetadata(this -->> Info.Occurrence(graph, occurrenceId)) } else { throw new CompilerError( - "Arguments should never be redefined. This is a bug." + s""" + Arguments should never be redefined. This is a bug. + ${} + """ ) } } From 30ecb0a1f44bec9d5f93c487c54bae0deee382a8 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 10 Aug 2022 15:44:22 +0200 Subject: [PATCH 040/110] keep going --- .../0.0.0-dev/src/Data/Text/Extensions.enso | 22 ++++++++-------- .../0.0.0-dev/src/Data/Text/Regex/Option.enso | 10 +++---- .../Standard/Base/0.0.0-dev/src/Runtime.enso | 8 +++--- .../0.0.0-dev/src/Runtime/Extensions.enso | 2 +- .../lib/Standard/Test/0.0.0-dev/src/Main.enso | 26 +++++++++---------- 5 files changed, 33 insertions(+), 35 deletions(-) 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 74ff289769be..fa1da1cad80e 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 @@ -367,7 +367,7 @@ Text.split self delimiter="," matcher=Text_Matcher = if delimiter.is_empty then delimiters = Vector.Vector <| case case_sensitivity of True -> Text_Utils.span_of_all self delimiter - Case_Insensitive locale -> + Case_Insensitive_Data locale -> Text_Utils.span_of_all_case_insensitive self delimiter locale.java_locale Vector.new delimiters.length+1 i-> start = if i == 0 then 0 else @@ -894,12 +894,12 @@ Text.from_codepoints codepoints = Text_Utils.from_codepoints codepoints.to_array "Hello!".starts_with "[A-Z]" Regex_Matcher == True Text.starts_with : Text -> Matcher -> Boolean Text.starts_with self prefix matcher=Text_Matcher = case matcher of - Text_Matcher case_sensitivity -> case case_sensitivity of + Text_Matcher_Data case_sensitivity -> case case_sensitivity of True -> self.take (Text_Sub_Range.First prefix.length) == prefix Case_Insensitive locale -> self.take (Text_Sub_Range.First prefix.length) . equals_ignore_case prefix locale=locale - Regex_Matcher _ _ _ _ _ -> + Regex_Matcher_Data _ _ _ _ _ -> preprocessed_pattern = "\A(?:" + prefix + ")" compiled_pattern = matcher.compile preprocessed_pattern match = compiled_pattern.match self Mode.First @@ -931,12 +931,12 @@ Text.starts_with self prefix matcher=Text_Matcher = case matcher of "Hello World".ends_with "[A-Z][a-z]{4}" Regex_Matcher == True Text.ends_with : Text -> Matcher -> Boolean Text.ends_with self suffix matcher=Text_Matcher = case matcher of - Text_Matcher case_sensitivity -> case case_sensitivity of + Text_Matcher_Data case_sensitivity -> case case_sensitivity of True -> self.take (Text_Sub_Range.Last suffix.length) == suffix Case_Insensitive locale -> self.take (Text_Sub_Range.Last suffix.length) . equals_ignore_case suffix locale=locale - Regex_Matcher _ _ _ _ _ -> + Regex_Matcher_Data _ _ _ _ _ -> preprocessed_pattern = "(?:" + suffix + ")\z" compiled_pattern = matcher.compile preprocessed_pattern match = compiled_pattern.match self Mode.First @@ -995,11 +995,11 @@ Text.ends_with self suffix matcher=Text_Matcher = case matcher of "Hello!".contains "[a-z]" Regex_Matcher Text.contains : Text -> Matcher -> Boolean Text.contains self term="" matcher=Text_Matcher = case matcher of - Text_Matcher case_sensitivity -> case case_sensitivity of + Text_Matcher_Data case_sensitivity -> case case_sensitivity of True -> Text_Utils.contains self term Case_Insensitive locale -> Text_Utils.contains_case_insensitive self term locale.java_locale - Regex_Matcher _ _ _ _ _ -> + Regex_Matcher_Data _ _ _ _ _ -> compiled_pattern = matcher.compile term match = compiled_pattern.match self Mode.First match.is_nothing.not @@ -1096,9 +1096,9 @@ Text.take : (Text_Sub_Range | Index_Sub_Range | Range) -> Text ! Index_Out_Of_Bo Text.take self range=(First 1) = ranges = Text_Sub_Range.find_codepoint_ranges self range case ranges of - Range start end _ -> + Range_Data start end _ -> Text_Utils.substring self start end - Text_Sub_Range.Codepoint_Ranges char_ranges _ -> + Text_Sub_Range.Codepoint_Ranges_Data char_ranges _ -> sb = StringBuilder.new char_ranges.map char_range-> sb.append self char_range.start char_range.end @@ -1394,7 +1394,7 @@ Text.location_of self term="" mode=Matching_Mode.First matcher=Text_Matcher = ca guaranteed to be the same. end = start + term.length Span (Range start end) self - Case_Insensitive locale -> case term.is_empty of + Case_Insensitive_Data locale -> case term.is_empty of True -> case mode of Matching_Mode.First -> Span (Range 0 0) self Matching_Mode.Last -> @@ -1496,7 +1496,7 @@ Text.location_of_all self term="" matcher=Text_Matcher = case matcher of grahpeme_ixes . map start-> end = start+offset Span (Range start end) self - Case_Insensitive locale -> + Case_Insensitive_Data locale -> grapheme_spans = Vector.Vector <| Text_Utils.span_of_all_case_insensitive self term locale.java_locale grapheme_spans.map grapheme_span-> Span (Range grapheme_span.grapheme_start grapheme_span.grapheme_end) self diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Option.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Option.enso index 5107cd309202..e21880a5ee13 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Option.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Option.enso @@ -15,10 +15,10 @@ type Option the ASCII character set, you may be able to obtain a performance boost by specifying this flag. This may not be the case on all engines or all regexes. - type Ascii_Matching + Ascii_Matching ## Specifies that matching should be performed in a case-insensitive manner. - type Case_Insensitive + Case_Insensitive ## Specifies that the regular expression should be interpreted in comments mode. @@ -31,16 +31,16 @@ type Option preceeded by an unescaped backslash, all characters from the leftmost such `#` to the end of the line are ignored. That is to say, they act as _comments_ in the regex. - type Comments + Comments ## Specifies that the `.` special character should match everything _including_ newline characters. Without this flag, it will match all characters _except_ newlines. - type Dot_Matches_Newline + Dot_Matches_Newline ## Specifies that the pattern character `^` matches at both the beginning of the string and at the beginning of each line (immediately following a newline), and that the pattern character `$` matches at the end of each line _and_ at the end of the string. - type Multiline + Multiline diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso index 7be0e01dbb0e..ad7c5f03f611 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso @@ -1,7 +1,7 @@ import Standard.Base.Data.Vector import Standard.Base.Polyglot import Standard.Base.Nothing -from Standard.Base.Runtime.Extensions import Source_Location +from Standard.Base.Runtime.Extensions import Source_Location, Source_Location_Data ## Utilities for interacting with the runtime. @@ -79,9 +79,9 @@ 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 + loc = if Polyglot.has_source_location el then (Source_Location_Data (Polyglot.get_source_location el)) else Nothing name = Polyglot.get_executable_name el - Stack_Trace_Element name loc + Stack_Trace_Element_Data name loc ## ADVANCED UNSTABLE @@ -89,4 +89,4 @@ wrap_primitive_stack_trace_element el = Represents a single stack frame in an Enso stack trace. type Stack_Trace_Element ## PRIVATE - type Stack_Trace_Element name source_location + Stack_Trace_Element_Data name source_location 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 1691670079ce..771c5a940237 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 @@ -6,7 +6,7 @@ from Standard.Base import all source file and code position within it. type Source_Location ## PRIVATE - type Source_Location prim_location + type Source_Location_Data prim_location ## UNSTABLE Pretty prints the location. 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 2c2b41c2db49..fb1272919688 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 @@ -553,12 +553,6 @@ Error.should_contain_the_same_elements_as self _ frames_to_skip=0 = fail_match_o type Verbs - - ## PRIVATE - - Verbs that describe how tests should execute. - type Verbs - ## PRIVATE Checks if the `subject` starts with `argument`. @@ -613,7 +607,7 @@ type Verbs ## PRVATE type Suite_Config - type Suite_Config only_group_regexp output_path + type Suite_Config_Data only_group_regexp output_path should_run_group self name = regexp = self.only_group_regexp @@ -633,7 +627,8 @@ type Suite_Config - config: Suite_Config controlloing the test run. - specs: The specs contained within the test suite. - builder: StringBuilder for JUnit output. -type Suite config specs builder +type Suite + Suite_Data config specs builder ## PRIVATE @@ -642,7 +637,8 @@ type Suite config specs builder Arguments: - name: The name of the spec. - behaviors: The results of the behaviors encapsulated in that spec. -type Spec name behaviors +type Spec + Spec_Data name behaviors ## PRIVATE @@ -651,7 +647,8 @@ type Spec name behaviors Arguments: - name: The name of the behavior. - result: The result of the behavior. -type Behavior name result +type Behavior + Behavior_Data name result ## PRIVATE @@ -679,7 +676,8 @@ Suite.is_fail self = self.specs.any .is_fail - err: The payload of the error that triggered this error. - stack_trace_text: A textual representation of the stack trace for the error. -type Finished_With_Error err stack_trace_text +type Finished_With_Error + Finished_With_Error_Data err stack_trace_text ## PRIVATE type Assertion @@ -687,7 +685,7 @@ type Assertion ## PRIVATE Represents a successful behavioral test. - type Success + Success ## PRIVATE @@ -695,7 +693,7 @@ type Assertion Arguments: - message: The reason why the test failed. - type Failure message + Failure message ## PRIVATE @@ -703,7 +701,7 @@ type Assertion Arguments: - reason: Text describing why the test is pending. - type Pending reason + Pending reason ## PRIVATE From 5f3475bc0fea7957437697b4d2ffe7ce77d63014 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 10 Aug 2022 16:03:34 +0200 Subject: [PATCH 041/110] more --- .../Base/0.0.0-dev/src/Data/Text/Line_Ending_Style.enso | 6 +++--- .../lib/Standard/Base/0.0.0-dev/src/System/File.enso | 6 +++--- .../0.0.0-dev/src/System/File/Existing_File_Behavior.enso | 8 ++++---- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Line_Ending_Style.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Line_Ending_Style.enso index 5f6f995a9c88..3851a35f3a03 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Line_Ending_Style.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Line_Ending_Style.enso @@ -4,14 +4,14 @@ from Standard.Base import all type Line_Ending_Style ## Unix-style endings. Used, among others, on Linux and modern MacOS. The text equivalent is `'\n'`. - type Unix + Unix ## Windows-style endings. The text equivalent is `'\r\n'`. - type Windows + Windows ## Legacy MacOS endings. Only used on very old Mac systems. The text equivalent is `'\r\n'`. - type Mac_Legacy + Mac_Legacy ## Returns the text equivalent of the line ending. to_text : Text 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 03efd75fde2d..f184d83f7b03 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 @@ -1008,17 +1008,17 @@ type File_Error Arguments: - file: The file that doesn't exist. - type File_Not_Found file + File_Not_Found file ## Indicates that a destination file already exists. - type File_Already_Exists_Error file + File_Already_Exists_Error file ## A generic IO error. Arguments: - file: The file that couldn't be read. - message: The message for the error. - type IO_Error file message + IO_Error file message ## UNSTABLE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/Existing_File_Behavior.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/Existing_File_Behavior.enso index 4660afe81564..14a8a5d891cb 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/Existing_File_Behavior.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/Existing_File_Behavior.enso @@ -11,21 +11,21 @@ type Existing_File_Behavior Note: There is a risk of data loss if a failure occurs during the write operation. - type Overwrite + Overwrite ## Creates a backup of the existing file (by appending a `.bak` suffix to the name) before replacing it with the new contents. Note: This requires sufficient storage to have two copies of the file. If an existing `.bak` file exists, it will be replaced. - type Backup + Backup ## Appends data to the existing file. - type Append + Append ## If the file already exists, a `File_Already_Exists_Error` error is raised. - type Error + Error ## PRIVATE Runs the `action` which is given a file output stream and should write From 49c12824231253374d7ac12b5584ace475dec7ca Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 11 Aug 2022 16:23:13 +0200 Subject: [PATCH 042/110] Keep going. Actually help myself in the compiler --- .../Base/0.0.0-dev/src/Data/Interval.enso | 10 ++-- .../Base/0.0.0-dev/src/Data/Json.enso | 16 ++--- .../0.0.0-dev/src/Data/Json/Internal.enso | 2 +- .../Base/0.0.0-dev/src/Data/Maybe.enso | 10 ++-- .../src/Data/Ordering/Natural_Order.enso | 2 +- .../Base/0.0.0-dev/src/Data/Range.enso | 8 +-- .../Base/0.0.0-dev/src/Data/Text.enso | 18 +++--- .../Base/0.0.0-dev/src/Data/Text/Case.enso | 6 +- .../0.0.0-dev/src/Data/Text/Extensions.enso | 60 +++++++++---------- .../0.0.0-dev/src/Data/Text/Matching.enso | 7 ++- .../0.0.0-dev/src/Data/Text/Regex/Engine.enso | 21 ------- .../src/Data/Text/Regex/Engine/Default.enso | 22 +++---- .../0.0.0-dev/src/Data/Text/Regex/Mode.enso | 8 +-- .../src/Data/Text/Text_Sub_Range.enso | 4 +- .../Base/0.0.0-dev/src/Data/Time.enso | 31 ++++------ .../Base/0.0.0-dev/src/Data/Time/Zone.enso | 4 +- .../Base/0.0.0-dev/src/Data/Vector.enso | 28 +++++---- .../Base/0.0.0-dev/src/Error/Common.enso | 52 ++++++++-------- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 2 +- .../Base/0.0.0-dev/src/Meta/Enso_Project.enso | 4 +- .../Standard/Base/0.0.0-dev/src/Nothing.enso | 15 ++--- .../Base/0.0.0-dev/src/Polyglot/Java.enso | 4 -- .../Standard/Base/0.0.0-dev/src/Runtime.enso | 2 +- .../0.0.0-dev/src/Runtime/Extensions.enso | 2 +- .../Base/0.0.0-dev/src/Runtime/Resource.enso | 15 ++--- .../Base/0.0.0-dev/src/System/File.enso | 8 +-- .../Standard/Base/0.0.0-dev/src/Warning.enso | 7 +-- .../scala/org/enso/compiler/Compiler.scala | 3 +- .../scala/org/enso/compiler/core/IR.scala | 18 +++++- .../compiler/pass/resolve/GlobalNames.scala | 52 +++++++++++----- .../compiler/pass/resolve/MethodCalls.scala | 2 +- .../pass/resolve/OverloadsResolution.scala | 2 +- 32 files changed, 223 insertions(+), 222 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Interval.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Interval.enso index dd4fbe5e0388..28aabdbe3e8f 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Interval.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Interval.enso @@ -13,7 +13,7 @@ export Standard.Base.Data.Interval.Bound example_exclusive = Interval.exclusive 0.1 0.5 exclusive : Number -> Number -> Interval -exclusive start end = Interval (Bound.Exclusive start) (Bound.Exclusive end) +exclusive start end = Interval_Data (Bound.Exclusive start) (Bound.Exclusive end) ## Creates an interval that excludes its lower bound. @@ -24,7 +24,7 @@ exclusive start end = Interval (Bound.Exclusive start) (Bound.Exclusive end) example_start_exclusive = Interval.start_exclusive 1 5 start_exclusive : Number -> Number -> Interval -start_exclusive start end = Interval (Bound.Exclusive start) (Bound.Inclusive end) +start_exclusive start end = Interval_Data (Bound.Exclusive start) (Bound.Inclusive end) ## Creates an interval that excludes its upper bound. @@ -35,7 +35,7 @@ start_exclusive start end = Interval (Bound.Exclusive start) (Bound.Inclusive en example_end_exclusive = Interval.end_exclusive 1 5 end_exclusive : Number -> Number -> Interval -end_exclusive start end = Interval (Bound.Inclusive start) (Bound.Exclusive end) +end_exclusive start end = Interval_Data (Bound.Inclusive start) (Bound.Exclusive end) ## Creates an interval that includes both of its bounds. @@ -46,7 +46,7 @@ end_exclusive start end = Interval (Bound.Inclusive start) (Bound.Exclusive end) example_inclusive = Interval.inclusive 0 0 inclusive : Number -> Number -> Interval -inclusive start end = Interval (Bound.Inclusive start) (Bound.Inclusive end) +inclusive start end = Interval_Data (Bound.Inclusive start) (Bound.Inclusive end) ## A type representing an interval over real numbers. type Interval @@ -58,7 +58,7 @@ type Interval Arguments: - start: The start of the interval. - end: The end of the interval. - type Interval (start : Number) (end : Number) + Interval_Data (start : Number) (end : Number) ## Checks if the interval contains `that`. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso index e814e3089339..847c3d1319fc 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso @@ -133,12 +133,12 @@ type Json example_unwrap = Json.Number 3 . unwrap unwrap : Any unwrap self = case self of - Json.Array its -> its.map .unwrap - Json.Boolean b -> b - Json.Number n -> n - Json.String t -> t - Json.Null -> Nothing - Json.Object f -> f.map .unwrap + Array its -> its.map .unwrap + Boolean b -> b + Number n -> n + String t -> t + Null -> Nothing + Object f -> f.map .unwrap ## UNSTABLE @@ -201,7 +201,7 @@ type Marshalling_Error - format: The type format that did not match. This can occur e.g. when trying to reinterpret a number as a `Text`, etc. - type Type_Mismatch_Error json format + Type_Mismatch_Error json format ## UNSTABLE @@ -215,7 +215,7 @@ type Marshalling_Error This can occure when trying to reinterpret a JSON object into an atom, when the JSON does not contain all the fields required by the atom. - type Missing_Field_Error json field format + Missing_Field_Error json field format ## UNSTABLE 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 3e5e67411a86..c2abc558d2e7 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 @@ -287,7 +287,7 @@ render_helper builder json = case json of See `Json.into` for semantics documentation. into_helper : Any -> Json -> Any into_helper fmt json = case fmt of - Base.Vector.Vector field -> case json of + Base.Vector.Vector_Data field -> case json of Array items -> items.map (into_helper field) _ -> Panic.throw (Type_Mismatch_Error json fmt) Base.Boolean -> case json of diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Maybe.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Maybe.enso index 1c1d21a07adf..3981569c32f4 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Maybe.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Maybe.enso @@ -4,7 +4,7 @@ from Standard.Base import all type Maybe ## No contained value. - Nothing + None ## A value. @@ -17,13 +17,13 @@ type Maybe import Standard.Base.Data.Maybe example_some = Maybe.Some "yes!" - type Some value + Some value ## Applies the provided function to the contained value if it exists, otherwise returning the provided default value. Arguments: - - default: The value to return if `self` is Nothing. This value is lazy + - default: The value to return if `self` is None. This value is lazy and hence will not execute any provided computation unless it is used. - function: The function to execute on the value inside the `Some`, if it is a just. @@ -36,13 +36,13 @@ type Maybe example_maybe = Maybe.Some 2 . maybe 0 *2 maybe : Any -> (Any -> Any) -> Any maybe self ~default function = case self of - Nothing -> default + None -> default Some val -> function val ## Check if the maybe value is `Some`. > Example - Check if `Nothing` is `Some`. + Check if `None` is `Some`. import Standard.Base.Data.Maybe diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Natural_Order.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Natural_Order.enso index 0ae7218ca8e4..324b4894c368 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Natural_Order.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Natural_Order.enso @@ -21,7 +21,7 @@ polyglot java import com.ibm.icu.text.BreakIterator compare : Text -> Text -> (True|Case_Insensitive) Ordering compare text1 text2 case_sensitive=True = compare_text = case case_sensitive of - Case_Insensitive locale -> a -> b -> a.compare_to_ignore_case b locale + Case_Insensitive_Data locale -> a -> b -> a.compare_to_ignore_case b locale _ -> _.compare_to _ iter1 = BreakIterator.getCharacterInstance diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Range.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Range.enso index 161ad29504c0..4f318e1be85d 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Range.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Range.enso @@ -11,7 +11,7 @@ type Range - end: The right boundary of the range. Its value is excluded. - step: The step between consecutive elements of the range. It must be non-zero. Defaults to 1. - type Range (start : Integer) (end : Integer) (step : Integer = 1) + Range_Data (start : Integer) (end : Integer) (step : Integer = 1) ## Creates a copy of this range with a changed step. @@ -29,7 +29,7 @@ type Range Integer -> if new_step == 0 then throw_zero_step_error else if new_step < 0 then Error.throw (Illegal_Argument_Error "The step should be positive. A decreasing sequence will remain decreasing after updating it with positive step, as this operation only sets the magnitude without changing the sign.") else - Range self.start self.end self.step.signum*new_step + Range_Data self.start self.end self.step.signum*new_step _ -> Error.throw (Illegal_Argument_Error "Range step should be an integer.") @@ -261,7 +261,7 @@ type Range 0.up_to 5 Integer.up_to : Integer -> Range Integer.up_to self n = case n of - Integer -> Range self n + Integer -> Range_Data self n _ -> Error.throw (Illegal_Argument_Error "Expected range end to be an Integer.") ## ALIAS Range @@ -277,7 +277,7 @@ Integer.up_to self n = case n of 5.down_to 0 Integer.down_to : Integer -> Range Integer.down_to self n = case n of - Integer -> Range self n -1 + Integer -> Range_Data self n -1 _ -> Error.throw (Illegal_Argument_Error "Expected range end to be an Integer.") ## PRIVATE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso index 94dc1e00f72a..634daee1d063 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text.enso @@ -1,19 +1,17 @@ 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. - Enso's text type is natively unicode aware, and will handle arbitrary - textual data. + 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 + ? 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. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Case.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Case.enso index 50e6821b3a87..1e2360090e94 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Case.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Case.enso @@ -1,10 +1,10 @@ ## Specifies the casing options for text conversion. type Case ## All letters in lower case. - type Lower + Lower ## All letters in upper case. - type Upper + Upper ## First letter of each word in upper case, rest in lower case. - type Title + Title 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 fa1da1cad80e..5bc8a42d99a1 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 @@ -361,9 +361,9 @@ Text.find self pattern mode=Mode.All match_ascii=Nothing case_insensitive=Nothin 'abc def\tghi'.split '\\s+' Regex_Matcher == ["abc", "def", "ghi"] Text.split : Text -> (Text_Matcher | Regex_Matcher) -> Vector.Vector Text -Text.split self delimiter="," matcher=Text_Matcher = if delimiter.is_empty then Error.throw (Illegal_Argument_Error "The delimiter cannot be empty.") else +Text.split self delimiter="," matcher=Text_Matcher_Data = if delimiter.is_empty then Error.throw (Illegal_Argument_Error "The delimiter cannot be empty.") else case matcher of - Text_Matcher case_sensitivity -> + Text_Matcher_Data case_sensitivity -> delimiters = Vector.Vector <| case case_sensitivity of True -> Text_Utils.span_of_all self delimiter @@ -375,7 +375,7 @@ Text.split self delimiter="," matcher=Text_Matcher = if delimiter.is_empty then end = if i == delimiters.length then (Text_Utils.char_length self) else delimiters.at i . codeunit_start Text_Utils.substring self start end - Regex_Matcher _ _ _ _ _ -> + Regex_Matcher_Data _ _ _ _ _ -> compiled_pattern = matcher.compile delimiter compiled_pattern.split self mode=Mode.All @@ -456,9 +456,9 @@ Text.split self delimiter="," matcher=Text_Matcher = if delimiter.is_empty then "aaa aaa".replace "aa" "c" mode=Matching_Mode.First matcher=Regex_Matcher . should_equal "ca aaa" "aaa aaa".replace "aa" "c" mode=Matching_Mode.Last matcher=Regex_Matcher . should_equal "aaa ca" Text.replace : Text -> Text -> (Matching_Mode.First | Matching_Mode.Last | Mode.All) -> (Text_Matcher | Regex_Matcher) -> Text -Text.replace self term="" new_text="" mode=Mode.All matcher=Text_Matcher = if term.is_empty then self else +Text.replace self term="" new_text="" mode=Mode.All matcher=Text_Matcher_Data = if term.is_empty then self else case matcher of - Text_Matcher case_sensitivity -> + Text_Matcher_Data case_sensitivity -> array_from_single_result result = case result of Nothing -> Array.empty _ -> Array.new_1 result @@ -470,7 +470,7 @@ Text.replace self term="" new_text="" mode=Mode.All matcher=Text_Matcher = if te array_from_single_result <| Text_Utils.span_of self term Matching_Mode.Last -> array_from_single_result <| Text_Utils.last_span_of self term - Case_Insensitive locale -> case mode of + Case_Insensitive_Data locale -> case mode of Mode.All -> Text_Utils.span_of_all_case_insensitive self term locale.java_locale Matching_Mode.First -> @@ -480,7 +480,7 @@ Text.replace self term="" new_text="" mode=Mode.All matcher=Text_Matcher = if te array_from_single_result <| Text_Utils.span_of_case_insensitive self term locale.java_locale True Text_Utils.replace_spans self spans_array new_text - Regex_Matcher _ _ _ _ _ -> + Regex_Matcher_Data _ _ _ _ _ -> compiled_pattern = matcher.compile term compiled_pattern.replace self new_text mode=mode @@ -677,8 +677,8 @@ Text.insert self index that = if (idx < 0) || (idx > len) then Error.throw (Index_Out_Of_Bounds_Error index len) else if idx == 0 then that + self else if idx == len then self + that else - pre = self.take (Range 0 idx) - post = self.take (Range idx len) + pre = self.take (Range_Data 0 idx) + post = self.take (Range_Data idx len) pre + that + post ## Returns if a character from the text at the specified index (0-based) is a @@ -893,11 +893,11 @@ Text.from_codepoints codepoints = Text_Utils.from_codepoints codepoints.to_array "Hello!".starts_with "[a-z]" Regex_Matcher == False "Hello!".starts_with "[A-Z]" Regex_Matcher == True Text.starts_with : Text -> Matcher -> Boolean -Text.starts_with self prefix matcher=Text_Matcher = case matcher of +Text.starts_with self prefix matcher=Text_Matcher_Data = case matcher of Text_Matcher_Data case_sensitivity -> case case_sensitivity of True -> self.take (Text_Sub_Range.First prefix.length) == prefix - Case_Insensitive locale -> + Case_Insensitive_Data locale -> self.take (Text_Sub_Range.First prefix.length) . equals_ignore_case prefix locale=locale Regex_Matcher_Data _ _ _ _ _ -> preprocessed_pattern = "\A(?:" + prefix + ")" @@ -930,11 +930,11 @@ Text.starts_with self prefix matcher=Text_Matcher = case matcher of "Hello World".ends_with "world" (Text_Matcher Case_Insensitive) == True "Hello World".ends_with "[A-Z][a-z]{4}" Regex_Matcher == True Text.ends_with : Text -> Matcher -> Boolean -Text.ends_with self suffix matcher=Text_Matcher = case matcher of +Text.ends_with self suffix matcher=Text_Matcher_Data = case matcher of Text_Matcher_Data case_sensitivity -> case case_sensitivity of True -> self.take (Text_Sub_Range.Last suffix.length) == suffix - Case_Insensitive locale -> + Case_Insensitive_Data locale -> self.take (Text_Sub_Range.Last suffix.length) . equals_ignore_case suffix locale=locale Regex_Matcher_Data _ _ _ _ _ -> preprocessed_pattern = "(?:" + suffix + ")\z" @@ -994,10 +994,10 @@ Text.ends_with self suffix matcher=Text_Matcher = case matcher of "Hello!".contains "[a-z]" Regex_Matcher Text.contains : Text -> Matcher -> Boolean -Text.contains self term="" matcher=Text_Matcher = case matcher of +Text.contains self term="" matcher=Text_Matcher_Data = case matcher of Text_Matcher_Data case_sensitivity -> case case_sensitivity of True -> Text_Utils.contains self term - Case_Insensitive locale -> + Case_Insensitive_Data locale -> Text_Utils.contains_case_insensitive self term locale.java_locale Regex_Matcher_Data _ _ _ _ _ -> compiled_pattern = matcher.compile term @@ -1145,16 +1145,16 @@ Text.drop : (Text_Sub_Range | Index_Sub_Range | Range) -> Text ! Index_Out_Of_Bo Text.drop self range=(First 1) = ranges = Text_Sub_Range.find_codepoint_ranges self range case ranges of - Range start end _ -> + Range_Data start end _ -> if start == 0 then Text_Utils.drop_first self end else prefix = Text_Utils.substring self 0 start if end == (Text_Utils.char_length self) then prefix else prefix + Text_Utils.drop_first self end - Text_Sub_Range.Codepoint_Ranges _ _ -> + Text_Sub_Range.Codepoint_Ranges_Data _ _ -> sorted_char_ranges_to_remove = ranges.sorted_and_distinct_ranges len = Text_Utils.char_length self sb = StringBuilder.new - ranges_with_sentinels = [Range 0 0] + sorted_char_ranges_to_remove + [Range len len] + ranges_with_sentinels = [Range_Data 0 0] + sorted_char_ranges_to_remove + [Range_Data len len] ranges_with_sentinels.zip ranges_with_sentinels.tail prev-> next-> sb.append self prev.end next.start sb.toString @@ -1381,8 +1381,8 @@ Text.trim self where=Location.Both what=_.is_whitespace = "aaa aaa".location_of "aa" mode=Matching_Mode.Last matcher=Text_Matcher == Span (Range 5 7) "aaa aaa" "aaa aaa".location_of "aa" mode=Matching_Mode.Last matcher=Regex_Matcher == Span (Range 4 6) "aaa aaa" Text.location_of : Text -> (Matching_Mode.First | Matching_Mode.Last) -> Matcher -> Span | Nothing -Text.location_of self term="" mode=Matching_Mode.First matcher=Text_Matcher = case matcher of - Text_Matcher case_sensitive -> case case_sensitive of +Text.location_of self term="" mode=Matching_Mode.First matcher=Text_Matcher_Data = case matcher of + Text_Matcher_Data case_sensitive -> case case_sensitive of True -> codepoint_span = case mode of Matching_Mode.First -> Text_Utils.span_of self term @@ -1393,13 +1393,13 @@ Text.location_of self term="" mode=Matching_Mode.First matcher=Text_Matcher = ca from our term, the `length` counted in grapheme clusters is guaranteed to be the same. end = start + term.length - Span (Range start end) self + Span_Data (Range_Data start end) self Case_Insensitive_Data locale -> case term.is_empty of True -> case mode of - Matching_Mode.First -> Span (Range 0 0) self + Matching_Mode.First -> Span_Data (Range_Data 0 0) self Matching_Mode.Last -> end = self.length - Span (Range end end) self + Span_Data (Range_Data end end) self False -> search_for_last = case mode of Matching_Mode.First -> False @@ -1407,8 +1407,8 @@ Text.location_of self term="" mode=Matching_Mode.First matcher=Text_Matcher = ca case Text_Utils.span_of_case_insensitive self term locale.java_locale search_for_last of Nothing -> Nothing grapheme_span -> - Span (Range grapheme_span.grapheme_start grapheme_span.grapheme_end) self - Regex_Matcher _ _ _ _ _ -> case mode of + Span_Data (Range_Data grapheme_span.grapheme_start grapheme_span.grapheme_end) self + Regex_Matcher_Data _ _ _ _ _ -> case mode of Matching_Mode.First -> case matcher.compile term . match self Mode.First of Nothing -> Nothing @@ -1484,8 +1484,8 @@ Text.location_of self term="" mode=Matching_Mode.First matcher=Text_Matcher = ca match_2 = ligatures . location_of_all "ffiff" matcher=(Text_Matcher Case_Insensitive) match_2 . map .length == [2, 5] Text.location_of_all : Text -> Matcher -> [Span] -Text.location_of_all self term="" matcher=Text_Matcher = case matcher of - Text_Matcher case_sensitive -> if term.is_empty then Vector.new (self.length + 1) (ix -> Span (Range ix ix) self) else case case_sensitive of +Text.location_of_all self term="" matcher=Text_Matcher_Data = case matcher of + Text_Matcher_Data case_sensitive -> if term.is_empty then Vector.new (self.length + 1) (ix -> Span_Data (Range_Data ix ix) self) else case case_sensitive of True -> codepoint_spans = Vector.Vector <| Text_Utils.span_of_all self term grahpeme_ixes = Vector.Vector <| Text_Utils.utf16_indices_to_grapheme_indices self (codepoint_spans.map .codeunit_start).to_array @@ -1495,12 +1495,12 @@ Text.location_of_all self term="" matcher=Text_Matcher = case matcher of offset = term.length grahpeme_ixes . map start-> end = start+offset - Span (Range start end) self + Span_Data (Range_Data start end) self Case_Insensitive_Data locale -> grapheme_spans = Vector.Vector <| Text_Utils.span_of_all_case_insensitive self term locale.java_locale grapheme_spans.map grapheme_span-> - Span (Range grapheme_span.grapheme_start grapheme_span.grapheme_end) self - Regex_Matcher _ _ _ _ _ -> + Span_Data (Range_Data grapheme_span.grapheme_start grapheme_span.grapheme_end) self + Regex_Matcher_Data _ _ _ _ _ -> case matcher.compile term . match self Mode.All of Nothing -> [] matches -> matches.map m-> m.span 0 . to_grapheme_span diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso index e6d166b267a5..115e8bbb0204 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso @@ -18,7 +18,8 @@ No_Matches_Found.to_display_text self = Arguments: - locale: The locale used for the comparison. -type Case_Insensitive locale=Locale.default +type Case_Insensitive + Case_Insensitive_Data locale=Locale.default ## Represents exact text matching mode. @@ -66,7 +67,7 @@ Regex_Matcher.compile self pattern = ## TODO [RW] Currently locale is not supported in case-insensitive Regex matching. There are plans to revisit it: https://www.pivotaltracker.com/story/show/181313576 - Case_Insensitive _ -> True + Case_Insensitive_Data _ -> True compiled_pattern = Regex.compile pattern case_insensitive=case_insensitive match_ascii=self.match_ascii dot_matches_newline=self.dot_matches_newline multiline=self.multiline comments=self.comments compiled_pattern @@ -86,7 +87,7 @@ Text_Matcher.match_single_criterion : Text -> Text -> Boolean Text_Matcher.match_single_criterion self name criterion = case self.case_sensitive of True -> name == criterion - Case_Insensitive locale -> name.equals_ignore_case criterion locale=locale + Case_Insensitive_Data locale -> name.equals_ignore_case criterion locale=locale ## UNSTABLE Checks if a name matches the provided criterion according to the specified 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 1f0e923c62e3..11f75409d82d 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 @@ -24,13 +24,6 @@ from Standard.Base.Data.Text.Regex.Engine.Default as Default_Engine export Defau ## The `Data.Text.Regex.Engine.Engine` interface. type Engine - ## PRIVATE - - A type to represent the regular expresion engine. - - This type may have whichever fields are required to implement the engine. - type Engine - ## PRIVATE Compile the provided `expression` into a regex pattern that can be used @@ -57,13 +50,6 @@ type Engine ## The `Data.Text.Regex.Engine.Pattern` interface. type Pattern - ## PRIVATE - - A type to represent the pattern that results from compilation. - - The type may contain any fields necessary for its implementation. - type Pattern - ## PRIVATE Tries to match the provided `input` against the pattern `self`. @@ -144,13 +130,6 @@ type Pattern ## The `Data.Text.Regex.Engine.Match` interface. type Match - ## PRIVATE - - A type to represent the match. - - This type may contain any fields necessary. - type Match - ## PRIVATE Gets the text matched by the group with the provided identifier, or 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 0543299f8834..50585adec25d 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 @@ -79,7 +79,7 @@ type Engine Arguments: - engine_opts: Options for regex matching that are specific to this engine. - type Engine (engine_opts : Vector.Vector Option) + Engine_Data (engine_opts : Vector.Vector Option) ## ADVANCED @@ -125,7 +125,7 @@ type Engine Syntax_Error ("The regex could not be compiled: " + err.getMessage) other -> other - Pattern internal_pattern all_options self + Pattern_Data internal_pattern all_options self ## ADVANCED @@ -159,7 +159,7 @@ type Pattern - internal_pattern: The internal representation of the compiled pattern. - options: The vector of options with which this pattern was built. - engine: A handle to the engine that built this pattern. - type Pattern (internal_pattern : Java_Pattern) (options : Vector.Vector (Global_Option.Option | Option)) (engine : Engine) + type Pattern_Data (internal_pattern : Java_Pattern) (options : Vector.Vector (Global_Option.Option | Option)) (engine : Engine) ## PRIVATE @@ -596,7 +596,7 @@ type Match - region_start: The start of the region over which the match was made. - region_end: The end of the region over which the match was made. - input: The input text that was being matched. - type Match (internal_match : Java_Matcher) (region_start : Integer) (region_end : Integer) (input : Text) + type Match_Data (internal_match : Java_Matcher) (region_start : Integer) (region_end : Integer) (input : Text) ## Gets the text matched by the group with the provided identifier, or `Nothing` if the group did not participate in the match. If no such group @@ -836,14 +836,14 @@ type Option ## Specifies that the input expression to the pattern be treated as a sequence of literal characters. Metacharacters and escape sequences have no special meaning in this mode. - type Literal_Pattern + Literal_Pattern ## Disables anchoring to the region's boundaries. By default, the regex engine will allow `^` and `$` to match the boundaries of a restricted region. With this option specified, they will only match the start and end of the input. - type No_Anchoring_Bounds + No_Anchoring_Bounds ## Enables transparent bounds. @@ -853,11 +853,11 @@ type Option Without this flag, the region boundaries are treated as opaque, meaning that the above constructs will fail to match anything outside the region. - type Transparent_Bounds + Transparent_Bounds ## Specifies that only the unix line ending `''\n'` be considered in the behaviour of the `^` and `$` special characters. - type Unix_Lines + Unix_Lines ## PRIVATE @@ -905,7 +905,8 @@ Invalid_Bounds_Error.to_display_text = Arguments: - message: The text of the message to display to users. -type Mode_Error (message : Text) +type Mode_Error + Mode_Error_Data (message : Text) ## PRIVATE @@ -919,7 +920,8 @@ Mode_Error.to_display_text self = self.message.to_text Arguments: - opt: The option that was not valid for this regex engine. -type Invalid_Option_Error (opt : Any) +type Invalid_Option_Error + Invalid_Option_Error_Data (opt : Any) ## PRIVATE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Mode.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Mode.enso index 1db9cf80eaab..31c9b5bf2aae 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Mode.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Mode.enso @@ -4,8 +4,6 @@ to matching on the `Full` content of the input text. from Standard.Base import all -from Standard.Base.Data.Text.Matching_Mode import First -from Standard.Base.Data.Text.Matching_Mode export First type Mode @@ -16,10 +14,10 @@ type Mode Integer ## The regex will make all possible matches. - type All + All ## The regex will only match if the _entire_ text matches. - type Full + Full ## The regex will only match within the region defined by start..end. @@ -32,5 +30,5 @@ type Mode The `start` and `end` indices range over _characters_ in the text. The precise definition of `character` is, for the moment, defined by the regular expression engine itself. - type Bounded (start : Integer) (end : Integer) (mode : (First | Integer | All | Full) = All) + Bounded (start : Integer) (end : Integer) (mode : (First | Integer | All | Full) = All) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso index 0123ce18425c..fb8e1f965098 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso @@ -83,7 +83,7 @@ find_codepoint_ranges text subrange = Range 0 indices.first By_Index indices -> case indices of - Vector.Vector _ -> + Vector.Vector_Data _ -> if indices.length == 1 then resolve_index_or_range text indices.first else batch_resolve_indices_or_ranges text indices _ -> resolve_index_or_range text indices @@ -97,7 +97,7 @@ find_codepoint_ranges text subrange = if start >= len then Range 0 0 else range = Range start text.length step find_codepoint_ranges text (By_Index range) - Range _ _ _ -> + Range_Data _ _ _ -> find_codepoint_ranges text (By_Index subrange) type Codepoint_Ranges diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time.enso index 56710721cd1b..d3e184605ddb 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time.enso @@ -21,7 +21,7 @@ polyglot java import org.enso.base.Time_Utils example_now = Time.now now : Time -now = Time ZonedDateTime.now +now = Time_Data ZonedDateTime.now ## Obtains an instance of `Time` from a year, month, day, hour, minute, second, nanosecond and timezone. @@ -55,8 +55,8 @@ now = Time ZonedDateTime.now example_new = Time.new 1986 8 5 new : Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> Integer -> Zone -> Time ! Time_Error new year (month = 1) (day = 1) (hour = 0) (minute = 0) (second = 0) (nanosecond = 0) (zone = Zone.system) = - Panic.catch_java Any (Time (ZonedDateTime.of year month day hour minute second nanosecond zone.internal_zone_id)) java_exception-> - Error.throw (Time_Error java_exception.getMessage) + Panic.catch_java Any (Time_Data (ZonedDateTime.of year month day hour minute second nanosecond zone.internal_zone_id)) java_exception-> + Error.throw (Time_Error_Data java_exception.getMessage) ## ALIAS Time from Text @@ -141,9 +141,9 @@ parse text pattern=Nothing locale=Locale.default = result = Panic.recover Any <| case pattern of Nothing -> Time_Utils.parse_time text Text -> Time_Utils.parse_time_format text pattern locale.java_locale - _ -> Panic.throw (Time_Error "An invalid pattern was provided.") - Time result . map_error <| case _ of - Polyglot_Error err -> Time_Error err.getMessage + _ -> Panic.throw (Time_Error_Data "An invalid pattern was provided.") + Time_Data result . map_error <| case _ of + Polyglot_Error_Data err -> Time_Error_Data err.getMessage x -> x type Time @@ -163,7 +163,7 @@ type Time For example, the value "2nd October 2007 at 13:45.30.123456789 +02:00 in the Europe/Paris timezone" can be stored as `Time`. - type Time internal_zoned_date_time + Time_Data internal_zoned_date_time ## Get the year portion of the time. @@ -316,7 +316,7 @@ type Time exaomple_at_zone = Time.new 2020 . at_zone (Zone.new -4) at_zone : Zone -> Time - at_zone self zone = Time (self.internal_zoned_date_time . withZoneSameInstant zone.internal_zone_id) + at_zone self zone = Time_Data (self.internal_zoned_date_time . withZoneSameInstant zone.internal_zone_id) ## Add the specified amount of time to this instant to produce a new instant. @@ -331,7 +331,7 @@ type Time example_plus = Time.new 2020 + 15.years + 3.hours + : Duration -> Time - + self amount = Time (self . internal_zoned_date_time . plus amount.internal_period . plus amount.internal_duration) + + self amount = Time_Data (self . internal_zoned_date_time . plus amount.internal_period . plus amount.internal_duration) ## Subtract the specified amount of time from this instant to get a new instant. @@ -347,7 +347,7 @@ type Time example_minus = Time.new 2020 - 1.year - 9.months - : Duration -> Time - - self amount = Time (self . internal_zoned_date_time . minus amount.internal_period . minus amount.internal_duration) + - self amount = Time_Data (self . internal_zoned_date_time . minus amount.internal_period . minus amount.internal_duration) ## Convert this time to text using the default formatter. @@ -468,16 +468,9 @@ type Time ## Compares two Time for equality. == : Time -> Boolean == self that = case that of - Time _ -> self.internal_zoned_date_time.equals that.internal_zoned_date_time + Time_Data _ -> self.internal_zoned_date_time.equals that.internal_zoned_date_time _ -> False type Time_Error - - ## UNSTABLE - - An error produced while working with time. - - Arguments: - - error_message: The message for the error. - type Time_Error error_message + Time_Error_Data error_message diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Zone.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Zone.enso index 6d8104c5ac9c..1fa5303c8ee4 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Zone.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Zone.enso @@ -12,7 +12,7 @@ polyglot java import java.time.ZoneOffset example_system = Zone.system system : Zone -system = Zone ZoneId.systemDefault +system = Zone_Data ZoneId.systemDefault ## ALIAS Current Time Zone @@ -109,7 +109,7 @@ type Zone A time zone can be eiter offset-based like "-06:00" or id-based like "Europe/Paris". - type Zone internal_zone_id + Zone_Data internal_zone_id ## Get the unique timezone ID. 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 2709e9f3cfee..fd1d9e1be54c 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 @@ -24,7 +24,7 @@ new : Number -> (Number -> Any) -> Vector Any new length constructor = arr = Array.new length 0.up_to length . each ix-> arr.set_at ix (constructor ix) - Vector arr + Vector_Data arr ## Creates a new vector of the given length, filling the elements with the provided constant. @@ -44,7 +44,7 @@ fill : Number -> Any -> Vector Any fill length ~item = arr = Array.new length 0.up_to length . each ix-> arr.set_at ix item - Vector arr + Vector_Data arr ## Creates a new vector builder instance. @@ -114,7 +114,7 @@ type Vector A vector containing 50 elements, each being the number `42`, can be created by: Vector.fill length=50 item=42 - type Vector to_array + Vector_Data to_array ## Returns the number of elements stored in this vector. @@ -462,7 +462,7 @@ type Vector self.fold 0 i-> vec-> Array.copy vec.to_array 0 arr i vec.length i + vec.length - Vector arr + Vector_Data arr ## Applies a function to each element of the vector, returning the vector of results. @@ -593,7 +593,7 @@ type Vector arr = Array.new (self_len + that.length) Array.copy self.to_array 0 arr 0 self_len Array.copy that.to_array 0 arr self_len that.length - Vector arr + Vector_Data arr ## Add `element` to the beginning of `self` vector. @@ -652,12 +652,12 @@ type Vector take self start end = slice_start = Math.max 0 start slice_end = Math.min self.length end - if slice_start >= slice_end then Vector (Array.new 0) else + if slice_start >= slice_end then Vector_Data (Array.new 0) else if (slice_start == 0) && (slice_end == self.length) then self else len = slice_end - slice_start arr = Array.new len Array.copy self.to_array slice_start arr 0 len - Vector arr + Vector_Data arr ## Creates a new vector with the first `count` elements in `self` removed. @@ -921,7 +921,7 @@ type Vector new_vec_arr.sort compare - Vector new_vec_arr + Vector_Data new_vec_arr ## UNSTABLE Keeps only unique elements within the Vector, removing any duplicates. @@ -1008,7 +1008,7 @@ type Builder @Tail_Call do_build new_builder start+1 stop builder = do_build Vector.new_builder 1 10 builder.to_vector - type Builder to_array length + Builder_Data to_array length ## Creates a new builder. @@ -1020,7 +1020,7 @@ type Builder Vector.new_builder new : Integer->Builder - new (capacity=1) = Builder (Array.new capacity) 0 + new (capacity=1) = Builder_Data (Array.new capacity) 0 ## Returns the current capacity (i.e. the size of the underlying storage) of this builder. @@ -1126,7 +1126,7 @@ type Builder old_array = self.to_array new_array = Array.new self.length Array.copy old_array 0 new_array 0 self.length - Vector new_array + Vector_Data new_array ## UNSTABLE @@ -1145,7 +1145,8 @@ Empty_Error.to_display_text self = "The vector is empty." Arguments: - vec: The vector that only has one element. -type Singleton_Error vec +type Singleton_Error + Singleton_Error_Data vec ## UNSTABLE @@ -1155,7 +1156,8 @@ Singleton_Error.to_display_text self = "The vector " + self.vec.to_text + " has only one element." ## PRIVATE -type Partition_Accumulator true_builder false_builder ix +type Partition_Accumulator + Partition_Accumulator_Data true_builder false_builder ix ## UNSTABLE 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 2c8c68015aba..04d1509f8a53 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 @@ -4,23 +4,19 @@ import Standard.Base.Runtime polyglot java import java.lang.IllegalArgumentException -## Dataflow errors. -type Error - - ## A type representing dataflow errors. +## 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 + 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: @@ -552,7 +548,8 @@ No_Such_Method_Error.method_name self = Arguments: - cause: A polyglot object corresponding to the original error. @Builtin_Type -type Polyglot_Error cause +type Polyglot_Error + Polyglot_Error_Data cause ## An error that occurs when the enso_project function is called in a file that is not part of a project. @@ -564,7 +561,8 @@ type Module_Not_In_Package_Error Arguments: - message: A description of the error condition. @Builtin_Type -type Arithmetic_Error message +type Arithmetic_Error + Arithmetic_Error_Data message ## An error that occurs when a program requests a read from an array index that is out of bounds in the array. @@ -573,7 +571,8 @@ type Arithmetic_Error message - 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 +type Invalid_Array_Index_Error + Invalid_Array_Index_Error_Data array index ## An error that occurs when an object is used as a function in a function call, but it cannot be called. @@ -581,7 +580,8 @@ type Invalid_Array_Index_Error array index Arguments: - target: The called object. @Builtin_Type -type Not_Invokable_Error target +type Not_Invokable_Error + Not_Invokable_Error_Data target ## An error that occurs when arguments used in a function call are invalid types for the function. @@ -589,14 +589,16 @@ type Not_Invokable_Error target Arguments: - arguments: The passed arguments. @Builtin_Type -type Unsupported_Argument_Types arguments +type Unsupported_Argument_Types + Unsupported_Argument_Types_Data 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 +type Module_Does_Not_Exist + Module_Does_Not_Exist_Data name ## An error that occurs when the specified value cannot be converted to a given type ## FIXME: please check @@ -604,7 +606,8 @@ type Module_Does_Not_Exist name Arguments: - target: ... @Builtin_Type -type Invalid_Conversion_Target_Error target +type Invalid_Conversion_Target_Error + Invalid_Conversion_Target_Error_Data target ## An error that occurs when the conversion from one type to another does not exist ## FIXME: please check @@ -622,7 +625,8 @@ type No_Such_Conversion_Error Arguments: - message: The message describing what implementation is missing. -type Unimplemented_Error message +type Unimplemented_Error + Unimplemented_Error_Data message ## UNSTABLE @@ -645,4 +649,4 @@ Unimplemented_Error.to_display_text self = "An implementation is missing: " + se example_unimplemented = Errors.unimplemented unimplemented : Text -> Void -unimplemented message="" = Panic.throw (Unimplemented_Error message) +unimplemented message="" = Panic.throw (Unimplemented_Error_Data message) 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 02267c98ae97..306023d07569 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 @@ -87,7 +87,7 @@ from project.Data.Range export all https://www.pivotaltracker.com/story/show/181403340 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, No_Matches_Found +from project.Data.Text.Matching export Case_Insensitive, Case_Insensitive_Data, Text_Matcher, Text_Matcher_Data, Regex_Matcher, Regex_Matcher_Data, No_Matches_Found from project.Data.Text export all hiding Encoding, Span, Text_Ordering from project.Data.Text.Encoding export Encoding, Encoding_Error from project.Data.Text.Text_Ordering export all 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 ad791ced9ca0..10116fb9c243 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,6 +1,7 @@ import Standard.Base.System.File ## Functionality for inspecting the current project. +@Builtin_Type type Project_Description ## A representation of an Enso project. @@ -8,8 +9,7 @@ type Project_Description 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 + Project_Description_Data prim_root_file prim_config ## Returns the root directory of the project. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso index 1b1dcbe1621a..63f3396ef694 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Nothing.enso @@ -1,15 +1,12 @@ from Standard.Base import Boolean, True -type Nothing - ## The type that has only a singleton value. Nothing in Enso is used as an - universal value to indicate the lack of presence of a 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 +## The type that has only a singleton value. Nothing in Enso is used as an + universal value to indicate the lack of presence of a value. + It is often used alongside a value of type a to provide a Maybe or + Option abstraction. +@Builtin_Type +type Nothing ## Checks if the type is an instance of `Nothing`. > Example 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 61b3d1edc94f..9154420d51e6 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,9 +1,5 @@ ## 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: diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso index ad7c5f03f611..d3d45d8c8055 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso @@ -79,7 +79,7 @@ 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_Data (Polyglot.get_source_location el)) else Nothing + loc = if Polyglot.has_source_location el then Source_Location_Data (Polyglot.get_source_location el) else Nothing name = Polyglot.get_executable_name el Stack_Trace_Element_Data name loc 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 771c5a940237..4f156c36bd44 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 @@ -6,7 +6,7 @@ from Standard.Base import all source file and code position within it. type Source_Location ## PRIVATE - type Source_Location_Data prim_location + Source_Location_Data prim_location ## UNSTABLE Pretty prints the location. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso index da74391ff404..d205bebe22fb 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Resource.enso @@ -19,16 +19,13 @@ 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. +## 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 + 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 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 f184d83f7b03..d09d433e9c96 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 @@ -622,7 +622,7 @@ type File opts = open_options . map (_.to_java) . to_array stream = handle_java_exceptions self (self.input_stream opts) resource = Managed_Resource.register stream close_stream - Input_Stream self resource + Input_Stream_Data self resource ## ADVANCED @@ -640,7 +640,7 @@ type File stream = handle_java_exceptions self <| self.output_stream opts resource = Managed_Resource.register stream close_stream - Output_Stream self resource + Output_Stream_Data self resource ## PRIVATE @@ -766,7 +766,7 @@ type Output_Stream - file: The file which the output stream will write into. - stream_resource: The internal resource that represents the underlying stream. - type Output_Stream file stream_resource + Output_Stream_Data file stream_resource ## ADVANCED @@ -856,7 +856,7 @@ type Input_Stream - file: The file from which the stream will read. - stream_resource: The internal resource that represents the underlying stream. - type Input_Stream file stream_resource + Input_Stream_Data file stream_resource ## ADVANCED 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 8b4d52ed2193..e19f2ae4df21 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 @@ -2,13 +2,8 @@ from Standard.Base import all from Standard.Base.Runtime import Stack_Trace_Element ## A representation of a dataflow warning attached to a value. +@Builtin_Type type Warning - ## PRIVATE - - The constructor to wrap primitive warnings. - @Builtin_Type - type Warning - ## UNSTABLE Returns the warning value – usually its explanation or other contents. 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 605db75911e9..dbd6fdbb9066 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala @@ -725,7 +725,8 @@ class Compiler( } if (reportDiagnostics(diagnostics)) { val count = diagnostics.map(_._2.collect { case e: IR.Error => e }.length).sum - println(s"Aborting due to ${count} errors.") + val warnCount = diagnostics.map(_._2.collect { case e: IR.Warning => e }.length).sum + println(s"Aborting due to ${count} errors and ${warnCount} warnings.") throw new CompilationAbortedException } } 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 3c1eba784c1d..a3c52d3eb4a3 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 @@ -6616,6 +6616,22 @@ object IR { override def diagnosticKeys(): Array[Any] = Array(ir.showCode(), reason) } + + case class NonUnitTypeUsedOnValueLevel(ir: IR.Name) extends Warning { + + /** @return a human-readable description of this error condition. + */ + override def message: String = + s"A non-unit type ${ir.name} is used on value level." + + " This is probably an error" + + /** The location at which the diagnostic occurs. */ + override val location: Option[IdentifiedLocation] = ir.location + + /** The important keys identifying identity of the diagnostic + */ + override def diagnosticKeys(): Array[Any] = Array(ir.name) + } } // === Errors =============================================================== @@ -7863,7 +7879,7 @@ object IR { with IRKind.Primitive { override protected var id: Identifier = randomId - /** Creates a copy of `this`. + /** Creates a copy of `this`. * * @param atomName the name of the atom the method was being redefined * on diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala index 41a888e75cd2..dfdaa37f542b 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala @@ -4,11 +4,7 @@ import org.enso.compiler.context.{FreshNameSupply, InlineContext, ModuleContext} import org.enso.compiler.core.IR import org.enso.compiler.core.ir.MetadataStorage.ToPair import org.enso.compiler.data.BindingsMap -import org.enso.compiler.data.BindingsMap.{ - Resolution, - ResolvedConstructor, - ResolvedMethod -} +import org.enso.compiler.data.BindingsMap.{Resolution, ResolvedMethod} import org.enso.compiler.exception.CompilerError import org.enso.compiler.pass.IRPass import org.enso.compiler.pass.analyse.{AliasAnalysis, BindingAnalysis} @@ -160,6 +156,13 @@ case object GlobalNames extends IRPass { fun.passData.remove(ExpressionAnnotations) app } + case Right(res @ BindingsMap.ResolvedType(_, tp)) => + val warned = if (tp.members.nonEmpty) { + lit.addDiagnostic(IR.Warning.NonUnitTypeUsedOnValueLevel(lit)) + } else { + lit + } + warned.updateMetadata(this -->> BindingsMap.Resolution(res)) case Right(value) => lit.updateMetadata(this -->> BindingsMap.Resolution(value)) } @@ -223,16 +226,35 @@ case object GlobalNames extends IRPass { app.arguments.map( _.mapExpressions(processExpression(_, bindings, freshNameSupply)) ) - val newApp: Option[IR.Expression] = for { + + val appData = for { thisArgPos <- findThisPosition(processedArgs) thisArg = processedArgs(thisArgPos) thisArgResolution <- thisArg.value.getMetadata(this) funAsVar <- asGlobalVar(processedFun) - cons <- resolveToCons(thisArgResolution, funAsVar) - newFun = - buildSymbolFor(cons, freshNameSupply).setLocation(funAsVar.location) - newArgs = processedArgs.patch(thisArgPos, Nil, 1) - } yield buildConsApplication(app, cons.cons, newFun, newArgs) + cons <- resolveQualName(thisArgResolution, funAsVar) + } yield (thisArgPos, funAsVar, cons) + + val newApp = appData.flatMap { + case (_, funAsVar, BindingsMap.ResolvedType(_, tp)) => + if (tp.members.nonEmpty) { + Some( + app + .copy(function = processedFun, arguments = processedArgs) + .addDiagnostic(IR.Warning.NonUnitTypeUsedOnValueLevel(funAsVar)) + ) + } else { None } + case ( + thisArgPos, + funAsVar, + cons: BindingsMap.ResolvedConstructor + ) => + val newFun = + buildSymbolFor(cons, freshNameSupply).setLocation(funAsVar.location) + val newArgs = processedArgs.patch(thisArgPos, Nil, 1) + Some(buildConsApplication(app, cons.cons, newFun, newArgs)) + case _ => None + } newApp.getOrElse( app.copy(function = processedFun, arguments = processedArgs) ) @@ -262,10 +284,10 @@ case object GlobalNames extends IRPass { .updateMetadata(this -->> BindingsMap.Resolution(cons)) } - private def resolveToCons( + private def resolveQualName( thisResolution: BindingsMap.Resolution, consName: IR.Name.Literal - ): Option[BindingsMap.ResolvedConstructor] = + ): Option[BindingsMap.ResolvedName] = thisResolution.target match { case BindingsMap.ResolvedModule(module) => val resolution = module @@ -277,8 +299,8 @@ case object GlobalNames extends IRPass { ) .resolveExportedName(consName.name) resolution match { - case Right(cons @ ResolvedConstructor(_, _)) => Some(cons) - case _ => None + case Right(res) => Some(res) + case _ => None } case _ => None } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodCalls.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodCalls.scala index b8fa19f47214..8527e730d212 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodCalls.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodCalls.scala @@ -84,7 +84,7 @@ object MethodCalls extends IRPass { targetBindings match { case Some(bindings) => val resolution = - bindings.exportedSymbols.get(name.name.toLowerCase) + bindings.exportedSymbols.get(name.name) resolution match { case Some(List(resolution)) => val newName = diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala index dea3f4a4ac4b..ee6b1e27755b 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala @@ -77,7 +77,7 @@ case object OverloadsResolution extends IRPass { IR.Error.Redefined .Method(method.typeName, method.methodName, method.location) } else { - types.find(_.name.name.equalsIgnoreCase(method.methodName.name)) match { + types.find(_.name.name.equals(method.methodName.name)) match { case Some(clashedAtom) if method.typeName.isEmpty => IR.Error.Redefined.MethodClashWithAtom( clashedAtom.name, From f3b481454a8d4c90831f1a76e56f529a0f842184 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 11 Aug 2022 17:19:41 +0200 Subject: [PATCH 043/110] more progress, same amount of suffering --- .../Base/0.0.0-dev/src/Data/Array.enso | 10 +-- .../Standard/Base/0.0.0-dev/src/Data/Map.enso | 6 +- .../src/Data/Ordering/Comparator.enso | 2 +- .../Base/0.0.0-dev/src/Data/Regression.enso | 4 +- .../0.0.0-dev/src/Data/Text/Extensions.enso | 22 ++--- .../src/Data/Text/Regex/Engine/Default.enso | 44 +++++----- .../Base/0.0.0-dev/src/Data/Text/Span.enso | 14 ++-- .../src/Data/Text/Text_Sub_Range.enso | 80 +++++++++---------- .../Base/0.0.0-dev/src/Data/Time.enso | 4 +- .../0.0.0-dev/src/Data/Time/Duration.enso | 28 +++---- .../0.0.0-dev/src/Data/Time/Time_Of_Day.enso | 26 +++--- .../Base/0.0.0-dev/src/Data/Time/Zone.enso | 4 +- .../Base/0.0.0-dev/src/Data/Vector.enso | 26 +++--- .../Base/0.0.0-dev/src/Error/Common.enso | 6 +- .../Standard/Base/0.0.0-dev/src/Function.enso | 13 ++- .../Standard/Base/0.0.0-dev/src/Polyglot.enso | 13 ++- .../Standard/Base/0.0.0-dev/src/Random.enso | 8 +- .../Standard/Base/0.0.0-dev/src/Runtime.enso | 2 +- .../Base/0.0.0-dev/src/System/File.enso | 27 +++---- .../Base/0.0.0-dev/src/System/Process.enso | 13 +-- .../Standard/Base/0.0.0-dev/src/Warning.enso | 12 +-- 21 files changed, 176 insertions(+), 188 deletions(-) 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 index 21b349b56984..2b6b10679e4a 100644 --- 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 @@ -1,12 +1,8 @@ import Standard.Base.Data.Vector -## Utilities for working with primitive arrays. +## The type of primitive mutable arrays. +@Builtin_Type type Array - - ## The type of primitive mutable arrays. - @Builtin_Type - type Array - ## Gets the element at index in the array this. Arguments: @@ -84,7 +80,7 @@ type Array [1, 2, 3, 4].to_array.to_default_visualization_data to_default_visualization_data : Text to_default_visualization_data self = - Vector.Vector self . to_default_visualization_data + Vector.Vector_Data self . to_default_visualization_data ## Creates an array with length 0. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso index 35cbdb33b124..68dd0629249a 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso @@ -40,7 +40,7 @@ singleton key value = Bin 1 key value Tip Tip example_from_vector = Map.from_vector [[1, 2], [3, 4]] from_vector : Vector.Vector Any -> Map -from_vector vec = vec.fold Map.empty (m -> el -> m.insert (el.at 0) (el.at 1)) +from_vector vec = vec.fold empty (m -> el -> m.insert (el.at 0) (el.at 1)) ## A key-value store. This type assumes all keys are pairwise comparable, using the `<`, `>` and `==` operators. @@ -445,7 +445,7 @@ type Map first : Pair first self = first p m = case m of - Bin _ k v l _ -> @Tail_Call first (Pair k v) l + Bin _ k v l _ -> @Tail_Call first (Pair_Data k v) l Tip -> p first Nothing self @@ -454,7 +454,7 @@ type Map last : Pair last self = last p m = case m of - Bin _ k v _ r -> @Tail_Call last (Pair k v) r + Bin _ k v _ r -> @Tail_Call last (Pair_Data k v) r Tip -> p last Nothing self diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Comparator.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Comparator.enso index 35347d973513..eadc902e1fa6 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Comparator.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Comparator.enso @@ -32,5 +32,5 @@ for_text_ordering text_ordering = txt_cmp a b = Natural_Order.compare a b text_ordering.case_sensitive . to_sign new.withCustomTextComparator txt_cmp False -> case text_ordering.case_sensitive of - Case_Insensitive locale -> new.withCaseInsensitivity locale.java_locale + Case_Insensitive_Data locale -> new.withCaseInsensitivity locale.java_locale _ -> new diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Regression.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Regression.enso index bda9f798dc0d..2100c642b50a 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Regression.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Regression.enso @@ -19,7 +19,7 @@ type Model ## Use Least Squares to fit a line to the data. fit_least_squares : Vector -> Vector -> Model -> Fitted_Model ! Illegal_Argument_Error | Fit_Error fit_least_squares known_xs known_ys model=Linear_Model = - Illegal_Argument_Error.handle_java_exception <| Fit_Error.handle_java_exception <| case model of + Illegal_Argument_Error.handle_java_exception <| handle_fit_java_exception <| case model of Linear_Model intercept -> fitted = if intercept.is_nothing then Regression.fit_linear known_xs.to_array known_ys.to_array else Regression.fit_linear known_xs.to_array known_ys.to_array intercept @@ -105,5 +105,5 @@ Fit_Error.to_display_text : Text Fit_Error.to_display_text self = "Could not fit the model: " + self.message.to_text ## PRIVATE -Fit_Error.handle_java_exception = +handle_fit_java_exception = Panic.catch_java FitError handler=(java_exception-> Error.throw (Fit_Error_Data java_exception.getMessage)) 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 5bc8a42d99a1..4627b862a51a 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 @@ -119,14 +119,14 @@ Text.at self index = True -> length = self.length new_index = index + length - if new_index < 0 then Error.throw (Index_Out_Of_Bounds_Error index length) else + if new_index < 0 then Error.throw (Index_Out_Of_Bounds_Error_Data index length) else self.at new_index False -> iterator = BreakIterator.getCharacterInstance iterator.setText self first = iterator.next index next = if first == -1 then -1 else iterator.next - if (next == -1) then (Error.throw (Index_Out_Of_Bounds_Error index self.length)) else + if (next == -1) then (Error.throw (Index_Out_Of_Bounds_Error_Data index self.length)) else Text_Utils.substring self first next ## ALIAS Get Characters @@ -364,7 +364,7 @@ Text.split : Text -> (Text_Matcher | Regex_Matcher) -> Vector.Vector Text Text.split self delimiter="," matcher=Text_Matcher_Data = if delimiter.is_empty then Error.throw (Illegal_Argument_Error "The delimiter cannot be empty.") else case matcher of Text_Matcher_Data case_sensitivity -> - delimiters = Vector.Vector <| case case_sensitivity of + delimiters = Vector.Vector_Data <| case case_sensitivity of True -> Text_Utils.span_of_all self delimiter Case_Insensitive_Data locale -> @@ -552,7 +552,7 @@ Text.words self keep_whitespace=False = '\na\nb\n'.lines keep_endings=True == ['\n', 'a\n', 'b\n'] Text.lines : Boolean -> Vector.Vector Text Text.lines self keep_endings=False = - Vector.Vector (Text_Utils.split_on_lines self keep_endings) + Vector.Vector_Data (Text_Utils.split_on_lines self keep_endings) ## Checks whether `self` is equal to `that`, ignoring the case of the texts. @@ -674,7 +674,7 @@ Text.insert : Integer -> Text -> Text ! Index_Out_Of_Bounds_Error Text.insert self index that = len = self.length idx = if index < 0 then len + index + 1 else index - if (idx < 0) || (idx > len) then Error.throw (Index_Out_Of_Bounds_Error index len) else + if (idx < 0) || (idx > len) then Error.throw (Index_Out_Of_Bounds_Error_Data index len) else if idx == 0 then that + self else if idx == len then self + that else pre = self.take (Range_Data 0 idx) @@ -739,7 +739,7 @@ Text.is_whitespace self = Text.bytes : Encoding -> Problem_Behavior -> Vector.Vector Byte Text.bytes self encoding on_problems=Report_Warning = result = Encoding_Utils.get_bytes self (encoding . to_java_charset) - vector = Vector.Vector result.result + vector = Vector.Vector_Data result.result if result.warnings.is_nothing then vector else on_problems.attach_problems_after vector [Encoding_Error result.warnings] @@ -817,7 +817,7 @@ Text.from_utf_8 bytes on_problems=Report_Warning = "Hello".char_vector Text.char_vector : Vector.Vector Integer -Text.char_vector self = Vector.Vector (Text_Utils.get_chars self) +Text.char_vector self = Vector.Vector_Data (Text_Utils.get_chars self) ## Takes a vector of characters and returns the text that results from it. @@ -840,7 +840,7 @@ Text.from_char_vector chars = Text_Utils.from_chars chars.to_array "Hello".codepoints Text.codepoints : Vector.Vector Integer -Text.codepoints self = Vector.Vector (Text_Utils.get_codepoints self) +Text.codepoints self = Vector.Vector_Data (Text_Utils.get_codepoints self) ## Takes an array of numbers and returns the text resulting from interpreting it as a sequence of Unicode codepoints. @@ -1487,8 +1487,8 @@ Text.location_of_all : Text -> Matcher -> [Span] Text.location_of_all self term="" matcher=Text_Matcher_Data = case matcher of Text_Matcher_Data case_sensitive -> if term.is_empty then Vector.new (self.length + 1) (ix -> Span_Data (Range_Data ix ix) self) else case case_sensitive of True -> - codepoint_spans = Vector.Vector <| Text_Utils.span_of_all self term - grahpeme_ixes = Vector.Vector <| Text_Utils.utf16_indices_to_grapheme_indices self (codepoint_spans.map .codeunit_start).to_array + codepoint_spans = Vector.Vector_Data <| Text_Utils.span_of_all self term + grahpeme_ixes = Vector.Vector_Data <| Text_Utils.utf16_indices_to_grapheme_indices self (codepoint_spans.map .codeunit_start).to_array ## While the codepoint_spans may have different code unit lengths from our term, the `length` counted in grapheme clusters is guaranteed to be the same. @@ -1497,7 +1497,7 @@ Text.location_of_all self term="" matcher=Text_Matcher_Data = case matcher of end = start+offset Span_Data (Range_Data start end) self Case_Insensitive_Data locale -> - grapheme_spans = Vector.Vector <| Text_Utils.span_of_all_case_insensitive self term locale.java_locale + grapheme_spans = Vector.Vector_Data <| Text_Utils.span_of_all_case_insensitive self term locale.java_locale grapheme_spans.map grapheme_span-> Span_Data (Range_Data grapheme_span.grapheme_start grapheme_span.grapheme_end) self Regex_Matcher_Data _ _ _ _ _ -> diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine/Default.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Engine/Default.enso index 50585adec25d..1a552a6264be 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 @@ -67,7 +67,7 @@ polyglot java import org.enso.base.Text_Utils engine_opts = [Default_Engine.Literal_Pattern] Default_Engine.new engine_opts new : Vector.Vector Option -> Engine -new opts=[] = Engine opts +new opts=[] = Engine_Data opts ## The default implementation of the `Data.Text.Regex.Engine.Engine` interface. type Engine @@ -120,7 +120,7 @@ type Engine Java_Pattern.compile (unicode_regex.transform expression) options_bitmask internal_pattern = maybe_java_pattern.map_error case _ of - Polyglot_Error err -> + Polyglot_Error_Data err -> if err.is_a PatternSyntaxException . not then err else Syntax_Error ("The regex could not be compiled: " + err.getMessage) other -> other @@ -159,7 +159,7 @@ type Pattern - internal_pattern: The internal representation of the compiled pattern. - options: The vector of options with which this pattern was built. - engine: A handle to the engine that built this pattern. - type Pattern_Data (internal_pattern : Java_Pattern) (options : Vector.Vector (Global_Option.Option | Option)) (engine : Engine) + Pattern_Data (internal_pattern : Java_Pattern) (options : Vector.Vector (Global_Option.Option | Option)) (engine : Engine) ## PRIVATE @@ -266,7 +266,7 @@ type Pattern Match internal_matcher start end input Integer -> if mode < 0 then Panic.throw <| - Mode_Error "Cannot match a negative number of times." + Mode_Error_Data "Cannot match a negative number of times." builder = Vector.new_builder @@ -313,7 +313,7 @@ type Pattern if internal_matcher.matches.not then Nothing else Match internal_matcher start end input Mode.Bounded _ _ _ -> Panic.throw <| - Mode_Error "Modes cannot be recursive." + Mode_Error_Data "Modes cannot be recursive." case mode of Mode.Bounded start end sub_mode -> @@ -341,8 +341,8 @@ type Pattern pattern.matches input matches : Text -> Boolean matches self input = case self.match input mode=Mode.Full of - Match _ _ _ _ -> True - Vector.Vector _ -> True + Match_Data _ _ _ _ -> True + Vector.Vector_Data _ -> True _ -> False ## ADVANCED @@ -412,8 +412,8 @@ type Pattern find self input mode=Mode.All = matches = self.match input mode case matches of - Match _ _ _ _ -> matches.group 0 - Vector.Vector _ -> matches.map (_.group 0) + Match_Data _ _ _ _ -> matches.group 0 + Vector.Vector_Data _ -> matches.map (_.group 0) _ -> matches ## ADVANCED @@ -468,17 +468,17 @@ type Pattern Mode.First -> 2 Integer -> if mode < 0 then Panic.throw <| - Mode_Error "Cannot match a negative number of times." + Mode_Error_Data "Cannot match a negative number of times." mode + 1 Mode.All -> -1 Mode.Full -> Panic.throw <| - Mode_Error "Splitting on a full match yields an empty text." + Mode_Error_Data "Splitting on a full match yields an empty text." Mode.Bounded _ _ _ -> Panic.throw <| - Mode_Error "Splitting on a bounded region is not well-defined." + Mode_Error_Data "Splitting on a bounded region is not well-defined." splits = self.internal_pattern.split input limit - Vector.Vector splits + Vector.Vector_Data splits ## ADVANCED @@ -537,7 +537,7 @@ type Pattern internal_matcher.replaceFirst replacement Integer -> if mode < 0 then Panic.throw <| - Mode_Error "Cannot replace a negative number of times." + Mode_Error_Data "Cannot replace a negative number of times." internal_matcher = self.build_matcher input start end buffer = StringBuffer.new @@ -555,7 +555,7 @@ type Pattern internal_matcher.replaceAll replacement Mode.Full -> case self.match input mode=Mode.Full of - Match _ _ _ _ -> self.replace input replacement Mode.First + Match_Data _ _ _ _ -> self.replace input replacement Mode.First Nothing -> input Matching_Mode.Last -> all_matches = self.match input @@ -576,11 +576,11 @@ type Pattern internal_matcher.appendTail buffer buffer.to_text Mode.Bounded _ _ _ -> Panic.throw <| - Mode_Error "Modes cannot be recursive." + Mode_Error_Data "Modes cannot be recursive." case mode of Mode.Bounded _ _ _ -> Panic.throw <| - Mode_Error "Bounded replacements are not well-formed." + Mode_Error_Data "Bounded replacements are not well-formed." _ -> do_replace_mode mode 0 (Text_Utils.char_length input) ## The default implementation of the `Data.Text.Regex.Engine.Match` interface. @@ -596,7 +596,7 @@ type Match - region_start: The start of the region over which the match was made. - region_end: The end of the region over which the match was made. - input: The input text that was being matched. - type Match_Data (internal_match : Java_Matcher) (region_start : Integer) (region_end : Integer) (input : Text) + Match_Data (internal_match : Java_Matcher) (region_start : Integer) (region_end : Integer) (input : Text) ## Gets the text matched by the group with the provided identifier, or `Nothing` if the group did not participate in the match. If no such group @@ -684,7 +684,7 @@ type Match matcg.named_groups default="UNMATCHED" named_groups : (a : Any) -> Map Text (Text | a) named_groups self default=Nothing = - group_names = Vector.Vector <| + group_names = Vector.Vector_Data <| Regex_Utils.get_group_names self.internal_match.pattern pairs = group_names.map name-> value = case self.group name of @@ -772,7 +772,7 @@ type Match span : Integer | Text -> Utf_16_Span | Nothing ! Regex.No_Such_Group_Error span self id = case self.group id of Nothing -> Nothing - _ -> Utf_16_Span (Range (self.start id) (self.end id)) self.input + _ -> Utf_16_Span_Data (Range_Data (self.start id) (self.end id)) self.input ## Returns the start character index of the match's region. @@ -821,7 +821,7 @@ type Match - id: The group identifier with which the error is associated. handle_error : Any -> (Text | Integer) -> Any handle_error error id = case error of - Polyglot_Error err -> + Polyglot_Error_Data err -> is_ioob = err.is_a IndexOutOfBoundsException is_iae = err.is_a IllegalArgumentException maps_to_no_such_group = is_ioob || is_iae @@ -878,7 +878,7 @@ from_enso_options opts = Global_Option.Ascii_Matching -> [] No_Anchoring_Bounds -> [] Transparent_Bounds -> [] - other -> Panic.throw (Invalid_Option_Error other) + other -> Panic.throw (Invalid_Option_Error_Data other) options_bitmask = java_flags.fold 0 .bit_or diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Span.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Span.enso index 52f6871b6af8..8511ec7bf23a 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Span.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Span.enso @@ -136,7 +136,7 @@ type Utf_16_Span case self.start == self.end of True -> grapheme_ix = Text_Utils.utf16_index_to_grapheme_index self.text self.start - Span_Data (Range grapheme_ix grapheme_ix) self.text + Span_Data (Range_Data grapheme_ix grapheme_ix) self.text False -> grapheme_ixes = Text_Utils.utf16_indices_to_grapheme_indices self.text [self.start, self.end - 1].to_array grapheme_first = grapheme_ixes.at 0 @@ -146,7 +146,7 @@ type Utf_16_Span only a part of a grapheme were contained in our original span, the resulting span will be extended to contain this whole grapheme. grapheme_end = grapheme_last + 1 - Span_Data (Range grapheme_first grapheme_end) self.text + Span_Data (Range_Data grapheme_first grapheme_end) self.text ## PRIVATE Utility function taking a range pointing at grapheme clusters and converting @@ -156,19 +156,19 @@ range_to_char_indices text range = if range.step != 1 then Error.throw (Illegal_ len = text.length start = if range.start < 0 then range.start + len else range.start end = if range.end == Nothing then len else (if range.end < 0 then range.end + len else range.end) - is_valid = (Range 0 len+1).contains + is_valid = (Range_Data 0 len+1).contains case (Pair_Data (is_valid start) (is_valid end)) of - Pair_Data False _ -> Error.throw (Index_Out_Of_Bounds_Error range.start len) - Pair_Data True False -> Error.throw (Index_Out_Of_Bounds_Error range.end len) + Pair_Data False _ -> Error.throw (Index_Out_Of_Bounds_Error_Data range.start len) + Pair_Data True False -> Error.throw (Index_Out_Of_Bounds_Error_Data range.end len) Pair_Data True True -> - if start>=end then (Range 0 0) else + if start>=end then (Range_Data 0 0) else iterator = BreakIterator.getCharacterInstance iterator.setText text start_index = iterator.next start end_index = iterator.next (end - start) - Range start_index end_index + Range_Data start_index end_index Span.from (that:Utf_16_Span) = that.to_grapheme_span Utf_16_Span.from (that:Span) = that.to_utf_16_span diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso index fb8e1f965098..76b6464dced8 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso @@ -40,47 +40,47 @@ type Text_Sub_Range While the input ranges may have varying steps, they are processed and split in such a way that the ranges returned by this method always have a step equal to 1. -find_codepoint_ranges : Text -> (Text_Sub_Range | Index_Sub_Range | Range) -> (Range | Codepoint_Ranges) +find_codepoint_ranges : Text -> (Text_Sub_Range | Index_Sub_Range | Range) -> (Range_Data | Codepoint_Ranges) find_codepoint_ranges text subrange = case subrange of Before delimiter -> - if delimiter.is_empty then (Range 0 0) else + if delimiter.is_empty then (Range_Data 0 0) else span = Text_Utils.span_of text delimiter - if span.is_nothing then (Range 0 (Text_Utils.char_length text)) else - (Range 0 span.codeunit_start) + if span.is_nothing then (Range_Data 0 (Text_Utils.char_length text)) else + (Range_Data 0 span.codeunit_start) Before_Last delimiter -> - if delimiter.is_empty then (Range 0 (Text_Utils.char_length text)) else + if delimiter.is_empty then (Range_Data 0 (Text_Utils.char_length text)) else span = Text_Utils.last_span_of text delimiter - if span.is_nothing then (Range 0 (Text_Utils.char_length text)) else - (Range 0 span.codeunit_start) + if span.is_nothing then (Range_Data 0 (Text_Utils.char_length text)) else + (Range_Data 0 span.codeunit_start) After delimiter -> - if delimiter.is_empty then (Range 0 (Text_Utils.char_length text)) else + if delimiter.is_empty then (Range_Data 0 (Text_Utils.char_length text)) else span = Text_Utils.span_of text delimiter - if span.is_nothing then (Range 0 0) else - (Range span.codeunit_end (Text_Utils.char_length text)) + if span.is_nothing then (Range_Data 0 0) else + (Range_Data span.codeunit_end (Text_Utils.char_length text)) After_Last delimiter -> - if delimiter.is_empty then (Range 0 0) else + if delimiter.is_empty then (Range_Data 0 0) else span = Text_Utils.last_span_of text delimiter - if span.is_nothing then (Range 0 0) else - (Range span.codeunit_end (Text_Utils.char_length text)) + if span.is_nothing then (Range_Data 0 0) else + (Range_Data span.codeunit_end (Text_Utils.char_length text)) First count -> - if count <= 0 then (Range 0 0) else + if count <= 0 then (Range_Data 0 0) else iterator = BreakIterator.getCharacterInstance iterator.setText text start_index = iterator.next count - Range 0 (if start_index == -1 then (Text_Utils.char_length text) else start_index) + Range_Data 0 (if start_index == -1 then (Text_Utils.char_length text) else start_index) Last count -> - if count <= 0 then (Range 0 0) else + if count <= 0 then (Range_Data 0 0) else iterator = BreakIterator.getCharacterInstance iterator.setText text iterator.last start_index = iterator.next -count - Range (if start_index == -1 then 0 else start_index) (Text_Utils.char_length text) + Range_Data (if start_index == -1 then 0 else start_index) (Text_Utils.char_length text) While predicate -> indices = find_sub_range_end text _-> start-> end-> predicate (Text_Utils.substring text start end) . not - if indices.first.is_nothing then (Range 0 indices.second) else - Range 0 indices.first + if indices.first.is_nothing then (Range_Data 0 indices.second) else + Range_Data 0 indices.first By_Index indices -> case indices of Vector.Vector_Data _ -> @@ -94,8 +94,8 @@ find_codepoint_ranges text subrange = Every step start -> if step <= 0 then Error.throw (Illegal_Argument_Error "Step within Every must be positive.") else len = text.length - if start >= len then Range 0 0 else - range = Range start text.length step + if start >= len then Range_Data 0 0 else + range = Range_Data start text.length step find_codepoint_ranges text (By_Index range) Range_Data _ _ _ -> find_codepoint_ranges text (By_Index subrange) @@ -125,7 +125,7 @@ type Codepoint_Ranges sorted.tail.each range-> current = current_ref.get case range.start <= current.end of - True -> current_ref.put (Range current.start (Math.max current.end range.end)) + True -> current_ref.put (Range_Data current.start (Math.max current.end range.end)) False -> builder.append current current_ref.put range @@ -148,14 +148,14 @@ find_sub_range_end = text->predicate-> iterator.setText text loop index start end = - if end == -1 then (Pair Nothing start) else - if predicate index start end then (Pair start end) else + if end == -1 then (Pair_Data Nothing start) else + if predicate index start end then (Pair_Data start end) else @Tail_Call loop (index + 1) end iterator.next loop 0 0 iterator.next ## PRIVATE -resolve_index_or_range text descriptor = Panic.recover [Index_Out_Of_Bounds_Error, Illegal_Argument_Error] <| +resolve_index_or_range text descriptor = Panic.recover [Index_Out_Of_Bounds_Error_Data, Illegal_Argument_Error_Data] <| iterator = BreakIterator.getCharacterInstance iterator.setText text case descriptor of @@ -164,12 +164,12 @@ resolve_index_or_range text descriptor = Panic.recover [Index_Out_Of_Bounds_Erro iterator.last start = iterator.next descriptor end = iterator.next - if (start == -1) || (end == -1) then Error.throw (Index_Out_Of_Bounds_Error descriptor text.length) else - Range start end - Range _ _ _ -> + if (start == -1) || (end == -1) then Error.throw (Index_Out_Of_Bounds_Error_Data descriptor text.length) else + Range_Data start end + Range_Data _ _ _ -> len = text.length true_range = normalize_range descriptor len - if descriptor.is_empty then Range 0 0 else + if descriptor.is_empty then Range_Data 0 0 else case true_range.step == 1 of True -> Span_Module.range_to_char_indices text true_range False -> @@ -178,14 +178,14 @@ resolve_index_or_range text descriptor = Panic.recover [Index_Out_Of_Bounds_Erro go start_index current_grapheme = end_index = iterator.next if (start_index == -1) || (end_index == -1) || (current_grapheme >= true_range.end) then Nothing else - ranges.append (Range start_index end_index) + ranges.append (Range_Data start_index end_index) ## We advance by step-1, because we already advanced by one grapheme when looking for the end of the previous one. @Tail_Call go (iterator.next true_range.step-1) current_grapheme+true_range.step go (iterator.next true_range.start) true_range.start - Codepoint_Ranges ranges.to_vector is_sorted_and_distinct=True + Codepoint_Ranges_Data ranges.to_vector is_sorted_and_distinct=True ## PRIVATE Returns an array of UTF-16 code-unit indices corresponding to the beginning @@ -197,13 +197,13 @@ character_ranges text = iterator.setText text ranges = Vector.new_builder go prev nxt = if nxt == -1 then Nothing else - ranges.append (Range prev nxt) + ranges.append (Range_Data prev nxt) @Tail_Call go nxt iterator.next go iterator.first iterator.next ranges.to_vector ## PRIVATE -batch_resolve_indices_or_ranges text descriptors = Panic.recover [Index_Out_Of_Bounds_Error, Illegal_Argument_Error] <| +batch_resolve_indices_or_ranges text descriptors = Panic.recover [Index_Out_Of_Bounds_Error_Data, Illegal_Argument_Error_Data] <| ## This is pre-computing the ranges for all characters in the string, which may be much more than necessary, for example if all ranges reference only the beginning of the string. In the future we may want to replace this @@ -216,20 +216,20 @@ batch_resolve_indices_or_ranges text descriptors = Panic.recover [Index_Out_Of_B case descriptor of Integer -> ranges.append (Panic.rethrow <| characters.at descriptor) - Range _ _ _ -> - if descriptor.is_empty then Range 0 0 else + Range_Data _ _ _ -> + if descriptor.is_empty then Range_Data 0 0 else true_range = normalize_range descriptor characters.length case true_range.step == 1 of True -> first_grapheme = Panic.rethrow <| characters.at true_range.start last_grapheme = Panic.rethrow <| characters.at true_range.end-1 - ranges.append (Range first_grapheme.start last_grapheme.end) + ranges.append (Range_Data first_grapheme.start last_grapheme.end) False -> if true_range.start >= characters.length then - Panic.throw (Index_Out_Of_Bounds_Error true_range.start characters.length) + Panic.throw (Index_Out_Of_Bounds_Error_Data true_range.start characters.length) true_range.to_vector.each ix-> ranges.append (Panic.rethrow <| characters.at ix) - Codepoint_Ranges ranges.to_vector is_sorted_and_distinct=False + Codepoint_Ranges_Data ranges.to_vector is_sorted_and_distinct=False ## PRIVATE panic_on_non_positive_step = @@ -243,6 +243,6 @@ normalize_range range length = if (range.start < 0) || (range.end < 0) then Panic.throw (Illegal_Argument_Error "Ranges with negative indices are not supported for indexing.") if (range.start >= length) then - Panic.throw (Index_Out_Of_Bounds_Error range.start length) - if range.end >= length then Range range.start length range.step else + Panic.throw (Index_Out_Of_Bounds_Error_Data range.start length) + if range.end >= length then Range_Data range.start length range.step else range diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time.enso index d3e184605ddb..066fd2aaa2d8 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time.enso @@ -251,7 +251,7 @@ type Time example_zone = Time.now.zone zone : Zone - zone self = Zone.Zone self.internal_zoned_date_time.getZone + zone self = Zone.Zone_Data self.internal_zoned_date_time.getZone ## Return the number of seconds from the Unix epoch. @@ -285,7 +285,7 @@ type Time example_time_of_day = Time.now.time_of_day time_of_day : Time_Of_Day - time_of_day self = Time_Of_Day.Time_Of_Day self.internal_zoned_date_time.toLocalTime + time_of_day self = Time_Of_Day.Time_Of_Day_Data self.internal_zoned_date_time.toLocalTime ## ALIAS Time to Date 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 afce7a3b4043..22f136c7a3ad 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 @@ -25,7 +25,7 @@ between start_inclusive end_exclusive = start = start_inclusive.internal_zoned_date_time end = end_exclusive.internal_zoned_date_time duration = Java_Duration.between start end - Duration period duration + Duration_Data period duration ## ADVANCED @@ -39,8 +39,8 @@ time_execution ~function = start = System.nano_time result = Runtime.no_inline function end = System.nano_time - duration = Duration (Java_Period.ofDays 0) (Java_Duration.ofNanos (end - start)) - Pair duration result + duration = Duration_Data (Java_Period.ofDays 0) (Java_Duration.ofNanos (end - start)) + Pair_Data duration result type Duration @@ -52,7 +52,7 @@ type Duration - internal_period: The internal representation of the time as a period. - internal_duration: The internal representation of the time as a duration. - type Duration internal_period internal_duration + Duration_Data internal_period internal_duration ## Add the specified amount of time to this duration. @@ -76,7 +76,7 @@ type Duration + self that = period = self.internal_period . plus that.internal_period . normalized duration = self.internal_duration . plus that.internal_duration - Duration period duration + Duration_Data period duration ## Subtract the specified amount of time from this duration. @@ -100,7 +100,7 @@ type Duration - self that = period = self.internal_period . minus that.internal_period . normalized duration = self.internal_duration . minus that.internal_duration - Duration period duration + Duration_Data period duration ## Get the portion of the duration expressed in nanoseconds. @@ -313,7 +313,7 @@ type Duration example_nano = 1.nanosecond Integer.nanosecond : Duration -Integer.nanosecond self = Duration (Java_Period.ofDays 0) (Java_Duration.ofNanos self) +Integer.nanosecond self = Duration_Data (Java_Period.ofDays 0) (Java_Duration.ofNanos self) ## Create a duration of `self` nanoseconds. @@ -335,7 +335,7 @@ Integer.nanoseconds self = self.nanosecond example_milli = 1.millisecond Integer.millisecond : Duration -Integer.millisecond self = Duration (Java_Period.ofDays 0) (Java_Duration.ofMillis self) +Integer.millisecond self = Duration_Data (Java_Period.ofDays 0) (Java_Duration.ofMillis self) ## Create a duration of `self` milliseconds. @@ -357,7 +357,7 @@ Integer.milliseconds self = self.millisecond example_second = 1.second Integer.second : Duration -Integer.second self = Duration (Java_Period.ofDays 0) (Java_Duration.ofSeconds self) +Integer.second self = Duration_Data (Java_Period.ofDays 0) (Java_Duration.ofSeconds self) ## Create a duration of `self` seconds. @@ -379,7 +379,7 @@ Integer.seconds self = self.second example_min = 1.minute Integer.minute : Duration -Integer.minute self = Duration (Java_Period.ofDays 0) (Java_Duration.ofMinutes self) +Integer.minute self = Duration_Data (Java_Period.ofDays 0) (Java_Duration.ofMinutes self) ## Create a duration of `self` minutes. @@ -401,7 +401,7 @@ Integer.minutes self = self.minute example_hour = 1.hour Integer.hour : Duration -Integer.hour self = Duration (Java_Period.ofDays 0) (Java_Duration.ofHours self) +Integer.hour self = Duration_Data (Java_Period.ofDays 0) (Java_Duration.ofHours self) ## Create a duration of `self` hours. @@ -423,7 +423,7 @@ Integer.hours self = self.hour example_day = 1.day Integer.day : Duration -Integer.day self = Duration (Java_Period.ofDays self . normalized) (Java_Duration.ofSeconds 0) +Integer.day self = Duration_Data (Java_Period.ofDays self . normalized) (Java_Duration.ofSeconds 0) ## Create a duration of `self` days. @@ -445,7 +445,7 @@ Integer.days self = self.day example_month = 1.month Integer.month : Duration -Integer.month self = Duration (Java_Period.ofMonths self . normalized) (Java_Duration.ofSeconds 0) +Integer.month self = Duration_Data (Java_Period.ofMonths self . normalized) (Java_Duration.ofSeconds 0) ## Create a duration of `self` months. @@ -467,7 +467,7 @@ Integer.months self = self.month example_year = 1.year Integer.year : Duration -Integer.year self = Duration (Java_Period.ofYears self . normalized) (Java_Duration.ofSeconds 0) +Integer.year self = Duration_Data (Java_Period.ofYears self . normalized) (Java_Duration.ofSeconds 0) ## Create a duration of `self` years. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Time_Of_Day.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Time_Of_Day.enso index 1559dff17a4d..cc0fbb24b998 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Time_Of_Day.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Time_Of_Day.enso @@ -19,7 +19,7 @@ polyglot java import org.enso.base.Time_Utils example_now = Time_Of_Day.now now : Time_Of_Day -now = Time_Of_Day LocalTime.now +now = Time_Of_Day_Data LocalTime.now ## Obtains an instance of `Time_Of_Day` from an hour, minute, second and nanosecond. @@ -47,8 +47,8 @@ now = Time_Of_Day LocalTime.now example_epoch = Time_Of_Day.new hour=9 minute=30 new : Integer -> Integer -> Integer -> Integer -> Time_Of_Day ! Time.Time_Error new (hour = 0) (minute = 0) (second = 0) (nanosecond = 0) = - Panic.catch_java Any (Time_Of_Day (LocalTime.of hour minute second nanosecond)) java_exception-> - Error.throw (Time.Time_Error java_exception.getMessage) + Panic.catch_java Any (Time_Of_Day_Data (LocalTime.of hour minute second nanosecond)) java_exception-> + Error.throw (Time.Time_Error_Data java_exception.getMessage) ## Obtains an instance of `Time_Of_Day` from a text such as "10:15". @@ -118,9 +118,9 @@ parse text pattern=Nothing locale=Locale.default = Text -> formatter = DateTimeFormatter.ofPattern pattern LocalTime.parse text (formatter.withLocale locale.java_locale) - _ -> Panic.throw (Time.Time_Error "An invalid pattern was provided.") - Time_Of_Day result . map_error <| case _ of - Polyglot_Error err -> Time.Time_Error err.getMessage + _ -> Panic.throw (Time.Time_Error_Data "An invalid pattern was provided.") + Time_Of_Day_Data result . map_error <| case _ of + Polyglot_Error_Data err -> Time.Time_Error_Data err.getMessage x -> x type Time_Of_Day @@ -135,7 +135,7 @@ type Time_Of_Day Time is represented to nanosecond precision. For example, the value "13:45.30.123456789" can be stored in a `Time_Of_Day`. - type Time_Of_Day internal_local_time + Time_Of_Day_Data internal_local_time ## Get the hour portion of the time of day. @@ -206,7 +206,7 @@ type Time_Of_Day example_to_time = Time_Of_Day.new 12 30 . to_time (Date.new 2020) to_time : Date -> Zone -> Time to_time self date (zone = Zone.system) = - Time.Time (self . internal_local_time . atDate date . atZone zone.internal_zone_id) + Time.Time_Data (self . internal_local_time . atDate date . atZone zone.internal_zone_id) ## Add the specified amount of time to this instant to get a new instant. @@ -220,8 +220,8 @@ type Time_Of_Day example_plus = Time_Of_Day.new + 3.seconds + : Duration -> Time_Of_Day - + self amount = if amount.is_date then Error.throw (Time.Time_Error "Time_Of_Day does not support date intervals") else - Time_Of_Day (self . internal_local_time . plus amount.internal_duration) + + self amount = if amount.is_date then Error.throw (Time.Time_Error_Data "Time_Of_Day does not support date intervals") else + Time_Of_Day_Data (self . internal_local_time . plus amount.internal_duration) ## Subtract the specified amount of time from this instant to get a new instant. @@ -237,8 +237,8 @@ type Time_Of_Day example_minus = Time_Of_Day.now - 12.hours - : Duration -> Time_Of_Day - - self amount = if amount.is_date then Error.throw (Time.Time_Error "Time_Of_Day does not support date intervals") else - Time_Of_Day (self . internal_local_time . minus amount.internal_duration) + - self amount = if amount.is_date then Error.throw (Time.Time_Error_Data "Time_Of_Day does not support date intervals") else + Time_Of_Day_Data (self . internal_local_time . minus amount.internal_duration) ## Format this time of day as text using the default formatter. @@ -334,5 +334,5 @@ type Time_Of_Day ## Compares two Time_Of_Day for equality. == : Date -> Boolean == self that = case that of - Time_Of_Day _ -> self.internal_local_time.equals that.internal_local_time + Time_Of_Day_Data _ -> self.internal_local_time.equals that.internal_local_time _ -> False diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Zone.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Zone.enso index 1fa5303c8ee4..b5759a9afefb 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Zone.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Zone.enso @@ -58,7 +58,7 @@ utc = parse "UTC" example_new = Zone.new 1 1 50 new : Integer -> Integer -> Integer -> Zone new (hours = 0) (minutes = 0) (seconds = 0) = - Zone (ZoneOffset.ofHoursMinutesSeconds hours minutes seconds . normalized) + Zone_Data (ZoneOffset.ofHoursMinutesSeconds hours minutes seconds . normalized) ## ALIAS Time Zone from Text @@ -95,7 +95,7 @@ new (hours = 0) (minutes = 0) (seconds = 0) = example_parse = Zone.parse "+03:02:01" parse : Text -> Zone -parse text = Zone (ZoneId.of text) +parse text = Zone_Data (ZoneId.of text) type Zone 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 fd1d9e1be54c..87f9710c9ea3 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 @@ -144,8 +144,8 @@ type Vector at : Integer -> Any ! Index_Out_Of_Bounds_Error at self index = actual_index = if index < 0 then self.length + index else index - Panic.catch Invalid_Array_Index_Error (self.unsafe_at actual_index) _-> - Error.throw (Index_Out_Of_Bounds_Error index self.length) + Panic.catch Invalid_Array_Index_Error_Data (self.unsafe_at actual_index) _-> + Error.throw (Index_Out_Of_Bounds_Error_Data index self.length) ## ADVANCED UNSTABLE @@ -231,7 +231,7 @@ type Vector sum self = result = Panic.recover Any <| self.reduce (+) result.map_error x->case x of - No_Such_Method_Error _ _ -> x + No_Such_Method_Error_Data _ _ -> x Empty_Error -> x _ -> Panic.throw x @@ -384,12 +384,12 @@ type Vector [1, 2, 3, 4, 5].partition (x -> x % 2 == 0) == (Pair [2, 4] [1, 3, 5]) partition : (Any -> Boolean) -> Pair (Vector Any) (Vector Any) partition self predicate = - pair = self.fold (Pair new_builder new_builder) acc-> elem-> + pair = self.fold (Pair_Data new_builder new_builder) acc-> elem-> case predicate elem of True -> - Pair (acc.first.append elem) acc.second + Pair_Data (acc.first.append elem) acc.second False -> - Pair acc.first (acc.second.append elem) + Pair_Data acc.first (acc.second.append elem) pair.map .to_vector ## Partitions the vector into vectors of elements which satisfy a given @@ -412,10 +412,10 @@ type Vector ["a", "b", "c", "d"].partition_with_index (ix -> _ -> ix % 2 == 0) == (Pair ["a", "c"] ["b", "d"]) partition_with_index : (Integer -> Any -> Boolean) -> Pair (Vector Any) (Vector Any) partition_with_index self predicate = - pair = self.fold_with_index (Pair new_builder new_builder) acc-> ix-> elem-> + pair = self.fold_with_index (Pair_Data new_builder new_builder) acc-> ix-> elem-> case predicate ix elem of - True -> Pair (acc.first.append elem) acc.second - False -> Pair acc.first (acc.second.append elem) + True -> Pair_Data (acc.first.append elem) acc.second + False -> Pair_Data acc.first (acc.second.append elem) pair.map .to_vector ## Applies a function to each element of the vector, returning the vector of @@ -852,7 +852,7 @@ type Vector [1, 2, 3, 4].second second : Vector ! Singleton_Error second self = if self.length >= 2 then self.unsafe_at 1 else - Error.throw (Singleton_Error self) + Error.throw (Singleton_Error_Data self) ## Get all elements in the vector except the first. @@ -1097,8 +1097,8 @@ type Builder at : Integer -> Any ! Index_Out_Of_Bounds_Error at self index = actual_index = if index < 0 then self.length + index else index - Panic.catch Invalid_Array_Index_Error (self.to_array.at actual_index) _-> - Error.throw (Index_Out_Of_Bounds_Error index self.length) + Panic.catch Invalid_Array_Index_Error_Data (self.to_array.at actual_index) _-> + Error.throw (Index_Out_Of_Bounds_Error_Data index self.length) ## Checks whether a predicate holds for at least one element of this builder. @@ -1170,4 +1170,4 @@ type Incomparable_Values_Error Incomparable_Values_Error if any occur. handle_incomparable_value ~function = handle t = Panic.catch t handler=(Error.throw Incomparable_Values_Error) - handle No_Such_Method_Error <| handle Type_Error <| handle Unsupported_Argument_Types <| function + handle No_Such_Method_Error_Data <| handle Type_Error_Data <| handle Unsupported_Argument_Types_Data <| 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 04d1509f8a53..ada6681db94d 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 @@ -201,7 +201,8 @@ type Illegal_Argument_Error Arguments: - index: The requested index. - length: The length of the collection. -type Index_Out_Of_Bounds_Error index length +type Index_Out_Of_Bounds_Error + Index_Out_Of_Bounds_Error_Data index length ## UNSTABLE @@ -213,7 +214,8 @@ Index_Out_Of_Bounds_Error.to_display_text self = ## PRIVATE Wraps a dataflow error lifted to a panic, making possible to distinguish it from other panics. -type Wrapped_Dataflow_Error payload +type Wrapped_Dataflow_Error + Wrapped_Dataflow_Error_Data payload ## PRIVATE Throws the original error. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso index d20c5469f144..84f5bc23d0e5 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Function.enso @@ -1,14 +1,11 @@ import Standard.Base.Data.Vector -# Function types. -type Function - - ## A function is any type that represents a not-yet evaluated computation. +## 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 + Methods are represented as functions with dynamic dispatch semantics on + the this argument. +@Builtin_Type +type Function ## An identity function which returns the provided argument. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso index 43c03bc0404b..708840728b8e 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot.enso @@ -1,12 +1,9 @@ -## 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. +## 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 +@Builtin_Type +type Polyglot ## Reads the number of elements in a given polyglot array object. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Random.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Random.enso index 1a99ee719986..19a1e7b30d13 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Random.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Random.enso @@ -14,11 +14,11 @@ get_default_seed = System.nano_time ## Constructs a new random number generator. new : Integer -> Random_Number_Generator new seed=get_default_seed = - Random_Number_Generator (Java_Random.new seed) + Random_Number_Generator_Data (Java_Random.new seed) type Random_Number_Generator ## A random number generator. - type Random_Number_Generator java_random + Random_Number_Generator_Data java_random ## Returns a new vector containing a random sample of the input vector, without replacement. @@ -28,7 +28,7 @@ type Random_Number_Generator sample : Vector Any -> Integer -> Random_Number_Generator -> Vector Any sample vector k rng = new_array = Random_Utils.sample vector.to_array k rng.java_random - Vector.Vector new_array + Vector.Vector_Data new_array ## Returns `k` indices sampled from the range [0, n-1] without replacement. @@ -36,4 +36,4 @@ sample vector k rng = random_indices : Integer -> Integer -> Random_Number_Generator -> Vector Integer random_indices n k rng = array = Random_Utils.random_indices n k rng.java_random - Vector.Vector array + Vector.Vector_Data array diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso index d3d45d8c8055..64b66bbe71f5 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime.enso @@ -20,7 +20,7 @@ primitive_get_stack_trace = @Builtin_Method "Runtime.primitive_get_stack_trace" get_stack_trace : Vector.Vector Stack_Trace_Element get_stack_trace = prim_stack = primitive_get_stack_trace - stack_with_prims = Vector.Vector prim_stack + stack_with_prims = Vector.Vector_Data prim_stack stack = stack_with_prims.map wrap_primitive_stack_trace_element # drop this frame and the one from `Runtime.primitive_get_stack_trace` stack.drop_start 2 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 d09d433e9c96..2193c20a73f9 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 @@ -173,14 +173,9 @@ list : (File | Text) -> Text -> Boolean -> Vector.Vector File list directory name_filter=Nothing recursive=False = new directory . list name_filter=name_filter recursive=recursive +@Builtin_Type type File - ## PRIVATE - - A type representing a file. - @Builtin_Type - type File - ## Creates a new output stream for this file and runs the specified action on it. @@ -339,7 +334,7 @@ type File creation_time : Time ! File_Error creation_time self = handle_java_exceptions self <| - Time (self.creation_time_builtin) + Time_Data (self.creation_time_builtin) ## PRIVATE @@ -360,7 +355,7 @@ type File last_modified_time : Time ! File_Error last_modified_time self = handle_java_exceptions self <| - Time (self.last_modified_time_builtin) + Time_Data (self.last_modified_time_builtin) ## PRIVATE @@ -649,7 +644,7 @@ type File read_last_bytes : Integer -> Vector ! File_Error read_last_bytes self n = handle_java_exceptions self <| - Vector.Vector (self.read_last_bytes_builtin n) + Vector.Vector_Data (self.read_last_bytes_builtin n) ## PRIVATE read_last_bytes_builtin : Integer -> Array @@ -739,7 +734,7 @@ type File Utility function that lists immediate children of a directory. list_immediate_children : Vector.Vector File - list_immediate_children self = Vector.Vector (self.list_immediate_children_array) + list_immediate_children self = Vector.Vector_Data (self.list_immediate_children_array) ## PRIVATE @@ -840,7 +835,7 @@ type Output_Stream replacement_sequence = Encoding_Utils.INVALID_CHARACTER.bytes encoding on_problems=Problem_Behavior.Ignore java_charset = encoding.to_java_charset results = Encoding_Utils.with_stream_encoder java_stream java_charset replacement_sequence.to_array action - problems = Vector.Vector results.problems . map Encoding_Error + problems = Vector.Vector_Data results.problems . map Encoding_Error_Data on_problems.attach_problems_after results.result problems ## An input stream, allowing for interactive reading of contents from an open @@ -877,7 +872,7 @@ type Input_Stream read_all_bytes : Vector.Vector ! File_Error read_all_bytes self = self.stream_resource . with java_stream-> handle_java_exceptions self.file <| - Vector.Vector java_stream.readAllBytes + Vector.Vector_Data java_stream.readAllBytes ## ADVANCED @@ -908,7 +903,7 @@ type Input_Stream read_n_bytes self n = self.stream_resource . with java_stream-> handle_java_exceptions self.file <| bytes = java_stream.readNBytes n - Vector.Vector bytes + Vector.Vector_Data bytes ## ADVANCED @@ -974,7 +969,7 @@ type Input_Stream with_stream_decoder self encoding on_problems action = self.stream_resource . with java_stream-> java_charset = encoding.to_java_charset results = Encoding_Utils.with_stream_decoder java_stream java_charset action - problems = Vector.Vector results.problems . map Encoding_Error + problems = Vector.Vector_Data results.problems . map Encoding_Error_Data on_problems.attach_problems_after results.result problems ## PRIVATE @@ -1119,10 +1114,10 @@ Text.write self path encoding=Encoding.utf_8 on_existing_file=Existing_File_Beha [36, -62, -93, -62, -89, -30, -126, -84, -62, -94].write_bytes Examples.scratch_file.write_bytes Examples.scratch_file Existing_File_Behavior.Append Vector.Vector.write_bytes : (File|Text) -> Existing_File_Behavior -> Nothing ! Illegal_Argument_Error | File_Not_Found | IO_Error | File_Already_Exists_Error Vector.Vector.write_bytes self path on_existing_file=Existing_File_Behavior.Backup = - Panic.catch Unsupported_Argument_Types handler=(Error.throw (Illegal_Argument_Error "Only Vectors consisting of bytes (integers in the range from -128 to 127) are supported by the `write_bytes` method.")) <| + Panic.catch Unsupported_Argument_Types_Data handler=(Error.throw (Illegal_Argument_Error "Only Vectors consisting of bytes (integers in the range from -128 to 127) are supported by the `write_bytes` method.")) <| ## Convert to a byte array before writing - and fail early if there is any problem. byte_array = Array_Utils.ensureByteArray self.to_array file = new path on_existing_file.write file stream-> - stream.write_bytes (Vector.Vector byte_array) + stream.write_bytes (Vector.Vector_Data byte_array) 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 a69a7031084a..35c04c4cabad 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 @@ -42,7 +42,7 @@ run command arguments=[] = example_new_builder = Process.new_builder "echo" new_builder : Text -> Vector Text -> Text -> Builder -new_builder command arguments=[] stdin="" = Builder command arguments stdin +new_builder command arguments=[] stdin="" = Builder_Data command arguments stdin ## UNSTABLE @@ -62,7 +62,7 @@ type Builder We recommend that you use this type with its builder interface. Start by creating a `Builder "command"` and then call functions on it to set arguments and standard output. It results in much clearer code. - type Builder command arguments stdin + type Builder_Data command arguments stdin ## UNSTABLE @@ -80,7 +80,7 @@ type Builder builder = Process.new_builder "echo" builder.set_arguments ["hello, world!"] set_arguments : Vector.Vector Text -> Builder - set_arguments self arguments = Builder self.command arguments self.stdin + set_arguments self arguments = Builder_Data self.command arguments self.stdin ## UNSTABLE @@ -99,7 +99,7 @@ type Builder builder = Process.new_builder "echo" builder.set_stdin "hello, world!" set_stdin : Text -> Builder - set_stdin self stdin = Builder self.command self.arguments stdin + set_stdin self stdin = Builder_Data self.command self.arguments stdin ## UNSTABLE @@ -117,7 +117,7 @@ type Builder create : Result create self = result = System.create_process self.command self.arguments.to_array self.stdin redirect_in=False redirect_out=False redirect_err=False - Result (Exit_Code.from_number result.exit_code) result.stdout result.stderr + Result_Data (Exit_Code.from_number result.exit_code) result.stdout result.stderr ## UNSTABLE @@ -127,4 +127,5 @@ type Builder - exit_code: The exit code for the process. - stdout: The contents of the process' standard output. - stderr: The contents of the process' standard error. -type Result exit_code stdout stderr +type Result + Result_Data 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 e19f2ae4df21..10e7b09d78dd 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,5 +1,5 @@ from Standard.Base import all -from Standard.Base.Runtime import Stack_Trace_Element +from Standard.Base.Runtime import Stack_Trace_Element, Stack_Trace_Element_Data ## A representation of a dataflow warning attached to a value. @Builtin_Type @@ -35,11 +35,11 @@ type Warning nature is preserved. reassignments : Vector.Vector Stack_Trace_Element reassignments self = - Vector.Vector self.get_reassignments . map r-> + Vector.Vector_Data self.get_reassignments . map r-> loc = case Polyglot.has_source_location r of False -> Nothing - True -> Source_Location (Polyglot.get_source_location r) - Stack_Trace_Element (Polyglot.get_executable_name r) loc + True -> Source_Location_Data (Polyglot.get_source_location r) + Stack_Trace_Element_Data (Polyglot.get_executable_name r) loc ## PRIVATE @@ -77,7 +77,7 @@ attach_with_stacktrace value warning origin = @Builtin_Method "Warning.attach_wi Gets all the warnings attached to the given value. Warnings are returned in the reverse-chronological order with respect to their attachment time. get_all : Any -> Vector.Vector Warning -get_all value = Vector.Vector (get_all_array value) +get_all value = Vector.Vector_Data (get_all_array value) ## PRIVATE @@ -200,7 +200,7 @@ detach_selected_warnings value predicate = result = warnings.partition w-> predicate w.value matched = result.first remaining = result.second - Pair (set remaining value) matched + Pair_Data (set remaining value) matched ## UNSTABLE A helper function which gathers warnings matching some predicate and passes From 00430652cb12d927d3099062d0b17ae6c5379968 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 11 Aug 2022 21:20:19 +0200 Subject: [PATCH 044/110] progress --- .../Standard/Base/0.0.0-dev/src/Data/Any.enso | 13 ++-- .../Base/0.0.0-dev/src/Data/Json.enso | 5 +- .../Base/0.0.0-dev/src/Data/Locale.enso | 6 +- .../src/Data/Ordering/Natural_Order.enso | 2 +- .../Base/0.0.0-dev/src/Data/Regression.enso | 8 +-- .../Base/0.0.0-dev/src/Data/Statistics.enso | 16 ++--- .../src/Data/Statistics/Rank_Method.enso | 10 +-- .../0.0.0-dev/src/Data/Text/Encoding.enso | 25 +++---- .../0.0.0-dev/src/Data/Text/Matching.enso | 2 +- .../Base/0.0.0-dev/src/Data/Time/Date.enso | 33 +++++---- .../Base/0.0.0-dev/src/Error/Common.enso | 68 ++++++++++--------- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 2 +- .../lib/Standard/Base/0.0.0-dev/src/Meta.enso | 8 +-- .../Base/0.0.0-dev/src/Runtime/Ref.enso | 8 +-- .../Base/0.0.0-dev/src/System/File.enso | 2 +- .../Base/0.0.0-dev/src/System/Process.enso | 2 +- 16 files changed, 104 insertions(+), 106 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso index 90f2dc06365a..fa4fdc8bbd14 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso @@ -2,15 +2,12 @@ from Standard.Base import all from Standard.Base.Error.Common import dataflow_error_handler -# The type that subsumes all types. -type Any - - ## Any is the universal top-type, with all other types being subsumed by it. +## 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 + 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 diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso index 847c3d1319fc..b00ea663a000 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso @@ -170,13 +170,14 @@ Parse_Error.to_display_text self = example_get = Examples.json_object.get "title" Object.get : Text -> Json ! No_Such_Field_Error Object.get self field = self.fields.get field . map_error case _ of - Map.No_Value_For_Key_Error _ -> No_Such_Field_Error field + Map.No_Value_For_Key_Error_Data _ -> No_Such_Field_Error_Data field x -> x ## UNSTABLE An error indicating that there is no such field in the JSON object. -type No_Such_Field_Error field_name +type No_Such_Field_Error + No_Such_Field_Error_Data field_name ## UNSTABLE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Locale.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Locale.enso index 98a46f9bca89..464f66ace176 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Locale.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Locale.enso @@ -303,7 +303,7 @@ type Locale Arguments: - java_locale: The Java locale representation used internally. - type Locale java_locale + Locale_Data java_locale ## Gets the language from the locale. @@ -417,7 +417,7 @@ type Locale ## Compares two locales for equality. == : Any -> Boolean == self other = case other of - Locale other_java_locale -> self.java_locale.equals other_java_locale + Locale_Data other_java_locale -> self.java_locale.equals other_java_locale _ -> False ## PRIVATE @@ -427,7 +427,7 @@ type Locale Arguments: - java: The java locale value. from_java : JavaLocale -> Locale -from_java java = Locale java +from_java java = Locale_Data java ## PRIVATE javaLocaleBuilder = JavaLocale.Builder diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Natural_Order.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Natural_Order.enso index 324b4894c368..f4c8864a7b2a 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Natural_Order.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Ordering/Natural_Order.enso @@ -75,7 +75,7 @@ compare text1 text2 case_sensitive=True = substring2 = Text_Utils.substring text2 prev2 next2 first_char_2 = Text_Utils.get_chars substring2 . at 0 - tmp = Pair (is_digit first_char_1) (is_digit first_char_2) + tmp = Pair_Data (is_digit first_char_1) (is_digit first_char_2) ## ToDo: Move to case on second block Appears to be an issue using a nested case statement on a pair https://www.pivotaltracker.com/story/show/181280737 diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Regression.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Regression.enso index 2100c642b50a..ac358b4a00e6 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Regression.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Regression.enso @@ -38,7 +38,7 @@ fit_least_squares known_xs known_ys model=Linear_Model = log_ys = ln_series known_ys "Y-values" fitted = Regression.fit_linear log_xs.to_array log_ys.to_array fitted_model_with_r_squared Fitted_Power_Model fitted.intercept.exp fitted.slope known_xs known_ys - _ -> Error.throw (Illegal_Argument_Error "Unsupported model.") + _ -> Error.throw (Illegal_Argument_Error_Data "Unsupported model.") type Fitted_Model ## Fitted line (y = slope x + intercept). @@ -70,7 +70,7 @@ type Fitted_Model Fitted_Exponential_Model a b _ -> a * (b * x).exp Fitted_Logarithmic_Model a b _ -> a * x.ln + b Fitted_Power_Model a b _ -> a * (x ^ b) - _ -> Error.throw (Illegal_Argument_Error "Unsupported model.") + _ -> Error.throw (Illegal_Argument_Error_Data "Unsupported model.") ## PRIVATE Computes the R Squared value for a model and returns a new instance. @@ -86,8 +86,8 @@ fitted_model_with_r_squared constructor a b known_xs known_ys = ln_series : Vector -> Vector ! Illegal_Argument_Error ln_series xs series_name="Values" = ln_with_panic x = if x.is_nothing then Nothing else - if x <= 0 then Panic.throw (Illegal_Argument_Error (series_name + " must be positive.")) else x.ln - Panic.recover Illegal_Argument_Error <| xs.map ln_with_panic + if x <= 0 then Panic.throw (Illegal_Argument_Error_Data (series_name + " must be positive.")) else x.ln + Panic.recover Illegal_Argument_Error_Data <| xs.map ln_with_panic ## PRIVATE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Statistics.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Statistics.enso index 362a39c6fafe..368bebf6ef5d 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Statistics.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Statistics.enso @@ -1,4 +1,4 @@ -from Standard.Base import Boolean, True, False, Nothing, Vector, Number, Any, Error, Array, Panic, Illegal_Argument_Error, Unsupported_Argument_Types +from Standard.Base import Boolean, True, False, Nothing, Vector, Number, Any, Error, Array, Panic, Illegal_Argument_Error_Data, Illegal_Argument_Error, Unsupported_Argument_Types, Unsupported_Argument_Types_Data from Standard.Base.Data.Vector import Empty_Error @@ -111,8 +111,8 @@ compute_bulk data statistics=[Count, Sum] = report_invalid _ = statistics.map_with_index i->v-> if java_stats.at i . is_nothing then Nothing else - Error.throw (Illegal_Argument_Error ("Can only compute " + v.to_text + " on numerical data sets.")) - handle_unsupported = Panic.catch Unsupported_Argument_Types handler=report_invalid + Error.throw (Illegal_Argument_Error_Data ("Can only compute " + v.to_text + " on numerical data sets.")) + handle_unsupported = Panic.catch Unsupported_Argument_Types_Data handler=report_invalid empty_map s = if (s == Count) || (s == Sum) then 0 else if (s == Minimum) || (s == Maximum) then Error.throw Empty_Error else @@ -181,8 +181,8 @@ spearman_correlation data = ## PRIVATE wrap_java_call : Any -> Any wrap_java_call ~function = - report_unsupported _ = Error.throw (Illegal_Argument_Error ("Can only compute correlations on numerical data sets.")) - handle_unsupported = Panic.catch Unsupported_Argument_Types handler=report_unsupported + report_unsupported _ = Error.throw (Illegal_Argument_Error_Data ("Can only compute correlations on numerical data sets.")) + handle_unsupported = Panic.catch Unsupported_Argument_Types_Data handler=report_unsupported handle_unsupported <| Illegal_Argument_Error.handle_java_exception <| function @@ -207,7 +207,7 @@ calculate_correlation_statistics_matrix : [Vector] -> [CorrelationStatistics] calculate_correlation_statistics_matrix data = data_array = Vector.new data.length i->(data.at i).to_array . to_array stats_array = wrap_java_call <| CorrelationStatistics.computeMatrix data_array - Vector.new stats_array.length i->(Vector.Vector (stats_array.at i)) + Vector.new stats_array.length i->(Vector.Vector_Data (stats_array.at i)) ## Compute a single statistic on the vector. @@ -242,10 +242,10 @@ rank_data input method=Rank_Method.Average = Rank_Method.Ordinal -> Rank.Method.ORDINAL Rank_Method.Dense -> Rank.Method.DENSE - report_nullpointer caught_panic = Error.throw (Illegal_Argument_Error caught_panic.payload.cause.getMessage) + report_nullpointer caught_panic = Error.throw (Illegal_Argument_Error_Data caught_panic.payload.cause.getMessage) handle_nullpointer = Panic.catch NullPointerException handler=report_nullpointer handle_classcast = Panic.catch ClassCastException handler=(Error.throw Vector.Incomparable_Values_Error) handle_classcast <| handle_nullpointer <| java_ranks = Rank.rank input.to_array Comparator.new java_method - Vector.Vector java_ranks + Vector.Vector_Data java_ranks diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Statistics/Rank_Method.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Statistics/Rank_Method.enso index 1718667bdf79..763b3241b3d4 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Statistics/Rank_Method.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Statistics/Rank_Method.enso @@ -2,17 +2,17 @@ ## Specifies how to handle ranking of equal values. type Rank_Method ## Use the mean of all ranks for equal values. - type Average + Average ## Use the lowest of all ranks for equal values. - type Minimum + Minimum ## Use the highest of all ranks for equal values. - type Maximum + Maximum ## Use same rank value for equal values and next group is the immediate following ranking number. - type Dense + Dense ## Equal values are assigned the next rank in order that they occur. - type Ordinal + Ordinal diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Encoding.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Encoding.enso index 4ad4cb1a0b4f..d873868e8f3e 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Encoding.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Encoding.enso @@ -9,12 +9,12 @@ polyglot java import org.enso.base.Text_Utils all_character_sets : Vector.Vector Text all_character_sets = java_array = Charset.availableCharsets.keySet.toArray - Vector.Vector java_array + Vector.Vector_Data java_array ## Get all available Encodings. all_encodings : Vector Encoding all_encodings = - all_character_sets.map Encoding + all_character_sets.map Encoding_Data ## Represents a character encoding. type Encoding @@ -22,7 +22,7 @@ type Encoding Arguments: - character_set: java.nio.charset name. - type Encoding (character_set:Text) + Encoding_Data (character_set:Text) ## PRIVATE Convert an Encoding to it's corresponding Java Charset @@ -33,35 +33,35 @@ type Encoding ## Encoding for ASCII. ascii : Encoding - ascii = Encoding "US-ASCII" + ascii = Encoding_Data "US-ASCII" ## Encoding for Unicode UTF-8. utf_8 : Encoding - utf_8 = Encoding "UTF-8" + utf_8 = Encoding_Data "UTF-8" ## Encoding for Unicode UTF-16 Little Endian. utf_16_le : Encoding - utf_16_le = Encoding "UTF-16LE" + utf_16_le = Encoding_Data "UTF-16LE" ## Encoding for Unicode UTF-16 Big Endian. utf_16_be : Encoding - utf_16_be = Encoding "UTF-16BE" + utf_16_be = Encoding_Data "UTF-16BE" ## Encoding for Unicode UTF-32 Little Endian. utf_32_le : Encoding - utf_32_le = Encoding "UTF-32LE" + utf_32_le = Encoding_Data "UTF-32LE" ## Encoding for Unicode UTF-32 Big Endian. utf_32_be : Encoding - utf_32_be = Encoding "UTF-32BE" + utf_32_be = Encoding_Data "UTF-32BE" ## Encoding for Central European (Windows). windows_1250 : Encoding - windows_1250 = Encoding "windows-1250" + windows_1250 = Encoding_Data "windows-1250" ## Encoding for Cyrillic (Windows). windows_1251 : Encoding - windows_1251 = Encoding "windows-1251" + windows_1251 = Encoding_Data "windows-1251" ## ALIAS ISO-8859-1 @@ -96,7 +96,8 @@ type Encoding windows_1258 = Encoding "windows-1258" ## One or more byte sequences were not decodable using the Encoding. -type Encoding_Error (message:Text) +type Encoding_Error + Encoding_Error_Data (message:Text) Encoding_Error.to_display_text : Text Encoding_Error.to_display_text self = "Encoding_Error: " + self.message diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso index 115e8bbb0204..c95dd9a7cdc2 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso @@ -206,7 +206,7 @@ match_criteria_callback matcher objects criteria problem_callback reorder=False type Match_Matrix ## PRIVATE A helper type holding a matrix of matches. - type Match_Matrix_Data matrix criteria objects + Match_Matrix_Data matrix criteria objects # Checks if the ith object is matched by any criterion. is_object_matched_by_anything : Integer -> Boolean diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso index 3cc3dc1a53db..38ad978ba83b 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso @@ -59,7 +59,7 @@ new year (month = 1) (day = 1) = https://github.com/enso-org/enso/pull/3559 Then this should be switched to use `Panic.catch_java`. Panic.recover Any (Date.internal_new year month day) . catch Any e-> case e of - Polyglot_Error err -> Error.throw (Time.Time_Error err.getMessage) + Polyglot_Error_Data err -> Error.throw (Time.Time_Error_Data err.getMessage) ex -> ex ## ALIAS Date from Text @@ -127,26 +127,25 @@ parse text pattern=Nothing = result = Panic.recover Any <| case pattern of Nothing -> Date.internal_parse text 0 Text -> Date.internal_parse text pattern - _ -> Panic.throw (Time.Time_Error "An invalid pattern was provided.") + _ -> Panic.throw (Time.Time_Error_Data "An invalid pattern was provided.") result . map_error <| case _ of - Polyglot_Error err -> Time.Time_Error err.getMessage + Polyglot_Error_Data err -> Time.Time_Error err.getMessage ex -> ex -type Date - ## This type represents a date, often viewed as year-month-day. +## This type represents a date, often viewed as year-month-day. - Arguments: - - internal_local_date: The internal date representation. + Arguments: + - internal_local_date: The internal date representation. - For example, the value "2nd October 2007" can be stored in a `Date`. + For example, the value "2nd October 2007" can be stored in a `Date`. - This class does not store or represent a time or timezone. Instead, it - is a description of the date, as used for birthdays. It cannot represent - an instant on the time-line without additional information such as an - offset or timezone. - @Builtin_Type - type Date + This class does not store or represent a time or timezone. Instead, it + is a description of the date, as used for birthdays. It cannot represent + an instant on the time-line without additional information such as an + offset or timezone. +@Builtin_Type +type Date ## Get the year field. @@ -211,7 +210,7 @@ type Date example_to_time = Date.new 2020 2 3 . to_time Time_Of_Day.new Zone.utc to_time : Time_Of_Day -> Zone -> Time - to_time self time_of_day (zone = Zone.system) = Time.Time (Time_Utils.date_with_time self time_of_day.internal_local_time zone.internal_zone_id) + to_time self time_of_day (zone = Zone.system) = Time.Time_Data (Time_Utils.date_with_time self time_of_day.internal_local_time zone.internal_zone_id) ## Add the specified amount of time to this instant to get another date. @@ -225,7 +224,7 @@ type Date example_add = Date.new 2020 + 6.months + : Duration -> Date - + self amount = if amount.is_time then Error.throw (Time.Time_Error "Date does not support time intervals") else + + self amount = if amount.is_time then Error.throw (Time.Time_Error_Data "Date does not support time intervals") else (Time_Utils.date_adjust self 1 amount.internal_period) . internal_local_date ## Subtract the specified amount of time from this instant to get another @@ -242,7 +241,7 @@ type Date example_subtract = Date.new 2020 - 7.days - : Duration -> Date - - self amount = if amount.is_time then Error.throw (Time.Time_Error "Date does not support time intervals") else + - self amount = if amount.is_time then Error.throw (Time.Time_Error_Data "Date does not support time intervals") else (Time_Utils.date_adjust self -1 amount.internal_period) . internal_local_date 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 ada6681db94d..9261429de159 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 @@ -175,7 +175,7 @@ type Illegal_State_Error - message: the error message explaining why the operation cannot be performed. - cause: (optional) another error that is the cause of this one. - type Illegal_State_Error message cause=Nothing + Illegal_State_Error_Data message cause=Nothing type Illegal_Argument_Error @@ -187,12 +187,12 @@ type Illegal_Argument_Error Arguments: - message: the error message explaining why the argument is illegal. - cause: (optional) another error that is the cause of this one. - type Illegal_Argument_Error message cause=Nothing + Illegal_Argument_Error_Data message cause=Nothing ## PRIVATE Capture a Java IllegalArgumentException and rethrow handle_java_exception = - Panic.catch_java IllegalArgumentException handler=(cause-> Error.throw (Illegal_Argument_Error cause.getMessage cause)) + Panic.catch_java IllegalArgumentException handler=(cause-> Error.throw (Illegal_Argument_Error_Data cause.getMessage cause)) ## UNSTABLE @@ -221,6 +221,7 @@ type Wrapped_Dataflow_Error Throws the original error. Wrapped_Dataflow_Error.unwrap self = Error.throw self.payload +@Builtin_Type type Caught_Panic ## A wrapper for a caught panic. @@ -230,8 +231,7 @@ type Caught_Panic 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 + Caught_Panic_Data payload internal_original_exception ## Converts this caught panic into a dataflow error containing the same payload and stack trace. @@ -243,21 +243,18 @@ type Caught_Panic stack_trace self = Panic.get_attached_stack_trace self -## Panics. -type Panic - - ## A panic is an error condition that is based _outside_ of the normal - program control flow. +## 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. + 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 + ? 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. @@ -315,10 +312,10 @@ type Panic 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 + Caught_Panic_Data _ 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 = Vector.Vector_Data 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, @@ -382,7 +379,7 @@ type Panic True -> handler caught_panic False -> Panic.throw caught_panic True -> case caught_panic.payload of - Polyglot_Error java_exception -> + Polyglot_Error_Data java_exception -> case java_exception.is_a panic_type of True -> handler caught_panic False -> Panic.throw caught_panic @@ -412,7 +409,7 @@ type Panic catch_java : Any -> Any -> (Throwable -> Any) -> Any catch_java panic_type ~action handler = Panic.catch_primitive action caught_panic-> case caught_panic.payload of - Polyglot_Error java_exception -> + Polyglot_Error_Data java_exception -> case (panic_type == Any) || (java_exception.is_a panic_type) of True -> handler java_exception False -> Panic.throw caught_panic @@ -444,7 +441,7 @@ type Panic recover : (Vector.Vector Any | Any) -> Any -> Any recover expected_types ~action = types_to_check = case expected_types of - Vector.Vector _ -> expected_types + Vector.Vector_Data _ -> expected_types _ -> [expected_types] Panic.catch Any action caught_panic-> is_matched = types_to_check.exists typ-> @@ -459,7 +456,7 @@ type Panic - value: value to return if not an error, or rethrow as a Panic. throw_wrapped_if_error : Any -> Any throw_wrapped_if_error ~value = - if value.is_error then Panic.throw (Wrapped_Dataflow_Error value.catch) else value + if value.is_error then Panic.throw (Wrapped_Dataflow_Error_Data value.catch) else value ## Catch any `Wrapped_Dataflow_Error` Panic and rethrow it as a dataflow error. @@ -467,7 +464,7 @@ type Panic - action: The code to execute that potentially raised a Wrapped_Dataflow_Error. handle_wrapped_dataflow_error : Any -> Any handle_wrapped_dataflow_error ~action = - Panic.catch Wrapped_Dataflow_Error action caught_panic-> + Panic.catch Wrapped_Dataflow_Error_Data action caught_panic-> Error.throw caught_panic.payload.payload ## The runtime representation of a syntax error. @@ -475,7 +472,8 @@ type Panic Arguments: - message: A description of the erroneous syntax. @Builtin_Type -type Syntax_Error message +type Syntax_Error + Syntax_Error_Data message ## The runtime representation of a type error. @@ -484,21 +482,24 @@ type Syntax_Error message - 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 +type Type_Error + Type_Error_Data expected actual name ## The runtime representation of a compilation error. Arguments: - message: A description of the erroneous state. @Builtin_Type -type Compile_Error message +type Compile_Error + Compile_Error_Data 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 +type Inexhaustive_Pattern_Match_Error + Inexhaustive_Pattern_Match_Error_Data scrutinee ## The error thrown when the number of arguments provided to an operation does not match the expected number of arguments. @@ -508,7 +509,8 @@ type Inexhaustive_Pattern_Match_Error scrutinee - 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 +type Arity_Error + Arity_Error_Data expected_min expected_max actual ## The error thrown when the program attempts to read from a state slot that has not yet been initialized. @@ -516,7 +518,8 @@ type Arity_Error expected_min expected_max actual Arguments: - key: The key for the state slot that was not initialized. @Builtin_Type -type Uninitialized_State key +type Uninitialized_State + Uninitialized_State_Data key ## The error thrown when the specified symbol does not exist as a method on the target. @@ -525,7 +528,8 @@ type Uninitialized_State key - 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 +type No_Such_Method_Error + No_Such_Method_Error_Data target symbol ## ADVANCED UNSTABLE 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 306023d07569..d87dd0ab37db 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 @@ -89,7 +89,7 @@ from project.Data.Range export all from project.Data.Text.Extensions export Text, Line_Ending_Style, Case, Location from project.Data.Text.Matching export Case_Insensitive, Case_Insensitive_Data, Text_Matcher, Text_Matcher_Data, Regex_Matcher, Regex_Matcher_Data, No_Matches_Found from project.Data.Text export all hiding Encoding, Span, Text_Ordering -from project.Data.Text.Encoding export Encoding, Encoding_Error +from project.Data.Text.Encoding export Encoding, Encoding_Error, Encoding_Error_Data from project.Data.Text.Text_Ordering export all from project.Data.Text.Span export all from project.Error.Common 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 8341ab748f89..f15e50458f38 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 @@ -90,7 +90,7 @@ get_atom_fields atom = @Builtin_Method "Meta.get_atom_fields" Returns a vector of field values of the given atom. Atom.fields : Vector.Vector -Atom.fields self = Vector.Vector (get_atom_fields self.value) +Atom.fields self = Vector.Vector_Data (get_atom_fields self.value) ## UNSTABLE ADVANCED @@ -208,7 +208,7 @@ new_atom constructor fields = @Builtin_Method "Meta.new_atom" Returns a vector of field names defined by a constructor. Constructor.fields : Vector.Vector -Constructor.fields self = Vector.Vector (get_constructor_fields self.value) +Constructor.fields self = Vector.Vector_Data (get_constructor_fields self.value) ## UNSTABLE ADVANCED @@ -347,13 +347,13 @@ type Language ADVANCED The Java laguage. - type Java + Java ## UNSTABLE ADVANCED An unknown language. - type Unknown + Unknown ## PRIVATE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Ref.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Ref.enso index febd6ca6db63..b652d11e88b2 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Ref.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Runtime/Ref.enso @@ -1,10 +1,6 @@ -## Utilities for working with mutable references. +## A mutable reference type. +@Builtin_Type type Ref - - ## A mutable reference type. - @Builtin_Type - type Ref - ## Gets the contents of this mutable reference ref. > Example 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 2193c20a73f9..95d96018e38a 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 @@ -9,7 +9,7 @@ import Standard.Base.Data.Text.Text_Sub_Range from Standard.Base.Error.Problem_Behavior import Report_Warning import Standard.Base.Runtime.Resource from Standard.Base.Runtime.Resource import Managed_Resource -from Standard.Base.Data.Time import Time +from Standard.Base.Data.Time import Time, Time_Data polyglot java import org.enso.base.Array_Utils polyglot java import org.enso.base.Encoding_Utils 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 35c04c4cabad..6e7e0293d789 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 @@ -62,7 +62,7 @@ type Builder We recommend that you use this type with its builder interface. Start by creating a `Builder "command"` and then call functions on it to set arguments and standard output. It results in much clearer code. - type Builder_Data command arguments stdin + Builder_Data command arguments stdin ## UNSTABLE From 2faceeb291855b6003f3a14a01f4c9996e3fff95 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 12 Aug 2022 17:58:06 +0200 Subject: [PATCH 045/110] keep going --- .../Base/0.0.0-dev/src/Data/Boolean.enso | 23 ++---- .../Base/0.0.0-dev/src/Data/Json.enso | 5 +- .../Standard/Base/0.0.0-dev/src/Data/Map.enso | 7 +- .../Base/0.0.0-dev/src/Error/Common.enso | 1 + .../Base/0.0.0-dev/src/Network/Http.enso | 6 +- .../Base/0.0.0-dev/src/Network/Http/Form.enso | 16 ++-- .../0.0.0-dev/src/Network/Http/Header.enso | 10 +-- .../0.0.0-dev/src/Network/Http/Request.enso | 24 +++--- .../0.0.0-dev/src/Network/Http/Response.enso | 2 +- .../src/Network/Http/Response/Body.enso | 2 +- .../src/Network/Http/Status_Code.enso | 82 +++++++++---------- .../0.0.0-dev/src/Network/Http/Version.enso | 4 +- .../Base/0.0.0-dev/src/Network/Proxy.enso | 6 +- .../Base/0.0.0-dev/src/Network/URI.enso | 6 +- .../Standard/Base/0.0.0-dev/src/System.enso | 3 +- .../lib/Standard/Test/0.0.0-dev/src/Main.enso | 12 +-- .../src/main/scala/org/enso/runner/Main.scala | 1 + .../builtin/error/ModuleDoesNotExist.java | 1 + .../builtin/error/NoSuchConversionError.java | 1 + .../scala/org/enso/compiler/Compiler.scala | 16 ++-- .../enso/compiler/codegen/IrToTruffle.scala | 20 +++-- .../codegen/RuntimeStubsGenerator.scala | 2 +- .../scala/org/enso/compiler/core/IR.scala | 19 ++++- .../org/enso/compiler/data/BindingsMap.scala | 30 ------- .../compiler/pass/resolve/GlobalNames.scala | 14 +++- .../pass/resolve/MethodDefinitions.scala | 9 +- .../compiler/pass/resolve/TypeNames.scala | 6 +- .../pass/resolve/VectorLiterals.scala | 2 +- test/Tests/src/Data/Json_Spec.enso | 2 +- test/Tests/src/Data/Text/Encoding_Spec.enso | 24 +++--- test/Tests/src/Data/Time/Date_Spec.enso | 16 ++-- .../Tests/src/Data/Time/Time_Of_Day_Spec.enso | 10 +-- test/Tests/src/Data/Time/Time_Spec.enso | 6 +- .../src/Runtime/Lazy_Generator_Spec.enso | 9 +- test/Tests/src/Semantic/Error_Spec.enso | 43 +++++----- test/Tests/src/Semantic/Js_Interop_Spec.enso | 8 +- .../Tests/src/Semantic/Names/Definitions.enso | 7 +- test/Tests/src/Semantic/Names_Spec.enso | 16 ++-- .../src/Semantic/Python_Interop_Spec.enso | 8 +- test/Tests/src/Semantic/R_Interop_Spec.enso | 6 +- test/Tests/src/Semantic/Warnings_Spec.enso | 37 +++++---- test/Tests/src/System/File_Spec.enso | 30 +++---- 42 files changed, 280 insertions(+), 272 deletions(-) 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 index 5992236e608a..69d4193ee99b 100644 --- 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 @@ -1,12 +1,11 @@ -## Booleans. -type Boolean - - ## A type with only two possible values. +## 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 + The boolean type represents the two truth values of boolean logic. It is + primarily used for control-flow. +@Builtin_Type +type Boolean + True + False ## Compares two booleans for equality. @@ -106,11 +105,3 @@ type Boolean if (27 % 3) == 0 then IO.println "Fizz" if_then : Any -> Any | Nothing if_then self ~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.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso index b00ea663a000..f44ee6ccc404 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso @@ -39,7 +39,7 @@ from_pairs contents = parse : Text -> Json ! Parse_Error parse json_text = Panic.catch_java Any (Internal.parse_helper json_text) java_exception-> - Error.throw (Parse_Error java_exception.getMessage) + Error.throw (Parse_Error_Data java_exception.getMessage) ## Represents a JSON structure. type Json @@ -145,7 +145,8 @@ type Json A failure indicating malformed text input into the JSON parser. Check the `message` field for detailed information on the specific failure. -type Parse_Error message +type Parse_Error + Parse_Error_Data message ## UNSTABLE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso index 68dd0629249a..341ae1b0ab19 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Map.enso @@ -193,7 +193,7 @@ type Map get : Any -> Any ! No_Value_For_Key_Error get self key = go map = case map of - Tip -> Error.throw (No_Value_For_Key_Error key) + Tip -> Error.throw (No_Value_For_Key_Error_Data key) Bin _ k v l r -> if k == key then v else if k > key then @Tail_Call go l else @Tail_Call go r @@ -217,7 +217,7 @@ type Map example_get_or_else = Examples.map.get_or_else 2 "zero" get_or_else : Any -> Any -> Any get_or_else self key ~other = - self.get key . catch No_Value_For_Key_Error (_ -> other) + self.get key . catch No_Value_For_Key_Error_Data (_ -> other) ## Transforms the map's keys and values to create a new map. @@ -464,7 +464,8 @@ type Map Arguments: - key: The key that was asked for. -type No_Value_For_Key_Error key +type No_Value_For_Key_Error + No_Value_For_Key_Error_Data key ## UNSTABLE 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 9261429de159..e965ef9c0c30 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 @@ -624,6 +624,7 @@ type Invalid_Conversion_Target_Error - conversion: ... @Builtin_Type type No_Such_Conversion_Error + No_Such_Conversion_Error_Data target that conversion ## UNSTABLE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http.enso index 3e91916b09e5..a7df3b0f6bf7 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http.enso @@ -50,7 +50,7 @@ polyglot java import org.enso.base.Http_Utils Http.new (timeout = 30.seconds) (proxy = Proxy.new "example.com" 8080) new : Duration -> Boolean -> Proxy -> Http new (timeout = 10.seconds) (follow_redirects = True) (proxy = Proxy.System) (version = Version.Http_1_1) = - Http timeout follow_redirects proxy version + Http_Data timeout follow_redirects proxy version ## Send an Options request. @@ -292,7 +292,7 @@ type Http - follow_redirects: Whether or not the client should follow redirects. - proxy: The proxy that the client should use, if any. - version: The HTTP version supported by the client. - type Http timeout follow_redirects proxy version + Http_Data timeout follow_redirects proxy version ## Send an Options request. @@ -644,7 +644,7 @@ type Http Method.Trace -> "TRACE" Method.Connect -> "CONNECT" case req_with_body of - Pair req body -> + Pair_Data req body -> # set method and body builder.method req_http_method body # set headers diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Form.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Form.enso index a90dd73a9c54..e44c5334df48 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Form.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Form.enso @@ -14,7 +14,7 @@ import Standard.Base.Data.Vector example_form_new = Form.new (Form.text_field "foo" "bar") new : Vector.Vector -> Form -new parts = Form parts +new parts = Form_Data parts # Helpers for creating different parts of the form. @@ -31,7 +31,7 @@ new parts = Form parts example_text_field = Form.text_field "Foo" "bar" text_field : Text -> Text -> Part -text_field key val = Part key (Part_Text val) +text_field key val = Part_Data key (Part_Text val) ## Create a file field of a Form. @@ -46,7 +46,7 @@ text_field key val = Part key (Part_Text val) example_text_field = Form.file_field "Foo" "My file contents" file_field : Text -> Text -> Part -file_field key file = Part key (Part_File file) +file_field key file = Part_Data key (Part_File file) ## The HTTP form containing a vector of parts. type Form @@ -57,7 +57,7 @@ type Form Arguments: - parts: A vector of form segments. - type Form parts + Form_Data parts ## Convert this to a Form. @@ -81,7 +81,7 @@ type Form part_1 = Form.text_field "Foo" "bar" part_2 = Form.text_field "Baz" "quux" [part_1, part_2].to_form -Vector.Vector.to_form self = Form self +Vector.Vector.to_form self = Form_Data self ## The key-value element of the form. type Part @@ -91,7 +91,7 @@ type Part Arguments: - key: The key for the form section. - value: The value of the form section. - type Part key value + Part_Data key value ## The value of the form element. type Part_Value @@ -100,10 +100,10 @@ type Part_Value Arguments: - part_text: The text for the form part. - type Part_Text part_text + Part_Text part_text ## A file value for a form part. Arguments: - part_file: The file for the form part. - type Part_File part_file + Part_File part_file diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Header.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Header.enso index 6272739d65a0..757f5e411458 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Header.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Header.enso @@ -17,7 +17,7 @@ polyglot java import org.enso.base.Http_Utils example_new = Header.new "My_Header" "my header's value" new : Text -> Text -> Header -new name value = Header name value +new name value = Header_Data name value # Accept @@ -33,7 +33,7 @@ new name value = Header name value example_accept = Header.accept "my_field" accept : Text -> Header -accept value = Header "Accept" value +accept value = Header_Data "Accept" value ## Create a header that accepts all (`"*/*"`). @@ -60,7 +60,7 @@ accept_all = accept "*/*" example_auth = Header.authorization "foo" authorization : Text -> Header -authorization value = Header "Authorization" value +authorization value = Header_Data "Authorization" value ## Create HTTP basic auth header. @@ -92,7 +92,7 @@ authorization_basic user pass = example_content_type = Header.content_type "my_type" content_type : Text -> Header -content_type value = Header "Content-Type" value +content_type value = Header_Data "Content-Type" value ## Header "Content-Type: application/json". @@ -163,7 +163,7 @@ type Header Arguments: - name: The header name. - value: The header value. - type Header name value + Header_Data name value ## Header equality. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Request.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Request.enso index c66e655001d3..26a6d2e41b57 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Request.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Request.enso @@ -25,7 +25,7 @@ import Standard.Base.System.File example_new = Request.new Method.Post (URI.parse "http://example.com") new : Method -> (Text | URI) -> Vector.Vector -> Request_Body -> Request new method addr (headers = []) (body = Request_Body.Empty) = - Panic.recover Any (Request method (Panic.rethrow (addr.to_uri)) headers body) + Panic.recover Any (Request_Data method (Panic.rethrow (addr.to_uri)) headers body) ## Create an Options request. @@ -136,7 +136,7 @@ type Request - uri: The URI for the request. - headers: A vector containing headers for the request. - body: The body of the request. - type Request method uri headers body + Request_Data method uri headers body ## Sets the header for the request. @@ -154,13 +154,13 @@ type Request with_header self key val = new_header = Header.new key val update_header p h = case p of - Pair acc True -> Pair (acc + [h]) True - Pair acc False -> - if h.name . equals_ignore_case key then Pair (acc + [new_header]) True else Pair (acc + [h]) False - new_headers = case self.headers.fold (Pair [] False) update_header of - Pair acc True -> acc - Pair acc False -> acc + [new_header] - Request self.method self.uri new_headers self.body + Pair_Data acc True -> Pair_Data (acc + [h]) True + Pair_Data acc False -> + if h.name . equals_ignore_case key then Pair_Data (acc + [new_header]) True else Pair_Data (acc + [h]) False + new_headers = case self.headers.fold (Pair_Data [] False) update_header of + Pair_Data acc True -> acc + Pair_Data acc False -> acc + [new_header] + Request_Data self.method self.uri new_headers self.body ## Sets the headers in the request. @@ -194,7 +194,7 @@ type Request example_with_body = Request.post (URI.parse "http://example.com") Request_Body.Empty |> _.with_body Request_Body.Empty with_body : Request_Body -> Request - with_body self new_body = Request self.method self.uri self.headers new_body + with_body self new_body = Request_Data self.method self.uri self.headers new_body ## Set the body text in the request encoded as "application/json". @@ -214,7 +214,7 @@ type Request with_json : (Text | Json) -> Request with_json self json_body = new_body = Request_Body.Json json_body - Request self.method self.uri self.headers new_body . with_headers [Header.application_json] + Request_Data self.method self.uri self.headers new_body . with_headers [Header.application_json] ## Set body as vector of parts encoded as "application/x-www-form-urlencoded". @@ -232,4 +232,4 @@ type Request with_form : (Vector | Form) -> Request with_form self parts = new_body = Request_Body.Form parts.to_form - Request self.method self.uri self.headers new_body . with_headers [Header.application_x_www_form_urlencoded] + Request_Data self.method self.uri self.headers new_body . with_headers [Header.application_x_www_form_urlencoded] diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Response.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Response.enso index d90cb9da0e13..797df6cf30d7 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Response.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Response.enso @@ -16,7 +16,7 @@ type Response Arguments: - internal_http_response: The internal represnetation of the HTTP response. - type Response internal_http_response + Response_Data internal_http_response ## Get the response headers. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Response/Body.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Response/Body.enso index 916b18db8d7d..730201156b5c 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Response/Body.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Response/Body.enso @@ -9,7 +9,7 @@ type Body Arguments: - bytes: The body of the response as binary data. - type Body bytes + Body_Data bytes ## Convert response body to Text. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Status_Code.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Status_Code.enso index acba8774226b..e8ed2684675c 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Status_Code.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Status_Code.enso @@ -6,164 +6,164 @@ type Status_Code Arguments: - code: The numeric representation of the code. - type Status_Code code + Status_Code_Data code ## 100 Continue. continue : Status_Code -continue = Status_Code 100 +continue = Status_Code_Data 100 ## 101 Switching Protocols. switching_protocols : Status_Code -switching_protocols = Status_Code 101 +switching_protocols = Status_Code_Data 101 ## 200 OK. ok : Status_Code -ok = Status_Code 200 +ok = Status_Code_Data 200 ## 201 Created. created : Status_Code -created = Status_Code 201 +created = Status_Code_Data 201 ## 202 Accepted. accepted : Status_Code -accepted = Status_Code 202 +accepted = Status_Code_Data 202 ## 203 Non-Authoritative Information. non_authoritative_information : Status_Code -non_authoritative_information = Status_Code 203 +non_authoritative_information = Status_Code_Data 203 ## 204 No Content. no_content : Status_Code -no_content = Status_Code 204 +no_content = Status_Code_Data 204 ## 205 Reset Content. reset_content : Status_Code -reset_content = Status_Code 205 +reset_content = Status_Code_Data 205 ## 206 Partial Content. partial_content : Status_Code -partial_content = Status_Code 206 +partial_content = Status_Code_Data 206 ## 300 Multiple Choices. multiple_choices : Status_Code -multiple_choices = Status_Code 300 +multiple_choices = Status_Code_Data 300 ## 301 Moved Permanently. moved_permanently : Status_Code -moved_permanently = Status_Code 301 +moved_permanently = Status_Code_Data 301 ## 302 Found. found : Status_Code -found = Status_Code 302 +found = Status_Code_Data 302 ## 303 See Other. see_other : Status_Code -see_other = Status_Code 303 +see_other = Status_Code_Data 303 ## 304 Not Modified. not_modified : Status_Code -not_modified = Status_Code 304 +not_modified = Status_Code_Data 304 ## 305 Use Proxy. use_proxy : Status_Code -use_proxy = Status_Code 305 +use_proxy = Status_Code_Data 305 ## 307 Temporary Redirect. temporary_redirect : Status_Code -temporary_redirect = Status_Code 307 +temporary_redirect = Status_Code_Data 307 ## 400 Bad Request. bad_request : Status_Code -bad_request = Status_Code 400 +bad_request = Status_Code_Data 400 ## 401 Unauthorized. unauthorized : Status_Code -unauthorized = Status_Code 401 +unauthorized = Status_Code_Data 401 ## 402 Payment Required. payment_required : Status_Code -payment_required = Status_Code 402 +payment_required = Status_Code_Data 402 ## 403 Forbidden. forbidden : Status_Code -forbidden = Status_Code 403 +forbidden = Status_Code_Data 403 ## 404 Not Found. not_found : Status_Code -not_found = Status_Code 404 +not_found = Status_Code_Data 404 ## 405 Method Not Allowed. method_not_allowed : Status_Code -method_not_allowed = Status_Code 405 +method_not_allowed = Status_Code_Data 405 ## 406 Not Acceptable. not_acceptable : Status_Code -not_acceptable = Status_Code 406 +not_acceptable = Status_Code_Data 406 ## 407 Proxy Authentication Required. proxy_authentication_required : Status_Code -proxy_authentication_required = Status_Code 407 +proxy_authentication_required = Status_Code_Data 407 ## 408 Request Timeout. request_timeout : Status_Code -request_timeout = Status_Code 408 +request_timeout = Status_Code_Data 408 ## 409 Conflict. conflict : Status_Code -conflict = Status_Code 409 +conflict = Status_Code_Data 409 ## 410 Gone. gone : Status_Code -gone = Status_Code 410 +gone = Status_Code_Data 410 ## 411 Length Required. length_required : Status_Code -length_required = Status_Code 411 +length_required = Status_Code_Data 411 ## 412 Precondition Failed. precondition_failed : Status_Code -precondition_failed = Status_Code 412 +precondition_failed = Status_Code_Data 412 ## 413 Request Entity Too Large. request_entity_too_large : Status_Code -request_entity_too_large = Status_Code 413 +request_entity_too_large = Status_Code_Data 413 ## 414 Request-URI Too Long. request_uri_too_long : Status_Code -request_uri_too_long = Status_Code 414 +request_uri_too_long = Status_Code_Data 414 ## 415 Unsupported Media Type. unsupported_media_type : Status_Code -unsupported_media_type = Status_Code 415 +unsupported_media_type = Status_Code_Data 415 ## 416 Requested Range Not Satisfiable. requested_range_not_satisfiable : Status_Code -requested_range_not_satisfiable = Status_Code 416 +requested_range_not_satisfiable = Status_Code_Data 416 ## 417 Expectation Failed. expectation_failed : Status_Code -expectation_failed = Status_Code 417 +expectation_failed = Status_Code_Data 417 ## 500 Internal Server Error. internal_server_error : Status_Code -internal_server_error = Status_Code 500 +internal_server_error = Status_Code_Data 500 ## 501 Not Implemented. not_implemented : Status_Code -not_implemented = Status_Code 501 +not_implemented = Status_Code_Data 501 ## 502 Bad Gateway. bad_gateway : Status_Code -bad_gateway = Status_Code 502 +bad_gateway = Status_Code_Data 502 ## 503 Service Unavailable. service_unavailable : Status_Code -service_unavailable = Status_Code 503 +service_unavailable = Status_Code_Data 503 ## 504 Gateway Timeout gateway_timeout : Status_Code -gateway_timeout = Status_Code 504 +gateway_timeout = Status_Code_Data 504 ## 505 HTTP Version Not Supported. http_version_not_supported : Status_Code -http_version_not_supported = Status_Code 505 +http_version_not_supported = Status_Code_Data 505 diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Version.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Version.enso index 96096e9f7f45..296153151a18 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Version.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Version.enso @@ -1,7 +1,7 @@ type Version ## HTTP version 1.1. - type Http_1_1 + Http_1_1 ## HTTP version 2. - type Http_2 + Http_2 diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Proxy.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Proxy.enso index 53e172d10748..30c413f6f1a3 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Proxy.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Proxy.enso @@ -4,13 +4,13 @@ from Standard.Base import all type Proxy ## The proxy is disabled. - type None + None ## Use the system proxy settings. - type System + System ## Use the provided proxy server. - type Proxy_Addr proxy_host proxy_port + Proxy_Addr proxy_host proxy_port ## Create new proxy settings from a host and port. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso index 460a6c1563d8..77bf13f46746 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso @@ -22,8 +22,8 @@ polyglot java import java.util.Optional example_parse = URI.parse "http://example.com" parse : Text -> URI ! Syntax_Error parse text = - Panic.catch_java Any (URI (Java_URI.create text)) java_exception-> - Error.throw (Syntax_Error ("URI syntax error: " + java_exception.getMessage)) + Panic.catch_java Any (URI_Data (Java_URI.create text)) java_exception-> + Error.throw (Syntax_Error_Data ("URI syntax error: " + java_exception.getMessage)) ## Convert Text to a URI. @@ -46,7 +46,7 @@ type URI Arguments: - internal_uri: The internal representation of the URI. - type URI internal_uri + URI_Data internal_uri ## Convert this to URI. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System.enso index 3bc9e0b4fc28..4eff5cfc5a01 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System.enso @@ -69,4 +69,5 @@ default_line_separator = Java_System.lineSeparator - 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 +type System_Process_Result + System_Process_Result_Data exit_code stdout stderr 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 fb1272919688..d7c10d6a030c 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 @@ -51,7 +51,7 @@ find_caller_script stack = find_caller idx = source = stack.at idx . source_location - if source.is_a Source_Location then stack.at idx . source_location . file else + if source.is_a Source_Location_Data then stack.at idx . source_location . file else if (idx + 1 == stack.length) then Nothing else @Tail_Call find_caller (idx + 1) @@ -99,7 +99,7 @@ Suite.run : Any -> Suite_Config -> Any Suite.run ~specs config = builder = if config.should_output_junit then StringBuilder.new else Nothing wrap_junit_testsuites config builder <| - State.run Suite (Suite config Nil builder) <| + State.run Suite (Suite_Data config Nil builder) <| specs State.get Suite @@ -168,7 +168,7 @@ specify label ~behavior pending=Nothing = Nothing -> run_spec behavior reason -> Pending reason spec = State.get Spec - new_spec = Spec spec.name (Cons (Behavior label result) spec.behaviors) + new_spec = Spec spec.name (Cons (Behavior_Data label result) spec.behaviors) State.put Spec new_spec ## PRIVATE @@ -607,7 +607,7 @@ type Verbs ## PRVATE type Suite_Config - type Suite_Config_Data only_group_regexp output_path + Suite_Config_Data only_group_regexp output_path should_run_group self name = regexp = self.only_group_regexp @@ -723,14 +723,14 @@ run_spec ~behavior = recovery = Panic.recover Any <| result = behavior result.catch Any err-> - Panic.throw (Finished_With_Error err result.get_stack_trace_text) + Panic.throw (Finished_With_Error_Data err result.get_stack_trace_text) Nothing maybeExc = case recovery of _ -> Success result = maybeExc.catch Any ex-> case ex of Failure _ -> ex - Finished_With_Error err stack_trace_text -> + Finished_With_Error_Data err stack_trace_text -> Failure ("An unexpected error was returned: " + err.to_display_text + '\n' + stack_trace_text) _ -> Failure ("An unexpected panic was thrown: " + ex.to_display_text + '\n' + maybeExc.get_stack_trace_text) result diff --git a/engine/runner/src/main/scala/org/enso/runner/Main.scala b/engine/runner/src/main/scala/org/enso/runner/Main.scala index 5f3af924e131..f9b0633eb197 100644 --- a/engine/runner/src/main/scala/org/enso/runner/Main.scala +++ b/engine/runner/src/main/scala/org/enso/runner/Main.scala @@ -704,6 +704,7 @@ object Main { .dropWhile(_.getLanguage.getId != LanguageInfo.ID) .reverse println(s"Execution finished with an error: ${exception.getMessage}") + exception.printStackTrace() dropInitJava.foreach { frame => val langId = if (frame.isHostFrame) "java" else frame.getLanguage.getId diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java index 2f429c53df83..bc436d89b5c1 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ModuleDoesNotExist.java @@ -6,6 +6,7 @@ import java.util.List; +@BuiltinType public class ModuleDoesNotExist extends UniquelyConstructibleBuiltin { @Override protected List getConstructorParamNames() { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java index 0ead0203f2c3..d2722998d85e 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchConversionError.java @@ -6,6 +6,7 @@ import java.util.List; +@BuiltinType public class NoSuchConversionError extends UniquelyConstructibleBuiltin { @Override protected List getConstructorParamNames() { 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 dbd6fdbb9066..66cdfd9782ad 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala @@ -824,14 +824,14 @@ class Compiler( source: Source ): Boolean = { val errors = diagnostics.collect { case e: IR.Error => e } - val warnings = diagnostics.collect { case w: IR.Warning => w } - - if (warnings.nonEmpty) { - context.getOut.println("Compiler encountered warnings:") - warnings.foreach { warning => - context.getOut.println(formatDiagnostic(warning, source)) - } - } +// val warnings = diagnostics.collect { case w: IR.Warning => w } + +// if (warnings.nonEmpty) { +// context.getOut.println("Compiler encountered warnings:") +// warnings.foreach { warning => +// context.getOut.println(formatDiagnostic(warning, source)) +// } +// } if (errors.nonEmpty) { context.getOut.println("Compiler encountered errors:") 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 26b7cad7e3e2..825d46b848d3 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 @@ -1124,12 +1124,20 @@ class IrToTruffle( tp.module.unsafeAsModule().getScope.getTypes.get(tp.tp.name) ) case BindingsMap.ResolvedConstructor(definitionModule, cons) => - ConstructorNode.build( - definitionModule - .unsafeAsModule() - .getScope - .getConstructors - .get(cons.name) + val c = definitionModule + .unsafeAsModule() + .getScope + .getConstructors + .get(cons.name) + if (c == null) { + throw new CompilerError(s"Constructor for $cons is null") + } + ConstructorNode.build(c +// definitionModule +// .unsafeAsModule() +// .getScope +// .getConstructors +// .get(cons.name) ) case BindingsMap.ResolvedModule(module) => ConstantObjectNode.build( 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 d4583c6df5ba..18da73cf57bc 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 @@ -28,7 +28,7 @@ class RuntimeStubsGenerator(builtins: Builtins) { if (tp.builtinType) { val builtinType = builtins.getBuiltinType(tp.name) if (builtinType == null) { - throw new CompilerError("Unknown @BuiltinType " + tp.name) + throw new CompilerError("Unknown @Builtin_Type " + tp.name) } if ( Set(tp.members: _*) != Set(builtinType.getConstructors.toIndexedSeq: _*) 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 a3c52d3eb4a3..3525076bb23d 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 @@ -6617,13 +6617,13 @@ object IR { override def diagnosticKeys(): Array[Any] = Array(ir.showCode(), reason) } - case class NonUnitTypeUsedOnValueLevel(ir: IR.Name) extends Warning { + case class NonUnitTypeUsedOnValueLevel(ir: IR.Name, context: String) extends Warning { /** @return a human-readable description of this error condition. */ override def message: String = - s"A non-unit type ${ir.name} is used on value level." + - " This is probably an error" + s"A non-unit type ${ir.name} is used on value level (in ${context})." + + " This is probably an error." /** The location at which the diagnostic occurs. */ override val location: Option[IdentifiedLocation] = ir.location @@ -6921,6 +6921,19 @@ object IR { s"but polyglot symbols are not allowed in $context." } + /** An error coming from an unexpected occurence of a constructor. + * + * @param context the description of a context in which the error + * happened. + */ + case class UnexpectedConstructor(context: String) extends Reason { + override def explain(originalName: Name): String = + s"The name ${originalName.name} resolved to a constructor, " + + s"but constructors are not allowed in $context." + } + + + /** An error coming from an unexpected occurence of a static method. * * @param context the description of a context in which the error 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 f12255b3aad0..1351aba4429d 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 @@ -958,36 +958,6 @@ object BindingsMap { */ case object ResolutionNotFound extends ResolutionError - /** A metadata-friendly storage for resolutions */ - case class TypeResolution(target: ResolvedName) extends IRPass.Metadata { - - /** The name of the metadata as a string. */ - override val metadataName: String = "Resolution" - - /** @inheritdoc */ - override def prepareForSerialization(compiler: Compiler): TypeResolution = - this.copy(target = this.target.toAbstract) - - /** @inheritdoc */ - override def restoreFromSerialization( - compiler: Compiler - ): Option[TypeResolution] = { - val moduleMap = compiler.context.getPackageRepository.getModuleMap - this.target.toConcrete(moduleMap).map(t => this.copy(target = t)) - } - - /** Creates a duplicate of this metadata if applicable. - * - * This method should employ deep-copy semantics where appropriate. It may - * return None to indicate that this metadata should not be preserved - * during duplication. - * - * @return Some duplicate of this metadata or None if this metadata should - * not be preserved - */ - override def duplicate(): Option[IRPass.Metadata] = Some(this) - } - /** A metadata-friendly storage for resolutions */ case class Resolution(target: ResolvedName) extends IRPass.Metadata { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala index dfdaa37f542b..b110b37f1dc0 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala @@ -158,7 +158,14 @@ case object GlobalNames extends IRPass { } case Right(res @ BindingsMap.ResolvedType(_, tp)) => val warned = if (tp.members.nonEmpty) { - lit.addDiagnostic(IR.Warning.NonUnitTypeUsedOnValueLevel(lit)) + lit.addDiagnostic( + IR.Warning.NonUnitTypeUsedOnValueLevel( + lit, + if (isInsideApplication) { + "a constructor position" + } else { "an argument position" } + ) + ) } else { lit } @@ -241,7 +248,10 @@ case object GlobalNames extends IRPass { Some( app .copy(function = processedFun, arguments = processedArgs) - .addDiagnostic(IR.Warning.NonUnitTypeUsedOnValueLevel(funAsVar)) + .addDiagnostic( + IR.Warning + .NonUnitTypeUsedOnValueLevel(funAsVar, "a qualified call") + ) ) } else { None } case ( diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala index 65ba61c622b1..ae7a4b43f387 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/MethodDefinitions.scala @@ -105,9 +105,12 @@ case object MethodDefinitions extends IRPass { typePointer, IR.Error.Resolution.ResolverError(err) ) - case Right(value: BindingsMap.ResolvedConstructor) => - typePointer.updateMetadata( - this -->> BindingsMap.Resolution(value) + case Right(_: BindingsMap.ResolvedConstructor) => + IR.Error.Resolution( + typePointer, + IR.Error.Resolution.UnexpectedConstructor( + "a method definition target" + ) ) case Right(value: BindingsMap.ResolvedModule) => typePointer.updateMetadata( diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala index 4f1ca4e2e436..e709fb0f023c 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/TypeNames.scala @@ -4,7 +4,7 @@ import org.enso.compiler.context.{InlineContext, ModuleContext} import org.enso.compiler.core.IR import org.enso.compiler.core.ir.MetadataStorage.ToPair import org.enso.compiler.data.BindingsMap -import org.enso.compiler.data.BindingsMap.TypeResolution +import org.enso.compiler.data.BindingsMap.Resolution import org.enso.compiler.pass.IRPass import org.enso.compiler.pass.analyse.BindingAnalysis @@ -15,7 +15,7 @@ import scala.annotation.unused case object TypeNames extends IRPass { /** The type of the metadata object that the pass writes to the IR. */ - override type Metadata = BindingsMap.TypeResolution + override type Metadata = BindingsMap.Resolution /** The type of configuration for the pass. */ override type Config = IRPass.Configuration.Default @@ -77,7 +77,7 @@ case object TypeNames extends IRPass { expression.transformExpressions { case n: IR.Name.Literal => bindingsMap .resolveName(n.name) - .map(res => n.updateMetadata(this -->> TypeResolution(res))) + .map(res => n.updateMetadata(this -->> Resolution(res))) .getOrElse(n) } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/VectorLiterals.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/VectorLiterals.scala index 49d3f1711a29..d4b755fbb96d 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/VectorLiterals.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/VectorLiterals.scala @@ -100,7 +100,7 @@ case object VectorLiterals extends IRPass { BindingsMap .ResolvedConstructor( ModuleReference.Concrete(module), - BindingsMap.Cons("Vector", 1, allFieldsDefaulted = false) + BindingsMap.Cons("Vector_Data", 1, allFieldsDefaulted = false) ) ) ) diff --git a/test/Tests/src/Data/Json_Spec.enso b/test/Tests/src/Data/Json_Spec.enso index a383e3037473..7fd14cab30eb 100644 --- a/test/Tests/src/Data/Json_Spec.enso +++ b/test/Tests/src/Data/Json_Spec.enso @@ -10,7 +10,7 @@ Text.should_fail_parsing_with self expected = as_fail = case Json.parse self of _ -> Test.Failure "Expected a parse error, but no error reported." result = as_fail.catch Any e-> case e of - Json.Parse_Error msg -> + Json.Parse_Error_Data msg -> if msg.contains expected then Test.Success else fail_msg = "The reported message " + msg.to_text + " did not contain " + expected.to_text + "." Test.Failure fail_msg diff --git a/test/Tests/src/Data/Text/Encoding_Spec.enso b/test/Tests/src/Data/Text/Encoding_Spec.enso index 61e43e497853..0094d4c96439 100644 --- a/test/Tests/src/Data/Text/Encoding_Spec.enso +++ b/test/Tests/src/Data/Text/Encoding_Spec.enso @@ -8,14 +8,14 @@ import Standard.Test.Problems spec = Test.group "Encoding object" <| Test.specify "Can get standard UTF encodings" <| - Encoding.utf_8 . should_equal (Encoding "UTF-8") - Encoding.utf_16_le . should_equal (Encoding "UTF-16LE") - Encoding.utf_16_be . should_equal (Encoding "UTF-16BE") - Encoding.utf_32_le . should_equal (Encoding "UTF-32LE") - Encoding.utf_32_be . should_equal (Encoding "UTF-32BE") + Encoding.utf_8 . should_equal (Encoding_Data "UTF-8") + Encoding.utf_16_le . should_equal (Encoding_Data "UTF-16LE") + Encoding.utf_16_be . should_equal (Encoding_Data "UTF-16BE") + Encoding.utf_32_le . should_equal (Encoding_Data "UTF-32LE") + Encoding.utf_32_be . should_equal (Encoding_Data "UTF-32BE") Test.specify "Catches invalid character sets" <| - invalid = Encoding "NotAValidCharacterSet" + invalid = Encoding_Data "NotAValidCharacterSet" invalid.to_java_charset . should_fail_with Illegal_Argument_Error Test.specify "Can get full set of character sets" <| @@ -49,13 +49,13 @@ spec = Test.specify "Invalid ASCII should raise a warning when decoding" <| action = Text.from_bytes invalid_ascii Encoding.ascii on_problems=_ tester result = result . should_equal invalid - problems = [Encoding_Error "Encoding issues at 12."] + problems = [Encoding_Error_Data "Encoding issues at 12."] Problems.test_problem_handling action problems tester Test.specify "Invalid ASCII should raise a warning when encoding" <| action = invalid.bytes Encoding.ascii on_problems=_ tester result = result . should_equal invalid_ascii_out - problems = [Encoding_Error "Encoding issues at 12."] + problems = [Encoding_Error_Data "Encoding issues at 12."] Problems.test_problem_handling action problems tester Test.group "UTF_8" <| @@ -88,13 +88,13 @@ spec = Test.specify "Invalid UTF-8 should raise a warning when decoding via encoding" <| action = Text.from_bytes invalid_utf_8 Encoding.utf_8 on_problems=_ tester result = result . should_equal invalid - problems = [Encoding_Error "Encoding issues at 19."] + problems = [Encoding_Error_Data "Encoding issues at 19."] Problems.test_problem_handling action problems tester Test.specify "Invalid UTF-8 should raise a warning when decoding" <| action = Text.from_utf_8 invalid_utf_8 on_problems=_ tester result = result . should_equal invalid - problems = [Encoding_Error "Encoding issues at 19."] + problems = [Encoding_Error_Data "Encoding issues at 19."] Problems.test_problem_handling action problems tester Test.group "UTF_16 BigEndian" <| @@ -156,13 +156,13 @@ spec = Test.specify "Invalid Windows-1252 should raise a warning when decoding" <| action = Text.from_bytes invalid_windows Encoding.windows_1252 on_problems=_ tester result = result . should_equal invalid - problems = [Encoding_Error "Encoding issues at 16."] + problems = [Encoding_Error_Data "Encoding issues at 16."] Problems.test_problem_handling action problems tester Test.specify "Invalid Windows-1252 should raise a warning when encoding" <| action = invalid.bytes Encoding.windows_1252 on_problems=_ tester result = result . should_equal invalid_windows_out - problems = [Encoding_Error "Encoding issues at 16."] + problems = [Encoding_Error_Data "Encoding issues at 16."] Problems.test_problem_handling action problems tester main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Time/Date_Spec.enso b/test/Tests/src/Data/Time/Date_Spec.enso index 2694c1b83480..11829ef2ef8f 100644 --- a/test/Tests/src/Data/Time/Date_Spec.enso +++ b/test/Tests/src/Data/Time/Date_Spec.enso @@ -27,7 +27,7 @@ specWith name create_new_date parse_date = Test.specify "should handle errors when creating local date" <| case create_new_date 2020 30 30 . catch of - Time.Time_Error msg -> + Time.Time_Error_Data msg -> msg . should_equal "Invalid value for MonthOfYear (valid values 1 - 12): 30" result -> Test.fail ("Unexpected result: " + result.to_text) @@ -49,7 +49,7 @@ specWith name create_new_date parse_date = Test.specify "should throw error when parsing invalid date" <| case parse_date "birthday" . catch of - Time.Time_Error msg -> + Time.Time_Error_Data msg -> msg . should_equal "Text 'birthday' could not be parsed at index 0" result -> Test.fail ("Unexpected result: " + result.to_text) @@ -69,7 +69,7 @@ specWith name create_new_date parse_date = Test.specify "should throw error when parsing custom format" <| date = parse_date "1999-01-01" "yyyy M d" case date.catch of - Time.Time_Error msg -> + Time.Time_Error_Data msg -> msg . should_equal "Text '1999-01-01' could not be parsed at index 4" result -> Test.fail ("Unexpected result: " + result.to_text) @@ -110,14 +110,14 @@ specWith name create_new_date parse_date = Test.specify "should throw error when adding time-based interval" <| case (create_new_date 1970 + 1.hour) . catch of - Time.Time_Error message -> + Time.Time_Error_Data message -> message . should_equal "Date does not support time intervals" result -> Test.fail ("Unexpected result: " + result.to_text) Test.specify "should throw error when subtracting time-based interval" <| case (create_new_date 1970 - (1.day - 1.minute)) . catch of - Time.Time_Error message -> + Time.Time_Error_Data message -> message . should_equal "Date does not support time intervals" result -> Test.fail ("Unexpected result: " + result.to_text) @@ -148,15 +148,15 @@ js_parse text format=Nothing = js_date d.year d.month d.day js_date year month=1 day=1 = - Panic.catch Any (js_date_impl year month day) (err -> Error.throw (Time.Time_Error err.payload.cause)) + Panic.catch Any (js_date_impl year month day) (err -> Error.throw (Time.Time_Error_Data err.payload.cause)) js_array_date year month=1 day=1 = - arr = Panic.catch Any (js_array_dateCreate year month day) (err -> Error.throw (Time.Time_Error err.payload.cause)) + arr = Panic.catch Any (js_array_dateCreate year month day) (err -> Error.throw (Time.Time_Error_Data err.payload.cause)) arr.at(0) java_date year month=1 day=1 = - Panic.catch Any (LocalDate.of year month day) (err -> Error.throw (Time.Time_Error <| err.payload.to_display_text.drop (Text_Sub_Range.First 16))) + Panic.catch Any (LocalDate.of year month day) (err -> Error.throw (Time.Time_Error_Data <| err.payload.to_display_text.drop (Text_Sub_Range.First 16))) foreign js js_date_impl year month=1 day=1 = """ if (month > 12) { diff --git a/test/Tests/src/Data/Time/Time_Of_Day_Spec.enso b/test/Tests/src/Data/Time/Time_Of_Day_Spec.enso index 1f9acd332a12..ec0118807df7 100644 --- a/test/Tests/src/Data/Time/Time_Of_Day_Spec.enso +++ b/test/Tests/src/Data/Time/Time_Of_Day_Spec.enso @@ -19,7 +19,7 @@ spec = Test.specify "should handle errors when creating a time" <| case Time_Of_Day.new 24 0 0 . catch of - Time.Time_Error msg -> + Time.Time_Error_Data msg -> msg . should_equal "Invalid value for HourOfDay (valid values 0 - 23): 24" result -> Test.fail ("Unexpected result: " + result.to_text) @@ -49,7 +49,7 @@ spec = Test.specify "should throw error when parsing invalid time" <| case Time_Of_Day.parse "1200" . catch of - Time.Time_Error msg -> + Time.Time_Error_Data msg -> msg . should_equal "Text '1200' could not be parsed at index 2" result -> Test.fail ("Unexpected result: " + result.to_text) @@ -61,7 +61,7 @@ spec = Test.specify "should throw error when parsing custom format" <| time = Time_Of_Day.parse "12:30" "HH:mm:ss" case time.catch of - Time.Time_Error msg -> + Time.Time_Error_Data msg -> msg . should_equal "Text '12:30' could not be parsed at index 5" result -> Test.fail ("Unexpected result: " + result.to_text) @@ -91,14 +91,14 @@ spec = Test.specify "should throw error when adding date-based interval" <| case (Time_Of_Day.new + 1.day) . catch of - Time.Time_Error message -> + Time.Time_Error_Data message -> message . should_equal "Time_Of_Day does not support date intervals" result -> Test.fail ("Unexpected result: " + result.to_text) Test.specify "should throw error when subtracting date-based interval" <| case (Time_Of_Day.new - (1.day - 1.minute)) . catch of - Time.Time_Error message -> + Time.Time_Error_Data message -> message . should_equal "Time_Of_Day does not support date intervals" result -> Test.fail ("Unexpected result: " + result.to_text) diff --git a/test/Tests/src/Data/Time/Time_Spec.enso b/test/Tests/src/Data/Time/Time_Spec.enso index daaa44ca1878..3ffd0b3b05e9 100644 --- a/test/Tests/src/Data/Time/Time_Spec.enso +++ b/test/Tests/src/Data/Time/Time_Spec.enso @@ -22,7 +22,7 @@ spec = Test.specify "should handle errors when creating time" <| case Time.new 1970 0 0 . catch of - Time.Time_Error msg -> + Time.Time_Error_Data msg -> msg . should_equal "Invalid value for MonthOfYear (valid values 1 - 12): 0" result -> Test.fail ("Unexpected result: " + result.to_text) @@ -110,7 +110,7 @@ spec = Test.specify "should throw error when parsing invalid time" <| case Time.parse "2008-1-1" . catch of - Time.Time_Error msg -> + Time.Time_Error_Data msg -> msg . should_equal "Text '2008-1-1' could not be parsed at index 5" result -> Test.fail ("Unexpected result: " + result.to_text) @@ -139,7 +139,7 @@ spec = Test.specify "should throw error when parsing custom format" <| time = Time.parse "2008-01-01" "yyyy-MM-dd'T'HH:mm:ss'['z']'" case time.catch of - Time.Time_Error msg -> + Time.Time_Error_Data msg -> msg . should_equal "Text '2008-01-01' could not be parsed at index 10" result -> Test.fail ("Unexpected result: " + result.to_text) diff --git a/test/Tests/src/Runtime/Lazy_Generator_Spec.enso b/test/Tests/src/Runtime/Lazy_Generator_Spec.enso index 73ce5b14630d..3c876183a535 100644 --- a/test/Tests/src/Runtime/Lazy_Generator_Spec.enso +++ b/test/Tests/src/Runtime/Lazy_Generator_Spec.enso @@ -1,15 +1,16 @@ import Standard.Test -type Generator h t +type Generator + Generator_Data h t natural = - gen ~n = if (n >= 10) then self else Generator n (@Tail_Call gen n+1) + gen ~n = if (n >= 10) then self else Generator_Data n (@Tail_Call gen n+1) gen 2 Generator.n self = case self of - Generator n _ -> n + Generator_Data n _ -> n Generator.next self = case self of - Generator _ n -> n + Generator_Data _ n -> n spec = Test.group "Lazy Generator" <| Test.specify "Generates four numbers properly" <| diff --git a/test/Tests/src/Semantic/Error_Spec.enso b/test/Tests/src/Semantic/Error_Spec.enso index 8b1a23443758..51aa5859cf04 100644 --- a/test/Tests/src/Semantic/Error_Spec.enso +++ b/test/Tests/src/Semantic/Error_Spec.enso @@ -8,7 +8,8 @@ polyglot java import java.lang.NumberFormatException import Standard.Test -type My_Type foo +type My_Type + My_Type_Data foo throw_a_bar = Error.throw "bar" throw_a_bar_panicking = Panic.throw "bar" @@ -21,7 +22,7 @@ spec = Test.specify "should be recoverable" <| err_1 = Panic.recover Any (123 . foobar "baz") . catch err_2 = Panic.recover Any ("foo" . baz 123) . catch - err_3 = Panic.recover Any (My_Type False . nope) . catch + err_3 = Panic.recover Any (My_Type_Data False . nope) . catch err_1.target.should_equal 123 err_1.method_name.should_equal "foobar" @@ -40,17 +41,17 @@ spec = Test.specify "should allow recovery of only a specific error-type" <| recover_illegal_argument ~action = - action . catch Illegal_Argument_Error err-> + action . catch Illegal_Argument_Error_Data err-> "recovered error: "+err.message - (recover_illegal_argument (Error.throw (Illegal_Argument_Error "foo"))) . should_equal "recovered error: foo" - (recover_illegal_argument (Error.throw (Illegal_State_Error "bar"))) . should_fail_with Illegal_State_Error + (recover_illegal_argument (Error.throw (Illegal_Argument_Error_Data "foo"))) . should_equal "recovered error: foo" + (recover_illegal_argument (Error.throw (Illegal_State_Error_Data "bar"))) . should_fail_with Illegal_State_Error_Data Test.specify "should be able to be shown in the default visualization" <| - json = (Error.throw <| My_Type "aaa").to_default_visualization_data + json = (Error.throw <| My_Type_Data "aaa").to_default_visualization_data json . should_equal <| (Json.from_pairs [["foo", "aaa"], ["type", "My_Type"]]).to_text Test.specify "should be able to be shown in the default vector visualization" <| - vec = [My_Type "bar", Error.throw (My_Type 42)] + vec = [My_Type_Data "bar", Error.throw (My_Type_Data 42)] visualization_text = vec.to_default_visualization_data expected_json = Json.parse ''' [ @@ -148,21 +149,21 @@ spec = Test.specify "should work as in the examples" <| fun ~act = Panic.catch Any act caught_panic-> case caught_panic.payload of - Illegal_Argument_Error message _ -> "Illegal arguments were provided: "+message + Illegal_Argument_Error_Data message _ -> "Illegal arguments were provided: "+message other_panic -> Panic.throw other_panic Panic.recover Any (fun "bar") . should_equal "bar" Panic.recover Any (fun (Panic.throw "foo")) . catch . should_equal "foo" - Panic.recover Any (fun (Panic.throw (Illegal_Argument_Error "msg" Nothing))) . should_equal "Illegal arguments were provided: msg" + Panic.recover Any (fun (Panic.throw (Illegal_Argument_Error_Data "msg" Nothing))) . should_equal "Illegal arguments were provided: msg" Test.specify "should allow catching Java exceptions easily" <| 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) + Error.throw (Illegal_Argument_Error_Data "The provided string is not a valid number: "+caught_panic.payload.cause.getMessage) parse "42" . should_equal 42 dataflow_error = parse "foo" - dataflow_error.catch . should_equal (Illegal_Argument_Error 'The provided string is not a valid number: For input string: "foo"') - Test.expect_panic_with (parse 0.0) Unsupported_Argument_Types + dataflow_error.catch . should_equal (Illegal_Argument_Error_Data 'The provided string is not a valid number: For input string: "foo"') + Test.expect_panic_with (parse 0.0) Unsupported_Argument_Types_Data Test.specify "should allow to throw raw Java exceptions" <| exception = Panic.catch_java NumberFormatException (throw_raw_java "foo") (p -> p) @@ -171,7 +172,7 @@ spec = caught_panic = Panic.catch Any (throw_raw_java "foo") x->x caught_panic.stack_trace.second.name . should_equal "Error_Spec.throw_raw_java" - caught_panic.payload . should_be_a Polyglot_Error + caught_panic.payload . should_be_a Polyglot_Error_Data Test.specify "should allow to re-throw raw Java exceptions" <| message_1 = Ref.new "" @@ -180,7 +181,7 @@ spec = message_1 . put caught_panic.payload.cause.getMessage Panic.throw caught_panic.payload.cause message_1.get . should_equal 'For input string: "foo"' - caught_1.catch . should_be_a Polyglot_Error + caught_1.catch . should_be_a Polyglot_Error_Data caught_1.stack_trace.at 2 . name . should_equal "Error_Spec.do_a_parse" message_2 = Ref.new "" @@ -189,29 +190,29 @@ spec = message_2.put caught_panic.payload.cause.getMessage Panic.throw caught_panic.payload.cause message_2.get . should_equal "foo" - caught_2.catch . should_be_a Polyglot_Error + caught_2.catch . should_be_a Polyglot_Error_Data caught_2.stack_trace.second.name . should_equal "Error_Spec.throw_raw_java" Test.specify "should allow to catch a specific panic type easily" <| - message_1 = Panic.catch Illegal_Argument_Error (Panic.throw (Illegal_Argument_Error "msg" Nothing)) caught_panic-> + message_1 = Panic.catch Illegal_Argument_Error_Data (Panic.throw (Illegal_Argument_Error "msg" Nothing)) caught_panic-> caught_panic.payload.message message_1 . should_equal "msg" - error = Panic.recover Any <| Panic.catch Illegal_Argument_Error (Panic.throw (Illegal_State_Error "foo" Nothing)) caught_panic-> + error = Panic.recover Any <| Panic.catch Illegal_Argument_Error_Data (Panic.throw (Illegal_State_Error_Data "foo" Nothing)) caught_panic-> caught_panic.payload.message - error.catch . should_be_an Illegal_State_Error + error.catch . should_be_an Illegal_State_Error_Data - message_2 = Panic.catch Any (Panic.throw (Illegal_Argument_Error "msg" Nothing)) _-> + message_2 = Panic.catch Any (Panic.throw (Illegal_Argument_Error_Data "msg" Nothing)) _-> "caught" message_2 . should_equal "caught" - message_3 = Panic.catch Polyglot_Error (Long.parseLong "foo") _-> + message_3 = Panic.catch Polyglot_Error_Data (Long.parseLong "foo") _-> "polyglot" message_3 . should_equal "polyglot" message_4 = Panic.catch Any (Long.parseLong "foo") _-> "polyglot2" message_4 . should_equal "polyglot2" - message_5 = Panic.catch Unsupported_Argument_Types (Long.parseLong 0) _-> + message_5 = Panic.catch Unsupported_Argument_Types_Data (Long.parseLong 0) _-> "uat" message_5 . should_equal "uat" diff --git a/test/Tests/src/Semantic/Js_Interop_Spec.enso b/test/Tests/src/Semantic/Js_Interop_Spec.enso index e87e98bc6af3..d6275c19fabc 100644 --- a/test/Tests/src/Semantic/Js_Interop_Spec.enso +++ b/test/Tests/src/Semantic/Js_Interop_Spec.enso @@ -9,7 +9,7 @@ foreign js debug = """ debugger; type My_Type - type My_Type a b + My_Type_Data a b foreign js my_method this = """ return this.a + this.b; @@ -80,7 +80,7 @@ spec = Test.group "Polyglot JS" <| m 2 . should_equal 3 Test.specify "should allow mutual calling of instance-level methods" <| - My_Type 3 4 . my_method_3 5 . should_equal 36 + My_Type_Data 3 4 . my_method_3 5 . should_equal 36 Test.specify "should expose methods and fields of JS objects" <| obj = make_object @@ -146,14 +146,14 @@ spec = Test.group "Polyglot JS" <| num_double_match.should_be_true Test.specify "should allow Enso to catch JS exceptions" <| - value = My_Type 1 2 + value = My_Type_Data 1 2 result = Panic.recover Any <| value.my_throw err = result.catch err.cause.message . should_equal "JS Exc" err.cause.name . should_equal "Error" Test.specify "should allow JS to catch Enso exceptions" <| - value = My_Type 7 2 + value = My_Type_Data 7 2 result = value.do_catch result . should_equal 7 diff --git a/test/Tests/src/Semantic/Names/Definitions.enso b/test/Tests/src/Semantic/Names/Definitions.enso index 1d0c6d063d8c..6359d8799205 100644 --- a/test/Tests/src/Semantic/Names/Definitions.enso +++ b/test/Tests/src/Semantic/Names/Definitions.enso @@ -1,7 +1,8 @@ -type Foo a b c +type Foo + Foo_Data a b c Foo.sum self = case self of - Foo a b c -> a + b + c + Foo_Data a b c -> a + b + c another_constant = 10 @@ -13,6 +14,6 @@ method_with_local_vars a = bar + (another_constant a) type Bar - type Bar a + Bar_Data a meh self x = self.a + x diff --git a/test/Tests/src/Semantic/Names_Spec.enso b/test/Tests/src/Semantic/Names_Spec.enso index ea39abe5f874..f09ce4eaf151 100644 --- a/test/Tests/src/Semantic/Names_Spec.enso +++ b/test/Tests/src/Semantic/Names_Spec.enso @@ -5,7 +5,7 @@ from project.Semantic.Names.Definitions import another_method, another_constant, import Standard.Test Definitions.Foo.my_method self = case self of - Definitions.Foo x y z -> x * y * z + Definitions.Foo_Data x y z -> x * y * z get_foo module = module.Foo @@ -16,15 +16,15 @@ add_one (x = 0) = x + 1 spec = Test.group "Qualified Names" <| Test.specify "should allow to call constructors in a qualified manner" <| - Definitions.Foo 1 2 3 . sum . should_equal 6 - Definitions . Foo 1 2 3 . sum . should_equal 6 + Definitions.Foo_Data 1 2 3 . sum . should_equal 6 + Definitions . Foo_Data 1 2 3 . sum . should_equal 6 Test.specify "should allow pattern matching in a qualified manner" <| - v = Definitions.Foo 1 2 3 + v = Definitions.Foo_Data 1 2 3 res = case v of - Definitions.Foo a b c -> a + b + c + Definitions.Foo_Data a b c -> a + b + c res.should_equal 6 Test.specify "should allow defining methods on qualified names" <| - v = Definitions.Foo 2 3 5 + v = Definitions.Foo_Data 2 3 5 v.my_method.should_equal 30 Test.group "Lowercase Methods" <| Test.specify "should allow calling methods without a target" <| @@ -44,8 +44,8 @@ spec = method_with_local_vars 1 . should_equal 13 Test.group "Methods" <| Test.specify "should be correctly resolved on instances" <| - b = Bar 1 + b = Bar_Data 1 b.meh 2 . should_equal 3 Test.specify "should be allowed to be called statically" pending="Needs changes to method dispatch logic" <| - b = Bar 1 + b = Bar_Data 1 Bar.meh b 2 . should_equal 3 diff --git a/test/Tests/src/Semantic/Python_Interop_Spec.enso b/test/Tests/src/Semantic/Python_Interop_Spec.enso index b0512edb001f..bd42d92fbb42 100644 --- a/test/Tests/src/Semantic/Python_Interop_Spec.enso +++ b/test/Tests/src/Semantic/Python_Interop_Spec.enso @@ -6,7 +6,7 @@ foreign python my_method a b = """ return a + b type My_Type - type My_Type a b + My_Type_Data a b foreign python my_method self = """ return self.a + self.b @@ -75,7 +75,7 @@ spec = my_method 1 2 . should_equal 3 Test.specify "should allow mutual calling of instance-level methods" <| - My_Type 3 4 . my_method_3 5 . should_equal 36 + My_Type_Data 3 4 . my_method_3 5 . should_equal 36 Test.specify "should expose methods and fields of Python objects" <| obj = make_object @@ -141,14 +141,14 @@ spec = num_double_match.should_be_true Test.specify "should allow Enso to catch Python exceptions" <| - value = My_Type 1 2 + value = My_Type_Data 1 2 result = Panic.recover Any <| value.my_throw err = result.catch err.cause.args.at 0 . should_equal 'Error!' err.cause.to_text . should_equal "RuntimeError('Error!')" Test.specify "should allow Python to catch Enso exceptions" <| - value = My_Type 7 2 + value = My_Type_Data 7 2 result = value.do_catch result . should_equal 7 diff --git a/test/Tests/src/Semantic/R_Interop_Spec.enso b/test/Tests/src/Semantic/R_Interop_Spec.enso index 462843f37688..c8c5c9a2b981 100644 --- a/test/Tests/src/Semantic/R_Interop_Spec.enso +++ b/test/Tests/src/Semantic/R_Interop_Spec.enso @@ -6,7 +6,7 @@ foreign js my_method a b = """ return a + b; type My_Type - type My_Type a b + My_Type_Data a b foreign r my_method self = """ self$a + self$b @@ -124,14 +124,14 @@ spec = num_double_match.should_be_true Test.specify "should allow Enso to catch R exceptions" <| - value = My_Type 1 2 + value = My_Type_Data 1 2 result = Panic.recover Any <| value.my_throw err = result.catch err.to_display_text.should_equal "Polyglot error: Error: error in R code!" pending="R does not support catching polyglot exceptions" Test.specify "should allow R to catch Enso exceptions" pending=pending <| - value = My_Type 7 2 + value = My_Type_Data 7 2 result = value.do_catch result . should_equal 7 diff --git a/test/Tests/src/Semantic/Warnings_Spec.enso b/test/Tests/src/Semantic/Warnings_Spec.enso index 3331026b8f33..6ea002ef87a6 100644 --- a/test/Tests/src/Semantic/Warnings_Spec.enso +++ b/test/Tests/src/Semantic/Warnings_Spec.enso @@ -4,15 +4,18 @@ polyglot java import java.lang.Long import Standard.Test -type My_Warning reason +type My_Warning + My_Warning_Data reason -type My_Type a b c +type My_Type + My_Type_Data a b c My_Type.my_method self = self.a + self.b + self.c -type Wrap foo +type Wrap + Wrap_Data foo rewrap w = case w of - Wrap a -> Wrap a+1 + Wrap_Data a -> Wrap_Data a+1 poly_sum x y = Long.sum x y @@ -22,10 +25,10 @@ get_foo x = x.foo unwrap x = Integer.from x reassign_test x = - consed = Wrap x + consed = Wrap_Data x reconsed = rewrap consed i = unwrap reconsed - rereconsed = Wrap i + rereconsed = Wrap_Data i x1 = get_foo rereconsed prim_sum = 1 + x1 r = poly_sum prim_sum 1 @@ -67,12 +70,12 @@ spec = Test.group "Dataflow Warnings" <| Warning.get_all z . map .value . should_equal ["I'm serious", "don't do this"] Test.specify "should thread warnings through constructor calls" <| - z = Warning.attach (My_Warning "warn!!!") 3 - y = Warning.attach (My_Warning "warn!!") 2 - x = Warning.attach (My_Warning "warn!") 1 + z = Warning.attach (My_Warning_Data "warn!!!") 3 + y = Warning.attach (My_Warning_Data "warn!!") 2 + x = Warning.attach (My_Warning_Data "warn!") 1 mtp = My_Type x y z mtp.should_equal (My_Type 1 2 3) - Warning.get_all mtp . map .value . should_equal [My_Warning "warn!", My_Warning "warn!!", My_Warning "warn!!!"] + Warning.get_all mtp . map .value . should_equal [My_Warning_Data "warn!", My_Warning_Data "warn!!", My_Warning_Data "warn!!!"] Test.specify "should thread warnings through method calls" mtp = My_Type 1 2 3 @@ -89,17 +92,17 @@ spec = Test.group "Dataflow Warnings" <| Warning.get_all r . map .value . should_equal ['warn!', 'warn!!'] Test.specify "should thread warnings through case expressions" <| - z = Warning.attach (My_Warning "warn!!!") 3 - y = Warning.attach (My_Warning "warn!!") 2 - x = Warning.attach (My_Warning "warn!") 1 - mtp = My_Type x y z + z = Warning.attach (My_Warning_Data "warn!!!") 3 + y = Warning.attach (My_Warning_Data "warn!!") 2 + x = Warning.attach (My_Warning_Data "warn!") 1 + mtp = My_Type_Data x y z r = case mtp of - My_Type a b c -> a + b + c + My_Type_Data a b c -> a + b + c r.should_equal 6 - Warning.get_all r . map .value . should_equal [My_Warning "warn!", My_Warning "warn!!", My_Warning "warn!!!"] + Warning.get_all r . map .value . should_equal [My_Warning_Data "warn!", My_Warning_Data "warn!!", My_Warning_Data "warn!!!"] Test.specify "should thread warnings through conversions" <| - z = Wrap (Warning.attach 'warn!' 1) + z = Wrap_Data (Warning.attach 'warn!' 1) i = Integer.from z Warning.get_all i . map .value . should_equal ['warn!'] diff --git a/test/Tests/src/System/File_Spec.enso b/test/Tests/src/System/File_Spec.enso index 423cc4631dcc..11d6d80a5c19 100644 --- a/test/Tests/src/System/File_Spec.enso +++ b/test/Tests/src/System/File_Spec.enso @@ -73,11 +73,11 @@ spec = Process.run "chmod" ["0777", f.absolute.path] . should_equal Exit_Success rwx = [Read, Write, Execute] f.posix_permissions . should_equal <| - File_Permissions rwx rwx rwx + File_Permissions_Data rwx rwx rwx Process.run "chmod" ["0421", f.absolute.path] . should_equal Exit_Success f.posix_permissions . should_equal <| - File_Permissions [Read] [Write] [Execute] + File_Permissions_Data [Read] [Write] [Execute] f.delete @@ -202,8 +202,8 @@ spec = f = transient / "work.txt" f.delete_if_exists f.exists.should_be_false - [0, 1, 256].write_bytes f . should_fail_with Illegal_Argument_Error - [0, 1, Nothing].write_bytes f . should_fail_with Illegal_Argument_Error + [0, 1, 256].write_bytes f . should_fail_with Illegal_Argument_Error_Data + [0, 1, Nothing].write_bytes f . should_fail_with Illegal_Argument_Error_Data Test.specify "should not change the file when trying to write an invalid byte vector" <| f = transient / "work.txt" @@ -211,12 +211,12 @@ spec = f_bak = transient / "work.txt.bak" f_bak.delete_if_exists data.write_bytes f - [0, 1, 256].write_bytes f . should_fail_with Illegal_Argument_Error + [0, 1, 256].write_bytes f . should_fail_with Illegal_Argument_Error_Data f.read_bytes.should_equal data f_bak.exists.should_be_false - [0, 1, 256].write_bytes f on_existing_file=Existing_File_Behavior.Overwrite . should_fail_with Illegal_Argument_Error + [0, 1, 256].write_bytes f on_existing_file=Existing_File_Behavior.Overwrite . should_fail_with Illegal_Argument_Error_Data f.read_bytes.should_equal data - [0, 1, 256].write_bytes f on_existing_file=Existing_File_Behavior.Append . should_fail_with Illegal_Argument_Error + [0, 1, 256].write_bytes f on_existing_file=Existing_File_Behavior.Append . should_fail_with Illegal_Argument_Error_Data f.read_bytes.should_equal data f.delete_if_exists @@ -301,10 +301,10 @@ spec = new_file = transient / "work.txt.new" [bak_file, new_file].each .delete_if_exists - result = Panic.catch Illegal_State_Error handler=(caught_panic-> caught_panic.payload.message) <| + result = Panic.catch Illegal_State_Error_Data handler=(caught_panic-> caught_panic.payload.message) <| Existing_File_Behavior.Backup.write f output_stream-> output_stream.write_bytes "foo".utf_8 - Panic.throw (Illegal_State_Error "baz") + Panic.throw (Illegal_State_Error_Data "baz") output_stream.write_bytes "bar".utf_8 Test.fail "Control flow should never get here, because the panic should have been propagated and handled." result.should_equal "baz" @@ -315,10 +315,10 @@ spec = Test.fail "The temporary file should have been cleaned up." f.delete - result2 = Panic.catch Illegal_State_Error handler=(caught_panic-> caught_panic.payload.message) <| + result2 = Panic.catch Illegal_State_Error_Data handler=(caught_panic-> caught_panic.payload.message) <| Existing_File_Behavior.Backup.write f output_stream-> output_stream.write_bytes "foo".utf_8 - Panic.throw (Illegal_State_Error "baz") + Panic.throw (Illegal_State_Error_Data "baz") output_stream.write_bytes "bar".utf_8 Test.fail "Control flow should never get here, because the panic should have been propagated and handled." result2.should_equal "baz" @@ -334,8 +334,8 @@ spec = "OLD".write f on_existing_file=Existing_File_Behavior.Overwrite result3 = Existing_File_Behavior.Backup.write f output_stream-> output_stream.write_bytes "foo".utf_8 - Error.throw (Illegal_State_Error "HMM...") - result3.should_fail_with Illegal_State_Error + Error.throw (Illegal_State_Error_Data "HMM...") + result3.should_fail_with Illegal_State_Error_Data result3.catch.message . should_equal "HMM..." f.read_text . should_equal "OLD" if bak_file.exists then @@ -346,8 +346,8 @@ spec = result4 = Existing_File_Behavior.Backup.write f output_stream-> output_stream.write_bytes "foo".utf_8 - Error.throw (Illegal_State_Error "HMM...") - result4.should_fail_with Illegal_State_Error + Error.throw (Illegal_State_Error_Data "HMM...") + result4.should_fail_with Illegal_State_Error_Data result4.catch.message . should_equal "HMM..." if f.exists.not then Test.fail "Since we were writing to the original destination, the partially written file should have been preserved even upon failure." From c8052a7c6224f1ac516ee7e930c4c666b9d37b6f Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 15 Aug 2022 14:50:16 +0200 Subject: [PATCH 046/110] first passing test --- .../Standard/Base/0.0.0-dev/src/Data/Any.enso | 12 +- .../Base/0.0.0-dev/src/Data/Json.enso | 48 ++-- .../0.0.0-dev/src/Data/Json/Internal.enso | 4 +- .../lib/Standard/Base/0.0.0-dev/src/Meta.enso | 103 ++++---- .../Base/0.0.0-dev/src/Network/Http.enso | 16 +- .../lib/Standard/Test/0.0.0-dev/src/Main.enso | 8 +- .../builtin/function/ApplicationOperator.java | 2 +- .../scala/org/enso/compiler/Compiler.scala | 22 +- test/Tests/src/Data/Array_Spec.enso | 12 +- test/Tests/src/Data/Range_Spec.enso | 86 +++---- test/Tests/src/Data/Statistics_Spec.enso | 44 ++-- .../src/Data/Text/Codepoint_Ranges_Spec.enso | 38 +-- test/Tests/src/Data/Text/Span_Spec.enso | 30 +-- test/Tests/src/Data/Vector_Spec.enso | 16 +- test/Tests/src/Main.enso | 228 +++++++++--------- test/Tests/src/Resource/Bracket_Spec.enso | 16 +- test/Tests/src/Semantic/Any_Spec.enso | 11 +- test/Tests/src/Semantic/Conversion_Spec.enso | 49 ++-- test/Tests/src/Semantic/Warnings_Spec.enso | 6 +- 19 files changed, 376 insertions(+), 375 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso index fa4fdc8bbd14..ed84bb7eb025 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso @@ -75,21 +75,21 @@ type Any == self that = if Meta.is_same_object self that then True else self_meta = Meta.meta self that_meta = Meta.meta that - case Cons self_meta that_meta of - Cons (Meta.Atom _) (Meta.Atom _) -> + case Pair_Data self_meta that_meta of + Pair_Data (Meta.Atom_Data _) (Meta.Atom_Data _) -> c_1 = self_meta.constructor c_2 = that_meta.constructor if Meta.is_same_object c_1 c_2 . not then False else f_1 = self_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 _) -> self_meta.payload == that_meta.payload - Cons (Meta.Polyglot o_1) (Meta.Polyglot o_2) -> + Pair_Data (Meta.Error_Data _) (Meta.Error_Data _) -> self_meta.payload == that_meta.payload + Pair_Data (Meta.Polyglot_Data o_1) (Meta.Polyglot_Data o_2) -> langs_match = (self_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 _) -> + Pair_Data (Meta.Unresolved_Symbol_Data _) (Meta.Unresolved_Symbol_Data _) -> (self_meta.name == that_meta.name) && (self_meta.scope == that_meta.scope) - ## Constructor comparison is covered by the identity equality. + ## Pair_Datatructor comparison is covered by the identity equality. Primitive objects should define their own equality. Therefore, there are no more cases to handle in self method. _ -> False diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso index f44ee6ccc404..30fdff3a5e91 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso @@ -140,6 +140,25 @@ type Json Null -> Nothing Object f -> f.map .unwrap + ## Gets the value associated with the given key in this object. + + Arguments: + - field: The name of the field from which to get the value. + + Throws `Nothing` if the associated key is not defined. + + > Example + Get the "title" field from this JSON representing a book. + + import Standard.Base.Data.Json + import Standard.Examples + + example_get = Examples.json_object.get "title" + get : Text -> Json ! No_Such_Field_Error + get self field = self.fields.get field . map_error case _ of + Map.No_Value_For_Key_Error_Data _ -> No_Such_Field_Error_Data field + x -> x + ## UNSTABLE A failure indicating malformed text input into the JSON parser. @@ -155,25 +174,6 @@ Parse_Error.to_display_text : Text Parse_Error.to_display_text self = "Parse error in parsing JSON: " + self.message.to_text + "." -## Gets the value associated with the given key in this object. - - Arguments: - - field: The name of the field from which to get the value. - - Throws `Nothing` if the associated key is not defined. - - > Example - Get the "title" field from this JSON representing a book. - - import Standard.Base.Data.Json - import Standard.Examples - - example_get = Examples.json_object.get "title" -Object.get : Text -> Json ! No_Such_Field_Error -Object.get self field = self.fields.get field . map_error case _ of - Map.No_Value_For_Key_Error_Data _ -> No_Such_Field_Error_Data field - x -> x - ## UNSTABLE An error indicating that there is no such field in the JSON object. @@ -245,21 +245,21 @@ type Marshalling_Error Any.to_json self = m = Meta.meta self case m of - Meta.Atom _ -> - cons = Meta.Constructor m.constructor + Meta.Atom_Data _ -> + cons = Meta.Constructor_Data m.constructor fs = m.fields fnames = cons.fields json_fs = 0.up_to fnames.length . fold Map.empty m-> i-> m.insert (fnames.at i) (fs.at i . to_json) with_tp = json_fs . insert "type" (String cons.name) Object with_tp - Meta.Constructor _ -> + Meta.Constructor_Data _ -> Object (Map.empty . insert "type" (String m.name)) ## The following two cases cannot be handled generically and should instead define their own `to_json` implementations. - Meta.Polyglot _ -> Null - Meta.Primitive _ -> Null + Meta.Polyglot_Data _ -> Null + Meta.Primitive_Data _ -> Null ## Method used by object builders to convert a value into a valid JSON key. 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 c2abc558d2e7..3e660a81d79d 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 @@ -302,9 +302,9 @@ into_helper fmt json = case fmt of _ -> m = Meta.meta fmt case m of - Meta.Atom _ -> case json of + Meta.Atom_Data _ -> case json of Object json_fields -> - cons = Meta.Constructor m.constructor + cons = Meta.Constructor_Data m.constructor fnames = cons.fields ffmts = m.fields field_values = fnames.zip ffmts n-> inner_fmt-> 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 f15e50458f38..5b7a68f85ae9 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 @@ -3,67 +3,62 @@ from Standard.Base import all ## UNSTABLE ADVANCED - A meta-representation of a runtime value. + An Atom meta-representation. - ! 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. - Atom value + Arguments: + - value: The value of the atom in the meta representation. +type Atom + Atom_Data value - ## UNSTABLE - ADVANCED +## UNSTABLE + ADVANCED - A constructor meta-representation. + A constructor meta-representation. - Arguments: - - value: The value of the constructor in the meta representation. - Constructor value + Arguments: + - value: The value of the constructor in the meta representation. +type Constructor + Constructor_Data value - ## UNSTABLE - ADVANCED +## UNSTABLE + ADVANCED - A primitive value meta-prepresentation. + A primitive value meta-prepresentation. - Arguments: - - value: The value of the primitive object in the meta representation. - Primitive value + Arguments: + - value: The value of the primitive object in the meta representation. +type Primitive + Primitive_Data value - ## UNSTABLE - ADVANCED +## UNSTABLE + ADVANCED - An unresolved symbol meta-representation. + An unresolved symbol meta-representation. - Arguments: - - value: The value of the unresolved symbol in the meta representation. - Unresolved_Symbol value + Arguments: + - value: The value of the unresolved symbol in the meta representation. +type Unresolved_Symbol + Unresolved_Symbol_Data value - ## UNSTABLE - ADVANCED +## UNSTABLE + ADVANCED - An error meta-representation, containing the payload of a dataflow error. + An error meta-representation, containing the payload of a dataflow error. - Arguments: - - value: The payload of the error. - Error value + Arguments: + - value: The payload of the error. +type Error + Error_Data value - ## UNSTABLE - ADVANCED +## UNSTABLE + ADVANCED - A polyglot value meta-representation. + A polyglot value meta-representation. - Arguments: - - value: The polyglot value contained in the meta representation. - Polyglot value + Arguments: + - value: The polyglot value contained in the meta representation. +type Polyglot + Polyglot_Data value ## Atom methods @@ -237,11 +232,11 @@ Constructor.new self fields = new_atom self.value fields.to_array Arguments: - value: The runtime entity to get the meta representation of. meta : Any -> Meta -meta value = if is_atom value then Atom value else - if is_atom_constructor value then Constructor value else +meta value = if is_atom value then Atom_Data value else + if is_atom_constructor value then Constructor_Data value else if is_polyglot value then Polyglot value else if is_unresolved_symbol value then Unresolved_Symbol value else - if is_error value then Error value.catch else + if is_error value then Error_Data value.catch else Primitive value ## UNSTABLE @@ -317,16 +312,16 @@ is_a value typ = if typ == Any then True else _ -> meta_val = meta value case meta_val of - Atom _ -> if is_atom typ then typ == value else + Atom_Data _ -> if is_atom typ then typ == value else meta_val.constructor == typ - Constructor _ -> + Constructor_Data _ -> meta_typ = meta typ case meta_typ of - Atom _ -> meta_val == meta_typ.constructor - Constructor _ -> meta_val == meta_typ + Atom_Data _ -> meta_val == meta_typ.constructor + Constructor_Data _ -> meta_val == meta_typ _ -> False - Error _ -> typ == Error - Unresolved_Symbol _ -> typ == Unresolved_Symbol + Error_Data _ -> typ == Error + Unresolved_Symbol_Data _ -> typ == Unresolved_Symbol _ -> False ## UNSTABLE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http.enso index a7df3b0f6bf7..ab6cb805174f 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http.enso @@ -606,14 +606,14 @@ type Http # prepare headers and body req_with_body = case req.body of Request_Body.Empty -> - Pair req body_publishers.noBody + Pair_Data req body_publishers.noBody Request_Body.Text text -> builder.header Header.text_plain.name Header.text_plain.value - Pair req (body_publishers.ofString text) + Pair_Data req (body_publishers.ofString text) Request_Body.Json json -> builder.header Header.application_json.name Header.application_json.value json_body = if json.is_a Text then json else json.to_text - Pair req (body_publishers.ofString json_body) + Pair_Data req (body_publishers.ofString json_body) Request_Body.Form form -> add_multipart form = body_builder = Http_Utils.multipart_body_builder @@ -621,18 +621,18 @@ type Http Form.Part_Text text -> body_builder.add_part_text part.key text Form.Part_File file -> body_builder.add_part_file part.key file.path boundary = body_builder.get_boundary - Pair (req.with_headers [Header.multipart_form_data boundary]) body_builder.build + Pair_Data (req.with_headers [Header.multipart_form_data boundary]) body_builder.build add_urlencoded form = body_builder = Http_Utils.urlencoded_body_builder form.parts.map part-> case part.value of Form.Part_Text text -> body_builder.add_part_text part.key text Form.Part_File file -> body_builder.add_part_file part.key file.path - Pair req body_builder.build + Pair_Data req body_builder.build if req.headers.contains Header.multipart_form_data then add_multipart form else add_urlencoded form Request_Body.Bytes bytes -> builder.header Header.application_octet_stream.name Header.application_octet_stream.value - Pair req (body_publishers.ofByteArray bytes.to_array) + Pair_Data req (body_publishers.ofByteArray bytes.to_array) # method req_http_method = case req.method of Method.Options -> "OPTIONS" @@ -651,7 +651,7 @@ type Http req.headers.map h-> builder.header h.name h.value http_request = builder.build body_handler = HttpResponse.BodyHandlers . ofByteArray - Response.Response (self.internal_http_client.send http_request body_handler) + Response.Response_Data (self.internal_http_client.send http_request body_handler) ## PRIVATE @@ -660,7 +660,7 @@ type Http internal_http_client self = builder = HttpClient.newBuilder # timeout - if self.timeout.is_date then Panic.throw (Time.Time_Error "Connection timeout does not support date intervals") else + if self.timeout.is_date then Panic.throw (Time.Time_Error_Data "Connection timeout does not support date intervals") else builder.connectTimeout self.timeout.internal_duration # redirect redirect = HttpClient.Redirect 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 d7c10d6a030c..ba8a66f6bb08 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 @@ -75,7 +75,7 @@ config_from_env = False -> (File.new junit_folder) / project_root.name / "JUnit.xml" - Suite_Config only_group_regexp results_path + Suite_Config_Data only_group_regexp results_path ## Creates a new test group, describing properties of the object @@ -127,11 +127,11 @@ group name ~behaviors pending=Nothing = if config.should_run_group name then case pending of Nothing -> - r = State.run Spec (Spec name Nil) <| + r = State.run Spec (Spec_Data name Nil) <| behaviors State.get Spec r.print_report config suite.builder - new_suite = Suite suite.config (Cons r suite.specs) suite.builder + new_suite = Suite_Data suite.config (Cons r suite.specs) suite.builder State.put Suite new_suite reason -> report_pending_group name reason config suite.builder @@ -168,7 +168,7 @@ specify label ~behavior pending=Nothing = Nothing -> run_spec behavior reason -> Pending reason spec = State.get Spec - new_spec = Spec spec.name (Cons (Behavior_Data label result) spec.behaviors) + new_spec = Spec_Data spec.name (Cons (Behavior_Data label result) spec.behaviors) State.put Spec new_spec ## PRIVATE diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/ApplicationOperator.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/ApplicationOperator.java index eb3551924134..33d1395d0dd9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/ApplicationOperator.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/function/ApplicationOperator.java @@ -28,7 +28,7 @@ public class ApplicationOperator extends Node { } Stateful execute( - VirtualFrame frame, @MonadicState Object state, Function self, @Suspend Object argument) { + VirtualFrame frame, @MonadicState Object state, Object self, @Suspend Object argument) { return invokeCallableNode.execute(self, frame, state, new Object[] {argument}); } } 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 66cdfd9782ad..fa7893222f87 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala @@ -724,8 +724,10 @@ class Compiler( List((module, errors)) } if (reportDiagnostics(diagnostics)) { - val count = diagnostics.map(_._2.collect { case e: IR.Error => e }.length).sum - val warnCount = diagnostics.map(_._2.collect { case e: IR.Warning => e }.length).sum + val count = + diagnostics.map(_._2.collect { case e: IR.Error => e }.length).sum + val warnCount = + diagnostics.map(_._2.collect { case e: IR.Warning => e }.length).sum println(s"Aborting due to ${count} errors and ${warnCount} warnings.") throw new CompilationAbortedException } @@ -824,14 +826,14 @@ class Compiler( source: Source ): Boolean = { val errors = diagnostics.collect { case e: IR.Error => e } -// val warnings = diagnostics.collect { case w: IR.Warning => w } - -// if (warnings.nonEmpty) { -// context.getOut.println("Compiler encountered warnings:") -// warnings.foreach { warning => -// context.getOut.println(formatDiagnostic(warning, source)) -// } -// } + val warnings = diagnostics.collect { case w: IR.Warning => w } + + if (warnings.nonEmpty) { + context.getOut.println("Compiler encountered warnings:") + warnings.foreach { warning => + context.getOut.println(formatDiagnostic(warning, source)) + } + } if (errors.nonEmpty) { context.getOut.println("Compiler encountered errors:") diff --git a/test/Tests/src/Data/Array_Spec.enso b/test/Tests/src/Data/Array_Spec.enso index 17bb3beeeaa4..a3be4856b117 100644 --- a/test/Tests/src/Data/Array_Spec.enso +++ b/test/Tests/src/Data/Array_Spec.enso @@ -9,7 +9,7 @@ spec = Test.group "Arrays" <| arr = Vector.fill 1000 0 . to_array text = arr.to_default_visualization_data json = Json.parse text - as_vec = json.into (Vector.Vector Number) + as_vec = json.into (Vector.Vector_Data Number) as_vec.should_equal <| Vector.fill 100 0 Test.specify "should allow accessing elements" <| @@ -25,17 +25,17 @@ spec = Test.group "Arrays" <| Test.specify "should panic on out of bounds access" <| arr = [1, 2, 3] . to_array - 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.expect_panic_with (arr.at -1) Invalid_Array_Index_Error_Data + Test.expect_panic_with (arr.at 3) Invalid_Array_Index_Error_Data + Test.expect_panic_with (arr.set_at 3 100) Invalid_Array_Index_Error_Data 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 Test.specify "should propagate dataflow errors" <| - err = Error.throw (Illegal_State_Error "Foo") + err = Error.throw (Illegal_State_Error_Data "Foo") res = Array.new err - res . should_fail_with Illegal_State_Error + res . should_fail_with Illegal_State_Error_Data main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Range_Spec.enso b/test/Tests/src/Data/Range_Spec.enso index e086a96714ba..90888f9d41b5 100644 --- a/test/Tests/src/Data/Range_Spec.enso +++ b/test/Tests/src/Data/Range_Spec.enso @@ -22,20 +22,20 @@ spec = Test.group "Range" <| range_3.step . should_equal -1 Test.specify "should allow setting a new step magnitude" <| - 1.up_to 2 . with_step 3 . should_equal (Range 1 2 3) + 1.up_to 2 . with_step 3 . should_equal (Range_Data 1 2 3) - 0.up_to 10 . with_step 2 . should_equal (Range 0 10 2) + 0.up_to 10 . with_step 2 . should_equal (Range_Data 0 10 2) 0.up_to 10 . with_step 2 . to_vector . should_equal [0, 2, 4, 6, 8] - 10.down_to 0 . with_step 2 . should_equal (Range 10 0 -2) + 10.down_to 0 . with_step 2 . should_equal (Range_Data 10 0 -2) 10.down_to 0 . with_step 2 . to_vector . should_equal [10, 8, 6, 4, 2] - 1.up_to 2 . with_step 0.5 . should_fail_with Illegal_Argument_Error - 1.up_to 2 . with_step -1 . should_fail_with Illegal_Argument_Error - 0.up_to 2.0 . should_fail_with Illegal_Argument_Error - 0.down_to 2.0 . should_fail_with Illegal_Argument_Error - Test.expect_panic_with (0.0.up_to 2) No_Such_Method_Error - Test.expect_panic_with (0.0.down_to 2) No_Such_Method_Error + 1.up_to 2 . with_step 0.5 . should_fail_with Illegal_Argument_Error_Data + 1.up_to 2 . with_step -1 . should_fail_with Illegal_Argument_Error_Data + 0.up_to 2.0 . should_fail_with Illegal_Argument_Error_Data + 0.down_to 2.0 . should_fail_with Illegal_Argument_Error_Data + Test.expect_panic_with (0.0.up_to 2) No_Such_Method_Error_Data + Test.expect_panic_with (0.0.down_to 2) No_Such_Method_Error_Data Test.specify "should have a length" <| 0.up_to 100 . length . should_equal 100 @@ -104,11 +104,11 @@ spec = Test.group "Range" <| 3.up_to 5 . contains 2 . should_be_false 0.up_to 10 . contains -3 . should_be_false - 0.up_to 10 . contains 2.5 . should_fail_with Illegal_Argument_Error - 0.up_to 10 . contains 3.0 . should_fail_with Illegal_Argument_Error + 0.up_to 10 . contains 2.5 . should_fail_with Illegal_Argument_Error_Data + 0.up_to 10 . contains 3.0 . should_fail_with Illegal_Argument_Error_Data - 5.down_to 0 . contains 2.5 . should_fail_with Illegal_Argument_Error - 5.down_to 0 . contains 3.0 . should_fail_with Illegal_Argument_Error + 5.down_to 0 . contains 2.5 . should_fail_with Illegal_Argument_Error_Data + 5.down_to 0 . contains 3.0 . should_fail_with Illegal_Argument_Error_Data verify_contains range expected unexpected = @@ -138,17 +138,17 @@ spec = Test.group "Range" <| verify_contains r [] [-1, 0, 1, 2, 10] check_empty_range (0.up_to 0) - check_empty_range (Range 1 1) - check_empty_range (Range 2 2 4) - check_empty_range (Range 0 -1 2) - check_empty_range (Range 0 -10 2) - check_empty_range (Range 10 0 2) - check_empty_range (Range -1 0 -1) - check_empty_range (Range 0 10 -1) - check_empty_range (Range -1 0 -2) + check_empty_range (Range_Data 1 1) + check_empty_range (Range_Data 2 2 4) + check_empty_range (Range_Data 0 -1 2) + check_empty_range (Range_Data 0 -10 2) + check_empty_range (Range_Data 10 0 2) + check_empty_range (Range_Data -1 0 -1) + check_empty_range (Range_Data 0 10 -1) + check_empty_range (Range_Data -1 0 -2) Test.specify "should behave correctly when containing exactly one element" <| - r1 = Range 10 11 + r1 = Range_Data 10 11 r1.is_empty . should_be_false r1.not_empty . should_be_true r1.length . should_equal 1 @@ -165,7 +165,7 @@ spec = Test.group "Range" <| verify_contains r1 [10] [-1, 0, 1, 2, 9, 11, 12] Test.specify "should behave correctly with step greater than 1" <| - r1 = Range 0 10 2 + r1 = Range_Data 0 10 2 r1.is_empty . should_be_false r1.not_empty . should_be_true r1.length . should_equal 5 @@ -181,7 +181,7 @@ spec = Test.group "Range" <| r1.find (x-> x*x == 25) . should_equal Nothing verify_contains r1 [0, 2, 4, 6, 8] [-3, -2, -1, 1, 3, 5, 7, 11, 12, 13, 14] - r2 = Range 0 3 2 + r2 = Range_Data 0 3 2 r2.is_empty . should_be_false r2.not_empty . should_be_true r2.length . should_equal 2 @@ -197,7 +197,7 @@ spec = Test.group "Range" <| r2.find (x-> x*x == 4) . should_equal 2 verify_contains r2 [0, 2] [-3, -2, -1, 1, 3, 4, 5] - r3 = Range 5 6 200 + r3 = Range_Data 5 6 200 r3.is_empty . should_be_false r3.not_empty . should_be_true r3.length . should_equal 1 @@ -213,7 +213,7 @@ spec = Test.group "Range" <| r3.find (x-> x*x == 25) . should_equal 5 verify_contains r3 [5] [0, 1, 4, 6, 7, 10] - r4 = Range 5 8 2 + r4 = Range_Data 5 8 2 r4.is_empty . should_be_false r4.not_empty . should_be_true r4.length . should_equal 2 @@ -229,7 +229,7 @@ spec = Test.group "Range" <| r4.find (x-> x*x == 4) . should_equal Nothing verify_contains r4 [5, 7] [0, 1, 4, 6, 8, 10] - r5 = Range 5 7 2 + r5 = Range_Data 5 7 2 r5.is_empty . should_be_false r5.not_empty . should_be_true r5.length . should_equal 1 @@ -245,7 +245,7 @@ spec = Test.group "Range" <| r5.find (x-> x*x == 4) . should_equal Nothing verify_contains r5 [5] [0, 1, 4, 6, 7, 10] - r6 = Range 0 10 3 + r6 = Range_Data 0 10 3 r6.is_empty . should_be_false r6.not_empty . should_be_true r6.length . should_equal 4 @@ -263,7 +263,7 @@ spec = Test.group "Range" <| verify_contains r6 [0, 3, 6, 9] [-3, -2, -1, 1, 2, 4, 5, 7, 8, 10, 11] Test.specify "should behave correctly with negative step" <| - r1 = Range 4 0 -1 + r1 = Range_Data 4 0 -1 r1.is_empty . should_be_false r1.not_empty . should_be_true r1.length . should_equal 4 @@ -279,7 +279,7 @@ spec = Test.group "Range" <| r1.find (x-> x*x == 0) . should_equal Nothing verify_contains r1 [4, 3, 2, 1] [-2, -1, 0, 5, 6, 7, 10] - r2 = Range 4 0 -2 + r2 = Range_Data 4 0 -2 r2.is_empty . should_be_false r2.not_empty . should_be_true r2.length . should_equal 2 @@ -295,7 +295,7 @@ spec = Test.group "Range" <| r2.find (x-> x*x == 0) . should_equal Nothing verify_contains r2 [4, 2] [-2, -1, 0, 1, 3, 5, 6, 7, 10] - r3 = Range 4 0 -10 + r3 = Range_Data 4 0 -10 r3.is_empty . should_be_false r3.not_empty . should_be_true r3.length . should_equal 1 @@ -311,7 +311,7 @@ spec = Test.group "Range" <| r3.find (x-> x*x == 0) . should_equal Nothing verify_contains r3 [4] [-2, -1, 0, 1, 2, 3, 5, 6, 7, 10] - r4 = Range 3 0 -3 + r4 = Range_Data 3 0 -3 r4.is_empty . should_be_false r4.not_empty . should_be_true r4.length . should_equal 1 @@ -328,22 +328,22 @@ spec = Test.group "Range" <| verify_contains r4 [3] [-3, -2, -1, 0, 1, 2, 4, 5, 6, 7, 10] Test.specify "should report errors if trying to set step to 0" <| - 0.up_to 0 . with_step 0 . should_fail_with Illegal_State_Error - invalid_range = Range 0 0 0 - invalid_range . length . should_fail_with Illegal_State_Error - invalid_range . is_empty . should_fail_with Illegal_State_Error - invalid_range . not_empty . should_fail_with Illegal_State_Error - invalid_range . each x->x . should_fail_with Illegal_State_Error - invalid_range . fold 0 (+) . should_fail_with Illegal_State_Error + 0.up_to 0 . with_step 0 . should_fail_with Illegal_State_Error_Data + invalid_range = Range_Data 0 0 0 + invalid_range . length . should_fail_with Illegal_State_Error_Data + invalid_range . is_empty . should_fail_with Illegal_State_Error_Data + invalid_range . not_empty . should_fail_with Illegal_State_Error_Data + invalid_range . each x->x . should_fail_with Illegal_State_Error_Data + invalid_range . fold 0 (+) . should_fail_with Illegal_State_Error_Data ## FIXME [RW] These tests are disabled because they fail in an unexpected way due to a codegen issue (noted below). They should be enabled once that is resolved. See: https://www.pivotaltracker.com/story/show/181652841 #invalid_range . map x->x . should_fail_with Illegal_State_Error #invalid_range . to_vector . should_fail_with Illegal_State_Error - invalid_range . any _->True . should_fail_with Illegal_State_Error - invalid_range . all _->True . should_fail_with Illegal_State_Error - invalid_range . find _->True . should_fail_with Illegal_State_Error - invalid_range . contains 0 . should_fail_with Illegal_State_Error + invalid_range . any _->True . should_fail_with Illegal_State_Error_Data + invalid_range . all _->True . should_fail_with Illegal_State_Error_Data + invalid_range . find _->True . should_fail_with Illegal_State_Error_Data + invalid_range . contains 0 . should_fail_with Illegal_State_Error_Data main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Statistics_Spec.enso b/test/Tests/src/Data/Statistics_Spec.enso index 145403295d62..c507fec793d9 100644 --- a/test/Tests/src/Data/Statistics_Spec.enso +++ b/test/Tests/src/Data/Statistics_Spec.enso @@ -135,11 +135,11 @@ spec = no_ord_set = [No_Ord 10, No_Ord 2, Nothing, No_Ord 9] Test.specify "should fail with Illegal_Argument_Error on number based statistics for text Vector" <| - text_set.compute Sum . should_fail_with Illegal_Argument_Error - text_set.compute Mean . should_fail_with Illegal_Argument_Error - text_set.compute Variance . should_fail_with Illegal_Argument_Error - text_set.compute Skew . should_fail_with Illegal_Argument_Error - text_set.compute Kurtosis . should_fail_with Illegal_Argument_Error + text_set.compute Sum . should_fail_with Illegal_Argument_Error_Data + text_set.compute Mean . should_fail_with Illegal_Argument_Error_Data + text_set.compute Variance . should_fail_with Illegal_Argument_Error_Data + text_set.compute Skew . should_fail_with Illegal_Argument_Error_Data + text_set.compute Kurtosis . should_fail_with Illegal_Argument_Error_Data Test.specify "should be able to do Count, Minimum and Maximum on custom type with compare_to" <| ord_set.compute . should_equal 3 @@ -183,7 +183,7 @@ spec = rank_data [1, "A"] . should_fail_with Vector.Incomparable_Values_Error Test.specify "should fail with Illegal_Argument_Error on Vectors with Nothing" <| - rank_data [1, Nothing, 4] . should_fail_with Illegal_Argument_Error + rank_data [1, Nothing, 4] . should_fail_with Illegal_Argument_Error_Data Test.group "Correlation Statistics" <| series_a = [0.22345,0.258315,0.74663,Nothing,0.686843,0.692246,Nothing,0.401859,0.725442,Nothing,0.963527,0.520363,0.633053,0.397123,Nothing,0.458942,0.036499,0.368194,0.598939,0.296476,0.093746,0.609329] @@ -220,28 +220,28 @@ spec = Test.specify "should fail with Illegal_Argument_Error if different lengths" <| data = [[1,2,3,4],[10,20,30]] - data.first.compute (Covariance data.second) . should_fail_with Illegal_Argument_Error - data.first.compute (Pearson data.second) . should_fail_with Illegal_Argument_Error - data.first.compute (Spearman data.second) . should_fail_with Illegal_Argument_Error - data.first.compute (R_Squared data.second) . should_fail_with Illegal_Argument_Error - covariance_matrix data . should_fail_with Illegal_Argument_Error - pearson_correlation data . should_fail_with Illegal_Argument_Error - spearman_correlation data . should_fail_with Illegal_Argument_Error + data.first.compute (Covariance data.second) . should_fail_with Illegal_Argument_Error_Data + data.first.compute (Pearson data.second) . should_fail_with Illegal_Argument_Error_Data + data.first.compute (Spearman data.second) . should_fail_with Illegal_Argument_Error_Data + data.first.compute (R_Squared data.second) . should_fail_with Illegal_Argument_Error_Data + covariance_matrix data . should_fail_with Illegal_Argument_Error_Data + pearson_correlation data . should_fail_with Illegal_Argument_Error_Data + spearman_correlation data . should_fail_with Illegal_Argument_Error_Data Test.specify "should fail with Illegal_Argument_Error if not number based" <| text = [["A","BC","CD"], ["0", "1", "2"], ["H", "I", "J"]] - text.first.compute (Covariance text.second) . should_fail_with Illegal_Argument_Error - text.first.compute (Pearson text.second) . should_fail_with Illegal_Argument_Error - text.first.compute (Spearman text.second) . should_fail_with Illegal_Argument_Error - text.first.compute (R_Squared text.second) . should_fail_with Illegal_Argument_Error - covariance_matrix text . should_fail_with Illegal_Argument_Error - pearson_correlation text . should_fail_with Illegal_Argument_Error - spearman_correlation text . should_fail_with Illegal_Argument_Error + text.first.compute (Covariance text.second) . should_fail_with Illegal_Argument_Error_Data + text.first.compute (Pearson text.second) . should_fail_with Illegal_Argument_Error_Data + text.first.compute (Spearman text.second) . should_fail_with Illegal_Argument_Error_Data + text.first.compute (R_Squared text.second) . should_fail_with Illegal_Argument_Error_Data + covariance_matrix text . should_fail_with Illegal_Argument_Error_Data + pearson_correlation text . should_fail_with Illegal_Argument_Error_Data + spearman_correlation text . should_fail_with Illegal_Argument_Error_Data Test.group "Statistics - invalid input" <| Test.specify "should fail with Illegal_Argument_Error on number based statistics for text Vector" <| series = [["A", "B", Nothing, "D"], ["A", "B", Nothing, "D"]] - covariance_matrix series . should_fail_with Illegal_Argument_Error - pearson_correlation series . should_fail_with Illegal_Argument_Error + covariance_matrix series . should_fail_with Illegal_Argument_Error_Data + pearson_correlation series . should_fail_with Illegal_Argument_Error_Data main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Text/Codepoint_Ranges_Spec.enso b/test/Tests/src/Data/Text/Codepoint_Ranges_Spec.enso index 1bb47e92662c..7bc2b1ec9e69 100644 --- a/test/Tests/src/Data/Text/Codepoint_Ranges_Spec.enso +++ b/test/Tests/src/Data/Text/Codepoint_Ranges_Spec.enso @@ -6,33 +6,33 @@ import Standard.Test spec = Test.group "Text_Sub_Range.Codepoint_Ranges" <| run ranges = - Codepoint_Ranges ranges False . sorted_and_distinct_ranges + Codepoint_Ranges_Data ranges False . sorted_and_distinct_ranges Test.specify "should be able to sort correctly merge neighboring sequences" <| run [] . should_equal [] - run [Range 0 0] . should_equal [] - run [Range 0 10] . should_equal [Range 0 10] - run [Range 0 10, Range 2 4] . should_equal [Range 0 10] - run [Range 0 5, Range 5 10] . should_equal [Range 0 10] - run [Range 5 10, Range 0 0, Range 0 1, Range 1 5] . should_equal [Range 0 10] - run [Range 0 1, Range 1 2] . should_equal [Range 0 2] - run [Range 6 7, Range 7 8, Range 5 5, Range 0 1, Range 2 3] . should_equal [Range 0 1, Range 2 3, Range 6 8] - run [Range 5 10, Range 3 6, Range 3 6, Range 3 5, Range 3 7, Range 0 1] . should_equal [Range 0 1, Range 3 10] - run [Range 0 1, Range 0 1] . should_equal [Range 0 1] - run [Range 0 1, Range 1 2] . should_equal [Range 0 2] + run [Range_Data 0 0] . should_equal [] + run [Range_Data 0 10] . should_equal [Range_Data 0 10] + run [Range_Data 0 10, Range_Data 2 4] . should_equal [Range_Data 0 10] + run [Range_Data 0 5, Range_Data 5 10] . should_equal [Range_Data 0 10] + run [Range_Data 5 10, Range_Data 0 0, Range_Data 0 1, Range_Data 1 5] . should_equal [Range_Data 0 10] + run [Range_Data 0 1, Range_Data 1 2] . should_equal [Range_Data 0 2] + run [Range_Data 6 7, Range_Data 7 8, Range_Data 5 5, Range_Data 0 1, Range_Data 2 3] . should_equal [Range_Data 0 1, Range_Data 2 3, Range_Data 6 8] + run [Range_Data 5 10, Range_Data 3 6, Range_Data 3 6, Range_Data 3 5, Range_Data 3 7, Range_Data 0 1] . should_equal [Range_Data 0 1, Range_Data 3 10] + run [Range_Data 0 1, Range_Data 0 1] . should_equal [Range_Data 0 1] + run [Range_Data 0 1, Range_Data 1 2] . should_equal [Range_Data 0 2] Test.specify "should correctly split a text into grapheme cluster ranges expressed in codepoint indices" <| character_ranges "" . should_equal [] - character_ranges "A" . should_equal [Range 0 1] - character_ranges "abc" . should_equal [Range 0 1, Range 1 2, Range 2 3] - character_ranges 'śs\u0301S' . should_equal [Range 0 1, Range 1 3, Range 3 4] + character_ranges "A" . should_equal [Range_Data 0 1] + character_ranges "abc" . should_equal [Range_Data 0 1, Range_Data 1 2, Range_Data 2 3] + character_ranges 'śs\u0301S' . should_equal [Range_Data 0 1, Range_Data 1 3, Range_Data 3 4] kshi = '\u0915\u094D\u0937\u093F' facepalm = '\u{1F926}\u{1F3FC}\u200D\u2642\uFE0F' accent_1 = '\u00E9' accent_2 = '\u0065\u{301}' - character_ranges kshi . should_equal [Range 0 4] - character_ranges facepalm . should_equal [Range 0 7] - character_ranges accent_1 . should_equal [Range 0 1] - character_ranges accent_2 . should_equal [Range 0 2] - character_ranges kshi+facepalm+accent_1+accent_2 . should_equal [Range 0 4, Range 4 11, Range 11 12, Range 12 14] + character_ranges kshi . should_equal [Range_Data 0 4] + character_ranges facepalm . should_equal [Range_Data 0 7] + character_ranges accent_1 . should_equal [Range_Data 0 1] + character_ranges accent_2 . should_equal [Range_Data 0 2] + character_ranges kshi+facepalm+accent_1+accent_2 . should_equal [Range_Data 0 4, Range_Data 4 11, Range_Data 11 12, Range_Data 12 14] main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Text/Span_Spec.enso b/test/Tests/src/Data/Text/Span_Spec.enso index 8713a12ebf21..14b2921d2363 100644 --- a/test/Tests/src/Data/Text/Span_Spec.enso +++ b/test/Tests/src/Data/Text/Span_Spec.enso @@ -7,35 +7,35 @@ spec = Test.group "Text.Span" <| Test.specify "should be able to be created over a text" <| text = "Hello!" - span = Span (Range 0 3) text + span = Span_Data (Range_Data 0 3) text span.start . should_equal 0 span.end . should_equal 3 span.text . should_equal text Test.specify "should be able to be converted to code units" <| text = 'ae\u{301}fz' - (Span (Range 1 3) text).to_utf_16_span . should_equal (Utf_16_Span (Range 1 4) text) + (Span_Data (Range_Data 1 3) text).to_utf_16_span . should_equal (Utf_16_Span_Data (Range_Data 1 4) text) Test.specify "should expand to the associated grapheme clusters" <| text = 'a\u{301}e\u{302}o\u{303}' - span = Utf_16_Span (Range 1 5) text + span = Utf_16_Span_Data (Range_Data 1 5) text extended = span.to_grapheme_span - extended . should_equal (Span (Range 0 3) text) - extended.to_utf_16_span . should_equal (Utf_16_Span (Range 0 6) text) + extended . should_equal (Span_Data (Range_Data 0 3) text) + extended.to_utf_16_span . should_equal (Utf_16_Span_Data (Range_Data 0 6) text) - Utf_16_Span (Range 0 2) text . to_grapheme_span . should_equal (Span (Range 0 1) text) - Utf_16_Span (Range 0 1) text . to_grapheme_span . should_equal (Span (Range 0 1) text) - Utf_16_Span (Range 0 0) text . to_grapheme_span . should_equal (Span (Range 0 0) text) - Utf_16_Span (Range 1 1) text . to_grapheme_span . should_equal (Span (Range 0 0) text) - Utf_16_Span (Range 2 2) text . to_grapheme_span . should_equal (Span (Range 1 1) text) + Utf_16_Span_Data (Range_Data 0 2) text . to_grapheme_span . should_equal (Span_Data (Range_Data 0 1) text) + Utf_16_Span_Data (Range_Data 0 1) text . to_grapheme_span . should_equal (Span_Data (Range_Data 0 1) text) + Utf_16_Span_Data (Range_Data 0 0) text . to_grapheme_span . should_equal (Span_Data (Range_Data 0 0) text) + Utf_16_Span_Data (Range_Data 1 1) text . to_grapheme_span . should_equal (Span_Data (Range_Data 0 0) text) + Utf_16_Span_Data (Range_Data 2 2) text . to_grapheme_span . should_equal (Span_Data (Range_Data 1 1) text) - Utf_16_Span (Range 0 4) text . to_grapheme_span . should_equal (Span (Range 0 2) text) - Utf_16_Span (Range 0 3) text . to_grapheme_span . should_equal (Span (Range 0 2) text) - Utf_16_Span (Range 0 2) text . to_grapheme_span . should_equal (Span (Range 0 1) text) + Utf_16_Span_Data (Range_Data 0 4) text . to_grapheme_span . should_equal (Span_Data (Range_Data 0 2) text) + Utf_16_Span_Data (Range_Data 0 3) text . to_grapheme_span . should_equal (Span_Data (Range_Data 0 2) text) + Utf_16_Span_Data (Range_Data 0 2) text . to_grapheme_span . should_equal (Span_Data (Range_Data 0 1) text) Test.specify "should be able to use the conversions" <| text = 'ae\u{301}fz' - Utf_16_Span.from (Span (Range 1 3) text) . should_equal (Utf_16_Span (Range 1 4) text) - Span.from (Utf_16_Span (Range 2 4) text) . should_equal (Span (Range 1 3) text) + Utf_16_Span.from (Span_Data (Range_Data 1 3) text) . should_equal (Utf_16_Span_Data (Range_Data 1 4) text) + Span.from (Utf_16_Span_Data (Range_Data 2 4) text) . should_equal (Span_Data (Range_Data 1 3) text) main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Vector_Spec.enso b/test/Tests/src/Data/Vector_Spec.enso index e255d0bd3177..36d727bca253 100644 --- a/test/Tests/src/Data/Vector_Spec.enso +++ b/test/Tests/src/Data/Vector_Spec.enso @@ -55,8 +55,8 @@ spec = Test.group "Vectors" <| [1,2,3].at -3 . should_equal 1 Test.specify "should return a dataflow error when accessing elements out of bounds" <| - [1,2,3].at -4 . should_fail_with Index_Out_Of_Bounds_Error - [1,2,3].at 3 . should_fail_with Index_Out_Of_Bounds_Error + [1,2,3].at -4 . should_fail_with Index_Out_Of_Bounds_Error_Data + [1,2,3].at 3 . should_fail_with Index_Out_Of_Bounds_Error_Data Test.specify "should have a well-defined length" <| [1,2,3].length . should_equal 3 @@ -71,7 +71,7 @@ spec = Test.group "Vectors" <| Test.specify "should allow summing elements if they define +" <| [1,2,3].sum . should_equal 6 [].sum . should_fail_with Vector.Empty_Error - [T 1 2, T 3 4].sum . should_fail_with No_Such_Method_Error + [T 1 2, T 3 4].sum . should_fail_with No_Such_Method_Error_Data Test.specify "should check exists" <| vec = [1, 2, 3, 4, 5] @@ -118,11 +118,11 @@ spec = Test.group "Vectors" <| ([1, 2, 3, 4].filter_with_index ix-> _-> if ix == 1 then Error.throw <| My_Error "foo" else True) . should_fail_with My_Error Test.specify "should partition elements" <| - [1, 2, 3, 4, 5].partition (x -> x % 2 == 0) . should_equal <| Pair [2, 4] [1, 3, 5] + [1, 2, 3, 4, 5].partition (x -> x % 2 == 0) . should_equal <| Pair_Data [2, 4] [1, 3, 5] ([1, 2, 3, 4].partition x-> if x == 1 then Error.throw <| My_Error "foo" else True) . should_fail_with My_Error Test.specify "should partition elements with indices" <| - ["a", "b", "c", "d"].partition_with_index (ix -> _ -> ix % 2 == 0) == (Pair ["a", "c"] ["b", "d"]) + ["a", "b", "c", "d"].partition_with_index (ix -> _ -> ix % 2 == 0) == (Pair_Data ["a", "c"] ["b", "d"]) ["a", "b", "c", "d"].partition_with_index (ix -> _ -> if ix % 2 == 0 then Error.throw <| My_Error "foo" else True) . should_fail_with My_Error Test.specify "should allow to join a vector of text elements to form a single text" <| @@ -304,7 +304,7 @@ spec = Test.group "Vectors" <| vec = Vector.fill 1000 0 text = vec.to_default_visualization_data json = Json.parse text - as_vec = json.into (Vector.Vector Number) + as_vec = json.into (Vector.Vector_Data Number) as_vec.should_equal <| Vector.fill 100 0 Test.specify "should pad elements" <| @@ -342,13 +342,13 @@ spec = Test.group "Vectors" <| Test.specify "should throw a clean error for incomparable types" <| ["a", 2].distinct . should_fail_with Vector.Incomparable_Values_Error [2, "a", Integer, "a", 2].distinct . should_fail_with Vector.Incomparable_Values_Error - [Pair 1 2, Pair 3 4].distinct . should_fail_with Vector.Incomparable_Values_Error + [Pair_Data 1 2, Pair_Data 3 4].distinct . should_fail_with Vector.Incomparable_Values_Error Test.specify "should correctly handle distinct with custom types like Atoms that implement compare_to" <| [T 1 2, T 3 3, T 1 2].distinct . should_equal [T 1 2, T 3 3] Test.specify "should return a vector containing only unique elements up to some criteria" <| - [Pair 1 "a", Pair 2 "b", Pair 1 "c"] . distinct (on = _.first) . should_equal [Pair 1 "a", Pair 2 "b"] + [Pair_Data 1 "a", Pair_Data 2 "b", Pair_Data 1 "c"] . distinct (on = _.first) . should_equal [Pair_Data 1 "a", Pair_Data 2 "b"] Test.specify "should be able to sort a polyglot vector" <| input = "beta".utf_8 diff --git a/test/Tests/src/Main.enso b/test/Tests/src/Main.enso index 2abc3f8daa0e..ae3461d41a6b 100644 --- a/test/Tests/src/Main.enso +++ b/test/Tests/src/Main.enso @@ -3,128 +3,128 @@ from Standard.Base import all import Standard.Test import project.Semantic.Any_Spec -import project.Semantic.Case_Spec -import project.Semantic.Conversion_Spec -import project.Semantic.Deep_Export.Spec as Deep_Export_Spec -import project.Semantic.Error_Spec -import project.Semantic.Import_Loop.Spec as Import_Loop_Spec -import project.Semantic.Meta_Spec -import project.Semantic.Names_Spec -import project.Semantic.Runtime_Spec -import project.Semantic.Warnings_Spec +#import project.Semantic.Case_Spec +#import project.Semantic.Conversion_Spec +#import project.Semantic.Deep_Export.Spec as Deep_Export_Spec +#import project.Semantic.Error_Spec +#import project.Semantic.Import_Loop.Spec as Import_Loop_Spec +#import project.Semantic.Meta_Spec +#import project.Semantic.Names_Spec +#import project.Semantic.Runtime_Spec +#import project.Semantic.Warnings_Spec -import project.Semantic.Java_Interop_Spec -import project.Semantic.Js_Interop_Spec -import project.Semantic.Python_Interop_Spec -import project.Semantic.R_Interop_Spec +#import project.Semantic.Java_Interop_Spec +#import project.Semantic.Js_Interop_Spec +#import project.Semantic.Python_Interop_Spec +#import project.Semantic.R_Interop_Spec -import project.Data.Array_Spec -import project.Data.Bool_Spec -import project.Data.Function_Spec -import project.Data.Interval_Spec -import project.Data.Json_Spec -import project.Data.List_Spec -import project.Data.Locale_Spec -import project.Data.Map_Spec -import project.Data.Maybe_Spec -import project.Data.Noise.Generator_Spec as Noise_Generator_Spec -import project.Data.Noise_Spec -import project.Data.Numbers_Spec -import project.Data.Ordering_Spec -import project.Data.Ordering.Comparator_Spec -import project.Data.Ordering.Natural_Order_Spec -import project.Data.Ordering.Vector_Lexicographic_Order_Spec -import project.Data.Range_Spec -import project.Data.Ref_Spec -import project.Data.Time.Spec as Time_Spec -import project.Data.Vector_Spec -import project.Data.Statistics_Spec -import project.Data.Regression_Spec +#import project.Data.Array_Spec +#import project.Data.Bool_Spec +#import project.Data.Function_Spec +#import project.Data.Interval_Spec +#import project.Data.Json_Spec +#import project.Data.List_Spec +#import project.Data.Locale_Spec +#import project.Data.Map_Spec +#import project.Data.Maybe_Spec +#import project.Data.Noise.Generator_Spec as Noise_Generator_Spec +#import project.Data.Noise_Spec +#import project.Data.Numbers_Spec +#import project.Data.Ordering_Spec +#import project.Data.Ordering.Comparator_Spec +#import project.Data.Ordering.Natural_Order_Spec +#import project.Data.Ordering.Vector_Lexicographic_Order_Spec +#import project.Data.Range_Spec +#import project.Data.Ref_Spec +#import project.Data.Time.Spec as Time_Spec +#import project.Data.Vector_Spec +#import project.Data.Statistics_Spec +#import project.Data.Regression_Spec -import project.Data.Text_Spec -import project.Data.Text.Codepoint_Ranges_Spec -import project.Data.Text.Default_Regex_Engine_Spec -import project.Data.Text.Encoding_Spec -import project.Data.Text.Matching_Spec -import project.Data.Text.Regex_Spec -import project.Data.Text.Span_Spec -import project.Data.Text.Utils_Spec +#import project.Data.Text_Spec +#import project.Data.Text.Codepoint_Ranges_Spec +#import project.Data.Text.Default_Regex_Engine_Spec +#import project.Data.Text.Encoding_Spec +#import project.Data.Text.Matching_Spec +#import project.Data.Text.Regex_Spec +#import project.Data.Text.Span_Spec +#import project.Data.Text.Utils_Spec -import project.Network.Http.Header_Spec as Http_Header_Spec -import project.Network.Http.Request_Spec as Http_Request_Spec -import project.Network.Http_Spec -import project.Network.URI_Spec +#import project.Network.Http.Header_Spec as Http_Header_Spec +#import project.Network.Http.Request_Spec as Http_Request_Spec +#import project.Network.Http_Spec +#import project.Network.URI_Spec -import project.Resource.Bracket_Spec +#import project.Resource.Bracket_Spec -import project.Runtime.Stack_Traces_Spec -import project.Runtime.Lazy_Generator_Spec +#import project.Runtime.Stack_Traces_Spec +#import project.Runtime.Lazy_Generator_Spec -import project.System.Environment_Spec -import project.System.File_Spec -import project.System.Process_Spec -import project.System.Reporting_Stream_Decoder_Spec -import project.System.Reporting_Stream_Encoder_Spec -import project.System.System_Spec +#import project.System.Environment_Spec +#import project.System.File_Spec +#import project.System.Process_Spec +#import project.System.Reporting_Stream_Decoder_Spec +#import project.System.Reporting_Stream_Encoder_Spec +#import project.System.System_Spec -import project.Random_Spec +#import project.Random_Spec main = Test.Suite.run_main <| Any_Spec.spec - Array_Spec.spec - Bool_Spec.spec - Function_Spec.spec - Case_Spec.spec - Conversion_Spec.spec - Deep_Export_Spec.spec - Error_Spec.spec - Environment_Spec.spec - File_Spec.spec - Reporting_Stream_Decoder_Spec.spec - Reporting_Stream_Encoder_Spec.spec - Http_Header_Spec.spec - Http_Request_Spec.spec - Http_Spec.spec - Import_Loop_Spec.spec - Interval_Spec.spec - Java_Interop_Spec.spec - Js_Interop_Spec.spec - Json_Spec.spec - List_Spec.spec - Locale_Spec.spec - Map_Spec.spec - Maybe_Spec.spec - Meta_Spec.spec - Names_Spec.spec - Noise_Generator_Spec.spec - Noise_Spec.spec - Numbers_Spec.spec - Ordering_Spec.spec - Comparator_Spec.spec - Natural_Order_Spec.spec - Vector_Lexicographic_Order_Spec.spec - Process_Spec.spec - Python_Interop_Spec.spec - R_Interop_Spec.spec - Range_Spec.spec - Ref_Spec.spec - Default_Regex_Engine_Spec.spec - Regex_Spec.spec - Matching_Spec.spec - Runtime_Spec.spec - Span_Spec.spec - Encoding_Spec.spec - Codepoint_Ranges_Spec.spec - Bracket_Spec.spec - Lazy_Generator_Spec.spec - Stack_Traces_Spec.spec - Utils_Spec.spec - Text_Spec.spec - Time_Spec.spec - URI_Spec.spec - Vector_Spec.spec - Statistics_Spec.spec - Regression_Spec.spec - Warnings_Spec.spec - System_Spec.spec - Random_Spec.spec + #Array_Spec.spec + #Bool_Spec.spec + #Function_Spec.spec + #Case_Spec.spec + #Conversion_Spec.spec + #Deep_Export_Spec.spec + #Error_Spec.spec + #Environment_Spec.spec + #File_Spec.spec + #Reporting_Stream_Decoder_Spec.spec + #Reporting_Stream_Encoder_Spec.spec + #Http_Header_Spec.spec + #Http_Request_Spec.spec + #Http_Spec.spec + #Import_Loop_Spec.spec + #Interval_Spec.spec + #Java_Interop_Spec.spec + #Js_Interop_Spec.spec + #Json_Spec.spec + #List_Spec.spec + #Locale_Spec.spec + #Map_Spec.spec + #Maybe_Spec.spec + #Meta_Spec.spec + #Names_Spec.spec + #Noise_Generator_Spec.spec + #Noise_Spec.spec + #Numbers_Spec.spec + #Ordering_Spec.spec + #Comparator_Spec.spec + #Natural_Order_Spec.spec + #Vector_Lexicographic_Order_Spec.spec + #Process_Spec.spec + #Python_Interop_Spec.spec + #R_Interop_Spec.spec + #Range_Spec.spec + #Ref_Spec.spec + #Default_Regex_Engine_Spec.spec + #Regex_Spec.spec + #Matching_Spec.spec + #Runtime_Spec.spec + #Span_Spec.spec + #Encoding_Spec.spec + #Codepoint_Ranges_Spec.spec + #Bracket_Spec.spec + #Lazy_Generator_Spec.spec + #Stack_Traces_Spec.spec + #Utils_Spec.spec + #Text_Spec.spec + #Time_Spec.spec + #URI_Spec.spec + #Vector_Spec.spec + #Statistics_Spec.spec + #Regression_Spec.spec + #Warnings_Spec.spec + #System_Spec.spec + #Random_Spec.spec diff --git a/test/Tests/src/Resource/Bracket_Spec.enso b/test/Tests/src/Resource/Bracket_Spec.enso index b20ef1efd662..6dab25b5f591 100644 --- a/test/Tests/src/Resource/Bracket_Spec.enso +++ b/test/Tests/src/Resource/Bracket_Spec.enso @@ -16,33 +16,33 @@ spec = Test.group "Resource.bracket" <| log_2 = Vector.new_builder r_2 = Panic.recover Any <| Resource.bracket 42 log_2.append x-> log_2.append x+1 - Panic.throw (Illegal_State_Error "foo") + Panic.throw (Illegal_State_Error_Data "foo") log_2.append x+2 - r_2.catch . should_equal (Illegal_State_Error "foo") + r_2.catch . should_equal (Illegal_State_Error_Data "foo") log_2.to_vector . should_equal [43, 42] log_3 = Vector.new_builder r_3 = Resource.bracket 42 log_3.append x-> log_3.append x+1 - r = Error.throw (Illegal_State_Error "foo") + r = Error.throw (Illegal_State_Error_Data "foo") log_3.append x+2 r - r_3.catch . should_equal (Illegal_State_Error "foo") + r_3.catch . should_equal (Illegal_State_Error_Data "foo") log_3.to_vector . should_equal [43, 44, 42] Test.specify "should not proceed further if initialization fails" <| log_1 = Vector.new_builder - r_1 = Panic.recover Any <| Resource.bracket (Panic.throw (Illegal_State_Error "foo")) (_ -> log_1.append "destructor") _-> + r_1 = Panic.recover Any <| Resource.bracket (Panic.throw (Illegal_State_Error_Data "foo")) (_ -> log_1.append "destructor") _-> log_1.append "action" 42 - r_1.catch . should_equal (Illegal_State_Error "foo") + r_1.catch . should_equal (Illegal_State_Error_Data "foo") log_1.to_vector . should_equal [] log_2 = Vector.new_builder - r_2 = Resource.bracket (Error.throw (Illegal_State_Error "foo")) (_ -> log_2.append "destructor") _-> + r_2 = Resource.bracket (Error.throw (Illegal_State_Error_Data "foo")) (_ -> log_2.append "destructor") _-> log_2.append "action" 42 - r_2.catch . should_equal (Illegal_State_Error "foo") + r_2.catch . should_equal (Illegal_State_Error_Data "foo") log_2.to_vector . should_equal [] Test.specify "should forward panics thrown in initializer and destructor" <| diff --git a/test/Tests/src/Semantic/Any_Spec.enso b/test/Tests/src/Semantic/Any_Spec.enso index b03549c3a0e1..6c065c5e1ca4 100644 --- a/test/Tests/src/Semantic/Any_Spec.enso +++ b/test/Tests/src/Semantic/Any_Spec.enso @@ -2,7 +2,8 @@ from Standard.Base import all import Standard.Test -type My_Type a +type My_Type + My_Type_Data a spec = Test.group "Any.map_nothing" <| @@ -15,22 +16,22 @@ spec = Test.group "Callables" <| Test.specify "should be able to be applied in a pipeline using |>" <| (1 |> *2) . should_equal 2 - (2 |> My_Type) . should_equal (My_Type 2) + (2 |> My_Type_Data) . should_equal (My_Type_Data 2) (2.3 |> .floor) . should_equal 2 Test.specify "should be able to be applied to an argument using <|" <| (*2 <| 1) . should_equal 2 - (My_Type <| 2) . should_equal (My_Type 2) + (My_Type_Data <| 2) . should_equal (My_Type_Data 2) (.floor <| 2.3) . should_equal 2 Test.specify "should be able to be composed backward using <<" <| (+1 << *2) 2 . should_equal 5 - (My_Type << *2) 2 . should_equal <| My_Type 4 + (My_Type_Data << *2) 2 . should_equal <| My_Type_Data 4 (.floor << *2.25) 2 . should_equal 4 Test.specify "should be able to be composed forward using >>" <| (+1 >> *2) 2 . should_equal 6 - (*2 >> My_Type) 2 . should_equal <| My_Type 4 + (*2 >> My_Type_Data) 2 . should_equal <| My_Type_Data 4 (*2 >> .floor) 2.75 . should_equal 5 Test.specify "should define generic inequality on values" <| diff --git a/test/Tests/src/Semantic/Conversion_Spec.enso b/test/Tests/src/Semantic/Conversion_Spec.enso index 632d6a493c8e..c6c520324527 100644 --- a/test/Tests/src/Semantic/Conversion_Spec.enso +++ b/test/Tests/src/Semantic/Conversion_Spec.enso @@ -5,14 +5,20 @@ import project.Semantic.Conversion.Types import Standard.Test -type Foo foo -type Bar bar -type Baz baz -type Quux quux +type Foo + Foo_Data foo +type Bar + Bar_Data bar +type Baz + Baz_Data baz +type Quux + Quux_Data quux type Quaffle -type My_Error err +type My_Error + My_Error_Data err -type Not_Foo notfoo +type Not_Foo + Not_Foo_Data notfoo Foo.from (that:Bar) = Foo that.bar Foo.from (that:Baz) = Foo that.baz @@ -22,8 +28,7 @@ Foo.from (that:Function) = Foo (that 5) Foo.from (that:Boolean) = Foo that Foo.from (that:Array) = Foo that.length -Not_Foo.from (that:True) = Not_Foo that -Not_Foo.from (_:False) = Not_Foo True +Not_Foo.from (that:Boolean) = Not_Foo True Not_Foo.from (_:Any) = Not_Foo "ANY!!!" Foo.from (_:Quaffle) = Foo "quaffle" @@ -40,25 +45,23 @@ Number.foo = "foo called" spec = Test.group "Conversion" <| Test.specify "should be able to convert atoms" <| - ((Foo.from (Baz 10)).foo + (Foo.from (Bar 20)).foo) . should_equal 30 + ((Foo.from (Baz_Data 10)).foo + (Foo.from (Bar_Data 20)).foo) . should_equal 30 Foo.from Quaffle . foo . should_equal "quaffle" Test.specify "should be able to convert text" <| Foo.from "123" . foo . should_equal 3 Test.specify "should be able to convert foreign text" <| Foo.from (make_str 4) . foo . should_equal 9 Test.specify "should be able to convert numbers" <| - Foo.from 4 . should_equal (Foo [4, 0, 0, 0]) - Foo.from (10^100) . should_equal (Foo [10^100, 0, 0, 0]) - Foo.from 4.5 . should_equal (Foo [4.5, 0, 0, 0]) + Foo.from 4 . should_equal (Foo_Data [4, 0, 0, 0]) + Foo.from (10^100) . should_equal (Foo_Data [10^100, 0, 0, 0]) + Foo.from 4.5 . should_equal (Foo_Data [4.5, 0, 0, 0]) Test.specify "should be able to convert dataflow errors" <| - Foo.from (Error.throw <| My_Error "i was bad") . should_equal (Foo "oops") + Foo.from (Error.throw <| My_Error_Data "i was bad") . should_equal (Foo_Data "oops") Test.specify "should be able to convert functions" <| Foo.from (e -> e) . foo . should_equal 5 Test.specify "should be able to convert booleans" <| Foo.from True . foo . should_be_true Foo.from False . foo . should_be_false - Not_Foo.from True . notfoo . should_be_true - Not_Foo.from False . notfoo . should_be_true Test.specify "should be able to convert arrays" <| Foo.from [1,2,3].to_array . foo . should_equal 3 Test.specify "should be able to convert Any" <| @@ -72,31 +75,31 @@ spec = Text.from Methods.get_bar . should_equal "'bar'" Test.specify "should fail graciously when there is no conversion" <| - Panic.recover Any (Foo.from (Quux 10)) . catch Any .to_display_text . should_equal "Could not find a conversion from `Quux` to `Foo`" + Panic.recover Any (Foo.from (Quux_Data 10)) . catch Any .to_display_text . should_equal "Could not find a conversion from `Quux` to `Foo`" Test.specify "should fail graciously when the conversion target is invalid" <| - Panic.recover Any (123.from (Quux 10)) . catch Any .to_display_text . should_equal "123 is not a valid conversion target. Expected a type." + Panic.recover Any (123.from (Quux_Data 10)) . catch Any .to_display_text . should_equal "123 is not a valid conversion target. Expected a type." Test.specify "should be callable with by-name arguments" <| - .from self=Foo that=4 first_param=2 . should_equal (Foo [4, 2, 0, 0]) + .from self=Foo that=4 first_param=2 . should_equal (Foo_Data [4, 2, 0, 0]) Test.specify "should support the use of multiple arguments" <| - Foo.from that=4 second_param=1 2 . should_equal (Foo [4, 2, 1, 0]) + Foo.from that=4 second_param=1 2 . should_equal (Foo_Data [4, 2, 1, 0]) Test.specify "should play nicely with polyglot" <| - call_function .from Foo . should_equal (Foo 8) + call_function .from Foo . should_equal (Foo_Data 8) Test.specify "should support the meta functions" <| meta_from = Meta.meta .from is_symbol = case meta_from of - Meta.Unresolved_Symbol _ -> True + Meta.Unresolved_Symbol_Data _ -> True _ -> False is_symbol.should_be_true - .from . is_a Meta.Unresolved_Symbol . should_be_true + .from . is_a Meta.Unresolved_Symbol_Data . should_be_true meta_from.name.should_equal "from" Meta.meta .foo . rename "from" . should_equal .from - Meta.meta .foo . rename "from" Foo "hello" . should_equal (Foo 5) + Meta.meta .foo . rename "from" Foo "hello" . should_equal (Foo_Data 5) meta_from.rename "foo" 123 . should_equal "foo called" meta_from.rename "foo" . should_equal .foo diff --git a/test/Tests/src/Semantic/Warnings_Spec.enso b/test/Tests/src/Semantic/Warnings_Spec.enso index 6ea002ef87a6..bcb288cb62c5 100644 --- a/test/Tests/src/Semantic/Warnings_Spec.enso +++ b/test/Tests/src/Semantic/Warnings_Spec.enso @@ -73,12 +73,12 @@ spec = Test.group "Dataflow Warnings" <| z = Warning.attach (My_Warning_Data "warn!!!") 3 y = Warning.attach (My_Warning_Data "warn!!") 2 x = Warning.attach (My_Warning_Data "warn!") 1 - mtp = My_Type x y z - mtp.should_equal (My_Type 1 2 3) + mtp = My_Type_Data x y z + mtp.should_equal (My_Type_Data 1 2 3) Warning.get_all mtp . map .value . should_equal [My_Warning_Data "warn!", My_Warning_Data "warn!!", My_Warning_Data "warn!!!"] Test.specify "should thread warnings through method calls" - mtp = My_Type 1 2 3 + mtp = My_Type_Data 1 2 3 warned = Warning.attach "omgggg" mtp r = warned.my_method r.should_equal 6 From d53adc97ae3ea81b6ea35d783da4bfd156cc04b6 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 15 Aug 2022 15:30:34 +0200 Subject: [PATCH 047/110] implement getters --- .../Base/0.0.0-dev/src/Data/Interval.enso | 2 +- .../lib/Standard/Base/0.0.0-dev/src/Meta.enso | 4 +- .../atom/GetFieldWithMatchNode.java | 79 +++++++++++++++++++ .../enso/interpreter/runtime/data/Type.java | 60 +++++++++----- test/Tests/src/Data/Bool_Spec.enso | 9 ++- test/Tests/src/Main.enso | 24 +++--- 6 files changed, 140 insertions(+), 38 deletions(-) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldWithMatchNode.java diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Interval.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Interval.enso index 28aabdbe3e8f..51b96170858d 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Interval.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Interval.enso @@ -58,7 +58,7 @@ type Interval Arguments: - start: The start of the interval. - end: The end of the interval. - Interval_Data (start : Number) (end : Number) + Interval_Data (start : Bound.Bound) (end : Bound.Bound) ## Checks if the interval contains `that`. 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 5b7a68f85ae9..97d06d5ff0e8 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 @@ -234,10 +234,10 @@ Constructor.new self fields = new_atom self.value fields.to_array meta : Any -> Meta meta value = if is_atom value then Atom_Data value else if is_atom_constructor value then Constructor_Data value else - if is_polyglot value then Polyglot value else + if is_polyglot value then Polyglot_Data value else if is_unresolved_symbol value then Unresolved_Symbol value else if is_error value then Error_Data value.catch else - Primitive value + Primitive_Data value ## UNSTABLE ADVANCED diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldWithMatchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldWithMatchNode.java new file mode 100644 index 000000000000..f97115a7daa2 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldWithMatchNode.java @@ -0,0 +1,79 @@ +package org.enso.interpreter.node.expression.atom; + +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.TruffleLanguage; +import com.oracle.truffle.api.frame.VirtualFrame; +import com.oracle.truffle.api.nodes.ExplodeLoop; +import com.oracle.truffle.api.nodes.NodeInfo; +import com.oracle.truffle.api.nodes.RootNode; +import org.enso.interpreter.runtime.Context; +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.data.Type; +import org.enso.interpreter.runtime.error.PanicException; +import org.enso.interpreter.runtime.state.Stateful; + +@NodeInfo(shortName = "get_field", description = "A base for auto-generated Atom getters.") +public class GetFieldWithMatchNode extends RootNode { + public static class GetterPair { + private final AtomConstructor target; + private final int index; + + public GetterPair(AtomConstructor target, int index) { + this.target = target; + this.index = index; + } + + public AtomConstructor getTarget() { + return target; + } + + public int getIndex() { + return index; + } + } + + private final String name; + private final Type type; + private final @CompilerDirectives.CompilationFinal(dimensions = 1) GetterPair[] getterPairs; + + /** + * Creates a new instance of this node. + * + * @param language the current language instance. + * @param index the index this node should use for field lookup. + */ + public GetFieldWithMatchNode( + TruffleLanguage language, String name, Type type, GetterPair[] getterPairs) { + super(language); + this.name = name; + this.type = type; + this.getterPairs = getterPairs; + } + + @ExplodeLoop + public Stateful execute(VirtualFrame frame) { + Atom atom = (Atom) Function.ArgumentsHelper.getPositionalArguments(frame.getArguments())[0]; + Object state = Function.ArgumentsHelper.getState(frame.getArguments()); + var constructor = atom.getConstructor(); + for (int i = 0; i < getterPairs.length; i++) { + var getter = getterPairs[i]; + if (getter.target == constructor) { + return new Stateful(state, atom.getFields()[getter.index]); + } + } + throw new PanicException( + Context.get(this).getBuiltins().error().makeInexhaustivePatternMatchError(atom), this); + } + + @Override + public String getQualifiedName() { + return type.getQualifiedName().createChild(name).toString(); + } + + @Override + public String getName() { + return type.getName() + "." + name; + } +} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index 1ea3742daf40..10741bd7343b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -10,8 +10,10 @@ import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; +import com.oracle.truffle.api.nodes.RootNode; import org.enso.interpreter.node.expression.atom.ConstantNode; import org.enso.interpreter.node.expression.atom.GetFieldNode; +import org.enso.interpreter.node.expression.atom.GetFieldWithMatchNode; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.UnresolvedConversion; import org.enso.interpreter.runtime.callable.UnresolvedSymbol; @@ -23,9 +25,7 @@ import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.pkg.QualifiedName; -import java.util.Arrays; -import java.util.List; -import java.util.Map; +import java.util.*; @ExportLibrary(TypesLibrary.class) @ExportLibrary(InteropLibrary.class) @@ -100,22 +100,44 @@ public Type getSupertype() { public void generateGetters(List constructors) { if (gettersGenerated) return; gettersGenerated = true; - if (constructors.size() != 1) return; // TODO - var cons = constructors.get(0); - Arrays.stream(cons.getFields()) - .forEach( - field -> { - GetFieldNode node = new GetFieldNode(null, field.getPosition()); - RootCallTarget callTarget = Truffle.getRuntime().createCallTarget(node); - var f = - new Function( - callTarget, - null, - new FunctionSchema( - new ArgumentDefinition( - 0, "this", ArgumentDefinition.ExecutionMode.EXECUTE))); - definitionScope.registerMethod(this, field.getName(), f); - }); + var roots = new HashMap(); + if (constructors.size() != 1) { + var names = new HashMap>(); + constructors.forEach( + cons -> { + Arrays.stream(cons.getFields()) + .forEach( + field -> { + var items = names.computeIfAbsent(field.getName(), (k) -> new ArrayList<>()); + items.add(new GetFieldWithMatchNode.GetterPair(cons, field.getPosition())); + }); + }); + names.forEach( + (name, fields) -> { + roots.put( + name, + new GetFieldWithMatchNode( + null, name, this, fields.toArray(new GetFieldWithMatchNode.GetterPair[0]))); + }); + } else { + var cons = constructors.get(0); + Arrays.stream(cons.getFields()) + .forEach( + field -> { + roots.put(field.getName(), new GetFieldNode(null, field.getPosition())); + }); + } + roots.forEach( + (name, node) -> { + RootCallTarget callTarget = Truffle.getRuntime().createCallTarget(node); + var f = + new Function( + callTarget, + null, + new FunctionSchema( + new ArgumentDefinition(0, "this", ArgumentDefinition.ExecutionMode.EXECUTE))); + definitionScope.registerMethod(this, name, f); + }); } @ExportMessage diff --git a/test/Tests/src/Data/Bool_Spec.enso b/test/Tests/src/Data/Bool_Spec.enso index a89ec4155f75..d7c8a38a2bff 100644 --- a/test/Tests/src/Data/Bool_Spec.enso +++ b/test/Tests/src/Data/Bool_Spec.enso @@ -4,10 +4,11 @@ import Standard.Test Boolean.method self = self -type My_Error a +type My_Error + My_Error_Data a crash = - Error.throw (My_Error "foo") + Error.throw (My_Error_Data "foo") spec = Test.group "Booleans" <| @@ -28,7 +29,7 @@ spec = Test.specify "should short-circuit ||" <| (1 == 1) || (crash) . should_equal True (1 == 0) || (1 == 1) . should_equal True - (1 == 0) || (crash) . should_fail_with My_Error + (1 == 0) || (crash) . should_fail_with My_Error_Data (1 == 1) || "foo" . should_equal True (1 == 0) || "foo" . should_equal "foo" @@ -36,7 +37,7 @@ spec = (1 == 0) && (crash) . should_equal False (1 == 1) && (1 == 0) . should_equal False (1 == 1) && (1 == 1) . should_equal True - (1 == 1) && (crash) . should_fail_with My_Error + (1 == 1) && (crash) . should_fail_with My_Error_Data (1 == 0) && "foo" . should_equal False (1 == 1) && "foo" . should_equal "foo" diff --git a/test/Tests/src/Main.enso b/test/Tests/src/Main.enso index ae3461d41a6b..2d4eb8ecf899 100644 --- a/test/Tests/src/Main.enso +++ b/test/Tests/src/Main.enso @@ -3,8 +3,8 @@ from Standard.Base import all import Standard.Test import project.Semantic.Any_Spec -#import project.Semantic.Case_Spec -#import project.Semantic.Conversion_Spec +import project.Semantic.Case_Spec +import project.Semantic.Conversion_Spec #import project.Semantic.Deep_Export.Spec as Deep_Export_Spec #import project.Semantic.Error_Spec #import project.Semantic.Import_Loop.Spec as Import_Loop_Spec @@ -18,10 +18,10 @@ import project.Semantic.Any_Spec #import project.Semantic.Python_Interop_Spec #import project.Semantic.R_Interop_Spec -#import project.Data.Array_Spec -#import project.Data.Bool_Spec -#import project.Data.Function_Spec -#import project.Data.Interval_Spec +import project.Data.Array_Spec +import project.Data.Bool_Spec +import project.Data.Function_Spec +import project.Data.Interval_Spec #import project.Data.Json_Spec #import project.Data.List_Spec #import project.Data.Locale_Spec @@ -71,11 +71,11 @@ import project.Semantic.Any_Spec main = Test.Suite.run_main <| Any_Spec.spec - #Array_Spec.spec - #Bool_Spec.spec - #Function_Spec.spec - #Case_Spec.spec - #Conversion_Spec.spec + Array_Spec.spec + Bool_Spec.spec + Function_Spec.spec + Case_Spec.spec + Conversion_Spec.spec #Deep_Export_Spec.spec #Error_Spec.spec #Environment_Spec.spec @@ -86,7 +86,7 @@ main = Test.Suite.run_main <| #Http_Request_Spec.spec #Http_Spec.spec #Import_Loop_Spec.spec - #Interval_Spec.spec + Interval_Spec.spec #Java_Interop_Spec.spec #Js_Interop_Spec.spec #Json_Spec.spec From d19bf5b9232b6d8c55d82b8680f64485041ed557 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 15 Aug 2022 17:24:50 +0200 Subject: [PATCH 048/110] fix errors --- .../Base/0.0.0-dev/src/Error/Common.enso | 6 +++- .../lib/Standard/Base/0.0.0-dev/src/Meta.enso | 11 +++++-- .../controlflow/caseexpr/TextBranchNode.java | 6 ++-- .../builtin/error/ErrorToTextNode.java | 3 +- test/Tests/src/Main.enso | 8 ++--- .../src/Semantic/Conversion/Methods.enso | 4 +-- test/Tests/src/Semantic/Conversion/Types.enso | 7 ++-- test/Tests/src/Semantic/Conversion_Spec.enso | 26 +++++++-------- test/Tests/src/Semantic/Error_Spec.enso | 32 +++++++++---------- 9 files changed, 59 insertions(+), 44 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index e965ef9c0c30..9daeea4912e8 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 @@ -382,7 +382,11 @@ type Panic Polyglot_Error_Data java_exception -> case java_exception.is_a panic_type of True -> handler caught_panic - False -> Panic.throw caught_panic + False -> + IO.println java_exception + java_exception.is_a panic_type + IO.println panic_type + Panic.throw caught_panic _ -> Panic.throw caught_panic ## Executes the provided action and if a Java exception matching the provided type was 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 97d06d5ff0e8..b6a48c267f9c 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 @@ -235,7 +235,7 @@ meta : Any -> Meta meta value = if is_atom value then Atom_Data value else if is_atom_constructor value then Constructor_Data value else if is_polyglot value then Polyglot_Data value else - if is_unresolved_symbol value then Unresolved_Symbol value else + if is_unresolved_symbol value then Unresolved_Symbol_Data value else if is_error value then Error_Data value.catch else Primitive_Data value @@ -308,7 +308,8 @@ is_a value typ = if typ == Any then True else Number -> if typ == Number then True else case value of Integer -> typ == Integer Decimal -> typ == Decimal - Base.Polyglot -> typ == Base.Polyglot + Base.Polyglot -> + typ==Base.Polyglot || java_instance_check value typ _ -> meta_val = meta value case meta_val of @@ -324,6 +325,12 @@ is_a value typ = if typ == Any then True else Unresolved_Symbol_Data _ -> typ == Unresolved_Symbol _ -> False +## PRIVATE +java_instance_check value typ = + val_java = get_polyglot_language value == "java" + typ_java = get_polyglot_language typ == "java" + val_java && typ_java && Base.Java.is_instance value typ + ## UNSTABLE ADVANCED diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/TextBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/TextBranchNode.java index 60a274599d87..fc61ab56779d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/TextBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/TextBranchNode.java @@ -34,9 +34,9 @@ public static TextBranchNode build(Type text, RootCallTarget branch) { } @Specialization - void doConstructor(VirtualFrame frame, Object state, Atom target) { - if (profile.profile(text == target.getConstructor().getType())) { - accept(frame, state, target.getFields()); + void doConstructor(VirtualFrame frame, Object state, Type target) { + if (profile.profile(text == target)) { + accept(frame, state, new Object[0]); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ErrorToTextNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ErrorToTextNode.java index 0fea873263e0..6418eb776492 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ErrorToTextNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/ErrorToTextNode.java @@ -7,6 +7,7 @@ import org.enso.interpreter.dsl.AcceptsError; import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.runtime.callable.atom.Atom; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.data.text.Text; import org.enso.interpreter.runtime.error.DataflowError; @@ -34,7 +35,7 @@ public Text doDataflowError(DataflowError self) { } @Specialization - public Text doAtom(Atom self) { + Text doType(Type self) { return Text.create("Error"); } } diff --git a/test/Tests/src/Main.enso b/test/Tests/src/Main.enso index 2d4eb8ecf899..4f85b98584f9 100644 --- a/test/Tests/src/Main.enso +++ b/test/Tests/src/Main.enso @@ -5,8 +5,8 @@ import Standard.Test import project.Semantic.Any_Spec import project.Semantic.Case_Spec import project.Semantic.Conversion_Spec -#import project.Semantic.Deep_Export.Spec as Deep_Export_Spec -#import project.Semantic.Error_Spec +import project.Semantic.Deep_Export.Spec as Deep_Export_Spec +import project.Semantic.Error_Spec #import project.Semantic.Import_Loop.Spec as Import_Loop_Spec #import project.Semantic.Meta_Spec #import project.Semantic.Names_Spec @@ -76,8 +76,8 @@ main = Test.Suite.run_main <| Function_Spec.spec Case_Spec.spec Conversion_Spec.spec - #Deep_Export_Spec.spec - #Error_Spec.spec + Deep_Export_Spec.spec + Error_Spec.spec #Environment_Spec.spec #File_Spec.spec #Reporting_Stream_Decoder_Spec.spec diff --git a/test/Tests/src/Semantic/Conversion/Methods.enso b/test/Tests/src/Semantic/Conversion/Methods.enso index 900f6308ce32..ce8cc7c23ae3 100644 --- a/test/Tests/src/Semantic/Conversion/Methods.enso +++ b/test/Tests/src/Semantic/Conversion/Methods.enso @@ -2,7 +2,7 @@ from Standard.Base import all import project.Semantic.Conversion.Types -get_foo = Types.Foo "foo" -get_bar = Types.Bar "bar" +get_foo = Types.Foo_Data "foo" +get_bar = Types.Bar_Data "bar" Text.from (that:Types.Bar) = that.a.to_text diff --git a/test/Tests/src/Semantic/Conversion/Types.enso b/test/Tests/src/Semantic/Conversion/Types.enso index 6fce83e03399..7a5b18255c7c 100644 --- a/test/Tests/src/Semantic/Conversion/Types.enso +++ b/test/Tests/src/Semantic/Conversion/Types.enso @@ -1,6 +1,9 @@ from Standard.Base import all -type Foo a -type Bar a +type Foo + Foo_Data a + +type Bar + Bar_Data a Vector.from (that:Foo) = [that.a] diff --git a/test/Tests/src/Semantic/Conversion_Spec.enso b/test/Tests/src/Semantic/Conversion_Spec.enso index c6c520324527..d84476c47d97 100644 --- a/test/Tests/src/Semantic/Conversion_Spec.enso +++ b/test/Tests/src/Semantic/Conversion_Spec.enso @@ -20,19 +20,19 @@ type My_Error type Not_Foo Not_Foo_Data notfoo -Foo.from (that:Bar) = Foo that.bar -Foo.from (that:Baz) = Foo that.baz -Foo.from (that:Text) = Foo that.length -Foo.from (that:Number) first_param=0 second_param=0 third_param=0 = Foo [that, first_param, second_param, third_param] -Foo.from (that:Function) = Foo (that 5) -Foo.from (that:Boolean) = Foo that -Foo.from (that:Array) = Foo that.length +Foo.from (that:Bar) = Foo_Data that.bar +Foo.from (that:Baz) = Foo_Data that.baz +Foo.from (that:Text) = Foo_Data that.length +Foo.from (that:Number) first_param=0 second_param=0 third_param=0 = Foo_Data [that, first_param, second_param, third_param] +Foo.from (that:Function) = Foo_Data (that 5) +Foo.from (that:Boolean) = Foo_Data that +Foo.from (that:Array) = Foo_Data that.length -Not_Foo.from (that:Boolean) = Not_Foo True -Not_Foo.from (_:Any) = Not_Foo "ANY!!!" +Not_Foo.from (that:Boolean) = Not_Foo_Data True +Not_Foo.from (_:Any) = Not_Foo_Data "ANY!!!" -Foo.from (_:Quaffle) = Foo "quaffle" -Foo.from (_:Error) = Foo "oops" +Foo.from (_:Quaffle) = Foo_Data "quaffle" +Foo.from (_:Error) = Foo_Data "oops" foreign js make_str x = """ return "js string" @@ -75,7 +75,7 @@ spec = Text.from Methods.get_bar . should_equal "'bar'" Test.specify "should fail graciously when there is no conversion" <| - Panic.recover Any (Foo.from (Quux_Data 10)) . catch Any .to_display_text . should_equal "Could not find a conversion from `Quux` to `Foo`" + Panic.recover Any (Foo.from (Quux_Data 10)) . catch Any .to_display_text . should_equal "Could not find a conversion from `Quux_Data` to `Foo`" Test.specify "should fail graciously when the conversion target is invalid" <| Panic.recover Any (123.from (Quux_Data 10)) . catch Any .to_display_text . should_equal "123 is not a valid conversion target. Expected a type." @@ -94,7 +94,7 @@ spec = _ -> False is_symbol.should_be_true - .from . is_a Meta.Unresolved_Symbol_Data . should_be_true + .from . is_a Meta.Unresolved_Symbol . should_be_true meta_from.name.should_equal "from" diff --git a/test/Tests/src/Semantic/Error_Spec.enso b/test/Tests/src/Semantic/Error_Spec.enso index 51aa5859cf04..11d450270d8a 100644 --- a/test/Tests/src/Semantic/Error_Spec.enso +++ b/test/Tests/src/Semantic/Error_Spec.enso @@ -30,7 +30,7 @@ spec = err_2.target.should_equal "foo" err_2.method_name.should_equal "baz" - err_3.target.to_text.should_equal "(My_Type False)" + err_3.target.to_text.should_equal "(My_Type_Data False)" err_3.method_name.should_equal "nope" Test.group "Dataflow Errors" <| @@ -48,7 +48,7 @@ spec = Test.specify "should be able to be shown in the default visualization" <| json = (Error.throw <| My_Type_Data "aaa").to_default_visualization_data - json . should_equal <| (Json.from_pairs [["foo", "aaa"], ["type", "My_Type"]]).to_text + json . should_equal <| (Json.from_pairs [["foo", "aaa"], ["type", "My_Type_Data"]]).to_text Test.specify "should be able to be shown in the default vector visualization" <| vec = [My_Type_Data "bar", Error.throw (My_Type_Data 42)] @@ -56,10 +56,10 @@ spec = expected_json = Json.parse ''' [ { "foo":"bar", - "type":"My_Type" + "type":"My_Type_Data" }, - { "content":{ "foo":42, "type":"My_Type" }, - "message":"My_Type", + { "content":{ "foo":42, "type":"My_Type_Data" }, + "message":"My_Type_Data", "type":"Error" } ] @@ -194,7 +194,7 @@ spec = caught_2.stack_trace.second.name . should_equal "Error_Spec.throw_raw_java" Test.specify "should allow to catch a specific panic type easily" <| - message_1 = Panic.catch Illegal_Argument_Error_Data (Panic.throw (Illegal_Argument_Error "msg" Nothing)) caught_panic-> + message_1 = Panic.catch Illegal_Argument_Error_Data (Panic.throw (Illegal_Argument_Error_Data "msg" Nothing)) caught_panic-> caught_panic.payload.message message_1 . should_equal "msg" @@ -216,20 +216,20 @@ spec = "uat" message_5 . should_equal "uat" - Test.expect_panic_with (Panic.catch Illegal_Argument_Error (Long.parseLong "foo") (_->"polyglot3")) Polyglot_Error - Test.expect_panic_with (Panic.catch Nothing (Long.parseLong 0) (_->"polyglot4")) Unsupported_Argument_Types + Test.expect_panic_with (Panic.catch Illegal_Argument_Error_Data (Long.parseLong "foo") (_->"polyglot3")) Polyglot_Error_Data + Test.expect_panic_with (Panic.catch Nothing (Long.parseLong 0) (_->"polyglot4")) Unsupported_Argument_Types_Data Test.specify "should be able to be recovered selectively" <| - Panic.recover Illegal_Argument_Error (Panic.throw (Illegal_Argument_Error "msg" Nothing)) . catch . should_be_an Illegal_Argument_Error - Panic.recover Any (Panic.throw (Illegal_Argument_Error "msg" Nothing)) . catch . should_be_an Illegal_Argument_Error - Panic.recover [Illegal_Argument_Error] (Panic.throw (Illegal_Argument_Error "msg" Nothing)) . catch . should_be_an Illegal_Argument_Error - Panic.recover [Illegal_State_Error, Illegal_Argument_Error] (Panic.throw (Illegal_Argument_Error "msg" Nothing)) . catch . should_be_an Illegal_Argument_Error + Panic.recover Illegal_Argument_Error_Data (Panic.throw (Illegal_Argument_Error_Data "msg" Nothing)) . catch . should_be_an Illegal_Argument_Error_Data + Panic.recover Any (Panic.throw (Illegal_Argument_Error_Data "msg" Nothing)) . catch . should_be_an Illegal_Argument_Error_Data + Panic.recover [Illegal_Argument_Error_Data] (Panic.throw (Illegal_Argument_Error_Data "msg" Nothing)) . catch . should_be_an Illegal_Argument_Error_Data + Panic.recover [Illegal_State_Error_Data, Illegal_Argument_Error_Data] (Panic.throw (Illegal_Argument_Error_Data "msg" Nothing)) . catch . should_be_an Illegal_Argument_Error_Data - Test.expect_panic_with <| Panic.recover Illegal_State_Error (Panic.throw (Illegal_Argument_Error "msg" Nothing)) . catch - Test.expect_panic_with <| Panic.recover [Illegal_State_Error, Polyglot_Error] (Panic.throw (Illegal_Argument_Error "msg" Nothing)) . catch - Test.expect_panic_with <| Panic.recover [] (Panic.throw (Illegal_Argument_Error "msg" Nothing)) . catch + Test.expect_panic_with <| Panic.recover Illegal_State_Error_Data (Panic.throw (Illegal_Argument_Error_Data "msg" Nothing)) . catch + Test.expect_panic_with <| Panic.recover [Illegal_State_Error_Data, Polyglot_Error_Data] (Panic.throw (Illegal_Argument_Error_Data "msg" Nothing)) . catch + Test.expect_panic_with <| Panic.recover [] (Panic.throw (Illegal_Argument_Error_Data "msg" Nothing)) . catch - Panic.recover [Polyglot_Error] (do_a_parse "foo") . catch . should_be_a Polyglot_Error + Panic.recover [Polyglot_Error_Data] (do_a_parse "foo") . catch . should_be_a Polyglot_Error_Data Panic.recover Any throw_a_bar_panicking . catch . should_equal "bar" Panic.recover Text throw_a_bar_panicking . stack_trace . second . name . should_equal "Error_Spec.throw_a_bar_panicking" From 6d9b65edbb2dd6b7f64e9266a3bdc9dc7bea236f Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 15 Aug 2022 18:56:51 +0200 Subject: [PATCH 049/110] keep going --- .../Base/0.0.0-dev/src/Data/Maybe.enso | 7 +- .../0.0.0-dev/src/Data/Text/Encoding.enso | 14 ++-- .../0.0.0-dev/src/Data/Text/Extensions.enso | 4 +- .../Base/0.0.0-dev/src/Network/Http.enso | 5 +- .../0.0.0-dev/src/Network/Http/Response.enso | 6 +- .../Base/0.0.0-dev/src/System/File.enso | 4 +- .../System/File/Existing_File_Behavior.enso | 18 ++-- .../lib/Standard/Test/0.0.0-dev/src/Main.enso | 2 +- .../expression/builtin/bool/EqualsNode.java | 6 +- .../builtin/number/bigInteger/EqualsNode.java | 7 +- .../builtin/number/decimal/EqualsNode.java | 2 +- .../number/smallInteger/EqualsNode.java | 2 +- .../enso/interpreter/runtime/data/Type.java | 1 + .../scala/org/enso/compiler/Compiler.scala | 16 ++-- test/Tests/src/Data/Json_Spec.enso | 26 +++--- test/Tests/src/Data/Map_Spec.enso | 4 +- test/Tests/src/Data/Maybe_Spec.enso | 14 ++-- test/Tests/src/Data/Noise/Generator_Spec.enso | 2 +- test/Tests/src/Main.enso | 84 +++++++++---------- test/Tests/src/Network/Http/Request_Spec.enso | 2 +- test/Tests/src/Network/Http_Spec.enso | 4 +- test/Tests/src/Network/URI_Spec.enso | 2 +- test/Tests/src/Semantic/Js_Interop_Spec.enso | 2 +- test/Tests/src/Semantic/Meta_Spec.enso | 40 ++++----- .../src/Semantic/Python_Interop_Spec.enso | 2 +- test/Tests/src/Semantic/R_Interop_Spec.enso | 4 +- test/Tests/src/System/File_Spec.enso | 2 +- .../System/Reporting_Stream_Decoder_Spec.enso | 2 +- .../System/Reporting_Stream_Encoder_Spec.enso | 4 +- 29 files changed, 150 insertions(+), 138 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Maybe.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Maybe.enso index 3981569c32f4..0fea7568accf 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Maybe.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Maybe.enso @@ -48,4 +48,9 @@ type Maybe example_is_some = Maybe.Some "yes!" . is_some is_some : Boolean - is_some self = self.is_nothing.not + is_some self = case self of + None -> False + Some _ -> True + + is_none : Boolean + is_none self = self.is_some.not diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Encoding.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Encoding.enso index d873868e8f3e..7c59a50f4c22 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Encoding.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Encoding.enso @@ -67,33 +67,33 @@ type Encoding Encoding for Western European (Windows). windows_1252 : Encoding - windows_1252 = Encoding "windows-1252" + windows_1252 = Encoding_Data "windows-1252" ## Encoding for Greek (Windows). windows_1253 : Encoding - windows_1253 = Encoding "windows-1253" + windows_1253 = Encoding_Data "windows-1253" ## ALIAS ISO-8859-9 Encoding for Turkish (Windows). windows_1254 : Encoding - windows_1254 = Encoding "windows-1254" + windows_1254 = Encoding_Data "windows-1254" ## Encoding for Hebrew (Windows). windows_1255 : Encoding - windows_1255 = Encoding "windows-1255" + windows_1255 = Encoding_Data "windows-1255" ## Encoding for Arabic (Windows). windows_1256 : Encoding - windows_1256 = Encoding "windows-1256" + windows_1256 = Encoding_Data "windows-1256" ## Encoding for Baltic (Windows). windows_1257 : Encoding - windows_1257 = Encoding "windows-1257" + windows_1257 = Encoding_Data "windows-1257" ## Encoding for Vietnamese (Windows). windows_1258 : Encoding - windows_1258 = Encoding "windows-1258" + windows_1258 = Encoding_Data "windows-1258" ## One or more byte sequences were not decodable using the Encoding. type Encoding_Error 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 4627b862a51a..59e1ca0c9e09 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 @@ -741,7 +741,7 @@ Text.bytes self encoding on_problems=Report_Warning = result = Encoding_Utils.get_bytes self (encoding . to_java_charset) vector = Vector.Vector_Data result.result if result.warnings.is_nothing then vector else - on_problems.attach_problems_after vector [Encoding_Error result.warnings] + on_problems.attach_problems_after vector [Encoding_Error_Data result.warnings] ## Takes a vector of bytes and returns Text resulting from decoding it using the specified encoding. @@ -763,7 +763,7 @@ Text.from_bytes : Vector.Vector Byte -> Encoding -> Text Text.from_bytes bytes encoding on_problems=Report_Warning = result = Encoding_Utils.from_bytes bytes.to_array (encoding . to_java_charset) if result.warnings.is_nothing then result.result else - on_problems.attach_problems_after result.result [Encoding_Error result.warnings] + on_problems.attach_problems_after result.result [Encoding_Error_Data result.warnings] ## Returns a vector containing bytes representing the UTF-8 encoding of the input text. diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http.enso index ab6cb805174f..e8d95008686a 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http.enso @@ -597,7 +597,7 @@ type Http request : Request -> Response ! Request_Error request self req = handle_request_error = - Panic.catch_java Any handler=(err-> Error.throw (Request_Error 'IllegalArgumentException' err.getMessage)) + Panic.catch_java Any handler=(err-> Error.throw (Request_Error_Data 'IllegalArgumentException' err.getMessage)) Panic.recover Any <| handle_request_error <| body_publishers = HttpRequest.BodyPublishers builder = HttpRequest.newBuilder @@ -694,7 +694,8 @@ type Http Arguments: - error_type: The type of the error. - message: The message for the error. -type Request_Error error_type message +type Request_Error + Request_Error_Data error_type message ## UNSTABLE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Response.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Response.enso index 797df6cf30d7..ee9d4964f997 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Response.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/Http/Response.enso @@ -29,7 +29,7 @@ type Response example_headers = Examples.get_response.headers headers : Vector.Vector headers self = - header_entries = Vector.Vector (Http_Utils.get_headers self.internal_http_response.headers) + header_entries = Vector.Vector_Data (Http_Utils.get_headers self.internal_http_response.headers) header_entries.map e-> Header.new e.getKey e.getValue ## Get the response body. @@ -42,7 +42,7 @@ type Response example_body = Examples.get_response.body body : Response_Body - body self = Response_Body.Body (Vector.Vector self.internal_http_response.body) + body self = Response_Body.Body_Data (Vector.Vector_Data self.internal_http_response.body) ## Get the response status code. @@ -54,7 +54,7 @@ type Response example_code = Examples.get_response.code code : Status_Code - code self = Status_Code.Status_Code self.internal_http_response.statusCode + code self = Status_Code.Status_Code_Data self.internal_http_response.statusCode ## Convert the response to JSON. 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 95d96018e38a..9c01e15fc420 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 @@ -44,7 +44,7 @@ new path = case path of Text -> get_file path File -> path - _ -> Error.throw (Illegal_Argument_Error "new file should be either a File or a Text") + _ -> Error.throw (Illegal_Argument_Error_Data "new file should be either a File or a Text") ## Open and reads all bytes in the file at the provided `path` into a byte vector. @@ -1114,7 +1114,7 @@ Text.write self path encoding=Encoding.utf_8 on_existing_file=Existing_File_Beha [36, -62, -93, -62, -89, -30, -126, -84, -62, -94].write_bytes Examples.scratch_file.write_bytes Examples.scratch_file Existing_File_Behavior.Append Vector.Vector.write_bytes : (File|Text) -> Existing_File_Behavior -> Nothing ! Illegal_Argument_Error | File_Not_Found | IO_Error | File_Already_Exists_Error Vector.Vector.write_bytes self path on_existing_file=Existing_File_Behavior.Backup = - Panic.catch Unsupported_Argument_Types_Data handler=(Error.throw (Illegal_Argument_Error "Only Vectors consisting of bytes (integers in the range from -128 to 127) are supported by the `write_bytes` method.")) <| + Panic.catch Unsupported_Argument_Types_Data handler=(Error.throw (Illegal_Argument_Error_Data "Only Vectors consisting of bytes (integers in the range from -128 to 127) are supported by the `write_bytes` method.")) <| ## Convert to a byte array before writing - and fail early if there is any problem. byte_array = Array_Utils.ensureByteArray self.to_array diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/Existing_File_Behavior.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/Existing_File_Behavior.enso index 14a8a5d891cb..b579a86dabb2 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/Existing_File_Behavior.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/System/File/Existing_File_Behavior.enso @@ -50,7 +50,7 @@ type Existing_File_Behavior handle_write_failure_dataflow caught_panic = Common.Error.throw caught_panic.payload.cause handle_file_already_exists = Panic.catch File_Already_Exists_Error handler=handle_existing_file - handle_internal_dataflow = Panic.catch Internal_Write_Operation_Errored handler=handle_write_failure_dataflow + handle_internal_dataflow = Panic.catch Internal_Write_Operation_Errored_Data handler=handle_write_failure_dataflow ## We first attempt to write the file to the original destination, but if that files due to the file already existing, we will run the alternative algorithm which uses a @@ -58,7 +58,7 @@ type Existing_File_Behavior handle_file_already_exists <| handle_internal_dataflow <| Panic.rethrow <| file.with_output_stream [Option.Write, Option.Create_New] output_stream-> action output_stream . catch Any dataflow_error-> - Panic.throw (Internal_Write_Operation_Errored dataflow_error) + Panic.throw (Internal_Write_Operation_Errored_Data dataflow_error) ## PRIVATE write_file_backing_up_old_one : File -> (Output_Stream -> Nothing) -> Nothing ! File_Not_Found | IO_Error | File_Already_Exists_Error @@ -80,15 +80,15 @@ write_file_backing_up_old_one file action = Panic.recover [IO_Error, File_Not_Fo new_file.delete Common.Error.throw caught_panic.payload.cause handle_file_already_exists = Panic.catch File_Already_Exists_Error handler=handle_existing_file - handle_internal_dataflow = Panic.catch Internal_Write_Operation_Errored handler=handle_write_failure_dataflow - handle_internal_panic = Panic.catch Internal_Write_Operation_Panicked handler=handle_write_failure_panic + handle_internal_dataflow = Panic.catch Internal_Write_Operation_Errored_Data handler=handle_write_failure_dataflow + handle_internal_panic = Panic.catch Internal_Write_Operation_Panicked_Data handler=handle_write_failure_panic handle_file_already_exists <| handle_internal_dataflow <| handle_internal_panic <| Panic.rethrow <| new_file.with_output_stream [Option.Write, Option.Create_New] output_stream-> result = Panic.catch Any (action output_stream) caught_panic-> - Panic.throw (Internal_Write_Operation_Panicked caught_panic) + Panic.throw (Internal_Write_Operation_Panicked_Data caught_panic) result.catch Any dataflow_error-> - Panic.throw (Internal_Write_Operation_Errored dataflow_error) + Panic.throw (Internal_Write_Operation_Errored_Data dataflow_error) ## We ignore the file not found error, because it means that there is no file to back-up. This may also be caused by someone removing the original file during the time when we have been @@ -102,7 +102,9 @@ write_file_backing_up_old_one file action = Panic.recover [IO_Error, File_Not_Fo ## PRIVATE -type Internal_Write_Operation_Panicked (cause : Caught_Panic) +type Internal_Write_Operation_Panicked + Internal_Write_Operation_Panicked_Data (cause : Caught_Panic) ## PRIVATE -type Internal_Write_Operation_Errored (cause : Any) +type Internal_Write_Operation_Errored + Internal_Write_Operation_Errored_Data (cause : Any) 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 ba8a66f6bb08..fbc59c4e3d2e 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 @@ -235,7 +235,7 @@ Any.should_fail_with self matcher frames_to_skip=0 = Error.should_fail_with : Any -> Integer -> Assertion Error.should_fail_with self matcher frames_to_skip=0 = caught = self.catch - if caught.is_a matcher then Nothing else + if (caught == matcher) || caught.is_a matcher then Nothing else loc = Meta.get_source_location 2+frames_to_skip fail ("Expected error "+matcher.to_text+", but error " + caught.to_text + " has been returned (at " + loc + ").") diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java index 03529b2c59e5..e6226b3ca528 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/bool/EqualsNode.java @@ -11,7 +11,7 @@ @BuiltinMethod(type = "Boolean", name = "==", description = "Computes the equality of two booleans") public abstract class EqualsNode extends Node { - abstract boolean execute(boolean self, Object that); + abstract boolean execute(Object self, Object that); static EqualsNode build() { return EqualsNodeGen.create(); @@ -23,7 +23,7 @@ boolean doBoolean(boolean self, boolean that) { } @Fallback - boolean doOther(boolean self, Object that) { - return false; + boolean doOther(Object self, Object that) { + return self == that; } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/EqualsNode.java index bcf5ce4639cc..9f7a39cd5a62 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/bigInteger/EqualsNode.java @@ -14,7 +14,7 @@ @BuiltinMethod(type = "Big_Integer", name = "==", description = "Big integer equality.") public abstract class EqualsNode extends Node { - abstract boolean execute(EnsoBigInteger self, Object that); + abstract boolean execute(Object self, Object that); static EqualsNode build() { return EqualsNodeGen.create(); @@ -31,8 +31,7 @@ boolean doDouble(EnsoBigInteger self, double that) { } @Fallback - boolean doOther(EnsoBigInteger self, Object that) { - return false; + boolean doOther(Object self, Object that) { + return self == that; } - } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/EqualsNode.java index b9431931ef7b..bd8129042b49 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/decimal/EqualsNode.java @@ -37,6 +37,6 @@ boolean doBigInteger(double self, EnsoBigInteger that) { @Fallback boolean doOther(Object self, Object that) { - return false; + return self == that; } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/EqualsNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/EqualsNode.java index 9e73c568491b..d1fa123f6be3 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/EqualsNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/smallInteger/EqualsNode.java @@ -30,6 +30,6 @@ boolean doDouble(long self, double that) { @Fallback boolean doOther(Object self, Object that) { - return false; + return self == that; } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index 10741bd7343b..470474d8967a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -75,6 +75,7 @@ public void setShadowDefinitions(ModuleScope scope) { methods.forEach((name, fun) -> scope.registerMethod(this, name, fun)); } this.definitionScope = scope; + generateQualifiedAccessor(); } 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/scala/org/enso/compiler/Compiler.scala b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala index fa7893222f87..01c3f2d84cb6 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala @@ -826,14 +826,14 @@ class Compiler( source: Source ): Boolean = { val errors = diagnostics.collect { case e: IR.Error => e } - val warnings = diagnostics.collect { case w: IR.Warning => w } - - if (warnings.nonEmpty) { - context.getOut.println("Compiler encountered warnings:") - warnings.foreach { warning => - context.getOut.println(formatDiagnostic(warning, source)) - } - } +// val warnings = diagnostics.collect { case w: IR.Warning => w } +// +// if (warnings.nonEmpty) { +// context.getOut.println("Compiler encountered warnings:") +// warnings.foreach { warning => +// context.getOut.println(formatDiagnostic(warning, source)) +// } +// } if (errors.nonEmpty) { context.getOut.println("Compiler encountered errors:") diff --git a/test/Tests/src/Data/Json_Spec.enso b/test/Tests/src/Data/Json_Spec.enso index 7fd14cab30eb..4bdf5ac50d8c 100644 --- a/test/Tests/src/Data/Json_Spec.enso +++ b/test/Tests/src/Data/Json_Spec.enso @@ -2,9 +2,11 @@ from Standard.Base import all import Standard.Test -type Author name year_of_birth +type Author + Author_Data name year_of_birth -type Book title author +type Book + Book_Data title author Text.should_fail_parsing_with self expected = as_fail = case Json.parse self of @@ -69,17 +71,17 @@ spec = "123 4".should_fail_parsing_with "Expected end of input" Test.specify "should parse and convert JSON into domain model" <| - book_1 = Book "Lord of the Rings" <| - Author "J. R. R. Tolkien" 1892 - book_2 = Book "The Little Prince" <| - Author "Antoine de Saint-Exupéry" 1900 - book_3 = Book "And Then There Were None" <| - Author "Agatha Christie" 1890 + book_1 = Book_Data "Lord of the Rings" <| + Author_Data "J. R. R. Tolkien" 1892 + book_2 = Book_Data "The Little Prince" <| + Author_Data "Antoine de Saint-Exupéry" 1900 + book_3 = Book_Data "And Then There Were None" <| + Author_Data "Agatha Christie" 1890 books = [book_1, book_2, book_3] json_string = (enso_project.data / "books.json").read_text parsed = Json.parse json_string - domain = parsed.into (Vector.Vector (Book title=Text (Author name=Text year_of_birth=Number))) + domain = parsed.into (Vector.Vector_Data (Book_Data title=Text (Author_Data name=Text year_of_birth=Number))) domain.should_equal books Test.group "JSON Serialization" <| @@ -105,10 +107,10 @@ spec = 1.54.to_json.should_equal (Json.Number 1.54) ["foo", "bar", "baz"].to_json.should_equal <| (Json.Array [Json.String "foo", Json.String "bar", Json.String "baz"]) - Author "Tolkien" 1892 . to_json . should_equal <| + Author_Data "Tolkien" 1892 . to_json . should_equal <| n = Json.String "Tolkien" y = Json.Number 1892 - t = Json.String "Author" + t = Json.String "Author_Data" fields = Map.empty . insert "type" t . insert "name" n . insert "year_of_birth" y Json.Object fields @@ -121,6 +123,6 @@ spec = "y": {"z": null, "w": null} } object.get "foo" . should_equal (Json.String "bar") - object.get "bar" . should_fail_with Json.No_Such_Field_Error + object.get "bar" . should_fail_with Json.No_Such_Field_Error_Data main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Map_Spec.enso b/test/Tests/src/Data/Map_Spec.enso index f3dafe991643..002562601c97 100644 --- a/test/Tests/src/Data/Map_Spec.enso +++ b/test/Tests/src/Data/Map_Spec.enso @@ -1,6 +1,6 @@ from Standard.Base import all -from Standard.Base.Data.Map import No_Value_For_Key_Error +from Standard.Base.Data.Map import No_Value_For_Key_Error_Data import Standard.Test @@ -45,7 +45,7 @@ spec = Test.group "Maps" <| m.get "foo" . should_equal 134 m.get "bar" . should_equal 654 m.get "baz" . should_equal "spam" - (m.get "nope").should_fail_with No_Value_For_Key_Error + (m.get "nope").should_fail_with No_Value_For_Key_Error_Data Test.specify "should support get_or_else" <| m = Map.empty . insert 2 3 m.get_or_else 2 0 . should_equal 3 diff --git a/test/Tests/src/Data/Maybe_Spec.enso b/test/Tests/src/Data/Maybe_Spec.enso index fa562bf5ffb0..af74e127e80a 100644 --- a/test/Tests/src/Data/Maybe_Spec.enso +++ b/test/Tests/src/Data/Maybe_Spec.enso @@ -3,17 +3,17 @@ from Standard.Base import all import Standard.Test spec = Test.group "Maybe" <| - Test.specify "should have a Nothing variant" <| - Nothing . should_equal Nothing + Test.specify "should have a None variant" <| + Maybe.None . should_equal Maybe.None Test.specify "should have a Some variant" <| (Maybe.Some 2).value . should_equal 2 Test.specify "should provide the `maybe` function" <| - Nothing.maybe 2 x->x . should_equal 2 + Maybe.None.maybe 2 x->x . should_equal 2 (Maybe.Some 7).maybe 2 (*2) . should_equal 14 Test.specify "should provide `is_some`" <| - Nothing.is_some . should_be_false + Maybe.None.is_some . should_be_false Maybe.Some 2 . is_some . should_be_true - Test.specify "should provide `is_nothing`" <| - Nothing.is_nothing . should_be_true - Maybe.Some 2 . is_nothing . should_be_false + Test.specify "should provide `is_none`" <| + Maybe.None.is_none . should_be_true + Maybe.Some 2 . is_none . should_be_false diff --git a/test/Tests/src/Data/Noise/Generator_Spec.enso b/test/Tests/src/Data/Noise/Generator_Spec.enso index db0b9829417b..0d239d3cdc69 100644 --- a/test/Tests/src/Data/Noise/Generator_Spec.enso +++ b/test/Tests/src/Data/Noise/Generator_Spec.enso @@ -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) Common.Unimplemented_Error + Test.expect_panic_with (gen.step 1 interval) Common.Unimplemented_Error_Data 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/Main.enso b/test/Tests/src/Main.enso index 4f85b98584f9..cc14de5395dc 100644 --- a/test/Tests/src/Main.enso +++ b/test/Tests/src/Main.enso @@ -7,28 +7,28 @@ import project.Semantic.Case_Spec import project.Semantic.Conversion_Spec import project.Semantic.Deep_Export.Spec as Deep_Export_Spec import project.Semantic.Error_Spec -#import project.Semantic.Import_Loop.Spec as Import_Loop_Spec -#import project.Semantic.Meta_Spec +import project.Semantic.Import_Loop.Spec as Import_Loop_Spec +import project.Semantic.Meta_Spec #import project.Semantic.Names_Spec #import project.Semantic.Runtime_Spec #import project.Semantic.Warnings_Spec -#import project.Semantic.Java_Interop_Spec -#import project.Semantic.Js_Interop_Spec -#import project.Semantic.Python_Interop_Spec -#import project.Semantic.R_Interop_Spec +import project.Semantic.Java_Interop_Spec +import project.Semantic.Js_Interop_Spec +import project.Semantic.Python_Interop_Spec +import project.Semantic.R_Interop_Spec import project.Data.Array_Spec import project.Data.Bool_Spec import project.Data.Function_Spec import project.Data.Interval_Spec -#import project.Data.Json_Spec -#import project.Data.List_Spec -#import project.Data.Locale_Spec -#import project.Data.Map_Spec -#import project.Data.Maybe_Spec -#import project.Data.Noise.Generator_Spec as Noise_Generator_Spec -#import project.Data.Noise_Spec +import project.Data.Json_Spec +import project.Data.List_Spec +import project.Data.Locale_Spec +import project.Data.Map_Spec +import project.Data.Maybe_Spec +import project.Data.Noise.Generator_Spec as Noise_Generator_Spec +import project.Data.Noise_Spec #import project.Data.Numbers_Spec #import project.Data.Ordering_Spec #import project.Data.Ordering.Comparator_Spec @@ -50,21 +50,21 @@ import project.Data.Interval_Spec #import project.Data.Text.Span_Spec #import project.Data.Text.Utils_Spec -#import project.Network.Http.Header_Spec as Http_Header_Spec -#import project.Network.Http.Request_Spec as Http_Request_Spec -#import project.Network.Http_Spec -#import project.Network.URI_Spec +import project.Network.Http.Header_Spec as Http_Header_Spec +import project.Network.Http.Request_Spec as Http_Request_Spec +import project.Network.Http_Spec +import project.Network.URI_Spec #import project.Resource.Bracket_Spec #import project.Runtime.Stack_Traces_Spec #import project.Runtime.Lazy_Generator_Spec -#import project.System.Environment_Spec -#import project.System.File_Spec +import project.System.Environment_Spec +import project.System.File_Spec #import project.System.Process_Spec -#import project.System.Reporting_Stream_Decoder_Spec -#import project.System.Reporting_Stream_Encoder_Spec +import project.System.Reporting_Stream_Decoder_Spec +import project.System.Reporting_Stream_Encoder_Spec #import project.System.System_Spec #import project.Random_Spec @@ -78,34 +78,34 @@ main = Test.Suite.run_main <| Conversion_Spec.spec Deep_Export_Spec.spec Error_Spec.spec - #Environment_Spec.spec - #File_Spec.spec - #Reporting_Stream_Decoder_Spec.spec - #Reporting_Stream_Encoder_Spec.spec - #Http_Header_Spec.spec - #Http_Request_Spec.spec - #Http_Spec.spec - #Import_Loop_Spec.spec + Environment_Spec.spec + File_Spec.spec + Reporting_Stream_Decoder_Spec.spec + Reporting_Stream_Encoder_Spec.spec + Http_Header_Spec.spec + Http_Request_Spec.spec + Http_Spec.spec + Import_Loop_Spec.spec Interval_Spec.spec - #Java_Interop_Spec.spec - #Js_Interop_Spec.spec - #Json_Spec.spec - #List_Spec.spec - #Locale_Spec.spec - #Map_Spec.spec - #Maybe_Spec.spec - #Meta_Spec.spec + Java_Interop_Spec.spec + Js_Interop_Spec.spec + Json_Spec.spec + List_Spec.spec + Locale_Spec.spec + Map_Spec.spec + Maybe_Spec.spec + Meta_Spec.spec #Names_Spec.spec - #Noise_Generator_Spec.spec - #Noise_Spec.spec + Noise_Generator_Spec.spec + Noise_Spec.spec #Numbers_Spec.spec #Ordering_Spec.spec #Comparator_Spec.spec #Natural_Order_Spec.spec #Vector_Lexicographic_Order_Spec.spec #Process_Spec.spec - #Python_Interop_Spec.spec - #R_Interop_Spec.spec + Python_Interop_Spec.spec + R_Interop_Spec.spec #Range_Spec.spec #Ref_Spec.spec #Default_Regex_Engine_Spec.spec @@ -121,7 +121,7 @@ main = Test.Suite.run_main <| #Utils_Spec.spec #Text_Spec.spec #Time_Spec.spec - #URI_Spec.spec + URI_Spec.spec #Vector_Spec.spec #Statistics_Spec.spec #Regression_Spec.spec diff --git a/test/Tests/src/Network/Http/Request_Spec.enso b/test/Tests/src/Network/Http/Request_Spec.enso index 46ed8577d63c..1777482c5152 100644 --- a/test/Tests/src/Network/Http/Request_Spec.enso +++ b/test/Tests/src/Network/Http/Request_Spec.enso @@ -14,7 +14,7 @@ spec = test_headers = [Header.application_json, Header.new "X-Foo-Id" "0123456789"] Test.group "Request" <| Test.specify "should return error when creating request from invalid URI" <| - Request.new Method.Post "invalid uri" . should_fail_with Syntax_Error + Request.new Method.Post "invalid uri" . should_fail_with Syntax_Error_Data Test.specify "should get method" <| req = Request.new Method.Post test_uri req.method.should_equal Method.Post diff --git a/test/Tests/src/Network/Http_Spec.enso b/test/Tests/src/Network/Http_Spec.enso index f790eea8ceda..db77f749ba2d 100644 --- a/test/Tests/src/Network/Http_Spec.enso +++ b/test/Tests/src/Network/Http_Spec.enso @@ -44,7 +44,7 @@ spec = http = Http.new (version = version_setting) http.version.should_equal version_setting Test.specify "should throw error when requesting invalid URI" <| - Http.new.get "not a uri" . should_fail_with Syntax_Error + Http.new.get "not a uri" . should_fail_with Syntax_Error_Data Test.specify "should send Get request" <| expected_response = Json.parse <| ''' @@ -89,7 +89,7 @@ spec = res = Http.fetch url_get res.to_json.should_equal expected_response Test.specify "should return error if the fetch method fails" <| - Http.fetch "http://undefined_host" . should_fail_with Http.Request_Error + Http.fetch "http://undefined_host" . should_fail_with Http.Request_Error_Data Test.specify "should send Head request" <| res = Http.new.head url_get diff --git a/test/Tests/src/Network/URI_Spec.enso b/test/Tests/src/Network/URI_Spec.enso index db471553a9cf..e91f71d291fb 100644 --- a/test/Tests/src/Network/URI_Spec.enso +++ b/test/Tests/src/Network/URI_Spec.enso @@ -29,4 +29,4 @@ spec = addr.raw_query.should_equal "%D0%9A%D0%BE%D0%B4" addr.raw_fragment.should_fail_with Nothing Test.specify "should return Syntax_Error when parsing invalid URI" <| - URI.parse "a b c" . should_fail_with Syntax_Error + URI.parse "a b c" . should_fail_with Syntax_Error_Data diff --git a/test/Tests/src/Semantic/Js_Interop_Spec.enso b/test/Tests/src/Semantic/Js_Interop_Spec.enso index d6275c19fabc..5f18c3d1b0eb 100644 --- a/test/Tests/src/Semantic/Js_Interop_Spec.enso +++ b/test/Tests/src/Semantic/Js_Interop_Spec.enso @@ -90,7 +90,7 @@ spec = Test.group "Polyglot JS" <| obj.compare 11 . should_be_true Test.specify "should expose array interfaces for JS arrays" <| - vec = Vector.Vector make_array + vec = Vector.Vector_Data make_array vec.map .x . should_equal [10, 20, 30] Test.specify "should correctly marshall strings" <| diff --git a/test/Tests/src/Semantic/Meta_Spec.enso b/test/Tests/src/Semantic/Meta_Spec.enso index 9c0cb5e92061..a9ff8e901418 100644 --- a/test/Tests/src/Semantic/Meta_Spec.enso +++ b/test/Tests/src/Semantic/Meta_Spec.enso @@ -8,11 +8,13 @@ polyglot java import java.util.Locale as JavaLocale import Standard.Test -type My_Type foo bar baz +type My_Type + My_Type_Data foo bar baz My_Type.my_method self = self.foo + self.bar + self.baz -type Test_Type x +type Test_Type + Test_Type_Data x spec = Test.group "Meta-Value Manipulation" <| Test.specify "should allow manipulating unresolved symbols" <| @@ -20,26 +22,26 @@ spec = Test.group "Meta-Value Manipulation" <| meta_sym = Meta.meta sym meta_sym.name.should_equal "does_not_exist" new_sym = meta_sym . rename "my_method" - object = My_Type 1 2 3 + object = My_Type_Data 1 2 3 new_sym object . should_equal 6 Test.specify "should allow manipulating atoms" <| - atom = My_Type 1 "foo" Nothing + atom = My_Type_Data 1 "foo" Nothing meta_atom = Meta.meta atom - meta_atom.constructor.should_equal My_Type + meta_atom.constructor.should_equal My_Type_Data meta_atom.fields.should_equal [1, "foo", Nothing] Meta.meta (meta_atom.constructor) . new [1, "foo", Nothing] . should_equal atom Test.specify "should correctly return representations of different classes of objects" <| - Meta.meta 1 . should_equal (Meta.Primitive 1) - Meta.meta "foo" . should_equal (Meta.Primitive "foo") + Meta.meta 1 . should_equal (Meta.Primitive_Data 1) + Meta.meta "foo" . should_equal (Meta.Primitive_Data "foo") Test.specify "should allow manipulation of error values" <| err = Error.throw "My Error" meta_err = Meta.meta err - meta_err.is_a Meta.Error . should_be_true + meta_err.is_a Meta.Error_Data . should_be_true meta_err.value . should_equal "My Error" Test.specify "should allow checking if a value is of a certain type" <| 1.is_an Any . should_be_true 1.2.is_an Any . should_be_true - (My_Type 1 "foo" Nothing).is_an Any . should_be_true + (My_Type_Data 1 "foo" Nothing).is_an Any . should_be_true Array.is_an Array . should_be_true [].to_array.is_an Array . should_be_true @@ -67,9 +69,9 @@ spec = Test.group "Meta-Value Manipulation" <| Meta.is_a random_gen Polyglot . should_be_true Meta.is_an random_gen Integer . should_be_false - (My_Type 1 "foo" Nothing).is_a My_Type . should_be_true - (My_Type 1 "foo" Nothing).is_a Test_Type . should_be_false - (My_Type 1 "foo" Nothing).is_a Number . should_be_false + (My_Type_Data 1 "foo" Nothing).is_a My_Type_Data . should_be_true + (My_Type_Data 1 "foo" Nothing).is_a Test_Type_Data . should_be_false + (My_Type_Data 1 "foo" Nothing).is_a Number . should_be_false err = Error.throw "Error Value" 1.is_an Error . should_be_false @@ -83,14 +85,14 @@ spec = Test.group "Meta-Value Manipulation" <| _ -> Nothing Test.specify "should allow to get the source location of a frame" pending=location_pending <| src = Meta.get_source_location 0 - loc = "Meta_Spec.enso:85:15-40" + loc = "Meta_Spec.enso:87:15-40" src.take (Last loc.length) . should_equal loc Test.specify "should allow to get qualified type names of values" <| x = 42 - y = My_Type 1 2 3 + y = My_Type_Data 1 2 3 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" + Meta.get_qualified_type_name y . should_equal "enso_dev.Tests.Semantic.Meta_Spec.My_Type_Data" Test.specify "should allow access to package names" <| enso_project.name.should_equal 'Tests' @@ -98,7 +100,7 @@ spec = Test.group "Meta-Value Manipulation" <| Test.specify "should correctly handle Java values" <| java_meta = Meta.meta Random.new - java_meta . should_be_a Meta.Polyglot + java_meta . should_be_a Meta.Polyglot_Data java_meta . get_language . should_equal Meta.Java Test.specify "should correctly handle equality of Java values" <| @@ -110,8 +112,8 @@ spec = Test.group "Meta-Value Manipulation" <| a==b . should_be_true a==c . should_be_false - (Test_Type a)==(Test_Type a) . should_be_true - (Test_Type a)==(Test_Type b) . should_be_true - (Test_Type a)==(Test_Type c) . should_be_false + (Test_Type_Data a)==(Test_Type_Data a) . should_be_true + (Test_Type_Data a)==(Test_Type_Data b) . should_be_true + (Test_Type_Data a)==(Test_Type_Data c) . should_be_false main = Test.Suite.run_main spec diff --git a/test/Tests/src/Semantic/Python_Interop_Spec.enso b/test/Tests/src/Semantic/Python_Interop_Spec.enso index bd42d92fbb42..ab6705bcea22 100644 --- a/test/Tests/src/Semantic/Python_Interop_Spec.enso +++ b/test/Tests/src/Semantic/Python_Interop_Spec.enso @@ -85,7 +85,7 @@ spec = obj.compare 11 . should_be_true Test.specify "should expose array interfaces for Python arrays" <| - vec = Vector.Vector make_array + vec = Vector.Vector_Data make_array vec.map .x . should_equal [10, 20, 30] Test.specify "should correctly marshall strings" <| diff --git a/test/Tests/src/Semantic/R_Interop_Spec.enso b/test/Tests/src/Semantic/R_Interop_Spec.enso index c8c5c9a2b981..fd2091cce2b6 100644 --- a/test/Tests/src/Semantic/R_Interop_Spec.enso +++ b/test/Tests/src/Semantic/R_Interop_Spec.enso @@ -58,7 +58,7 @@ spec = my_method 1 2 . should_equal 3 Test.specify "should allow mutual calling of instance-level methods" <| - My_Type 3 4 . my_method_3 5 . should_equal 36 + My_Type_Data 3 4 . my_method_3 5 . should_equal 36 Test.specify "should expose methods and fields of R objects" <| obj = make_object @@ -68,7 +68,7 @@ spec = obj.compare 11 . should_be_true Test.specify "should expose array interfaces for R arrays" <| - vec = Vector.Vector make_array + vec = Vector.Vector_Data make_array vec.map .x . should_equal [10, 20, 30] Test.specify "should correctly marshall strings" <| diff --git a/test/Tests/src/System/File_Spec.enso b/test/Tests/src/System/File_Spec.enso index 11d6d80a5c19..65ea9ee98763 100644 --- a/test/Tests/src/System/File_Spec.enso +++ b/test/Tests/src/System/File_Spec.enso @@ -133,7 +133,7 @@ spec = Test.specify "should raise warnings when reading invalid characters" <| action = windows_file.read_text Encoding.ascii on_problems=_ tester result = result.should_equal 'Hello World! $\uFFFD\uFFFD\uFFFD' - problems = [Encoding_Error "Encoding issues at 14, 15, 16."] + problems = [Encoding_Error_Data "Encoding issues at 14, 15, 16."] Problems.test_problem_handling action problems tester Test.specify "should handle exceptions when reading a non-existent file" <| diff --git a/test/Tests/src/System/Reporting_Stream_Decoder_Spec.enso b/test/Tests/src/System/Reporting_Stream_Decoder_Spec.enso index 7f010555d3dd..3d3183d51721 100644 --- a/test/Tests/src/System/Reporting_Stream_Decoder_Spec.enso +++ b/test/Tests/src/System/Reporting_Stream_Decoder_Spec.enso @@ -89,7 +89,7 @@ spec = Test.specify "should raise warnings when reading invalid characters" <| encoding = Encoding.ascii expected_contents = 'Hello World! $\uFFFD\uFFFD\uFFFD' - expected_problems = [Encoding_Error "Encoding issues at bytes 14, 15, 16."] + expected_problems = [Encoding_Error_Data "Encoding issues at bytes 14, 15, 16."] contents_1 = read_file_one_by_one windows_file encoding expected_contents.length on_problems=Problem_Behavior.Report_Warning contents_1.should_equal expected_contents Warning.get_all contents_1 . map .value . should_equal expected_problems diff --git a/test/Tests/src/System/Reporting_Stream_Encoder_Spec.enso b/test/Tests/src/System/Reporting_Stream_Encoder_Spec.enso index 182981efb5df..76059211a7e0 100644 --- a/test/Tests/src/System/Reporting_Stream_Encoder_Spec.enso +++ b/test/Tests/src/System/Reporting_Stream_Encoder_Spec.enso @@ -60,7 +60,7 @@ spec = stream.with_stream_encoder encoding Problem_Behavior.Report_Warning reporting_stream_encoder-> reporting_stream_encoder.write contents result.should_succeed - Warning.get_all result . map .value . should_equal [Encoding_Error "Encoding issues at codepoints 1, 3."] + Warning.get_all result . map .value . should_equal [Encoding_Error_Data "Encoding issues at codepoints 1, 3."] f.read_text encoding . should_equal "S?o?wka!" f.delete_if_exists @@ -73,7 +73,7 @@ spec = reporting_stream_encoder.write "bar" result_2.should_succeed - Warning.get_all result_2 . map .value . should_equal [Encoding_Error "Encoding issues at codepoints 3, 9."] + Warning.get_all result_2 . map .value . should_equal [Encoding_Error_Data "Encoding issues at codepoints 3, 9."] f.read_text encoding . should_equal "ABC?foo -?- bar" Test.specify "should work correctly if no data is written to it" <| From 72da137e07890a49d9b45a6b468dcdf35f69cb20 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 16 Aug 2022 14:01:02 +0200 Subject: [PATCH 050/110] keep going --- .../Base/0.0.0-dev/src/Data/Numbers.enso | 4 +- .../Base/0.0.0-dev/src/Data/Range.enso | 12 ++--- .../src/Data/Text/Text_Ordering.enso | 3 +- .../Base/0.0.0-dev/src/Data/Time/Date.enso | 2 +- .../Base/0.0.0-dev/src/Data/Vector.enso | 2 +- .../Base/0.0.0-dev/src/Error/Common.enso | 7 +++ .../lib/Standard/Test/0.0.0-dev/src/Main.enso | 34 ++++++------ .../node/expression/builtin/Error.java | 7 ++- .../runtime/callable/atom/Atom.java | 5 -- .../enso/interpreter/runtime/data/Type.java | 6 +++ .../enso/interpreter/runtime/type/Types.java | 10 ++-- test/Tests/src/Data/Numbers_Spec.enso | 42 +++++++-------- .../src/Data/Ordering/Comparator_Spec.enso | 14 ++--- .../src/Data/Ordering/Natural_Order_Spec.enso | 2 +- .../Vector_Lexicographic_Order_Spec.enso | 7 +-- test/Tests/src/Data/Ordering_Spec.enso | 15 +++--- test/Tests/src/Data/Statistics_Spec.enso | 16 +++--- test/Tests/src/Data/Vector_Spec.enso | 53 ++++++++++--------- test/Tests/src/Main.enso | 48 ++++++++--------- 19 files changed, 159 insertions(+), 130 deletions(-) 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 index 996e0a200d97..b2860904e38d 100644 --- 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 @@ -597,7 +597,7 @@ type Decimal parse : Text -> Decimal ! Parse_Error parse text = Panic.catch NumberFormatException (Double.parseDouble text) _-> - Error.throw (Parse_Error text) + Error.throw (Parse_Error_Data text) ## Integer is the type of integral numbers in Enso. They are of unbounded size and can grow as large as necessary. @@ -975,7 +975,7 @@ type Integer parse : Text -> Text -> Integer ! Parse_Error parse text (radix=10) = Panic.catch NumberFormatException (Long.parseLong text radix) _-> - Error.throw (Parse_Error text) + Error.throw (Parse_Error_Data text) ## UNSTABLE diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Range.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Range.enso index 4f318e1be85d..6d56dfd130ee 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Range.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Range.enso @@ -28,10 +28,10 @@ type Range with_step self new_step = case new_step of Integer -> if new_step == 0 then throw_zero_step_error else - if new_step < 0 then Error.throw (Illegal_Argument_Error "The step should be positive. A decreasing sequence will remain decreasing after updating it with positive step, as this operation only sets the magnitude without changing the sign.") else + if new_step < 0 then Error.throw (Illegal_Argument_Error_Data "The step should be positive. A decreasing sequence will remain decreasing after updating it with positive step, as this operation only sets the magnitude without changing the sign.") else Range_Data self.start self.end self.step.signum*new_step _ -> - Error.throw (Illegal_Argument_Error "Range step should be an integer.") + Error.throw (Illegal_Argument_Error_Data "Range step should be an integer.") ## Returns the last element that is included within the range or `Nothing` if the range is empty. @@ -246,7 +246,7 @@ type Range `Range 0 10 . contains 3.0 == False` and get a type error for decimals instead. _ -> - Error.throw (Illegal_Argument_Error "`Range.contains` only accepts Integers.") + Error.throw (Illegal_Argument_Error_Data "`Range.contains` only accepts Integers.") ## ALIAS Range @@ -262,7 +262,7 @@ type Range Integer.up_to : Integer -> Range Integer.up_to self n = case n of Integer -> Range_Data self n - _ -> Error.throw (Illegal_Argument_Error "Expected range end to be an Integer.") + _ -> Error.throw (Illegal_Argument_Error_Data "Expected range end to be an Integer.") ## ALIAS Range @@ -278,7 +278,7 @@ Integer.up_to self n = case n of Integer.down_to : Integer -> Range Integer.down_to self n = case n of Integer -> Range_Data self n -1 - _ -> Error.throw (Illegal_Argument_Error "Expected range end to be an Integer.") + _ -> Error.throw (Illegal_Argument_Error_Data "Expected range end to be an Integer.") ## PRIVATE -throw_zero_step_error = Error.throw (Illegal_State_Error "A range with step = 0 is ill-formed.") +throw_zero_step_error = Error.throw (Illegal_State_Error_Data "A range with step = 0 is ill-formed.") diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Ordering.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Ordering.enso index 1ea26a45e230..8ccea71e3c12 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Ordering.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Ordering.enso @@ -9,4 +9,5 @@ from Standard.Base import all set to `Nothing` (the default), it chooses the default ordering for a given backend. For the In-memory backend, the default ordering is case sensitive. In databases, the default ordering depends on the database configuration. -type Text_Ordering (sort_digits_as_numbers:Boolean=False) (case_sensitive:(Nothing|True|Case_Insensitive)=Nothing) +type Text_Ordering + Text_Ordering_Data (sort_digits_as_numbers:Boolean=False) (case_sensitive:(Nothing|True|Case_Insensitive)=Nothing) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso index 38ad978ba83b..9fc837a75f9e 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Date.enso @@ -129,7 +129,7 @@ parse text pattern=Nothing = Text -> Date.internal_parse text pattern _ -> Panic.throw (Time.Time_Error_Data "An invalid pattern was provided.") result . map_error <| case _ of - Polyglot_Error_Data err -> Time.Time_Error err.getMessage + Polyglot_Error_Data err -> Time.Time_Error_Data err.getMessage ex -> ex 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 87f9710c9ea3..6ef06628357a 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 @@ -552,7 +552,7 @@ type Vector (0.up_to 100).to_vector.short_display_text max_entries=2 == "[0, 1 and 98 more elements]" short_display_text : Integer -> Text short_display_text self max_entries=10 = - if max_entries < 1 then Error.throw <| Illegal_Argument_Error "The `max_entries` parameter must be positive." else + if max_entries < 1 then Error.throw <| Illegal_Argument_Error_Data "The `max_entries` parameter must be positive." else prefix = self.take_start max_entries if prefix.length == self.length then self.to_text else remaining_count = self.length - prefix.length 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 9daeea4912e8..2bb8f26cc235 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 @@ -163,6 +163,13 @@ type Error is_error : Boolean is_error self = True + ## PRIVATE + TODO this is a kludge until we have proper eigentypes and statics. + Allows to check equality of the `Error` type with itself. + == self that = if Meta.is_error self then self else + if Meta.is_error that then that else + Meta.is_same_object self that + type Illegal_State_Error 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 fbc59c4e3d2e..1baabf40a425 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 @@ -63,7 +63,7 @@ find_caller_script stack = config_from_env : Suite_Config config_from_env = only_group_regexp = Environment.get "TEST_ONLY_GROUP" - + print_only_failures = Environment.get "REPORT_ONLY_FAILED" != "" junit_folder = Environment.get "ENSO_TEST_JUNIT_DIR" results_path = if junit_folder.is_nothing then Nothing else caller_script = find_caller_script Runtime.get_stack_trace @@ -75,7 +75,7 @@ config_from_env = False -> (File.new junit_folder) / project_root.name / "JUnit.xml" - Suite_Config_Data only_group_regexp results_path + Suite_Config_Data only_group_regexp print_only_failures results_path ## Creates a new test group, describing properties of the object @@ -472,7 +472,7 @@ Error.should_be_false self = fail_match_on_unexpected_error self 1 example_should_be_a = 1.should_be_a Boolean Any.should_be_a : Any -> Assertion -Any.should_be_a self typ = if self.is_a typ then Success else +Any.should_be_a self typ = if self.is_a typ || self==typ then Success else loc = Meta.get_source_location 0 expected_type = Meta.get_qualified_type_name typ actual_type = Meta.get_qualified_type_name self @@ -607,7 +607,7 @@ type Verbs ## PRVATE type Suite_Config - Suite_Config_Data only_group_regexp output_path + Suite_Config_Data only_group_regexp print_only_failures output_path should_run_group self name = regexp = self.only_group_regexp @@ -796,17 +796,21 @@ Spec.print_report self config builder = builder.append '\n' builder.append ' \n' - IO.println (self.name + ":") - self.behaviors.reverse.each behavior-> - case behavior.result of - Success -> - IO.println (" - " + behavior.name) - Failure msg -> - IO.println (" - [FAILED] " + behavior.name) - IO.println (" Reason: " + msg) - Pending reason -> - IO.println (" - [PENDING] " + behavior.name) - IO.println (" Reason: " + reason) + should_print_behavior = config.print_only_failures.not || self.behaviors.any (b -> b.result.is_a Failure) + if should_print_behavior then + IO.println (self.name + ":") + self.behaviors.reverse.each behavior-> + case behavior.result of + Success -> + if config.print_only_failures.not then + IO.println (" - " + behavior.name) + Failure msg -> + IO.println (" - [FAILED] " + behavior.name) + IO.println (" Reason: " + msg) + Pending reason -> + if config.print_only_failures.not then + IO.println (" - [PENDING] " + behavior.name) + IO.println (" Reason: " + reason) ## PRIVATE diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java index b9398edf89c4..09515d82812b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Error.java @@ -3,4 +3,9 @@ import org.enso.interpreter.dsl.BuiltinType; @BuiltinType(name = "Standard.Base.Error.Common.Error") -public class Error extends Builtin {} +public class Error extends Builtin { + @Override + protected Class getSuperType() { + return null; + } +} 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 c0747016eec7..ed4660f8c106 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 @@ -193,11 +193,6 @@ Text toDisplayString(boolean allowSideEffects, @CachedLibrary("this") InteropLib } } - @ExportMessage - boolean isNull() { - return this.getConstructor().getType() == Context.get(null).getBuiltins().nothing(); - } - @ExportMessage boolean hasType() { return true; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index 470474d8967a..0b6534515aa6 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -8,6 +8,7 @@ import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.TruffleObject; +import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.nodes.RootNode; @@ -157,6 +158,11 @@ String toDisplayString(boolean allowSideEffects) { return name; } + @ExportMessage + boolean isNull(@CachedLibrary("this") InteropLibrary self) { + return this == Context.get(self).getBuiltins().nothing(); + } + @Override public String toString() { return toDisplayString(true); 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 e0550f1d821f..7f57ee42b250 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 @@ -120,10 +120,12 @@ public static String getName(Object value) { return ConstantsGen.TEXT; } else if (TypesGen.isFunction(value)) { 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 (value instanceof Atom atom) { + return atom.getConstructor().getQualifiedName().toString(); + } else if (value instanceof AtomConstructor cons) { + return cons.getQualifiedName().toString(); + } else if (value instanceof Type t) { + return t.getQualifiedName().toString(); } else if (TypesGen.isDataflowError(value)) { return ConstantsGen.ERROR; } else if (TypesGen.isUnresolvedSymbol(value) || TypesGen.isUnresolvedConversion(value)) { diff --git a/test/Tests/src/Data/Numbers_Spec.enso b/test/Tests/src/Data/Numbers_Spec.enso index 593342d5eacd..c0cdafafdeac 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.Numbers import Parse_Error +from Standard.Base.Data.Numbers import Parse_Error_Data import Standard.Test @@ -58,7 +58,7 @@ spec = Test.specify "should support integer division" <| (10.div 3) . should_equal 3 - (10.div 0).should_fail_with Arithmetic_Error + (10.div 0).should_fail_with Arithmetic_Error_Data Test.specify "should support integral binary literals" <| lit = 2_01101101 @@ -116,28 +116,28 @@ spec = positive_bits.bit_shift_l 64 . should_equal 16_6d0000000000000000 positive_bits.bit_shift_l -2 . should_equal 2_011011 positive_bits.bit_shift_l -64 . should_equal 0 - (positive_bits.bit_shift_l positive_big_bits).should_fail_with Arithmetic_Error + (positive_bits.bit_shift_l positive_big_bits).should_fail_with Arithmetic_Error_Data positive_bits.bit_shift_l negative_big_bits . should_equal 0 negative_bits.bit_shift_l 2 . should_equal -436 negative_bits.bit_shift_l 64 . should_equal -2010695104034341126144 negative_bits.bit_shift_l -2 . should_equal -28 negative_bits.bit_shift_l -64 . should_equal -1 - (negative_bits.bit_shift_l positive_big_bits).should_fail_with Arithmetic_Error + (negative_bits.bit_shift_l positive_big_bits).should_fail_with Arithmetic_Error_Data negative_bits.bit_shift_l negative_big_bits . should_equal -1 positive_big_bits.bit_shift_l 2 . should_equal 110680464442257309672 positive_big_bits.bit_shift_l 64 . should_equal 510423550381407695084381446705395007488 positive_big_bits.bit_shift_l -2 . should_equal 6917529027641081854 positive_big_bits.bit_shift_l -100 . should_equal 0 - (positive_big_bits.bit_shift_l positive_big_bits).should_fail_with Arithmetic_Error + (positive_big_bits.bit_shift_l positive_big_bits).should_fail_with Arithmetic_Error_Data positive_big_bits.bit_shift_l negative_big_bits . should_equal 0 negative_big_bits.bit_shift_l 2 . should_equal -110680464442257309672 negative_big_bits.bit_shift_l 64 . should_equal -510423550381407695084381446705395007488 negative_big_bits.bit_shift_l -2 . should_equal -6917529027641081855 negative_big_bits.bit_shift_l -100 . should_equal -1 - (negative_big_bits.bit_shift_l positive_big_bits).should_fail_with Arithmetic_Error + (negative_big_bits.bit_shift_l positive_big_bits).should_fail_with Arithmetic_Error_Data negative_big_bits.bit_shift_l negative_big_bits . should_equal -1 Test.specify "should support right bit shifts, preserving sign" <| positive_bits = 2_01101101 @@ -149,28 +149,28 @@ spec = positive_bits.bit_shift_r 64 . should_equal (positive_bits.bit_shift_l -64) positive_bits.bit_shift_r -2 . should_equal (positive_bits.bit_shift_l 2) positive_bits.bit_shift_r -64 . should_equal (positive_bits.bit_shift_l 64) - (positive_bits.bit_shift_r negative_big_bits).should_fail_with Arithmetic_Error + (positive_bits.bit_shift_r negative_big_bits).should_fail_with Arithmetic_Error_Data positive_bits.bit_shift_r positive_big_bits . should_equal 0 negative_bits.bit_shift_r 2 . should_equal (negative_bits.bit_shift_l -2) negative_bits.bit_shift_r 64 . should_equal (negative_bits.bit_shift_l -64) negative_bits.bit_shift_r -2 . should_equal (negative_bits.bit_shift_l 2) negative_bits.bit_shift_r -64 . should_equal (negative_bits.bit_shift_l 64) - (negative_bits.bit_shift_r negative_big_bits).should_fail_with Arithmetic_Error + (negative_bits.bit_shift_r negative_big_bits).should_fail_with Arithmetic_Error_Data negative_bits.bit_shift_r positive_big_bits . should_equal -1 positive_big_bits.bit_shift_r 2 . should_equal (positive_big_bits.bit_shift_l -2) positive_big_bits.bit_shift_r 64 . should_equal (positive_big_bits.bit_shift_l -64) positive_big_bits.bit_shift_r -2 . should_equal (positive_big_bits.bit_shift_l 2) positive_big_bits.bit_shift_r -100 . should_equal (positive_big_bits.bit_shift_l 100) - (positive_big_bits.bit_shift_r negative_big_bits).should_fail_with Arithmetic_Error + (positive_big_bits.bit_shift_r negative_big_bits).should_fail_with Arithmetic_Error_Data positive_big_bits.bit_shift_r positive_big_bits . should_equal 0 negative_big_bits.bit_shift_r 2 . should_equal (negative_big_bits.bit_shift_l -2) negative_big_bits.bit_shift_r 64 . should_equal (negative_big_bits.bit_shift_l -64) negative_big_bits.bit_shift_r -2 . should_equal (negative_big_bits.bit_shift_l 2) negative_big_bits.bit_shift_r -100 . should_equal (negative_big_bits.bit_shift_l 100) - (negative_big_bits.bit_shift_r negative_big_bits).should_fail_with Arithmetic_Error + (negative_big_bits.bit_shift_r negative_big_bits).should_fail_with Arithmetic_Error_Data negative_big_bits.bit_shift_r positive_big_bits . should_equal -1 Test.specify "should be able to parse" <| @@ -179,28 +179,28 @@ spec = Integer.parse "-1234567" . should_equal -1234567 Integer.parse "00000" . should_equal 0 Integer.parse "00000123" . should_equal 123 - Integer.parse "123.45" . should_fail_with Parse_Error - Integer.parse "123A" . should_fail_with Parse_Error - Integer.parse "aaaa" . should_fail_with Parse_Error + Integer.parse "123.45" . should_fail_with Parse_Error_Data + Integer.parse "123A" . should_fail_with Parse_Error_Data + Integer.parse "aaaa" . should_fail_with Parse_Error_Data Test.specify "should be able to parse alternate bases" <| Integer.parse "1245623" 8 . should_equal 347027 Integer.parse "-1245623" 8 . should_equal -347027 Integer.parse "0001245623" 8 . should_equal 347027 Integer.parse "00000" 8 . should_equal 0 - Integer.parse "9847" 8 . should_fail_with Parse_Error - Integer.parse "8479" 8 . should_fail_with Parse_Error + Integer.parse "9847" 8 . should_fail_with Parse_Error_Data + Integer.parse "8479" 8 . should_fail_with Parse_Error_Data Integer.parse "ABC123" 16 . should_equal 11256099 Integer.parse "123ABC" 16 . should_equal 1194684 Integer.parse "123aBc" 16 . should_equal 1194684 Integer.parse "-ABC123" 16 . should_equal -11256099 Integer.parse "00000ABC123" 16 . should_equal 11256099 - Integer.parse "123aBcG" 16 . should_fail_with Parse_Error + Integer.parse "123aBcG" 16 . should_fail_with Parse_Error_Data Integer.parse "10101010" 2 . should_equal 170 Integer.parse "00001111" 2 . should_equal 15 Integer.parse "-10101010" 2 . should_equal -170 - Integer.parse "-101021010" 2 . should_fail_with Parse_Error - Integer.parse "123" 128 . should_fail_with Parse_Error + Integer.parse "-101021010" 2 . should_fail_with Parse_Error_Data + Integer.parse "123" 128 . should_fail_with Parse_Error_Data Test.group "Decimals" <| @@ -216,7 +216,7 @@ spec = Decimal.parse "-98.5" . should_equal -98.5 Decimal.parse "000000" . should_equal 0 Decimal.parse "000000.0001" . should_equal 0.0001 - Decimal.parse "aaaa" . should_fail_with Parse_Error + Decimal.parse "aaaa" . should_fail_with Parse_Error_Data Test.group "Numbers" <| @@ -248,8 +248,8 @@ spec = almost_max_long_times_three%10 . should_equal 8 1000%almost_max_long_times_three . should_equal 1000 - 1%0 . should_fail_with Arithmetic_Error - almost_max_long_times_three%0 . should_fail_with Arithmetic_Error + 1%0 . should_fail_with Arithmetic_Error_Data + almost_max_long_times_three%0 . should_fail_with Arithmetic_Error_Data 1.0%0.0 . is_nan . should_be_true 1%0.0 . is_nan . should_be_true diff --git a/test/Tests/src/Data/Ordering/Comparator_Spec.enso b/test/Tests/src/Data/Ordering/Comparator_Spec.enso index 5cada4852dbd..020ddbd9f60a 100644 --- a/test/Tests/src/Data/Ordering/Comparator_Spec.enso +++ b/test/Tests/src/Data/Ordering/Comparator_Spec.enso @@ -8,19 +8,21 @@ import Standard.Test # === Test Resources === -type Ord number +type Ord + Ord_Data number Ord.compare_to : Ord -> Ordering Ord.compare_to self that = that.number.compare_to self.number -type No_Ord number +type No_Ord + No_Ord_Data number # Tests spec = Test.group "Object Comparator" <| handle_classcast = Panic.catch ClassCastException handler=(Error.throw Vector.Incomparable_Values_Error) default_comparator a b = handle_classcast <| Comparator.new.compare a b - case_insensitive a b = handle_classcast <| Comparator.for_text_ordering (Text_Ordering False Case_Insensitive) . compare a b + case_insensitive a b = handle_classcast <| Comparator.for_text_ordering (Text_Ordering_Data False Case_Insensitive_Data) . compare a b Test.specify "can compare numbers" <| ((default_comparator 1 2) < 0) . should_equal True @@ -52,11 +54,11 @@ spec = Test.group "Object Comparator" <| ((case_insensitive '\u00E9' '\u0065\u{301}') == 0) . should_equal True Test.specify "can compare custom types" <| - ((default_comparator (Ord 1) (Ord 0)) < 0) . should_equal True - ((default_comparator (Ord 1) (Ord 1)) == 0) . should_equal True + ((default_comparator (Ord_Data 1) (Ord_Data 0)) < 0) . should_equal True + ((default_comparator (Ord_Data 1) (Ord_Data 1)) == 0) . should_equal True Test.specify "should fail gracefully for incomparable items" <| (default_comparator 1 True).should_fail_with Vector.Incomparable_Values_Error - (default_comparator (No_Ord 1) (No_Ord 2)).should_fail_with Vector.Incomparable_Values_Error + (default_comparator (No_Ord_Data 1) (No_Ord_Data 2)).should_fail_with Vector.Incomparable_Values_Error main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Ordering/Natural_Order_Spec.enso b/test/Tests/src/Data/Ordering/Natural_Order_Spec.enso index 4bfe1391930f..267129711a4e 100644 --- a/test/Tests/src/Data/Ordering/Natural_Order_Spec.enso +++ b/test/Tests/src/Data/Ordering/Natural_Order_Spec.enso @@ -3,7 +3,7 @@ from Standard.Base import all import Standard.Test spec = Test.group "Natural Order" <| - case_insensitive_compare a b = Natural_Order.compare a b Case_Insensitive + case_insensitive_compare a b = Natural_Order.compare a b Case_Insensitive_Data Test.specify "should behave as shown in examples" <| Natural_Order.compare "a2" "a100" . should_equal Ordering.Less diff --git a/test/Tests/src/Data/Ordering/Vector_Lexicographic_Order_Spec.enso b/test/Tests/src/Data/Ordering/Vector_Lexicographic_Order_Spec.enso index ecf4d68a2ce6..12f3449c68e1 100644 --- a/test/Tests/src/Data/Ordering/Vector_Lexicographic_Order_Spec.enso +++ b/test/Tests/src/Data/Ordering/Vector_Lexicographic_Order_Spec.enso @@ -4,7 +4,8 @@ import Standard.Base.Data.Ordering.Vector_Lexicographic_Order import Standard.Test -type My_Type a b +type My_Type + My_Type_Data a b spec = Test.group "Lexicographic Order on Vectors" <| Test.specify "should behave as shown in examples" <| @@ -15,7 +16,7 @@ spec = Test.group "Lexicographic Order on Vectors" <| Test.specify "should work correctly with a custom comparator" <| comparator = x-> y-> x.a.compare_to y.a - Vector_Lexicographic_Order.compare [My_Type "a" 1, My_Type "b" 1, My_Type "c" 1] [My_Type "b" 1, My_Type "a" 1, My_Type "c" 1] element_comparator=comparator . should_equal Ordering.Less - Vector_Lexicographic_Order.compare [My_Type "a" 1, My_Type "b" 1, My_Type "c" 1] [My_Type "a" 100, My_Type "b" 2, My_Type "c" 3] element_comparator=comparator . should_equal Ordering.Equal + Vector_Lexicographic_Order.compare [My_Type_Data "a" 1, My_Type_Data "b" 1, My_Type_Data "c" 1] [My_Type_Data "b" 1, My_Type_Data "a" 1, My_Type_Data "c" 1] element_comparator=comparator . should_equal Ordering.Less + Vector_Lexicographic_Order.compare [My_Type_Data "a" 1, My_Type_Data "b" 1, My_Type_Data "c" 1] [My_Type_Data "a" 100, My_Type_Data "b" 2, My_Type_Data "c" 3] element_comparator=comparator . should_equal Ordering.Equal main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Ordering_Spec.enso b/test/Tests/src/Data/Ordering_Spec.enso index ec01b8a49e8e..fb357e074fec 100644 --- a/test/Tests/src/Data/Ordering_Spec.enso +++ b/test/Tests/src/Data/Ordering_Spec.enso @@ -4,7 +4,8 @@ import Standard.Test # === Test Resources === -type Ord number +type Ord + Ord_Data number Ord.compare_to : Ord -> Ordering Ord.compare_to self that = if self.number == that.number then Ordering.Equal else @@ -17,18 +18,18 @@ spec = Test.group "Ordering" <| Test.specify "should allow comparing Less" <| - left = Ord 1032 - right = Ord 101111 + left = Ord_Data 1032 + right = Ord_Data 101111 left.compare_to right . should_equal Ordering.Less Test.specify "should allow comparing Equal" <| - left = Ord 1032 - right = Ord 1032 + left = Ord_Data 1032 + right = Ord_Data 1032 left.compare_to right . should_equal Ordering.Equal Test.specify "should allow comparing Greater" <| - left = Ord 1032 - right = Ord -1 + left = Ord_Data 1032 + right = Ord_Data -1 left.compare_to right . should_equal Ordering.Greater Test.specify "should allow conversion to sign representation" <| diff --git a/test/Tests/src/Data/Statistics_Spec.enso b/test/Tests/src/Data/Statistics_Spec.enso index c507fec793d9..f19da20e9d90 100644 --- a/test/Tests/src/Data/Statistics_Spec.enso +++ b/test/Tests/src/Data/Statistics_Spec.enso @@ -5,12 +5,14 @@ import Standard.Test # === Test Resources === -type Ord number +type Ord + Ord_Data number Ord.compare_to : Ord -> Ordering Ord.compare_to self that = that.number.compare_to self.number -type No_Ord number +type No_Ord + No_Ord_Data number # Tests @@ -131,8 +133,8 @@ spec = Test.group "Statistics - invalid input" <| text_set = ["A", "B", Nothing, "D"] - ord_set = [Ord 10, Ord 2, Nothing, Ord 9] - no_ord_set = [No_Ord 10, No_Ord 2, Nothing, No_Ord 9] + ord_set = [Ord_Data 10, Ord_Data 2, Nothing, Ord_Data 9] + no_ord_set = [No_Ord_Data 10, No_Ord_Data 2, Nothing, No_Ord_Data 9] Test.specify "should fail with Illegal_Argument_Error on number based statistics for text Vector" <| text_set.compute Sum . should_fail_with Illegal_Argument_Error_Data @@ -143,8 +145,8 @@ spec = Test.specify "should be able to do Count, Minimum and Maximum on custom type with compare_to" <| ord_set.compute . should_equal 3 - ord_set.compute Minimum . should_equal (Ord 10) - ord_set.compute Maximum . should_equal (Ord 2) + ord_set.compute Minimum . should_equal (Ord_Data 10) + ord_set.compute Maximum . should_equal (Ord_Data 2) Test.specify "should fail with Incomparable_Values_Error on custom type without compare_to" <| no_ord_set.compute . should_equal 3 @@ -176,7 +178,7 @@ spec = rank_data values . should_equal [1.5, 5, 4, 1.5, 3] Test.specify "should fail with Incomparable_Values_Error on custom type without compare_to" <| - values = [No_Ord 10, No_Ord 2, No_Ord 9] + values = [No_Ord_Data 10, No_Ord_Data 2, No_Ord_Data 9] rank_data values . should_fail_with Vector.Incomparable_Values_Error Test.specify "should fail with Incomparable_Values_Error on mixed Vectors" <| diff --git a/test/Tests/src/Data/Vector_Spec.enso b/test/Tests/src/Data/Vector_Spec.enso index 36d727bca253..9d7e7c3d5513 100644 --- a/test/Tests/src/Data/Vector_Spec.enso +++ b/test/Tests/src/Data/Vector_Spec.enso @@ -2,15 +2,18 @@ from Standard.Base import all import Standard.Test -type T a b +type T + T_Data a b T.== self that = self.a == that.a T.compare_to self that = if self == that then Ordering.Equal else if self.a > that.a then Ordering.Greater else Ordering.Less -type My_Error a +type My_Error + My_Error_Data a -type Foo vec +type Foo + Foo_Data vec compare_tco a b = case a.vec.length == b.vec.length of False -> a.vec.length . compare_to b.vec.length @@ -45,9 +48,9 @@ spec = Test.group "Vectors" <| [1,2,3].at 2 . should_equal 3 Test.specify "should allow to store dataflow errors and raise them on access" <| - vec = [Error.throw (My_Error "foo"), "bar"] + vec = [Error.throw (My_Error_Data "foo"), "bar"] vec.at 1 . should_equal "bar" - vec.at 0 . should_fail_with My_Error + vec.at 0 . should_fail_with My_Error_Data Test.specify "should allow accessing elements with negative indices" <| [1,2,3].at -1 . should_equal 3 @@ -71,7 +74,7 @@ spec = Test.group "Vectors" <| Test.specify "should allow summing elements if they define +" <| [1,2,3].sum . should_equal 6 [].sum . should_fail_with Vector.Empty_Error - [T 1 2, T 3 4].sum . should_fail_with No_Such_Method_Error_Data + [T_Data 1 2, T_Data 3 4].sum . should_fail_with No_Such_Method_Error_Data Test.specify "should check exists" <| vec = [1, 2, 3, 4, 5] @@ -110,20 +113,20 @@ spec = Test.group "Vectors" <| vec.filter (x -> x > 3) . should_equal [4, 5] vec.filter (x -> x == 1) . should_equal [1] vec.filter (x -> x < 0) . should_equal [] - vec.filter (x -> if x == 2 then Error.throw <| My_Error "foo" else True) . should_fail_with My_Error + vec.filter (x -> if x == 2 then Error.throw <| My_Error_Data "foo" else True) . should_fail_with My_Error_Data Test.specify "should filter elements with indices" <| [0, 10, 2, 2].filter_with_index (==) . should_equal [0, 2] ([1, 2, 3, 4].filter_with_index ix-> _-> ix < 2) . should_equal [1, 2] - ([1, 2, 3, 4].filter_with_index ix-> _-> if ix == 1 then Error.throw <| My_Error "foo" else True) . should_fail_with My_Error + ([1, 2, 3, 4].filter_with_index ix-> _-> if ix == 1 then Error.throw <| My_Error_Data "foo" else True) . should_fail_with My_Error_Data Test.specify "should partition elements" <| [1, 2, 3, 4, 5].partition (x -> x % 2 == 0) . should_equal <| Pair_Data [2, 4] [1, 3, 5] - ([1, 2, 3, 4].partition x-> if x == 1 then Error.throw <| My_Error "foo" else True) . should_fail_with My_Error + ([1, 2, 3, 4].partition x-> if x == 1 then Error.throw <| My_Error_Data "foo" else True) . should_fail_with My_Error_Data Test.specify "should partition elements with indices" <| ["a", "b", "c", "d"].partition_with_index (ix -> _ -> ix % 2 == 0) == (Pair_Data ["a", "c"] ["b", "d"]) - ["a", "b", "c", "d"].partition_with_index (ix -> _ -> if ix % 2 == 0 then Error.throw <| My_Error "foo" else True) . should_fail_with My_Error + ["a", "b", "c", "d"].partition_with_index (ix -> _ -> if ix % 2 == 0 then Error.throw <| My_Error_Data "foo" else True) . should_fail_with My_Error_Data Test.specify "should allow to join a vector of text elements to form a single text" <| ["a", "b", "c"].join . should_equal "abc" @@ -147,7 +150,7 @@ spec = Test.group "Vectors" <| [[], []].flatten . should_equal [] [[1]].flatten . should_equal [1] [[[1], [2, 3]], [[4]]].flatten . should_equal [[1], [2, 3], [4]] - [["a", 2], [], [[[3]]], [T 1 2, 44]].flatten . should_equal ["a", 2, [[3]], T 1 2, 44] + [["a", 2], [], [[[3]]], [T_Data 1 2, 44]].flatten . should_equal ["a", 2, [[3]], T_Data 1 2, 44] (["polyglot", " ", "array"].map .utf_8).flatten . should_equal "polyglot array".utf_8 Test.specify "should allow applying a function to each element" <| @@ -174,7 +177,7 @@ spec = Test.group "Vectors" <| [1, 2, 3, 4, 5, 6].short_display_text max_entries=3 . should_equal "[1, 2, 3 and 3 more elements]" (0.up_to 100).to_vector.short_display_text max_entries=2 . should_equal "[0, 1 and 98 more elements]" - [].short_display_text max_entries=0 . should_fail_with Illegal_Argument_Error + [].short_display_text max_entries=0 . should_fail_with Illegal_Argument_Error_Data Test.specify "should define equality" <| [1,2,3]==[1,2] . should_be_false @@ -261,13 +264,13 @@ spec = Test.group "Vectors" <| sorted . should_equal [2, 2, 2, 3, 3, 4] Test.specify "should have a stable sort" <| - small_vec = [T 1 8, T 1 3, T -20 0, T -1 1, T -1 10, T 4 0] - small_expected = [T -20 0, T -1 1, T -1 10, T 1 8, T 1 3, T 4 0] + small_vec = [T_Data 1 8, T_Data 1 3, T_Data -20 0, T_Data -1 1, T_Data -1 10, T_Data 4 0] + small_expected = [T_Data -20 0, T_Data -1 1, T_Data -1 10, T_Data 1 8, T_Data 1 3, T_Data 4 0] small_vec.sort . should_equal small_expected Test.specify "should be able to use a custom element projection" <| - small_vec = [T 1 8, T 1 3, T -20 0, T -1 1, T -1 10, T 4 0] - small_expected = [T -20 0, T 4 0, T -1 1, T 1 3, T 1 8, T -1 10] + small_vec = [T_Data 1 8, T_Data 1 3, T_Data -20 0, T_Data -1 1, T_Data -1 10, T_Data 4 0] + small_expected = [T_Data -20 0, T_Data 4 0, T_Data -1 1, T_Data 1 3, T_Data 1 8, T_Data -1 10] small_vec.sort (on = _.b) . should_equal small_expected Test.specify "should be able to use a custom comparator" <| @@ -276,13 +279,13 @@ spec = Test.group "Vectors" <| small_vec.sort (by = l -> r -> r.compare_to l) . should_equal small_expected Test.specify "should allow tail-recursive comparators in sort" <| - v = [Foo [4,2,2], Foo [1,2,3], Foo [1,2,4]] - r = [Foo [1,2,3], Foo [1,2,4], Foo [4,2,2]] + v = [Foo_Data [4,2,2], Foo_Data [1,2,3], Foo_Data [1,2,4]] + r = [Foo_Data [1,2,3], Foo_Data [1,2,4], Foo_Data [4,2,2]] v.sort by=compare_tco . should_equal r Test.specify "should be able to use a custom comparator and projection" <| - small_vec = [T 1 8, T 1 3, T -20 0, T -1 1, T -1 10, T 4 0] - small_expected = [T -1 10, T 1 8, T 1 3, T -1 1, T -20 0, T 4 0] + small_vec = [T_Data 1 8, T_Data 1 3, T_Data -20 0, T_Data -1 1, T_Data -1 10, T_Data 4 0] + small_expected = [T_Data -1 10, T_Data 1 8, T_Data 1 3, T_Data -1 1, T_Data -20 0, T_Data 4 0] small_vec.sort (on = _.b) (by = l -> r -> r.compare_to l) . should_equal small_expected Test.specify "should be able to sort in descending order" <| @@ -291,14 +294,14 @@ spec = Test.group "Vectors" <| small_vec.sort order=Sort_Direction.Descending . should_equal small_expected Test.specify "should be stable in descending order" <| - small_vec = [T 1 8, T 1 3, T -20 0, T -1 1, T -1 10, T 4 0] - small_expected = [T 4 0, T 1 3, T 1 8, T -1 10, T -1 1, T -20 0] + small_vec = [T_Data 1 8, T_Data 1 3, T_Data -20 0, T_Data -1 1, T_Data -1 10, T_Data 4 0] + small_expected = [T_Data 4 0, T_Data 1 3, T_Data 1 8, T_Data -1 10, T_Data -1 1, T_Data -20 0] small_vec.sort order=Sort_Direction.Descending . should_equal small_expected Test.specify "should be able to map over errors" <| - fail a = Error.throw <| My_Error a + fail a = Error.throw <| My_Error_Data a [fail 1].map (x -> x.catch Any (x -> x.a)) . should_equal [1] - [1].map fail . map .catch . should_equal [My_Error 1] + [1].map fail . map .catch . should_equal [My_Error_Data 1] Test.specify "should be able to be efficiently converted to a visualisation" <| vec = Vector.fill 1000 0 @@ -345,7 +348,7 @@ spec = Test.group "Vectors" <| [Pair_Data 1 2, Pair_Data 3 4].distinct . should_fail_with Vector.Incomparable_Values_Error Test.specify "should correctly handle distinct with custom types like Atoms that implement compare_to" <| - [T 1 2, T 3 3, T 1 2].distinct . should_equal [T 1 2, T 3 3] + [T_Data 1 2, T_Data 3 3, T_Data 1 2].distinct . should_equal [T_Data 1 2, T_Data 3 3] Test.specify "should return a vector containing only unique elements up to some criteria" <| [Pair_Data 1 "a", Pair_Data 2 "b", Pair_Data 1 "c"] . distinct (on = _.first) . should_equal [Pair_Data 1 "a", Pair_Data 2 "b"] diff --git a/test/Tests/src/Main.enso b/test/Tests/src/Main.enso index cc14de5395dc..d1da63d25fc0 100644 --- a/test/Tests/src/Main.enso +++ b/test/Tests/src/Main.enso @@ -9,7 +9,7 @@ import project.Semantic.Deep_Export.Spec as Deep_Export_Spec import project.Semantic.Error_Spec import project.Semantic.Import_Loop.Spec as Import_Loop_Spec import project.Semantic.Meta_Spec -#import project.Semantic.Names_Spec +import project.Semantic.Names_Spec #import project.Semantic.Runtime_Spec #import project.Semantic.Warnings_Spec @@ -29,16 +29,16 @@ import project.Data.Map_Spec import project.Data.Maybe_Spec import project.Data.Noise.Generator_Spec as Noise_Generator_Spec import project.Data.Noise_Spec -#import project.Data.Numbers_Spec -#import project.Data.Ordering_Spec -#import project.Data.Ordering.Comparator_Spec -#import project.Data.Ordering.Natural_Order_Spec -#import project.Data.Ordering.Vector_Lexicographic_Order_Spec -#import project.Data.Range_Spec -#import project.Data.Ref_Spec -#import project.Data.Time.Spec as Time_Spec -#import project.Data.Vector_Spec -#import project.Data.Statistics_Spec +import project.Data.Numbers_Spec +import project.Data.Ordering_Spec +import project.Data.Ordering.Comparator_Spec +import project.Data.Ordering.Natural_Order_Spec +import project.Data.Ordering.Vector_Lexicographic_Order_Spec +import project.Data.Range_Spec +import project.Data.Ref_Spec +import project.Data.Time.Spec as Time_Spec +import project.Data.Vector_Spec +import project.Data.Statistics_Spec #import project.Data.Regression_Spec #import project.Data.Text_Spec @@ -62,7 +62,7 @@ import project.Network.URI_Spec import project.System.Environment_Spec import project.System.File_Spec -#import project.System.Process_Spec +import project.System.Process_Spec import project.System.Reporting_Stream_Decoder_Spec import project.System.Reporting_Stream_Encoder_Spec #import project.System.System_Spec @@ -95,19 +95,19 @@ main = Test.Suite.run_main <| Map_Spec.spec Maybe_Spec.spec Meta_Spec.spec - #Names_Spec.spec + Names_Spec.spec Noise_Generator_Spec.spec Noise_Spec.spec - #Numbers_Spec.spec - #Ordering_Spec.spec - #Comparator_Spec.spec - #Natural_Order_Spec.spec - #Vector_Lexicographic_Order_Spec.spec - #Process_Spec.spec + Numbers_Spec.spec + Ordering_Spec.spec + Comparator_Spec.spec + Natural_Order_Spec.spec + Vector_Lexicographic_Order_Spec.spec + Process_Spec.spec Python_Interop_Spec.spec R_Interop_Spec.spec - #Range_Spec.spec - #Ref_Spec.spec + Range_Spec.spec + Ref_Spec.spec #Default_Regex_Engine_Spec.spec #Regex_Spec.spec #Matching_Spec.spec @@ -120,10 +120,10 @@ main = Test.Suite.run_main <| #Stack_Traces_Spec.spec #Utils_Spec.spec #Text_Spec.spec - #Time_Spec.spec + Time_Spec.spec URI_Spec.spec - #Vector_Spec.spec - #Statistics_Spec.spec + Vector_Spec.spec + Statistics_Spec.spec #Regression_Spec.spec #Warnings_Spec.spec #System_Spec.spec From dbecbbec9e39ab56c89e98f7aaf3d79a34411583 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 16 Aug 2022 14:59:51 +0200 Subject: [PATCH 051/110] progress --- .../0.0.0-dev/src/Data/Text/Encoding.enso | 2 +- .../0.0.0-dev/src/Data/Text/Matching.enso | 21 ++--- .../Base/0.0.0-dev/src/Data/Text/Regex.enso | 4 +- .../src/Data/Text/Regex/Engine/Default.enso | 12 +-- .../lib/Standard/Base/0.0.0-dev/src/Main.enso | 2 +- .../node/expression/atom/GetFieldNode.java | 17 ++++- .../callable/atom/AtomConstructor.java | 19 +---- .../enso/interpreter/runtime/data/Type.java | 4 +- .../Data/Text/Default_Regex_Engine_Spec.enso | 52 ++++++------- test/Tests/src/Data/Text/Encoding_Spec.enso | 2 +- test/Tests/src/Data/Text/Matching_Spec.enso | 76 +++++++++---------- test/Tests/src/Data/Text/Regex_Spec.enso | 2 +- test/Tests/src/Main.enso | 36 ++++----- 13 files changed, 126 insertions(+), 123 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Encoding.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Encoding.enso index 7c59a50f4c22..7eefba30b55a 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Encoding.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Encoding.enso @@ -29,7 +29,7 @@ type Encoding to_java_charset : Charset to_java_charset self = Panic.catch UnsupportedCharsetException (Charset.forName self.character_set) _-> - Error.throw (Illegal_Argument_Error ("Unknown Character Set: " + self.character_set)) + Error.throw (Illegal_Argument_Error_Data ("Unknown Character Set: " + self.character_set)) ## Encoding for ASCII. ascii : Encoding diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso index c95dd9a7cdc2..c342309b56ef 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Matching.enso @@ -3,11 +3,12 @@ from Standard.Base import all import Standard.Base.Data.Locale import Standard.Base.Data.Text.Regex from Standard.Base.Error.Problem_Behavior import Problem_Behavior, Report_Warning -from Standard.Base.Error.Common import Wrapped_Dataflow_Error +from Standard.Base.Error.Common import Wrapped_Dataflow_Error_Data ## UNSTABLE An error indicating that some criteria did not match any names in the input. -type No_Matches_Found (criteria : Vector Text) +type No_Matches_Found + No_Matches_Found_Data (criteria : Vector Text) No_Matches_Found.to_display_text : Text No_Matches_Found.to_display_text self = @@ -143,7 +144,7 @@ Regex_Matcher.match_single_criterion self name criterion = Selects pairs matching their first element with the provided criteria and ordering the result according to the order of criteria that matched them. - Text_Matcher.match_criteria [Pair "foo" 42, Pair "bar" 33, Pair "baz" 10, Pair "foo" 0, Pair 10 10] ["bar", "foo"] reorder=True name_mapper=_.name == [Pair "bar" 33, Pair "foo" 42, Pair "foo" 0] + Text_Matcher.match_criteria [Pair_Data "foo" 42, Pair_Data "bar" 33, Pair_Data "baz" 10, Pair_Data "foo" 0, Pair_Data 10 10] ["bar", "foo"] reorder=True name_mapper=_.name == [Pair_Data "bar" 33, Pair_Data "foo" 42, Pair_Data "foo" 0] Text_Matcher.match_criteria : Vector Any -> Vector Text -> Boolean -> (Any -> Text) -> Problem_Behavior -> Vector Any ! No_Matches_Found Text_Matcher.match_criteria self = match_criteria_implementation self @@ -184,7 +185,7 @@ Text_Matcher.match_criteria self = match_criteria_implementation self Selects pairs matching their first element with the provided criteria and ordering the result according to the order of criteria that matched them. - Text_Matcher.match_criteria [Pair "foo" 42, Pair "bar" 33, Pair "baz" 10, Pair "foo" 0, Pair 10 10] ["bar", "foo"] reorder=True name_mapper=_.name == [Pair "bar" 33, Pair "foo" 42, Pair "foo" 0] + Text_Matcher.match_criteria [Pair_Data "foo" 42, Pair_Data "bar" 33, Pair_Data "baz" 10, Pair_Data "foo" 0, Pair_Data 10 10] ["bar", "foo"] reorder=True name_mapper=_.name == [Pair_Data "bar" 33, Pair_Data "foo" 42, Pair_Data "foo" 0] Regex_Matcher.match_criteria : Vector Any -> Vector Text -> Boolean -> (Any -> Text) -> Problem_Behavior -> Vector Any ! No_Matches_Found Regex_Matcher.match_criteria self = match_criteria_implementation self @@ -193,7 +194,7 @@ match_criteria_implementation matcher objects criteria reorder=False name_mapper result = internal_match_criteria_implementation matcher objects criteria reorder name_mapper unmatched_criteria = result.second problems = if unmatched_criteria.is_empty then [] else - [No_Matches_Found unmatched_criteria] + [No_Matches_Found_Data unmatched_criteria] on_problems.attach_problems_after result.first problems ## PRIVATE @@ -223,7 +224,7 @@ type Match_Matrix unmatched_criteria self = checked_criteria = self.criteria.map_with_index j-> criterion-> has_matches = self.does_criterion_match_anything j - Pair has_matches criterion + Pair_Data has_matches criterion checked_criteria.filter (p -> p.first.not) . map .second ## PRIVATE @@ -250,13 +251,13 @@ make_match_matrix matcher objects criteria object_name_mapper=(x->x) criterion_m matrix = objects.map obj-> criteria.map criterion-> matcher.match_single_criterion (object_name_mapper obj) (criterion_mapper criterion) - Match_Matrix matrix criteria objects + Match_Matrix_Data matrix criteria objects ## PRIVATE -internal_match_criteria_implementation matcher objects criteria reorder=False name_mapper=(x->x) = Panic.catch Wrapped_Dataflow_Error (handler = x-> x.payload.unwrap) <| +internal_match_criteria_implementation matcher objects criteria reorder=False name_mapper=(x->x) = Panic.catch Wrapped_Dataflow_Error_Data (handler = x-> x.payload.unwrap) <| ## TODO [RW] discuss: this line of code also shows an issue we had with ensuring input dataflow-errors are correctly propagated, later on we stopped doing that and testing for that as it was too cumbersome. Maybe it could be helped with an @Accepts_Error annotation similar to the one from the interpreter??? [matcher, objects, criteria, reorder, name_mapper] . each v-> - Panic.rethrow (v.map_error Wrapped_Dataflow_Error) + Panic.rethrow (v.map_error Wrapped_Dataflow_Error_Data) match_matrix = make_match_matrix matcher objects criteria name_mapper unmatched_criteria = match_matrix.unmatched_criteria @@ -277,4 +278,4 @@ internal_match_criteria_implementation matcher objects criteria reorder=False na select_matching_indices match_matrix.is_object_matched_by_anything result = selected_indices.map objects.at - Pair result unmatched_criteria + Pair_Data result unmatched_criteria 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 9f031fc469a7..ab88691db532 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 @@ -1,4 +1,5 @@ ## This module contains the basic interface to the more advanced functionality + of Enso's regular expression engine. TODO Examples @@ -122,7 +123,8 @@ from_flags match_ascii case_insensitive dot_matches_newline multiline comments e Arguments: - id: The identifier of the group that was asked for but does not exist. -type No_Such_Group_Error (id : Text | Integer) +type No_Such_Group_Error + No_Such_Group_Error_Data (id : Text | Integer) ## PRIVATE 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 1a552a6264be..20d985b44358 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 @@ -122,7 +122,7 @@ type Engine internal_pattern = maybe_java_pattern.map_error case _ of Polyglot_Error_Data err -> if err.is_a PatternSyntaxException . not then err else - Syntax_Error ("The regex could not be compiled: " + err.getMessage) + Syntax_Error_Data ("The regex could not be compiled: " + err.getMessage) other -> other Pattern_Data internal_pattern all_options self @@ -263,7 +263,7 @@ type Pattern internal_matcher = self.build_matcher input start end if internal_matcher . find start . not then Nothing else - Match internal_matcher start end input + Match_Data internal_matcher start end input Integer -> if mode < 0 then Panic.throw <| Mode_Error_Data "Cannot match a negative number of times." @@ -278,7 +278,7 @@ type Pattern found = internal_matcher.find offset if found.not then Nothing else - builder.append (Match internal_matcher start end input) + builder.append (Match_Data internal_matcher start end input) match_end = internal_matcher.end 0 # Ensure progress even if the match is an empty string. new_offset = if match_end > offset then match_end else offset+1 @@ -298,7 +298,7 @@ type Pattern found = internal_matcher.find offset if found.not then Nothing else - builder.append (Match internal_matcher start end input) + builder.append (Match_Data internal_matcher start end input) match_end = internal_matcher.end 0 # Ensure progress even if the match is an empty string. new_offset = if match_end > offset then match_end else offset+1 @@ -311,7 +311,7 @@ type Pattern Mode.Full -> internal_matcher = self.build_matcher input start end if internal_matcher.matches.not then Nothing else - Match internal_matcher start end input + Match_Data internal_matcher start end input Mode.Bounded _ _ _ -> Panic.throw <| Mode_Error_Data "Modes cannot be recursive." @@ -827,7 +827,7 @@ handle_error error id = case error of maps_to_no_such_group = is_ioob || is_iae if maps_to_no_such_group.not then err else - Regex.No_Such_Group_Error id + Regex.No_Such_Group_Error_Data id other -> other ## Options specific to the `Default` regular expression engine. 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 d87dd0ab37db..1edd3aaaca48 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 @@ -87,7 +87,7 @@ from project.Data.Range export all https://www.pivotaltracker.com/story/show/181403340 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, Case_Insensitive_Data, Text_Matcher, Text_Matcher_Data, Regex_Matcher, Regex_Matcher_Data, No_Matches_Found +from project.Data.Text.Matching export Case_Insensitive, Case_Insensitive_Data, Text_Matcher, Text_Matcher_Data, Regex_Matcher, Regex_Matcher_Data, No_Matches_Found, No_Matches_Found_Data from project.Data.Text export all hiding Encoding, Span, Text_Ordering from project.Data.Text.Encoding export Encoding, Encoding_Error, Encoding_Error_Data from project.Data.Text.Text_Ordering export all diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldNode.java index 493feb8487ed..89ce4d12d6d1 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldNode.java @@ -6,11 +6,14 @@ import com.oracle.truffle.api.nodes.RootNode; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.function.Function; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.state.Stateful; @NodeInfo(shortName = "get_field", description = "A base for auto-generated Atom getters.") public class GetFieldNode extends RootNode { private final int index; + private final String name; + private final Type type; /** * Creates a new instance of this node. @@ -18,9 +21,11 @@ public class GetFieldNode extends RootNode { * @param language the current language instance. * @param index the index this node should use for field lookup. */ - public GetFieldNode(TruffleLanguage language, int index) { + public GetFieldNode(TruffleLanguage language, int index, Type type, String name) { super(language); this.index = index; + this.type = type; + this.name = name; } /** @@ -35,4 +40,14 @@ public Stateful execute(VirtualFrame frame) { Object state = Function.ArgumentsHelper.getState(frame.getArguments()); return new Stateful(state, atom.getFields()[index]); } + + @Override + public String getQualifiedName() { + return type.getQualifiedName().createChild(name).toString(); + } + + @Override + public String getName() { + return type.getName() + "." + name; + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/atom/AtomConstructor.java index 8d0db57e1d1f..a25f28e75a08 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 @@ -110,7 +110,7 @@ public AtomConstructor initializeFields( ArgumentDefinition... args) { CompilerDirectives.transferToInterpreterAndInvalidate(); this.constructorFunction = buildConstructorFunction(localScope, assignments, varReads, args); - generateMethods(args); + generateQualifiedAccessor(); if (args.length == 0) { cachedInstance = new Atom(this); } else { @@ -154,13 +154,6 @@ private Function buildConstructorFunction( return new Function(callTarget, null, new FunctionSchema(args)); } - private void generateMethods(ArgumentDefinition[] args) { - generateQualifiedAccessor(); - // for (ArgumentDefinition arg : args) { - // definitionScope.registerMethod(this, arg.getName(), generateGetter(arg.getPosition())); - // } - } - private void generateQualifiedAccessor() { QualifiedAccessorNode node = new QualifiedAccessorNode(null, this); RootCallTarget callTarget = Truffle.getRuntime().createCallTarget(node); @@ -173,16 +166,6 @@ private void generateQualifiedAccessor() { definitionScope.registerMethod(definitionScope.getAssociatedType(), this.name, function); } - private Function generateGetter(int position) { - GetFieldNode node = new GetFieldNode(null, position); - RootCallTarget callTarget = Truffle.getRuntime().createCallTarget(node); - return new Function( - callTarget, - null, - new FunctionSchema( - new ArgumentDefinition(0, "self", ArgumentDefinition.ExecutionMode.EXECUTE))); - } - /** * Gets the name of the constructor. * diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index 0b6534515aa6..2b915323087b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -126,7 +126,9 @@ public void generateGetters(List constructors) { Arrays.stream(cons.getFields()) .forEach( field -> { - roots.put(field.getName(), new GetFieldNode(null, field.getPosition())); + roots.put( + field.getName(), + new GetFieldNode(null, field.getPosition(), this, field.getName())); }); } roots.forEach( diff --git a/test/Tests/src/Data/Text/Default_Regex_Engine_Spec.enso b/test/Tests/src/Data/Text/Default_Regex_Engine_Spec.enso index f4e2473078b7..02006c9a67eb 100644 --- a/test/Tests/src/Data/Text/Default_Regex_Engine_Spec.enso +++ b/test/Tests/src/Data/Text/Default_Regex_Engine_Spec.enso @@ -1,6 +1,6 @@ from Standard.Base import all -from Standard.Base.Data.Text.Regex import No_Such_Group_Error +from Standard.Base.Data.Text.Regex import No_Such_Group_Error_Data import Standard.Base.Data.Text.Regex.Engine.Default as Default_Engine import Standard.Base.Data.Text.Regex.Option as Global_Option @@ -34,8 +34,8 @@ spec = actual_mask . should_equal 0 Test.specify "should result in an error when an option is invalid" <| - Default_Engine.from_enso_options [""] . should_fail_with Default_Engine.Invalid_Option_Error - Default_Engine.from_enso_options ["", Global_Option.Ascii_Matching] . should_fail_with Default_Engine.Invalid_Option_Error + Default_Engine.from_enso_options [""] . should_fail_with Default_Engine.Invalid_Option_Error_Data + Default_Engine.from_enso_options ["", Global_Option.Ascii_Matching] . should_fail_with Default_Engine.Invalid_Option_Error_Data Test.group "The default regex engine (Default_Engine)" <| @@ -70,11 +70,11 @@ spec = Test.specify "should return a syntax error of the regex syntax is invalid" <| engine = Default_Engine.new - engine.compile "^(a" [] . should_fail_with Syntax_Error + engine.compile "^(a" [] . should_fail_with Syntax_Error_Data Test.specify "should throw an invalid options error if an option is invalid" <| engine = Default_Engine.new - engine.compile "^a$" ["invalid"] . should_fail_with Default_Engine.Invalid_Option_Error + engine.compile "^a$" ["invalid"] . should_fail_with Default_Engine.Invalid_Option_Error_Data Test.specify "should escape an expression for use as a literal" <| pattern = "http://example.com" @@ -106,7 +106,7 @@ spec = pattern = engine.compile "(.. .. )(?.+)()??(?)??" [] input = "aa ab abc a bc bcd" match = pattern.match input mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data match.group 0 . should_equal input Test.specify "should return `Nothing` if there are no matches in first mode" <| @@ -160,7 +160,7 @@ spec = pattern = engine.compile "(.. .. )(?.+)()??(?)??" [] input = "aa ab abc a bc bcd" match = pattern.match input mode=Regex_Mode.Full - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data match.group 0 . should_equal input Test.specify "should return `Nothing` if a full match does not match the entire input" <| @@ -169,7 +169,7 @@ spec = full_match = pattern.match input mode=Regex_Mode.Full full_match . should_equal Nothing match = pattern.match input mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data Test.specify "should be able to `match` the pattern against bounded input" <| pattern = engine.compile "(..)" [] @@ -454,7 +454,7 @@ spec = pattern = engine.compile "(.. .. )(?.+)()??(?)??" [] input = "aa ab abc a bc bcd" match = pattern.match input mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data Test.specify "should return the full match with index 0" <| match.group 0 . should_equal "aa ab abc a bc bcd" @@ -469,8 +469,8 @@ spec = match.group 3 . should_equal Nothing Test.specify "should fail with No_Such_Group_Error if the group did not exist" <| - match.group "fail" . should_fail_with No_Such_Group_Error - match.group 5 . should_fail_with No_Such_Group_Error + match.group "fail" . should_fail_with No_Such_Group_Error_Data + match.group 5 . should_fail_with No_Such_Group_Error_Data Test.specify "should make named groups accessible by index" <| match.group 2 . should_equal (match.group "letters") @@ -480,7 +480,7 @@ spec = pattern = engine.compile "(.. .. )(?.+)()??(?)??" [] input = "aa ab abc a bc bcd" match = pattern.match input mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data Test.specify "should return the results of all groups" <| groups = match.groups @@ -497,7 +497,7 @@ spec = pattern = engine.compile "(.. .. )(?.+)()??(?)??" [] input = "aa ab abc a bc bcd" match = pattern.match input mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data Test.specify "should return the results of all named groups" <| groups = match.named_groups @@ -516,7 +516,7 @@ spec = pattern = engine.compile "(.. .. )(?.+)()??(?)??" [] input = "aa ab abc a bc bcd" match = pattern.match input mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data Test.specify "should return the start of a group by index" <| match.start 1 . should_equal 0 @@ -529,15 +529,15 @@ spec = match.start "empty" . should_equal Nothing Test.specify "should return No_Such_Group_Error if the group doesn't exist" <| - match.start 5 . should_fail_with No_Such_Group_Error - match.start "nonexistent" . should_fail_with No_Such_Group_Error + match.start 5 . should_fail_with No_Such_Group_Error_Data + match.start "nonexistent" . should_fail_with No_Such_Group_Error_Data Test.group "Match.end" <| engine = Default_Engine.new pattern = engine.compile "(.. .. )(?.+)()??(?)??" [] input = "aa ab abc a bc bcd" match = pattern.match input mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data Test.specify "should return the end of a group by index" <| match.end 1 . should_equal 6 @@ -550,36 +550,36 @@ spec = match.end "empty" . should_equal Nothing Test.specify "should return No_Such_Group_Error if the group doesn't exist" <| - match.end 5 . should_fail_with No_Such_Group_Error - match.end "nonexistent" . should_fail_with No_Such_Group_Error + match.end 5 . should_fail_with No_Such_Group_Error_Data + match.end "nonexistent" . should_fail_with No_Such_Group_Error_Data Test.group "Match.span" <| engine = Default_Engine.new pattern = engine.compile "(.. .. )(?.+)()??(?)??" [] input = "aa ab abc a bc bcd" match = pattern.match input mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data Test.specify "should get the span of a group by index" <| - match.span 1 . should_equal (Utf_16_Span (Range 0 6) input) + match.span 1 . should_equal (Utf_16_Span_Data (Range_Data 0 6) input) Test.specify "should get the span of a group by name" <| - match.span "letters" . should_equal (Utf_16_Span (Range 6 18) input) + match.span "letters" . should_equal (Utf_16_Span_Data (Range_Data 6 18) input) Test.specify "should return Nothing if the group didn't match" <| match.span 3 . should_equal Nothing match.span "empty" . should_equal Nothing Test.specify "should fail with a No_Such_Group_Error if the group doesn't exist" <| - match.span 5 . should_fail_with No_Such_Group_Error - match.span "nonexistent" . should_fail_with No_Such_Group_Error + match.span 5 . should_fail_with No_Such_Group_Error_Data + match.span "nonexistent" . should_fail_with No_Such_Group_Error_Data Test.group "Match.start_position" <| engine = Default_Engine.new pattern = engine.compile "(.. .. )(?.+)()??(?)??" [] input = "aa ab abc a bc bcd" match = pattern.match input mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data Test.specify "should return the region start over which self match was performed" <| match.start_position . should_equal 0 @@ -589,7 +589,7 @@ spec = pattern = engine.compile "(.. .. )(?.+)()??(?)??" [] input = "aa ab abc a bc bcd" match = pattern.match input mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data Test.specify "should return the region end over which self match was performed" <| match.end_position . should_equal 18 diff --git a/test/Tests/src/Data/Text/Encoding_Spec.enso b/test/Tests/src/Data/Text/Encoding_Spec.enso index 0094d4c96439..0285586be5fa 100644 --- a/test/Tests/src/Data/Text/Encoding_Spec.enso +++ b/test/Tests/src/Data/Text/Encoding_Spec.enso @@ -16,7 +16,7 @@ spec = Test.specify "Catches invalid character sets" <| invalid = Encoding_Data "NotAValidCharacterSet" - invalid.to_java_charset . should_fail_with Illegal_Argument_Error + invalid.to_java_charset . should_fail_with Illegal_Argument_Error_Data Test.specify "Can get full set of character sets" <| character_sets = all_character_sets diff --git a/test/Tests/src/Data/Text/Matching_Spec.enso b/test/Tests/src/Data/Text/Matching_Spec.enso index 6f43c8f17a61..934f9f3f6d3e 100644 --- a/test/Tests/src/Data/Text/Matching_Spec.enso +++ b/test/Tests/src/Data/Text/Matching_Spec.enso @@ -7,70 +7,70 @@ type Foo_Error spec = Test.group 'Matching Helper' <| Test.specify 'should match a single name with a single Text_Matcher criterion' <| - Text_Matcher.match_single_criterion "foo" "foo" . should_be_true - Text_Matcher.match_single_criterion "foobar" "foo" . should_be_false - Text_Matcher.match_single_criterion "foo" "f.*" . should_be_false - Text_Matcher.match_single_criterion "foo" "Foo" . should_be_false + Text_Matcher_Data.match_single_criterion "foo" "foo" . should_be_true + Text_Matcher_Data.match_single_criterion "foobar" "foo" . should_be_false + Text_Matcher_Data.match_single_criterion "foo" "f.*" . should_be_false + Text_Matcher_Data.match_single_criterion "foo" "Foo" . should_be_false - Test.specify 'should correctly handle Unicode folding with Text_Matcher matching' <| - Text_Matcher.match_single_criterion '\u00E9' '\u0065\u{301}' . should_be_true - Text_Matcher.match_single_criterion 'é' '\u00E9' . should_be_true - Text_Matcher.match_single_criterion 'é' 'ę' . should_be_false + Test.specify 'should correctly handle Unicode folding with Text_Matcher_Data matching' <| + Text_Matcher_Data.match_single_criterion '\u00E9' '\u0065\u{301}' . should_be_true + Text_Matcher_Data.match_single_criterion 'é' '\u00E9' . should_be_true + Text_Matcher_Data.match_single_criterion 'é' 'ę' . should_be_false Test.specify 'should match a single name with a single regex criterion' <| - Regex_Matcher.match_single_criterion "foo" "foo" . should_be_true - Regex_Matcher.match_single_criterion "foobar" "foo" . should_be_false - Regex_Matcher.match_single_criterion "foo" "f.*" . should_be_true - Regex_Matcher.match_single_criterion "foo" "foo.*" . should_be_true - Regex_Matcher.match_single_criterion "foo" "F.*" . should_be_false + Regex_Matcher_Data.match_single_criterion "foo" "foo" . should_be_true + Regex_Matcher_Data.match_single_criterion "foobar" "foo" . should_be_false + Regex_Matcher_Data.match_single_criterion "foo" "f.*" . should_be_true + Regex_Matcher_Data.match_single_criterion "foo" "foo.*" . should_be_true + Regex_Matcher_Data.match_single_criterion "foo" "F.*" . should_be_false Test.specify 'should support case-insensitive matching' <| - (Regex_Matcher case_sensitive=Case_Insensitive).match_single_criterion "foo" "F.*" . should_be_true - (Text_Matcher case_sensitive=Case_Insensitive).match_single_criterion "foO" "FOo" . should_be_true + (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data).match_single_criterion "foo" "F.*" . should_be_true + (Text_Matcher_Data case_sensitive=Case_Insensitive_Data).match_single_criterion "foO" "FOo" . should_be_true - (Regex_Matcher case_sensitive=Case_Insensitive).match_single_criterion "foo" "fF.*" . should_be_false - (Text_Matcher case_sensitive=Case_Insensitive).match_single_criterion "foo" "Foos" . should_be_false + (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data).match_single_criterion "foo" "fF.*" . should_be_false + (Text_Matcher_Data case_sensitive=Case_Insensitive_Data).match_single_criterion "foo" "Foos" . should_be_false # Small beta is equal to capital 'beta' which looks the same as capital 'b' but is a different symbol. - (Text_Matcher case_sensitive=Case_Insensitive).match_single_criterion "β" "Β" . should_be_true - (Text_Matcher case_sensitive=Case_Insensitive).match_single_criterion "β" "B" . should_be_false + (Text_Matcher_Data case_sensitive=Case_Insensitive_Data).match_single_criterion "β" "Β" . should_be_true + (Text_Matcher_Data case_sensitive=Case_Insensitive_Data).match_single_criterion "β" "B" . should_be_false Test.specify 'should match a list of names with a list of criteria, correctly handling reordering' <| - Text_Matcher.match_criteria ["foo", "bar", "baz"] ["baz", "foo"] reorder=True . should_equal ["baz", "foo"] - Text_Matcher.match_criteria ["foo", "bar", "baz"] ["baz", "foo"] reorder=False . should_equal ["foo", "baz"] + Text_Matcher_Data.match_criteria ["foo", "bar", "baz"] ["baz", "foo"] reorder=True . should_equal ["baz", "foo"] + Text_Matcher_Data.match_criteria ["foo", "bar", "baz"] ["baz", "foo"] reorder=False . should_equal ["foo", "baz"] Test.specify 'should allow multiple matches to a single criterion (Regex)' <| - Regex_Matcher.match_criteria ["foo", "bar", "baz", "quux"] ["b.*"] reorder=True . should_equal ["bar", "baz"] - Regex_Matcher.match_criteria ["foo", "bar", "baz", "quux"] ["b.*", "foo"] reorder=False . should_equal ["foo", "bar", "baz"] + Regex_Matcher_Data.match_criteria ["foo", "bar", "baz", "quux"] ["b.*"] reorder=True . should_equal ["bar", "baz"] + Regex_Matcher_Data.match_criteria ["foo", "bar", "baz", "quux"] ["b.*", "foo"] reorder=False . should_equal ["foo", "bar", "baz"] Test.specify 'should include the object only with the first criterion that matched it, avoiding duplication' <| - Regex_Matcher.match_criteria ["foo", "bar", "baz", "zap"] [".*z.*", "b.*"] reorder=True . should_equal ["baz", "zap", "bar"] - Regex_Matcher.match_criteria ["foo", "bar", "baz", "zap"] [".*z.*", "b.*"] reorder=False . should_equal ["bar", "baz", "zap"] + Regex_Matcher_Data.match_criteria ["foo", "bar", "baz", "zap"] [".*z.*", "b.*"] reorder=True . should_equal ["baz", "zap", "bar"] + Regex_Matcher_Data.match_criteria ["foo", "bar", "baz", "zap"] [".*z.*", "b.*"] reorder=False . should_equal ["bar", "baz", "zap"] Test.specify 'should correctly handle criteria which did not match anything' <| - action = Text_Matcher.match_criteria ["foo", "bar", "baz"] ["baz", "unknown_column"] reorder=True on_problems=_ + action = Text_Matcher_Data.match_criteria ["foo", "bar", "baz"] ["baz", "unknown_column"] reorder=True on_problems=_ tester = _.should_equal ["baz"] - problems = [No_Matches_Found ["unknown_column"]] + problems = [No_Matches_Found_Data ["unknown_column"]] Problems.test_problem_handling action problems tester - action_2 = Text_Matcher.match_criteria ["foo", "bar", "baz"] ["baz", "unknown_column_1", "unknown_column_2"] reorder=False on_problems=_ - problems_2 = [No_Matches_Found ["unknown_column_1", "unknown_column_2"]] + action_2 = Text_Matcher_Data.match_criteria ["foo", "bar", "baz"] ["baz", "unknown_column_1", "unknown_column_2"] reorder=False on_problems=_ + problems_2 = [No_Matches_Found_Data ["unknown_column_1", "unknown_column_2"]] Problems.test_problem_handling action_2 problems_2 tester Test.specify 'should correctly work with complex object using a function extracting their names' <| - pairs = [Pair "foo" 42, Pair "bar" 33, Pair "baz" 10, Pair "foo" 0, Pair 10 10] - selected = [Pair "bar" 33, Pair "foo" 42, Pair "foo" 0] - Text_Matcher.match_criteria pairs ["bar", "foo"] reorder=True name_mapper=_.first . should_equal selected + pairs = [Pair_Data "foo" 42, Pair_Data "bar" 33, Pair_Data "baz" 10, Pair_Data "foo" 0, Pair_Data 10 10] + selected = [Pair_Data "bar" 33, Pair_Data "foo" 42, Pair_Data "foo" 0] + Text_Matcher_Data.match_criteria pairs ["bar", "foo"] reorder=True name_mapper=_.first . should_equal selected - Text_Matcher.match_criteria [1, 2, 3] ["2"] name_mapper=_.to_text . should_equal [2] + Text_Matcher_Data.match_criteria [1, 2, 3] ["2"] name_mapper=_.to_text . should_equal [2] Test.specify 'should correctly forward errors' <| - Text_Matcher.match_criteria (Error.throw Foo_Error) [] . should_fail_with Foo_Error - Text_Matcher.match_criteria [] (Error.throw Foo_Error) . should_fail_with Foo_Error + Text_Matcher_Data.match_criteria (Error.throw Foo_Error) [] . should_fail_with Foo_Error + Text_Matcher_Data.match_criteria [] (Error.throw Foo_Error) . should_fail_with Foo_Error (Error.throw Foo_Error).match_criteria [] [] . should_fail_with Foo_Error - Text_Matcher.match_criteria [1, 2, 3] ["2"] name_mapper=(x-> if x == 3 then Error.throw Foo_Error else x.to_text) . should_fail_with Foo_Error + Text_Matcher_Data.match_criteria [1, 2, 3] ["2"] name_mapper=(x-> if x == 3 then Error.throw Foo_Error else x.to_text) . should_fail_with Foo_Error - Test.expect_panic_with matcher=No_Such_Method_Error <| - Text_Matcher.match_criteria ["a"] ["a"] name_mapper=_.nonexistent_function + Test.expect_panic_with matcher=No_Such_Method_Error_Data <| + Text_Matcher_Data.match_criteria ["a"] ["a"] name_mapper=_.nonexistent_function main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Text/Regex_Spec.enso b/test/Tests/src/Data/Text/Regex_Spec.enso index c8d4b248cd39..3e55f64113ae 100644 --- a/test/Tests/src/Data/Text/Regex_Spec.enso +++ b/test/Tests/src/Data/Text/Regex_Spec.enso @@ -19,7 +19,7 @@ spec = Test.group "Regexes" <| Test.specify "should be able to be compiled" <| pattern = Regex.compile "(?..)" case_insensitive=True - pattern . should_be_a Default_Engine.Pattern + pattern . should_be_a Default_Engine.Pattern_Data pattern.options . should_equal [Option.Case_Insensitive] Test.specify "should be able to be escaped" <| diff --git a/test/Tests/src/Main.enso b/test/Tests/src/Main.enso index d1da63d25fc0..2b9cd5f08a2c 100644 --- a/test/Tests/src/Main.enso +++ b/test/Tests/src/Main.enso @@ -10,7 +10,7 @@ import project.Semantic.Error_Spec import project.Semantic.Import_Loop.Spec as Import_Loop_Spec import project.Semantic.Meta_Spec import project.Semantic.Names_Spec -#import project.Semantic.Runtime_Spec +import project.Semantic.Runtime_Spec #import project.Semantic.Warnings_Spec import project.Semantic.Java_Interop_Spec @@ -42,12 +42,12 @@ import project.Data.Statistics_Spec #import project.Data.Regression_Spec #import project.Data.Text_Spec -#import project.Data.Text.Codepoint_Ranges_Spec -#import project.Data.Text.Default_Regex_Engine_Spec -#import project.Data.Text.Encoding_Spec -#import project.Data.Text.Matching_Spec -#import project.Data.Text.Regex_Spec -#import project.Data.Text.Span_Spec +import project.Data.Text.Codepoint_Ranges_Spec +import project.Data.Text.Default_Regex_Engine_Spec +import project.Data.Text.Encoding_Spec +import project.Data.Text.Matching_Spec +import project.Data.Text.Regex_Spec +import project.Data.Text.Span_Spec #import project.Data.Text.Utils_Spec import project.Network.Http.Header_Spec as Http_Header_Spec @@ -55,10 +55,10 @@ import project.Network.Http.Request_Spec as Http_Request_Spec import project.Network.Http_Spec import project.Network.URI_Spec -#import project.Resource.Bracket_Spec +import project.Resource.Bracket_Spec #import project.Runtime.Stack_Traces_Spec -#import project.Runtime.Lazy_Generator_Spec +import project.Runtime.Lazy_Generator_Spec import project.System.Environment_Spec import project.System.File_Spec @@ -108,15 +108,15 @@ main = Test.Suite.run_main <| R_Interop_Spec.spec Range_Spec.spec Ref_Spec.spec - #Default_Regex_Engine_Spec.spec - #Regex_Spec.spec - #Matching_Spec.spec - #Runtime_Spec.spec - #Span_Spec.spec - #Encoding_Spec.spec - #Codepoint_Ranges_Spec.spec - #Bracket_Spec.spec - #Lazy_Generator_Spec.spec + Default_Regex_Engine_Spec.spec + Regex_Spec.spec + Matching_Spec.spec + Runtime_Spec.spec + Span_Spec.spec + Encoding_Spec.spec + Codepoint_Ranges_Spec.spec + Bracket_Spec.spec + Lazy_Generator_Spec.spec #Stack_Traces_Spec.spec #Utils_Spec.spec #Text_Spec.spec From 4730eeed9fe8a8fb4380412b04c265bf57bcf59b Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 17 Aug 2022 11:18:12 +0200 Subject: [PATCH 052/110] progress --- .../0.0.0-dev/src/Data/Text/Extensions.enso | 4 +- .../0.0.0-dev/src/Data/Text/Regex/Mode.enso | 9 +- .../src/Data/Text/Text_Sub_Range.enso | 6 +- test/Tests/src/Data/Text/Utils_Spec.enso | 6 +- test/Tests/src/Data/Text_Spec.enso | 754 +++++++++--------- test/Tests/src/Main.enso | 12 +- test/Tests/src/Runtime/Stack_Traces_Spec.enso | 2 +- 7 files changed, 395 insertions(+), 398 deletions(-) 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 59e1ca0c9e09..45899250c1cf 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 @@ -361,7 +361,7 @@ Text.find self pattern mode=Mode.All match_ascii=Nothing case_insensitive=Nothin 'abc def\tghi'.split '\\s+' Regex_Matcher == ["abc", "def", "ghi"] Text.split : Text -> (Text_Matcher | Regex_Matcher) -> Vector.Vector Text -Text.split self delimiter="," matcher=Text_Matcher_Data = if delimiter.is_empty then Error.throw (Illegal_Argument_Error "The delimiter cannot be empty.") else +Text.split self delimiter="," matcher=Text_Matcher_Data = if delimiter.is_empty then Error.throw (Illegal_Argument_Error_Data "The delimiter cannot be empty.") else case matcher of Text_Matcher_Data case_sensitivity -> delimiters = Vector.Vector_Data <| case case_sensitivity of @@ -1223,7 +1223,7 @@ Text.to_case self case_option=Case.Lower locale=Locale.default = case case_optio Text.pad : Integer -> Text -> (Location.Start | Location.End) -> Text Text.pad self length=0 with_pad=' ' at=Location.End = with_pad_length = with_pad.length - if with_pad_length == 0 then Error.throw (Illegal_Argument_Error "`with_pad` must not be an empty string.") else + if with_pad_length == 0 then Error.throw (Illegal_Argument_Error_Data "`with_pad` must not be an empty string.") else pad_size = length - self.length if pad_size <= 0 then self else full_repetitions = pad_size.div with_pad_length diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Mode.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Mode.enso index 31c9b5bf2aae..facf748df354 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Mode.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Regex/Mode.enso @@ -4,15 +4,10 @@ to matching on the `Full` content of the input text. from Standard.Base import all +from Standard.Base.Data.Text.Matching_Mode import First, Last +from Standard.Base.Data.Text.Matching_Mode export First, Last type Mode - - ## The regex will only match the first instance it finds. - First - - ## The regex will match up to some `Integer` number of instances. - Integer - ## The regex will make all possible matches. All diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso index 76b6464dced8..be9a0f4e3fc3 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Text/Text_Sub_Range.enso @@ -92,7 +92,7 @@ find_codepoint_ranges text subrange = indices = Random.random_indices text.length count rng find_codepoint_ranges text (By_Index indices) Every step start -> - if step <= 0 then Error.throw (Illegal_Argument_Error "Step within Every must be positive.") else + if step <= 0 then Error.throw (Illegal_Argument_Error_Data "Step within Every must be positive.") else len = text.length if start >= len then Range_Data 0 0 else range = Range_Data start text.length step @@ -233,7 +233,7 @@ batch_resolve_indices_or_ranges text descriptors = Panic.recover [Index_Out_Of_B ## PRIVATE panic_on_non_positive_step = - Panic.throw (Illegal_Argument_Error "Range step must be positive.") + Panic.throw (Illegal_Argument_Error_Data "Range step must be positive.") ## PRIVATE Ensures that the range is valid and trims it to the length of the collection. @@ -241,7 +241,7 @@ normalize_range range length = if range.step <= 0 then panic_on_non_positive_step # We may add support for negative indices in the future. if (range.start < 0) || (range.end < 0) then - Panic.throw (Illegal_Argument_Error "Ranges with negative indices are not supported for indexing.") + Panic.throw (Illegal_Argument_Error_Data "Ranges with negative indices are not supported for indexing.") if (range.start >= length) then Panic.throw (Index_Out_Of_Bounds_Error_Data range.start length) if range.end >= length then Range_Data range.start length range.step else diff --git a/test/Tests/src/Data/Text/Utils_Spec.enso b/test/Tests/src/Data/Text/Utils_Spec.enso index a59dc6497453..3132827e2d4c 100644 --- a/test/Tests/src/Data/Text/Utils_Spec.enso +++ b/test/Tests/src/Data/Text/Utils_Spec.enso @@ -36,7 +36,7 @@ spec = Test.specify "should correctly translate a series of codepoint indices to a grapheme indices in a batch" <| translate_indices text ixes = - Vector.Vector <| Text_Utils.utf16_indices_to_grapheme_indices text ixes.to_array + Vector.Vector_Data <| Text_Utils.utf16_indices_to_grapheme_indices text ixes.to_array codepoint_indices = Vector.new text.char_vector.length ix->ix translate_indices text codepoint_indices . should_equal codepoints_to_graphemes @@ -55,7 +55,7 @@ spec = folded.findGrapheme ix . index grapheme_ixes . should_equal [0, 0, 1, 2, 3, 3, 4, 4, 4, 5, 6] - Test.expect_panic_with (folded.findGrapheme -1) Polyglot_Error - Test.expect_panic_with (folded.findGrapheme folded.getFoldedString.char_vector.length+1) Polyglot_Error + Test.expect_panic_with (folded.findGrapheme -1) Polyglot_Error_Data + Test.expect_panic_with (folded.findGrapheme folded.getFoldedString.char_vector.length+1) Polyglot_Error_Data main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Text_Spec.enso b/test/Tests/src/Data/Text_Spec.enso index 621ea14d3f17..af53f57cfd66 100644 --- a/test/Tests/src/Data/Text_Spec.enso +++ b/test/Tests/src/Data/Text_Spec.enso @@ -1,15 +1,17 @@ from Standard.Base import all -from Standard.Base.Data.Text.Extensions import Index_Out_Of_Bounds_Error +from Standard.Base.Data.Text.Extensions import Index_Out_Of_Bounds_Error_Data import Standard.Base.Data.Text.Regex.Engine.Default as Default_Engine from Standard.Base.Data.Text.Text_Sub_Range import all import Standard.Test -type Auto a +type Auto + Auto_Data a -type Manual b +type Manual + Manual_Data b Manual.to_text self = "[[[MyREP " + self.b.to_text + "]]]" @@ -43,7 +45,7 @@ Manual.to_text self = "[[[MyREP " + self.b.to_text + "]]]" - Casing is locale-dependent. The pair of `i - I` is handled differently in Turkish and Azerbaijani - instead there are two separate pairs: 'İ - i' and 'I - ı'. - - Handling of out of range indices should be checked. In particular, often + - Handling of out of range_Data indices should be checked. In particular, often the index `text.length` should still be valid to point just right at the end of the text. Moreover, negative indices are usually allowed to index from the back. @@ -152,10 +154,10 @@ spec = Test.specify "should return a dataflow error when accessing characters out of bounds" <| str = kshi + facepalm + accent_1 + accent_2 - str.at -5 . should_fail_with Index_Out_Of_Bounds_Error - str.at -5 . catch . should_equal (Index_Out_Of_Bounds_Error -5 4) - str.at 4 . should_fail_with Index_Out_Of_Bounds_Error - str.at 4 . catch . should_equal (Index_Out_Of_Bounds_Error 4 4) + str.at -5 . should_fail_with Index_Out_Of_Bounds_Error_Data + str.at -5 . catch . should_equal (Index_Out_Of_Bounds_Error_Data -5 4) + str.at 4 . should_fail_with Index_Out_Of_Bounds_Error_Data + str.at 4 . catch . should_equal (Index_Out_Of_Bounds_Error_Data 4 4) Test.specify "should be able to split the text into words" <| "I have not one, but two cats.".words . should_equal ['I', 'have', 'not', 'one', ',', 'but', 'two', 'cats', '.'] @@ -201,37 +203,37 @@ spec = "".split "." . should_equal [""] "abc[a-z]def".split "[a-z]" . should_equal ["abc", "def"] 'aśbs\u{301}c'.split 'ś' . should_equal ['a', 'b', 'c'] - 'abc'.split '' . should_fail_with Illegal_Argument_Error + 'abc'.split '' . should_fail_with Illegal_Argument_Error_Data Test.specify "should be able to split the text on arbitrary text sequence, case-insensitively" <| - matcher = Text_Matcher Case_Insensitive + matcher = Text_Matcher_Data Case_Insensitive_Data "AbCdABCDabDCba" . split "ab" matcher . should_equal ["", "Cd", "CD", "DCba"] "abc".split "d" matcher . should_equal ["abc"] "AAA".split "a" matcher . should_equal ["", "", "", ""] "baB".split "b" matcher . should_equal ["", "a", ""] "".split "a" matcher . should_equal [""] 'aŚbS\u{301}c'.split 'ś' matcher . should_equal ['a', 'b', 'c'] - 'abc'.split '' matcher . should_fail_with Illegal_Argument_Error + 'abc'.split '' matcher . should_fail_with Illegal_Argument_Error_Data Test.specify "should be able to split the text on Regex patterns" <| - "cababdabe" . split "ab" Regex_Matcher . should_equal ["c", "", "d", "e"] - "cababdabe" . split "(ab)+" Regex_Matcher . should_equal ["c", "d", "e"] - "abc" . split "[a-z]" Regex_Matcher . should_equal ["", "", "", ""] - "abc--def==>ghi".split "[-=>]+" Regex_Matcher == ["abc", "def", "ghi"] - "abc".split "." Regex_Matcher . should_equal ["", "", "", ""] - "abc".split "d" Regex_Matcher . should_equal ["abc"] - ".a.".split "\." Regex_Matcher . should_equal ["", "a", ""] - "".split "a" Regex_Matcher . should_equal [""] - 'aśbs\u{301}c'.split 'ś' Regex_Matcher . should_equal ['a', 'b', 'c'] - 'abc'.split '' Regex_Matcher . should_fail_with Illegal_Argument_Error + "cababdabe" . split "ab" Regex_Matcher_Data . should_equal ["c", "", "d", "e"] + "cababdabe" . split "(ab)+" Regex_Matcher_Data . should_equal ["c", "d", "e"] + "abc" . split "[a-z]" Regex_Matcher_Data . should_equal ["", "", "", ""] + "abc--def==>ghi".split "[-=>]+" Regex_Matcher_Data == ["abc", "def", "ghi"] + "abc".split "." Regex_Matcher_Data . should_equal ["", "", "", ""] + "abc".split "d" Regex_Matcher_Data . should_equal ["abc"] + ".a.".split "\." Regex_Matcher_Data . should_equal ["", "a", ""] + "".split "a" Regex_Matcher_Data . should_equal [""] + 'aśbs\u{301}c'.split 'ś' Regex_Matcher_Data . should_equal ['a', 'b', 'c'] + 'abc'.split '' Regex_Matcher_Data . should_fail_with Illegal_Argument_Error_Data Test.specify "should be able to split the text on UTF-8 whitespace" <| - utf_8_whitespace.split "\s+" Regex_Matcher . should_equal utf_8_whitespace_split - 'abc def\tghi'.split '\\s+' Regex_Matcher . should_equal ["abc", "def", "ghi"] + utf_8_whitespace.split "\s+" Regex_Matcher_Data . should_equal utf_8_whitespace_split + 'abc def\tghi'.split '\\s+' Regex_Matcher_Data . should_equal ["abc", "def", "ghi"] Test.specify "should convert any type to text automatically and using provided methods" <| - t = Auto (Manual 123) . to_text - t.should_equal "(Auto [[[MyREP 123]]])" + t = Auto_Data (Manual_Data 123) . to_text + t.should_equal "(Auto_Data [[[MyREP 123]]])" Test.specify "should escape special characters when debug-printing text" <| text_1 = ''' @@ -285,29 +287,29 @@ spec = Test.specify "should allow taking or dropping many indices or subranges (possibly overlapping)" <| "123"*1000 . take (By_Index (Vector.new 3000 ix-> 2999-ix)) . should_equal "321"*1000 "123"*1000 . take (By_Index (Vector.new 3000 _-> 0)) . should_equal "1"*3000 - "123456"*1000 . take (By_Index (Vector.new 100 ix-> Range 6*ix+1 6*ix+3)) . should_equal "23"*100 - "AB"*1000 . take (By_Index (Vector.new 100 ix-> Range ix+1 ix+5)) . should_equal "BABAABAB"*50 + "123456"*1000 . take (By_Index (Vector.new 100 ix-> Range_Data 6*ix+1 6*ix+3)) . should_equal "23"*100 + "AB"*1000 . take (By_Index (Vector.new 100 ix-> Range_Data ix+1 ix+5)) . should_equal "BABAABAB"*50 "123"*1000 . drop (By_Index (Vector.new 300 ix-> 2999-ix)) . should_equal "123"*900 "123"*1000 . drop (By_Index (Vector.new 3000 _-> 0)) . should_equal "23"+"123"*999 - "123456"*1000 . drop (By_Index (Vector.new 1000 ix-> Range 6*ix+1 6*ix+3)) . should_equal "1456"*1000 - "ABCD"*25 . drop (By_Index (Vector.new 90 ix-> Range ix+1 ix+5)) . should_equal "ACDABCD" + "123456"*1000 . drop (By_Index (Vector.new 1000 ix-> Range_Data 6*ix+1 6*ix+3)) . should_equal "1456"*1000 + "ABCD"*25 . drop (By_Index (Vector.new 90 ix-> Range_Data ix+1 ix+5)) . should_equal "ACDABCD" - "ABCD"*1000 . take (Range 0 4000 4) . should_equal "A"*1000 + "ABCD"*1000 . take (Range_Data 0 4000 4) . should_equal "A"*1000 "ABCD"*1000 . take (Every 4) . should_equal "A"*1000 - "ABCD"*1000 . take (By_Index [Range 0 4000 4, Range 1 4000 4]) . should_equal ("A"*1000 + "B"*1000) - "ABCD"*1000 . take (By_Index [Range 0 4000 4, Range 2 4000 4]) . should_equal ("A"*1000 + "C"*1000) + "ABCD"*1000 . take (By_Index [Range_Data 0 4000 4, Range_Data 1 4000 4]) . should_equal ("A"*1000 + "B"*1000) + "ABCD"*1000 . take (By_Index [Range_Data 0 4000 4, Range_Data 2 4000 4]) . should_equal ("A"*1000 + "C"*1000) - "ABCD"*1000 . drop (Range 0 4000 4) . should_equal "BCD"*1000 + "ABCD"*1000 . drop (Range_Data 0 4000 4) . should_equal "BCD"*1000 "ABCD"*1000 . drop (Every 4) . should_equal "BCD"*1000 - "ABCD"*1000 . drop (By_Index [Range 0 4000 4, Range 1 4000 4]) . should_equal "CD"*1000 - "ABCD"*1000 . drop (By_Index [Range 0 4000 4, Range 2 4000 4]) . should_equal "BD"*1000 + "ABCD"*1000 . drop (By_Index [Range_Data 0 4000 4, Range_Data 1 4000 4]) . should_equal "CD"*1000 + "ABCD"*1000 . drop (By_Index [Range_Data 0 4000 4, Range_Data 2 4000 4]) . should_equal "BD"*1000 - "0123456789".take (By_Index [Range 0 4, Range 4 6, Range 8 9]) . should_equal "0123458" - "0123456789".take (By_Index [Range 4 6, Range 0 4, 0, 0]) . should_equal "45012300" - "0123456789".drop (By_Index [Range 0 4, Range 4 6, Range 8 9]) . should_equal "679" - "0123456789".drop (By_Index [Range 4 6, Range 0 4, 0, 0]) . should_equal "6789" - "0123456789".drop (By_Index [Range 2 5, Range 0 3, 0, 0]) . should_equal "56789" + "0123456789".take (By_Index [Range_Data 0 4, Range_Data 4 6, Range_Data 8 9]) . should_equal "0123458" + "0123456789".take (By_Index [Range_Data 4 6, Range_Data 0 4, 0, 0]) . should_equal "45012300" + "0123456789".drop (By_Index [Range_Data 0 4, Range_Data 4 6, Range_Data 8 9]) . should_equal "679" + "0123456789".drop (By_Index [Range_Data 4 6, Range_Data 0 4, 0, 0]) . should_equal "6789" + "0123456789".drop (By_Index [Range_Data 2 5, Range_Data 0 3, 0, 0]) . should_equal "56789" Test.specify "should allow selecting substrings by characters" <| txt = kshi + facepalm + accent_1 + accent_2 @@ -315,15 +317,15 @@ spec = txt.drop (First 2) . should_equal (accent_1 + accent_2) txt.take (Last 2) . should_equal (accent_1 + accent_2) txt.drop (Last 2) . should_equal (kshi + facepalm) - txt.take (Range 0 2) . should_equal (kshi + facepalm) - txt.take (By_Index (Range 0 2)) . should_equal (kshi + facepalm) - txt.drop (Range 0 2) . should_equal (accent_1 + accent_2) - txt.take (Range 2 4) . should_equal (accent_1 + accent_2) - txt.drop (Range 2 4) . should_equal (kshi + facepalm) + txt.take (Range_Data 0 2) . should_equal (kshi + facepalm) + txt.take (By_Index (Range_Data 0 2)) . should_equal (kshi + facepalm) + txt.drop (Range_Data 0 2) . should_equal (accent_1 + accent_2) + txt.take (Range_Data 2 4) . should_equal (accent_1 + accent_2) + txt.drop (Range_Data 2 4) . should_equal (kshi + facepalm) txt.take (Every 2) . should_equal (kshi + accent_1) txt.take (Every 2 first=1) . should_equal (facepalm + accent_2) txt.drop (Every 2) . should_equal (facepalm + accent_2) - txt.take (Range 0 4 2) . should_equal (kshi + accent_1) + txt.take (Range_Data 0 4 2) . should_equal (kshi + accent_1) txt.take (By_Index [0, 3]) . should_equal (kshi + accent_2) txt.take (By_Index 0) . should_equal kshi txt.take (By_Index 1) . should_equal facepalm @@ -333,8 +335,8 @@ spec = txt.drop (By_Index [0, 3, 0]) . should_equal (facepalm + accent_1) txt.drop (By_Index [0, 3, 0, 2, 1]) . should_equal "" txt.take (By_Index [0, 3, 0, 2, 1]) . should_equal (kshi + accent_2 + kshi + accent_1 + facepalm) - txt.take (By_Index [0, 0, Range 0 2]) . should_equal (kshi + kshi + kshi + facepalm) - txt.drop (By_Index [Range 2 4, Range 0 2]) . should_equal "" + txt.take (By_Index [0, 0, Range_Data 0 2]) . should_equal (kshi + kshi + kshi + facepalm) + txt.drop (By_Index [Range_Data 2 4, Range_Data 0 2]) . should_equal "" Test.specify "take should work as in the examples" <| "Hello World!".take First . should_equal "H" @@ -355,45 +357,45 @@ spec = "Hello World!".take (After_Last "z") . should_equal "" "Hello World!".take (While c->c!=" ") . should_equal "Hello" "Hello World!".take (While c->c!="z") . should_equal "Hello World!" - "Hello World!".take (Range 3 5) . should_equal "lo" - "Hello World!".take (Range 5 12) . should_equal " World!" - "Hello World!".take (Range 6 12 2) . should_equal "Wrd" + "Hello World!".take (Range_Data 3 5) . should_equal "lo" + "Hello World!".take (Range_Data 5 12) . should_equal " World!" + "Hello World!".take (Range_Data 6 12 2) . should_equal "Wrd" "Hello World!".take (Every 2 first=6) . should_equal "Wrd" "Hello World!".take (Every 3) . should_equal "HlWl" "Hello World!".take (By_Index 0) . should_equal "H" "Hello World!".take (By_Index [1, 0, 0, 6, 0]) . should_equal "eHHWH" - "Hello World!".take (By_Index [Range 0 3, 6, Range 6 12 2]) . should_equal "HelWWrd" + "Hello World!".take (By_Index [Range_Data 0 3, 6, Range_Data 6 12 2]) . should_equal "HelWWrd" "Hello World!".take (Sample 3 seed=42) . should_equal "l d" Test.specify "take should report errors for start indices out of bounds but just go till the end if the end index is OOB" <| txt = "Hello World!" - txt.take (Range 0 14) . should_equal txt - txt.take (Range 6 100) . should_equal "World!" - txt.take (Range txt.length-1 txt.length) . should_equal "!" - txt.take (Range txt.length txt.length) . should_fail_with Index_Out_Of_Bounds_Error - txt.take (Range txt.length txt.length) . catch . should_equal (Index_Out_Of_Bounds_Error txt.length txt.length) - txt.take (Range txt.length 100) . should_fail_with Index_Out_Of_Bounds_Error + txt.take (Range_Data 0 14) . should_equal txt + txt.take (Range_Data 6 100) . should_equal "World!" + txt.take (Range_Data txt.length-1 txt.length) . should_equal "!" + txt.take (Range_Data txt.length txt.length) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.take (Range_Data txt.length txt.length) . catch . should_equal (Index_Out_Of_Bounds_Error_Data txt.length txt.length) + txt.take (Range_Data txt.length 100) . should_fail_with Index_Out_Of_Bounds_Error_Data txt.take (First 100) . should_equal txt txt.take (Last 100) . should_equal txt - txt.take (By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error - txt.take (By_Index 13) . should_fail_with Index_Out_Of_Bounds_Error - txt.take (By_Index [0, 1, 13]) . should_fail_with Index_Out_Of_Bounds_Error - txt.take (By_Index [0, Range 14 15, 1]) . should_fail_with Index_Out_Of_Bounds_Error - txt.take (By_Index [0, 1, Range 6 100]) . should_equal "HeWorld!" - txt.take (By_Index [0, 1, Range 6 100 2]) . should_equal "HeWrd" - txt.take (Range 13 12) . should_fail_with Index_Out_Of_Bounds_Error - "".take (Range 0 0) . should_fail_with Index_Out_Of_Bounds_Error - "".take (Range 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error 0 0) - "".take (By_Index 0) . should_fail_with Index_Out_Of_Bounds_Error - "ABC".take (By_Index 3) . should_fail_with Index_Out_Of_Bounds_Error - txt.take (Range 13 20) . should_fail_with Index_Out_Of_Bounds_Error - txt.take (Range 13 20 2) . should_fail_with Index_Out_Of_Bounds_Error - txt.take (By_Index [Range 0 2, Range 13 20]) . should_fail_with Index_Out_Of_Bounds_Error - txt.take (By_Index [Range 0 0, Range 13 10, Range 2 2 2]) . should_equal "" - txt.take (By_Index [Range 0 2 2, Range 13 20 2]) . should_fail_with Index_Out_Of_Bounds_Error - txt.take (By_Index [Range 0 2 2, Range 13 20 2]) . catch . should_equal (Index_Out_Of_Bounds_Error 13 12) - txt.take (By_Index [Range 0 2 2, Range txt.length 100 2]) . should_fail_with Index_Out_Of_Bounds_Error - "".take (By_Index 0) . should_fail_with Index_Out_Of_Bounds_Error + txt.take (By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.take (By_Index 13) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.take (By_Index [0, 1, 13]) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.take (By_Index [0, Range_Data 14 15, 1]) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.take (By_Index [0, 1, Range_Data 6 100]) . should_equal "HeWorld!" + txt.take (By_Index [0, 1, Range_Data 6 100 2]) . should_equal "HeWrd" + txt.take (Range_Data 13 12) . should_fail_with Index_Out_Of_Bounds_Error_Data + "".take (Range_Data 0 0) . should_fail_with Index_Out_Of_Bounds_Error_Data + "".take (Range_Data 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 0 0) + "".take (By_Index 0) . should_fail_with Index_Out_Of_Bounds_Error_Data + "ABC".take (By_Index 3) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.take (Range_Data 13 20) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.take (Range_Data 13 20 2) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.take (By_Index [Range_Data 0 2, Range_Data 13 20]) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.take (By_Index [Range_Data 0 0, Range_Data 13 10, Range_Data 2 2 2]) . should_equal "" + txt.take (By_Index [Range_Data 0 2 2, Range_Data 13 20 2]) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.take (By_Index [Range_Data 0 2 2, Range_Data 13 20 2]) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 13 12) + txt.take (By_Index [Range_Data 0 2 2, Range_Data txt.length 100 2]) . should_fail_with Index_Out_Of_Bounds_Error_Data + "".take (By_Index 0) . should_fail_with Index_Out_Of_Bounds_Error_Data Test.specify "take should work on grapheme clusters" <| txt_1 = 'He\u0302llo\u0308 Wo\u0301rld!' @@ -418,8 +420,8 @@ spec = txt_2.take (While c->c!='e\u{302}') . should_equal 'H' txt_2.take (While c->c!='ê') . should_equal 'H' txt_2.take (While c->c!='e') . should_equal txt_2 - txt_2.take (Range 3 5) . should_equal 'lo\u{308}' - txt_2.take (Range 5 12) . should_equal ' Wo\u{308}rld!' + txt_2.take (Range_Data 3 5) . should_equal 'lo\u{308}' + txt_2.take (Range_Data 5 12) . should_equal ' Wo\u{308}rld!' Test.specify "take should work on emojis" <| '✨🚀🚧😍😃😎😙😉☺'.take First . should_equal '✨' @@ -432,7 +434,7 @@ spec = '✨🚀🚧😍😃😍😎😙😉☺'.take (After '😍') . should_equal '😃😍😎😙😉☺' '✨🚀🚧😍😃😍😎😙😉☺'.take (After_Last '😍') . should_equal '😎😙😉☺' '✨🚀🚧😍😃😍😎😙😉☺'.take (While c->c!="😃") . should_equal '✨🚀🚧😍' - '✨🚀🚧😍😃😍😎😙😉☺'.take (Range 3 6) . should_equal '😍😃😍' + '✨🚀🚧😍😃😍😎😙😉☺'.take (Range_Data 3 6) . should_equal '😍😃😍' Test.specify "take should correctly handle edge cases" <| "ABC".take . should_equal "A" @@ -452,7 +454,7 @@ spec = "".take (While _->True) . should_equal "" - 'ABC\u{301}'.take (Range 0 0) . should_equal "" + 'ABC\u{301}'.take (Range_Data 0 0) . should_equal "" 'ABC\u{301}'.take (After "") . should_equal 'ABC\u{301}' 'ABC\u{301}'.take (After_Last "") . should_equal "" @@ -462,7 +464,7 @@ spec = "ABC".take (By_Index -1) . should_equal "C" "ABC".take (By_Index [-1, -1, -1, -3, 2]) . should_equal "CCCAC" "ABC".take (By_Index []) . should_equal "" - "ABC".take (By_Index (Range -2 -1)) . should_fail_with Illegal_Argument_Error + "ABC".take (By_Index (Range_Data -2 -1)) . should_fail_with Illegal_Argument_Error_Data "".take (Every 2) . should_equal "" "".take (Every 2 first=1) . should_equal "" "ABC".take (Every 5) . should_equal "A" @@ -489,36 +491,36 @@ spec = "Hello World!".drop (After_Last "z") . should_equal "Hello World!" "Hello World!".drop (While c->c!=" ") . should_equal " World!" "Hello World!".drop (While c->c!="z") . should_equal "" - "Hello World!".drop (Range 3 5) . should_equal "Hel World!" - "Hello World!".drop (Range 5 12) . should_equal "Hello" - "Hello World!".drop (Range 6 12 2) . should_equal "Hello ol!" + "Hello World!".drop (Range_Data 3 5) . should_equal "Hel World!" + "Hello World!".drop (Range_Data 5 12) . should_equal "Hello" + "Hello World!".drop (Range_Data 6 12 2) . should_equal "Hello ol!" "Hello World!".drop (Every 2 first=6) . should_equal "Hello ol!" "Hello World!".drop (Every 3) . should_equal "elo ord!" "Hello World!".drop (By_Index 0) . should_equal "ello World!" "Hello World!".drop (By_Index [1, 0, 0, 6, 0]) . should_equal "llo orld!" - "Hello World!".drop (By_Index [Range 0 3, 6, Range 6 12 2]) . should_equal "lo ol!" + "Hello World!".drop (By_Index [Range_Data 0 3, 6, Range_Data 6 12 2]) . should_equal "lo ol!" "Hello World!".drop (Sample 3 seed=42) . should_equal "HeloWorl!" Test.specify "drop should report errors for start indices out of bounds but just go till the end if the end index is OOB" <| txt = "Hello World!" - txt.drop (Range 0 14) . should_equal "" + txt.drop (Range_Data 0 14) . should_equal "" txt.drop (First 100) . should_equal "" txt.drop (Last 100) . should_equal "" - txt.drop (By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error - txt.drop (By_Index 100) . catch . should_equal (Index_Out_Of_Bounds_Error 100 12) - txt.drop (By_Index 13) . should_fail_with Index_Out_Of_Bounds_Error - txt.drop (By_Index [0, 1, 13]) . should_fail_with Index_Out_Of_Bounds_Error - txt.drop (By_Index [0, Range 14 15, 1]) . should_fail_with Index_Out_Of_Bounds_Error - txt.drop (By_Index [0, 1, Range 6 100]) . should_equal "llo " - txt.drop (Range 13 12) . should_fail_with Index_Out_Of_Bounds_Error - txt.drop (Range 14 15) . should_fail_with Index_Out_Of_Bounds_Error - "".drop (By_Index 0) . should_fail_with Index_Out_Of_Bounds_Error - "".drop (Range 0 0) . should_fail_with Index_Out_Of_Bounds_Error - "".drop (Range 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error 0 0) - txt.drop (Range 0 0) . should_equal txt - txt.drop (Range 5 100) . should_equal "Hello" - txt.drop (Range 5 100 2) . should_equal "HelloWrd" - txt.drop (By_Index [0, 1, 0, Range 5 100 2]) . should_equal "lloWrd" + txt.drop (By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.drop (By_Index 100) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 100 12) + txt.drop (By_Index 13) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.drop (By_Index [0, 1, 13]) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.drop (By_Index [0, Range_Data 14 15, 1]) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.drop (By_Index [0, 1, Range_Data 6 100]) . should_equal "llo " + txt.drop (Range_Data 13 12) . should_fail_with Index_Out_Of_Bounds_Error_Data + txt.drop (Range_Data 14 15) . should_fail_with Index_Out_Of_Bounds_Error_Data + "".drop (By_Index 0) . should_fail_with Index_Out_Of_Bounds_Error_Data + "".drop (Range_Data 0 0) . should_fail_with Index_Out_Of_Bounds_Error_Data + "".drop (Range_Data 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 0 0) + txt.drop (Range_Data 0 0) . should_equal txt + txt.drop (Range_Data 5 100) . should_equal "Hello" + txt.drop (Range_Data 5 100 2) . should_equal "HelloWrd" + txt.drop (By_Index [0, 1, 0, Range_Data 5 100 2]) . should_equal "lloWrd" Test.specify "drop should work on grapheme clusters" <| txt_1 = 'He\u0302llo\u0308 Wo\u0301rld!' @@ -543,8 +545,8 @@ spec = txt_2.drop (While c->c!='e\u{302}') . should_equal 'e\u{302}llo\u{308} Wo\u{308}rld!' txt_2.drop (While c->c!='ê') . should_equal 'e\u{302}llo\u{308} Wo\u{308}rld!' txt_2.drop (While c->c!='e') . should_equal '' - txt_2.drop (Range 3 5) . should_equal 'He\u{302}l Wo\u{308}rld!' - txt_2.drop (Range 5 12) . should_equal 'He\u{302}llo\u{308}' + txt_2.drop (Range_Data 3 5) . should_equal 'He\u{302}l Wo\u{308}rld!' + txt_2.drop (Range_Data 5 12) . should_equal 'He\u{302}llo\u{308}' Test.specify "drop should work on emojis" <| '✨🚀🚧😍😃😎😙😉☺'.drop First . should_equal '🚀🚧😍😃😎😙😉☺' @@ -556,7 +558,7 @@ spec = '✨🚀🚧😍😃😍😎😙😉☺'.drop (After '😍') . should_equal '✨🚀🚧😍' '✨🚀🚧😍😃😍😎😙😉☺'.drop (After_Last '😍') . should_equal '✨🚀🚧😍😃😍' '✨🚀🚧😍😃😍😎😙😉☺'.drop (While c->c!="😃") . should_equal '😃😍😎😙😉☺' - '✨🚀🚧😍😃😍😎😙😉☺'.drop (Range 3 6) . should_equal '✨🚀🚧😎😙😉☺' + '✨🚀🚧😍😃😍😎😙😉☺'.drop (Range_Data 3 6) . should_equal '✨🚀🚧😎😙😉☺' Test.specify "drop should correctly handle edge cases" <| "ABC".drop . should_equal "BC" @@ -576,8 +578,8 @@ spec = "".drop (While _->True) . should_equal "" - "".drop (Range 0 0) . should_fail_with Index_Out_Of_Bounds_Error - 'ABC\u{301}'.drop (Range 0 0) . should_equal 'ABC\u{301}' + "".drop (Range_Data 0 0) . should_fail_with Index_Out_Of_Bounds_Error_Data + 'ABC\u{301}'.drop (Range_Data 0 0) . should_equal 'ABC\u{301}' 'ABC\u{301}'.drop (After "") . should_equal '' 'ABC\u{301}'.drop (After_Last "") . should_equal 'ABC\u{301}' @@ -643,9 +645,9 @@ spec = txt.insert 2 " Cruel" . should_equal (kshi + facepalm + " Cruel" + accent_1) txt.insert 3 " Cruel" . should_equal (kshi + facepalm + accent_1 + " Cruel") - Test.specify "should report Index_Out_Of_Bounds_Error when inserting text at an invalid non-negative index position" <| - "Hello World!".insert ("Hello World!".length + 1) "foo" . should_fail_with Index_Out_Of_Bounds_Error - (kshi + facepalm + accent_1).insert 4 "foo" . should_fail_with Index_Out_Of_Bounds_Error + Test.specify "should report Index_Out_Of_Bounds_Error_Data when inserting text at an invalid non-negative index position" <| + "Hello World!".insert ("Hello World!".length + 1) "foo" . should_fail_with Index_Out_Of_Bounds_Error_Data + (kshi + facepalm + accent_1).insert 4 "foo" . should_fail_with Index_Out_Of_Bounds_Error_Data Test.specify "should insert text at a negative index position" <| "Hello World!".insert -1 " Cruel" . should_equal "Hello World! Cruel" @@ -656,10 +658,10 @@ spec = txt.insert -1 " Cruel" . should_equal (txt + " Cruel") txt.insert -(txt.length) " Cruel" . should_equal (kshi + " Cruel" + facepalm + accent_1) - Test.specify "should report Index_Out_Of_Bounds_Error when inserting text at an invalid negative index position" <| - "Hello World!".insert -("Hello World!".length + 2) " Cruel" . should_fail_with Index_Out_Of_Bounds_Error + Test.specify "should report Index_Out_Of_Bounds_Error_Data when inserting text at an invalid negative index position" <| + "Hello World!".insert -("Hello World!".length + 2) " Cruel" . should_fail_with Index_Out_Of_Bounds_Error_Data txt = kshi + facepalm + accent_1 - txt.insert -(txt.length + 2) " Cruel" . should_fail_with Index_Out_Of_Bounds_Error + txt.insert -(txt.length + 2) " Cruel" . should_fail_with Index_Out_Of_Bounds_Error_Data Test.specify "should be able to check by index if is a digit" <| str = kshi + "A12" + accent_2 @@ -668,7 +670,7 @@ spec = str.is_digit 2 . should_be_true str.is_digit 3 . should_be_true str.is_digit 4 . should_be_false - str.is_digit 5 . should_fail_with Index_Out_Of_Bounds_Error + str.is_digit 5 . should_fail_with Index_Out_Of_Bounds_Error_Data Test.specify "should be able to check by negative index if is a digit" <| str = kshi + "A12" + accent_2 @@ -677,7 +679,7 @@ spec = str.is_digit -3 . should_be_true str.is_digit -4 . should_be_false str.is_digit -5 . should_be_false - str.is_digit -100 . should_fail_with Index_Out_Of_Bounds_Error + str.is_digit -100 . should_fail_with Index_Out_Of_Bounds_Error_Data Test.specify "should be able to check if a text consists only of whitespace" <| ' \t\n'.is_whitespace . should_be_true @@ -690,8 +692,8 @@ spec = Test.specify "should return a dataflow error when checking is digit for out of bounds" <| str = kshi + "A12" + accent_2 - str.at -6 . should_fail_with Index_Out_Of_Bounds_Error - str.at 5 . should_fail_with Index_Out_Of_Bounds_Error + str.at -6 . should_fail_with Index_Out_Of_Bounds_Error_Data + str.at 5 . should_fail_with Index_Out_Of_Bounds_Error_Data Test.specify "should be able to reverse characters" <| "Hello World!".reverse . should_equal "!dlroW olleH" @@ -739,25 +741,25 @@ spec = "Hello!".contains "Lo" . should_be_false Test.specify "should allow for case-insensitive contains checks" <| - "Hello!".contains 'LO' (Text_Matcher Case_Insensitive) . should_be_true - "FoObar" . contains "foo" (Text_Matcher Case_Insensitive) . should_be_true - "aaaIAAA" . contains "i" (Text_Matcher Case_Insensitive) . should_be_true - "Foo" . contains "bar" (Text_Matcher Case_Insensitive) . should_be_false - "Ściana" . contains "ś" (Text_Matcher Case_Insensitive) . should_be_true - "Ściana" . contains "s" (Text_Matcher Case_Insensitive) . should_be_false + "Hello!".contains 'LO' (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "FoObar" . contains "foo" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "aaaIAAA" . contains "i" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "Foo" . contains "bar" (Text_Matcher_Data Case_Insensitive_Data) . should_be_false + "Ściana" . contains "ś" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "Ściana" . contains "s" (Text_Matcher_Data Case_Insensitive_Data) . should_be_false "Straße" . contains "ss" . should_be_false "Strasse" . contains "ß" . should_be_false - "Straße" . contains "ss" (Text_Matcher Case_Insensitive) . should_be_true - "Strasse" . contains "ß" (Text_Matcher Case_Insensitive) . should_be_true + "Straße" . contains "ss" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "Strasse" . contains "ß" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true Test.specify "should allow for Regex contains checks" <| - "Hello!".contains "[a-z]" Regex_Matcher . should_be_true - "foobar" . contains "b.." Regex_Matcher . should_be_true - "foob" . contains "b.." Regex_Matcher . should_be_false + "Hello!".contains "[a-z]" Regex_Matcher_Data . should_be_true + "foobar" . contains "b.." Regex_Matcher_Data . should_be_true + "foob" . contains "b.." Regex_Matcher_Data . should_be_false - "123 meters and 4 centimeters" . contains "[0-9]+" Regex_Matcher . should_be_true - "foo" . contains "[0-9]+" Regex_Matcher . should_be_false + "123 meters and 4 centimeters" . contains "[0-9]+" Regex_Matcher_Data . should_be_true + "foo" . contains "[0-9]+" Regex_Matcher_Data . should_be_false 'ś' . contains 's' . should_be_false 's\u{301}' . contains 's' . should_be_false @@ -768,28 +770,28 @@ spec = documenting here what is the current behaviour. ## This shows what regex is doing by default and we cannot easily fix that. - 's\u{301}' . contains 's' Regex_Matcher . should_be_true - 'ś' . contains 's' Regex_Matcher . should_be_false - 's\u{301}' . contains 'ś' Regex_Matcher . should_be_true - 'ś' . contains 's\u{301}' Regex_Matcher . should_be_true - - "Cześć" . contains "ś" Regex_Matcher . should_be_true - "Cześć" . contains 's\u{301}' Regex_Matcher . should_be_true - 'Czes\u{301}c\u{301}' . contains 's\u{301}' Regex_Matcher . should_be_true - 'Czes\u{301}c\u{301}' . contains 'ś' Regex_Matcher . should_be_true + 's\u{301}' . contains 's' Regex_Matcher_Data . should_be_true + 'ś' . contains 's' Regex_Matcher_Data . should_be_false + 's\u{301}' . contains 'ś' Regex_Matcher_Data . should_be_true + 'ś' . contains 's\u{301}' Regex_Matcher_Data . should_be_true + + "Cześć" . contains "ś" Regex_Matcher_Data . should_be_true + "Cześć" . contains 's\u{301}' Regex_Matcher_Data . should_be_true + 'Czes\u{301}c\u{301}' . contains 's\u{301}' Regex_Matcher_Data . should_be_true + 'Czes\u{301}c\u{301}' . contains 'ś' Regex_Matcher_Data . should_be_true ## These two tests below are disabled due to how regex is handling letters with accents. See the tests above for explanation. - #"Cześć" . contains "s" Regex_Matcher . should_be_false - #'Czes\u{301}c\u{301}' . contains 's' Regex_Matcher . should_be_false + #"Cześć" . contains "s" Regex_Matcher_Data . should_be_false + #'Czes\u{301}c\u{301}' . contains 's' Regex_Matcher_Data . should_be_false - "fooBar" . contains "b.." (Regex_Matcher case_sensitive=Case_Insensitive) . should_be_true - "foar" . contains "b.." (Regex_Matcher case_sensitive=Case_Insensitive) . should_be_false + "fooBar" . contains "b.." (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data) . should_be_true + "foar" . contains "b.." (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data) . should_be_false long_text = """ Hello from a long text. EOL SOL Hmm... - long_text . contains "EOL.SOL" (Regex_Matcher dot_matches_newline=True) . should_be_true - long_text . contains "EOL.SOL" (Regex_Matcher dot_matches_newline=False) . should_be_false + long_text . contains "EOL.SOL" (Regex_Matcher_Data dot_matches_newline=True) . should_be_true + long_text . contains "EOL.SOL" (Regex_Matcher_Data dot_matches_newline=False) . should_be_false Test.specify "should check for starts_with using Unicode normalization" <| "Hello".starts_with "He" . should_be_true @@ -813,36 +815,36 @@ spec = Test.specify "starts_with should work as shown in the examples" <| "Hello!".starts_with "Hello" . should_be_true "Hello!".starts_with "hello" . should_be_false - "Hello!".starts_with "hello" (Text_Matcher Case_Insensitive) . should_be_true - "Hello!".starts_with "[a-z]" Regex_Matcher . should_be_false - "Hello!".starts_with "[A-Z]" Regex_Matcher . should_be_true + "Hello!".starts_with "hello" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "Hello!".starts_with "[a-z]" Regex_Matcher_Data . should_be_false + "Hello!".starts_with "[A-Z]" Regex_Matcher_Data . should_be_true Test.specify "should allow for case-insensitive starts_with checks" <| - "Hello".starts_with "he" (Text_Matcher Case_Insensitive) . should_be_true + "Hello".starts_with "he" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true - "Ściana".starts_with 's\u{301}' (Text_Matcher Case_Insensitive) . should_be_true - "Ściana".starts_with 's' (Text_Matcher Case_Insensitive) . should_be_false - 'S\u{301}ciana'.starts_with 'ś' (Text_Matcher Case_Insensitive) . should_be_true - 'S\u{301}ciana'.starts_with 's\u{301}' (Text_Matcher Case_Insensitive) . should_be_true - 'S\u{301}ciana'.starts_with 's' (Text_Matcher Case_Insensitive) . should_be_false + "Ściana".starts_with 's\u{301}' (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "Ściana".starts_with 's' (Text_Matcher_Data Case_Insensitive_Data) . should_be_false + 'S\u{301}ciana'.starts_with 'ś' (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + 'S\u{301}ciana'.starts_with 's\u{301}' (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + 'S\u{301}ciana'.starts_with 's' (Text_Matcher_Data Case_Insensitive_Data) . should_be_false - "ABC" . starts_with "A" (Text_Matcher Case_Insensitive) . should_be_true - "ABC" . starts_with "a" (Text_Matcher Case_Insensitive) . should_be_true - "ABC" . starts_with "C" (Text_Matcher Case_Insensitive) . should_be_false - "" . starts_with "foo" (Text_Matcher Case_Insensitive) . should_be_false - "abc" . starts_with "" (Text_Matcher Case_Insensitive) . should_be_true - "" . starts_with "" (Text_Matcher Case_Insensitive) . should_be_true - "fOo FOO foo" . starts_with "FoO" (Text_Matcher Case_Insensitive) . should_be_true + "ABC" . starts_with "A" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "ABC" . starts_with "a" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "ABC" . starts_with "C" (Text_Matcher_Data Case_Insensitive_Data) . should_be_false + "" . starts_with "foo" (Text_Matcher_Data Case_Insensitive_Data) . should_be_false + "abc" . starts_with "" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "" . starts_with "" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "fOo FOO foo" . starts_with "FoO" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true - "Hello!".starts_with "he" (Text_Matcher Case_Insensitive) . should_be_true + "Hello!".starts_with "he" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true Test.specify "should allow for Regex starts_with checks" <| - "Hello!".starts_with "[A-Z]" Regex_Matcher . should_be_true - "foobar" . starts_with ".o." Regex_Matcher . should_be_true - "foob" . starts_with ".f." Regex_Matcher . should_be_false + "Hello!".starts_with "[A-Z]" Regex_Matcher_Data . should_be_true + "foobar" . starts_with ".o." Regex_Matcher_Data . should_be_true + "foob" . starts_with ".f." Regex_Matcher_Data . should_be_false - "123 meters and 4 centimeters" . starts_with "[0-9]+" Regex_Matcher . should_be_true - "foo 123" . starts_with "[0-9]+" Regex_Matcher . should_be_false + "123 meters and 4 centimeters" . starts_with "[0-9]+" Regex_Matcher_Data . should_be_true + "foo 123" . starts_with "[0-9]+" Regex_Matcher_Data . should_be_false # Correct non-regex behaviour for reference. 'ś' . starts_with 's' == False @@ -851,44 +853,44 @@ spec = 'ś' . starts_with 's\u{301}' == True # These two behave as expected. - 's\u{301}' . starts_with 'ś' Regex_Matcher == True - 'ś' . starts_with 's\u{301}' Regex_Matcher == True + 's\u{301}' . starts_with 'ś' Regex_Matcher_Data == True + 'ś' . starts_with 's\u{301}' Regex_Matcher_Data == True ## These two are included to document the current behaviour (even though ideally, we would want them to return False). - 'ś' . starts_with 's' Regex_Matcher == True - 's\u{301}' . starts_with 's' Regex_Matcher == True + 'ś' . starts_with 's' Regex_Matcher_Data == True + 's\u{301}' . starts_with 's' Regex_Matcher_Data == True - "ściana" . starts_with "ś" Regex_Matcher . should_be_true - "ściana" . starts_with 's\u{301}' Regex_Matcher . should_be_true - 's\u{301}ciana' . starts_with 's\u{301}' Regex_Matcher . should_be_true - 's\u{301}ciana' . starts_with 'ś' Regex_Matcher . should_be_true + "ściana" . starts_with "ś" Regex_Matcher_Data . should_be_true + "ściana" . starts_with 's\u{301}' Regex_Matcher_Data . should_be_true + 's\u{301}ciana' . starts_with 's\u{301}' Regex_Matcher_Data . should_be_true + 's\u{301}ciana' . starts_with 'ś' Regex_Matcher_Data . should_be_true ## These two tests below are disabled due to how regex is handling letters with accents. See the tests above for explanation. - #"ściana" . starts_with "s" Regex_Matcher . should_be_false - # 's\u{301}ciana' . starts_with 's' Regex_Matcher . should_be_false + #"ściana" . starts_with "s" Regex_Matcher_Data . should_be_false + # 's\u{301}ciana' . starts_with 's' Regex_Matcher_Data . should_be_false - "fOOBar" . starts_with ".o." (Regex_Matcher case_sensitive=Case_Insensitive) . should_be_true - "faaaar" . starts_with ".o." (Regex_Matcher case_sensitive=Case_Insensitive) . should_be_false + "fOOBar" . starts_with ".o." (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data) . should_be_true + "faaaar" . starts_with ".o." (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data) . should_be_false long_text = """ EOL SOL Hmm... - long_text . starts_with "EOL.SOL" (Regex_Matcher dot_matches_newline=True) . should_be_true - long_text . starts_with "EOL.SOL" (Regex_Matcher dot_matches_newline=False) . should_be_false - - "aaazzz" . starts_with "a|b" Regex_Matcher . should_be_true - "bbbzzz" . starts_with "a|b" Regex_Matcher . should_be_true - "zzzaaa" . starts_with "a|b" Regex_Matcher . should_be_false - "zzzbbb" . starts_with "a|b" Regex_Matcher . should_be_false - "aaazzz" . starts_with "(a|b){2}" Regex_Matcher . should_be_true - "bbbzzz" . starts_with "(a|b){2}" Regex_Matcher . should_be_true - "zzzaaa" . starts_with "(a|b){2}" Regex_Matcher . should_be_false - "ABC" . starts_with "\AA" Regex_Matcher . should_be_true - "ABC" . starts_with "\AA\z" Regex_Matcher . should_be_false - "foobar" . starts_with "" Regex_Matcher . should_be_true - "" . starts_with "" Regex_Matcher . should_be_true + long_text . starts_with "EOL.SOL" (Regex_Matcher_Data dot_matches_newline=True) . should_be_true + long_text . starts_with "EOL.SOL" (Regex_Matcher_Data dot_matches_newline=False) . should_be_false + + "aaazzz" . starts_with "a|b" Regex_Matcher_Data . should_be_true + "bbbzzz" . starts_with "a|b" Regex_Matcher_Data . should_be_true + "zzzaaa" . starts_with "a|b" Regex_Matcher_Data . should_be_false + "zzzbbb" . starts_with "a|b" Regex_Matcher_Data . should_be_false + "aaazzz" . starts_with "(a|b){2}" Regex_Matcher_Data . should_be_true + "bbbzzz" . starts_with "(a|b){2}" Regex_Matcher_Data . should_be_true + "zzzaaa" . starts_with "(a|b){2}" Regex_Matcher_Data . should_be_false + "ABC" . starts_with "\AA" Regex_Matcher_Data . should_be_true + "ABC" . starts_with "\AA\z" Regex_Matcher_Data . should_be_false + "foobar" . starts_with "" Regex_Matcher_Data . should_be_true + "" . starts_with "" Regex_Matcher_Data . should_be_true Test.specify "should check for ends_with using Unicode normalization" <| "Hello".ends_with "lo" . should_be_true @@ -911,64 +913,64 @@ spec = Test.specify "ends_with should work as shown in the examples" <| "Hello World".ends_with "World" . should_be_true "Hello World".ends_with "world" . should_be_false - "Hello World".ends_with "world" (Text_Matcher Case_Insensitive) . should_be_true - "Hello World".ends_with "[A-Z][a-z]{4}" Regex_Matcher . should_be_true + "Hello World".ends_with "world" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "Hello World".ends_with "[A-Z][a-z]{4}" Regex_Matcher_Data . should_be_true Test.specify "should allow for case-insensitive ends_with checks" <| - "Hello".ends_with "LO" (Text_Matcher Case_Insensitive) . should_be_true - - "rzeczywistość".ends_with 'C\u{301}' (Text_Matcher Case_Insensitive) . should_be_true - "rzeczywistość".ends_with 'C' (Text_Matcher Case_Insensitive) . should_be_false - 'rzeczywistos\u{301}c\u{301}'.ends_with 'Ć' (Text_Matcher Case_Insensitive) . should_be_true - 'rzeczywistos\u{301}c\u{301}'.ends_with 'C\u{301}' (Text_Matcher Case_Insensitive) . should_be_true - 'rzeczywistos\u{301}c\u{301}'.ends_with 'C' (Text_Matcher Case_Insensitive) . should_be_false - - "ABC" . ends_with "C" (Text_Matcher Case_Insensitive) . should_be_true - "ABC" . ends_with "c" (Text_Matcher Case_Insensitive) . should_be_true - "ABC" . ends_with "A" (Text_Matcher Case_Insensitive) . should_be_false - "" . ends_with "foo" (Text_Matcher Case_Insensitive) . should_be_false - "abc" . ends_with "" (Text_Matcher Case_Insensitive) . should_be_true - "" . ends_with "" (Text_Matcher Case_Insensitive) . should_be_true - "fOo FOO fOo" . ends_with "FoO" (Text_Matcher Case_Insensitive) . should_be_true + "Hello".ends_with "LO" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + + "rzeczywistość".ends_with 'C\u{301}' (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "rzeczywistość".ends_with 'C' (Text_Matcher_Data Case_Insensitive_Data) . should_be_false + 'rzeczywistos\u{301}c\u{301}'.ends_with 'Ć' (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + 'rzeczywistos\u{301}c\u{301}'.ends_with 'C\u{301}' (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + 'rzeczywistos\u{301}c\u{301}'.ends_with 'C' (Text_Matcher_Data Case_Insensitive_Data) . should_be_false + + "ABC" . ends_with "C" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "ABC" . ends_with "c" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "ABC" . ends_with "A" (Text_Matcher_Data Case_Insensitive_Data) . should_be_false + "" . ends_with "foo" (Text_Matcher_Data Case_Insensitive_Data) . should_be_false + "abc" . ends_with "" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "" . ends_with "" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true + "fOo FOO fOo" . ends_with "FoO" (Text_Matcher_Data Case_Insensitive_Data) . should_be_true Test.specify "should allow for Regex ends_with checks" <| - "Hello".ends_with "[a-z]" Regex_Matcher . should_be_true - "Hello!".ends_with "[a-z]" Regex_Matcher . should_be_false + "Hello".ends_with "[a-z]" Regex_Matcher_Data . should_be_true + "Hello!".ends_with "[a-z]" Regex_Matcher_Data . should_be_false - "foobar" . ends_with ".o." Regex_Matcher . should_be_false - "foobar" . ends_with ".a." Regex_Matcher . should_be_true + "foobar" . ends_with ".o." Regex_Matcher_Data . should_be_false + "foobar" . ends_with ".a." Regex_Matcher_Data . should_be_true - "123 meters and 4 centimeters" . ends_with "[0-9]+" Regex_Matcher . should_be_false - "foo 123" . ends_with "[0-9]+" Regex_Matcher . should_be_true + "123 meters and 4 centimeters" . ends_with "[0-9]+" Regex_Matcher_Data . should_be_false + "foo 123" . ends_with "[0-9]+" Regex_Matcher_Data . should_be_true - "rzeczywistość" . ends_with "ć" Regex_Matcher . should_be_true - "rzeczywistość" . ends_with 'c\u{301}' Regex_Matcher . should_be_true - 'rzeczywistos\u{301}c\u{301}' . ends_with 'c\u{301}' Regex_Matcher . should_be_true - 'rzeczywistos\u{301}c\u{301}' . ends_with 'ć' Regex_Matcher . should_be_true - "rzeczywistość" . ends_with "c" Regex_Matcher . should_be_false - 'rzeczywistos\u{301}c\u{301}' . ends_with 'c' Regex_Matcher . should_be_false + "rzeczywistość" . ends_with "ć" Regex_Matcher_Data . should_be_true + "rzeczywistość" . ends_with 'c\u{301}' Regex_Matcher_Data . should_be_true + 'rzeczywistos\u{301}c\u{301}' . ends_with 'c\u{301}' Regex_Matcher_Data . should_be_true + 'rzeczywistos\u{301}c\u{301}' . ends_with 'ć' Regex_Matcher_Data . should_be_true + "rzeczywistość" . ends_with "c" Regex_Matcher_Data . should_be_false + 'rzeczywistos\u{301}c\u{301}' . ends_with 'c' Regex_Matcher_Data . should_be_false - 'rzeczywistos\u{301}c\u{301}' . ends_with 'Ć' (Regex_Matcher case_sensitive=Case_Insensitive) . should_be_true - "fOOBar" . ends_with ".A." (Regex_Matcher case_sensitive=Case_Insensitive) . should_be_true - "faaaar" . ends_with ".o." (Regex_Matcher case_sensitive=Case_Insensitive) . should_be_false + 'rzeczywistos\u{301}c\u{301}' . ends_with 'Ć' (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data) . should_be_true + "fOOBar" . ends_with ".A." (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data) . should_be_true + "faaaar" . ends_with ".o." (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data) . should_be_false long_text = """ Hnnnn EOL SOL - long_text . ends_with "EOL.SOL" (Regex_Matcher dot_matches_newline=True) . should_be_true - long_text . ends_with "EOL.SOL" (Regex_Matcher dot_matches_newline=False) . should_be_false - - "zzzaaa" . ends_with "a|b" Regex_Matcher . should_be_true - "zzzbbb" . ends_with "a|b" Regex_Matcher . should_be_true - "aaazzz" . ends_with "a|b" Regex_Matcher . should_be_false - "bbbzzz" . ends_with "a|b" Regex_Matcher . should_be_false - "zzzaaa" . ends_with "(a|b){2}" Regex_Matcher . should_be_true - "zzzbbb" . ends_with "(a|b){2}" Regex_Matcher . should_be_true - "aaazzz" . ends_with "(a|b){2}" Regex_Matcher . should_be_false - "ABC" . ends_with "C\z" Regex_Matcher . should_be_true - "ABC" . ends_with "\AC\z" Regex_Matcher . should_be_false - "foobar" . ends_with "" Regex_Matcher . should_be_true - "" . ends_with "" Regex_Matcher . should_be_true + long_text . ends_with "EOL.SOL" (Regex_Matcher_Data dot_matches_newline=True) . should_be_true + long_text . ends_with "EOL.SOL" (Regex_Matcher_Data dot_matches_newline=False) . should_be_false + + "zzzaaa" . ends_with "a|b" Regex_Matcher_Data . should_be_true + "zzzbbb" . ends_with "a|b" Regex_Matcher_Data . should_be_true + "aaazzz" . ends_with "a|b" Regex_Matcher_Data . should_be_false + "bbbzzz" . ends_with "a|b" Regex_Matcher_Data . should_be_false + "zzzaaa" . ends_with "(a|b){2}" Regex_Matcher_Data . should_be_true + "zzzbbb" . ends_with "(a|b){2}" Regex_Matcher_Data . should_be_true + "aaazzz" . ends_with "(a|b){2}" Regex_Matcher_Data . should_be_false + "ABC" . ends_with "C\z" Regex_Matcher_Data . should_be_true + "ABC" . ends_with "\AC\z" Regex_Matcher_Data . should_be_false + "foobar" . ends_with "" Regex_Matcher_Data . should_be_true + "" . ends_with "" Regex_Matcher_Data . should_be_true Test.specify "should allow to pad a text" <| "Hello World!".pad 15 . should_equal "Hello World! " @@ -976,9 +978,9 @@ spec = "HELLO".pad 8 "AB" . should_equal "HELLOABA" "HELLO".pad 8 "AB" Location.Start . should_equal "BABHELLO" "".pad 4 . should_equal " " - "A".pad 3 "" . should_fail_with Illegal_Argument_Error - "ABCDE".pad 3 "" . should_fail_with Illegal_Argument_Error - "".pad 0 "" . should_fail_with Illegal_Argument_Error + "A".pad 3 "" . should_fail_with Illegal_Argument_Error_Data + "ABCDE".pad 3 "" . should_fail_with Illegal_Argument_Error_Data + "".pad 0 "" . should_fail_with Illegal_Argument_Error_Data "".pad 0 . should_equal "" "ABC".pad 3 . should_equal "ABC" @@ -1071,13 +1073,13 @@ spec = Test.specify "location_of should work as shown in examples" <| example_1 = "Hello World!".location_of "J" == Nothing - "Hello World!".location_of "o" == Span (Range 4 5) "Hello World!" - "Hello World!".location_of "o" mode=Matching_Mode.Last == Span (Range 4 5) "Hello World!" + "Hello World!".location_of "o" == Span_Data (Range_Data 4 5) "Hello World!" + "Hello World!".location_of "o" mode=Matching_Mode.Last == Span_Data (Range_Data 4 5) "Hello World!" example_2 = term = "straße" text = "MONUMENTENSTRASSE 42" - match = text . location_of term matcher=(Text_Matcher Case_Insensitive) + match = text . location_of term matcher=(Text_Matcher_Data Case_Insensitive_Data) term.length . should_equal 6 match.length . should_equal 7 @@ -1085,11 +1087,11 @@ spec = ligatures = "ffiffl" ligatures.length . should_equal 2 term_1 = "IFF" - match_1 = ligatures . location_of term_1 matcher=(Text_Matcher Case_Insensitive) + match_1 = ligatures . location_of term_1 matcher=(Text_Matcher_Data Case_Insensitive_Data) term_1.length . should_equal 3 match_1.length . should_equal 2 term_2 = "ffiffl" - match_2 = ligatures . location_of term_2 matcher=(Text_Matcher Case_Insensitive) + match_2 = ligatures . location_of term_2 matcher=(Text_Matcher_Data Case_Insensitive_Data) term_2.length . should_equal 6 match_2.length . should_equal 2 match_1 . should_equal match_2 @@ -1101,16 +1103,16 @@ spec = example_5 = term = "strasse" text = "MONUMENTENSTRASSE ist eine große Straße." - match = text . location_of_all term matcher=(Text_Matcher Case_Insensitive) + match = text . location_of_all term matcher=(Text_Matcher_Data Case_Insensitive_Data) term.length . should_equal 7 match . map .length . should_equal [7, 6] example_6 = ligatures = "ffifflFFIFF" ligatures.length . should_equal 7 - match_1 = ligatures . location_of_all "IFF" matcher=(Text_Matcher Case_Insensitive) + match_1 = ligatures . location_of_all "IFF" matcher=(Text_Matcher_Data Case_Insensitive_Data) match_1 . map .length . should_equal [2, 3] - match_2 = ligatures . location_of_all "ffiff" matcher=(Text_Matcher Case_Insensitive) + match_2 = ligatures . location_of_all "ffiff" matcher=(Text_Matcher_Data Case_Insensitive_Data) match_2 . map .length . should_equal [2, 5] # Put them in blocks to avoid name clashes. @@ -1126,115 +1128,115 @@ spec = "Hello World!".location_of_all "o" . map .start . should_equal [4, 7] accents = 'a\u{301}e\u{301}o\u{301}' - accents.location_of accent_1 . should_equal (Span (Range 1 2) accents) + accents.location_of accent_1 . should_equal (Span_Data (Range_Data 1 2) accents) "".location_of "foo" . should_equal Nothing "".location_of "foo" mode=Matching_Mode.Last . should_equal Nothing "".location_of_all "foo" . should_equal [] - "".location_of "" . should_equal (Span (Range 0 0) "") - "".location_of "" mode=Matching_Mode.Last . should_equal (Span (Range 0 0) "") - "".location_of_all "" . should_equal [Span (Range 0 0) ""] + "".location_of "" . should_equal (Span_Data (Range_Data 0 0) "") + "".location_of "" mode=Matching_Mode.Last . should_equal (Span_Data (Range_Data 0 0) "") + "".location_of_all "" . should_equal [Span_Data (Range_Data 0 0) ""] abc = 'A\u{301}ßC' - abc.location_of "" . should_equal (Span (Range 0 0) abc) - abc.location_of "" mode=Matching_Mode.Last . should_equal (Span (Range 3 3) abc) - abc.location_of_all "" . should_equal [Span (Range 0 0) abc, Span (Range 1 1) abc, Span (Range 2 2) abc, Span (Range 3 3) abc] + abc.location_of "" . should_equal (Span_Data (Range_Data 0 0) abc) + abc.location_of "" mode=Matching_Mode.Last . should_equal (Span_Data (Range_Data 3 3) abc) + abc.location_of_all "" . should_equal [Span_Data (Range_Data 0 0) abc, Span_Data (Range_Data 1 1) abc, Span_Data (Range_Data 2 2) abc, Span_Data (Range_Data 3 3) abc] Test.specify "should allow case-insensitive matching in location_of" <| hello = "Hello WORLD!" - case_insensitive = Text_Matcher Case_Insensitive + case_insensitive = Text_Matcher_Data Case_Insensitive_Data hello.location_of "world" . should_equal Nothing - hello.location_of "world" matcher=case_insensitive . should_equal (Span (Range 6 11) hello) + hello.location_of "world" matcher=case_insensitive . should_equal (Span_Data (Range_Data 6 11) hello) - hello.location_of "o" mode=Regex_Mode.First matcher=case_insensitive . should_equal (Span (Range 4 5) hello) - hello.location_of "o" mode=Matching_Mode.Last matcher=case_insensitive . should_equal (Span (Range 7 8) hello) + hello.location_of "o" mode=Regex_Mode.First matcher=case_insensitive . should_equal (Span_Data (Range_Data 4 5) hello) + hello.location_of "o" mode=Matching_Mode.Last matcher=case_insensitive . should_equal (Span_Data (Range_Data 7 8) hello) accents = 'A\u{301}E\u{301}O\u{301}' - accents.location_of accent_1 matcher=case_insensitive . should_equal (Span (Range 1 2) accents) + accents.location_of accent_1 matcher=case_insensitive . should_equal (Span_Data (Range_Data 1 2) accents) - "Strasse".location_of "ß" matcher=case_insensitive . should_equal (Span (Range 4 6) "Strasse") - "Monumentenstraße 42".location_of "STRASSE" matcher=case_insensitive . should_equal (Span (Range 10 16) "Monumentenstraße 42") + "Strasse".location_of "ß" matcher=case_insensitive . should_equal (Span_Data (Range_Data 4 6) "Strasse") + "Monumentenstraße 42".location_of "STRASSE" matcher=case_insensitive . should_equal (Span_Data (Range_Data 10 16) "Monumentenstraße 42") - '\u0390'.location_of '\u03B9\u0308\u0301' matcher=case_insensitive . should_equal (Span (Range 0 1) '\u0390') + '\u0390'.location_of '\u03B9\u0308\u0301' matcher=case_insensitive . should_equal (Span_Data (Range_Data 0 1) '\u0390') 'ԵՒ'.location_of 'և' . should_equal Nothing - 'ԵՒ'.location_of 'և' matcher=case_insensitive . should_equal (Span (Range 0 2) 'ԵՒ') - 'և'.location_of 'ԵՒ' matcher=case_insensitive . should_equal (Span (Range 0 1) 'և') + 'ԵՒ'.location_of 'և' matcher=case_insensitive . should_equal (Span_Data (Range_Data 0 2) 'ԵՒ') + 'և'.location_of 'ԵՒ' matcher=case_insensitive . should_equal (Span_Data (Range_Data 0 1) 'և') ligatures = 'ffafffiflffifflſtstZ' - ligatures.location_of 'FFI' matcher=case_insensitive . should_equal (Span (Range 3 5) ligatures) - ligatures.location_of 'FF' matcher=case_insensitive . should_equal (Span (Range 0 2) ligatures) - ligatures.location_of 'ff' matcher=case_insensitive mode=Matching_Mode.Last . should_equal (Span (Range 7 8) ligatures) - ligatures.location_of_all 'ff' . should_equal [Span (Range 0 2) ligatures] - ligatures.location_of_all 'FF' matcher=case_insensitive . should_equal [Span (Range 0 2) ligatures, Span (Range 3 4) ligatures, Span (Range 6 7) ligatures, Span (Range 7 8) ligatures] - ligatures.location_of_all 'ffi' matcher=case_insensitive . should_equal [Span (Range 3 5) ligatures, Span (Range 6 7) ligatures] - 'fffi'.location_of_all 'ff' matcher=case_insensitive . should_equal [Span (Range 0 2) 'fffi'] + ligatures.location_of 'FFI' matcher=case_insensitive . should_equal (Span_Data (Range_Data 3 5) ligatures) + ligatures.location_of 'FF' matcher=case_insensitive . should_equal (Span_Data (Range_Data 0 2) ligatures) + ligatures.location_of 'ff' matcher=case_insensitive mode=Matching_Mode.Last . should_equal (Span_Data (Range_Data 7 8) ligatures) + ligatures.location_of_all 'ff' . should_equal [Span_Data (Range_Data 0 2) ligatures] + ligatures.location_of_all 'FF' matcher=case_insensitive . should_equal [Span_Data (Range_Data 0 2) ligatures, Span_Data (Range_Data 3 4) ligatures, Span_Data (Range_Data 6 7) ligatures, Span_Data (Range_Data 7 8) ligatures] + ligatures.location_of_all 'ffi' matcher=case_insensitive . should_equal [Span_Data (Range_Data 3 5) ligatures, Span_Data (Range_Data 6 7) ligatures] + 'fffi'.location_of_all 'ff' matcher=case_insensitive . should_equal [Span_Data (Range_Data 0 2) 'fffi'] 'fffi'.location_of_all 'ffi' . should_equal [] - 'fffi'.location_of_all 'ffi' matcher=case_insensitive . should_equal [Span (Range 1 4) 'fffi'] - 'FFFI'.location_of 'ffi' matcher=case_insensitive . should_equal (Span (Range 1 4) 'FFFI') + 'fffi'.location_of_all 'ffi' matcher=case_insensitive . should_equal [Span_Data (Range_Data 1 4) 'fffi'] + 'FFFI'.location_of 'ffi' matcher=case_insensitive . should_equal (Span_Data (Range_Data 1 4) 'FFFI') - 'ffiffl'.location_of 'IF' matcher=case_insensitive . should_equal (Span (Range 0 2) 'ffiffl') - 'ffiffl'.location_of 'F' Matching_Mode.Last matcher=case_insensitive . should_equal (Span (Range 1 2) 'ffiffl') - 'ffiffl'.location_of_all 'F' matcher=case_insensitive . should_equal [Span (Range 0 1) 'ffiffl', Span (Range 0 1) 'ffiffl', Span (Range 1 2) 'ffiffl', Span (Range 1 2) 'ffiffl'] - 'aaffibb'.location_of_all 'af' matcher=case_insensitive . should_equal [Span (Range 1 3) 'aaffibb'] - 'aaffibb'.location_of_all 'affi' matcher=case_insensitive . should_equal [Span (Range 1 3) 'aaffibb'] - 'aaffibb'.location_of_all 'ib' matcher=case_insensitive . should_equal [Span (Range 2 4) 'aaffibb'] - 'aaffibb'.location_of_all 'ffib' matcher=case_insensitive . should_equal [Span (Range 2 4) 'aaffibb'] + 'ffiffl'.location_of 'IF' matcher=case_insensitive . should_equal (Span_Data (Range_Data 0 2) 'ffiffl') + 'ffiffl'.location_of 'F' Matching_Mode.Last matcher=case_insensitive . should_equal (Span_Data (Range_Data 1 2) 'ffiffl') + 'ffiffl'.location_of_all 'F' matcher=case_insensitive . should_equal [Span_Data (Range_Data 0 1) 'ffiffl', Span_Data (Range_Data 0 1) 'ffiffl', Span_Data (Range_Data 1 2) 'ffiffl', Span_Data (Range_Data 1 2) 'ffiffl'] + 'aaffibb'.location_of_all 'af' matcher=case_insensitive . should_equal [Span_Data (Range_Data 1 3) 'aaffibb'] + 'aaffibb'.location_of_all 'affi' matcher=case_insensitive . should_equal [Span_Data (Range_Data 1 3) 'aaffibb'] + 'aaffibb'.location_of_all 'ib' matcher=case_insensitive . should_equal [Span_Data (Range_Data 2 4) 'aaffibb'] + 'aaffibb'.location_of_all 'ffib' matcher=case_insensitive . should_equal [Span_Data (Range_Data 2 4) 'aaffibb'] "".location_of "foo" matcher=case_insensitive . should_equal Nothing "".location_of "foo" matcher=case_insensitive mode=Matching_Mode.Last . should_equal Nothing "".location_of_all "foo" matcher=case_insensitive . should_equal [] - "".location_of "" matcher=case_insensitive . should_equal (Span (Range 0 0) "") - "".location_of "" matcher=case_insensitive mode=Matching_Mode.Last . should_equal (Span (Range 0 0) "") - "".location_of_all "" matcher=case_insensitive . should_equal [Span (Range 0 0) ""] + "".location_of "" matcher=case_insensitive . should_equal (Span_Data (Range_Data 0 0) "") + "".location_of "" matcher=case_insensitive mode=Matching_Mode.Last . should_equal (Span_Data (Range_Data 0 0) "") + "".location_of_all "" matcher=case_insensitive . should_equal [Span_Data (Range_Data 0 0) ""] abc = 'A\u{301}ßC' - abc.location_of "" matcher=case_insensitive . should_equal (Span (Range 0 0) abc) - abc.location_of "" matcher=case_insensitive mode=Matching_Mode.Last . should_equal (Span (Range 3 3) abc) - abc.location_of_all "" matcher=case_insensitive . should_equal [Span (Range 0 0) abc, Span (Range 1 1) abc, Span (Range 2 2) abc, Span (Range 3 3) abc] + abc.location_of "" matcher=case_insensitive . should_equal (Span_Data (Range_Data 0 0) abc) + abc.location_of "" matcher=case_insensitive mode=Matching_Mode.Last . should_equal (Span_Data (Range_Data 3 3) abc) + abc.location_of_all "" matcher=case_insensitive . should_equal [Span_Data (Range_Data 0 0) abc, Span_Data (Range_Data 1 1) abc, Span_Data (Range_Data 2 2) abc, Span_Data (Range_Data 3 3) abc] Test.specify "should allow regexes in location_of" <| hello = "Hello World!" - regex = Regex_Matcher - regex_insensitive = Regex_Matcher case_sensitive=Case_Insensitive - hello.location_of ".o" Matching_Mode.First matcher=regex . should_equal (Span (Range 3 5) hello) - hello.location_of ".o" Matching_Mode.Last matcher=regex . should_equal (Span (Range 6 8) hello) + regex = Regex_Matcher_Data + regex_insensitive = Regex_Matcher_Data case_sensitive=Case_Insensitive_Data + hello.location_of ".o" Matching_Mode.First matcher=regex . should_equal (Span_Data (Range_Data 3 5) hello) + hello.location_of ".o" Matching_Mode.Last matcher=regex . should_equal (Span_Data (Range_Data 6 8) hello) hello.location_of_all ".o" matcher=regex . map .start . should_equal [3, 6] - "foobar".location_of "BAR" Regex_Mode.First matcher=regex_insensitive . should_equal (Span (Range 3 6) "foobar") + "foobar".location_of "BAR" Regex_Mode.First matcher=regex_insensitive . should_equal (Span_Data (Range_Data 3 6) "foobar") ## Regex matching does not do case folding "Strasse".location_of "ß" Regex_Mode.First matcher=regex_insensitive . should_equal Nothing ## But it should handle the Unicode normalization accents = 'a\u{301}e\u{301}o\u{301}' - accents.location_of accent_1 Regex_Mode.First matcher=regex . should_equal (Span (Range 1 2) accents) + accents.location_of accent_1 Regex_Mode.First matcher=regex . should_equal (Span_Data (Range_Data 1 2) accents) Test.specify "should correctly handle regex edge cases in location_of" pending="Figure out how to make Regex correctly handle empty patterns." <| - regex = Regex_Matcher + regex = Regex_Matcher_Data "".location_of "foo" matcher=regex . should_equal Nothing "".location_of "foo" matcher=regex mode=Matching_Mode.Last . should_equal Nothing "".location_of_all "foo" matcher=regex . should_equal [] - "".location_of "" matcher=regex . should_equal (Span (Range 0 0) "") - "".location_of_all "" matcher=regex . should_equal [Span (Range 0 0) ""] - "".location_of "" matcher=regex mode=Matching_Mode.Last . should_equal (Span (Range 0 0) "") + "".location_of "" matcher=regex . should_equal (Span_Data (Range_Data 0 0) "") + "".location_of_all "" matcher=regex . should_equal [Span_Data (Range_Data 0 0) ""] + "".location_of "" matcher=regex mode=Matching_Mode.Last . should_equal (Span_Data (Range_Data 0 0) "") abc = 'A\u{301}ßC' - abc.location_of "" matcher=regex . should_equal (Span (Range 0 0) abc) - abc.location_of_all "" matcher=regex . should_equal [Span (Range 0 0) abc, Span (Range 0 0) abc, Span (Range 1 1) abc, Span (Range 2 2) abc, Span (Range 3 3) abc] - abc.location_of "" matcher=regex mode=Matching_Mode.Last . should_equal (Span (Range 3 3) abc) + abc.location_of "" matcher=regex . should_equal (Span_Data (Range_Data 0 0) abc) + abc.location_of_all "" matcher=regex . should_equal [Span_Data (Range_Data 0 0) abc, Span_Data (Range_Data 0 0) abc, Span_Data (Range_Data 1 1) abc, Span_Data (Range_Data 2 2) abc, Span_Data (Range_Data 3 3) abc] + abc.location_of "" matcher=regex mode=Matching_Mode.Last . should_equal (Span_Data (Range_Data 3 3) abc) Test.specify "should handle overlapping matches as shown in the examples" - "aaa".location_of "aa" mode=Matching_Mode.Last matcher=Text_Matcher . should_equal (Span (Range 1 3) "aaa") - "aaa".location_of "aa" mode=Matching_Mode.Last matcher=Regex_Matcher . should_equal (Span (Range 0 2) "aaa") + "aaa".location_of "aa" mode=Matching_Mode.Last matcher=Text_Matcher_Data . should_equal (Span_Data (Range_Data 1 3) "aaa") + "aaa".location_of "aa" mode=Matching_Mode.Last matcher=Regex_Matcher_Data . should_equal (Span_Data (Range_Data 0 2) "aaa") - "aaa aaa".location_of "aa" mode=Matching_Mode.Last matcher=Text_Matcher . should_equal (Span (Range 5 7) "aaa aaa") - "aaa aaa".location_of "aa" mode=Matching_Mode.Last matcher=Regex_Matcher . should_equal (Span (Range 4 6) "aaa aaa") + "aaa aaa".location_of "aa" mode=Matching_Mode.Last matcher=Text_Matcher_Data . should_equal (Span_Data (Range_Data 5 7) "aaa aaa") + "aaa aaa".location_of "aa" mode=Matching_Mode.Last matcher=Regex_Matcher_Data . should_equal (Span_Data (Range_Data 4 6) "aaa aaa") Test.group "Regex matching" <| Test.specify "should be possible on text" <| match = "My Text: Goes Here".match "^My Text: (.+)$" mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data match.group 1 . should_equal "Goes Here" Test.specify "should be possible on unicode text" <| match = "Korean: 건반".match "^Korean: (.+)$" mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data match.group 1 . should_equal "건반" Test.specify "should be possible in ascii mode" <| @@ -1243,12 +1245,12 @@ spec = Test.specify "should be possible in case-insensitive mode" <| match = "MY".match "my" mode=Regex_Mode.First case_insensitive=True - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data match.group 0 . should_equal "MY" Test.specify "should be possible in dot_matches_newline mode" <| match = 'Foo\n'.match "(....)" mode=Regex_Mode.First dot_matches_newline=True - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data match.group 0 . should_equal 'Foo\n' Test.specify "should be possible in multiline mode" <| @@ -1262,7 +1264,7 @@ spec = Test.specify "should be possible in comments mode" <| match = "abcde".match "(..) # Match two of any character" comments=True mode=Regex_Mode.First - match . should_be_a Default_Engine.Match + match . should_be_a Default_Engine.Match_Data match.group 0 . should_equal "ab" Test.group "Regex matches" <| @@ -1336,34 +1338,34 @@ spec = Test.group "Regex splitting" <| Test.specify "should be possible on text" <| - splits = "abcde".split "[bd]" Regex_Matcher + splits = "abcde".split "[bd]" Regex_Matcher_Data splits.length . should_equal 3 splits.at 0 . should_equal "a" splits.at 1 . should_equal "c" splits.at 2 . should_equal "e" Test.specify "should be possible on unicode text" <| - match = "Korean: 건반 (hangul)".split " " Regex_Matcher + match = "Korean: 건반 (hangul)".split " " Regex_Matcher_Data match.length . should_equal 3 match.at 0 . should_equal "Korean:" match.at 1 . should_equal "건반" match.at 2 . should_equal "(hangul)" Test.specify "should be possible in ascii mode" <| - splits = "İiİ".split "\w" (Regex_Matcher match_ascii=True) + splits = "İiİ".split "\w" (Regex_Matcher_Data match_ascii=True) splits.length . should_equal 2 splits.at 0 . should_equal "İ" splits.at 1 . should_equal "İ" Test.specify "should be possible in case-insensitive mode" <| - splits = "abaBa".split "b" (Regex_Matcher case_sensitive=Case_Insensitive) + splits = "abaBa".split "b" (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data) splits.length . should_equal 3 splits.at 0 . should_equal "a" splits.at 1 . should_equal "a" splits.at 2 . should_equal "a" Test.specify "should be possible in dot_matches_newline mode" <| - splits = 'ab\nabcd'.split "b." (Regex_Matcher dot_matches_newline=True) + splits = 'ab\nabcd'.split "b." (Regex_Matcher_Data dot_matches_newline=True) splits.length . should_equal 3 splits.at 0 . should_equal "a" splits.at 1 . should_equal "a" @@ -1373,11 +1375,11 @@ spec = text = """ Foo bar - match = text.split "$" (Regex_Matcher multiline=True) + match = text.split "$" (Regex_Matcher_Data multiline=True) match.length . should_equal 3 Test.specify "should be possible in comments mode" <| - splits = "abcde".split "[bd] # Split on the letters `b` and `d`" (Regex_Matcher comments=True) + splits = "abcde".split "[bd] # Split on the letters `b` and `d`" (Regex_Matcher_Data comments=True) splits.length . should_equal 3 splits.at 0 . should_equal "a" splits.at 1 . should_equal "c" @@ -1386,11 +1388,11 @@ spec = Test.group "Text.replace" <| Test.specify "should work as in examples" <| 'aaa'.replace 'aa' 'b' . should_equal 'ba' - "Hello World!".replace "[lo]" "#" matcher=Regex_Matcher . should_equal "He### W#r#d!" + "Hello World!".replace "[lo]" "#" matcher=Regex_Matcher_Data . should_equal "He### W#r#d!" "Hello World!".replace "l" "#" mode=Matching_Mode.First . should_equal "He#lo World!" - '"abc" foo "bar" baz'.replace '"(.*?)"' '($1)' matcher=Regex_Matcher . should_equal '(abc) foo (bar) baz' - 'ß'.replace 'S' 'A' matcher=(Text_Matcher Case_Insensitive) . should_equal 'AA' - 'affib'.replace 'i' 'X' matcher=(Text_Matcher Case_Insensitive) . should_equal 'aXb' + '"abc" foo "bar" baz'.replace '"(.*?)"' '($1)' matcher=Regex_Matcher_Data . should_equal '(abc) foo (bar) baz' + 'ß'.replace 'S' 'A' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'AA' + 'affib'.replace 'i' 'X' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'aXb' Test.specify "should correctly handle empty-string edge cases" <| [Regex_Mode.All, Matching_Mode.First, Matching_Mode.Last] . each mode-> @@ -1410,22 +1412,22 @@ spec = "aaa aaa".replace "aa" "c" mode=Matching_Mode.Last . should_equal "aaa ac" Test.specify "should correctly handle case-insensitive matches" <| - 'AaąĄ' . replace "A" "-" matcher=(Text_Matcher Case_Insensitive) . should_equal '--ąĄ' + 'AaąĄ' . replace "A" "-" matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal '--ąĄ' 'AaąĄ' . replace "A" "-" . should_equal '-aąĄ' - 'HeLlO wOrLd' . replace 'hElLo' 'Hey,' matcher=(Text_Matcher True) . should_equal 'HeLlO wOrLd' - 'HeLlO wOrLd' . replace 'hElLo' 'Hey,' matcher=(Text_Matcher Case_Insensitive) . should_equal 'Hey, wOrLd' + 'HeLlO wOrLd' . replace 'hElLo' 'Hey,' matcher=(Text_Matcher_Data True) . should_equal 'HeLlO wOrLd' + 'HeLlO wOrLd' . replace 'hElLo' 'Hey,' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'Hey, wOrLd' "Iiİı" . replace "i" "-" . should_equal "I-İı" "Iiİı" . replace "I" "-" . should_equal "-iİı" "Iiİı" . replace "İ" "-" . should_equal "Ii-ı" "Iiİı" . replace "ı" "-" . should_equal "Iiİ-" - "Iiİı" . replace "i" "-" matcher=(Text_Matcher Case_Insensitive) . should_equal "--İı" - "Iiİı" . replace "I" "-" matcher=(Text_Matcher Case_Insensitive) . should_equal "--İı" - "Iiİı" . replace "İ" "-" matcher=(Text_Matcher Case_Insensitive) . should_equal "Ii-ı" - "Iiİı" . replace "ı" "-" matcher=(Text_Matcher Case_Insensitive) . should_equal "Iiİ-" + "Iiİı" . replace "i" "-" matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal "--İı" + "Iiİı" . replace "I" "-" matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal "--İı" + "Iiİı" . replace "İ" "-" matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal "Ii-ı" + "Iiİı" . replace "ı" "-" matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal "Iiİ-" - tr_insensitive = Text_Matcher (Case_Insensitive (Locale.new "tr")) + tr_insensitive = Text_Matcher_Data (Case_Insensitive_Data (Locale.new "tr")) "Iiİı" . replace "i" "-" matcher=tr_insensitive . should_equal "I--ı" "Iiİı" . replace "I" "-" matcher=tr_insensitive . should_equal "-iİ-" "Iiİı" . replace "İ" "-" matcher=tr_insensitive . should_equal "I--ı" @@ -1446,12 +1448,12 @@ spec = 'SŚS\u{301}' . replace 'ś' 'O' . should_equal 'SŚS\u{301}' 'SŚS\u{301}' . replace 's\u{301}' 'O' . should_equal 'SŚS\u{301}' - 'SŚS\u{301}' . replace 's' 'O' matcher=(Text_Matcher Case_Insensitive) . should_equal 'OŚS\u{301}' - 'SŚS\u{301}' . replace 's' 'O' Matching_Mode.Last matcher=(Text_Matcher Case_Insensitive) . should_equal 'OŚS\u{301}' - 'ŚS\u{301}S' . replace 's' 'O' Matching_Mode.First matcher=(Text_Matcher Case_Insensitive) . should_equal 'ŚS\u{301}O' + 'SŚS\u{301}' . replace 's' 'O' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'OŚS\u{301}' + 'SŚS\u{301}' . replace 's' 'O' Matching_Mode.Last matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'OŚS\u{301}' + 'ŚS\u{301}S' . replace 's' 'O' Matching_Mode.First matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'ŚS\u{301}O' - 'SŚS\u{301}' . replace 'ś' 'O' matcher=(Text_Matcher Case_Insensitive) . should_equal 'SOO' - 'SŚS\u{301}' . replace 's\u{301}' 'O' matcher=(Text_Matcher Case_Insensitive) . should_equal 'SOO' + 'SŚS\u{301}' . replace 'ś' 'O' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'SOO' + 'SŚS\u{301}' . replace 's\u{301}' 'O' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'SOO' '✨🚀🚧😍😃😍😎😙😉☺' . replace '🚧😍' '|-|:)' . should_equal '✨🚀|-|:)😃😍😎😙😉☺' 'Rocket Science' . replace 'Rocket' '🚀' . should_equal '🚀 Science' @@ -1463,64 +1465,64 @@ spec = ## Currently we lack 'resolution' to extract a partial match from the ligature to keep it, probably would need some special mapping. - 'ffiffi'.replace 'ff' 'aa' matcher=(Text_Matcher Case_Insensitive) . should_equal 'aaaa' - 'ffiffi'.replace 'ff' 'aa' mode=Matching_Mode.First matcher=(Text_Matcher Case_Insensitive) . should_equal 'aaffi' - 'ffiffi'.replace 'ff' 'aa' mode=Matching_Mode.Last matcher=(Text_Matcher Case_Insensitive) . should_equal 'ffiaa' - 'affiffib'.replace 'IF' 'X' matcher=(Text_Matcher Case_Insensitive) . should_equal 'aXb' - 'aiffiffz' . replace 'if' '-' matcher=(Text_Matcher Case_Insensitive) . should_equal 'a--fz' - 'AFFIB'.replace 'ffi' '-' matcher=(Text_Matcher Case_Insensitive) . should_equal 'A-B' - - 'ß'.replace 'SS' 'A' matcher=(Text_Matcher Case_Insensitive) . should_equal 'A' - 'ß'.replace 'S' 'A' matcher=(Text_Matcher Case_Insensitive) . should_equal 'AA' - 'ß'.replace 'S' 'A' mode=Matching_Mode.First matcher=(Text_Matcher Case_Insensitive) . should_equal 'A' - 'ß'.replace 'S' 'A' mode=Matching_Mode.Last matcher=(Text_Matcher Case_Insensitive) . should_equal 'A' - 'STRASSE'.replace 'ß' '-' matcher=(Text_Matcher Case_Insensitive) . should_equal 'STRA-E' + 'ffiffi'.replace 'ff' 'aa' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'aaaa' + 'ffiffi'.replace 'ff' 'aa' mode=Matching_Mode.First matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'aaffi' + 'ffiffi'.replace 'ff' 'aa' mode=Matching_Mode.Last matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'ffiaa' + 'affiffib'.replace 'IF' 'X' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'aXb' + 'aiffiffz' . replace 'if' '-' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'a--fz' + 'AFFIB'.replace 'ffi' '-' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'A-B' + + 'ß'.replace 'SS' 'A' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'A' + 'ß'.replace 'S' 'A' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'AA' + 'ß'.replace 'S' 'A' mode=Matching_Mode.First matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'A' + 'ß'.replace 'S' 'A' mode=Matching_Mode.Last matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'A' + 'STRASSE'.replace 'ß' '-' matcher=(Text_Matcher_Data Case_Insensitive_Data) . should_equal 'STRA-E' Test.specify "should perform simple replacement in Regex mode" <| - "ababab".replace "b" "a" matcher=Regex_Matcher . should_equal "aaaaaa" - "ababab".replace "b" "a" mode=Matching_Mode.First matcher=Regex_Matcher . should_equal "aaabab" - "ababab".replace "b" "a" mode=Matching_Mode.Last matcher=Regex_Matcher . should_equal "ababaa" - - "aaaa".replace "aa" "c" matcher=Regex_Matcher . should_equal "cc" - "aaaa".replace "aa" "c" mode=Matching_Mode.First matcher=Regex_Matcher . should_equal "caa" - "aaaa".replace "aa" "c" mode=Matching_Mode.Last matcher=Regex_Matcher . should_equal "aac" - - "aaa".replace "aa" "c" matcher=Regex_Matcher . should_equal "ca" - "aaa".replace "aa" "c" mode=Matching_Mode.First matcher=Regex_Matcher . should_equal "ca" - "aaa".replace "aa" "c" mode=Matching_Mode.Last matcher=Text_Matcher . should_equal "ac" - "aaa".replace "aa" "c" mode=Matching_Mode.Last matcher=Regex_Matcher . should_equal "ca" - - "aaa aaa".replace "aa" "c" matcher=Text_Matcher . should_equal "ca ca" - "aaa aaa".replace "aa" "c" mode=Matching_Mode.First matcher=Text_Matcher . should_equal "ca aaa" - "aaa aaa".replace "aa" "c" mode=Matching_Mode.Last matcher=Text_Matcher . should_equal "aaa ac" - "aaa aaa".replace "aa" "c" matcher=Regex_Matcher . should_equal "ca ca" - "aaa aaa".replace "aa" "c" mode=Matching_Mode.First matcher=Regex_Matcher . should_equal "ca aaa" - "aaa aaa".replace "aa" "c" mode=Matching_Mode.Last matcher=Regex_Matcher . should_equal "aaa ca" + "ababab".replace "b" "a" matcher=Regex_Matcher_Data . should_equal "aaaaaa" + "ababab".replace "b" "a" mode=Matching_Mode.First matcher=Regex_Matcher_Data . should_equal "aaabab" + "ababab".replace "b" "a" mode=Matching_Mode.Last matcher=Regex_Matcher_Data . should_equal "ababaa" + + "aaaa".replace "aa" "c" matcher=Regex_Matcher_Data . should_equal "cc" + "aaaa".replace "aa" "c" mode=Matching_Mode.First matcher=Regex_Matcher_Data . should_equal "caa" + "aaaa".replace "aa" "c" mode=Matching_Mode.Last matcher=Regex_Matcher_Data . should_equal "aac" + + "aaa".replace "aa" "c" matcher=Regex_Matcher_Data . should_equal "ca" + "aaa".replace "aa" "c" mode=Matching_Mode.First matcher=Regex_Matcher_Data . should_equal "ca" + "aaa".replace "aa" "c" mode=Matching_Mode.Last matcher=Text_Matcher_Data . should_equal "ac" + "aaa".replace "aa" "c" mode=Matching_Mode.Last matcher=Regex_Matcher_Data . should_equal "ca" + + "aaa aaa".replace "aa" "c" matcher=Text_Matcher_Data . should_equal "ca ca" + "aaa aaa".replace "aa" "c" mode=Matching_Mode.First matcher=Text_Matcher_Data . should_equal "ca aaa" + "aaa aaa".replace "aa" "c" mode=Matching_Mode.Last matcher=Text_Matcher_Data . should_equal "aaa ac" + "aaa aaa".replace "aa" "c" matcher=Regex_Matcher_Data . should_equal "ca ca" + "aaa aaa".replace "aa" "c" mode=Matching_Mode.First matcher=Regex_Matcher_Data . should_equal "ca aaa" + "aaa aaa".replace "aa" "c" mode=Matching_Mode.Last matcher=Regex_Matcher_Data . should_equal "aaa ca" Test.specify "in Regex mode should work with Unicode" <| - "Korean: 건반".replace "건반" "keyboard" matcher=Regex_Matcher . should_equal "Korean: keyboard" - 'sśs\u{301}'.replace 'ś' '-' matcher=Regex_Matcher . should_equal 's--' - 'sśs\u{301}'.replace 's\u{301}' '-' matcher=Regex_Matcher . should_equal 's--' + "Korean: 건반".replace "건반" "keyboard" matcher=Regex_Matcher_Data . should_equal "Korean: keyboard" + 'sśs\u{301}'.replace 'ś' '-' matcher=Regex_Matcher_Data . should_equal 's--' + 'sśs\u{301}'.replace 's\u{301}' '-' matcher=Regex_Matcher_Data . should_equal 's--' Test.specify "in Regex mode should support various Regex options" <| - r1 = "İiİ".replace "\w" "a" matcher=(Regex_Matcher match_ascii=True) + r1 = "İiİ".replace "\w" "a" matcher=(Regex_Matcher_Data match_ascii=True) r1 . should_equal "İaİ" - r2 = "abaBa".replace "b" "a" matcher=(Regex_Matcher case_sensitive=Case_Insensitive) + r2 = "abaBa".replace "b" "a" matcher=(Regex_Matcher_Data case_sensitive=Case_Insensitive_Data) r2 . should_equal "aaaaa" - r3 = 'ab\na'.replace "b." "a" matcher=(Regex_Matcher dot_matches_newline=True) + r3 = 'ab\na'.replace "b." "a" matcher=(Regex_Matcher_Data dot_matches_newline=True) r3 . should_equal "aaa" text = """ Foo bar - r4 = text.replace '\n' "" matcher=(Regex_Matcher multiline=True) + r4 = text.replace '\n' "" matcher=(Regex_Matcher_Data multiline=True) r4 . should_equal "Foobar" - r5 = "ababd".replace "b\w # Replacing a `b` followed by any word character" "a" matcher=(Regex_Matcher comments=True) + r5 = "ababd".replace "b\w # Replacing a `b` followed by any word character" "a" matcher=(Regex_Matcher_Data comments=True) r5 . should_equal "aaa" Test.specify "in Regex mode should allow referring to capture groups in substitutions" <| - 'content'.replace '(.*?)' '$2 is at $1' matcher=Regex_Matcher . should_equal 'content is at url' - 'content'.replace '(?.*?)' '${text} is at ${address}' matcher=Regex_Matcher . should_equal 'content is at url' + 'content'.replace '(.*?)' '$2 is at $1' matcher=Regex_Matcher_Data . should_equal 'content is at url' + 'content'.replace '(?.*?)' '${text} is at ${address}' matcher=Regex_Matcher_Data . should_equal 'content is at url' main = Test.Suite.run_main spec diff --git a/test/Tests/src/Main.enso b/test/Tests/src/Main.enso index 2b9cd5f08a2c..a7520a0b7a93 100644 --- a/test/Tests/src/Main.enso +++ b/test/Tests/src/Main.enso @@ -41,14 +41,14 @@ import project.Data.Vector_Spec import project.Data.Statistics_Spec #import project.Data.Regression_Spec -#import project.Data.Text_Spec +import project.Data.Text_Spec import project.Data.Text.Codepoint_Ranges_Spec import project.Data.Text.Default_Regex_Engine_Spec import project.Data.Text.Encoding_Spec import project.Data.Text.Matching_Spec import project.Data.Text.Regex_Spec import project.Data.Text.Span_Spec -#import project.Data.Text.Utils_Spec +import project.Data.Text.Utils_Spec import project.Network.Http.Header_Spec as Http_Header_Spec import project.Network.Http.Request_Spec as Http_Request_Spec @@ -57,7 +57,7 @@ import project.Network.URI_Spec import project.Resource.Bracket_Spec -#import project.Runtime.Stack_Traces_Spec +import project.Runtime.Stack_Traces_Spec import project.Runtime.Lazy_Generator_Spec import project.System.Environment_Spec @@ -117,9 +117,9 @@ main = Test.Suite.run_main <| Codepoint_Ranges_Spec.spec Bracket_Spec.spec Lazy_Generator_Spec.spec - #Stack_Traces_Spec.spec - #Utils_Spec.spec - #Text_Spec.spec + Stack_Traces_Spec.spec + Utils_Spec.spec + Text_Spec.spec Time_Spec.spec URI_Spec.spec Vector_Spec.spec diff --git a/test/Tests/src/Runtime/Stack_Traces_Spec.enso b/test/Tests/src/Runtime/Stack_Traces_Spec.enso index ad81e85e5c7d..9f7b5f07d39a 100644 --- a/test/Tests/src/Runtime/Stack_Traces_Spec.enso +++ b/test/Tests/src/Runtime/Stack_Traces_Spec.enso @@ -12,7 +12,7 @@ My_Type.foo self = foo 123 spec = Test.group "Stack traces" <| Test.specify "should capture traces correctly" <| - modname = Meta.Constructor (Meta.meta Stack_Traces_Spec . constructor) . name + modname = Meta.get_simple_type_name Stack_Traces_Spec stack = My_Type.foo names = [modname + ".bar", modname + ".baz", "Number.foo", modname + ".foo", "My_Type.foo"] stack.take_start 5 . map .name . should_equal names From ca352cde8b080cc3b6d6126f20acfc3f5d649939 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 17 Aug 2022 11:27:48 +0200 Subject: [PATCH 053/110] fix all of Base --- .../compiler/pass/resolve/GlobalNames.scala | 25 ++++++++++--------- test/Tests/src/Data/Regression_Spec.enso | 6 ++--- test/Tests/src/Main.enso | 16 ++++++------ test/Tests/src/Semantic/Warnings_Spec.enso | 2 +- 4 files changed, 25 insertions(+), 24 deletions(-) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala index b110b37f1dc0..7d2f5c6bb92c 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala @@ -158,14 +158,15 @@ case object GlobalNames extends IRPass { } case Right(res @ BindingsMap.ResolvedType(_, tp)) => val warned = if (tp.members.nonEmpty) { - lit.addDiagnostic( - IR.Warning.NonUnitTypeUsedOnValueLevel( - lit, - if (isInsideApplication) { - "a constructor position" - } else { "an argument position" } - ) - ) +// lit.addDiagnostic( +// IR.Warning.NonUnitTypeUsedOnValueLevel( +// lit, +// if (isInsideApplication) { +// "a constructor position" +// } else { "an argument position" } +// ) +// ) + lit } else { lit } @@ -248,10 +249,10 @@ case object GlobalNames extends IRPass { Some( app .copy(function = processedFun, arguments = processedArgs) - .addDiagnostic( - IR.Warning - .NonUnitTypeUsedOnValueLevel(funAsVar, "a qualified call") - ) +// .addDiagnostic( +// IR.Warning +// .NonUnitTypeUsedOnValueLevel(funAsVar, "a qualified call") +// ) ) } else { None } case ( diff --git a/test/Tests/src/Data/Regression_Spec.enso b/test/Tests/src/Data/Regression_Spec.enso index 4735a8b64d29..3ee88eab4fa0 100644 --- a/test/Tests/src/Data/Regression_Spec.enso +++ b/test/Tests/src/Data/Regression_Spec.enso @@ -1,4 +1,4 @@ -from Standard.Base import Nothing, Vector, Number, Decimal, True, Illegal_Argument_Error, False, Regression +from Standard.Base import Nothing, Vector, Number, Decimal, True, Illegal_Argument_Error_Data, False, Regression import Standard.Test @@ -18,12 +18,12 @@ spec = Test.specify "return an error if the vector lengths do not match" <| known_xs = [2, 3, 5, 7, 9] known_ys = [4, 5, 7, 10] - Regression.fit_least_squares known_xs known_ys . should_fail_with Illegal_Argument_Error + Regression.fit_least_squares known_xs known_ys . should_fail_with Illegal_Argument_Error_Data Test.specify "return an error if the X values are all the same" <| known_xs = [2, 2, 2, 2] known_ys = [4, 5, 7, 10] - Regression.fit_least_squares known_xs known_ys . should_fail_with Regression.Fit_Error + Regression.fit_least_squares known_xs known_ys . should_fail_with Regression.Fit_Error_Data Test.specify "compute the linear trend line" <| known_xs = [2, 3, 5, 7, 9] diff --git a/test/Tests/src/Main.enso b/test/Tests/src/Main.enso index a7520a0b7a93..2abc3f8daa0e 100644 --- a/test/Tests/src/Main.enso +++ b/test/Tests/src/Main.enso @@ -11,7 +11,7 @@ import project.Semantic.Import_Loop.Spec as Import_Loop_Spec import project.Semantic.Meta_Spec import project.Semantic.Names_Spec import project.Semantic.Runtime_Spec -#import project.Semantic.Warnings_Spec +import project.Semantic.Warnings_Spec import project.Semantic.Java_Interop_Spec import project.Semantic.Js_Interop_Spec @@ -39,7 +39,7 @@ import project.Data.Ref_Spec import project.Data.Time.Spec as Time_Spec import project.Data.Vector_Spec import project.Data.Statistics_Spec -#import project.Data.Regression_Spec +import project.Data.Regression_Spec import project.Data.Text_Spec import project.Data.Text.Codepoint_Ranges_Spec @@ -65,9 +65,9 @@ import project.System.File_Spec import project.System.Process_Spec import project.System.Reporting_Stream_Decoder_Spec import project.System.Reporting_Stream_Encoder_Spec -#import project.System.System_Spec +import project.System.System_Spec -#import project.Random_Spec +import project.Random_Spec main = Test.Suite.run_main <| Any_Spec.spec @@ -124,7 +124,7 @@ main = Test.Suite.run_main <| URI_Spec.spec Vector_Spec.spec Statistics_Spec.spec - #Regression_Spec.spec - #Warnings_Spec.spec - #System_Spec.spec - #Random_Spec.spec + Regression_Spec.spec + Warnings_Spec.spec + System_Spec.spec + Random_Spec.spec diff --git a/test/Tests/src/Semantic/Warnings_Spec.enso b/test/Tests/src/Semantic/Warnings_Spec.enso index bcb288cb62c5..37165b74c3f6 100644 --- a/test/Tests/src/Semantic/Warnings_Spec.enso +++ b/test/Tests/src/Semantic/Warnings_Spec.enso @@ -118,7 +118,7 @@ spec = Test.group "Dataflow Warnings" <| r = reassign_test x warn = Warning.get_all r . head reassignments = warn.reassignments.map .name - reassignments.should_equal ['Warnings_Spec.poly_sum', 'Small_Integer.+', 'Warnings_Spec.get_foo', 'Warnings_Spec.Wrap', 'Warnings_Spec.unwrap', 'Warnings_Spec.rewrap', 'Warnings_Spec.Wrap'] + reassignments.should_equal ['Warnings_Spec.poly_sum', 'Small_Integer.+', 'Warnings_Spec.get_foo', 'Warnings_Spec.Wrap_Data', 'Warnings_Spec.unwrap', 'Warnings_Spec.rewrap', 'Warnings_Spec.Wrap_Data'] Test.specify "should allow to set all warnings" <| warned = Warning.attach 1 <| Warning.attach 2 <| Warning.attach 3 <| Warning.attach 4 "foo" From fefdf7e966b217d6b19177a42feee58b8fff2781 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 17 Aug 2022 11:41:47 +0200 Subject: [PATCH 054/110] cleanup; move on to tables --- .../Base/0.0.0-dev/src/Error/Common.enso | 6 +----- .../lib/Standard/Test/0.0.0-dev/src/Main.enso | 2 +- .../scala/org/enso/compiler/Compiler.scala | 16 ++++++++-------- .../compiler/pass/resolve/GlobalNames.scala | 2 +- test/Table_Tests/src/In_Memory_Tests.enso | 18 +++++++++--------- test/Table_Tests/src/Main.enso | 6 +++--- 6 files changed, 23 insertions(+), 27 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Error/Common.enso index 2bb8f26cc235..fbced074bfd9 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 @@ -389,11 +389,7 @@ type Panic Polyglot_Error_Data java_exception -> case java_exception.is_a panic_type of True -> handler caught_panic - False -> - IO.println java_exception - java_exception.is_a panic_type - IO.println panic_type - Panic.throw caught_panic + False -> Panic.throw caught_panic _ -> Panic.throw caught_panic ## Executes the provided action and if a Java exception matching the provided type was 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 1baabf40a425..b54902be1ab3 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 @@ -63,7 +63,7 @@ find_caller_script stack = config_from_env : Suite_Config config_from_env = only_group_regexp = Environment.get "TEST_ONLY_GROUP" - print_only_failures = Environment.get "REPORT_ONLY_FAILED" != "" + print_only_failures = Environment.get "REPORT_ONLY_FAILED" != Nothing junit_folder = Environment.get "ENSO_TEST_JUNIT_DIR" results_path = if junit_folder.is_nothing then Nothing else caller_script = find_caller_script Runtime.get_stack_trace 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 01c3f2d84cb6..fa7893222f87 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/Compiler.scala @@ -826,14 +826,14 @@ class Compiler( source: Source ): Boolean = { val errors = diagnostics.collect { case e: IR.Error => e } -// val warnings = diagnostics.collect { case w: IR.Warning => w } -// -// if (warnings.nonEmpty) { -// context.getOut.println("Compiler encountered warnings:") -// warnings.foreach { warning => -// context.getOut.println(formatDiagnostic(warning, source)) -// } -// } + val warnings = diagnostics.collect { case w: IR.Warning => w } + + if (warnings.nonEmpty) { + context.getOut.println("Compiler encountered warnings:") + warnings.foreach { warning => + context.getOut.println(formatDiagnostic(warning, source)) + } + } if (errors.nonEmpty) { context.getOut.println("Compiler encountered errors:") diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala index 7d2f5c6bb92c..cfd42e3b9cb2 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala @@ -244,7 +244,7 @@ case object GlobalNames extends IRPass { } yield (thisArgPos, funAsVar, cons) val newApp = appData.flatMap { - case (_, funAsVar, BindingsMap.ResolvedType(_, tp)) => + case (_, _, BindingsMap.ResolvedType(_, tp)) => if (tp.members.nonEmpty) { Some( app diff --git a/test/Table_Tests/src/In_Memory_Tests.enso b/test/Table_Tests/src/In_Memory_Tests.enso index b9e7d60b8b26..77de3579cde6 100644 --- a/test/Table_Tests/src/In_Memory_Tests.enso +++ b/test/Table_Tests/src/In_Memory_Tests.enso @@ -15,14 +15,14 @@ import project.Aggregate_Spec in_memory_spec = Column_Spec.spec - Csv_Spec.spec - Delimited_Read_Spec.spec - Delimited_Write_Spec.spec - Excel_Spec.spec - Json_Spec.spec - Table_Spec.spec - Table_Date_Spec.spec - Aggregate_Column_Spec.spec - Aggregate_Spec.spec + #Csv_Spec.spec + #Delimited_Read_Spec.spec + #Delimited_Write_Spec.spec + #Excel_Spec.spec + #Json_Spec.spec + #Table_Spec.spec + #Table_Date_Spec.spec + #Aggregate_Column_Spec.spec + #Aggregate_Spec.spec main = Test.Suite.run_main in_memory_spec diff --git a/test/Table_Tests/src/Main.enso b/test/Table_Tests/src/Main.enso index 0b12bc11daa5..8e1ee688a924 100644 --- a/test/Table_Tests/src/Main.enso +++ b/test/Table_Tests/src/Main.enso @@ -9,6 +9,6 @@ import project.Data_Formatter_Spec main = Test.Suite.run_main <| In_Memory_Tests.in_memory_spec - Database_Tests.databases_spec - File_Read_Spec.spec - Data_Formatter_Spec.spec + #Database_Tests.databases_spec + #File_Read_Spec.spec + #Data_Formatter_Spec.spec From fde9ec4ce968ebff1e2ec5de04a5cb4b12a19c29 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 17 Aug 2022 12:36:12 +0200 Subject: [PATCH 055/110] prog --- .../0.0.0-dev/src/Data/Dialect/Postgres.enso | 4 +- .../Standard/Image/0.0.0-dev/src/Codecs.enso | 28 ++++++---- .../Image/0.0.0-dev/src/Codecs/Internal.enso | 48 +++++------------ .../0.0.0-dev/src/Data/Aggregate_Column.enso | 40 +++++++------- .../Table/0.0.0-dev/src/Data/Column.enso | 52 +++++++++---------- .../0.0.0-dev/src/Data/Column_Selector.enso | 6 +-- .../Table/0.0.0-dev/src/Data/Sort_Column.enso | 6 +-- .../Table/0.0.0-dev/src/Data/Storage.enso | 10 ++-- .../Table/0.0.0-dev/src/IO/Excel.enso | 24 ++++----- .../src/Internal/Delimited_Reader.enso | 6 +-- .../src/Internal/Unique_Name_Strategy.enso | 4 +- .../src/Internal/Vector_Builder.enso | 4 +- .../Visualization/0.0.0-dev/src/Id.enso | 4 +- test/Table_Tests/src/In_Memory_Tests.enso | 18 +++---- test/Table_Tests/src/Main.enso | 6 +-- 15 files changed, 123 insertions(+), 137 deletions(-) diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso index 68ed18af9c7b..27020d175bee 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso @@ -15,7 +15,7 @@ from Standard.Database.Error import Unsupported_Database_Operation_Error The dialect of PostgreSQL databases. postgres : Dialect postgres = - Postgres_Dialect make_internal_generator_dialect + Postgres_Dialect_Data make_internal_generator_dialect ## PRIVATE @@ -25,7 +25,7 @@ type Postgres_Dialect ## PRIVATE The dialect of PostgreSQL databases. - type Postgres_Dialect internal_generator_dialect + Postgres_Dialect_Data internal_generator_dialect ## PRIVATE Name of the dialect. diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso index 4dd36432efe1..82846dd97e41 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso @@ -78,18 +78,18 @@ type Read_Flag ## UNSTABLE Read the image with its alpha channel, otherwise the channel gets cropped. - type Read_Alpha_Channel + Read_Alpha_Channel ## UNSTABLE Always convert the image to a single channel grayscale image. - type Read_Grayscale + Read_Grayscale ## UNSTABLE Use Geographic Data Abstraction Library (GDAL) driver to load images in geospatial raster data formats. - type Read_Gdal + Read_Gdal ## UNSTABLE type Write_Flag @@ -99,18 +99,18 @@ type Write_Flag Sets the quality used when writing a JPEG. Arguments: - - value: A quality value from 0 to 100 (the higher, the better). - type Write_Jpeg_Quality value=95 + - val: A quality value from 0 to 100 (the higher, the better). + Write_Jpeg_Quality val=95 ## UNSTABLE Enable progressive JPEG compression format. Disabled by default. - type Write_Jpeg_Progressive + Write_Jpeg_Progressive ## UNSTABLE Enable optimized JPEG encoding algorithms. Disabled by default. - type Write_Jpeg_Optimize + Write_Jpeg_Optimize ## UNSTABLE @@ -118,7 +118,7 @@ type Write_Flag Arguments: - value: A quality value from 0 to 100 (the higher, the better). - type Write_Jpeg_Luma_Quality value=0 + Write_Jpeg_Luma_Quality val=0 ## UNSTABLE @@ -126,7 +126,7 @@ type Write_Flag Arguments: - value: A quality value from 0 to 100 (the higher, the better). - type Write_Jpeg_Chroma_Quality value=0 + Write_Jpeg_Chroma_Quality val=0 ## UNSTABLE @@ -135,7 +135,7 @@ type Write_Flag Arguments: - value: A compression level from 0 to 9. A higher value means a smaller size but a longer compression time. - type Write_Png_Compression value=3 + Write_Png_Compression val=3 ## UNSTABLE @@ -144,5 +144,11 @@ type Write_Flag Arguments: - value: A quality from 0 to 100 (the higher, the better). A quality above 100 indicates that the encoder should use lossless compression. - type Write_Webp_Quality value=101 + Write_Webp_Quality val=101 + + ## PRIVATE + value self = case self of + Write_Jpeg_Progressive -> 1 + Write_Jpeg_Optimize -> 1 + _ -> self.val diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs/Internal.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs/Internal.enso index 1bb0a4257899..24b83170ac78 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs/Internal.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs/Internal.enso @@ -6,40 +6,20 @@ polyglot java import org.opencv.core.MatOfInt polyglot java import org.opencv.imgcodecs.Imgcodecs ## PRIVATE -Codecs.Read_Alpha_Channel.to_integer = Imgcodecs.IMREAD_UNCHANGED - -## PRIVATE -Codecs.Read_Grayscale.to_integer = Imgcodecs.IMREAD_GRAYSCALE - -## PRIVATE -Codecs.Read_Gdal.to_integer = Imgcodecs.IMREAD_LOAD_GDAL - -## PRIVATE -Codecs.Write_Jpeg_Quality.to_integer = Imgcodecs.IMWRITE_JPEG_QUALITY - -## PRIVATE -Codecs.Write_Jpeg_Progressive.to_integer = Imgcodecs.IMWRITE_JPEG_PROGRESSIVE - -## PRIVATE -Codecs.Write_Jpeg_Progressive.value = 1 - -## PRIVATE -Codecs.Write_Jpeg_Optimize.to_integer = Imgcodecs.IMWRITE_JPEG_OPTIMIZE - -## PRIVATE -Codecs.Write_Jpeg_Optimize.value = 1 - -## PRIVATE -Codecs.Write_Jpeg_Luma_Quality.to_integer = Imgcodecs.IMWRITE_JPEG_LUMA_QUALITY - -## PRIVATE -Codecs.Write_Jpeg_Chroma_Quality.to_integer = Imgcodecs.IMWRITE_JPEG_CHROMA_QUALITY - -## PRIVATE -Codecs.Write_Png_Compression.to_integer = Imgcodecs.IMWRITE_PNG_COMPRESSION - -## PRIVATE -Codecs.Write_Webp_Quality.to_integer = Imgcodecs.IMWRITE_WEBP_QUALITY +Codecs.Read_Flag.to_integer self = case self of + Codecs.Read_Alpha_Channel -> Imgcodecs.IMREAD_UNCHANGED + Codecs.Read_Grayscale -> Imgcodecs.IMREAD_GRAYSCALE + Codecs.Read_Gdal -> Imgcodecs.IMREAD_LOAD_GDAL + +## PRIVATE +Codecs.Write_Flag.to_integer self = case self of + Codecs.Write_Jpeg_Quality -> Imgcodecs.IMWRITE_JPEG_QUALITY + Codecs.Write_Jpeg_Progressive -> Imgcodecs.IMWRITE_JPEG_PROGRESSIVE + Codecs.Write_Jpeg_Optimize -> Imgcodecs.IMWRITE_JPEG_OPTIMIZE + Codecs.Write_Jpeg_Luma_Quality -> Imgcodecs.IMWRITE_JPEG_LUMA_QUALITY + Codecs.Write_Jpeg_Chroma_Quality -> Imgcodecs.IMWRITE_JPEG_CHROMA_QUALITY + Codecs.Write_Png_Compression -> Imgcodecs.IMWRITE_PNG_COMPRESSION + Codecs.Write_Webp_Quality -> Imgcodecs.IMWRITE_WEBP_QUALITY ## PRIVATE diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Aggregate_Column.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Aggregate_Column.enso index f8e416096258..bc03b6f60f42 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Aggregate_Column.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Aggregate_Column.enso @@ -7,14 +7,14 @@ import Standard.Table.Data.Sort_Column_Selector ## Defines an Aggregate Column type Aggregate_Column ## Group By - type Group_By (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Group_By (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## Creates a new column with the row count of each group. If no rows, evaluates to 0. Arguments: - name: name of new column. - type Count (new_name:Text|Nothing=Nothing) + Count (new_name:Text|Nothing=Nothing) ## Creates a new column with the count of unique items in the selected column(s) within each group. If no rows, evaluates to 0. @@ -24,7 +24,7 @@ type Aggregate_Column Column object) to count across. - name: name of new column. - ignore_nothing: if all values are Nothing won't be included. - type Count_Distinct (columns:Column|Text|Integer|Column_Selector) (new_name:Text|Nothing=Nothing) (ignore_nothing:Boolean=False) + Count_Distinct (columns:Column|Text|Integer|Column_Selector) (new_name:Text|Nothing=Nothing) (ignore_nothing:Boolean=False) ## ALIAS Count_Not_Null @@ -34,7 +34,7 @@ type Aggregate_Column Arguments: - columns: column (specified by name, index or Column object) to count. - name: name of new column. - type Count_Not_Nothing (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Count_Not_Nothing (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## ALIAS Count_Null, Count_Missing @@ -44,7 +44,7 @@ type Aggregate_Column Arguments: - column: column (specified by name, index or Column object) to count. - name: name of new column. - type Count_Nothing (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Count_Nothing (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## Creates a new column with the count of not `Nothing` (null) and non-empty ("") values of the column within each group. If no rows, evaluates to 0. @@ -52,7 +52,7 @@ type Aggregate_Column Arguments: - column: column (specified by name, index or Column object) to count. - name: name of new column. - type Count_Not_Empty (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Count_Not_Empty (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## Creates a new column with the count of `Nothing` (null) or empty ("") text values of the column within each group. If no rows, evaluates to 0. @@ -60,7 +60,7 @@ type Aggregate_Column Arguments: - column: column (specified by name, index or Column object) to count. - name: name of new column. - type Count_Empty (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Count_Empty (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## Creates a new column with the sum of values (ignoring missing values) of the column within each group. If no rows, evaluates to `Nothing`. @@ -68,7 +68,7 @@ type Aggregate_Column Arguments: - column: column (specified by name, index or Column object) to total. - name: name of new column. - type Sum (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Sum (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## Creates a new column with the mean of values (ignoring missing values) of the column within each group. If no rows, evaluates to `Nothing`. @@ -76,7 +76,7 @@ type Aggregate_Column Arguments: - column: column (specified by name, index or Column object) to average. - name: name of new column. - type Average (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Average (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## Creates a new column with the median of values (ignoring missing values) of the column within each group. If no rows, evaluates to `Nothing`. @@ -85,7 +85,7 @@ type Aggregate_Column - column: column (specified by name, index or Column object) to calculate median on. - name: name of new column. - type Median (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Median (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## Creates a new column with the median of values (ignoring missing values) of the column within each group. If no rows, evaluates to `Nothing`. @@ -95,7 +95,7 @@ type Aggregate_Column - column: column (specified by name, index or Column object) to compute percentile. - name: name of new column. - type Percentile (percentile:Decimal) (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Percentile (percentile:Decimal) (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## Creates a new column with the mode of values (ignoring missing values) of the column within each group. If no rows, evaluates to `Nothing`. @@ -104,7 +104,7 @@ type Aggregate_Column - column: column (specified by name, index or Column object) to find the most common value. - name: name of new column. - type Mode (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Mode (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## Creates a new column with the standard deviation of values (ignoring missing values) of the column within each group. If no rows, evaluates to @@ -115,7 +115,7 @@ type Aggregate_Column standard deviation. - name: name of new column. - population: specifies if group is a sample or the population - type Standard_Deviation (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) (population:Boolean=False) + Standard_Deviation (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) (population:Boolean=False) ## Creates a new column with the values concatenated together. `Nothing` values will become an empty string. If no rows, evaluates to `Nothing`. @@ -129,7 +129,7 @@ type Aggregate_Column - suffix: added at the end of the result. - quote_char: character used to quote the values if the value is `Empty` or contains the separator. - type Concatenate (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) (separator:Text="") (prefix:Text="") (suffix:Text="") (quote_char:Text="") + Concatenate (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) (separator:Text="") (prefix:Text="") (suffix:Text="") (quote_char:Text="") ## Creates a new column with the first value in each group. If no rows, evaluates to `Nothing`. @@ -142,7 +142,7 @@ type Aggregate_Column not missing value returned. - order_by: required for database tables. Specifies how to order the results within the group. - type First (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) (ignore_nothing:Boolean=True) (order_by:Sort_Column_Selector|Nothing=Nothing) + First (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) (ignore_nothing:Boolean=True) (order_by:Sort_Column_Selector|Nothing=Nothing) ## Creates a new column with the last value in each group. If no rows, evaluates to `Nothing`. @@ -155,7 +155,7 @@ type Aggregate_Column not missing value returned. - order_by: required for database tables. Specifies how to order the results within the group. - type Last (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) (ignore_nothing:Boolean=True) (order_by:Sort_Column_Selector|Nothing=Nothing) + Last (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) (ignore_nothing:Boolean=True) (order_by:Sort_Column_Selector|Nothing=Nothing) ## Creates a new column with the maximum value in each group. If no rows, evaluates to `Nothing`. @@ -164,7 +164,7 @@ type Aggregate_Column - column: column (specified by name, index or Column object) to find maximum. - name: name of new column. - type Maximum (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Maximum (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## Creates a new column with the maximum value in each group. If no rows, evaluates to `Nothing`. @@ -173,7 +173,7 @@ type Aggregate_Column - column: column (specified by name, index or Column object) to find minimum. - name: name of new column. - type Minimum (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Minimum (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## Creates a new column with the shortest text in each group. If no rows, evaluates to `Nothing`. @@ -182,7 +182,7 @@ type Aggregate_Column - column: column (specified by name, index or Column object) to find shortest value. - name: name of new column. - type Shortest (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Shortest (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) ## Creates a new column with the longest text in each group. If no rows, evaluates to `Nothing`. @@ -191,4 +191,4 @@ type Aggregate_Column - column: column (specified by name, index or Column object) to find longest value. - name: name of new column. - type Longest (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) + Longest (column:Column|Text|Integer) (new_name:Text|Nothing=Nothing) diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso index cbc24bee5388..85fb005c485d 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso @@ -21,7 +21,7 @@ polyglot java import org.enso.table.operations.OrderBuilder example_from_vector = Table.Column.from_vector "My Column" [1, 2, 3, 4, 5] from_vector : Text -> Vector -> Column -from_vector name items = Column (Java_Column.fromItems name items.to_array) +from_vector name items = Column_Data (Java_Column.fromItems name items.to_array) type Column @@ -31,7 +31,7 @@ type Column Arguments: - java_column: The internal representation of the column. - type Column java_column + Column_Data java_column ## Returns a text containing an ASCII-art table displaying this data. @@ -472,13 +472,13 @@ type Column index = self.java_column.getIndex name = self.java_column.getName new_st = case default of - Column java_col -> + Column_Data java_col -> other_storage = java_col.getStorage storage.fillMissingFrom other_storage _ -> storage.fillMissing default col = Java_Column.new name index new_st - Column col + Column_Data col ## ALIAS Drop Missing @@ -592,7 +592,7 @@ type Column index = self.java_column.getIndex new_st = storage.map Nothing function col = Java_Column.new "Result" index new_st - Column col + Column_Data col ## ALIAS Transform Columns @@ -622,7 +622,7 @@ type Column ix = self.java_column.getIndex s2 = that.java_column.getStorage rs = s1.zip Nothing function s2 skip_missing - Column (Java_Column.new "Result" ix rs) + Column_Data (Java_Column.new "Result" ix rs) ## ALIAS Rename Column @@ -639,7 +639,7 @@ type Column example_rename = Examples.integer_column.rename "My Numbers" rename : Text -> Column - rename self name = Column (self.java_column.rename name) + rename self name = Column_Data (self.java_column.rename name) ## Returns the name of this column. @@ -698,7 +698,7 @@ type Column index : Column ! Table.No_Index_Set_Error index self = case self.java_column.getIndex.toColumn of Nothing -> Error.throw Table.No_Index_Set_Error - i -> Column i + i -> Column_Data i ## Sets the index of this column, using the provided column. @@ -713,7 +713,7 @@ type Column example_set_index = Examples.decimal_column.set_index Examples.integer_column set_index : Column -> Column - set_index self index = Column (self.java_column.setIndex index.java_column) + set_index self index = Column_Data (self.java_column.setIndex index.java_column) ## Returns the value contained in this column at the given index. @@ -756,7 +756,7 @@ type Column Examples.text_column_1.where (Examples.text_column_1.map .length > 2) where : Column -> Column where self indexes = - Column (self.java_column.mask indexes.java_column) + Column_Data (self.java_column.mask indexes.java_column) ## Returns a vector containing all the elements in this column. @@ -1004,7 +1004,7 @@ type Column rule = OrderBuilder.OrderRule.new self.java_column java_cmp order_bool missing_last mask = OrderBuilder.buildOrderMask [rule].to_array new_col = self.java_column.applyMask mask - Column new_col + Column_Data new_col ## UNSTABLE @@ -1024,7 +1024,7 @@ type Column example_take_start = Examples.integer_column.take_start 2 take_start : Integer -> Column take_start self count = - Column (self.java_column.slice 0 count) + Column_Data (self.java_column.slice 0 count) ## UNSTABLE @@ -1045,7 +1045,7 @@ type Column take_end : Integer -> Column take_end self count = start_point = Math.max (self.length - count) 0 - Column (self.java_column.slice start_point count) + Column_Data (self.java_column.slice start_point count) ## UNSTABLE @@ -1109,7 +1109,7 @@ type Column reverse : Column reverse self = mask = OrderBuilder.buildReversedMask self.length - Column <| self.java_column.applyMask mask + Column_Data <| self.java_column.applyMask mask ## UNSTABLE @@ -1123,7 +1123,7 @@ type Column example_duplicate_count = Examples.integer_column.duplicate_count duplicate_count : Column - duplicate_count self = Column self.java_column.duplicateCount + duplicate_count self = Column_Data self.java_column.duplicateCount ## Wraps a column grouped by its index. Allows performing aggregation operations on the contained values. @@ -1155,7 +1155,7 @@ type Aggregate_Column reduce self function skip_missing=True name_suffix="_result" = f arr = function (Vector.Vector arr) r = self.java_column.aggregate Nothing name_suffix f skip_missing - Column r + Column_Data r ## Sums the values in each group. @@ -1173,7 +1173,7 @@ type Aggregate_Column sum : Text -> Column sum self name_suffix='_sum' = r = self.java_column.aggregate 'sum' name_suffix (x-> Vector.Vector x . reduce (+)) True - Column r + Column_Data r ## Computes the maximum element of each group. @@ -1190,7 +1190,7 @@ type Aggregate_Column max : Text -> Column max self name_suffix='_max' = r = self.java_column.aggregate 'max' name_suffix (x-> Vector.Vector x . reduce Math.max) True - Column r + Column_Data r ## Computes the minimum element of each group. @@ -1207,7 +1207,7 @@ type Aggregate_Column min : Text -> Column min self name_suffix='_min' = r = self.java_column.aggregate 'min' name_suffix (x-> Vector.Vector x . reduce Math.min) True - Column r + Column_Data r ## Computes the number of non-missing elements in each group. @@ -1225,7 +1225,7 @@ type Aggregate_Column count : Text -> Column count self name_suffix='_count' = r = self.java_column.aggregate 'count' name_suffix (x-> x.length) True - Column r + Column_Data r ## Computes the mean of non-missing elements in each group. @@ -1244,7 +1244,7 @@ type Aggregate_Column vec_mean v = if v.length == 0 then Nothing else (Vector.Vector v).reduce (+) / v.length r = self.java_column.aggregate 'mean' name_suffix vec_mean True - Column r + Column_Data r ## Gathers all elements in a group into a vector and returns a column of such vectors. @@ -1262,7 +1262,7 @@ type Aggregate_Column values : Text -> Column values self name_suffix='_values' = r = self.java_column.aggregate Nothing name_suffix Vector.Vector False - Column r + Column_Data r ## Prints an ASCII-art column with this data to the standard output. @@ -1310,17 +1310,17 @@ Empty_Error.to_display_text self = "The column is empty." - operand: The operand to apply to the function after `column`. run_vectorized_binary_op : Column -> Text -> (Any -> Any) -> Any -> Column run_vectorized_binary_op column name fallback_fn operand = case operand of - Column col2 -> + Column_Data col2 -> s1 = column.java_column.getStorage ix = column.java_column.getIndex s2 = col2.getStorage rs = s1.zip name fallback_fn s2 True - Column (Java_Column.new "Result" ix rs) + Column_Data (Java_Column.new "Result" ix rs) _ -> s1 = column.java_column.getStorage ix = column.java_column.getIndex rs = s1.bimap name fallback_fn operand - Column (Java_Column.new "Result" ix rs) + Column_Data (Java_Column.new "Result" ix rs) ## PRIVATE @@ -1335,7 +1335,7 @@ run_vectorized_unary_op column name fallback_fn = s = column.java_column.getStorage ix = column.java_column.getIndex rs = s.map name fallback_fn - Column (Java_Column.new "Result" ix rs) + Column_Data (Java_Column.new "Result" ix rs) ## PRIVATE diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Selector.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Selector.enso index bf8b52bb26f6..7c74ba158939 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Selector.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Selector.enso @@ -9,14 +9,14 @@ type Column_Selector The `matcher` can be used to specify if the names should be matched exactly or should be treated as regular expressions. It also allows to specify if the matching should be case-sensitive. - type By_Name (names : Vector Text) (matcher : Matcher = Text_Matcher) + By_Name (names : Vector Text) (matcher : Matcher = Text_Matcher) ## Selects columns by their index. The index of the first column in the table is 0. If the provided index is negative, it counts from the end of the table (e.g. -1 refers to the last column in the table). - type By_Index (indexes : Vector Integer) + By_Index (indexes : Vector Integer) ## Selects columns having exactly the same names as the columns provided in the input. @@ -24,4 +24,4 @@ type Column_Selector The input columns do not necessarily have to come from the same table, so this approach can be used to match columns with the same names as a set of columns of some other table, for example, when preparing for a join. - type By_Column (columns : Vector Column) + By_Column (columns : Vector Column) diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Sort_Column.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Sort_Column.enso index b96d3d87c731..cf7c3b4c4727 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Sort_Column.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Sort_Column.enso @@ -1,6 +1,6 @@ from Standard.Base import all type Sort_Column - type Name name:Text direction:Sort_Direction=Sort_Direction.Ascending - type Index index:Integer direction:Sort_Direction=Sort_Direction.Ascending - type Column column:Column direction:Sort_Direction=Sort_Direction.Ascending + Name name:Text direction:Sort_Direction=Sort_Direction.Ascending + Index index:Integer direction:Sort_Direction=Sort_Direction.Ascending + Column column:Column direction:Sort_Direction=Sort_Direction.Ascending diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Storage.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Storage.enso index a386700738e9..f3653d76dda4 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Storage.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Storage.enso @@ -2,16 +2,16 @@ type Type ## A column storing text data. - type Text + Text ## A column storing integer data. - type Integer + Integer ## A column storing decimal data. - type Decimal + Decimal ## A column storing boolean data. - type Boolean + Boolean ## A column storing arbitrary data. - type Any + Any diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/IO/Excel.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/IO/Excel.enso index f571a6481c0c..5057e37a7af2 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/IO/Excel.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/IO/Excel.enso @@ -26,24 +26,24 @@ polyglot java import org.enso.table.util.problems.InvalidNames type Excel_Section ## Gets a list of sheets within a workbook. - type Sheet_Names + Sheet_Names ## Gets a list of named ranges within a workbook. - type Range_Names + Range_Names ## Gets the data from a specific sheet. Column names are the Excel column names. - type Sheet (sheet:(Integer|Text)=1) (skip_rows:Integer=0) (row_limit:(Integer|Nothing)=Nothing) + Sheet (sheet:(Integer|Text)=1) (skip_rows:Integer=0) (row_limit:(Integer|Nothing)=Nothing) ## Gets a specific range (taking either a defined name or external style address) from the workbook. If it is a single cell, it will be treated as the top left cell and will expand right and down to cover the connected cells. - type Cell_Range (address:(Text|Excel_Range)) (skip_rows:Integer=0) (row_limit:(Integer|Nothing)=Nothing) + Cell_Range (address:(Text|Excel_Range)) (skip_rows:Integer=0) (row_limit:(Integer|Nothing)=Nothing) type Excel_Range ## Specifies a range within an Excel Workbook. - type Excel_Range java_range:Java_Range + Excel_Range_Data java_range:Java_Range ## Gets the name of the sheet. sheet_name : Text @@ -114,7 +114,7 @@ type Excel_Range from_address : Text -> Excel_Range from_address address = Illegal_Argument_Error.handle_java_exception <| - Excel_Range (Java_Range.new address) + Excel_Range_Data (Java_Range.new address) ## Create a Range for a single cell. for_cell : Text -> (Text|Integer) -> Integer -> Excel_Range @@ -125,7 +125,7 @@ type Excel_Range row_valid = validate (Excel_Range.is_valid_row row) ("Invalid row for Excel: " + row.to_text + ".") col_valid <| row_valid <| - Excel_Range (Java_Range.new sheet col_index row) + Excel_Range_Data (Java_Range.new sheet col_index row) ## Create an Excel_Range for a range of cells. for_range : Text -> (Text|Integer) -> Integer -> (Text|Integer) -> Integer -> Excel_Range @@ -139,7 +139,7 @@ type Excel_Range bottom_valid = validate (Excel_Range.is_valid_row bottom) ("Invalid bottom row for Excel: " + bottom.to_text + ".") left_valid <| right_valid <| top_valid <| bottom_valid <| - Excel_Range (Java_Range.new sheet left_index top right_index bottom) + Excel_Range_Data (Java_Range.new sheet left_index top right_index bottom) ## Create an Excel_Range for a set of columns. for_columns : Text -> (Text|Integer) -> (Text|Integer) -> Excel_Range @@ -151,7 +151,7 @@ type Excel_Range right_valid = validate (Excel_Range.is_valid_column right_index) ("Invalid right column for Excel: " + right.to_text + ".") left_valid <| right_valid <| - Excel_Range (Java_Range.forColumns sheet left_index right_index) + Excel_Range_Data (Java_Range.forColumns sheet left_index right_index) ## Create an Excel_Range for a set of rows. for_rows : Text -> Integer -> Integer -> Excel_Range @@ -160,7 +160,7 @@ type Excel_Range bottom_valid = validate (Excel_Range.is_valid_row bottom) ("Invalid bottom row for Excel: " + bottom.to_text + ".") top_valid <| bottom_valid <| - Excel_Range (Java_Range.forRows sheet top bottom) + Excel_Range_Data (Java_Range.forRows sheet top bottom) ## PRIVATE @@ -192,7 +192,7 @@ read_excel file section headers on_problems xls_format=False = Text -> ExcelReader.readSheetByName stream sheet (make_java_headers headers) skip_rows row_limit xls_format Cell_Range address skip_rows row_limit -> prepare_reader_table on_problems <| case address of - Excel_Range _ -> ExcelReader.readRange stream address.java_range (make_java_headers headers) skip_rows row_limit xls_format + Excel_Range_Data _ -> ExcelReader.readRange stream address.java_range (make_java_headers headers) skip_rows row_limit xls_format Text -> ExcelReader.readRangeByName stream address (make_java_headers headers) skip_rows row_limit xls_format handle_reader file reader @@ -213,7 +213,7 @@ write_excel file table on_existing_file section headers match_columns _ xls_form Sheet sheet skip_rows row_limit -> ExcelWriter.writeTableToSheet workbook sheet existing_data_mode skip_rows table.java_table row_limit java_headers Cell_Range address skip_rows row_limit -> case address of - Excel_Range java_range -> ExcelWriter.writeTableToRange workbook java_range existing_data_mode skip_rows table.java_table row_limit java_headers + Excel_Range_Data java_range -> ExcelWriter.writeTableToRange workbook java_range existing_data_mode skip_rows table.java_table row_limit java_headers Text -> ExcelWriter.writeTableToRange workbook address existing_data_mode skip_rows table.java_table row_limit java_headers if result.is_error then result else 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 279d0976e7eb..38e995e92013 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 @@ -144,10 +144,10 @@ type Detected_Headers Nothing ## Represents the headers found in the file. - type Existing_Headers (column_names : Vector Text) + Existing_Headers (column_names : Vector Text) ## Indicates that the file exists but no headers have been found, so only positional column matching is possible. - type No_Headers (column_count : Integer) + No_Headers (column_count : Integer) type Detected_File_Metadata ## PRIVATE @@ -160,7 +160,7 @@ type Detected_File_Metadata - ends_with_newline: specifies if the last line ends with a line separator that is consistent with the detected one. - has_any_content: specifies if the file contains any content. - type Detected_File_Metadata (headers : Detected_Headers) (line_separator : Text|Nothing) (ends_with_newline : Boolean) (has_any_content : Boolean) + Detected_File_Metadata (headers : Detected_Headers) (line_separator : Text|Nothing) (ends_with_newline : Boolean) (has_any_content : Boolean) ## PRIVATE Reads the beginning of the file to detect the existing headers and column 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 ec04f6fad5ac..6bcee4d2904e 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 @@ -16,7 +16,7 @@ polyglot java import org.enso.table.util.NameDeduplicator duplicates = unique_name_strategy.renames invalid = unique_name_strategy.invalid_names new : Unique_Name_Strategy -new = Unique_Name_Strategy NameDeduplicator.new +new = Unique_Name_Strategy_Data NameDeduplicator.new type Unique_Name_Strategy ## PRIVATE @@ -24,7 +24,7 @@ type Unique_Name_Strategy Arguments: - deduplicator: Name deduplicator - type Unique_Name_Strategy deduplicator + Unique_Name_Strategy_Data deduplicator ## Vector of any duplicates renamed 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 4e0d22d66375..6164bec1294a 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 @@ -16,7 +16,7 @@ type Vector_Builder Arguments: - vec: The vector at the leaf. - type Leaf vec + Leaf vec ## PRIVATE @@ -26,7 +26,7 @@ type Vector_Builder - left: The left subtree. - right: The right subtree. - len: The length of the vectors across the subtrees. - type Append left right len + Append left right len ## PRIVATE diff --git a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Id.enso b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Id.enso index c356ed09d01e..c29b0ec7e4df 100644 --- a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Id.enso +++ b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Id.enso @@ -5,9 +5,9 @@ from Standard.Base import all type Id ## A builtin visulization, implemented in the graphical interface and not imported from any library. - type Builtin name + Builtin name ## A visualization implemented in a library. - type Library project name + Library project name ## Serializes this ID to a JSON format understandable by the graphical interface. diff --git a/test/Table_Tests/src/In_Memory_Tests.enso b/test/Table_Tests/src/In_Memory_Tests.enso index 77de3579cde6..a67727b06533 100644 --- a/test/Table_Tests/src/In_Memory_Tests.enso +++ b/test/Table_Tests/src/In_Memory_Tests.enso @@ -3,15 +3,15 @@ from Standard.Base import all import Standard.Test import project.Column_Spec -import project.Csv_Spec -import project.Delimited_Read_Spec -import project.Delimited_Write_Spec -import project.Excel_Spec -import project.Json_Spec -import project.Table_Spec -import project.Table_Date_Spec -import project.Aggregate_Column_Spec -import project.Aggregate_Spec +#import project.Csv_Spec +#import project.Delimited_Read_Spec +#import project.Delimited_Write_Spec +#import project.Excel_Spec +#import project.Json_Spec +#import project.Table_Spec +#import project.Table_Date_Spec +#import project.Aggregate_Column_Spec +#import project.Aggregate_Spec in_memory_spec = Column_Spec.spec diff --git a/test/Table_Tests/src/Main.enso b/test/Table_Tests/src/Main.enso index 8e1ee688a924..0a626d00adeb 100644 --- a/test/Table_Tests/src/Main.enso +++ b/test/Table_Tests/src/Main.enso @@ -3,9 +3,9 @@ from Standard.Base import all import Standard.Test import project.In_Memory_Tests -import project.Database.Main as Database_Tests -import project.File_Read_Spec -import project.Data_Formatter_Spec +#import project.Database.Main as Database_Tests +#import project.File_Read_Spec +#import project.Data_Formatter_Spec main = Test.Suite.run_main <| In_Memory_Tests.in_memory_spec From cfbd607d34a81bb9b8532ef6d8dbf24532c1e4a4 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 18 Aug 2022 13:46:08 +0200 Subject: [PATCH 056/110] first successes in table --- .../Standard/Geo/0.0.0-dev/src/Geo_Json.enso | 24 +++--- .../Standard/Image/0.0.0-dev/src/Codecs.enso | 6 +- .../Image/0.0.0-dev/src/Codecs/Internal.enso | 10 +-- .../Image/0.0.0-dev/src/Data/Histogram.enso | 4 +- .../Image/0.0.0-dev/src/Data/Image.enso | 4 +- .../0.0.0-dev/src/Data/Image/Internal.enso | 4 +- .../Image/0.0.0-dev/src/Data/Matrix.enso | 20 ++--- .../0.0.0-dev/src/Data/Matrix/Internal.enso | 6 +- .../Table/0.0.0-dev/src/Data/Column.enso | 30 ++++---- .../src/Data/Column_Name_Mapping.enso | 8 +- .../0.0.0-dev/src/Data/Data_Formatter.enso | 20 ++--- .../0.0.0-dev/src/Data/Match_Columns.enso | 4 +- .../Table/0.0.0-dev/src/Data/Position.enso | 4 +- .../src/Data/Sort_Column_Selector.enso | 6 +- .../Table/0.0.0-dev/src/Data/Table.enso | 68 ++++++++--------- .../Standard/Table/0.0.0-dev/src/Errors.enso | 74 ++++++++++++------- .../Table/0.0.0-dev/src/IO/File_Format.enso | 17 ++--- .../Table/0.0.0-dev/src/IO/Quote_Style.enso | 4 +- .../src/Internal/Aggregate_Column_Helper.enso | 5 +- .../src/Internal/Delimited_Reader.enso | 20 ++--- .../src/Internal/Parse_Values_Helper.enso | 8 +- .../src/Internal/Problem_Builder.enso | 4 +- .../0.0.0-dev/src/Internal/Table_Helpers.enso | 8 +- .../src/Internal/Vector_Builder.enso | 4 +- .../Standard/Table/0.0.0-dev/src/Main.enso | 74 ++++++------------- .../0.0.0-dev/src/Histogram.enso | 6 +- test/Table_Tests/src/Column_Spec.enso | 4 +- test/Table_Tests/src/Csv_Spec.enso | 10 +-- test/Table_Tests/src/Data_Formatter_Spec.enso | 66 ++++++++--------- test/Table_Tests/src/In_Memory_Tests.enso | 2 +- test/Table_Tests/src/Main.enso | 4 +- 31 files changed, 259 insertions(+), 269 deletions(-) diff --git a/distribution/lib/Standard/Geo/0.0.0-dev/src/Geo_Json.enso b/distribution/lib/Standard/Geo/0.0.0-dev/src/Geo_Json.enso index 66cfed717d0b..5dcdd8f0e6ed 100644 --- a/distribution/lib/Standard/Geo/0.0.0-dev/src/Geo_Json.enso +++ b/distribution/lib/Standard/Geo/0.0.0-dev/src/Geo_Json.enso @@ -8,12 +8,12 @@ type Object_Type ## PRIVATE A Geo JSON feature. - type Feature + Feature ## PRIVATE A Geo JSON feature collection. - type Feature_Collection + Feature_Collection ## PRIVATE @@ -26,16 +26,16 @@ type Object_Type ## PRIVATE Get the type field of a GeoJSON object. -Json.Object.get_type : Any -Json.Object.get_type self = case self of +Json.Json.get_type : Any +Json.Json.get_type self = case self of Json.Object object -> object.get_or_else "type" Nothing.to_json . unwrap ## PRIVATE Get key-value pairs of a Feature GeoJSON object. -Json.Object.get_feature_row : Map -Json.Object.get_feature_row self = +Json.Json.get_feature_row : Map +Json.Json.get_feature_row self = properties_row = self.get "properties" . get_properties_row geometry_row = self.get "geometry" . get_geometry_row geometry_row.fold_with_key properties_row acc-> k-> v-> @@ -44,8 +44,8 @@ Json.Object.get_feature_row self = ## PRIVATE Get column key-value pairs of a feature's "properties" object. -Json.Object.get_properties_row : Map -Json.Object.get_properties_row self = case self of +Json.Json.get_properties_row : Map +Json.Json.get_properties_row self = case self of Json.Object properties -> properties.map p-> case p of Json.Object _ -> Nothing.to_json _ -> p @@ -53,8 +53,8 @@ Json.Object.get_properties_row self = case self of ## PRIVATE Get column key-value pairs of a feature's "geometry" object. -Json.Object.get_geometry_row : Map -Json.Object.get_geometry_row self = case self of +Json.Json.get_geometry_row : Map +Json.Json.get_geometry_row self = case self of Json.Object fields -> geometry_type = fields.get_or_else "type" Nothing if geometry_type == "Point".to_json then self.get_point_row else Map.empty @@ -62,8 +62,8 @@ Json.Object.get_geometry_row self = case self of ## PRIVATE Get column key-value pairs of a "Point" geometry object. -Json.Object.get_point_row : Map -Json.Object.get_point_row self = +Json.Json.get_point_row : Map +Json.Json.get_point_row self = fields = ["longitude", "latitude", "elevation"] case self.get "coordinates" of Json.Array coordinates -> diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso index 82846dd97e41..4f2be90f183a 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso @@ -34,11 +34,11 @@ read location flags=[] = File.File -> location.path _ -> location read_flags = case flags of - Vector.Vector _ -> + Vector.Vector_Data _ -> if flags.is_empty then Java_Codecs.READ_FLAG_EMPTY else flags.map .to_integer . reduce (_.bit_or _) _ -> flags.to_integer - Panic.catch_java Any (Image.Image (Java_Codecs.read path read_flags)) _-> + Panic.catch_java Any (Image.Image_Data (Java_Codecs.read path read_flags)) _-> Error.throw (File.IO_Error (File.new path) 'Failed to read the file') ## UNSTABLE @@ -66,7 +66,7 @@ Image.Image.write self location flags=[] = File.File -> location.path _ -> location write_flags = case flags of - Vector.Vector _ -> flags + Vector.Vector_Data _ -> flags _ -> [flags] int_flags = Internal.mat_of_int (write_flags.flat_map x-> [x.to_integer, x.value]) Panic.catch_java Any (Java_Codecs.write path self.opencv_mat int_flags) _-> diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs/Internal.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs/Internal.enso index 24b83170ac78..77526eb2bcef 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs/Internal.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs/Internal.enso @@ -13,13 +13,13 @@ Codecs.Read_Flag.to_integer self = case self of ## PRIVATE Codecs.Write_Flag.to_integer self = case self of - Codecs.Write_Jpeg_Quality -> Imgcodecs.IMWRITE_JPEG_QUALITY + Codecs.Write_Jpeg_Quality _ -> Imgcodecs.IMWRITE_JPEG_QUALITY Codecs.Write_Jpeg_Progressive -> Imgcodecs.IMWRITE_JPEG_PROGRESSIVE Codecs.Write_Jpeg_Optimize -> Imgcodecs.IMWRITE_JPEG_OPTIMIZE - Codecs.Write_Jpeg_Luma_Quality -> Imgcodecs.IMWRITE_JPEG_LUMA_QUALITY - Codecs.Write_Jpeg_Chroma_Quality -> Imgcodecs.IMWRITE_JPEG_CHROMA_QUALITY - Codecs.Write_Png_Compression -> Imgcodecs.IMWRITE_PNG_COMPRESSION - Codecs.Write_Webp_Quality -> Imgcodecs.IMWRITE_WEBP_QUALITY + Codecs.Write_Jpeg_Luma_Quality _ -> Imgcodecs.IMWRITE_JPEG_LUMA_QUALITY + Codecs.Write_Jpeg_Chroma_Quality _ -> Imgcodecs.IMWRITE_JPEG_CHROMA_QUALITY + Codecs.Write_Png_Compression _ -> Imgcodecs.IMWRITE_PNG_COMPRESSION + Codecs.Write_Webp_Quality _ -> Imgcodecs.IMWRITE_WEBP_QUALITY ## PRIVATE diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Histogram.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Histogram.enso index d94d10ed3112..44268f4ce9c8 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Histogram.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Histogram.enso @@ -15,7 +15,7 @@ type Histogram Arguments: - channel: The channel in the image for which this is a histogram. - data: The histogram data. - type Histogram channel data + Histogram_Data channel data ## UNSTABLE @@ -52,4 +52,4 @@ type Histogram Image.Image.histogram : Integer -> Histogram Image.Image.histogram self channel = hist = Java_Histogram.calculate self.opencv_mat channel - Histogram channel (Vector.Vector hist.get_data) + Histogram_Data channel (Vector.Vector hist.get_data) diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image.enso index 155ec3373b09..0bf5b0577851 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image.enso @@ -27,7 +27,7 @@ polyglot java import org.enso.image.data.Image as Java_Image Image.from_vector [0, 0, 0, 0, 0, 0] rows=2 channels=1 from_vector : Vector -> Integer -> Integer -> Image from_vector values rows=1 channels=1 = - Image (Java_Image.from_vector values.to_array rows channels) + Image_Data (Java_Image.from_vector values.to_array rows channels) ## UNSTABLE type Image @@ -42,7 +42,7 @@ type Image The image is represented with a matrix of rows x columns. Each pixel is represented with a vector of 1 to 4 values (channels). Pixel values are normalized in a range [0.0 .. 1.0]. - type Image opencv_mat + Image_Data opencv_mat ## UNSTABLE diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image/Internal.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image/Internal.enso index 42a793ff325b..6d22b3394886 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image/Internal.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image/Internal.enso @@ -19,9 +19,9 @@ core_op : Mat -> Any -> (Mat -> Scalar -> Mat -> Nothing) -> Nothing core_op mat value function = result = Mat.new scalar = case value of - Vector.Vector arr -> + Vector.Vector_Data arr -> Scalar.new arr - Matrix.Matrix m -> + Matrix.Matrix_Data m -> if ((m.rows == mat.rows) && (m.cols == mat.cols) && (m.channels == mat.channels)) then m else Panic.throw Matrix.Dimensions_Not_Equal _ -> Scalar.all value diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Matrix.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Matrix.enso index 3c2152ff5c6e..5b4e1b91ef31 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Matrix.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Matrix.enso @@ -23,7 +23,7 @@ polyglot java import org.enso.image.data.Matrix as Java_Matrix example_zeros = Matrix.zeros rows=2 columns=2 zeros : Integer -> Integer -> Integer -> Matrix zeros rows columns channels=1 = - Matrix (Java_Matrix.zeros rows columns channels) + Matrix_Data (Java_Matrix.zeros rows columns channels) ## UNSTABLE @@ -42,7 +42,7 @@ zeros rows columns channels=1 = example_ones = Matrix.zeros rows=2 columns=2 channels=3 ones : Integer -> Integer -> Integer -> Matrix ones rows columns channels=1 = - Matrix (Java_Matrix.ones rows columns channels) + Matrix_Data (Java_Matrix.ones rows columns channels) ## UNSTABLE @@ -61,7 +61,7 @@ ones rows columns channels=1 = example_identity = Matrix.identity rows=2 columns=2 channels=3 identity : Integer -> Integer -> Integer -> Matrix identity rows columns channels=1 = - Matrix (Java_Matrix.identity rows columns channels) + Matrix_Data (Java_Matrix.identity rows columns channels) ## UNSTABLE @@ -79,7 +79,7 @@ identity rows columns channels=1 = example_from_vector = Matrix.from_vector [1, 1, 0, 0] rows=2 from_vector : Vector -> Integer -> Integer -> Matrix from_vector values rows=1 channels=1 = - Matrix (Java_Matrix.from_vector values.to_array channels rows) + Matrix_Data (Java_Matrix.from_vector values.to_array channels rows) ## UNSTABLE type Matrix @@ -94,7 +94,7 @@ type Matrix Each value of the matrix is represented with an array of channels. In contrast to an Image data type, Matrix values are not normalized. - type Matrix opencv_mat + Matrix_Data opencv_mat ## UNSTABLE @@ -171,8 +171,8 @@ type Matrix reshape : Integer -> Integer -> Matrix reshape self rows channels=Nothing = case channels of - Nothing -> Matrix (self.opencv_mat.reshape self.channels rows) - _ -> Matrix (self.opencv_mat.reshape channels rows) + Nothing -> Matrix_Data (self.opencv_mat.reshape self.channels rows) + _ -> Matrix_Data (self.opencv_mat.reshape channels rows) ## UNSTABLE @@ -385,7 +385,7 @@ type Matrix example_normalize = Matrix.identity 3 3 . normalize normalize : Number -> Number -> Matrix normalize self min_value=0.0 max_value=1.0 = - Matrix (Java_Matrix.normalize self.opencv_mat min_value max_value) + Matrix_Data (Java_Matrix.normalize self.opencv_mat min_value max_value) ## UNSTABLE @@ -439,13 +439,13 @@ type Matrix_Error - rows: The number of rows in the matrix. - columns: The number of columns in the matrix. - index: The requested index in the matrix. - type Index_Out_Of_Bounds_Error rows columns index + Index_Out_Of_Bounds_Error rows columns index ## UNSTABLE An error indicating that an operation has failed due to a mismatch of matrix dimensions. - type Dimensions_Not_Equal + Dimensions_Not_Equal ## UNSTABLE diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Matrix/Internal.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Matrix/Internal.enso index 868b14e63395..dcaf48e393c7 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Matrix/Internal.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Matrix/Internal.enso @@ -18,14 +18,14 @@ core_op : Mat -> Any -> (Mat -> Scalar -> Mat -> Nothing) -> Nothing core_op mat value function = result = Mat.new scalar = case value of - Vector.Vector arr -> + Vector.Vector_Data arr -> Scalar.new arr - Matrix.Matrix m -> + Matrix.Matrix_Data m -> if ((m.rows == mat.rows) && (m.cols == mat.cols) && (m.channels == mat.channels)) then m else Panic.throw Matrix.Dimensions_Not_Equal _ -> Scalar.all value function mat scalar result - Matrix.Matrix result + Matrix.Matrix_Data result ## PRIVATE diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso index 85fb005c485d..211cfff09d5c 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso @@ -732,7 +732,7 @@ type Column at : Integer -> (Any | Nothing) ! Index_Out_Of_Bounds_Error at self index = valid_index = (index >= 0) && (index < self.length) - if valid_index.not then Error.throw (Index_Out_Of_Bounds_Error index self.length) else + if valid_index.not then Error.throw (Index_Out_Of_Bounds_Error_Data index self.length) else storage = self.java_column.getStorage if storage.isNa index then Nothing else storage.getItem index @@ -767,7 +767,7 @@ type Column example_to_vector = Examples.integer_column.to_vector to_vector : Vector - to_vector self = Vector.Vector self.java_column.getStorage.toList + to_vector self = Vector.Vector_Data self.java_column.getStorage.toList ## Returns the underlying storage type of this column. @@ -875,7 +875,7 @@ type Column example_sum = Examples.integer_column.sum sum : Any - sum self = self.java_column.aggregate 'sum' (x-> Vector.Vector x . reduce (+)) True + sum self = self.java_column.aggregate 'sum' (x-> Vector.Vector_Data x . reduce (+)) True ## ALIAS Max Columns @@ -889,7 +889,7 @@ type Column example_max = Examples.integer_column.max max : Any max self = - self.java_column.aggregate 'max' (x-> Vector.Vector x . reduce Math.max) True + self.java_column.aggregate 'max' (x-> Vector.Vector_Data x . reduce Math.max) True ## ALIAS Min Columns @@ -903,7 +903,7 @@ type Column example_min = Examples.integer_column.min min : Any min self = - self.java_column.aggregate 'min' (x-> Vector.Vector x . reduce Math.min) True + self.java_column.aggregate 'min' (x-> Vector.Vector_Data x . reduce Math.min) True ## ALIAS Mean Columns @@ -918,7 +918,7 @@ type Column mean : Any mean self = vec_mean v = if v.length == 0 then Nothing else - (Vector.Vector v).reduce (+) / v.length + (Vector.Vector_Data v).reduce (+) / v.length self.java_column.aggregate 'mean' vec_mean True ## Computes the variance of the sample represented by this column. @@ -1061,7 +1061,7 @@ type Column example_first = Examples.integer_column.first first : Any ! Empty_Error - first self = self.at 0 . catch Index_Out_Of_Bounds_Error (_ -> Error.throw Empty_Error) + first self = self.at 0 . catch Index_Out_Of_Bounds_Error_Data (_ -> Error.throw Empty_Error) ## UNSTABLE @@ -1093,7 +1093,7 @@ type Column example_last = Examples.integer_column.last last : Any ! Empty_Error - last self = self.at (self.length - 1) . catch Index_Out_Of_Bounds_Error (_ -> Error.throw Empty_Error) + last self = self.at (self.length - 1) . catch Index_Out_Of_Bounds_Error_Data (_ -> Error.throw Empty_Error) ## UNSTABLE @@ -1130,7 +1130,7 @@ type Column type Aggregate_Column ## PRIVATE - type Aggregate_Column java_column + Aggregate_Column_Data java_column ## Converts this aggregate column into a column, aggregating groups with the provided `function`. @@ -1153,7 +1153,7 @@ type Aggregate_Column Examples.aggregate_column.reduce .length . rename "transaction_count" reduce : (Vector.Vector -> Any) -> Boolean -> Text -> Column reduce self function skip_missing=True name_suffix="_result" = - f arr = function (Vector.Vector arr) + f arr = function (Vector.Vector_Data arr) r = self.java_column.aggregate Nothing name_suffix f skip_missing Column_Data r @@ -1172,7 +1172,7 @@ type Aggregate_Column example_sum = Examples.aggregate_column.sum . rename "id_sum" sum : Text -> Column sum self name_suffix='_sum' = - r = self.java_column.aggregate 'sum' name_suffix (x-> Vector.Vector x . reduce (+)) True + r = self.java_column.aggregate 'sum' name_suffix (x-> Vector.Vector_Data x . reduce (+)) True Column_Data r ## Computes the maximum element of each group. @@ -1189,7 +1189,7 @@ type Aggregate_Column example_max = Examples.aggregate_column.max . rename "latest_transaction" max : Text -> Column max self name_suffix='_max' = - r = self.java_column.aggregate 'max' name_suffix (x-> Vector.Vector x . reduce Math.max) True + r = self.java_column.aggregate 'max' name_suffix (x-> Vector.Vector_Data x . reduce Math.max) True Column_Data r ## Computes the minimum element of each group. @@ -1206,7 +1206,7 @@ type Aggregate_Column example_min = Examples.aggregate_column.min . rename "first_transaction" min : Text -> Column min self name_suffix='_min' = - r = self.java_column.aggregate 'min' name_suffix (x-> Vector.Vector x . reduce Math.min) True + r = self.java_column.aggregate 'min' name_suffix (x-> Vector.Vector_Data x . reduce Math.min) True Column_Data r ## Computes the number of non-missing elements in each group. @@ -1242,7 +1242,7 @@ type Aggregate_Column mean : Text -> Column mean self name_suffix='_mean' = vec_mean v = if v.length == 0 then Nothing else - (Vector.Vector v).reduce (+) / v.length + (Vector.Vector_Data v).reduce (+) / v.length r = self.java_column.aggregate 'mean' name_suffix vec_mean True Column_Data r @@ -1261,7 +1261,7 @@ type Aggregate_Column example_values = Examples.aggregate_column.values values : Text -> Column values self name_suffix='_values' = - r = self.java_column.aggregate Nothing name_suffix Vector.Vector False + r = self.java_column.aggregate Nothing name_suffix Vector.Vector_Data False Column_Data r ## Prints an ASCII-art column with this data to the standard output. diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Name_Mapping.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Name_Mapping.enso index 0d93d478dba3..8f3eb590bbb6 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Name_Mapping.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Name_Mapping.enso @@ -9,14 +9,14 @@ type Column_Name_Mapping The `matcher` can be used to specify if the names should be matched exactly or should be treated as regular expressions. It also allows to specify if the matching should be case-sensitive. - type By_Name (names : Map Text Text) (matcher : Matcher = Text_Matcher) + By_Name (names : Map Text Text) (matcher : Matcher = Text_Matcher) ## Selects columns by their index. The index of the first column in the table is 0. If the provided index is negative, it counts from the end of the table (e.g. -1 refers to the last column in the table). - type By_Index (indexes : Map Number Text) + By_Index (indexes : Map Number Text) ## Selects columns having exactly the same names as the columns provided in the input. @@ -26,8 +26,8 @@ type Column_Name_Mapping of columns of some other table, for example, when preparing for a join. The Vector should be of the form [[Column, Name], [Column1, Name1], ...] - type By_Column (columns : Vector) + By_Column (columns : Vector) ## Selects columns by position starting at the first column until the new_names is exhausted. - type By_Position (new_names : [Text]) + By_Position (new_names : [Text]) diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Data_Formatter.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Data_Formatter.enso index 040b1252c5e3..1b2e63f34d15 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Data_Formatter.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Data_Formatter.enso @@ -56,7 +56,7 @@ type Data_Formatter - datetime_locale: The locale to use when parsing dates and times. - true_values: Values representing True. - false_values: Values representing False. - type Data_Formatter trim_values:Boolean=True allow_leading_zeros:Boolean=False decimal_point:Text='.' thousand_separator:Text='' allow_exponential_notation:Boolean=False datetime_formats:[Text]=["yyyy-MM-dd HH:mm:ss"] date_formats:[Text]=["yyyy-MM-dd"] time_formats:[Text]=["HH:mm:ss"] datetime_locale:Locale=Locale.default true_values:[Text]=["True","true","TRUE"] false_values:[Text]=["False","false","FALSE"] + Data_Formatter_Data trim_values:Boolean=True allow_leading_zeros:Boolean=False decimal_point:Text='.' thousand_separator:Text='' allow_exponential_notation:Boolean=False datetime_formats:[Text]=["yyyy-MM-dd HH:mm:ss"] date_formats:[Text]=["yyyy-MM-dd"] time_formats:[Text]=["HH:mm:ss"] datetime_locale:Locale=Locale.default true_values:[Text]=["True","true","TRUE"] false_values:[Text]=["False","false","FALSE"] ## Parse a Text into a value. @@ -73,7 +73,7 @@ type Data_Formatter Auto -> self.make_auto_parser _ -> self.make_datatype_parser datatype result = parser.parseIndependentValue text - problems = Vector.Vector result.problems . map (Parse_Values_Helper.translate_parsing_problem datatype) + problems = Vector.Vector_Data result.problems . map (Parse_Values_Helper.translate_parsing_problem datatype) on_problems.attach_problems_after result.value problems ## Format a value into a Text. @@ -131,7 +131,7 @@ type Data_Formatter Clone the instance with some properties overridden. clone : Boolean->Boolean->Text->Text->Boolean->[Text]->[Text]->[Text]->Locale->[Text]->[Text]->Data_Formatter clone self (trim_values=self.trim_values) (allow_leading_zeros=self.allow_leading_zeros) (decimal_point=self.decimal_point) (thousand_separator=self.thousand_separator) (allow_exponential_notation=self.allow_exponential_notation) (datetime_formats=self.datetime_formats) (date_formats=self.date_formats) (time_formats=self.time_formats) (datetime_locale=self.datetime_locale) (true_values=self.true_values) (false_values=self.false_values) = - Data_Formatter trim_values=trim_values allow_leading_zeros=allow_leading_zeros decimal_point=decimal_point thousand_separator=thousand_separator allow_exponential_notation=allow_exponential_notation datetime_formats=datetime_formats date_formats=date_formats time_formats=time_formats datetime_locale=datetime_locale true_values=true_values false_values=false_values + Data_Formatter_Data trim_values=trim_values allow_leading_zeros=allow_leading_zeros decimal_point=decimal_point thousand_separator=thousand_separator allow_exponential_notation=allow_exponential_notation datetime_formats=datetime_formats date_formats=date_formats time_formats=time_formats datetime_locale=datetime_locale true_values=true_values false_values=false_values ## PRIVATE get_thousand_separator self = @@ -178,7 +178,7 @@ type Data_Formatter if datatype == Date then self.make_date_parser else if datatype == Time then self.make_datetime_parser else if datatype == Time_Of_Day then self.make_time_parser else - Error.throw (Illegal_Argument_Error "Unsupported datatype: "+datatype.to_text) + Error.throw (Illegal_Argument_Error_Data "Unsupported datatype: "+datatype.to_text) ## PRIVATE get_specific_type_parsers self = @@ -199,23 +199,23 @@ type Data_Formatter ## PRIVATE make_date_formatter self = - if self.date_formats.is_empty then Error.throw (Illegal_Argument_Error "Formatting dates requires at least one entry in the `date_formats` parameter") else + if self.date_formats.is_empty then Error.throw (Illegal_Argument_Error_Data "Formatting dates requires at least one entry in the `date_formats` parameter") else DateFormatter.new self.date_formats.first self.datetime_locale.java_locale ## PRIVATE make_time_formatter self = - if self.time_formats.is_empty then Error.throw (Illegal_Argument_Error "Formatting times requires at least one entry in the `time_formats` parameter") else + if self.time_formats.is_empty then Error.throw (Illegal_Argument_Error_Data "Formatting times requires at least one entry in the `time_formats` parameter") else TimeFormatter.new self.time_formats.first self.datetime_locale.java_locale ## PRIVATE make_datetime_formatter self = - if self.datetime_formats.is_empty then Error.throw (Illegal_Argument_Error "Formatting date-times requires at least one entry in the `datetime_formats` parameter") else + if self.datetime_formats.is_empty then Error.throw (Illegal_Argument_Error_Data "Formatting date-times requires at least one entry in the `datetime_formats` parameter") else DateTimeFormatter.new self.datetime_formats.first self.datetime_locale.java_locale ## PRIVATE make_boolean_formatter self = - if self.true_values.is_empty then Error.throw (Illegal_Argument_Error "Formatting booleans requires at least one entry in the `true_values` parameter") else - if self.false_values.is_empty then Error.throw (Illegal_Argument_Error "Formatting booleans requires at least one entry in the `false_values` parameter") else + if self.true_values.is_empty then Error.throw (Illegal_Argument_Error_Data "Formatting booleans requires at least one entry in the `true_values` parameter") else + if self.false_values.is_empty then Error.throw (Illegal_Argument_Error_Data "Formatting booleans requires at least one entry in the `false_values` parameter") else BooleanFormatter.new self.true_values.first self.false_values.first ## PRIVATE @@ -229,7 +229,7 @@ type Data_Formatter ## PRIVATE make_auto_formatter self = # TODO The panic rethrow+recover is a workaround for the vector error propagation bug. - formatters = Panic.recover Illegal_Argument_Error (self.get_specific_type_formatters.map Panic.rethrow) + formatters = Panic.recover Illegal_Argument_Error_Data (self.get_specific_type_formatters.map Panic.rethrow) AnyObjectFormatter.new formatters.to_array ## PRIVATE diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Match_Columns.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Match_Columns.enso index 4741bbb95f3c..fb4e10998f8c 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Match_Columns.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Match_Columns.enso @@ -6,10 +6,10 @@ type Match_Columns A `Column_Name_Mismatch` error occurs if any column name in the existing data could not be matched to the new data, or any column name in the new data was not found in the existing data. - type By_Name + By_Name ## Columns are matched by Position against the existing data. Note: column names are not compared. A `Column_Count_Mismatch` error occurs if the existing data has a different number of columns than the table. - type By_Position + By_Position diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Position.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Position.enso index d01eb6926afd..910140e8f098 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Position.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Position.enso @@ -3,8 +3,8 @@ from Standard.Base import all type Position ## UNSTABLE Selected columns will be moved to the front of the output table. - type Before_Other_Columns + Before_Other_Columns ## UNSTABLE Selected columns will be moved to the back of the output table. - type After_Other_Columns + After_Other_Columns diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Sort_Column_Selector.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Sort_Column_Selector.enso index 37ac646764ff..c5c932a77afc 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Sort_Column_Selector.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Sort_Column_Selector.enso @@ -3,6 +3,6 @@ from Standard.Base import all import Standard.Table.Data.Sort_Column type Sort_Column_Selector - type By_Name (columns : Vector Sort_Column.Name) (matcher:Matcher=Text_Matcher) - type By_Index (columns : Vector Sort_Column.Index) - type By_Column (columns : Vector Sort_Column.Column) + By_Name (columns : Vector Sort_Column.Name) (matcher:Matcher=Text_Matcher) + By_Index (columns : Vector Sort_Column.Index) + By_Column (columns : Vector Sort_Column.Column) diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso index 9a64e945d393..6a5e91f36a0a 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso @@ -16,7 +16,7 @@ import Standard.Table.Internal.Problem_Builder from Standard.Table.Data.Column_Selector import Column_Selector, By_Index from Standard.Table.Data.Column_Type_Selection import Column_Type_Selection, Auto -from Standard.Table.Data.Data_Formatter import Data_Formatter +from Standard.Table.Data.Data_Formatter import Data_Formatter, Data_Formatter_Data from Standard.Base.Data.Text.Text_Ordering import Text_Ordering from Standard.Base.Error.Problem_Behavior import Problem_Behavior, Report_Warning from Standard.Table.Errors import Missing_Input_Columns, Column_Indexes_Out_Of_Range, Duplicate_Type_Selector @@ -52,8 +52,8 @@ new : Vector (Vector | Column) -> Table new columns = cols = columns.map c-> case c of - Vector.Vector _ -> Column.from_vector (c.at 0) (c.at 1) . java_column - Column.Column java_col -> java_col + Vector.Vector_Data _ -> Column.from_vector (c.at 0) (c.at 1) . java_column + Column.Column_Data java_col -> java_col from_columns cols ## Creates a new table from a vector of column names and a vector of vectors @@ -129,7 +129,7 @@ join tables = Table.concat [table_1, table_2] concat : Vector -> Table concat tables = - Table (Java_Table.concat (tables.map .java_table).to_array) + Table_Data (Java_Table.concat (tables.map .java_table).to_array) ## Represents a column-oriented table data structure. type Table @@ -140,7 +140,7 @@ type Table Arguments: - java_table: The internal java representation of the table. - type Table java_table + Table_Data java_table ## Returns a text containing an ASCII-art table displaying this data. @@ -156,7 +156,7 @@ type Table example_display = Examples.inventory_table.display display : Integer -> Boolean -> Text display self show_rows=10 format_terminal=False = - cols = Vector.Vector self.java_table.getColumns + cols = Vector.Vector_Data self.java_table.getColumns index = self.java_table.getIndex col_names = [index.getName] + cols.map .getName col_vals = cols.map .getStorage @@ -249,7 +249,7 @@ type Table at : Text -> Column ! No_Such_Column_Error at self name = case self.java_table.getColumnOrIndexByName name of Nothing -> Error.throw (No_Such_Column_Error name) - c -> Column.Column c + c -> Column.Column_Data c ## Returns a new table with a chosen subset of columns, as specified by the `columns`, from the input table. Any unmatched input columns will be @@ -533,7 +533,7 @@ type Table new_columns = validated.valid_columns.map c->(Aggregate_Column_Helper.java_aggregator c.first c.second) java_table = index.makeTable new_columns.to_array - new_table = Table java_table + new_table = Table_Data java_table on_problems.attach_problems_after new_table <| problems = java_table.getProblems @@ -617,7 +617,7 @@ type Table ordering = columns_for_ordering.map c->c.associated_selector.direction.to_sign comparator = Comparator.for_text_ordering text_ordering java_table = self.java_table.orderBy selected_columns.to_array ordering.to_array comparator - Table java_table + Table_Data java_table ## Parses columns within a Table to a specific value type. By default, it looks at all `Text` columns and attempts to deduce the @@ -630,7 +630,7 @@ type Table a leading 0). However, settings in the `Data_Formatter` can control this. parse_values : Data_Formatter -> (Nothing | [Column_Type_Selection]) -> Problem_Behavior -> Table - parse_values self value_formatter=Data_Formatter column_types=Nothing on_problems=Report_Warning = + parse_values self value_formatter=Data_Formatter_Data column_types=Nothing on_problems=Report_Warning = columns = self.columns problem_builder = Vector.new_builder @@ -678,9 +678,9 @@ type Table storage = column.java_column.getStorage new_storage_and_problems = parser.parseColumn column.name storage new_storage = new_storage_and_problems.value - problems = Vector.Vector new_storage_and_problems.problems . map (Parse_Values_Helper.translate_parsing_problem expected_type) + problems = Vector.Vector_Data new_storage_and_problems.problems . map (Parse_Values_Helper.translate_parsing_problem expected_type) problems.each problem_builder.append - Column.Column (Java_Column.new column.name column.java_column.getIndex new_storage) + Column.Column_Data (Java_Column.new column.name column.java_column.getIndex new_storage) ## TODO [RW] this case of is a workaround for wrong dataflow handling on arrays, it can be removed once the PR fixing it is merged, the relevant PR is: https://github.com/enso-org/enso/pull/3400 @@ -711,7 +711,7 @@ type Table table.where mask where : Column -> Table where self indexes = - Table (self.java_table.mask indexes.java_column) + Table_Data (self.java_table.mask indexes.java_column) ## ALIAS Add Column @@ -736,10 +736,10 @@ type Table table.set "total_stock" double_inventory set : Text -> Column.Column | Vector.Vector -> Table set self name column = case column of - Vector.Vector _ -> + Vector.Vector_Data _ -> self.set name (Column.from_vector name column) - Column.Column _ -> - Table (self.java_table.addOrReplaceColumn (column.rename name . java_column)) + Column.Column_Data _ -> + Table_Data (self.java_table.addOrReplaceColumn (column.rename name . java_column)) ## Returns the vector of columns contained in this table. @@ -750,7 +750,7 @@ type Table example_columns = Examples.inventory_table.columns columns : Vector - columns self = Vector.Vector self.java_table.getColumns . map Column.Column + columns self = Vector.Vector_Data self.java_table.getColumns . map Column.Column ## Sets the index of this table, using the column with the provided name. @@ -766,8 +766,8 @@ type Table example_set_index = Examples.inventory_table.set_index "item_name" set_index : Text | Column -> Table set_index self index = case index of - Text -> Table (self.java_table.indexFromColumn index) - Column.Column c -> Table (self.java_table.indexFromColumn c) + Text -> Table_Data (self.java_table.indexFromColumn index) + Column.Column_Data c -> Table_Data (self.java_table.indexFromColumn c) ## Returns the index of this table, as a column that is indexed by itself. @@ -783,7 +783,7 @@ type Table index : Column.Column ! No_Index_Set_Error index self = case self.java_table.getIndex.toColumn of Nothing -> Error.throw No_Index_Set_Error - i -> Column.Column i + i -> Column.Column_Data i ## ALIAS Join Table @@ -819,9 +819,9 @@ type Table join : Table | Column.Column -> Text | Nothing -> Boolean -> Text -> Text -> Table join self other on=Nothing drop_unmatched=False left_suffix='_left' right_suffix='_right' = case other of - Column.Column _ -> self.join other.to_table on drop_unmatched left_suffix right_suffix - Table t -> - Table (self.java_table.join t drop_unmatched on left_suffix right_suffix) + Column.Column_Data _ -> self.join other.to_table on drop_unmatched left_suffix right_suffix + Table_Data t -> + Table_Data (self.java_table.join t drop_unmatched on left_suffix right_suffix) ## ALIAS Clean Rows @@ -860,7 +860,7 @@ type Table drop_missing_columns self = non_missing = self.columns . filter (col -> col.count_missing == 0) index = self.java_table.getIndex - Table (Java_Table.new (non_missing.map .java_column . to_array) index) + Table_Data (Java_Table.new (non_missing.map .java_column . to_array) index) ## Returns the number of rows in this table. @@ -918,7 +918,7 @@ type Table example_concat = Examples.inventory_table.concat Examples.popularity_table concat : Table -> Table - concat self other = Table (Java_Table.concat [self.java_table, other.java_table].to_array) + concat self other = Table_Data (Java_Table.concat [self.java_table, other.java_table].to_array) ## ALIAS First N Rows UNSTABLE @@ -938,7 +938,7 @@ type Table example_take_start = Examples.inventory_table.take_start 4 take_start : Integer -> Table - take_start self count = Table (self.java_table.slice 0 count) + take_start self count = Table_Data (self.java_table.slice 0 count) ## ALIAS Last N Rows UNSTABLE @@ -960,7 +960,7 @@ type Table take_end : Integer -> Table take_end self count = start_point = Math.max (self.row_count - count) 0 - Table (self.java_table.slice start_point count) + Table_Data (self.java_table.slice start_point count) ## ALIAS First Row UNSTABLE @@ -1030,7 +1030,7 @@ type Table reverse : Table reverse self = mask = OrderBuilder.buildReversedMask self.row_count - Table <| self.java_table.applyMask mask + Table_Data <| self.java_table.applyMask mask ## ALIAS Write JSON UNSTABLE @@ -1104,7 +1104,7 @@ type Table import Standard.Examples import Standard.Table - example_to_csv = Examples.inventory_table.write (Enso_Project.data / "example_csv_output.csv") (File_Format.Delimited delimiter="," headers=False) + example_to_csv = Examples.inventory_table.write (Enso_Project.data / "example_csv_output.csv") (File_Format.Delimited_Data delimiter="," headers=False) > Example Write a table to an XLSX file. @@ -1119,7 +1119,7 @@ type Table ## Creates a text representation of the table using the CSV format. to_csv : Text - to_csv self = Text.from self (File_Format.Delimited delimiter=",") + to_csv self = Text.from self (File_Format.Delimited_Data delimiter=",") ## UNSTABLE @@ -1160,7 +1160,7 @@ Empty_Error.to_display_text : Text Empty_Error.to_display_text self = "The table is empty." ## PRIVATE -from_columns cols = Table (Java_Table.new cols.to_array) +from_columns cols = Table_Data (Java_Table.new cols.to_array) ## PRIVATE @@ -1216,10 +1216,10 @@ print_table header rows indices_count format_term = " " + y ([" " + header_line, divider] + row_lines).join '\n' -Table.from (that : Text) (format:File_Format.Delimited|File_Format.Fixed_Width = File_Format.Delimited '\t') (on_problems:Problem_Behavior=Report_Warning) = - if format.is_a File_Format.Delimited then Delimited_Reader.read_text that format on_problems else +Table.from (that : Text) (format:File_Format.Delimited|File_Format.Fixed_Width = File_Format.Delimited_Data '\t') (on_problems:Problem_Behavior=Report_Warning) = + if format.is_a File_Format.Delimited_Data then Delimited_Reader.read_text that format on_problems else Errors.unimplemented "Table.from for fixed-width files is not yet implemented." -Text.from (that : Table) (format:File_Format.Delimited|File_Format.Fixed_Width = File_Format.Delimited '\t') = +Text.from (that : Table) (format:File_Format.Delimited|File_Format.Fixed_Width = File_Format.Delimited_Data '\t') = if format.is_a File_Format.Delimited then Delimited_Writer.write_text that format else Errors.unimplemented "Text.from for fixed-width files is not yet implemented." diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso index c83cc23aa2c7..c8a27837a231 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso @@ -5,7 +5,8 @@ polyglot java import org.enso.table.error.ColumnNameMismatchException ## One or more columns not found in the input table. Can occur when using By_Name or By_Column. -type Missing_Input_Columns (criteria : [Text]) +type Missing_Input_Columns + Missing_Input_Columns_Data (criteria : [Text]) Missing_Input_Columns.to_display_text : Text Missing_Input_Columns.to_display_text self = @@ -13,7 +14,8 @@ Missing_Input_Columns.to_display_text self = ## One or more column indexes were invalid on the input table. Can occur when using By_Index. -type Column_Indexes_Out_Of_Range (indexes : [Integer]) +type Column_Indexes_Out_Of_Range + Column_Indexes_Out_Of_Range_Data (indexes : [Integer]) Column_Indexes_Out_Of_Range.to_display_text : Text Column_Indexes_Out_Of_Range.to_display_text self = case self.indexes.length == 1 of @@ -22,14 +24,16 @@ Column_Indexes_Out_Of_Range.to_display_text self = case self.indexes.length == 1 ## More names than the column count provided to the function. Can occur when using By_Position. -type Too_Many_Column_Names_Provided (column_names : [Text]) +type Too_Many_Column_Names_Provided + Too_Many_Column_Names_Provided_Data (column_names : [Text]) Too_Many_Column_Names_Provided.to_display_text : Text Too_Many_Column_Names_Provided.to_display_text self = "Too many column names provided. " + (self.column_names.at 0).to_text + " unused." ## One or more column names were invalid during a rename operation. -type Invalid_Output_Column_Names (column_names : [Text]) +type Invalid_Output_Column_Names + Invalid_Output_Column_Names_Data (column_names : [Text]) Invalid_Output_Column_Names.to_display_text : Text Invalid_Output_Column_Names.to_display_text self = case self.column_names.length == 1 of @@ -37,7 +41,8 @@ Invalid_Output_Column_Names.to_display_text self = case self.column_names.length False -> "The names "+self.column_names.short_display_text+" are invalid." ## One or more column names clashed during a rename operation. -type Duplicate_Output_Column_Names (column_names : [Text]) +type Duplicate_Output_Column_Names + Duplicate_Output_Column_Names_Data (column_names : [Text]) Duplicate_Output_Column_Names.to_display_text : Text Duplicate_Output_Column_Names.to_display_text self = case self.column_names.length == 1 of @@ -52,7 +57,8 @@ No_Output_Columns.to_display_text self = "The result contains no columns." ## Indicates that the provided Column_Selector has duplicate entries. -type Duplicate_Column_Selectors (duplicate_selectors : [(Text | Integer)]) +type Duplicate_Column_Selectors + Duplicate_Column_Selectors_Data (duplicate_selectors : [(Text | Integer)]) Duplicate_Column_Selectors.to_display_text : Text Duplicate_Column_Selectors.to_display_text self = @@ -62,7 +68,8 @@ Duplicate_Column_Selectors.to_display_text self = In case the selectors have differing metadata and the error does not prevent the operation from continuing, the first selector on the list is used. -type Column_Matched_By_Multiple_Selectors (column_name : Text) (selectors : [Any]) +type Column_Matched_By_Multiple_Selectors + Column_Matched_By_Multiple_Selectors_Data (column_name : Text) (selectors : [Any]) Column_Matched_By_Multiple_Selectors.to_display_text : Text Column_Matched_By_Multiple_Selectors.to_display_text self = @@ -74,7 +81,8 @@ Column_Matched_By_Multiple_Selectors.to_display_text self = For example, if the table has only one column, then selecting `By_Index [0, -1]` will only yield this single column and `Input_Indices_Already_Matched [-1]` will be raised. -type Input_Indices_Already_Matched (indices : [Integer]) +type Input_Indices_Already_Matched + Input_Indices_Already_Matched_Data (indices : [Integer]) Input_Indices_Already_Matched.to_display_text : Text Input_Indices_Already_Matched.to_display_text self = @@ -90,28 +98,32 @@ No_Input_Columns_Selected.to_display_text self = ## Indicates that an aggregation calculation could not be completed. -type Invalid_Aggregation (column:Text) (rows:[Integer]) (message:Text) +type Invalid_Aggregation + Invalid_Aggregation_Data (column:Text) (rows:[Integer]) (message:Text) Invalid_Aggregation.to_display_text : Text Invalid_Aggregation.to_display_text self = "The "+self.column+" could not be calculated at "+self.row.to_text+" : "+self.message ## Indicates that a floating point number was used in a grouping. -type Floating_Point_Grouping (column:Text) (rows:[Integer]) +type Floating_Point_Grouping + Floating_Point_Grouping_Data (column:Text) (rows:[Integer]) Floating_Point_Grouping.to_display_text : Text Floating_Point_Grouping.to_display_text self = "Grouping on floating points is not recommended within "+self.column+" at row "+self.row.to_text+"." ## Indicates that a text value with a delimiter was included in a concatenation without any quote character -type Unquoted_Delimiter (column:Text) (rows:[Integer]) +type Unquoted_Delimiter + Unquoted_Delimiter_Data (column:Text) (rows:[Integer]) Unquoted_Delimiter.to_display_text : Text Unquoted_Delimiter.to_display_text self = "The "+self.column+" at row "+self.row.to_text+" contains the delimiter and there is no specified quote character." ## Warning when additional warnings occurred. -type Additional_Warnings (count:Integer) +type Additional_Warnings + Additional_Warnings_Data (count:Integer) Additional_Warnings.to_display_text : Text Additional_Warnings.to_display_text self = @@ -122,20 +134,24 @@ Additional_Warnings.to_display_text self = Only the first 10 rows are reported, any additional ones are aggregated into a single instance of `Additional_Invalid_Rows`. -type Invalid_Row (source_file_line_number : Integer) (index : Integer | Nothing) (row : [Text]) +type Invalid_Row + Invalid_Row_Data (source_file_line_number : Integer) (index : Integer | Nothing) (row : [Text]) ## Indicates how many additional `Invalid_Row` warnings have been suppressed. -type Additional_Invalid_Rows (count : Integer) +type Additional_Invalid_Rows + Additional_Invalid_Rows_Data (count : Integer) ## Indicates that a quote inside of a delimited file cell has been opened but never closed. type Mismatched_Quote ## Indicates an unexpected parser error. -type Parser_Error cause +type Parser_Error + Parser_Error_Data cause ## Indicates that a specified location was not valid. -type Invalid_Location (location:Text) +type Invalid_Location + Invalid_Location_Data (location:Text) Invalid_Location.to_display_text : Text Invalid_Location.to_display_text self = @@ -149,7 +165,8 @@ Invalid_Location.to_display_text self = - datatype: The expected datatype. - cells: Contents of the cells that did not match the expected datatype format. -type Invalid_Format column:(Text|Nothing) (datatype:(Integer|Number|Date|Time|Time_Of_Day|Boolean)) (cells:[Text]) +type Invalid_Format + Invalid_Format_Data column:(Text|Nothing) (datatype:(Integer|Number|Date|Time|Time_Of_Day|Boolean)) (cells:[Text]) Invalid_Format.to_display_text : Text Invalid_Format.to_display_text self = @@ -162,17 +179,20 @@ Invalid_Format.to_display_text self = It may be empty if the value is parsed outside of a context of a column. - datatype: The expected datatype. - cells: Contents of the cells that contained leading zeros. -type Leading_Zeros column:(Text|Nothing) (datatype:(Integer|Number|Date|Time|Time_Of_Day|Boolean)) (cells:[Text]) +type Leading_Zeros + Leading_Zeros_Data column:(Text|Nothing) (datatype:(Integer|Number|Date|Time|Time_Of_Day|Boolean)) (cells:[Text]) ## Indicates that multiple `Column_Type_Selector` match the same column. If all matching selectors indicate the same type, the warning is reported but a parse is attempted anyway. If mixed types are requested, the column is not parsed due to ambiguity. -type Duplicate_Type_Selector column:Text ambiguous:Boolean +type Duplicate_Type_Selector + Duplicate_Type_Selector_Data column:Text ambiguous:Boolean ## Indicates that the given file type is not supported by the `Auto` format. -type Unsupported_File_Type filename +type Unsupported_File_Type + Unsupported_File_Type_Data filename Unsupported_File_Type.to_display_text : Text Unsupported_File_Type.to_display_text self = @@ -180,20 +200,23 @@ Unsupported_File_Type.to_display_text self = ## Indicates that the target range contains existing data and the user did not specify to overwrite. -type Existing_Data message +type Existing_Data + Existing_Data_Data message Existing_Data.to_display_text : Text Existing_Data.to_display_text self = self.message ## Indicates that the specified range is not large enough to fit the data. -type Range_Exceeded message +type Range_Exceeded + Range_Exceeded_Data message Range_Exceeded.to_display_text : Text Range_Exceeded.to_display_text self = self.message ## Indicates that the existing table has a different number of columns to the new table. -type Column_Count_Mismatch expected actual +type Column_Count_Mismatch + Column_Count_Mismatch_Data expected actual Column_Count_Mismatch.to_display_text : Text Column_Count_Mismatch.to_display_text self = @@ -208,7 +231,8 @@ Column_Count_Mismatch.handle_java_exception self = ## Indicates that the existing table has a different set of column names to the new table. -type Column_Name_Mismatch missing extras message +type Column_Name_Mismatch + Column_Name_Mismatch_Data missing extras message Column_Name_Mismatch.to_display_text : Text Column_Name_Mismatch.to_display_text self = self.message @@ -217,5 +241,5 @@ Column_Name_Mismatch.to_display_text self = self.message Column_Name_Mismatch.handle_java_exception = throw_column_name_mismatch caught_panic = cause = caught_panic.payload.cause - Error.throw (Column_Name_Mismatch (Vector.Vector cause.getMissing) (Vector.Vector cause.getExtras) cause.getMessage) + Error.throw (Column_Name_Mismatch_Data (Vector.Vector_Data cause.getMissing) (Vector.Vector_Data cause.getExtras) cause.getMessage) Panic.catch ColumnNameMismatchException handler=throw_column_name_mismatch 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 a36acecdd819..ff6e7c0cffe8 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 @@ -11,7 +11,7 @@ import Standard.Table.Internal.Delimited_Reader import Standard.Table.Internal.Delimited_Writer from Standard.Table.Errors import Unsupported_File_Type -from Standard.Table.Data.Data_Formatter import Data_Formatter +from Standard.Table.Data.Data_Formatter import Data_Formatter, Data_Formatter_Data import Standard.Table.IO.Excel as Excel_Module import Standard.Table.IO.Quote_Style @@ -21,8 +21,6 @@ import Standard.Table.IO.Quote_Style ## Determines the format of file to use based on the file extension. type Auto - type Auto - ## ADVANCED Gets the underlying File_Format for the specified file materialise : File->File_Format @@ -56,7 +54,6 @@ type Auto ## Reads the file to a `Vector` of bytes. type Bytes - type Bytes ## Implements the `File.read` for this `File_Format` read : File -> Problem_Behavior -> Any @@ -70,7 +67,7 @@ type Bytes ## Reads the file to a `Text` with specified encoding. type Plain_Text - type Plain_Text (encoding:Encoding=Encoding.utf_8) + Plain_Text_Data (encoding:Encoding=Encoding.utf_8) ## Implements the `File.read` for this `File_Format` read : File -> Problem_Behavior -> Any @@ -120,7 +117,7 @@ type Delimited character if it anywhere else than at the beginning of the line. This option is only applicable for read mode and does not affect writing. It defaults to `Nothing` which means that comments are disabled. - type Delimited (delimiter:Text) (encoding:Encoding=Encoding.utf_8) (skip_rows:Integer=0) (row_limit:Integer|Nothing=Nothing) (quote_style:Quote_Style=Quote_Style.With_Quotes) (headers:Boolean|Infer=Infer) (value_formatter:Data_Formatter|Nothing=Data_Formatter) (keep_invalid_rows:Boolean=True) (line_endings:Line_Ending_Style=Infer) (comment_character:Text|Nothing=Nothing) + Delimited_Data (delimiter:Text) (encoding:Encoding=Encoding.utf_8) (skip_rows:Integer=0) (row_limit:Integer|Nothing=Nothing) (quote_style:Quote_Style=Quote_Style.With_Quotes) (headers:Boolean|Infer=Infer) (value_formatter:Data_Formatter|Nothing=Data_Formatter_Data) (keep_invalid_rows:Boolean=True) (line_endings:Line_Ending_Style=Infer) (comment_character:Text|Nothing=Nothing) ## Implements the `File.read` for this `File_Format` read : File -> Problem_Behavior -> Any @@ -133,8 +130,8 @@ type Delimited Delimited_Writer.write_file table self file on_existing_file match_columns on_problems ## PRIVATE - Clone the instance with some properties overridden. - Note: This function is internal until such time as Atom cloning with modification is built into Enso. + Clone the instance with some properties overridden. + Note: This function is internal until such time as Atom cloning with modification is built into Enso. clone : Text->Text->(Boolean|Infer)->Data_Formatter->Boolean->(Text|Nothing)->(Text|Nothing)->Delimited clone self (quote_style=self.quote_style) (headers=self.headers) (value_formatter=self.value_formatter) (keep_invalid_rows=self.keep_invalid_rows) (line_endings=self.line_endings) (comment_character=self.comment_character) = Delimited self.delimiter self.encoding self.skip_rows self.row_limit quote_style headers value_formatter keep_invalid_rows line_endings comment_character @@ -162,7 +159,7 @@ type Delimited A custom `Data_Formatter` can be provided to customize parser options. with_parsing : Data_Formatter -> Delimited - with_parsing self (value_formatter=Data_Formatter) = + with_parsing self (value_formatter=Data_Formatter_Data) = self.clone value_formatter=value_formatter ## Create a clone of this without value parsing. @@ -208,7 +205,7 @@ type Excel If set to `True`, the file is read as an Excel 95-2003 format. If set to `False`, the file is read as an Excel 2007+ format. `Infer` will attempt to deduce this from the extension of the filename. - type Excel (section:Excel_Section=Excel_Module.Sheet) (headers:(True|False|Infer)=Infer) (xls_format:(True|False|Infer)=Infer) + Excel_Data (section:Excel_Section=Excel_Module.Sheet) (headers:(True|False|Infer)=Infer) (xls_format:(True|False|Infer)=Infer) ## Implements the `File.read` for this `File_Format` read : File -> Problem_Behavior -> Any diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/IO/Quote_Style.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/IO/Quote_Style.enso index 9ec7de9f0e2d..092ecedbd00e 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/IO/Quote_Style.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/IO/Quote_Style.enso @@ -6,7 +6,7 @@ type Quote_Style No quote parsing is done when reading the file. In write mode, values are not quoted even if this would result in an invalid file. - type No_Quotes + No_Quotes ## Specifies the style of quotes when reading or writing a `Delimited` file. @@ -30,4 +30,4 @@ type Quote_Style The quote and escape characters must consist of exactly one code-point (i.e. it can be only one character and complex characters like emojis may not be used). - type With_Quotes (always_quote : Boolean = False) (quote : Text = '"') (quote_escape : Text = '"') + With_Quotes (always_quote : Boolean = False) (quote : Text = '"') (quote_escape : Text = '"') diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Aggregate_Column_Helper.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Aggregate_Column_Helper.enso index f5cdabccefe4..21a60cc612e0 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Aggregate_Column_Helper.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Aggregate_Column_Helper.enso @@ -39,7 +39,8 @@ polyglot java import org.enso.table.data.table.problems.UnquotedDelimiter - key_columns: Vector of Columns from the table to group by - valid_columns: Table structure to build as pairs of unique column name and Aggregate_Column - problems: Set of any problems when validating the input -type Validated_Aggregate_Columns (key_columns:[Column]) (valid_columns:[Pair Text Aggregate_Column]) (problems:[Any]) +type Validated_Aggregate_Columns + Validated_Aggregate_Columns_Data (key_columns:[Column]) (valid_columns:[Pair Text Aggregate_Column]) (problems:[Any]) ## PRIVATE Prepares an aggregation input for further processing: @@ -80,7 +81,7 @@ prepare_aggregate_columns aggregates table = if unique.renames.not_empty then problem_builder.report_other_warning (Duplicate_Output_Column_Names unique.renames) - Validated_Aggregate_Columns unique_key_columns renamed_columns problem_builder.build_problemset + Validated_Aggregate_Columns_Data unique_key_columns renamed_columns problem_builder.build_problemset ## PRIVATE Defines the default name of an `Aggregate_Column`. 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 38e995e92013..8665a69510ab 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 @@ -7,7 +7,7 @@ from Standard.Base.Error.Problem_Behavior import Problem_Behavior, Ignore, Repor from Standard.Table.Errors import Duplicate_Output_Column_Names, Invalid_Output_Column_Names, Invalid_Row, Mismatched_Quote, Parser_Error, Additional_Invalid_Rows from Standard.Base.Data.Text.Encoding import Encoding, Encoding_Error from Standard.Table.IO.File_Format import Infer -from Standard.Table.Data.Data_Formatter import Data_Formatter +from Standard.Table.Data.Data_Formatter import Data_Formatter_Data import Standard.Table.IO.Quote_Style polyglot java import org.enso.base.encoding.NewlineDetector @@ -93,8 +93,8 @@ read_from_reader format java_reader on_problems max_columns=4096 = Illegal_Argument_Error.handle_java_exception <| handle_parsing_failure <| handle_parsing_exception <| reader = prepare_delimited_reader java_reader format max_columns on_problems result_with_problems = reader.read - parsing_problems = Vector.Vector (result_with_problems.problems) . map translate_reader_problem - on_problems.attach_problems_after (Table.Table result_with_problems.value) parsing_problems + parsing_problems = Vector.Vector_Data (result_with_problems.problems) . map translate_reader_problem + on_problems.attach_problems_after (Table.Table_Data result_with_problems.value) parsing_problems ## PRIVATE prepare_delimited_reader java_reader format max_columns on_problems newline_override=Nothing = @@ -105,11 +105,11 @@ prepare_delimited_reader java_reader format max_columns on_problems newline_over row_limit = case format.row_limit of Nothing -> -1 Integer -> format.row_limit - _ -> Error.throw (Illegal_Argument_Error "`row_limit` should be Integer or Nothing.") + _ -> Error.throw (Illegal_Argument_Error_Data "`row_limit` should be Integer or Nothing.") warnings_as_errors = on_problems == Report_Error quote_characters = case format.quote_style of - Quote_Style.No_Quotes -> Pair Nothing Nothing - Quote_Style.With_Quotes _ quote quote_escape -> Pair quote quote_escape + Quote_Style.No_Quotes -> Pair_Data Nothing Nothing + Quote_Style.With_Quotes _ quote quote_escape -> Pair_Data quote quote_escape base_parser = case format.quote_style of Quote_Style.No_Quotes -> IdentityParser.new Quote_Style.With_Quotes _ quote _ -> @@ -118,7 +118,7 @@ prepare_delimited_reader java_reader format max_columns on_problems newline_over wrapped = format.value_formatter.wrap_base_parser base_parser TypeInferringParser.new format.value_formatter.get_specific_type_parsers.to_array wrapped cell_type_guesser = if format.headers != Infer then Nothing else - formatter = format.value_formatter.if_nothing Data_Formatter + formatter = format.value_formatter.if_nothing Data_Formatter_Data TypeInferringParser.new formatter.get_specific_type_parsers.to_array IdentityParser.new newline = newline_override.if_nothing <| case format.line_endings of Infer -> Nothing @@ -160,7 +160,7 @@ type Detected_File_Metadata - ends_with_newline: specifies if the last line ends with a line separator that is consistent with the detected one. - has_any_content: specifies if the file contains any content. - Detected_File_Metadata (headers : Detected_Headers) (line_separator : Text|Nothing) (ends_with_newline : Boolean) (has_any_content : Boolean) + Detected_File_Metadata_Data (headers : Detected_Headers) (line_separator : Text|Nothing) (ends_with_newline : Boolean) (has_any_content : Boolean) ## PRIVATE Reads the beginning of the file to detect the existing headers and column @@ -199,8 +199,8 @@ detect_metadata file format = True -> line_separator_from_parser False -> trailing_line_separator has_any_content = reader.getVisitedCharactersCount > 0 - Detected_File_Metadata headers effective_line_separator has_trailing_line_separator has_any_content - result.catch File.File_Not_Found (_->(Detected_File_Metadata Nothing Nothing False False)) + Detected_File_Metadata_Data headers effective_line_separator has_trailing_line_separator has_any_content + result.catch File.File_Not_Found (_->(Detected_File_Metadata_Data Nothing Nothing False False)) ## PRIVATE Checks if the file has a newline at the end. diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Parse_Values_Helper.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Parse_Values_Helper.enso index 094b56adb86e..41f140f07554 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Parse_Values_Helper.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Parse_Values_Helper.enso @@ -1,16 +1,16 @@ from Standard.Base import all -from Standard.Table.Errors as Table_Errors import Invalid_Format, Leading_Zeros +from Standard.Table.Errors as Table_Errors import Invalid_Format_Data, Leading_Zeros_Data polyglot java import org.enso.table.parsing.problems.InvalidFormat polyglot java import org.enso.table.parsing.problems.LeadingZeros translate_parsing_problem expected_datatype problem = - invalid_format = [InvalidFormat, (java_problem-> Invalid_Format java_problem.column expected_datatype (Vector.Vector java_problem.cells))] - leading_zeros = [LeadingZeros, (java_problem-> Leading_Zeros java_problem.column expected_datatype (Vector.Vector java_problem.cells))] + invalid_format = [InvalidFormat, (java_problem-> Invalid_Format_Data java_problem.column expected_datatype (Vector.Vector_Data java_problem.cells))] + leading_zeros = [LeadingZeros, (java_problem-> Leading_Zeros_Data java_problem.column expected_datatype (Vector.Vector_Data java_problem.cells))] translations = [invalid_format, leading_zeros] found = translations.find t-> Java.is_instance problem t.first translation = found.catch Any _-> - Error.throw (Illegal_State_Error "Reported an unknown problem type: "+problem.to_text) + Error.throw (Illegal_State_Error_Data "Reported an unknown problem type: "+problem.to_text) translation.second problem diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Problem_Builder.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Problem_Builder.enso index c39672a24602..cb95848e9abb 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Problem_Builder.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Problem_Builder.enso @@ -7,7 +7,7 @@ import Standard.Table.Internal.Vector_Builder from Standard.Table.Errors import Missing_Input_Columns, Column_Indexes_Out_Of_Range, No_Output_Columns, Duplicate_Column_Selectors, Input_Indices_Already_Matched, Too_Many_Column_Names_Provided, Duplicate_Output_Column_Names, Invalid_Output_Column_Names, Column_Matched_By_Multiple_Selectors type Problem_Builder - type Problem_Builder oob_indices duplicate_column_selectors input_indices_already_matched missing_input_columns other + Problem_Builder_Data oob_indices duplicate_column_selectors input_indices_already_matched missing_input_columns other report_oob_indices self indices = append_to_ref self.oob_indices indices @@ -62,7 +62,7 @@ type Problem_Builder Creates a new helper object for aggregating problems to report. new : Problem_Builder new = - Problem_Builder (Ref.new Vector_Builder.empty) (Ref.new Vector_Builder.empty) (Ref.new Vector_Builder.empty) (Ref.new Vector_Builder.empty) other=Vector.new_builder + Problem_Builder_Data (Ref.new Vector_Builder.empty) (Ref.new Vector_Builder.empty) (Ref.new Vector_Builder.empty) (Ref.new Vector_Builder.empty) other=Vector.new_builder ## PRIVATE Appends a `Vector` to a `Vector_Builder` stored in a `Ref`. diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Table_Helpers.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Table_Helpers.enso index 2d7574518838..d7f0c703fff6 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Table_Helpers.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Table_Helpers.enso @@ -146,10 +146,10 @@ rename_columns internal_columns mapping on_problems = _ -> matched.add index new_name = case ms of - Regex_Matcher _ _ _ _ _ -> + Regex_Matcher_Data _ _ _ _ _ -> pattern = ms.compile ((good_names.at index).at 0) pattern.replace name ((good_names.at index).at 1) - Text_Matcher _ -> (good_names.at index).at 1 + Text_Matcher_Data _ -> (good_names.at index).at 1 unique.make_unique new_name new_names = 0.up_to col_count . map i->(mapper (internal_columns.at i).name) @@ -209,7 +209,7 @@ sort_columns internal_columns direction text_ordering = case_sensitive = text_ordering.case_sensitive.if_nothing True mapper = case case_sensitive of True -> _.name - Case_Insensitive locale -> + Case_Insensitive_Data locale -> col -> col.name.to_case_insensitive_key locale=locale comparator = case text_ordering.sort_digits_as_numbers of True -> Natural_Order.compare @@ -273,7 +273,7 @@ resolve_column_helper internal_columns selector problem_builder = case selector Converts the generic `No_Matches_Found` error to a more specific `Missing_Input_Columns`. Any other errors are returned as-is. promote_no_matches_to_missing_columns error = case error of - Matching.No_Matches_Found criteria -> Maybe.Some <| Missing_Input_Columns criteria + Matching.No_Matches_Found_Data criteria -> Maybe.Some <| Missing_Input_Columns criteria _ -> Nothing ## PRIVATE 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 6164bec1294a..dd5cf44055f7 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 @@ -56,7 +56,7 @@ type Vector_Builder ix2 = go ix l go ix2 r go 0 self - Vector.Vector array + Vector.Vector_Data array ## PRIVATE @@ -73,7 +73,7 @@ type Vector_Builder case other of Leaf _ -> Append self other len Append _ _ _ -> Append self other len - Vector.Vector _ -> Append self (Leaf other) len + Vector.Vector_Data _ -> Append self (Leaf other) len ## PRIVATE diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso index 063f0e95eade..08fe9897304a 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso @@ -48,8 +48,8 @@ from Standard.Table.Data.Table export new, from_rows, join, concat, No_Such_Colu json = Examples.simple_table_json headers = Examples.simple_table_json_headers json.to_table headers -Json.Array.to_table : Vector -> Table -Json.Array.to_table self fields = case self of +Json.Json.to_table : Vector -> Table +Json.Json.to_table self fields = case self of Json.Array items -> rows = items.map item-> case item of Json.Object fs -> @@ -59,58 +59,26 @@ Json.Array.to_table self fields = case self of cols = fields.map_with_index i-> n-> [n, rows.map (_.at i)] Table.new cols + Json.Object _ -> + if self.get_type != Geo_Json.Feature_Collection.to_text then Error.throw (Invalid_Format_Error self "not being a feature collection") else + case self.get "features" of + Json.Array items -> + feature_rows = items.map .get_feature_row + column_names = case fields of + Nothing -> + column_names_row = feature_rows.fold Map.empty acc-> row-> + row.fold_with_key acc a-> k-> _-> + a.insert k 0 + column_names_row.keys + _ -> fields + rows = feature_rows.map row-> + column_names.map n-> row.get n . unwrap . catch Any (_ -> Nothing) + cols = column_names.map_with_index i-> n-> + [n, rows.map (_.at i)] + Table.new cols + + _ -> Error.throw (Invalid_Format_Error self "not having the 'features' key.") -## ALIAS To Table - - Converts a JSON object into a dataframe, by looking up the requested keys - from each item. - - Arguments: - - fields: a vector of texts representing the names of fields to look up. - - The function assumes the elements have one of the following structures: - - a GeoJSON object of type FeatureCollection. The format is described in - rfc7946. - - ? Implementation Note - The GeoJson support is only partial. - - Supported geometry objects are Position and Point. Rows containing - other geometry objects are not included in the resulting dataframe. - - Position arrays are truncated to 3 elements: longitude, latitude - and elevation. - - Nested properties are not supported and not included in the resulting - dataframe. - - > Example - Convert a GeoJSON object into a dataframe by looking up the necessary keys - in the input item. - - import Standard.Examples - import Standard.Table - - example_to_table = - json = Examples.geo_json - json.to_table -Json.Object.to_table : Vector -> Table ! Invalid_Format_Error -Json.Object.to_table self fields=Nothing = - if self.get_type != Geo_Json.Feature_Collection.to_text then Error.throw (Invalid_Format_Error self "not being a feature collection") else - case self.get "features" of - Json.Array items -> - feature_rows = items.map .get_feature_row - column_names = case fields of - Nothing -> - column_names_row = feature_rows.fold Map.empty acc-> row-> - row.fold_with_key acc a-> k-> _-> - a.insert k 0 - column_names_row.keys - _ -> fields - rows = feature_rows.map row-> - column_names.map n-> row.get n . unwrap . catch Any (_ -> Nothing) - cols = column_names.map_with_index i-> n-> - [n, rows.map (_.at i)] - Table.new cols - - _ -> Error.throw (Invalid_Format_Error self "not having the 'features' key.") ## UNSTABLE diff --git a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Histogram.enso b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Histogram.enso index 4425655f9d86..0f58785ac0bf 100644 --- a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Histogram.enso +++ b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Histogram.enso @@ -24,7 +24,7 @@ Table.Table.value_column self = type Update ## PRIVATE - type Update values label + Update_Data values label ## PRIVATE @@ -44,12 +44,12 @@ from_table table = col = table.value_column label = col.name.catch_ Nothing values = col.to_vector.catch_ [] - Update values label + Update_Data values label ## PRIVATE from_vector : Vector -> Update from_vector vector = - Update vector Nothing + Update_Data vector Nothing ## PRIVATE from_value : Any -> Update diff --git a/test/Table_Tests/src/Column_Spec.enso b/test/Table_Tests/src/Column_Spec.enso index 18dfec14370e..963429068f2a 100644 --- a/test/Table_Tests/src/Column_Spec.enso +++ b/test/Table_Tests/src/Column_Spec.enso @@ -13,8 +13,8 @@ spec = Test.group "Columns" <| test_column.at 0 . should_equal 1 test_column.at 2 . should_equal 5 test_column.at 5 . should_equal 6 - test_column.at 6 . should_fail_with Index_Out_Of_Bounds_Error - empty_column.at 0 . should_fail_with Index_Out_Of_Bounds_Error + test_column.at 6 . should_fail_with Index_Out_Of_Bounds_Error_Data + empty_column.at 0 . should_fail_with Index_Out_Of_Bounds_Error_Data Test.specify "should be able to take the first n elements" <| expected_1 = Column.from_vector "Test" [1, 3, 5] diff --git a/test/Table_Tests/src/Csv_Spec.enso b/test/Table_Tests/src/Csv_Spec.enso index a601d6a8472c..df82211738c9 100644 --- a/test/Table_Tests/src/Csv_Spec.enso +++ b/test/Table_Tests/src/Csv_Spec.enso @@ -18,7 +18,7 @@ spec = Test.group "Table.from Text" <| Test.specify "should create a table from a textual CSV" <| file_contents = (enso_project.data / "simple_empty.csv") . read_text - table = Table.Table.from file_contents (format = File_Format.Delimited ",") + table = Table.Table.from file_contents (format = File_Format.Delimited_Data ",") table.should_equal expected_table Test.group "File.read (Delimited)" <| @@ -44,13 +44,13 @@ spec = csv = """ name,x,y,x,y foo,10,20,30,20 - t = Table.Table.from csv (format = File_Format.Delimited ",") + t = Table.Table.from csv (format = File_Format.Delimited_Data ",") t.columns.map .name . should_equal ['name', 'x', 'y', 'x_1', 'y_1'] Test.group 'Writing' <| Test.specify 'should properly serialize simple tables' <| varied_column = (enso_project.data / "varied_column.csv") . read - res = Text.from varied_column format=(File_Format.Delimited ",") + res = Text.from varied_column format=(File_Format.Delimited_Data ",") exp = normalize_lines <| ''' Column_1,Column_2,Column_3,Column_4,Column_5,Column_6 2005-02-25,2005-02-25,1,1,1.0,1 @@ -74,7 +74,7 @@ spec = "This;Name;;Is""""Strange";20 Marcin,,;"hello;world" - res = Text.from t format=(File_Format.Delimited ";") + res = Text.from t format=(File_Format.Delimited_Data ";") res.should_equal expected Test.specify 'should allow forced quoting of records' @@ -88,7 +88,7 @@ spec = "This;Name;;Is""""Strange",20 "Marcin,,","hello;world" - res = Text.from t format=(File_Format.Delimited "," . with_quotes always_quote=True) + res = Text.from t format=(File_Format.Delimited_Data "," . with_quotes always_quote=True) res.should_equal expected diff --git a/test/Table_Tests/src/Data_Formatter_Spec.enso b/test/Table_Tests/src/Data_Formatter_Spec.enso index c08264ce4a5e..6e69ae79aa23 100644 --- a/test/Table_Tests/src/Data_Formatter_Spec.enso +++ b/test/Table_Tests/src/Data_Formatter_Spec.enso @@ -6,37 +6,37 @@ import Standard.Base.Data.Time.Time_Of_Day import Standard.Table import Standard.Table.Data.Column from Standard.Table.Errors import all -from Standard.Table.Data.Data_Formatter as Data_Formatter_Module import Data_Formatter +from Standard.Table.Data.Data_Formatter as Data_Formatter_Module import Data_Formatter_Data import Standard.Table.IO.Quote_Style import Standard.Test import Standard.Test.Problems type Custom_Type - type Custom_Type field + Custom_Type_Data field type Custom_Type_With_To_Text - type Custom_Type_With_To_Text field + Custom_Type_With_To_Text_Data field to_text : Text to_text self = "[CUSTOM = " + self.field.to_text + "]" type Custom_Type_With_Error - type Custom_Type_With_Error + Custom_Type_With_Error_Data to_text : Text - to_text self = Error.throw (Illegal_State_Error "foo_error") + to_text self = Error.throw (Illegal_State_Error_Data "foo_error") type Custom_Type_With_Panic - type Custom_Type_With_Panic + Custom_Type_With_Panic_Data to_text : Text - to_text self = Panic.throw (Illegal_State_Error "foo_panic") + to_text self = Panic.throw (Illegal_State_Error_Data "foo_panic") spec = Test.group "DataFormatter.parse" <| Test.specify "should parse numbers" <| - formatter = Data_Formatter + formatter = Data_Formatter_Data formatter.parse "123" . should_equal 123 formatter.parse "1000000" . should_equal 1000000 formatter.parse "1000000.0" . should_equal 1000000.0 @@ -51,7 +51,7 @@ spec = formatter.parse "NaN" . is_nan . should_be_true Test.specify "should allow customizing the decimal point and thousand separator" <| - formatter = Data_Formatter thousand_separator="_" decimal_point="," + formatter = Data_Formatter_Data thousand_separator="_" decimal_point="," formatter.parse "123" . should_equal 123 formatter.parse "1_000_000" . should_equal 1000000 formatter.parse "1_000_000_000" . should_equal (1000 * 1000 * 1000) @@ -63,13 +63,13 @@ spec = formatter.parse "1,0001" . should_equal 1.0001 Test.specify "should support exponential notation, but only if explicitly enabled" <| - plain_formatter = Data_Formatter - exponential_formatter = Data_Formatter allow_exponential_notation=True + plain_formatter = Data_Formatter_Data + exponential_formatter = Data_Formatter_Data allow_exponential_notation=True plain_formatter.parse "1E3" . should_equal "1E3" r1 = plain_formatter.parse "1E3" Decimal r1.should_equal Nothing - Warning.get_all r1 . map .value . should_equal [(Invalid_Format Nothing Decimal ["1E3"])] + Warning.get_all r1 . map .value . should_equal [(Invalid_Format_Data Nothing Decimal ["1E3"])] exponential_formatter.parse "1E3" . should_equal 1000.0 exponential_formatter.parse "1E3" Decimal . should_equal 1000.0 @@ -81,16 +81,16 @@ spec = exponential_formatter.parse "1.2E-3" Decimal . should_equal 0.0012 Test.specify "handle leading zeros, only if enabled" <| - Data_Formatter.parse "0100" . should_equal "0100" - Data_Formatter.parse "000" . should_equal "000" - Data_Formatter.parse "000.0" . should_equal "000.0" - formatter = Data_Formatter allow_leading_zeros=True + Data_Formatter_Data.parse "0100" . should_equal "0100" + Data_Formatter_Data.parse "000" . should_equal "000" + Data_Formatter_Data.parse "000.0" . should_equal "000.0" + formatter = Data_Formatter_Data allow_leading_zeros=True formatter.parse "0100" . should_equal 100 formatter.parse "000" . should_equal 0 formatter.parse "000.0" . should_equal 0.0 Test.specify "should fallback to Text" <| - formatter = Data_Formatter + formatter = Data_Formatter_Data formatter.parse "Text" . should_equal "Text" complex_text = """ Text with such 'quotes' and also "that" and `that` @@ -99,10 +99,10 @@ spec = Test.group "DataFormatter.format" <| Test.specify "should handle Nothing" <| - Data_Formatter.format Nothing . should_equal Nothing + Data_Formatter_Data.format Nothing . should_equal Nothing Test.specify "should format numbers" <| - formatter = Data_Formatter + formatter = Data_Formatter_Data formatter.format 123 . should_equal "123" formatter.format 1000000 . should_equal "1000000" formatter.format 1000000.0 . should_equal "1000000.0" @@ -115,7 +115,7 @@ spec = formatter.format (Number.nan) . should_equal "NaN" Test.specify "should allow customizing the decimal point and thousand separator" <| - formatter = Data_Formatter thousand_separator="_" decimal_point="," + formatter = Data_Formatter_Data thousand_separator="_" decimal_point="," formatter.format 123 . should_equal "123" formatter.format 1000000 . should_equal "1_000_000" formatter.format (1000 * 1000 * 1000) . should_equal "1_000_000_000" @@ -127,30 +127,30 @@ spec = formatter.format 1.0001 . should_equal "1,0001" Test.specify "should format booleans" <| - formatter = Data_Formatter + formatter = Data_Formatter_Data formatter.format True . should_equal "True" formatter.format False . should_equal "False" Test.specify "should allow custom boolean formats" <| - formatter = Data_Formatter true_values=["YES", "1", "true"] false_values=["NO", "0", "false"] + formatter = Data_Formatter_Data true_values=["YES", "1", "true"] false_values=["NO", "0", "false"] formatter.format True . should_equal "YES" formatter.format False . should_equal "NO" - (Data_Formatter true_values=[] false_values=[]).format True . should_fail_with Illegal_Argument_Error + (Data_Formatter_Data true_values=[] false_values=[]).format True . should_fail_with Illegal_Argument_Error_Data Test.specify "should format dates" <| - formatter = Data_Formatter + formatter = Data_Formatter_Data formatter.format (Date.new 2022) . should_equal "2022-01-01" formatter.format (Time.new 1999 . internal_zoned_date_time) . should_equal "1999-01-01 00:00:00" formatter.format (Time_Of_Day.new . internal_local_time) . should_equal "00:00:00" Test.specify "should allow custom date formats" <| - formatter = Data_Formatter date_formats=["E, d MMM y", "d MMM y[ G]"] datetime_formats=["dd/MM/yyyy HH:mm"] time_formats=["h:mma"] datetime_locale=Locale.uk + formatter = Data_Formatter_Data date_formats=["E, d MMM y", "d MMM y[ G]"] datetime_formats=["dd/MM/yyyy HH:mm"] time_formats=["h:mma"] datetime_locale=Locale.uk formatter.format (Date.new 2022 06 21) . should_equal "Tue, 21 Jun 2022" formatter.format (Time.new 1999 02 03 04 56 11 . internal_zoned_date_time) . should_equal "03/02/1999 04:56" formatter.format (Time_Of_Day.new 13 55 . internal_local_time) . should_equal "1:55pm" Test.specify "should act as identity on Text" <| - formatter = Data_Formatter + formatter = Data_Formatter_Data formatter.format "Text" . should_equal "Text" complex_text = """ Text with such 'quotes' and also "that" and `that` @@ -158,19 +158,19 @@ spec = formatter.format complex_text . should_equal complex_text Test.specify "should work with custom types, falling back to the `.to_text` method" <| - formatter = Data_Formatter thousand_separator="_" - formatter.format (Custom_Type 42) . should_equal "(Custom_Type 42)" + formatter = Data_Formatter_Data thousand_separator="_" + formatter.format (Custom_Type_Data 42) . should_equal "(Custom_Type_Data 42)" # We fallback to `to_text`, so obviously the nested numbers will not know about our formatting settings. - formatter.format (Custom_Type_With_To_Text 1000) . should_equal "[CUSTOM = 1000]" + formatter.format (Custom_Type_With_To_Text_Data 1000) . should_equal "[CUSTOM = 1000]" Test.specify "should correctly pass through errors from custom type's `.to_text` method" pending="TODO: figure out the desired behavior, see: https://www.pivotaltracker.com/story/show/182522644" <| - formatter = Data_Formatter - formatter.format Custom_Type_With_Error . should_fail_with Illegal_State_Error - Test.expect_panic_with (formatter.format Custom_Type_With_Panic) Illegal_State_Error + formatter = Data_Formatter_Data + formatter.format Custom_Type_With_Error_Data . should_fail_with Illegal_State_Error_Data + Test.expect_panic_with (formatter.format Custom_Type_With_Panic_Data) Illegal_State_Error_Data Test.group "DataFormatter builders" <| # We create a formatter with all non-default values to ensure that the builders keep the existing values of other properties instead of switching to the constructor's defaults. - formatter_1 = Data_Formatter trim_values=False allow_leading_zeros=True decimal_point=',' thousand_separator='_' allow_exponential_notation=True datetime_formats=["yyyy/MM/dd HH:mm:ss"] date_formats=["dd/MM/yyyy"] time_formats=["HH/mm/ss"] datetime_locale=Locale.uk true_values=["YES"] false_values=["NO"] + formatter_1 = Data_Formatter_Data trim_values=False allow_leading_zeros=True decimal_point=',' thousand_separator='_' allow_exponential_notation=True datetime_formats=["yyyy/MM/dd HH:mm:ss"] date_formats=["dd/MM/yyyy"] time_formats=["HH/mm/ss"] datetime_locale=Locale.uk true_values=["YES"] false_values=["NO"] Test.specify "should allow changing number formatting settings" <| formatter_2 = formatter_1.with_number_formatting decimal_point="*" formatter_2.decimal_point . should_equal "*" diff --git a/test/Table_Tests/src/In_Memory_Tests.enso b/test/Table_Tests/src/In_Memory_Tests.enso index a67727b06533..2c09e6ae2051 100644 --- a/test/Table_Tests/src/In_Memory_Tests.enso +++ b/test/Table_Tests/src/In_Memory_Tests.enso @@ -3,7 +3,7 @@ from Standard.Base import all import Standard.Test import project.Column_Spec -#import project.Csv_Spec +import project.Csv_Spec #import project.Delimited_Read_Spec #import project.Delimited_Write_Spec #import project.Excel_Spec diff --git a/test/Table_Tests/src/Main.enso b/test/Table_Tests/src/Main.enso index 0a626d00adeb..5f5298789ca9 100644 --- a/test/Table_Tests/src/Main.enso +++ b/test/Table_Tests/src/Main.enso @@ -5,10 +5,10 @@ import Standard.Test import project.In_Memory_Tests #import project.Database.Main as Database_Tests #import project.File_Read_Spec -#import project.Data_Formatter_Spec +import project.Data_Formatter_Spec main = Test.Suite.run_main <| In_Memory_Tests.in_memory_spec #Database_Tests.databases_spec #File_Read_Spec.spec - #Data_Formatter_Spec.spec + Data_Formatter_Spec.spec From 875d02d2d24bfe6b9c8c44e24891ee1b655f330b Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 18 Aug 2022 15:37:46 +0200 Subject: [PATCH 057/110] progress --- .../Table/0.0.0-dev/src/Data/Table.enso | 4 ++-- .../Table/0.0.0-dev/src/IO/File_Format.enso | 6 +++--- .../src/Internal/Delimited_Reader.enso | 19 +++++++++---------- .../src/Internal/Delimited_Writer.enso | 4 ++-- .../Standard/Table/0.0.0-dev/src/Main.enso | 2 +- .../caseexpr/ObjectEqualityBranchNode.java | 1 + test/Table_Tests/src/In_Memory_Tests.enso | 2 +- 7 files changed, 19 insertions(+), 19 deletions(-) diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso index 6a5e91f36a0a..f7ce738f4734 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso @@ -750,7 +750,7 @@ type Table example_columns = Examples.inventory_table.columns columns : Vector - columns self = Vector.Vector_Data self.java_table.getColumns . map Column.Column + columns self = Vector.Vector_Data self.java_table.getColumns . map Column.Column_Data ## Sets the index of this table, using the column with the provided name. @@ -1221,5 +1221,5 @@ Table.from (that : Text) (format:File_Format.Delimited|File_Format.Fixed_Width = Errors.unimplemented "Table.from for fixed-width files is not yet implemented." Text.from (that : Table) (format:File_Format.Delimited|File_Format.Fixed_Width = File_Format.Delimited_Data '\t') = - if format.is_a File_Format.Delimited then Delimited_Writer.write_text that format else + if format.is_a File_Format.Delimited_Data then Delimited_Writer.write_text that format else Errors.unimplemented "Text.from for fixed-width files is not yet implemented." 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 ff6e7c0cffe8..6a7bccc57d95 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 @@ -30,8 +30,8 @@ type Auto output = Ref.new Nothing if ".txt".equals_ignore_case extension then output.put File_Format.Plain_Text if ".log".equals_ignore_case extension then output.put File_Format.Plain_Text - if ".csv".equals_ignore_case extension then output.put (File_Format.Delimited ',') - if ".tsv".equals_ignore_case extension then output.put (File_Format.Delimited '\t') + if ".csv".equals_ignore_case extension then output.put (File_Format.Delimited_Data ',') + if ".tsv".equals_ignore_case extension then output.put (File_Format.Delimited_Data '\t') if ".xlsx".equals_ignore_case extension then output.put File_Format.Excel if ".xlsm".equals_ignore_case extension then output.put File_Format.Excel if ".xls".equals_ignore_case extension then output.put File_Format.Excel @@ -134,7 +134,7 @@ type Delimited Note: This function is internal until such time as Atom cloning with modification is built into Enso. clone : Text->Text->(Boolean|Infer)->Data_Formatter->Boolean->(Text|Nothing)->(Text|Nothing)->Delimited clone self (quote_style=self.quote_style) (headers=self.headers) (value_formatter=self.value_formatter) (keep_invalid_rows=self.keep_invalid_rows) (line_endings=self.line_endings) (comment_character=self.comment_character) = - Delimited self.delimiter self.encoding self.skip_rows self.row_limit quote_style headers value_formatter keep_invalid_rows line_endings comment_character + Delimited_Data self.delimiter self.encoding self.skip_rows self.row_limit quote_style headers value_formatter keep_invalid_rows line_endings comment_character ## Create a clone of this with specified quoting settings. with_quotes : Text->Text->Boolean->Delimited 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 8665a69510ab..1efa6f706595 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 @@ -4,7 +4,7 @@ import Standard.Table import Standard.Base.Data.Statistics import Standard.Base.Error.Common as Errors from Standard.Base.Error.Problem_Behavior import Problem_Behavior, Ignore, Report_Error -from Standard.Table.Errors import Duplicate_Output_Column_Names, Invalid_Output_Column_Names, Invalid_Row, Mismatched_Quote, Parser_Error, Additional_Invalid_Rows +from Standard.Table.Errors import Duplicate_Output_Column_Names_Data, Invalid_Output_Column_Names_Data, Invalid_Row, Mismatched_Quote, Parser_Error, Additional_Invalid_Rows_Data from Standard.Base.Data.Text.Encoding import Encoding, Encoding_Error from Standard.Table.IO.File_Format import Infer from Standard.Table.Data.Data_Formatter import Data_Formatter_Data @@ -105,7 +105,9 @@ prepare_delimited_reader java_reader format max_columns on_problems newline_over row_limit = case format.row_limit of Nothing -> -1 Integer -> format.row_limit - _ -> Error.throw (Illegal_Argument_Error_Data "`row_limit` should be Integer or Nothing.") + _ -> + IO.println format.row_limit + Error.throw (Illegal_Argument_Error_Data "`row_limit` should be Integer or Nothing.") warnings_as_errors = on_problems == Report_Error quote_characters = case format.quote_style of Quote_Style.No_Quotes -> Pair_Data Nothing Nothing @@ -126,11 +128,11 @@ prepare_delimited_reader java_reader format max_columns on_problems newline_over DelimitedReader.new java_reader format.delimiter quote_characters.first quote_characters.second java_headers format.skip_rows row_limit max_columns value_parser cell_type_guesser format.keep_invalid_rows newline format.comment_character warnings_as_errors translate_reader_problem problem = - invalid_row = [InvalidRow, (java_problem-> Invalid_Row java_problem.source_row java_problem.table_index (Vector.Vector java_problem.row))] - additional_invalid_rows = [AdditionalInvalidRows, (java_problem-> Additional_Invalid_Rows java_problem.count)] + invalid_row = [InvalidRow, (java_problem-> Invalid_Row java_problem.source_row java_problem.table_index (Vector.Vector_Data java_problem.row))] + additional_invalid_rows = [AdditionalInvalidRows, (java_problem-> Additional_Invalid_Rows_Data java_problem.count)] mismatched_quote = [MismatchedQuote, (_-> Mismatched_Quote)] - duplicate_names = [DuplicateNames, (java_problem-> Duplicate_Output_Column_Names (Vector.Vector java_problem.duplicatedNames))] - invalid_names = [InvalidNames, (java_problem-> Invalid_Output_Column_Names (Vector.Vector java_problem.invalidNames))] + duplicate_names = [DuplicateNames, (java_problem-> Duplicate_Output_Column_Names_Data (Vector.Vector_Data java_problem.duplicatedNames))] + invalid_names = [InvalidNames, (java_problem-> Invalid_Output_Column_Names_Data (Vector.Vector_Data java_problem.invalidNames))] translations = [invalid_row, additional_invalid_rows, mismatched_quote, duplicate_names, invalid_names] found = translations.find t-> Java.is_instance problem t.first @@ -140,9 +142,6 @@ translate_reader_problem problem = ## PRIVATE An internal type representing columns deduced from an existing file. type Detected_Headers - ## Indicates that the file did not exist or was empty. - Nothing - ## Represents the headers found in the file. Existing_Headers (column_names : Vector Text) @@ -187,7 +186,7 @@ detect_metadata file format = column_count = reader.getColumnCount if column_count == 0 then Nothing else No_Headers column_count - _ -> Existing_Headers (Vector.Vector defined_columns) + _ -> Existing_Headers (Vector.Vector_Data defined_columns) line_separator_from_parser = reader.getEffectiveLineSeparator has_seen_newline = newline_detecting_reader.newlineEncountered ## If the parser has seen a newline, we can trust that it diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Delimited_Writer.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Delimited_Writer.enso index 6653306ab9fc..785d0c218974 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Delimited_Writer.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Delimited_Writer.enso @@ -148,8 +148,8 @@ write_to_writer table format java_writer separator_override=Nothing needs_leadin Quote_Style.With_Quotes always _ _ -> if always then WriteQuoteBehavior.ALWAYS else WriteQuoteBehavior.NECESSARY quote_characters = case format.quote_style of - Quote_Style.No_Quotes -> Pair Nothing Nothing - Quote_Style.With_Quotes _ quote quote_escape -> Pair quote quote_escape + Quote_Style.No_Quotes -> Pair_Data Nothing Nothing + Quote_Style.With_Quotes _ quote quote_escape -> Pair_Data quote quote_escape write_headers = should_write_headers format.headers newline = separator_override.if_nothing <| case format.line_endings of diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso index 08fe9897304a..f7e31cb22fb7 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso @@ -13,7 +13,7 @@ export Standard.Table.Data.Column export Standard.Table.IO.File_Read export Standard.Table.IO.File_Format -from Standard.Table.Data.Table export new, from_rows, join, concat, No_Such_Column_Error, Table +from Standard.Table.Data.Table export new, from_rows, join, concat, No_Such_Column_Error, Table, Table_Data ## ALIAS To Table diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ObjectEqualityBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ObjectEqualityBranchNode.java index 81b3a2bb67b4..2b00a599dbdd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ObjectEqualityBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ObjectEqualityBranchNode.java @@ -2,6 +2,7 @@ import com.oracle.truffle.api.RootCallTarget; import com.oracle.truffle.api.frame.VirtualFrame; +import org.enso.interpreter.runtime.Context; public class ObjectEqualityBranchNode extends BranchNode { private final Object expected; diff --git a/test/Table_Tests/src/In_Memory_Tests.enso b/test/Table_Tests/src/In_Memory_Tests.enso index 2c09e6ae2051..fbeeed211f08 100644 --- a/test/Table_Tests/src/In_Memory_Tests.enso +++ b/test/Table_Tests/src/In_Memory_Tests.enso @@ -15,7 +15,7 @@ import project.Csv_Spec in_memory_spec = Column_Spec.spec - #Csv_Spec.spec + Csv_Spec.spec #Delimited_Read_Spec.spec #Delimited_Write_Spec.spec #Excel_Spec.spec From 4889661c093ee3856ed72430c5183128cac6eae9 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 23 Aug 2022 11:47:55 +0200 Subject: [PATCH 058/110] keep going --- .../lib/Standard/Base/0.0.0-dev/src/Meta.enso | 51 +++--- .../Standard/Table/0.0.0-dev/src/Errors.enso | 2 +- .../src/Internal/Delimited_Reader.enso | 4 +- .../src/Internal/Delimited_Writer.enso | 12 +- .../src/Internal/Unique_Name_Strategy.enso | 4 +- .../builtin/meta/GetAtomConstructorNode.java | 18 +- .../expression/builtin/meta/IsAtomNode.java | 4 +- test/Table_Tests/src/Delimited_Read_Spec.enso | 160 +++++++++--------- .../Table_Tests/src/Delimited_Write_Spec.enso | 78 ++++----- test/Table_Tests/src/In_Memory_Tests.enso | 8 +- test/Table_Tests/src/Main.enso | 4 +- 11 files changed, 181 insertions(+), 164 deletions(-) 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 b6a48c267f9c..6b2c6273a5c1 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 @@ -299,31 +299,32 @@ Base.Error.is_an self typ = typ==Any || typ==Base.Error - value: The value to check for being an instance of `typ`. - typ: The type to check `self` against. is_a : Any -> Any -> Boolean -is_a value typ = if typ == Any then True else - if is_error value then typ == Base.Error else - case value of - Array -> typ == Array - Boolean -> if typ == Boolean then True else value == typ - Text -> typ == Text - Number -> if typ == Number then True else case value of - Integer -> typ == Integer - Decimal -> typ == Decimal - Base.Polyglot -> - typ==Base.Polyglot || java_instance_check value typ - _ -> - meta_val = meta value - case meta_val of - Atom_Data _ -> if is_atom typ then typ == value else - meta_val.constructor == typ - Constructor_Data _ -> - meta_typ = meta typ - case meta_typ of - Atom_Data _ -> meta_val == meta_typ.constructor - Constructor_Data _ -> meta_val == meta_typ - _ -> False - Error_Data _ -> typ == Error - Unresolved_Symbol_Data _ -> typ == Unresolved_Symbol - _ -> False +is_a value typ = if is_same_object value typ then True else + if typ == Any then True else + if is_error value then typ == Base.Error else + case value of + Array -> typ == Array + Boolean -> if typ == Boolean then True else value == typ + Text -> typ == Text + Number -> if typ == Number then True else case value of + Integer -> typ == Integer + Decimal -> typ == Decimal + Base.Polyglot -> + typ==Base.Polyglot || java_instance_check value typ + _ -> + meta_val = meta value + case meta_val of + Atom_Data _ -> if is_atom typ then typ == value else + meta_val.constructor == typ + Constructor_Data _ -> + meta_typ = meta typ + case meta_typ of + Atom_Data _ -> meta_val == meta_typ.constructor + Constructor_Data _ -> meta_val == meta_typ + _ -> False + Error_Data _ -> typ == Error + Unresolved_Symbol_Data _ -> typ == Unresolved_Symbol + _ -> False ## PRIVATE java_instance_check value typ = diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso index c8a27837a231..7fd72721b7b1 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso @@ -226,7 +226,7 @@ Column_Count_Mismatch.to_display_text self = Column_Count_Mismatch.handle_java_exception self = throw_column_count_mismatch caught_panic = cause = caught_panic.payload.cause - Error.throw (Column_Count_Mismatch cause.getExpected cause.getActual) + Error.throw (Column_Count_Mismatch_Data cause.getExpected cause.getActual) Panic.catch ColumnCountMismatchException handler=throw_column_count_mismatch ## Indicates that the existing table has a different set of column names to the 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 1efa6f706595..2176a7714301 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 @@ -4,7 +4,7 @@ import Standard.Table import Standard.Base.Data.Statistics import Standard.Base.Error.Common as Errors from Standard.Base.Error.Problem_Behavior import Problem_Behavior, Ignore, Report_Error -from Standard.Table.Errors import Duplicate_Output_Column_Names_Data, Invalid_Output_Column_Names_Data, Invalid_Row, Mismatched_Quote, Parser_Error, Additional_Invalid_Rows_Data +from Standard.Table.Errors import Duplicate_Output_Column_Names_Data, Invalid_Output_Column_Names_Data, Invalid_Row_Data, Mismatched_Quote, Parser_Error, Additional_Invalid_Rows_Data from Standard.Base.Data.Text.Encoding import Encoding, Encoding_Error from Standard.Table.IO.File_Format import Infer from Standard.Table.Data.Data_Formatter import Data_Formatter_Data @@ -128,7 +128,7 @@ prepare_delimited_reader java_reader format max_columns on_problems newline_over DelimitedReader.new java_reader format.delimiter quote_characters.first quote_characters.second java_headers format.skip_rows row_limit max_columns value_parser cell_type_guesser format.keep_invalid_rows newline format.comment_character warnings_as_errors translate_reader_problem problem = - invalid_row = [InvalidRow, (java_problem-> Invalid_Row java_problem.source_row java_problem.table_index (Vector.Vector_Data java_problem.row))] + invalid_row = [InvalidRow, (java_problem-> Invalid_Row_Data java_problem.source_row java_problem.table_index (Vector.Vector_Data java_problem.row))] additional_invalid_rows = [AdditionalInvalidRows, (java_problem-> Additional_Invalid_Rows_Data java_problem.count)] mismatched_quote = [MismatchedQuote, (_-> Mismatched_Quote)] duplicate_names = [DuplicateNames, (java_problem-> Duplicate_Output_Column_Names_Data (Vector.Vector_Data java_problem.duplicatedNames))] diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Delimited_Writer.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Delimited_Writer.enso index 785d0c218974..926abbdecbb2 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Delimited_Writer.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Delimited_Writer.enso @@ -51,7 +51,7 @@ write_file table format file on_existing_file match_columns on_problems = If the file does not exist or is empty, it acts like a regular overwrite. append_to_file : Table -> File_Format.Delimited -> File -> Match_Columns -> Problem_Behavior -> Any append_to_file table format file match_columns on_problems = - Column_Name_Mismatch.handle_java_exception <| Column_Count_Mismatch.handle_java_exception <| Panic.recover Illegal_Argument_Error <| + Column_Name_Mismatch.handle_java_exception <| Column_Count_Mismatch.handle_java_exception <| Panic.recover Illegal_Argument_Error_Data <| inferring_format = format.with_line_endings Infer metadata = Delimited_Reader.detect_metadata file inferring_format preexisting_headers = metadata.headers @@ -61,7 +61,7 @@ append_to_file table format file match_columns on_problems = selected_separator = other_ending_style.to_text existing_separator = metadata.line_separator if existing_separator.is_nothing.not && (selected_separator != existing_separator) then - Panic.throw <| Illegal_Argument_Error <| + Panic.throw <| Illegal_Argument_Error_Data <| # Ensure that these are properly escaped once `to_text` meaning is changed. "The explicitly provided line endings (" + selected_separator.to_text + ") do not match the line endings in the file (" + existing_separator.to_text + ")." other_ending_style.to_text @@ -76,10 +76,10 @@ append_to_file table format file match_columns on_problems = ColumnMapper.mapColumnsByPosition table.java_table column_count No_Headers column_count -> case match_columns of Match_Columns.By_Name -> - Error.throw (Illegal_Argument_Error "Cannot append by name when headers are not present in the existing data.") + Error.throw (Illegal_Argument_Error_Data "Cannot append by name when headers are not present in the existing data.") Match_Columns.By_Position -> ColumnMapper.mapColumnsByPosition table.java_table column_count - reordered_table = Table.Table reordered_java_table + reordered_table = Table.Table_Data reordered_java_table writing_new_file = preexisting_headers == Nothing amended_format = case writing_new_file && (should_write_headers format.headers) of True -> format.with_headers @@ -135,11 +135,11 @@ write_to_stream table format stream on_problems related_file=Nothing separator_o instead of the one from `format`. write_to_writer : Table -> File_Format.Delimited -> Writer -> Text | Nothing -> Boolean -> Any write_to_writer table format java_writer separator_override=Nothing needs_leading_newline=False = - column_formatters = Panic.recover Illegal_Argument_Error <| case format.value_formatter of + column_formatters = Panic.recover Illegal_Argument_Error_Data <| case format.value_formatter of Nothing -> table.columns.map column-> case column.storage_type of Storage.Text -> TextFormatter.new _ -> - Panic.throw (Illegal_Argument_Error "If the expected file format does not specify a valid `Data_Formatter`, only Text columns are allowed.") + Panic.throw (Illegal_Argument_Error_Data "If the expected file format does not specify a valid `Data_Formatter`, only Text columns are allowed.") value_formatter -> table.columns.map column-> storage_type = column.storage_type value_formatter.make_formatter_for_column_type storage_type 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 6bcee4d2904e..af39c92c559f 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 @@ -29,12 +29,12 @@ type Unique_Name_Strategy ## Vector of any duplicates renamed renames : Vector - renames self = Vector.Vector self.deduplicator.getDuplicatedNames + renames self = Vector.Vector_Data self.deduplicator.getDuplicatedNames ## Vector of any invalid names invalid_names : Vector - invalid_names self = Vector.Vector self.deduplicator.getInvalidNames + invalid_names self = Vector.Vector_Data self.deduplicator.getInvalidNames ## Takes a value and converts to a valid (but not necessarily unique) name diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/GetAtomConstructorNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/GetAtomConstructorNode.java index 0f97c9c7b787..a9a1ea16593d 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/GetAtomConstructorNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/GetAtomConstructorNode.java @@ -1,16 +1,30 @@ package org.enso.interpreter.node.expression.builtin.meta; +import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.dsl.BuiltinMethod; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.atom.AtomConstructor; +import org.enso.interpreter.runtime.data.Type; @BuiltinMethod( type = "Meta", name = "get_atom_constructor", description = "Gets the constructor of an atom.") -public class GetAtomConstructorNode extends Node { - AtomConstructor execute(Atom atom) { +public abstract class GetAtomConstructorNode extends Node { + abstract Object execute(Object atom); + + static GetAtomConstructorNode build() { + return GetAtomConstructorNodeGen.create(); + } + + @Specialization + Object doAtom(Atom atom) { return atom.getConstructor(); } + + @Specialization + Object doType(Type type) { + return type; + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/IsAtomNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/IsAtomNode.java index ca5fb0fd99de..e9a5c7c1a9b8 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/IsAtomNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/meta/IsAtomNode.java @@ -3,11 +3,13 @@ import com.oracle.truffle.api.nodes.Node; import org.enso.interpreter.dsl.AcceptsError; import org.enso.interpreter.dsl.BuiltinMethod; +import org.enso.interpreter.runtime.callable.atom.Atom; +import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.type.TypesGen; @BuiltinMethod(type = "Meta", name = "is_atom", description = "Checks if the argument is an atom") public class IsAtomNode extends Node { boolean execute(@AcceptsError Object value) { - return TypesGen.isAtom(value); + return value instanceof Atom || value instanceof Type; } } diff --git a/test/Table_Tests/src/Delimited_Read_Spec.enso b/test/Table_Tests/src/Delimited_Read_Spec.enso index 5aed1c1b6038..7620c5345a65 100644 --- a/test/Table_Tests/src/Delimited_Read_Spec.enso +++ b/test/Table_Tests/src/Delimited_Read_Spec.enso @@ -4,9 +4,9 @@ import Standard.Table import Standard.Table.Data.Column from Standard.Table.Errors import all import Standard.Table.IO.File_Read -from Standard.Table.IO.File_Format import Delimited +from Standard.Table.IO.File_Format import Delimited_Data import Standard.Table.IO.File_Format -from Standard.Table.Data.Data_Formatter as Data_Formatter_Module import Data_Formatter +from Standard.Table.Data.Data_Formatter import Data_Formatter_Data import Standard.Table.IO.Quote_Style import Standard.Base.Data.Text.Line_Ending_Style @@ -22,7 +22,7 @@ spec = c_2 = ["b", ['2', Nothing, '8', '11']] c_3 = ["c", [Nothing, '6', '9', '12']] expected_table = Table.new [c_1, c_2, c_3] - simple_empty = File.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=True value_formatter=Nothing) + simple_empty = File.read (enso_project.data / "simple_empty.csv") (Delimited_Data "," headers=True value_formatter=Nothing) simple_empty.should_equal expected_table Test.specify "should load a simple table without headers" <| @@ -30,11 +30,11 @@ spec = c_2 = ["Column_2", ['b', '2', Nothing, '8', '11']] c_3 = ["Column_3", ['c', Nothing, '6', '9', '12']] expected_table = Table.new [c_1, c_2, c_3] - simple_empty = File.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=False value_formatter=Nothing) + simple_empty = File.read (enso_project.data / "simple_empty.csv") (Delimited_Data "," headers=False value_formatter=Nothing) simple_empty.should_equal expected_table Test.specify "should work in presence of missing headers" <| - action on_problems = File.read (enso_project.data / "missing_header.csv") (Delimited "," headers=True value_formatter=Nothing) on_problems + action on_problems = File.read (enso_project.data / "missing_header.csv") (Delimited_Data "," headers=True value_formatter=Nothing) on_problems tester table = table.columns.map .name . should_equal ["a", "Column_1", "c", "Column_2", "d"] table.at "a" . to_vector . should_equal ["1"] @@ -42,65 +42,65 @@ spec = table.at "c" . to_vector . should_equal ["3"] table.at "Column_2" . to_vector . should_equal ["4"] table.at "d" . to_vector . should_equal ["5"] - problems = [Invalid_Output_Column_Names [Nothing, Nothing]] + problems = [Invalid_Output_Column_Names_Data [Nothing, Nothing]] Problems.test_problem_handling action problems tester Test.specify "should infer headers based on the first two rows" <| - t1 = File.read (enso_project.data / "data_small.csv") (Delimited "," headers=File_Format.Infer) + t1 = File.read (enso_project.data / "data_small.csv") (Delimited_Data "," headers=File_Format.Infer) t1.columns.map .name . should_equal ["Code", "Index", "Flag", "Value", "ValueWithNothing", "TextWithNothing", "Hexadecimal", "Leading0s", "QuotedNumbers", "Mixed Types"] - t2 = File.read (enso_project.data / "all_text.csv") (Delimited "," headers=File_Format.Infer) + t2 = File.read (enso_project.data / "all_text.csv") (Delimited_Data "," headers=File_Format.Infer) t2.columns.map .name . should_equal ["Column_1", "Column_2"] t2.at "Column_1" . to_vector . should_equal ["a", "c", "e", "g"] t2.at "Column_2" . to_vector . should_equal ["b", "d", "f", "h"] - t3 = File.read (enso_project.data / "two_rows1.csv") (Delimited "," headers=File_Format.Infer) + t3 = File.read (enso_project.data / "two_rows1.csv") (Delimited_Data "," headers=File_Format.Infer) t3.columns.map .name . should_equal ["a", "b", "c"] t3.at "a" . to_vector . should_equal ["x"] t3.at "b" . to_vector . should_equal [Nothing] t3.at "c" . to_vector . should_equal [Nothing] - t4 = File.read (enso_project.data / "two_rows2.csv") (Delimited "," headers=File_Format.Infer) + t4 = File.read (enso_project.data / "two_rows2.csv") (Delimited_Data "," headers=File_Format.Infer) t4.columns.map .name . should_equal ["Column_1", "Column_2", "Column_3"] t4.at "Column_1" . to_vector . should_equal ["a", "d"] t4.at "Column_2" . to_vector . should_equal ["b", "e"] t4.at "Column_3" . to_vector . should_equal ["c", "f"] - t5 = File.read (enso_project.data / "numbers_in_header.csv") (Delimited "," headers=File_Format.Infer) + t5 = File.read (enso_project.data / "numbers_in_header.csv") (Delimited_Data "," headers=File_Format.Infer) t5.columns.map .name . should_equal ["Column_1", "Column_2", "Column_3"] t5.at "Column_1" . to_vector . should_equal ["a", "1"] t5.at "Column_2" . to_vector . should_equal ["b", "2"] t5.at "Column_3" . to_vector . should_equal [0, 3] - t6 = File.read (enso_project.data / "quoted_numbers_in_header.csv") (Delimited "," headers=File_Format.Infer) + t6 = File.read (enso_project.data / "quoted_numbers_in_header.csv") (Delimited_Data "," headers=File_Format.Infer) t6.columns.map .name . should_equal ["1", "x"] t6.at "1" . to_vector . should_equal ["y"] t6.at "x" . to_vector . should_equal [2] Test.specify "should not use the first row as headers if it is the only row, unless specifically asked to" <| - t1 = File.read (enso_project.data / "one_row.csv") (Delimited "," headers=File_Format.Infer) + t1 = File.read (enso_project.data / "one_row.csv") (Delimited_Data "," headers=File_Format.Infer) t1.columns.map .name . should_equal ["Column_1", "Column_2", "Column_3"] t1.at "Column_1" . to_vector . should_equal ["x"] t1.at "Column_2" . to_vector . should_equal ["y"] t1.at "Column_3" . to_vector . should_equal ["z"] - t2 = File.read (enso_project.data / "one_row.csv") (Delimited "," headers=True) + t2 = File.read (enso_project.data / "one_row.csv") (Delimited_Data "," headers=True) t2.columns.map .name . should_equal ["x", "y", "z"] t2.row_count . should_equal 0 t2.at "x" . to_vector . should_equal [] Test.specify "should be able to load even an empty file" <| - table = File.read (enso_project.data / "empty.txt") (Delimited "," headers=True value_formatter=Nothing) + table = File.read (enso_project.data / "empty.txt") (Delimited_Data "," headers=True value_formatter=Nothing) table.columns.map .name . should_equal [] table.row_count . should_equal 0 Test.specify "should correctly handle file opening issues" <| nonexistent_file = enso_project.data / "a_filename_that_does_not_exist.foobar" - r1 = File.read nonexistent_file (Delimited "," headers=True value_formatter=Nothing) + r1 = File.read nonexistent_file (Delimited_Data "," headers=True value_formatter=Nothing) r1.should_fail_with File.File_Not_Found directory = enso_project.data - r2 = File.read directory (Delimited "," headers=True value_formatter=Nothing) Problem_Behavior.Report_Error + r2 = File.read directory (Delimited_Data "," headers=True value_formatter=Nothing) Problem_Behavior.Report_Error r2.should_fail_with File.IO_Error Test.specify "should work with all kinds of line endings" <| @@ -111,7 +111,7 @@ spec = text.write (path name) test_file name = - table = File.read (path name) (Delimited "," headers=True value_formatter=Nothing) Problem_Behavior.Report_Error + table = File.read (path name) (Delimited_Data "," headers=True value_formatter=Nothing) Problem_Behavior.Report_Error table.columns.map .name . should_equal ['a', 'b', 'c'] table.at 'a' . to_vector . should_equal ['d', '1'] table.at 'b' . to_vector . should_equal ['e', '2'] @@ -126,7 +126,7 @@ spec = # Currently mixed line endings are not supported. 'a,b,c\nd,e,f\r1,2,3'.write (path 'mixed.csv') - File.read (path 'mixed.csv') (Delimited "," headers=True value_formatter=Nothing) Problem_Behavior.Report_Error . should_fail_with Invalid_Row + File.read (path 'mixed.csv') (Delimited_Data "," headers=True value_formatter=Nothing) Problem_Behavior.Report_Error . should_fail_with Invalid_Row_Data ['crlf.csv', 'lf.csv', 'cr.csv', 'mixed.csv'].each (path >> .delete) @@ -136,7 +136,7 @@ spec = text = lines.join '\n' text.write file - format = Delimited ',' headers=False value_formatter=(Data_Formatter trim_values=False) + format = Delimited_Data ',' headers=False value_formatter=(Data_Formatter_Data trim_values=False) reference_table = Table.new [["Column_1", ["a", "d", "1"]], ["Column_2", ["b", "e", "2"]], ["Column_3", ["c", "f", "3"]]] collapsed_table = Table.new <| @@ -158,14 +158,14 @@ spec = file_2.delete Test.specify "should work with Windows-1252 encoding" <| - table = File.read (enso_project.data / "windows.csv") (Delimited "," headers=True encoding=Encoding.windows_1252) Problem_Behavior.Report_Error + table = File.read (enso_project.data / "windows.csv") (Delimited_Data "," headers=True encoding=Encoding.windows_1252) Problem_Behavior.Report_Error table.columns.map .name . should_equal ['a', 'b', 'c'] table.at 'a' . to_vector . should_equal ['$¢'] table.at 'b' . to_vector . should_equal ['¤'] table.at 'c' . to_vector . should_equal ['¥'] Test.specify "should work with UTF-16 encoding" <| - table = File.read (enso_project.data / "utf16.csv") (Delimited "," headers=True encoding=Encoding.utf_16_be) Problem_Behavior.Report_Error + table = File.read (enso_project.data / "utf16.csv") (Delimited_Data "," headers=True encoding=Encoding.utf_16_be) Problem_Behavior.Report_Error table.columns.map .name . should_equal ['ą', '🚀b', 'ć😎'] table.at 'ą' . to_vector . should_equal ['ą'] table.at '🚀b' . to_vector . should_equal ['✨🚀🚧😍😃😍😎😙😉☺'] @@ -176,18 +176,18 @@ spec = utf8_bytes = [97, 44, 98, 44, 99, 10, -60, -123, 44, -17, -65, -65, 44, -61, 40, -61, 40, 10] utf8_bytes.write_bytes utf8_file action_1 on_problems = - utf8_file.read (Delimited "," headers=True) on_problems + utf8_file.read (Delimited_Data "," headers=True) on_problems tester_1 table = table.columns.map .name . should_equal ['a', 'b', 'c'] table.at 'a' . to_vector . should_equal ['ą'] table.at 'b' . to_vector . should_equal ['\uFFFF'] table.at 'c' . to_vector . should_equal ['\uFFFD(\uFFFD('] - problems_1 = [Encoding_Error "Encoding issues at bytes 13, 15."] + problems_1 = [Encoding_Error_Data "Encoding issues at bytes 13, 15."] Problems.test_problem_handling action_1 problems_1 tester_1 utf8_file.delete action_2 on_problems = - (enso_project.data / "utf16_invalid.csv").read (Delimited "," headers=True encoding=Encoding.utf_16_be) on_problems + (enso_project.data / "utf16_invalid.csv").read (Delimited_Data "," headers=True encoding=Encoding.utf_16_be) on_problems tester_2 table = table.columns.map .name . should_equal ['a', 'b', 'c'] # This column does not raise a problem - the '\uFFFD' is simply present in the input file. @@ -195,40 +195,40 @@ spec = table.at 'b' . to_vector . should_equal ['\uFFFF'] # However, this column will raise a problem as the '\uFFFD' comes from replacing an invalid codepoint. table.at 'c' . to_vector . should_equal ['\uFFFD'] - problems_2 = [Encoding_Error "Encoding issues at byte 22."] + problems_2 = [Encoding_Error_Data "Encoding issues at byte 22."] Problems.test_problem_handling action_2 problems_2 tester_2 Test.specify "should handle duplicated columns" <| - action on_problems = File.read (enso_project.data / "duplicated_columns.csv") (Delimited "," headers=True value_formatter=Nothing) on_problems + action on_problems = File.read (enso_project.data / "duplicated_columns.csv") (Delimited_Data "," headers=True value_formatter=Nothing) on_problems tester table = table.columns.map .name . should_equal ['a', 'b', 'c', 'a_1'] table.at 'a' . to_vector . should_equal ['1'] table.at 'a_1' . to_vector . should_equal ['4'] - problems = [Duplicate_Output_Column_Names ['a']] + problems = [Duplicate_Output_Column_Names_Data ['a']] Problems.test_problem_handling action problems tester Test.specify "should handle quotes" <| - t1 = File.read (enso_project.data / "double_quoted.csv") (Delimited "," headers=True value_formatter=Nothing) + t1 = File.read (enso_project.data / "double_quoted.csv") (Delimited_Data "," headers=True value_formatter=Nothing) t1.at 'a' . to_vector . should_equal ['a, x', '"a'] t1.at 'c' . to_vector . should_equal ['3', '"'] - t2 = File.read (enso_project.data / "escape_quoted.csv") (Delimited "," headers=True value_formatter=Nothing . with_quotes quote_escape="\") + t2 = File.read (enso_project.data / "escape_quoted.csv") (Delimited_Data "," headers=True value_formatter=Nothing . with_quotes quote_escape="\") t2.at 'a' . to_vector . should_equal ['a"b', 'a\\\"z'] - t3 = File.read (enso_project.data / "no_quoting.csv") (Delimited "," headers=True value_formatter=Nothing . without_quotes) + t3 = File.read (enso_project.data / "no_quoting.csv") (Delimited_Data "," headers=True value_formatter=Nothing . without_quotes) t3.at 'a' . to_vector . should_equal ['"y'] t3.at 'b' . to_vector . should_equal ['z"'] t3.at 'c' . to_vector . should_equal ['a'] Test.specify "should support rows spanning multiple lines if quoted" <| - t1 = File.read (enso_project.data / "multiline_quoted.csv") (Delimited "," headers=True value_formatter=Nothing) + t1 = File.read (enso_project.data / "multiline_quoted.csv") (Delimited_Data "," headers=True value_formatter=Nothing) t1.at 'a' . to_vector . should_equal ['1', '4'] t1.at 'b' . to_vector . should_equal ['start\n\ncontinue', '5'] t1.at 'c' . to_vector . should_equal ['3', '6'] Test.specify "should behave correctly in presence of a mismatched quote" <| action_1 on_problems = - File.read (enso_project.data / "mismatched_quote.csv") (Delimited "," headers=True value_formatter=Nothing) on_problems + File.read (enso_project.data / "mismatched_quote.csv") (Delimited_Data "," headers=True value_formatter=Nothing) on_problems tester_1 table = table.columns.map .name . should_equal ['a', 'b', 'c'] @@ -239,26 +239,26 @@ spec = Problems.test_problem_handling action_1 problems_1 tester_1 action_2 on_problems = - File.read (enso_project.data / "mismatched_quote2.csv") (Delimited "," headers=True value_formatter=Nothing) on_problems + File.read (enso_project.data / "mismatched_quote2.csv") (Delimited_Data "," headers=True value_formatter=Nothing) on_problems tester_2 table = table.columns.map .name . should_equal ['a', 'b', 'c'] table.at 'a' . to_vector . should_equal ['1', 'abc'] table.at 'b' . to_vector . should_equal ['2', '"def,g h i\n7,8,9\n'] table.at 'c' . to_vector . should_equal ['3', Nothing] - problems_2 = [Invalid_Row 3 1 ['abc', '"def,g h i\n7,8,9\n'], Mismatched_Quote] + problems_2 = [Invalid_Row_Data 3 1 ['abc', '"def,g h i\n7,8,9\n'], Mismatched_Quote] Problems.test_problem_handling action_2 problems_2 tester_2 Test.specify "should handle too long and too short rows" <| action keep_invalid_rows on_problems = - File.read (enso_project.data / "varying_rows.csv") (Delimited "," headers=True keep_invalid_rows=keep_invalid_rows value_formatter=Nothing) on_problems + File.read (enso_project.data / "varying_rows.csv") (Delimited_Data "," headers=True keep_invalid_rows=keep_invalid_rows value_formatter=Nothing) on_problems tester_kept table = table.columns.map .name . should_equal ['a', 'b', 'c'] table.at 'a' . to_vector . should_equal ['1', '1', '1', Nothing, '1', '1'] table.at 'b' . to_vector . should_equal ['2', '2', '2', Nothing, Nothing, '2'] table.at 'c' . to_vector . should_equal ['3', '3', Nothing, Nothing, Nothing, '3'] - problems_kept = [Invalid_Row 2 0 ['1', '2', '3', '4'], Invalid_Row 4 2 ['1', '2'], Invalid_Row 5 3 [Nothing], Invalid_Row 6 4 ['1'], Invalid_Row 7 5 ['1', '2', '3', '4', '5', '6', '7', '8']] + problems_kept = [Invalid_Row_Data 2 0 ['1', '2', '3', '4'], Invalid_Row_Data 4 2 ['1', '2'], Invalid_Row_Data 5 3 [Nothing], Invalid_Row_Data 6 4 ['1'], Invalid_Row_Data 7 5 ['1', '2', '3', '4', '5', '6', '7', '8']] Problems.test_problem_handling (action keep_invalid_rows=True) problems_kept tester_kept tester_dropped table = @@ -266,61 +266,61 @@ spec = table.at 'a' . to_vector . should_equal ['1'] table.at 'b' . to_vector . should_equal ['2'] table.at 'c' . to_vector . should_equal ['3'] - problems_dropped = [Invalid_Row 2 Nothing ['1', '2', '3', '4'], Invalid_Row 4 Nothing ['1', '2'], Invalid_Row 5 Nothing [Nothing], Invalid_Row 6 Nothing ['1'], Invalid_Row 7 Nothing ['1', '2', '3', '4', '5', '6', '7', '8']] + problems_dropped = [Invalid_Row_Data 2 Nothing ['1', '2', '3', '4'], Invalid_Row_Data 4 Nothing ['1', '2'], Invalid_Row_Data 5 Nothing [Nothing], Invalid_Row_Data 6 Nothing ['1'], Invalid_Row_Data 7 Nothing ['1', '2', '3', '4', '5', '6', '7', '8']] Problems.test_problem_handling (action keep_invalid_rows=False) problems_dropped tester_dropped Test.specify "should aggregate invalid rows over some limit" <| action on_problems = - File.read (enso_project.data / "many_invalid_rows.csv") (Delimited "," headers=True keep_invalid_rows=False value_formatter=Nothing) on_problems + File.read (enso_project.data / "many_invalid_rows.csv") (Delimited_Data "," headers=True keep_invalid_rows=False value_formatter=Nothing) on_problems tester table = table.columns.map .name . should_equal ['a', 'b', 'c'] table.at 'a' . to_vector . should_equal ['0', '5'] table.at 'b' . to_vector . should_equal ['x', 'u'] table.at 'c' . to_vector . should_equal ['y', 'v'] - problems = [Invalid_Row 3 Nothing ['1'], Invalid_Row 4 Nothing ['2'], Invalid_Row 5 Nothing ['3'], Invalid_Row 6 Nothing ['4'], Invalid_Row 8 Nothing ['6'], Invalid_Row 9 Nothing ['7'], Invalid_Row 10 Nothing ['8'], Invalid_Row 11 Nothing ['9'], Invalid_Row 12 Nothing ['10'], Invalid_Row 13 Nothing ['11'], Additional_Invalid_Rows 3] + problems = [Invalid_Row_Data 3 Nothing ['1'], Invalid_Row_Data 4 Nothing ['2'], Invalid_Row_Data 5 Nothing ['3'], Invalid_Row_Data 6 Nothing ['4'], Invalid_Row_Data 8 Nothing ['6'], Invalid_Row_Data 9 Nothing ['7'], Invalid_Row_Data 10 Nothing ['8'], Invalid_Row_Data 11 Nothing ['9'], Invalid_Row_Data 12 Nothing ['10'], Invalid_Row_Data 13 Nothing ['11'], Additional_Invalid_Rows_Data 3] Problems.test_problem_handling action problems tester Test.specify "should allow to skip rows" <| - t1 = File.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=False skip_rows=3 value_formatter=Nothing) + t1 = File.read (enso_project.data / "simple_empty.csv") (Delimited_Data "," headers=False skip_rows=3 value_formatter=Nothing) t1.at "Column_1" . to_vector . should_equal ['7', '10'] - t2 = File.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=True skip_rows=3 value_formatter=Nothing) + t2 = File.read (enso_project.data / "simple_empty.csv") (Delimited_Data "," headers=True skip_rows=3 value_formatter=Nothing) t2.columns.map .name . should_equal ['7', '8', '9'] t2.at "7" . to_vector . should_equal ['10'] Test.specify "should allow to set a limit of rows to read" <| - t1 = File.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=False row_limit=2 value_formatter=Nothing) + t1 = File.read (enso_project.data / "simple_empty.csv") (Delimited_Data "," headers=False row_limit=2 value_formatter=Nothing) t1.at "Column_1" . to_vector . should_equal ['a', '1'] - t2 = File.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=True row_limit=2 value_formatter=Nothing) + t2 = File.read (enso_project.data / "simple_empty.csv") (Delimited_Data "," headers=True row_limit=2 value_formatter=Nothing) t2.at "a" . to_vector . should_equal ['1', '4'] - t3 = File.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=False skip_rows=3 row_limit=1 value_formatter=Nothing) + t3 = File.read (enso_project.data / "simple_empty.csv") (Delimited_Data "," headers=False skip_rows=3 row_limit=1 value_formatter=Nothing) t3.at "Column_1" . to_vector . should_equal ['7'] - t4 = File.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=False row_limit=0 value_formatter=Nothing) + t4 = File.read (enso_project.data / "simple_empty.csv") (Delimited_Data "," headers=False row_limit=0 value_formatter=Nothing) t4.columns.map .name . should_equal ['Column_1', 'Column_2', 'Column_3'] t4.row_count . should_equal 0 - t5 = File.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=True row_limit=0 value_formatter=Nothing) + t5 = File.read (enso_project.data / "simple_empty.csv") (Delimited_Data "," headers=True row_limit=0 value_formatter=Nothing) t5.columns.map .name . should_equal ['a', 'b', 'c'] t5.at 'a' . to_vector . should_equal [] t5.row_count . should_equal 0 - t6 = File.read (enso_project.data / "simple_empty.csv") (Delimited "," headers=False skip_rows=3 row_limit=1000 value_formatter=Nothing) + t6 = File.read (enso_project.data / "simple_empty.csv") (Delimited_Data "," headers=False skip_rows=3 row_limit=1000 value_formatter=Nothing) t6.at "Column_1" . to_vector . should_equal ['7', '10'] Test.specify "should check arguments" <| path = (enso_project.data / "simple_empty.csv") pb = Problem_Behavior.Report_Error - path.read (Delimited "," headers=False . with_quotes quote='abc') pb . should_fail_with Illegal_Argument_Error - path.read (Delimited "," headers=False . with_quotes quote='🚧') pb . should_fail_with Illegal_Argument_Error - path.read (Delimited "," headers=False . with_quotes quote_escape='//') pb . should_fail_with Illegal_Argument_Error - path.read (Delimited 'a\u{301}' headers=False) pb . should_fail_with Illegal_Argument_Error + path.read (Delimited_Data "," headers=False . with_quotes quote='abc') pb . should_fail_with Illegal_Argument_Error_Data + path.read (Delimited_Data "," headers=False . with_quotes quote='🚧') pb . should_fail_with Illegal_Argument_Error_Data + path.read (Delimited_Data "," headers=False . with_quotes quote_escape='//') pb . should_fail_with Illegal_Argument_Error_Data + path.read (Delimited_Data 'a\u{301}' headers=False) pb . should_fail_with Illegal_Argument_Error_Data Test.specify "should correctly guess column types" <| - t = (enso_project.data / "data_small.csv") . read (Delimited "," headers=True) + t = (enso_project.data / "data_small.csv") . read (Delimited_Data "," headers=True) t.at "Code" . to_vector . should_equal ["gxl", "wca", "nfw", "der"] t.at "Index" . to_vector . should_equal [7, 0, 1, 7] t.at "Flag" . to_vector . should_equal [True, False, True, True] @@ -332,7 +332,7 @@ spec = t.at "QuotedNumbers" . to_vector . should_equal ["1", "2", Nothing, "34"] t.at "Mixed Types" . to_vector . should_equal ["33", Nothing, "45", "True"] - t2 = (enso_project.data / "data_small.csv") . read (Delimited "," headers=True value_formatter=(Data_Formatter allow_leading_zeros=True)) + t2 = (enso_project.data / "data_small.csv") . read (Delimited_Data "," headers=True value_formatter=(Data_Formatter_Data allow_leading_zeros=True)) t2.at "Leading0s" . to_vector . should_equal [1, 2, 123, Nothing] Test.specify "should be able to detect types automatically" <| @@ -351,7 +351,7 @@ spec = a,b,c 1,2,3 4,5,6 - t1 = Table.Table.from text1 (format = Delimited ",") + t1 = Table.Table.from text1 (format = Delimited_Data ",") t1.columns.map .name . should_equal ["a", "b", "c"] t1.at "a" . to_vector . should_equal [1, 4] t1.at "b" . to_vector . should_equal [2, 5] @@ -372,32 +372,32 @@ spec = table_hash = Table.new [["a", [";1", "5"]], ["42", [2, 6]], ["c # comment??", ["3", "7;comment?"]]] table_semicolon = Table.new [["#", ["a", "5"]], ["x", [42, 6]], ["y", ["c # comment??", "7;comment?"]]] - File.read (enso_project.data / "comments.csv") (Delimited ',' . with_comments . with_headers) . should_equal table_hash - File.read (enso_project.data / "comments.csv") (Delimited ',' . with_comments ';' . with_headers) . should_equal table_semicolon + File.read (enso_project.data / "comments.csv") (Delimited_Data ',' . with_comments . with_headers) . should_equal table_hash + File.read (enso_project.data / "comments.csv") (Delimited_Data ',' . with_comments ';' . with_headers) . should_equal table_semicolon Test.specify "should allow to build the Delimited configuration using builders" <| - Delimited "," . clone . should_equal (Delimited ",") - Delimited "," encoding=Encoding.ascii skip_rows=123 row_limit=100 headers=False value_formatter=Nothing . clone . should_equal (Delimited "," headers=False value_formatter=Nothing skip_rows=123 row_limit=100 encoding=Encoding.ascii) - Delimited "," . clone quote_style=Quote_Style.No_Quotes headers=False value_formatter=Nothing . should_equal (Delimited "," headers=False value_formatter=Nothing quote_style=Quote_Style.No_Quotes) - - Delimited '\t' . with_quotes "|" . should_equal (Delimited '\t' quote_style=(Quote_Style.With_Quotes quote='|' quote_escape='|')) - Delimited '\t' . with_quotes "-" '\\' True . should_equal (Delimited '\t' quote_style=(Quote_Style.With_Quotes always_quote=True quote='-' quote_escape='\\')) - Delimited '\t' . without_quotes . should_equal (Delimited '\t' quote_style=Quote_Style.No_Quotes) - - Delimited ',' . with_headers . should_equal (Delimited ',' headers=True) - Delimited ',' . without_headers . should_equal (Delimited ',' headers=False) - Delimited "," skip_rows=123 headers=False value_formatter=Nothing quote_style=Quote_Style.No_Quotes . with_headers . should_equal (Delimited "," skip_rows=123 value_formatter=Nothing quote_style=Quote_Style.No_Quotes headers=True) - Delimited "," skip_rows=123 headers=True value_formatter=Nothing quote_style=Quote_Style.No_Quotes . without_headers . should_equal (Delimited "," skip_rows=123 value_formatter=Nothing quote_style=Quote_Style.No_Quotes headers=False) - - Delimited ',' . with_parsing . should_equal (Delimited ',') - Delimited ',' . without_parsing . should_equal (Delimited ',' value_formatter=Nothing) - custom_formatter = Data_Formatter true_values=["A", "B", "C"] false_values=["D", "E", "F"] - Delimited ',' . with_parsing custom_formatter . should_equal (Delimited ',' value_formatter=custom_formatter) - Delimited ',' row_limit=456 . without_parsing . should_equal (Delimited ',' value_formatter=Nothing row_limit=456) - - Delimited ',' . with_comments . should_equal (Delimited ',' comment_character='#') - Delimited ',' . with_comments ';' . should_equal (Delimited ',' comment_character=';') - Delimited ',' comment_character='#' . without_comments . should_equal (Delimited ',' comment_character=Nothing) - Delimited ',' . with_line_endings Line_Ending_Style.Unix . should_equal (Delimited ',' line_endings=Line_Ending_Style.Unix) + Delimited_Data "," . clone . should_equal (Delimited_Data ",") + Delimited_Data "," encoding=Encoding.ascii skip_rows=123 row_limit=100 headers=False value_formatter=Nothing . clone . should_equal (Delimited_Data "," headers=False value_formatter=Nothing skip_rows=123 row_limit=100 encoding=Encoding.ascii) + Delimited_Data "," . clone quote_style=Quote_Style.No_Quotes headers=False value_formatter=Nothing . should_equal (Delimited_Data "," headers=False value_formatter=Nothing quote_style=Quote_Style.No_Quotes) + + Delimited_Data '\t' . with_quotes "|" . should_equal (Delimited_Data '\t' quote_style=(Quote_Style.With_Quotes quote='|' quote_escape='|')) + Delimited_Data '\t' . with_quotes "-" '\\' True . should_equal (Delimited_Data '\t' quote_style=(Quote_Style.With_Quotes always_quote=True quote='-' quote_escape='\\')) + Delimited_Data '\t' . without_quotes . should_equal (Delimited_Data '\t' quote_style=Quote_Style.No_Quotes) + + Delimited_Data ',' . with_headers . should_equal (Delimited_Data ',' headers=True) + Delimited_Data ',' . without_headers . should_equal (Delimited_Data ',' headers=False) + Delimited_Data "," skip_rows=123 headers=False value_formatter=Nothing quote_style=Quote_Style.No_Quotes . with_headers . should_equal (Delimited_Data "," skip_rows=123 value_formatter=Nothing quote_style=Quote_Style.No_Quotes headers=True) + Delimited_Data "," skip_rows=123 headers=True value_formatter=Nothing quote_style=Quote_Style.No_Quotes . without_headers . should_equal (Delimited_Data "," skip_rows=123 value_formatter=Nothing quote_style=Quote_Style.No_Quotes headers=False) + + Delimited_Data ',' . with_parsing . should_equal (Delimited_Data ',') + Delimited_Data ',' . without_parsing . should_equal (Delimited_Data ',' value_formatter=Nothing) + custom_formatter = Data_Formatter_Data true_values=["A", "B", "C"] false_values=["D", "E", "F"] + Delimited_Data ',' . with_parsing custom_formatter . should_equal (Delimited_Data ',' value_formatter=custom_formatter) + Delimited_Data ',' row_limit=456 . without_parsing . should_equal (Delimited_Data ',' value_formatter=Nothing row_limit=456) + + Delimited_Data ',' . with_comments . should_equal (Delimited_Data ',' comment_character='#') + Delimited_Data ',' . with_comments ';' . should_equal (Delimited_Data ',' comment_character=';') + Delimited_Data ',' comment_character='#' . without_comments . should_equal (Delimited_Data ',' comment_character=Nothing) + Delimited_Data ',' . with_line_endings Line_Ending_Style.Unix . should_equal (Delimited_Data ',' line_endings=Line_Ending_Style.Unix) main = Test.Suite.run_main spec diff --git a/test/Table_Tests/src/Delimited_Write_Spec.enso b/test/Table_Tests/src/Delimited_Write_Spec.enso index 21487e52683e..388d59f34253 100644 --- a/test/Table_Tests/src/Delimited_Write_Spec.enso +++ b/test/Table_Tests/src/Delimited_Write_Spec.enso @@ -8,13 +8,13 @@ import Standard.Table import Standard.Table.Data.Column from Standard.Table.Errors import all import Standard.Table.IO.File_Read -from Standard.Table.IO.File_Format import Delimited -from Standard.Table.Data.Data_Formatter as Data_Formatter_Module import Data_Formatter +from Standard.Table.IO.File_Format import Delimited_Data +from Standard.Table.Data.Data_Formatter import Data_Formatter_Data import Standard.Table.IO.Quote_Style import Standard.Table.Data.Match_Columns import Standard.Table.Data.Column_Name_Mapping from Standard.Table.Data.Column_Selector as Column_Selector_Module import By_Name -from Standard.Table.Errors as Table_Errors import Column_Count_Mismatch, Column_Name_Mismatch +from Standard.Table.Errors as Table_Errors import Column_Count_Mismatch_Data, Column_Name_Mismatch_Data import Standard.Test import Standard.Test.Problems @@ -22,7 +22,7 @@ import Standard.Test.Problems from project.Util import all type My_Type - type My_Type x + My_Type_Data x to_text : Text to_text self = "[[[My Type :: " + self.x.to_text + "]]]" @@ -36,7 +36,7 @@ spec = line_ending_pairs = [[Line_Ending_Style.Unix, '\n'], [Line_Ending_Style.Windows, '\r\n'], [Line_Ending_Style.Mac_Legacy, '\r']] Test.group "Delimited File Writing" <| Test.specify "should correctly write a simple table" <| - table = Table.new [["A", [1,2,3]], ["B", [1.0,1.5,2.2]], ["C", ["x","y","z"]], ["D", ["a", 2, My_Type 10]]] + table = Table.new [["A", [1,2,3]], ["B", [1.0,1.5,2.2]], ["C", ["x","y","z"]], ["D", ["a", 2, My_Type_Data 10]]] file = (enso_project.data / "transient" / "written.csv") file.delete_if_exists table.write file on_problems=Report_Error . should_succeed @@ -56,7 +56,7 @@ spec = style=setting.first separator=setting.second file = (enso_project.data / "transient" / "endings.csv") - table.write file (Delimited ',' line_endings=style) on_problems=Report_Error . should_succeed + table.write file (Delimited_Data ',' line_endings=style) on_problems=Report_Error . should_succeed text = File.read_text file text.should_equal (lines.join separator suffix=separator) file.delete @@ -71,11 +71,11 @@ spec = file.delete Test.specify 'should quote values that contain the delimiter or quotes, in the [,""] variant' <| - data_formatter = Data_Formatter decimal_point="," + data_formatter = Data_Formatter_Data decimal_point="," table = Table.new [['The Column "Name"', ["foo","'bar'",'"baz"', 'one, two, three']], ["Hello, Column?", [1.0, 1000000.5, 2.2, -1.5]]] file = (enso_project.data / "transient" / "quotes1.csv") file.delete_if_exists - table.write file (Delimited "," value_formatter=data_formatter) on_problems=Report_Error . should_succeed + table.write file (Delimited_Data "," value_formatter=data_formatter) on_problems=Report_Error . should_succeed expected_text = normalize_lines <| """ "The Column ""Name""","Hello, Column?" foo,"1,0" @@ -87,11 +87,11 @@ spec = file.delete Test.specify 'should quote values that contain the delimiter or quotes, in the [;\\\"] variant' <| - data_formatter = Data_Formatter thousand_separator="'" + data_formatter = Data_Formatter_Data thousand_separator="'" table = Table.new [['"A"', ["foo",'!"baz" ', 'one, two, three', "a;b; c ", "a\b"]], ["B", [1000000.5, 1000.0, 0.0, -1.2, Nothing]]] file = (enso_project.data / "transient" / "quotes2.csv") file.delete_if_exists - table.write file (Delimited ";" value_formatter=data_formatter . with_quotes quote='"' quote_escape='\\') on_problems=Report_Error . should_succeed + table.write file (Delimited_Data ";" value_formatter=data_formatter . with_quotes quote='"' quote_escape='\\') on_problems=Report_Error . should_succeed expected_text = normalize_lines <| """ "\"A\"";B foo;1'000'000.5 @@ -104,11 +104,11 @@ spec = file.delete Test.specify "should quote values that contain the delimiter or quotes, in the [\t''] variant" <| - data_formatter = Data_Formatter thousand_separator="'" + data_formatter = Data_Formatter_Data thousand_separator="'" table = Table.new [['"A"', [Nothing,"The 'thing'.", 'one, "two", three', 'a\tb']], ["B\C", [1000000.5, 1000.0, Nothing, -1.2]]] file = (enso_project.data / "transient" / "quotes3.csv") file.delete_if_exists - table.write file (Delimited '\t' value_formatter=data_formatter . with_quotes quote='\'' quote_escape='\'') on_problems=Report_Error . should_succeed + table.write file (Delimited_Data '\t' value_formatter=data_formatter . with_quotes quote='\'' quote_escape='\'') on_problems=Report_Error . should_succeed expected_text = normalize_lines <| ''' "A"\tB\\C \t'1''000''000.5' @@ -143,7 +143,7 @@ spec = text.should_equal expected_text file.delete - format = Delimited ',' . with_comments + format = Delimited_Data ',' . with_comments table.write file format on_problems=Report_Error . should_succeed expected_text_2 = normalize_lines <| """ "#",B @@ -155,7 +155,7 @@ spec = file.delete Test.specify 'should not quote values if quoting is disabled' <| - format = Delimited "," value_formatter=(Data_Formatter decimal_point=",") . without_quotes + format = Delimited_Data "," value_formatter=(Data_Formatter_Data decimal_point=",") . without_quotes table = Table.new [['The Column "Name"', ["foo","'bar'",'"baz"', 'one, two, three']], ["Hello, Column?", [1.0, 1000000.5, 2.2, -1.5]]] file = (enso_project.data / "transient" / "quote_disabled.csv") file.delete_if_exists @@ -171,8 +171,8 @@ spec = file.delete Test.specify 'should allow to always quote text and custom values, but for non-text primitves only if absolutely necessary' <| - format = Delimited "," value_formatter=(Data_Formatter thousand_separator='"' date_formats=["E, d MMM y"]) . with_quotes always_quote=True quote_escape='\\' - table = Table.new [['The Column "Name"', ["foo","'bar'",'"baz"', 'one, two, three']], ["B", [1.0, 1000000.5, 2.2, -1.5]], ["C", ["foo", My_Type 44, (Date.new 2022 06 21), 42]], ["D", [1,2,3,4000]], ["E", [Nothing, (Time_Of_Day.new 13 55 . internal_local_time), Nothing, Nothing]]] + format = Delimited_Data "," value_formatter=(Data_Formatter_Data thousand_separator='"' date_formats=["E, d MMM y"]) . with_quotes always_quote=True quote_escape='\\' + table = Table.new [['The Column "Name"', ["foo","'bar'",'"baz"', 'one, two, three']], ["B", [1.0, 1000000.5, 2.2, -1.5]], ["C", ["foo", My_Type_Data 44, (Date.new 2022 06 21), 42]], ["D", [1,2,3,4000]], ["E", [Nothing, (Time_Of_Day.new 13 55 . internal_local_time), Nothing, Nothing]]] file = (enso_project.data / "transient" / "quote_always.csv") file.delete_if_exists table.write file format on_problems=Report_Error . should_succeed @@ -190,7 +190,7 @@ spec = table = Table.new [["ąęćś", [0]], ["ß", ["żółw 🐢"]]] file = (enso_project.data / "transient" / "utf16.csv") file.delete_if_exists - table.write file (Delimited "," encoding=Encoding.utf_16_be) on_problems=Report_Error . should_succeed + table.write file (Delimited_Data "," encoding=Encoding.utf_16_be) on_problems=Report_Error . should_succeed expected_text = normalize_lines <| """ ąęćś,ß 0,żółw 🐢 @@ -202,7 +202,7 @@ spec = table = Table.new [["A", [0, 1]], ["B", ["słówka", "🐢"]]] file = (enso_project.data / "transient" / "ascii.csv") file.delete_if_exists - result = table.write file (Delimited "," encoding=Encoding.ascii) + result = table.write file (Delimited_Data "," encoding=Encoding.ascii) expected_text = normalize_lines <| """ A,B 0,s??wka @@ -213,11 +213,11 @@ spec = positions = [7, 8, 15] msg = "Encoding issues at codepoints " + positions.map .to_text . join separator=", " suffix="." - Warning.get_all result . map .value . should_equal [Encoding_Error msg] + Warning.get_all result . map .value . should_equal [Encoding_Error_Data msg] file.delete Test.specify "should allow only text columns if no formatter is specified" <| - format = Delimited "," value_formatter=Nothing + format = Delimited_Data "," value_formatter=Nothing table_1 = Table.new [["A", ["x", "y"]], ["B", ["z", "w"]]] file_1 = (enso_project.data / "transient" / "textonly.csv") file_1.delete_if_exists @@ -234,7 +234,7 @@ spec = file_2 = (enso_project.data / "transient" / "non-text_but_no_formatter.csv") file_2.delete_if_exists result_2 = table_2.write file_2 format - result_2 . should_fail_with Illegal_Argument_Error + result_2 . should_fail_with Illegal_Argument_Error_Data text_2 = File.read_text file_2 text_2.should_equal "" @@ -289,7 +289,7 @@ spec = file = (enso_project.data / "transient" / "append_by_name_2.csv") file.delete_if_exists existing_table.write file on_existing_file=Existing_File_Behavior.Overwrite on_problems=Report_Error . should_succeed - format = Delimited "," . with_headers + format = Delimited_Data "," . with_headers appending_table.write file format on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed got_table = file.read format expected_table = Table.new [["0", [1,2,Nothing,0]], ["B1", [1.0,1.5,33,44]], ["C", ["x","y","a","BB"]]] @@ -301,9 +301,9 @@ spec = appending_table = Table.new [["B", [33,44]], ["A", [Nothing, 0]], ["C", ["a","BB"]]] file = (enso_project.data / "transient" / "append_no_header.csv") file.delete_if_exists - no_header_format = Delimited "," . without_headers + no_header_format = Delimited_Data "," . without_headers existing_table.write file no_header_format on_existing_file=Existing_File_Behavior.Overwrite - appending_table.write file on_existing_file=Existing_File_Behavior.Append . should_fail_with Illegal_Argument_Error + appending_table.write file on_existing_file=Existing_File_Behavior.Append . should_fail_with Illegal_Argument_Error_Data file.delete Test.specify "should fail when appending and matching columns by name but headers are disabled (headers=False)" <| @@ -311,9 +311,9 @@ spec = appending_table = Table.new [["B", [33,44]], ["A", [Nothing, 0]], ["C", ["a","BB"]]] file = (enso_project.data / "transient" / "append_no_header.csv") file.delete_if_exists - no_header_format = Delimited "," . without_headers + no_header_format = Delimited_Data "," . without_headers existing_table.write file on_existing_file=Existing_File_Behavior.Overwrite - appending_table.write file no_header_format on_existing_file=Existing_File_Behavior.Append . should_fail_with Illegal_Argument_Error + appending_table.write file no_header_format on_existing_file=Existing_File_Behavior.Append . should_fail_with Illegal_Argument_Error_Data file.delete Test.specify "should fail on column mismatch when appending to a file by name" <| @@ -323,7 +323,7 @@ spec = file.delete_if_exists existing_table.write file on_existing_file=Existing_File_Behavior.Overwrite result = appending_table.write file on_existing_file=Existing_File_Behavior.Append - result . should_fail_with Column_Name_Mismatch + result . should_fail_with Column_Name_Mismatch_Data result.catch.missing . should_equal ["A"] result.catch.extras . should_equal ["X"] result.catch.to_display_text . should_equal "Columns mismatch. Missing from new data: [A] Extras in new data: [X]" @@ -343,7 +343,7 @@ spec = got_table.should_equal expected_table file.delete - base_format = Delimited "," + base_format = Delimited_Data "," no_headers = base_format . without_headers with_headers = base_format . with_headers @@ -364,13 +364,13 @@ spec = existing_table.write file on_existing_file=Existing_File_Behavior.Overwrite result_1 = appending_table_1.write file match_columns=Match_Columns.By_Position on_existing_file=Existing_File_Behavior.Append - result_1 . should_fail_with Column_Count_Mismatch + result_1 . should_fail_with Column_Count_Mismatch_Data result_1.catch.expected . should_equal 3 result_1.catch.actual . should_equal 2 result_1.catch.to_display_text . should_equal "Expected 3 columns, got 2." result_2 = appending_table_2.write file match_columns=Match_Columns.By_Position on_existing_file=Existing_File_Behavior.Append - result_2 . should_fail_with Column_Count_Mismatch + result_2 . should_fail_with Column_Count_Mismatch_Data result_2.catch.expected . should_equal 3 result_2.catch.actual . should_equal 4 result_2.catch.to_display_text . should_equal "Expected 3 columns, got 4." @@ -385,7 +385,7 @@ spec = style=setting.first separator=setting.second file = (enso_project.data / "transient" / "endings.csv") - initial_table.write file (Delimited ',' line_endings=style) on_problems=Report_Error . should_succeed + initial_table.write file (Delimited_Data ',' line_endings=style) on_problems=Report_Error . should_succeed table_to_append.write file on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed text = File.read_text file text.should_equal (expected_lines.join separator suffix=separator) @@ -415,7 +415,7 @@ spec = separator=setting.second file.delete_if_exists (initial_lines.join separator suffix=separator).write file - format = Delimited ',' . with_comments + format = Delimited_Data ',' . with_comments table_to_append.write file format on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed text = File.read_text file expected_text = expected_lines.join separator suffix=separator @@ -431,7 +431,7 @@ spec = separator=setting.second file.delete_if_exists (initial_lines.join separator).write file - format = Delimited ',' . with_comments + format = Delimited_Data ',' . with_comments table_to_append.write file format on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed text = File.read_text file expected_text = expected_lines.join separator suffix=separator @@ -443,7 +443,7 @@ spec = file = (enso_project.data / "transient" / "append_edge_cases.csv") file.delete_if_exists - format = Delimited ',' . without_headers + format = Delimited_Data ',' . without_headers # A long line but without a trailing newline base_line = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-ABC" @@ -518,7 +518,7 @@ spec = separator=setting.second file.delete_if_exists (initial_line+separator).write file - format = Delimited ',' . with_comments + format = Delimited_Data ',' . with_comments table_to_append.write file format on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed text = File.read_text file expected_text = expected_lines.join separator suffix=separator @@ -532,7 +532,7 @@ spec = file = (enso_project.data / "transient" / "endings_comments_only.csv") file.delete_if_exists (join_lines initial_lines trailing_newline=False).write file - format = Delimited ',' . with_comments + format = Delimited_Data ',' . with_comments table_to_append.write file format on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed text = File.read_text file expected_text = join_lines expected_lines @@ -544,9 +544,9 @@ spec = table_to_append = Table.new [["a", ["x", "y"]]] file = (enso_project.data / "transient" / "endings_mismatch.csv") file.delete_if_exists - initial_table.write file (Delimited ',' line_endings=Line_Ending_Style.Mac_Legacy) - result = table_to_append.write file (Delimited ',' line_endings=Line_Ending_Style.Unix) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position - result . should_fail_with Illegal_Argument_Error + initial_table.write file (Delimited_Data ',' line_endings=Line_Ending_Style.Mac_Legacy) + result = table_to_append.write file (Delimited_Data ',' line_endings=Line_Ending_Style.Unix) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position + result . should_fail_with Illegal_Argument_Error_Data result.catch.message . should_equal "The explicitly provided line endings ('\n') do not match the line endings in the file ('\r')." file.delete diff --git a/test/Table_Tests/src/In_Memory_Tests.enso b/test/Table_Tests/src/In_Memory_Tests.enso index fbeeed211f08..07d4d9aa6b50 100644 --- a/test/Table_Tests/src/In_Memory_Tests.enso +++ b/test/Table_Tests/src/In_Memory_Tests.enso @@ -4,8 +4,8 @@ import Standard.Test import project.Column_Spec import project.Csv_Spec -#import project.Delimited_Read_Spec -#import project.Delimited_Write_Spec +import project.Delimited_Read_Spec +import project.Delimited_Write_Spec #import project.Excel_Spec #import project.Json_Spec #import project.Table_Spec @@ -16,8 +16,8 @@ import project.Csv_Spec in_memory_spec = Column_Spec.spec Csv_Spec.spec - #Delimited_Read_Spec.spec - #Delimited_Write_Spec.spec + Delimited_Read_Spec.spec + Delimited_Write_Spec.spec #Excel_Spec.spec #Json_Spec.spec #Table_Spec.spec diff --git a/test/Table_Tests/src/Main.enso b/test/Table_Tests/src/Main.enso index 5f5298789ca9..1bf6a1bfb26f 100644 --- a/test/Table_Tests/src/Main.enso +++ b/test/Table_Tests/src/Main.enso @@ -4,11 +4,11 @@ import Standard.Test import project.In_Memory_Tests #import project.Database.Main as Database_Tests -#import project.File_Read_Spec +import project.File_Read_Spec import project.Data_Formatter_Spec main = Test.Suite.run_main <| In_Memory_Tests.in_memory_spec #Database_Tests.databases_spec - #File_Read_Spec.spec + File_Read_Spec.spec Data_Formatter_Spec.spec From 26fc60c4bf24258d644a91f5b53551ac09064139 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 23 Aug 2022 12:55:05 +0200 Subject: [PATCH 059/110] another test --- .../Table/0.0.0-dev/src/IO/Excel.enso | 26 +- .../Table/0.0.0-dev/src/IO/File_Format.enso | 16 +- test/Table_Tests/src/Excel_Spec.enso | 290 +++++++++--------- test/Table_Tests/src/File_Read_Spec.enso | 20 +- test/Table_Tests/src/In_Memory_Tests.enso | 4 +- 5 files changed, 178 insertions(+), 178 deletions(-) diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/IO/Excel.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/IO/Excel.enso index 5057e37a7af2..3d1cb1c52b7e 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/IO/Excel.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/IO/Excel.enso @@ -5,7 +5,7 @@ import Standard.Base.System.File.Option from Standard.Table.IO.File_Format import Infer import Standard.Table.Data.Table -from Standard.Table.Errors import Invalid_Location, Duplicate_Output_Column_Names, Invalid_Output_Column_Names, Range_Exceeded, Existing_Data, Column_Count_Mismatch, Column_Name_Mismatch +from Standard.Table.Errors import Invalid_Location_Data, Duplicate_Output_Column_Names_Data, Invalid_Output_Column_Names_Data, Range_Exceeded_Data, Existing_Data_Data, Column_Count_Mismatch, Column_Name_Mismatch import Standard.Base.Error.Common as Errors import Standard.Table.Data.Match_Columns @@ -167,7 +167,7 @@ type Excel_Range Wrapper for validation of a value prior to execution. validate : Boolean -> Text -> Any validate validation ~error_message ~wrapped = - if validation then wrapped else Error.throw (Illegal_Argument_Error error_message) + if validation then wrapped else Error.throw (Illegal_Argument_Error_Data error_message) ## PRIVATE Reads an input Excel file according to the provided section. @@ -184,8 +184,8 @@ validate validation ~error_message ~wrapped = read_excel : File -> Excel_Section -> (Boolean|Infer) -> Problem_Behavior -> Boolean -> (Table | Vector) read_excel file section headers on_problems xls_format=False = reader stream = case section of - Sheet_Names -> Vector.Vector (ExcelReader.readSheetNames stream xls_format) - Range_Names -> Vector.Vector (ExcelReader.readRangeNames stream xls_format) + Sheet_Names -> Vector.Vector_Data (ExcelReader.readSheetNames stream xls_format) + Range_Names -> Vector.Vector_Data (ExcelReader.readRangeNames stream xls_format) Sheet sheet skip_rows row_limit -> prepare_reader_table on_problems <| case sheet of Integer -> ExcelReader.readSheetByIndex stream sheet (make_java_headers headers) skip_rows row_limit xls_format @@ -229,11 +229,11 @@ write_excel file table on_existing_file section headers match_columns _ xls_form prepare_reader_table : Problem_Behavior -> Any -> Table prepare_reader_table on_problems result_with_problems = map_problem java_problem = - if Java.is_instance java_problem DuplicateNames then Duplicate_Output_Column_Names (Vector.Vector java_problem.duplicatedNames) else - if Java.is_instance java_problem InvalidNames then Invalid_Output_Column_Names (Vector.Vector java_problem.invalidNames) else + if Java.is_instance java_problem DuplicateNames then Duplicate_Output_Column_Names_Data (Vector.Vector_Data java_problem.duplicatedNames) else + if Java.is_instance java_problem InvalidNames then Invalid_Output_Column_Names_Data (Vector.Vector_Data java_problem.invalidNames) else java_problem - parsing_problems = Vector.Vector (result_with_problems.problems) . map map_problem - on_problems.attach_problems_after (Table.Table result_with_problems.value) parsing_problems + parsing_problems = Vector.Vector_Data (result_with_problems.problems) . map map_problem + on_problems.attach_problems_after (Table.Table_Data result_with_problems.value) parsing_problems ## PRIVATE Convert Boolean|Infer to the correct HeaderBehavior @@ -260,7 +260,7 @@ handle_reader file reader = bad_format caught_panic = Error.throw (File.IO_Error file caught_panic.payload.cause.getMessage) handle_bad_format = Panic.catch UnsupportedFileFormatException handler=bad_format - bad_argument caught_panic = Error.throw (Invalid_Location caught_panic.payload.cause.getCause) + bad_argument caught_panic = Error.throw (Invalid_Location_Data caught_panic.payload.cause.getCause) handle_bad_argument = Panic.catch InvalidLocationException handler=bad_argument File.handle_java_exceptions file <| handle_bad_argument <| handle_bad_format <| @@ -270,17 +270,17 @@ handle_reader file reader = ## PRIVATE Handle and map the Java errors when writing an Excel file handle_writer ~writer = - bad_location caught_panic = Error.throw (Invalid_Location caught_panic.payload.cause.getCause) + bad_location caught_panic = Error.throw (Invalid_Location_Data caught_panic.payload.cause.getCause) handle_bad_location = Panic.catch InvalidLocationException handler=bad_location - throw_range_exceeded caught_panic = Error.throw (Range_Exceeded caught_panic.payload.cause.getMessage) + throw_range_exceeded caught_panic = Error.throw (Range_Exceeded_Data caught_panic.payload.cause.getMessage) handle_range_exceeded = Panic.catch RangeExceededException handler=throw_range_exceeded - throw_existing_data caught_panic = Error.throw (Existing_Data caught_panic.payload.cause.getMessage) + throw_existing_data caught_panic = Error.throw (Existing_Data_Data caught_panic.payload.cause.getMessage) handle_existing_data = Panic.catch ExistingDataException handler=throw_existing_data ## Should be impossible - occurs if no fallback serializer is provided. - throw_illegal_state caught_panic = Panic.throw (Illegal_State_Error caught_panic.payload.cause.getMessage) + throw_illegal_state caught_panic = Panic.throw (Illegal_State_Error_Data caught_panic.payload.cause.getMessage) handle_illegal_state = Panic.catch IllegalStateException handler=throw_illegal_state handle_illegal_state <| Column_Name_Mismatch.handle_java_exception <| 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 6a7bccc57d95..6dfa3392f698 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 @@ -9,7 +9,7 @@ from Standard.Base.Data.Text.Encoding import Encoding import Standard.Base.Runtime.Ref import Standard.Table.Internal.Delimited_Reader import Standard.Table.Internal.Delimited_Writer -from Standard.Table.Errors import Unsupported_File_Type +from Standard.Table.Errors import Unsupported_File_Type_Data from Standard.Table.Data.Data_Formatter import Data_Formatter, Data_Formatter_Data import Standard.Table.IO.Excel as Excel_Module @@ -28,17 +28,17 @@ type Auto extension = file.extension output = Ref.new Nothing - if ".txt".equals_ignore_case extension then output.put File_Format.Plain_Text - if ".log".equals_ignore_case extension then output.put File_Format.Plain_Text + if ".txt".equals_ignore_case extension then output.put File_Format.Plain_Text_Data + if ".log".equals_ignore_case extension then output.put File_Format.Plain_Text_Data if ".csv".equals_ignore_case extension then output.put (File_Format.Delimited_Data ',') if ".tsv".equals_ignore_case extension then output.put (File_Format.Delimited_Data '\t') - if ".xlsx".equals_ignore_case extension then output.put File_Format.Excel - if ".xlsm".equals_ignore_case extension then output.put File_Format.Excel - if ".xls".equals_ignore_case extension then output.put File_Format.Excel - if ".xlt".equals_ignore_case extension then output.put File_Format.Excel + if ".xlsx".equals_ignore_case extension then output.put File_Format.Excel_Data + if ".xlsm".equals_ignore_case extension then output.put File_Format.Excel_Data + if ".xls".equals_ignore_case extension then output.put File_Format.Excel_Data + if ".xlt".equals_ignore_case extension then output.put File_Format.Excel_Data output.get.if_nothing <| - Error.throw (Unsupported_File_Type file.name) + Error.throw (Unsupported_File_Type_Data file.name) ## Implements the `File.read` for this `File_Format` read : File -> Problem_Behavior -> Any diff --git a/test/Table_Tests/src/Excel_Spec.enso b/test/Table_Tests/src/Excel_Spec.enso index 5f6a35b666b6..b70f282c2c47 100644 --- a/test/Table_Tests/src/Excel_Spec.enso +++ b/test/Table_Tests/src/Excel_Spec.enso @@ -10,8 +10,8 @@ import Standard.Table.Data.Column_Name_Mapping import Standard.Table.Data.Match_Columns from Standard.Table.Data.Column_Selector as Column_Selector_Module import By_Index from Standard.Table.IO.Excel import Excel_Range, Sheet_Names, Range_Names, Sheet, Cell_Range -from Standard.Table.Errors as Table_Errors import Invalid_Output_Column_Names, Duplicate_Output_Column_Names, Invalid_Location, Range_Exceeded, Existing_Data, Column_Count_Mismatch, Column_Name_Mismatch -from Standard.Table.Data.Data_Formatter as Data_Formatter_Module import Data_Formatter +from Standard.Table.Errors as Table_Errors import Invalid_Output_Column_Names_Data, Duplicate_Output_Column_Names_Data, Invalid_Location_Data, Range_Exceeded_Data, Existing_Data_Data, Column_Count_Mismatch_Data, Column_Name_Mismatch_Data +from Standard.Table.Data.Data_Formatter as Data_Formatter_Module import Data_Formatter_Data import Standard.Test import Standard.Test.Problems @@ -30,7 +30,7 @@ spec_fmt header file read_method = t.at 'Price' . to_vector . should_equal [22.3, 32, 43.2, 54, 31, Nothing] Test.specify "should read the specified sheet by index and properly format a table" <| - t = read_method file (File_Format.Excel (Sheet 2) headers=False) + t = read_method file (File_Format.Excel_Data (Sheet 2) headers=False) t.columns.map .name . should_equal ['A', 'B', 'C', 'D', 'E'] t.at 'A' . to_vector . should_equal [Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing] t.at 'B' . to_vector . should_equal [Nothing, Nothing, 10, Nothing, Nothing, Nothing, Nothing] @@ -39,32 +39,32 @@ spec_fmt header file read_method = t.at 'E' . to_vector . should_equal [Nothing, Nothing, Nothing, Nothing, Nothing, 'foo', Nothing] Test.specify "should read the specified sheet by name and properly handle dates" <| - t = read_method file (File_Format.Excel (Sheet 'Dates')) + t = read_method file (File_Format.Excel_Data (Sheet 'Dates')) t.columns.map .name . should_equal ['Student Name', 'Enrolment Date'] t.at 'Enrolment Date' . map .day . to_vector . should_equal [2, 26, 4, 24, 31, 7] Test.specify "should read an empty table" <| - t = read_method file (File_Format.Excel (Sheet "Empty")) + t = read_method file (File_Format.Excel_Data (Sheet "Empty")) t.columns.length.should_equal 0 Test.specify "should gracefully handle duplicate column names and formulas" <| - t = read_method file (File_Format.Excel (Sheet "Duplicate Columns")) + t = read_method file (File_Format.Excel_Data (Sheet "Duplicate Columns")) t.columns.map .name . should_equal ['Item', 'Price', 'Quantity', 'Price_1'] t.at 'Price_1' . to_vector . should_equal [20, 40, 0, 60, 0, 10] Test.specify "should allow reading with cell range specified" <| - t_1 = read_method file (File_Format.Excel (Cell_Range "Simple!B:C")) + t_1 = read_method file (File_Format.Excel_Data (Cell_Range "Simple!B:C")) t_1.columns.map .name . should_equal ['Quantity', 'Price'] t_1.at 'Quantity' . to_vector . should_equal [10, 20, Nothing, 30, Nothing, 5] t_1.at 'Price' . to_vector . should_equal [22.3, 32, 43.2, 54, 31, Nothing] - t_2 = read_method file (File_Format.Excel (Cell_Range "Simple!3:5") headers=False) + t_2 = read_method file (File_Format.Excel_Data (Cell_Range "Simple!3:5") headers=False) t_2.columns.length.should_equal 3 t_2.at 'A' . to_vector . should_equal ['t-shirt', 'trousers', 'shoes'] t_2.at 'B' . to_vector . should_equal [20, Nothing, 30] t_2.at 'C' . to_vector . should_equal [32, 43.2, 54] - t_3 = read_method file (File_Format.Excel (Cell_Range "Simple!B4:C5") headers=False) + t_3 = read_method file (File_Format.Excel_Data (Cell_Range "Simple!B4:C5") headers=False) t_3.columns.length.should_equal 2 t_3.at 'B' . to_vector . should_equal [Nothing, 30] t_3.at 'C' . to_vector . should_equal [43.2, 54] @@ -75,7 +75,7 @@ spec_write suffix test_sheet_name = for these tests. This should ideally be re-enabled with the completion of the following story: https://www.pivotaltracker.com/story/show/181755990 - no_dates = File_Format.Delimited "," value_formatter=(Data_Formatter date_formats=[] time_formats=[] datetime_formats=[]) + no_dates = File_Format.Delimited_Data "," value_formatter=(Data_Formatter_Data date_formats=[] time_formats=[] datetime_formats=[]) out = enso_project.data / ('out.' + suffix) out_bak = enso_project.data / ('out.' + suffix + '.bak') table = enso_project.data/'varied_column.csv' . read (format = no_dates) @@ -99,77 +99,77 @@ spec_write suffix test_sheet_name = Test.specify 'should write a table to existing file in overwrite mode as a new sheet with headers' <| out.delete_if_exists (enso_project.data / test_sheet_name) . copy_to out - table.write out (File_Format.Excel (Sheet "Another")) on_existing_file=Existing_File_Behavior.Overwrite on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Sheet "Another")) + table.write out (File_Format.Excel_Data (Sheet "Another")) on_existing_file=Existing_File_Behavior.Overwrite on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Sheet "Another")) written.should_equal table out.delete_if_exists Test.specify 'should write a table to existing file in overwrite mode as a new sheet without headers' <| out.delete_if_exists (enso_project.data / test_sheet_name) . copy_to out - table.write out (File_Format.Excel (Sheet "NoHeaders")) on_existing_file=Existing_File_Behavior.Overwrite on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Sheet "NoHeaders")) + table.write out (File_Format.Excel_Data (Sheet "NoHeaders")) on_existing_file=Existing_File_Behavior.Overwrite on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Sheet "NoHeaders")) written.should_equal (table.rename_columns (Column_Name_Mapping.By_Position ['A', 'B', 'C', 'D', 'E', 'F'])) out.delete_if_exists Test.specify 'should create new sheets at the start if index is 0' <| out.delete_if_exists - table.write out (File_Format.Excel (Sheet 0)) on_problems=Report_Error . should_succeed - clothes.write out (File_Format.Excel (Sheet 0)) on_problems=Report_Error . should_succeed - read_1 = out.read (File_Format.Excel (Sheet "Sheet1")) + table.write out (File_Format.Excel_Data (Sheet 0)) on_problems=Report_Error . should_succeed + clothes.write out (File_Format.Excel_Data (Sheet 0)) on_problems=Report_Error . should_succeed + read_1 = out.read (File_Format.Excel_Data (Sheet "Sheet1")) read_1 . should_equal table - read_2 = out.read (File_Format.Excel (Sheet "Sheet2")) + read_2 = out.read (File_Format.Excel_Data (Sheet "Sheet2")) read_2 . should_equal clothes - read_3 = out.read (File_Format.Excel (Sheet_Names)) + read_3 = out.read (File_Format.Excel_Data (Sheet_Names)) read_3 . should_equal ["Sheet2", "Sheet1"] out.delete_if_exists Test.specify 'should write a table to specific single cell location of an existing sheet' <| out.delete_if_exists (enso_project.data / test_sheet_name) . copy_to out - table.write out (File_Format.Excel (Cell_Range "Another!G1")) on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Cell_Range "Another!G1")) + table.write out (File_Format.Excel_Data (Cell_Range "Another!G1")) on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Cell_Range "Another!G1")) written.should_equal table out.delete_if_exists Test.specify 'should clear out an existing fixed range and replace' <| out.delete_if_exists (enso_project.data / test_sheet_name) . copy_to out - sub_clothes.write out (File_Format.Excel (Cell_Range "Another!A1:D20")) on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Cell_Range "Another!A1")) + sub_clothes.write out (File_Format.Excel_Data (Cell_Range "Another!A1:D20")) on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Cell_Range "Another!A1")) written.should_equal sub_clothes out.delete_if_exists Test.specify 'should clear out an existing range and replace' <| out.delete_if_exists (enso_project.data / test_sheet_name) . copy_to out - sub_clothes.write out (File_Format.Excel (Cell_Range "Another!A1")) on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Cell_Range "Another!A1")) + sub_clothes.write out (File_Format.Excel_Data (Cell_Range "Another!A1")) on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Cell_Range "Another!A1")) written.should_equal sub_clothes out.delete_if_exists Test.specify 'should result in Invalid_Location error if trying to write in a bad location' <| out.delete_if_exists (enso_project.data / test_sheet_name) . copy_to out - sub_clothes.write out (File_Format.Excel (Cell_Range "DoesNotExist!A1")) . should_fail_with Invalid_Location - sub_clothes.write out (File_Format.Excel (Cell_Range "DoesNotExist!A1:B2")) . should_fail_with Invalid_Location - sub_clothes.write out (File_Format.Excel (Cell_Range "SillyRangeName")) . should_fail_with Invalid_Location + sub_clothes.write out (File_Format.Excel_Data (Cell_Range "DoesNotExist!A1")) . should_fail_with Invalid_Location_Data + sub_clothes.write out (File_Format.Excel_Data (Cell_Range "DoesNotExist!A1:B2")) . should_fail_with Invalid_Location_Data + sub_clothes.write out (File_Format.Excel_Data (Cell_Range "SillyRangeName")) . should_fail_with Invalid_Location_Data out.delete_if_exists Test.specify 'should result in Range_Exceeded error if trying to write in too small a range' <| out.delete_if_exists (enso_project.data / test_sheet_name) . copy_to out - sub_clothes.write out (File_Format.Excel (Cell_Range "Another!A1:B2")) . should_fail_with Range_Exceeded + sub_clothes.write out (File_Format.Excel_Data (Cell_Range "Another!A1:B2")) . should_fail_with Range_Exceeded_Data out.delete_if_exists Test.specify 'should result in Existing_Data error if in Error mode and trying to replace' <| out.delete_if_exists (enso_project.data / test_sheet_name) . copy_to out lmd = out.last_modified_time - sub_clothes.write out (File_Format.Excel (Sheet 1)) on_existing_file=Existing_File_Behavior.Error . should_fail_with Existing_Data - sub_clothes.write out (File_Format.Excel (Sheet "Another")) on_existing_file=Existing_File_Behavior.Error . should_fail_with Existing_Data - sub_clothes.write out (File_Format.Excel (Cell_Range "Another!A1")) on_existing_file=Existing_File_Behavior.Error . should_fail_with Existing_Data - sub_clothes.write out (File_Format.Excel (Cell_Range "Sheet1!A9")) on_existing_file=Existing_File_Behavior.Error . should_fail_with Existing_Data + sub_clothes.write out (File_Format.Excel_Data (Sheet 1)) on_existing_file=Existing_File_Behavior.Error . should_fail_with Existing_Data_Data + sub_clothes.write out (File_Format.Excel_Data (Sheet "Another")) on_existing_file=Existing_File_Behavior.Error . should_fail_with Existing_Data_Data + sub_clothes.write out (File_Format.Excel_Data (Cell_Range "Another!A1")) on_existing_file=Existing_File_Behavior.Error . should_fail_with Existing_Data_Data + sub_clothes.write out (File_Format.Excel_Data (Cell_Range "Sheet1!A9")) on_existing_file=Existing_File_Behavior.Error . should_fail_with Existing_Data_Data out.last_modified_time.should_equal lmd out.delete_if_exists @@ -177,13 +177,13 @@ spec_write suffix test_sheet_name = out.delete_if_exists (enso_project.data / test_sheet_name) . copy_to out lmd = out.last_modified_time - sub_clothes.write out (File_Format.Excel (Sheet "Testing")) on_existing_file=Existing_File_Behavior.Error . should_fail_with File_Already_Exists_Error + sub_clothes.write out (File_Format.Excel_Data (Sheet "Testing")) on_existing_file=Existing_File_Behavior.Error . should_fail_with File_Already_Exists_Error out.last_modified_time.should_equal lmd out.delete_if_exists Test.specify 'should write a table to non-existent file as a new sheet without headers' <| out.delete_if_exists - table.write out (File_Format.Excel (Sheet "Sheet1") headers=False) on_problems=Report_Error . should_succeed + table.write out (File_Format.Excel_Data (Sheet "Sheet1") headers=False) on_problems=Report_Error . should_succeed written = out.read written.should_equal (table.rename_columns (Column_Name_Mapping.By_Position ['A', 'B', 'C', 'D', 'E', 'F'])) out.delete_if_exists @@ -193,8 +193,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['AA', ['d', 'e']], ['BB',[4, 5]], ['CC',[True, False]], ['DD', ['2022-01-20', '2022-01-21']]] expected = Table.new [['AA', ['a','b','c','d', 'e']], ['BB',[1,2,3,4,5]], ['CC',[True, False, False, True, False]]] - extra_another.write out (File_Format.Excel (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) + extra_another.write out (File_Format.Excel_Data (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) written.should_equal expected out.delete_if_exists @@ -203,8 +203,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['A', ['d', 'e']], ['B',[4, 5]], ['C',[True, False]], ['D', ['2022-01-20', '2022-01-21']]] expected = Table.new [['AA', ['a','b','c','d', 'e']], ['BB',[1,2,3,4,5]], ['CC',[True, False, False, True, False]]] - extra_another.write out (File_Format.Excel (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) + extra_another.write out (File_Format.Excel_Data (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) written.should_equal expected out.delete_if_exists @@ -213,8 +213,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['CC',[True, False]], ['BB',[4, 5]], ['AA', ['d', 'e']], ['DD', ['2022-01-20', '2022-01-21']]] expected = Table.new [['AA', ['a','b','c','d', 'e']], ['BB',[1,2,3,4,5]], ['CC',[True, False, False, True, False]]] - extra_another.write out (File_Format.Excel (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) + extra_another.write out (File_Format.Excel_Data (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) written.should_equal expected out.delete_if_exists @@ -223,8 +223,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['AA', ['d', 'e']], ['BB',[4, 5]], ['CC',[True, False]], ['DD', ['2022-01-20', '2022-01-21']]] expected = Table.new [['AA', ['a','b','c','d', 'e']], ['BB',[1,2,3,4,5]], ['CC',[True, False, False, True, False]]] - extra_another.write out (File_Format.Excel (Cell_Range "Another!A1")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) + extra_another.write out (File_Format.Excel_Data (Cell_Range "Another!A1")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) written.should_equal expected out.delete_if_exists @@ -233,8 +233,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['A', ['d', 'e']], ['B',[4, 5]], ['C',[True, False]], ['D', ['2022-01-20', '2022-01-21']]] expected = Table.new [['AA', ['a','b','c','d', 'e']], ['BB',[1,2,3,4,5]], ['CC',[True, False, False, True, False]]] - extra_another.write out (File_Format.Excel (Cell_Range "Another!A1")) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) + extra_another.write out (File_Format.Excel_Data (Cell_Range "Another!A1")) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) written.should_equal expected out.delete_if_exists @@ -243,8 +243,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['CC',[True, False]], ['BB',[4, 5]], ['AA', ['d', 'e']], ['DD', ['2022-01-20', '2022-01-21']]] expected = Table.new [['AA', ['a','b','c','d', 'e']], ['BB',[1,2,3,4,5]], ['CC',[True, False, False, True, False]]] - extra_another.write out (File_Format.Excel (Cell_Range "Another!A1")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) + extra_another.write out (File_Format.Excel_Data (Cell_Range "Another!A1")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) written.should_equal expected out.delete_if_exists @@ -253,8 +253,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['AA', ['d', 'e']], ['BB', [4, 5]], ['CC', [True, False]], ['DD', ['2022-01-20', '2022-01-21']]] expected = Table.new [['AA', ['a', 'b', 'c', 'd', 'e']], ['BB', [1, 2, 3, 4, 5]], ['CC', [True, False, False, True, False]]] - extra_another.write out (File_Format.Excel (Cell_Range "Another!A1:D6")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) + extra_another.write out (File_Format.Excel_Data (Cell_Range "Another!A1:D6")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) written.should_equal expected out.delete_if_exists @@ -263,8 +263,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['A', ['d', 'e']], ['B',[4, 5]], ['C',[True, False]], ['D', ['2022-01-20', '2022-01-21']]] expected = Table.new [['AA', ['a','b','c','d', 'e']], ['BB',[1,2,3,4,5]], ['CC',[True, False, False, True, False]]] - extra_another.write out (File_Format.Excel (Cell_Range "Another!A1:D6")) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) + extra_another.write out (File_Format.Excel_Data (Cell_Range "Another!A1:D6")) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) written.should_equal expected out.delete_if_exists @@ -273,8 +273,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['AA', ['d', 'e']], ['BB',[4, 5]], ['CC',[True, False]], ['DD', ['2022-01-20', '2022-01-21']]] expected = Table.new [['AA', ['f', 'g', 'h', 'd', 'e']], ['BB',[1, 2, 3, 4, 5]], ['CC',[True, False, False, True, False]]] - extra_another.write out (File_Format.Excel (Cell_Range "Random!K9")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Cell_Range "Random!K9")) . select_columns (By_Index [0, 1, 2]) + extra_another.write out (File_Format.Excel_Data (Cell_Range "Random!K9")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Cell_Range "Random!K9")) . select_columns (By_Index [0, 1, 2]) written.should_equal expected out.delete_if_exists @@ -283,8 +283,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['AA', ['d', 'e']], ['BB',[4, 5]], ['AA_1',[True, False]], ['BB_1', ['2022-01-20', '2022-01-21']]] expected = Table.new [['AA', ['f', 'g', 'h', 'd', 'e']], ['BB',[1, 2, 3, 4, 5]], ['AA_1',[True, False, False, True, False]]] - extra_another.write out (File_Format.Excel (Cell_Range "Random!S3")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Cell_Range "Random!S3")) . select_columns (By_Index [0, 1, 2]) + extra_another.write out (File_Format.Excel_Data (Cell_Range "Random!S3")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Cell_Range "Random!S3")) . select_columns (By_Index [0, 1, 2]) written.should_equal expected out.delete_if_exists @@ -293,8 +293,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['A', ['d', 'e']], ['B',[4, 5]], ['C',[True, False]], ['D', ['2022-01-20', '2022-01-21']]] expected = Table.new [['AA', ['f', 'g', 'h', 'd', 'e']], ['BB',[1, 2, 3, 4, 5]], ['CC',[True, False, False, True, False]]] - extra_another.write out (File_Format.Excel (Cell_Range "Random!K9")) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Cell_Range "Random!K9")) . select_columns (By_Index [0, 1, 2]) + extra_another.write out (File_Format.Excel_Data (Cell_Range "Random!K9")) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Cell_Range "Random!K9")) . select_columns (By_Index [0, 1, 2]) written.should_equal expected out.delete_if_exists @@ -303,8 +303,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['CC',[True, False]], ['BB',[4, 5]], ['AA', ['d', 'e']], ['DD', ['2022-01-20', '2022-01-21']]] expected = Table.new [['AA', ['a','b','c','d', 'e']], ['BB',[1,2,3,4,5]], ['CC',[True, False, False, True, False]]] - extra_another.write out (File_Format.Excel (Cell_Range "Another!A1:D6")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed - written = out.read (File_Format.Excel (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) + extra_another.write out (File_Format.Excel_Data (Cell_Range "Another!A1:D6")) on_existing_file=Existing_File_Behavior.Append on_problems=Report_Error . should_succeed + written = out.read (File_Format.Excel_Data (Sheet "Another")) . select_columns (By_Index [0, 1, 2]) written.should_equal expected out.delete_if_exists @@ -312,7 +312,7 @@ spec_write suffix test_sheet_name = out.delete_if_exists (enso_project.data / test_sheet_name) . copy_to out extra_another = Table.new [['CC',[True, False]], ['BB',[4, 5]], ['AA', ['d', 'e']]] - extra_another.write out (File_Format.Excel (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append . should_fail_with Column_Name_Mismatch + extra_another.write out (File_Format.Excel_Data (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append . should_fail_with Column_Name_Mismatch_Data out.delete_if_exists Test.specify 'should fail to append to a sheet by name if extra columns' <| @@ -320,7 +320,7 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out lmd = out.last_modified_time extra_another = Table.new [['CC',[True, False]], ['BB',[4, 5]], ['AA', ['d', 'e']], ['DD', ['2022-01-20', '2022-01-21']], ['EE', ['2022-01-20', '2022-01-21']]] - extra_another.write out (File_Format.Excel (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append . should_fail_with Column_Name_Mismatch + extra_another.write out (File_Format.Excel_Data (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append . should_fail_with Column_Name_Mismatch_Data out.last_modified_time.should_equal lmd out.delete_if_exists @@ -329,8 +329,8 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out lmd = out.last_modified_time extra_another = Table.new [['CC',[True, False]], ['BB',[4, 5]], ['AA', ['d', 'e']], ['DD', ['2022-01-20', '2022-01-21']], ['EE', ['2022-01-20', '2022-01-21']]] - extra_another.write out (File_Format.Excel (Sheet "NoHeaders")) on_existing_file=Existing_File_Behavior.Append . should_fail_with Illegal_Argument_Error - extra_another.write out (File_Format.Excel (Sheet "Another") False) on_existing_file=Existing_File_Behavior.Append . should_fail_with Illegal_Argument_Error + extra_another.write out (File_Format.Excel_Data (Sheet "NoHeaders")) on_existing_file=Existing_File_Behavior.Append . should_fail_with Illegal_Argument_Error_Data + extra_another.write out (File_Format.Excel_Data (Sheet "Another") False) on_existing_file=Existing_File_Behavior.Append . should_fail_with Illegal_Argument_Error_Data out.last_modified_time.should_equal lmd out.delete_if_exists @@ -339,7 +339,7 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out lmd = out.last_modified_time extra_another = Table.new [['CC',[True, False]], ['BB',[4, 5]], ['AA', ['d', 'e']]] - extra_another.write out (File_Format.Excel (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position . should_fail_with Column_Count_Mismatch + extra_another.write out (File_Format.Excel_Data (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position . should_fail_with Column_Count_Mismatch_Data out.last_modified_time.should_equal lmd out.delete_if_exists @@ -348,7 +348,7 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out lmd = out.last_modified_time extra_another = Table.new [['CC',[True, False]], ['BB',[4, 5]], ['AA', ['d', 'e']], ['DD', ['2022-01-20', '2022-01-21']], ['EE', ['2022-01-20', '2022-01-21']]] - extra_another.write out (File_Format.Excel (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position . should_fail_with Column_Count_Mismatch + extra_another.write out (File_Format.Excel_Data (Sheet "Another")) on_existing_file=Existing_File_Behavior.Append match_columns=Match_Columns.By_Position . should_fail_with Column_Count_Mismatch_Data out.last_modified_time.should_equal lmd out.delete_if_exists @@ -357,7 +357,7 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out lmd = out.last_modified_time extra_another = Table.new [['AA', ['d', 'e']], ['BB',[4, 5]], ['CC',[True, False]], ['DD', ['2022-01-20', '2022-01-21']]] - extra_another.write out (File_Format.Excel (Cell_Range "Another!A1:D5")) on_existing_file=Existing_File_Behavior.Append . should_fail_with Range_Exceeded + extra_another.write out (File_Format.Excel_Data (Cell_Range "Another!A1:D5")) on_existing_file=Existing_File_Behavior.Append . should_fail_with Range_Exceeded_Data out.last_modified_time.should_equal lmd out.delete_if_exists @@ -366,7 +366,7 @@ spec_write suffix test_sheet_name = (enso_project.data / test_sheet_name) . copy_to out lmd = out.last_modified_time extra_another = Table.new [['AA', ['d', 'e']], ['BB',[4, 5]], ['CC',[True, False]], ['DD', ['2022-01-20', '2022-01-21']]] - extra_another.write out (File_Format.Excel (Cell_Range "Random!B3")) on_existing_file=Existing_File_Behavior.Append . should_fail_with Existing_Data + extra_another.write out (File_Format.Excel_Data (Cell_Range "Random!B3")) on_existing_file=Existing_File_Behavior.Append . should_fail_with Existing_Data_Data out.last_modified_time.should_equal lmd out.delete_if_exists @@ -374,7 +374,7 @@ spec_write suffix test_sheet_name = out_bak.delete_if_exists spec = - Test.group 'Excel Range' <| + Test.group 'Excel_Data Range' <| check_range excel_range sheet_name tlbr_vector single_cell=False = excel_range.sheet_name . should_equal sheet_name excel_range.top_row . should_equal (tlbr_vector.at 0) @@ -403,66 +403,66 @@ spec = check_range (Excel_Range.from_address "Test!R1C1:R5C3") 'Test' [1, 1, 5, 3] Test.specify 'should fail gracefully for invalid patterns' <| - Excel_Range.from_address "Test!$$QA1" . should_fail_with Illegal_Argument_Error - Excel_Range.from_address "Test!BADADDRESS" . should_fail_with Illegal_Argument_Error + Excel_Range.from_address "Test!$$QA1" . should_fail_with Illegal_Argument_Error_Data + Excel_Range.from_address "Test!BADADDRESS" . should_fail_with Illegal_Argument_Error_Data Test.specify 'should allow Range creation for a cell' <| check_range (Excel_Range.for_cell "Hello World" 123 14) 'Hello World' [14, 123, 14, 123] True check_range (Excel_Range.for_cell "Hello World" "DS" 14) 'Hello World' [14, 123, 14, 123] True Excel_Range.for_cell "Test" 123 14 . address . should_equal "Test!DS14" Excel_Range.for_cell "Hello World" 123 14 . address . should_equal "'Hello World'!DS14" - Excel_Range.for_cell "Test" 20000 1 . should_fail_with Illegal_Argument_Error - Excel_Range.for_cell "Test" "ZZZ" 1 . should_fail_with Illegal_Argument_Error - Excel_Range.for_cell "Test" 0 1 . should_fail_with Illegal_Argument_Error - Excel_Range.for_cell "Test" 1 10000000 . should_fail_with Illegal_Argument_Error - Excel_Range.for_cell "Test" 1 0 . should_fail_with Illegal_Argument_Error + Excel_Range.for_cell "Test" 20000 1 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_cell "Test" "ZZZ" 1 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_cell "Test" 0 1 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_cell "Test" 1 10000000 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_cell "Test" 1 0 . should_fail_with Illegal_Argument_Error_Data Test.specify 'should allow Range creation for a range' <| check_range (Excel_Range.for_range "Hello World" 55 120 123 14) 'Hello World' [14, 55, 120, 123] check_range (Excel_Range.for_range "Hello World" "BC" 120 "DS" 14) 'Hello World' [14, 55, 120, 123] Excel_Range.for_range "Test" 55 120 123 14 . address . should_equal "Test!BC14:DS120" Excel_Range.for_range "Hello World" 55 120 123 14 . address . should_equal "'Hello World'!BC14:DS120" - Excel_Range.for_range "Test" 20000 1 123 14 . should_fail_with Illegal_Argument_Error - Excel_Range.for_range "Test" "ZZZ" 1 123 14 . should_fail_with Illegal_Argument_Error - Excel_Range.for_range "Test" 0 1 123 14 . should_fail_with Illegal_Argument_Error - Excel_Range.for_range "Test" 5 1 20000 14 . should_fail_with Illegal_Argument_Error - Excel_Range.for_range "Test" 5 1 0 14 . should_fail_with Illegal_Argument_Error - Excel_Range.for_range "Test" 5 0 123 14 . should_fail_with Illegal_Argument_Error - Excel_Range.for_range "Test" 5 10000000 123 14 . should_fail_with Illegal_Argument_Error - Excel_Range.for_range "Test" 5 1 123 0 . should_fail_with Illegal_Argument_Error - Excel_Range.for_range "Test" 5 1 123 10000000 . should_fail_with Illegal_Argument_Error + Excel_Range.for_range "Test" 20000 1 123 14 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_range "Test" "ZZZ" 1 123 14 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_range "Test" 0 1 123 14 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_range "Test" 5 1 20000 14 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_range "Test" 5 1 0 14 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_range "Test" 5 0 123 14 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_range "Test" 5 10000000 123 14 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_range "Test" 5 1 123 0 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_range "Test" 5 1 123 10000000 . should_fail_with Illegal_Argument_Error_Data Test.specify 'should allow Range creation for a column' <| check_range (Excel_Range.for_columns "Hello World" 123) 'Hello World' [Nothing, 123, Nothing, 123] check_range (Excel_Range.for_columns "Hello World" "DS") 'Hello World' [Nothing, 123, Nothing, 123] Excel_Range.for_columns "Test" 123 . address . should_equal "Test!DS" Excel_Range.for_columns "Hello World" 123 . address . should_equal "'Hello World'!DS" - Excel_Range.for_columns "Test" 20000 . should_fail_with Illegal_Argument_Error - Excel_Range.for_columns "Test" "ZZZ" . should_fail_with Illegal_Argument_Error - Excel_Range.for_columns "Test" 0 . should_fail_with Illegal_Argument_Error + Excel_Range.for_columns "Test" 20000 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_columns "Test" "ZZZ" . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_columns "Test" 0 . should_fail_with Illegal_Argument_Error_Data Test.specify 'should allow Range creation for columns' <| check_range (Excel_Range.for_columns "Hello World" "BC" 123) 'Hello World' [Nothing, 55, Nothing, 123] check_range (Excel_Range.for_columns "Hello World" 55 "DS") 'Hello World' [Nothing, 55, Nothing, 123] Excel_Range.for_columns "Test" 55 123 . address . should_equal "Test!BC:DS" Excel_Range.for_columns "Hello World" "BC" "DS" . address . should_equal "'Hello World'!BC:DS" - Excel_Range.for_columns "Test" 55 20000 . should_fail_with Illegal_Argument_Error - Excel_Range.for_columns "Test" 55 "ZZZ" . should_fail_with Illegal_Argument_Error - Excel_Range.for_columns "Test" 55 0 . should_fail_with Illegal_Argument_Error + Excel_Range.for_columns "Test" 55 20000 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_columns "Test" 55 "ZZZ" . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_columns "Test" 55 0 . should_fail_with Illegal_Argument_Error_Data Test.specify 'should allow Range creation for a row' <| check_range (Excel_Range.for_rows "Hello World" 123) 'Hello World' [123, Nothing, 123, Nothing] Excel_Range.for_rows "Test" 123 . address . should_equal "Test!123" Excel_Range.for_rows "Hello World" 123 . address . should_equal "'Hello World'!123" - Excel_Range.for_rows "Test" 20000000 . should_fail_with Illegal_Argument_Error - Excel_Range.for_rows "Test" 0 . should_fail_with Illegal_Argument_Error + Excel_Range.for_rows "Test" 20000000 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_rows "Test" 0 . should_fail_with Illegal_Argument_Error_Data Test.specify 'should allow Range creation for rows' <| check_range (Excel_Range.for_rows "Hello World" 55 123) 'Hello World' [55, Nothing, 123, Nothing] Excel_Range.for_rows "Test" 55 123 . address . should_equal "Test!55:123" Excel_Range.for_rows "Hello World" 55 123 . address . should_equal "'Hello World'!55:123" - Excel_Range.for_rows "Test" 55 20000000 . should_fail_with Illegal_Argument_Error - Excel_Range.for_rows "Test" 55 0 . should_fail_with Illegal_Argument_Error + Excel_Range.for_rows "Test" 55 20000000 . should_fail_with Illegal_Argument_Error_Data + Excel_Range.for_rows "Test" 55 0 . should_fail_with Illegal_Argument_Error_Data xlsx_sheet = enso_project.data / "TestSheet.xlsx" xlsx_path = xlsx_sheet.path @@ -496,90 +496,90 @@ spec = check_table <| File.read xls_sheet check_table <| File.read xls_path - Test.specify "should let you read the first sheet with File_Format.Excel" <| - check_table <| xlsx_sheet.read File_Format.Excel - check_table <| File.read xlsx_sheet File_Format.Excel - check_table <| File.read xlsx_path File_Format.Excel - check_table <| xls_sheet.read File_Format.Excel - check_table <| File.read xls_sheet File_Format.Excel - check_table <| File.read xls_path File_Format.Excel + Test.specify "should let you read the first sheet with File_Format.Excel_Data" <| + check_table <| xlsx_sheet.read File_Format.Excel_Data + check_table <| File.read xlsx_sheet File_Format.Excel_Data + check_table <| File.read xlsx_path File_Format.Excel_Data + check_table <| xls_sheet.read File_Format.Excel_Data + check_table <| File.read xls_sheet File_Format.Excel_Data + check_table <| File.read xls_path File_Format.Excel_Data Test.specify "should let you read the sheet names" <| sheet_names = ["Sheet1", "Another", "NoHeaders", "Random"] - xlsx_sheet.read (File_Format.Excel Sheet_Names) . should_equal sheet_names - xls_sheet.read (File_Format.Excel Sheet_Names) . should_equal sheet_names + xlsx_sheet.read (File_Format.Excel_Data Sheet_Names) . should_equal sheet_names + xls_sheet.read (File_Format.Excel_Data Sheet_Names) . should_equal sheet_names Test.specify "should let you read the range names" <| range_names = ["myData"] - xlsx_sheet.read (File_Format.Excel Range_Names) . should_equal range_names - xls_sheet.read (File_Format.Excel Range_Names) . should_equal range_names + xlsx_sheet.read (File_Format.Excel_Data Range_Names) . should_equal range_names + xls_sheet.read (File_Format.Excel_Data Range_Names) . should_equal range_names Test.specify "should let you read by sheet index" <| - table = xlsx_sheet.read (File_Format.Excel (Sheet 1)) + table = xlsx_sheet.read (File_Format.Excel_Data (Sheet 1)) check_table table - table_2 = xlsx_sheet.read (File_Format.Excel (Sheet 1 (table.length - col_a.length))) + table_2 = xlsx_sheet.read (File_Format.Excel_Data (Sheet 1 (table.length - col_a.length))) table_2.length . should_equal col_a.length check_table <| table_2 Test.specify "should let you read by sheet name" <| - table = xlsx_sheet.read (File_Format.Excel (Sheet "Sheet1")) + table = xlsx_sheet.read (File_Format.Excel_Data (Sheet "Sheet1")) check_table table - table_2 = xlsx_sheet.read (File_Format.Excel (Sheet "Sheet1" (table.length - col_a.length))) + table_2 = xlsx_sheet.read (File_Format.Excel_Data (Sheet "Sheet1" (table.length - col_a.length))) table_2.length . should_equal col_a.length check_table <| table_2 Test.specify "should let you read XLS by sheet index" <| - table = xls_sheet.read (File_Format.Excel (Sheet 1)) + table = xls_sheet.read (File_Format.Excel_Data (Sheet 1)) check_table table - table_2 = xls_sheet.read (File_Format.Excel (Sheet 1 (table.length - col_a.length))) + table_2 = xls_sheet.read (File_Format.Excel_Data (Sheet 1 (table.length - col_a.length))) table_2.length . should_equal col_a.length check_table <| table_2 Test.specify "should let you read XLS by sheet name" <| - table = xls_sheet.read (File_Format.Excel (Sheet "Sheet1")) + table = xls_sheet.read (File_Format.Excel_Data (Sheet "Sheet1")) check_table table Test.specify "should let you read by range" <| - table = xlsx_sheet.read (File_Format.Excel (Cell_Range "Sheet1!A:C")) + table = xlsx_sheet.read (File_Format.Excel_Data (Cell_Range "Sheet1!A:C")) check_table table - table_2 = xlsx_sheet.read (File_Format.Excel (Cell_Range "Sheet1!A:C" (table.length - col_a.length))) + table_2 = xlsx_sheet.read (File_Format.Excel_Data (Cell_Range "Sheet1!A:C" (table.length - col_a.length))) table_2.length . should_equal col_a.length check_table <| table_2 - check_table <| xlsx_sheet.read (File_Format.Excel (Cell_Range "Sheet1!10:13")) - check_table <| xlsx_sheet.read (File_Format.Excel (Cell_Range "Sheet1!A10:C13")) + check_table <| xlsx_sheet.read (File_Format.Excel_Data (Cell_Range "Sheet1!10:13")) + check_table <| xlsx_sheet.read (File_Format.Excel_Data (Cell_Range "Sheet1!A10:C13")) Test.specify "should let you read by range name" <| - table = xlsx_sheet.read (File_Format.Excel (Cell_Range "myData")) + table = xlsx_sheet.read (File_Format.Excel_Data (Cell_Range "myData")) table.length . should_equal col_a.length check_table <| table Test.specify "should let you restrict number of rows read and skip rows" <| - table = xlsx_sheet.read (File_Format.Excel (Sheet "Sheet1")) + table = xlsx_sheet.read (File_Format.Excel_Data (Sheet "Sheet1")) check_table table - table_2 = xlsx_sheet.read (File_Format.Excel (Sheet "Sheet1" (table.length - col_a.length))) + table_2 = xlsx_sheet.read (File_Format.Excel_Data (Sheet "Sheet1" (table.length - col_a.length))) table_2.length . should_equal col_a.length check_table <| table_2 - table_3 = xlsx_sheet.read (File_Format.Excel (Sheet "Sheet1" (table.length - col_a.length) 2)) + table_3 = xlsx_sheet.read (File_Format.Excel_Data (Sheet "Sheet1" (table.length - col_a.length) 2)) table_3.length . should_equal 2 - table_4 = xlsx_sheet.read (File_Format.Excel (Sheet "Sheet1" row_limit=6)) + table_4 = xlsx_sheet.read (File_Format.Excel_Data (Sheet "Sheet1" row_limit=6)) table_4.length . should_equal 6 Test.group "Problems" <| Test.specify "should handle non-existing file gracefully" <| bad_file = enso_project.data / "DoesNotExists.xlsx" - bad_file.read (File_Format.Excel (Cell_Range "Sheet1!A:C")) . should_fail_with File.File_Not_Found + bad_file.read (File_Format.Excel_Data (Cell_Range "Sheet1!A:C")) . should_fail_with File.File_Not_Found Test.specify "should handle wrong xls_format gracefully" <| - xlsx_sheet.read (File_Format.Excel (Cell_Range "Sheet1!A:C") xls_format=True) . should_fail_with File.IO_Error - xls_sheet.read (File_Format.Excel (Cell_Range "Sheet1!A:C") xls_format=False) . should_fail_with File.IO_Error + xlsx_sheet.read (File_Format.Excel_Data (Cell_Range "Sheet1!A:C") xls_format=True) . should_fail_with File.IO_Error + xls_sheet.read (File_Format.Excel_Data (Cell_Range "Sheet1!A:C") xls_format=False) . should_fail_with File.IO_Error spec_fmt 'XLSX reading' Examples.xlsx .read @@ -595,42 +595,42 @@ spec = table.at (col_names.at idx) . to_vector . should_equal values Test.specify "Simple table" <| - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!A1"))) ["AA", "BB"] [[1,2,3,4,5,6], ["A","B","C","D","E","F"]] - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!A2"))) ["A", "B"] [[1,2,3,4,5,6], ["A","B","C","D","E","F"]] - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!A1:A1"))) ["A"] [["AA"]] - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!B1"))) ["B"] [["BB", "A","B","C","D","E","F"]] - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!B1") headers=True)) ["BB"] [["A","B","C","D","E","F"]] - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!B2"))) ["B"] [["A","B","C","D","E","F"]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!A1"))) ["AA", "BB"] [[1,2,3,4,5,6], ["A","B","C","D","E","F"]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!A2"))) ["A", "B"] [[1,2,3,4,5,6], ["A","B","C","D","E","F"]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!A1:A1"))) ["A"] [["AA"]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!B1"))) ["B"] [["BB", "A","B","C","D","E","F"]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!B1") headers=True)) ["BB"] [["A","B","C","D","E","F"]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!B2"))) ["B"] [["A","B","C","D","E","F"]] Test.specify "Patchy table" <| - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!D1"))) ["A", "B", "Column_1"] [[1,2,4], [4,4,Nothing], [6,Nothing,6]] - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!D2"))) ["D", "E", "F"] [[1,2,4], [4,4,Nothing], [6,Nothing,6]] - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!E"))) ["B"] [[4,4,Nothing,Nothing,Nothing,Nothing]] - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!E1"))) ["B", "Column_1"] [[4,4,Nothing], [6,Nothing,6]] - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!E2"))) ["E", "F"] [[4,4,Nothing], [6,Nothing,6]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!D1"))) ["A", "B", "Column_1"] [[1,2,4], [4,4,Nothing], [6,Nothing,6]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!D2"))) ["D", "E", "F"] [[1,2,4], [4,4,Nothing], [6,Nothing,6]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!E"))) ["B"] [[4,4,Nothing,Nothing,Nothing,Nothing]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!E1"))) ["B", "Column_1"] [[4,4,Nothing], [6,Nothing,6]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!E2"))) ["E", "F"] [[4,4,Nothing], [6,Nothing,6]] Test.specify "Single cell" <| - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!H1"))) ["H"] [["Single Cell"]] - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!H2"))) ["H"] [[]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!H1"))) ["H"] [["Single Cell"]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!H2"))) ["H"] [[]] Test.specify "Single line" <| - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!J1"))) ["J", "K", "L"] [["Just"],["Some"],["Headers"]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!J1"))) ["J", "K", "L"] [["Just"],["Some"],["Headers"]] Test.specify "Growing table" <| - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!N1"))) ["A", "Full", "Table", "Column_1"] [["Hello","World",Nothing,"Extend"],[1,Nothing,"Gap",3],[2,2,"Here",5],[Nothing,Nothing,"To","Hello"]] - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!O1"))) ["Full", "Table", "Column_1"] [[1,Nothing,"Gap",3],[2,2,"Here",5],[Nothing,Nothing,"To","Hello"]] - check_table (file.read (File_Format.Excel (Cell_Range "Sheet1!O2"))) ["O", "P", "Q"] [[1,Nothing,"Gap",3],[2,2,"Here",5],[Nothing,Nothing,"To","Hello"]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!N1"))) ["A", "Full", "Table", "Column_1"] [["Hello","World",Nothing,"Extend"],[1,Nothing,"Gap",3],[2,2,"Here",5],[Nothing,Nothing,"To","Hello"]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!O1"))) ["Full", "Table", "Column_1"] [[1,Nothing,"Gap",3],[2,2,"Here",5],[Nothing,Nothing,"To","Hello"]] + check_table (file.read (File_Format.Excel_Data (Cell_Range "Sheet1!O2"))) ["O", "P", "Q"] [[1,Nothing,"Gap",3],[2,2,"Here",5],[Nothing,Nothing,"To","Hello"]] Test.specify "Should handle invalid headers with warnings" <| - action = file.read (File_Format.Excel (Cell_Range "Sheet1!D1")) on_problems=_ + action = file.read (File_Format.Excel_Data (Cell_Range "Sheet1!D1")) on_problems=_ tester = check_table _ ["A", "B", "Column_1"] [[1,2,4], [4,4,Nothing], [6,Nothing,6]] - problems = [Invalid_Output_Column_Names [""]] + problems = [Invalid_Output_Column_Names_Data [""]] Problems.test_problem_handling action problems tester Test.specify "Should handle duplicate headers with warnings" <| - action = file.read (File_Format.Excel (Cell_Range "Sheet1!S1")) on_problems=_ + action = file.read (File_Format.Excel_Data (Cell_Range "Sheet1!S1")) on_problems=_ tester = check_table _ ["DD", "DD_1"] [[1,3], [2,4]] - problems = [Duplicate_Output_Column_Names ["DD"]] + problems = [Duplicate_Output_Column_Names_Data ["DD"]] Problems.test_problem_handling action problems tester spec_write "xlsx" 'TestSheet.xlsx' diff --git a/test/Table_Tests/src/File_Read_Spec.enso b/test/Table_Tests/src/File_Read_Spec.enso index 255202c2a89a..4a41c16f53ae 100644 --- a/test/Table_Tests/src/File_Read_Spec.enso +++ b/test/Table_Tests/src/File_Read_Spec.enso @@ -2,7 +2,7 @@ from Standard.Base import all import Standard.Table.IO.File_Read import Standard.Table.IO.File_Format -from Standard.Table.Errors import Unsupported_File_Type +from Standard.Table.Errors import Unsupported_File_Type_Data import Standard.Test import Standard.Test.Problems @@ -14,21 +14,21 @@ spec = Test.group "File_Format.Auto materialise" <| Test.specify "should be Bytes for unknown file" <| - File_Format.Auto . materialise sample_xxx . should_fail_with Unsupported_File_Type + File_Format.Auto . materialise sample_xxx . should_fail_with Unsupported_File_Type_Data Test.specify "should be Text for text file" <| - File_Format.Auto . materialise sample_txt . should_be_a File_Format.Plain_Text + File_Format.Auto . materialise sample_txt . should_be_a File_Format.Plain_Text_Data Test.specify "should be Text for log file" <| - File_Format.Auto . materialise windows_log . should_be_a File_Format.Plain_Text + File_Format.Auto . materialise windows_log . should_be_a File_Format.Plain_Text_Data Test.specify "should detect CSV files" <| - File_Format.Auto . materialise (enso_project.data / "data.csv") . should_equal (File_Format.Delimited ",") + File_Format.Auto . materialise (enso_project.data / "data.csv") . should_equal (File_Format.Delimited_Data ",") Test.group "File_Format.Auto" <| Test.specify "should raise an error when reading an unknown file" <| bytes = sample_xxx.read - bytes.should_fail_with Unsupported_File_Type + bytes.should_fail_with Unsupported_File_Type_Data Test.specify "should be able to read a text file" <| content = sample_txt.read @@ -50,17 +50,17 @@ spec = Test.group "File_Format.Plain_Text" <| Test.specify "should be able to read a file as Text" <| - text = sample_xxx.read File_Format.Plain_Text + text = sample_xxx.read File_Format.Plain_Text_Data text.should_equal "Hello World!" Test.specify "should be able to read a file as Text with Encoding" <| - text = windows_log.read (File_Format.Plain_Text Encoding.windows_1252) + text = windows_log.read (File_Format.Plain_Text_Data Encoding.windows_1252) text.should_equal "Hello World! $¢¤¥" Test.specify "should raise a warning when invalid encoding in a Text file" <| - action = windows_log.read (File_Format.Plain_Text Encoding.ascii) on_problems=_ + action = windows_log.read (File_Format.Plain_Text_Data Encoding.ascii) on_problems=_ tester result = result . should_equal 'Hello World! $\uFFFD\uFFFD\uFFFD' - problems = [Encoding_Error "Encoding issues at 14, 15, 16."] + problems = [Encoding_Error_Data "Encoding issues at 14, 15, 16."] Problems.test_problem_handling action problems tester main = Test.Suite.run_main spec diff --git a/test/Table_Tests/src/In_Memory_Tests.enso b/test/Table_Tests/src/In_Memory_Tests.enso index 07d4d9aa6b50..97a4738cc054 100644 --- a/test/Table_Tests/src/In_Memory_Tests.enso +++ b/test/Table_Tests/src/In_Memory_Tests.enso @@ -6,7 +6,7 @@ import project.Column_Spec import project.Csv_Spec import project.Delimited_Read_Spec import project.Delimited_Write_Spec -#import project.Excel_Spec +import project.Excel_Spec #import project.Json_Spec #import project.Table_Spec #import project.Table_Date_Spec @@ -18,7 +18,7 @@ in_memory_spec = Csv_Spec.spec Delimited_Read_Spec.spec Delimited_Write_Spec.spec - #Excel_Spec.spec + Excel_Spec.spec #Json_Spec.spec #Table_Spec.spec #Table_Date_Spec.spec From 010abe47b02e76c827ebb821dc5ba1c1fdf2304f Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 23 Aug 2022 13:59:50 +0200 Subject: [PATCH 060/110] progress --- .../src/Data/Internal/Aggregate_Helper.enso | 6 +- .../Database/0.0.0-dev/src/Data/Sql.enso | 2 +- .../Database/0.0.0-dev/src/Data/Table.enso | 8 +- .../src/Data/Column_Name_Mapping.enso | 2 +- .../0.0.0-dev/src/Data/Column_Selector.enso | 2 +- .../src/Data/Sort_Column_Selector.enso | 2 +- .../Table/0.0.0-dev/src/Data/Table.enso | 6 +- .../src/Internal/Problem_Builder.enso | 12 +- .../0.0.0-dev/src/Internal/Table_Helpers.enso | 31 +-- .../Standard/Table/0.0.0-dev/src/Main.enso | 9 +- .../node/expression/atom/GetFieldNode.java | 12 +- test/Table_Tests/src/Common_Table_Spec.enso | 189 +++++++++--------- test/Table_Tests/src/In_Memory_Tests.enso | 8 +- test/Table_Tests/src/Table_Spec.enso | 39 ++-- 14 files changed, 171 insertions(+), 157 deletions(-) diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Aggregate_Helper.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Aggregate_Helper.enso index 11391cf35fae..14d7b1e6f1d6 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Aggregate_Helper.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Aggregate_Helper.enso @@ -1,5 +1,5 @@ from Standard.Base import all -from Standard.Base.Data.Text.Text_Ordering import Text_Ordering +from Standard.Base.Data.Text.Text_Ordering import Text_Ordering_Data from Standard.Table.Data.Aggregate_Column import all import Standard.Database.Data.Internal.IR @@ -40,14 +40,14 @@ make_expression aggregate dialect = First c _ ignore_nothing order_by -> case is_non_empty_selector order_by of False -> Error.throw (Unsupported_Database_Operation_Error "`First` aggregation requires at least one `order_by` column.") True -> - order_bys = order_by.columns.map c-> dialect.prepare_order_descriptor c.column.as_internal c.direction Text_Ordering + order_bys = order_by.columns.map c-> dialect.prepare_order_descriptor c.column.as_internal c.direction Text_Ordering_Data case ignore_nothing of False -> IR.Operation "FIRST" [c.expression]+order_bys True -> IR.Operation "FIRST_NOT_NULL" [c.expression]+order_bys Last c _ ignore_nothing order_by -> case is_non_empty_selector order_by of False -> Error.throw (Unsupported_Database_Operation_Error "`Last` aggregation requires at least one `order_by` column.") True -> - order_bys = order_by.columns.map c-> dialect.prepare_order_descriptor c.column.as_internal c.direction Text_Ordering + order_bys = order_by.columns.map c-> dialect.prepare_order_descriptor c.column.as_internal c.direction Text_Ordering_Data case ignore_nothing of False -> IR.Operation "LAST" [c.expression]+order_bys True -> IR.Operation "LAST_NOT_NULL" [c.expression]+order_bys diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Sql.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Sql.enso index 80327c5a2088..14f300b6823b 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Sql.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Sql.enso @@ -152,7 +152,7 @@ type Sql_Type match more possible types. is_likely_text : Boolean is_likely_text self = - self.is_definitely_text || self.name.contains "text" (Text_Matcher Case_Insensitive) + self.is_definitely_text || self.name.contains "text" (Text_Matcher_Data Case_Insensitive_Data) ## UNSTABLE diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso index e373f572dc31..ef33e0525c67 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso @@ -18,7 +18,7 @@ from Standard.Database.Data.Column import Column, Aggregate_Column_Builder from Standard.Database.Data.Internal.IR import Internal_Column from Standard.Table.Data.Table import No_Such_Column_Error from Standard.Table.Data.Column_Selector import Column_Selector, By_Index -from Standard.Base.Data.Text.Text_Ordering import Text_Ordering +from Standard.Base.Data.Text.Text_Ordering import Text_Ordering_Data from Standard.Table.Data.Data_Formatter import Data_Formatter from Standard.Base.Error.Problem_Behavior import Problem_Behavior, Report_Warning from Standard.Database.Error import Unsupported_Database_Operation_Error @@ -266,14 +266,14 @@ type Table > Example Sort columns according to the natural case-insensitive ordering. - table.sort_columns text_ordering=(Text_Ordering sort_digits_as_numbers=True case_sensitive=Case_Insensitive) + table.sort_columns text_ordering=(Text_Ordering_Data sort_digits_as_numbers=True case_sensitive=Case_Insensitive) > Example Sort columns in descending order. table.reorder_columns Sort_Direction.Descending sort_columns : Sort_Direction -> Text_Ordering -> Table - sort_columns self direction=Sort_Direction.Ascending text_ordering=Text_Ordering = + sort_columns self direction=Sort_Direction.Ascending text_ordering=Text_Ordering_Data = new_columns = Table_Helpers.sort_columns internal_columns=self.internal_columns direction text_ordering self.updated_columns new_columns @@ -506,7 +506,7 @@ type Table table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name 'Quantity', Sort_Column.Name 'Rating' Sort_Direction.Descending]) order_by : Sort_Column_Selector -> Text_Ordering -> Problem_Behavior -> Table - order_by self (columns = (Sort_Column_Selector.By_Name [(Sort_Column.Name (self.columns.at 0 . name))])) text_ordering=Text_Ordering on_problems=Report_Warning = Panic.handle_wrapped_dataflow_error <| + order_by self (columns = (Sort_Column_Selector.By_Name [(Sort_Column.Name (self.columns.at 0 . name))])) text_ordering=Text_Ordering_Data on_problems=Report_Warning = Panic.handle_wrapped_dataflow_error <| problem_builder = Problem_Builder.new columns_for_ordering = Table_Helpers.prepare_order_by self.columns columns problem_builder problem_builder.attach_problems_before on_problems <| diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Name_Mapping.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Name_Mapping.enso index 8f3eb590bbb6..821bf2084f3e 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Name_Mapping.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Name_Mapping.enso @@ -9,7 +9,7 @@ type Column_Name_Mapping The `matcher` can be used to specify if the names should be matched exactly or should be treated as regular expressions. It also allows to specify if the matching should be case-sensitive. - By_Name (names : Map Text Text) (matcher : Matcher = Text_Matcher) + By_Name (names : Map Text Text) (matcher : Matcher = Text_Matcher_Data) ## Selects columns by their index. diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Selector.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Selector.enso index 7c74ba158939..e01c82e14432 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Selector.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column_Selector.enso @@ -9,7 +9,7 @@ type Column_Selector The `matcher` can be used to specify if the names should be matched exactly or should be treated as regular expressions. It also allows to specify if the matching should be case-sensitive. - By_Name (names : Vector Text) (matcher : Matcher = Text_Matcher) + By_Name (names : Vector Text) (matcher : Matcher = Text_Matcher_Data) ## Selects columns by their index. diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Sort_Column_Selector.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Sort_Column_Selector.enso index c5c932a77afc..0d1fc4763ed0 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Sort_Column_Selector.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Sort_Column_Selector.enso @@ -3,6 +3,6 @@ from Standard.Base import all import Standard.Table.Data.Sort_Column type Sort_Column_Selector - By_Name (columns : Vector Sort_Column.Name) (matcher:Matcher=Text_Matcher) + By_Name (columns : Vector Sort_Column.Name) (matcher:Matcher=Text_Matcher_Data) By_Index (columns : Vector Sort_Column.Index) By_Column (columns : Vector Sort_Column.Column) diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso index f7ce738f4734..de711954345e 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso @@ -424,14 +424,14 @@ type Table > Example Sort columns according to the natural case-insensitive ordering. - table.sort_columns text_ordering=(Text_Ordering sort_digits_as_numbers=True case_sensitive=Case_Insensitive) + table.sort_columns text_ordering=(Text_Ordering_Data sort_digits_as_numbers=True case_sensitive=Case_Insensitive) > Example Sort columns in descending order. table.reorder_columns Sort_Direction.Descending sort_columns : Sort_Direction -> Text_Ordering -> Table - sort_columns self direction=Sort_Direction.Ascending text_ordering=Text_Ordering = + sort_columns self direction=Sort_Direction.Ascending text_ordering=Text_Ordering_Data = new_columns = Table_Helpers.sort_columns internal_columns=self.columns direction text_ordering new new_columns @@ -609,7 +609,7 @@ type Table table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "total_stock", Sort_Column.Name "sold_stock" Sort_Direction.Descending]) order_by : Sort_Column_Selector -> Text_Ordering -> Problem_Behavior -> Table - order_by self (columns = (Sort_Column_Selector.By_Name [(Sort_Column.Name (self.columns.at 0 . name))])) text_ordering=Text_Ordering on_problems=Report_Warning = + order_by self (columns = (Sort_Column_Selector.By_Name [(Sort_Column.Name (self.columns.at 0 . name))])) text_ordering=Text_Ordering_Data on_problems=Report_Warning = problem_builder = Problem_Builder.new columns_for_ordering = Table_Helpers.prepare_order_by self.columns columns problem_builder problem_builder.attach_problems_before on_problems <| diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Problem_Builder.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Problem_Builder.enso index cb95848e9abb..fb20e40d152a 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Problem_Builder.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Problem_Builder.enso @@ -4,7 +4,7 @@ from Standard.Base.Error.Problem_Behavior import Problem_Behavior, Report_Warnin import Standard.Base.Runtime.Ref import Standard.Table.Internal.Vector_Builder -from Standard.Table.Errors import Missing_Input_Columns, Column_Indexes_Out_Of_Range, No_Output_Columns, Duplicate_Column_Selectors, Input_Indices_Already_Matched, Too_Many_Column_Names_Provided, Duplicate_Output_Column_Names, Invalid_Output_Column_Names, Column_Matched_By_Multiple_Selectors +from Standard.Table.Errors import Missing_Input_Columns_Data, Column_Indexes_Out_Of_Range_Data, No_Output_Columns, Duplicate_Column_Selectors_Data, Input_Indices_Already_Matched_Data, Too_Many_Column_Names_Provided, Duplicate_Output_Column_Names, Invalid_Output_Column_Names, Column_Matched_By_Multiple_Selectors_Data type Problem_Builder Problem_Builder_Data oob_indices duplicate_column_selectors input_indices_already_matched missing_input_columns other @@ -22,7 +22,7 @@ type Problem_Builder append_to_ref self.missing_input_columns columns report_column_matched_by_multiple_selectors self column_name selectors = - self.report_other_warning (Column_Matched_By_Multiple_Selectors column_name selectors) + self.report_other_warning (Column_Matched_By_Multiple_Selectors_Data column_name selectors) report_other_warning self warning = self.other.append warning @@ -36,10 +36,10 @@ type Problem_Builder if vec.not_empty then problems.append (problem_creator vec) - build_vector_and_append self.oob_indices Column_Indexes_Out_Of_Range - build_vector_and_append self.duplicate_column_selectors Duplicate_Column_Selectors - build_vector_and_append self.input_indices_already_matched Input_Indices_Already_Matched - build_vector_and_append self.missing_input_columns Missing_Input_Columns + build_vector_and_append self.oob_indices Column_Indexes_Out_Of_Range_Data + build_vector_and_append self.duplicate_column_selectors Duplicate_Column_Selectors_Data + build_vector_and_append self.input_indices_already_matched Input_Indices_Already_Matched_Data + build_vector_and_append self.missing_input_columns Missing_Input_Columns_Data self.other.to_vector.each problems.append problems.to_vector diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Table_Helpers.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Table_Helpers.enso index d7f0c703fff6..0d07eaa0caff 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Table_Helpers.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Table_Helpers.enso @@ -6,7 +6,7 @@ import Standard.Base.Data.Ordering.Vector_Lexicographic_Order from Standard.Base.Data.Text.Text_Ordering import Text_Ordering from Standard.Base.Error.Problem_Behavior import Problem_Behavior, Report_Warning import Standard.Table.Data.Position -from Standard.Table.Errors import Missing_Input_Columns, Column_Indexes_Out_Of_Range, No_Output_Columns, Duplicate_Column_Selectors, Input_Indices_Already_Matched, Too_Many_Column_Names_Provided, Duplicate_Output_Column_Names, Invalid_Output_Column_Names, No_Input_Columns_Selected +from Standard.Table.Errors import Missing_Input_Columns_Data, No_Output_Columns, Too_Many_Column_Names_Provided_Data, Duplicate_Output_Column_Names_Data, Invalid_Output_Column_Names_Data, No_Input_Columns_Selected from Standard.Table.Data.Column_Selector import Column_Selector, By_Name, By_Index, By_Column import Standard.Table.Data.Column_Name_Mapping import Standard.Table.Internal.Unique_Name_Strategy @@ -158,7 +158,7 @@ rename_columns internal_columns mapping on_problems = new_names mapped = case mapping of - Column_Name_Mapping.By_Column vec -> name_mapper (vec.map r-> [r.at 0 . name, r.at 1]) (Text_Matcher case_sensitive=True) + Column_Name_Mapping.By_Column vec -> name_mapper (vec.map r-> [r.at 0 . name, r.at 1]) (Text_Matcher_Data case_sensitive=True) Column_Name_Mapping.By_Name map ms -> name_mapper map.to_vector ms Column_Name_Mapping.By_Index map -> good_indices = validate_indices col_count map.keys problem_builder @@ -173,7 +173,7 @@ rename_columns internal_columns mapping on_problems = Column_Name_Mapping.By_Position vec -> good_names = case vec.length > col_count of True -> - problem_builder.report_other_warning (Too_Many_Column_Names_Provided (vec.drop_start col_count)) + problem_builder.report_other_warning (Too_Many_Column_Names_Provided_Data (vec.drop_start col_count)) vec.take_start col_count False -> vec @@ -185,9 +185,9 @@ rename_columns internal_columns mapping on_problems = n.if_nothing (unique.make_unique (internal_columns.at i).name) if unique.invalid_names.not_empty then - problem_builder.report_other_warning (Invalid_Output_Column_Names unique.invalid_names) + problem_builder.report_other_warning (Invalid_Output_Column_Names_Data unique.invalid_names) if unique.renames.not_empty then - problem_builder.report_other_warning (Duplicate_Output_Column_Names unique.renames) + problem_builder.report_other_warning (Duplicate_Output_Column_Names_Data unique.renames) problem_builder.attach_problems_before on_problems processed @@ -247,7 +247,7 @@ select_columns_helper internal_columns selector reorder problem_builder = case s select_indices_preserving_order internal_columns good_indices By_Column columns -> column_names = columns.map .name - new_selector = By_Name column_names (Text_Matcher case_sensitive=True) + new_selector = By_Name column_names (Text_Matcher_Data case_sensitive=True) select_columns_helper internal_columns new_selector reorder=reorder problem_builder=problem_builder ## PRIVATE @@ -256,7 +256,7 @@ select_columns_helper internal_columns selector reorder problem_builder = case s resolve_column_helper : Vector a -> (Integer | Text | Column) -> Problem_Builder -> a | Nothing resolve_column_helper internal_columns selector problem_builder = case selector of Text -> - matched_columns = Matching.match_criteria_callback (Text_Matcher case_sensitive=True) internal_columns [selector] reorder=True name_mapper=(_.name) problem_callback=problem_builder.report_missing_input_columns + matched_columns = Matching.match_criteria_callback (Text_Matcher_Data case_sensitive=True) internal_columns [selector] reorder=True name_mapper=(_.name) problem_callback=problem_builder.report_missing_input_columns if matched_columns.length == 1 then matched_columns.first else if matched_columns.length == 0 then Nothing else Panic.throw (Illegal_State_Error "A single exact match should never match more than one column. Perhaps the table breaks the invariant of unique column names?") @@ -273,7 +273,7 @@ resolve_column_helper internal_columns selector problem_builder = case selector Converts the generic `No_Matches_Found` error to a more specific `Missing_Input_Columns`. Any other errors are returned as-is. promote_no_matches_to_missing_columns error = case error of - Matching.No_Matches_Found_Data criteria -> Maybe.Some <| Missing_Input_Columns criteria + Matching.No_Matches_Found_Data criteria -> Maybe.Some <| Missing_Input_Columns_Data criteria _ -> Nothing ## PRIVATE @@ -358,7 +358,8 @@ validate_unique vector problem_callback on=(x->x) = ## PRIVATE A helper type used by transform helpers. -type Column_Transform_Element column associated_selector +type Column_Transform_Element + Column_Transform_Element_Data column associated_selector ## PRIVATE prepare_order_by : Vector -> Problem_Builder -> Vector Column_Transform_Element @@ -426,7 +427,7 @@ transform_columns_by_index internal_columns index_selectors problem_builder inde selectors_map = Map.from_vector good_indices internal_columns.map_with_index i-> column-> associated_selector = selectors_map.get_or_else i Nothing - Column_Transform_Element column associated_selector + Column_Transform_Element_Data column associated_selector ## PRIVATE A helper function which can be used by methods that transform a subset of @@ -450,7 +451,7 @@ transform_columns_by_column_reference internal_columns column_selectors problem_ name_extractor = selector-> column = column_extractor selector column.name - transform_columns_by_name internal_columns column_selectors (Text_Matcher case_sensitive=True) problem_builder name_extractor + transform_columns_by_name internal_columns column_selectors (Text_Matcher_Data case_sensitive=True) problem_builder name_extractor ## PRIVATE A helper function which can be used by methods that select a subset of @@ -484,8 +485,8 @@ select_columns_by_name internal_columns name_selectors matcher problem_builder n problem_builder.report_column_matched_by_multiple_selectors column.name matching_selectors associated_selector_index = matching_selector_indices.first associated_selector = name_selectors.at associated_selector_index - element = Column_Transform_Element column associated_selector - results.append (Pair element [associated_selector_index, i]) + element = Column_Transform_Element_Data column associated_selector + results.append (Pair_Data element [associated_selector_index, i]) # We sort the results by the associated selector index, breaking ties by the column index. sorted = results.to_vector.sort on=(_.second) by=Vector_Lexicographic_Order.compare sorted.map .first @@ -511,7 +512,7 @@ select_columns_by_index : Vector -> Vector -> Problem_Builder -> (Any -> Integer select_columns_by_index internal_columns index_selectors problem_builder index_extractor = good_selectors = validate_indices internal_columns.length index_selectors problem_builder index_extractor good_selectors.map pair-> - Column_Transform_Element (internal_columns.at pair.first) pair.second + Column_Transform_Element_Data (internal_columns.at pair.first) pair.second ## PRIVATE A helper function which can be used by methods that select a subset of @@ -536,4 +537,4 @@ select_columns_by_column_reference internal_columns column_selectors problem_bui name_extractor = selector-> column = column_extractor selector column.name - select_columns_by_name internal_columns column_selectors (Text_Matcher case_sensitive=True) problem_builder name_extractor + select_columns_by_name internal_columns column_selectors (Text_Matcher_Data case_sensitive=True) problem_builder name_extractor diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso index f7e31cb22fb7..c24aa4d6eb99 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso @@ -49,7 +49,7 @@ from Standard.Table.Data.Table export new, from_rows, join, concat, No_Such_Colu headers = Examples.simple_table_json_headers json.to_table headers Json.Json.to_table : Vector -> Table -Json.Json.to_table self fields = case self of +Json.Json.to_table self fields=Nothing = case self of Json.Array items -> rows = items.map item-> case item of Json.Object fs -> @@ -60,7 +60,7 @@ Json.Json.to_table self fields = case self of [n, rows.map (_.at i)] Table.new cols Json.Object _ -> - if self.get_type != Geo_Json.Feature_Collection.to_text then Error.throw (Invalid_Format_Error self "not being a feature collection") else + if self.get_type != Geo_Json.Feature_Collection.to_text then Error.throw (Invalid_Format_Error_Data self "not being a feature collection") else case self.get "features" of Json.Array items -> feature_rows = items.map .get_feature_row @@ -77,13 +77,14 @@ Json.Json.to_table self fields = case self of [n, rows.map (_.at i)] Table.new cols - _ -> Error.throw (Invalid_Format_Error self "not having the 'features' key.") + _ -> Error.throw (Invalid_Format_Error_Data self "not having the 'features' key.") ## UNSTABLE An error representing an invalid format for conversion. -type Invalid_Format_Error input message +type Invalid_Format_Error + Invalid_Format_Error_Data input message ## UNSTABLE diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldNode.java index 89ce4d12d6d1..8ec74b8ed9fe 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldNode.java @@ -4,9 +4,11 @@ import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.NodeInfo; import com.oracle.truffle.api.nodes.RootNode; +import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.callable.atom.Atom; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.Type; +import org.enso.interpreter.runtime.error.PanicException; import org.enso.interpreter.runtime.state.Stateful; @NodeInfo(shortName = "get_field", description = "A base for auto-generated Atom getters.") @@ -36,7 +38,15 @@ public GetFieldNode(TruffleLanguage language, int index, Type type, String na * @return the field value at predefined index */ public Stateful execute(VirtualFrame frame) { - Atom atom = (Atom) Function.ArgumentsHelper.getPositionalArguments(frame.getArguments())[0]; + if (!(Function.ArgumentsHelper.getPositionalArguments(frame.getArguments())[0] instanceof Atom atom)) { + var msg = Function.ArgumentsHelper.getPositionalArguments(frame.getArguments())[0]; + throw new PanicException( + Context.get(this) + .getBuiltins() + .error() + .makeInexhaustivePatternMatchError(msg), + this); + } Object state = Function.ArgumentsHelper.getState(frame.getArguments()); return new Stateful(state, atom.getFields()[index]); } diff --git a/test/Table_Tests/src/Common_Table_Spec.enso b/test/Table_Tests/src/Common_Table_Spec.enso index 4c602ff119b1..7f324f080715 100644 --- a/test/Table_Tests/src/Common_Table_Spec.enso +++ b/test/Table_Tests/src/Common_Table_Spec.enso @@ -10,7 +10,8 @@ import Standard.Table.Data.Sort_Column import Standard.Test import Standard.Test.Problems -type Test_Selection supports_case_sensitive_columns=True order_by=True natural_ordering=False case_insensitive_ordering=True order_by_unicode_normalization_by_default=False case_insensitive_ascii_only=False +type Test_Selection + Test_Selection_Data supports_case_sensitive_columns=True order_by=True natural_ordering=False case_insensitive_ordering=True order_by_unicode_normalization_by_default=False case_insensitive_ascii_only=False ## A common test suite for shared operations on the Table API. @@ -50,7 +51,7 @@ spec prefix table_builder test_selection pending=Nothing = Test.group prefix+"Table.select_columns" pending=pending <| Test.specify "should work as shown in the doc examples" <| expect_column_names ["foo", "bar"] <| table.select_columns (By_Name ["bar", "foo"]) - expect_column_names ["bar", "Baz", "foo_1", "foo_2"] <| table.select_columns (By_Name ["foo.+", "b.*"] (Regex_Matcher case_sensitive=Case_Insensitive)) + expect_column_names ["bar", "Baz", "foo_1", "foo_2"] <| table.select_columns (By_Name ["foo.+", "b.*"] (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data)) expect_column_names ["abcd123", "foo", "bar"] <| table.select_columns (By_Index [-1, 0, 1]) reorder=True column1 = table.at "foo_1" @@ -64,11 +65,11 @@ spec prefix table_builder test_selection pending=Nothing = table_2 . at "foo" . to_vector . should_equal [1,2,3] Test.specify "should correctly handle regex matching" <| - expect_column_names ["foo"] <| table.select_columns (By_Name ["foo"] Regex_Matcher) - expect_column_names ["ab.+123", "abcd123"] <| table.select_columns (By_Name ["a.*"] Regex_Matcher) - expect_column_names ["ab.+123", "abcd123"] <| table.select_columns (By_Name ["ab.+123"] Regex_Matcher) + expect_column_names ["foo"] <| table.select_columns (By_Name ["foo"] Regex_Matcher_Data) + expect_column_names ["ab.+123", "abcd123"] <| table.select_columns (By_Name ["a.*"] Regex_Matcher_Data) + expect_column_names ["ab.+123", "abcd123"] <| table.select_columns (By_Name ["ab.+123"] Regex_Matcher_Data) expect_column_names ["ab.+123"] <| table.select_columns (By_Name ["ab.+123"]) - expect_column_names ["abcd123"] <| table.select_columns (By_Name ["abcd123"] Regex_Matcher) + expect_column_names ["abcd123"] <| table.select_columns (By_Name ["abcd123"] Regex_Matcher_Data) Test.specify "should allow negative indices" <| expect_column_names ["foo", "bar", "foo_2"] <| table.select_columns (By_Index [-3, 0, 1]) @@ -80,52 +81,52 @@ spec prefix table_builder test_selection pending=Nothing = col2 = ["bar", [4,5,6]] col3 = ["Bar", [7,8,9]] table_builder [col1, col2, col3] - expect_column_names ["bar", "Bar"] <| table.select_columns (By_Name ["bar"] (Text_Matcher Case_Insensitive)) + expect_column_names ["bar", "Bar"] <| table.select_columns (By_Name ["bar"] (Text_Matcher_Data Case_Insensitive_Data)) Test.specify "should correctly handle regexes matching multiple names" <| - expect_column_names ["foo", "bar", "foo_1", "foo_2"] <| table.select_columns (By_Name ["b.*", "f.+"] Regex_Matcher) - expect_column_names ["bar", "foo", "foo_1", "foo_2"] <| table.select_columns (By_Name ["b.*", "f.+"] Regex_Matcher) reorder=True + expect_column_names ["foo", "bar", "foo_1", "foo_2"] <| table.select_columns (By_Name ["b.*", "f.+"] Regex_Matcher_Data) + expect_column_names ["bar", "foo", "foo_1", "foo_2"] <| table.select_columns (By_Name ["b.*", "f.+"] Regex_Matcher_Data) reorder=True Test.specify "should correctly handle problems: out of bounds indices" <| selector = By_Index [1, 0, 100, -200, 300] action = table.select_columns selector on_problems=_ tester = expect_column_names ["foo", "bar"] - problems = [Column_Indexes_Out_Of_Range [100, -200, 300]] + problems = [Column_Indexes_Out_Of_Range_Data [100, -200, 300]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate indices" <| selector = By_Index [0, 0, 0] action = table.select_columns selector on_problems=_ tester = expect_column_names ["foo"] - problems = [Duplicate_Column_Selectors [0, 0]] + problems = [Duplicate_Column_Selectors_Data [0, 0]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: aliased indices" <| selector = By_Index [0, -7, -6, 1] action = table.select_columns selector on_problems=_ tester = expect_column_names ["foo", "bar"] - problems = [Input_Indices_Already_Matched [-7, 1]] + problems = [Input_Indices_Already_Matched_Data [-7, 1]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate names" <| selector = By_Name ["foo", "foo"] action = table.select_columns selector on_problems=_ tester = expect_column_names ["foo"] - problems = [Duplicate_Column_Selectors ["foo"]] + problems = [Duplicate_Column_Selectors_Data ["foo"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate matches due to case insensitivity" pending="TODO needs fixing" <| - selector = By_Name ["FOO", "foo"] (Text_Matcher case_sensitive=Case_Insensitive) + selector = By_Name ["FOO", "foo"] (Text_Matcher_Data case_sensitive=Case_Insensitive_Data) action = table.select_columns selector on_problems=_ tester = expect_column_names ["foo"] - problems = [Duplicate_Column_Selectors ["foo"]] + problems = [Duplicate_Column_Selectors_Data ["foo"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate matches due to case insensitivity" pending="TODO needs fixing" <| - selector = By_Name.new ["FOO", "foo"] (Text_Matcher case_sensitive=Case_Insensitive) + selector = By_Name.new ["FOO", "foo"] (Text_Matcher_Data case_sensitive=Case_Insensitive_Data) action = table.select_columns selector on_problems=_ tester = expect_column_names ["foo"] - problems = [Duplicate_Column_Selectors ["foo"]] + problems = [Duplicate_Column_Selectors_Data ["foo"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: unmatched names" <| @@ -133,7 +134,7 @@ spec prefix table_builder test_selection pending=Nothing = selector = By_Name ["foo", "hmm", weird_name] action = table.select_columns selector on_problems=_ tester = expect_column_names ["foo"] - problems = [Missing_Input_Columns ["hmm", weird_name]] + problems = [Missing_Input_Columns_Data ["hmm", weird_name]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate columns" <| @@ -141,7 +142,7 @@ spec prefix table_builder test_selection pending=Nothing = selector = By_Column [foo, foo] action = table.select_columns selector on_problems=_ tester = expect_column_names ["foo"] - problems = [Duplicate_Column_Selectors ["foo"]] + problems = [Duplicate_Column_Selectors_Data ["foo"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: unmatched columns" <| @@ -153,7 +154,7 @@ spec prefix table_builder test_selection pending=Nothing = selector = By_Column [bar, weird_column, foo] action = table.select_columns selector reorder=True on_problems=_ tester = expect_column_names ["bar", "foo"] - problems = [Missing_Input_Columns ["weird_column"]] + problems = [Missing_Input_Columns_Data ["weird_column"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: no columns in the output" <| @@ -167,18 +168,18 @@ spec prefix table_builder test_selection pending=Nothing = selector = By_Name ["hmmm"] action = table.select_columns selector on_problems=_ tester = expect_column_names [] - problems = [Missing_Input_Columns ["hmmm"], No_Output_Columns] + problems = [Missing_Input_Columns_Data ["hmmm"], No_Output_Columns] Problems.test_problem_handling action problems tester action_2 = table.select_columns (By_Index [0, -7, 0, 100]) on_problems=_ - problems_2 = [Column_Indexes_Out_Of_Range [100], Duplicate_Column_Selectors [0], Input_Indices_Already_Matched [-7]] + problems_2 = [Column_Indexes_Out_Of_Range_Data [100], Duplicate_Column_Selectors_Data [0], Input_Indices_Already_Matched_Data [-7]] tester_2 = expect_column_names ["foo"] Problems.test_problem_handling action_2 problems_2 tester_2 Test.group prefix+"Table.remove_columns" pending=pending <| Test.specify "should work as shown in the doc examples" <| expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] <| table.remove_columns (By_Name ["bar", "foo"]) - expect_column_names ["foo", "ab.+123", "abcd123"] <| table.remove_columns (By_Name ["foo.+", "b.*"] (Regex_Matcher case_sensitive=Case_Insensitive)) + expect_column_names ["foo", "ab.+123", "abcd123"] <| table.remove_columns (By_Name ["foo.+", "b.*"] (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data)) expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123"] <| table.remove_columns (By_Index [-1, 0, 1]) column1 = table.at "foo_1" @@ -187,12 +188,12 @@ spec prefix table_builder test_selection pending=Nothing = Test.specify "should correctly handle regex matching" <| last_ones = table.columns.tail.map .name - expect_column_names last_ones <| table.remove_columns (By_Name ["foo"] Regex_Matcher) + expect_column_names last_ones <| table.remove_columns (By_Name ["foo"] Regex_Matcher_Data) first_ones = ["foo", "bar", "Baz", "foo_1", "foo_2"] - expect_column_names first_ones <| table.remove_columns (By_Name ["a.*"] Regex_Matcher) - expect_column_names first_ones <| table.remove_columns (By_Name ["ab.+123"] Regex_Matcher) + expect_column_names first_ones <| table.remove_columns (By_Name ["a.*"] Regex_Matcher_Data) + expect_column_names first_ones <| table.remove_columns (By_Name ["ab.+123"] Regex_Matcher_Data) expect_column_names first_ones+["abcd123"] <| table.remove_columns (By_Name ["ab.+123"]) - expect_column_names first_ones+["ab.+123"] <| table.remove_columns (By_Name ["abcd123"] Regex_Matcher) + expect_column_names first_ones+["ab.+123"] <| table.remove_columns (By_Name ["abcd123"] Regex_Matcher_Data) Test.specify "should allow negative indices" <| expect_column_names ["Baz", "foo_1", "ab.+123"] <| table.remove_columns (By_Index [-1, -3, 0, 1]) @@ -204,51 +205,51 @@ spec prefix table_builder test_selection pending=Nothing = col2 = ["bar", [4,5,6]] col3 = ["Bar", [7,8,9]] table_builder [col1, col2, col3] - expect_column_names ["foo"] <| table.remove_columns (By_Name ["bar"] (Text_Matcher Case_Insensitive)) + expect_column_names ["foo"] <| table.remove_columns (By_Name ["bar"] (Text_Matcher_Data Case_Insensitive_Data)) Test.specify "should correctly handle regexes matching multiple names" <| - expect_column_names ["Baz", "ab.+123", "abcd123"] <| table.remove_columns (By_Name ["b.*", "f.+"] Regex_Matcher) + expect_column_names ["Baz", "ab.+123", "abcd123"] <| table.remove_columns (By_Name ["b.*", "f.+"] Regex_Matcher_Data) Test.specify "should correctly handle problems: out of bounds indices" <| selector = By_Index [1, 0, 100, -200, 300] action = table.remove_columns selector on_problems=_ tester = expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] - problems = [Column_Indexes_Out_Of_Range [100, -200, 300]] + problems = [Column_Indexes_Out_Of_Range_Data [100, -200, 300]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate indices" <| selector = By_Index [0, 0, 0] action = table.remove_columns selector on_problems=_ tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] - problems = [Duplicate_Column_Selectors [0, 0]] + problems = [Duplicate_Column_Selectors_Data [0, 0]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: aliased indices" <| selector = By_Index [0, -7, -6, 1] action = table.remove_columns selector on_problems=_ tester = expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] - problems = [Input_Indices_Already_Matched [-7, 1]] + problems = [Input_Indices_Already_Matched_Data [-7, 1]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate names" <| selector = By_Name ["foo", "foo"] action = table.remove_columns selector on_problems=_ tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] - problems = [Duplicate_Column_Selectors ["foo"]] + problems = [Duplicate_Column_Selectors_Data ["foo"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate matches due to case insensitivity" pending="TODO needs fixing" <| - selector = By_Name ["FOO", "foo"] (Text_Matcher case_sensitive=Case_Insensitive) + selector = By_Name ["FOO", "foo"] (Text_Matcher_Data case_sensitive=Case_Insensitive_Data) action = table.remove_columns selector on_problems=_ tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] - problems = [Duplicate_Column_Selectors ["foo"]] + problems = [Duplicate_Column_Selectors_Data ["foo"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate matches due to case insensitivity" pending="TODO needs fixing" <| - selector = By_Name.new ["FOO", "foo"] (Text_Matcher case_sensitive=Case_Insensitive) + selector = By_Name.new ["FOO", "foo"] (Text_Matcher_Data case_sensitive=Case_Insensitive_Data) action = table.remove_columns selector on_problems=_ tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] - problems = [Duplicate_Column_Selectors ["foo"]] + problems = [Duplicate_Column_Selectors_Data ["foo"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: unmatched names" <| @@ -256,7 +257,7 @@ spec prefix table_builder test_selection pending=Nothing = selector = By_Name ["foo", "hmm", weird_name] action = table.remove_columns selector on_problems=_ tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] - problems = [Missing_Input_Columns ["hmm", weird_name]] + problems = [Missing_Input_Columns_Data ["hmm", weird_name]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate columns" <| @@ -264,7 +265,7 @@ spec prefix table_builder test_selection pending=Nothing = selector = By_Column [foo, foo] action = table.remove_columns selector on_problems=_ tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] - problems = [Duplicate_Column_Selectors ["foo"]] + problems = [Duplicate_Column_Selectors_Data ["foo"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: unmatched columns" <| @@ -276,32 +277,32 @@ spec prefix table_builder test_selection pending=Nothing = selector = By_Column [bar, weird_column, foo] action = table.remove_columns selector on_problems=_ tester = expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] - problems = [Missing_Input_Columns ["weird_column"]] + problems = [Missing_Input_Columns_Data ["weird_column"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: no columns in the output" <| - selector = By_Name [".*"] Regex_Matcher + selector = By_Name [".*"] Regex_Matcher_Data action = table.remove_columns selector on_problems=_ tester = expect_column_names [] problems = [No_Output_Columns] Problems.test_problem_handling action problems tester Test.specify "should correctly handle multiple problems" <| - selector = By_Name [".*", "hmmm"] Regex_Matcher + selector = By_Name [".*", "hmmm"] Regex_Matcher_Data action = table.remove_columns selector on_problems=_ tester = expect_column_names [] - problems = [Missing_Input_Columns ["hmmm"], No_Output_Columns] + problems = [Missing_Input_Columns_Data ["hmmm"], No_Output_Columns] Problems.test_problem_handling action problems tester action_2 = table.remove_columns (By_Index [0, -7, 0, 100]) on_problems=_ - problems_2 = [Column_Indexes_Out_Of_Range [100], Duplicate_Column_Selectors [0], Input_Indices_Already_Matched [-7]] + problems_2 = [Column_Indexes_Out_Of_Range_Data [100], Duplicate_Column_Selectors_Data [0], Input_Indices_Already_Matched_Data [-7]] tester_2 = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] Problems.test_problem_handling action_2 problems_2 tester_2 Test.group prefix+"Table.reorder_columns" pending=pending <| Test.specify "should work as shown in the doc examples" <| expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] <| table.reorder_columns (By_Name ["foo"]) position=After_Other_Columns - expect_column_names ["foo_1", "foo_2", "bar", "Baz", "foo", "ab.+123", "abcd123"] <| table.reorder_columns (By_Name ["foo.+", "b.*"] (Regex_Matcher case_sensitive=Case_Insensitive)) + expect_column_names ["foo_1", "foo_2", "bar", "Baz", "foo", "ab.+123", "abcd123"] <| table.reorder_columns (By_Name ["foo.+", "b.*"] (Regex_Matcher_Data case_sensitive=Case_Insensitive_Data)) expect_column_names ["bar", "foo", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] <| table.reorder_columns (By_Index [1, 0]) position=Before_Other_Columns expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] <| table.reorder_columns (By_Index [0]) position=After_Other_Columns @@ -310,12 +311,12 @@ spec prefix table_builder test_selection pending=Nothing = expect_column_names ["foo_1", "Baz", "foo", "bar", "foo_2", "ab.+123", "abcd123"] <| table.reorder_columns (By_Column [column1, column2]) Test.specify "should correctly handle regex matching" <| - expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] <| table.reorder_columns (By_Name ["foo"] Regex_Matcher) position=After_Other_Columns + expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] <| table.reorder_columns (By_Name ["foo"] Regex_Matcher_Data) position=After_Other_Columns rest = ["foo", "bar", "Baz", "foo_1", "foo_2"] - expect_column_names ["ab.+123", "abcd123"]+rest <| table.reorder_columns (By_Name ["a.*"] Regex_Matcher) - expect_column_names ["ab.+123", "abcd123"]+rest <| table.reorder_columns (By_Name ["ab.+123"] Regex_Matcher) + expect_column_names ["ab.+123", "abcd123"]+rest <| table.reorder_columns (By_Name ["a.*"] Regex_Matcher_Data) + expect_column_names ["ab.+123", "abcd123"]+rest <| table.reorder_columns (By_Name ["ab.+123"] Regex_Matcher_Data) expect_column_names ["ab.+123"]+rest+["abcd123"] <| table.reorder_columns (By_Name ["ab.+123"]) - expect_column_names ["abcd123"]+rest+["ab.+123"] <| table.reorder_columns (By_Name ["abcd123"] Regex_Matcher) + expect_column_names ["abcd123"]+rest+["ab.+123"] <| table.reorder_columns (By_Name ["abcd123"] Regex_Matcher_Data) Test.specify "should allow negative indices" <| expect_column_names ["abcd123", "foo_2", "foo", "bar", "Baz", "foo_1", "ab.+123"] <| table.reorder_columns (By_Index [-1, -3, 0, 1]) @@ -327,37 +328,37 @@ spec prefix table_builder test_selection pending=Nothing = col2 = ["bar", [4,5,6]] col3 = ["Bar", [7,8,9]] table_builder [col1, col2, col3] - expect_column_names ["bar", "Bar", "foo"] <| table.reorder_columns (By_Name ["bar"] (Text_Matcher Case_Insensitive)) + expect_column_names ["bar", "Bar", "foo"] <| table.reorder_columns (By_Name ["bar"] (Text_Matcher_Data Case_Insensitive_Data)) Test.specify "should correctly handle regexes matching multiple names" <| - expect_column_names ["bar", "foo", "foo_1", "foo_2", "Baz", "ab.+123", "abcd123"] <| table.reorder_columns (By_Name ["b.*", "f.+"] Regex_Matcher) + expect_column_names ["bar", "foo", "foo_1", "foo_2", "Baz", "ab.+123", "abcd123"] <| table.reorder_columns (By_Name ["b.*", "f.+"] Regex_Matcher_Data) Test.specify "should correctly handle problems: out of bounds indices" <| selector = By_Index [1, 0, 100, -200, 300] action = table.reorder_columns selector on_problems=_ tester = expect_column_names ["bar", "foo", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123"] - problems = [Column_Indexes_Out_Of_Range [100, -200, 300]] + problems = [Column_Indexes_Out_Of_Range_Data [100, -200, 300]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate indices" <| selector = By_Index [0, 0, 0] action = table.reorder_columns selector position=After_Other_Columns on_problems=_ tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] - problems = [Duplicate_Column_Selectors [0, 0]] + problems = [Duplicate_Column_Selectors_Data [0, 0]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: aliased indices" <| selector = By_Index [0, -7, -6, 1] action = table.reorder_columns selector position=After_Other_Columns on_problems=_ tester = expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo", "bar"] - problems = [Input_Indices_Already_Matched [-7, 1]] + problems = [Input_Indices_Already_Matched_Data [-7, 1]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate names" <| selector = By_Name ["foo", "foo"] action = table.reorder_columns selector position=After_Other_Columns on_problems=_ tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] - problems = [Duplicate_Column_Selectors ["foo"]] + problems = [Duplicate_Column_Selectors_Data ["foo"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: unmatched names" <| @@ -365,7 +366,7 @@ spec prefix table_builder test_selection pending=Nothing = selector = By_Name ["foo", "hmm", weird_name] action = table.reorder_columns selector position=After_Other_Columns on_problems=_ tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] - problems = [Missing_Input_Columns ["hmm", weird_name]] + problems = [Missing_Input_Columns_Data ["hmm", weird_name]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate columns" <| @@ -373,7 +374,7 @@ spec prefix table_builder test_selection pending=Nothing = selector = By_Column [foo, foo] action = table.reorder_columns selector position=After_Other_Columns on_problems=_ tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] - problems = [Duplicate_Column_Selectors ["foo"]] + problems = [Duplicate_Column_Selectors_Data ["foo"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: unmatched columns" <| @@ -385,12 +386,12 @@ spec prefix table_builder test_selection pending=Nothing = selector = By_Column [bar, weird_column, foo] action = table.reorder_columns selector position=After_Other_Columns on_problems=_ tester = expect_column_names ["Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "bar", "foo"] - problems = [Missing_Input_Columns ["weird_column"]] + problems = [Missing_Input_Columns_Data ["weird_column"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle multiple problems" <| action = table.reorder_columns (By_Index [0, -7, 0, 100]) position=After_Other_Columns on_problems=_ - problems = [Column_Indexes_Out_Of_Range [100], Duplicate_Column_Selectors [0], Input_Indices_Already_Matched [-7]] + problems = [Column_Indexes_Out_Of_Range_Data [100], Duplicate_Column_Selectors_Data [0], Input_Indices_Already_Matched_Data [-7]] tester = expect_column_names ["bar", "Baz", "foo_1", "foo_2", "ab.+123", "abcd123", "foo"] Problems.test_problem_handling action problems tester @@ -410,17 +411,17 @@ spec prefix table_builder test_selection pending=Nothing = expect_column_names ["Foo_2", "bar", "foo_001", "foo_1", "foo_100", "foo_21", "foo_3"] sorted sorted.columns.first.to_vector . should_equal [10,11,12] - expect_column_names ["bar", "foo_001", "foo_1", "Foo_2", "foo_3", "foo_21", "foo_100"] <| table.sort_columns text_ordering=(Text_Ordering sort_digits_as_numbers=True case_sensitive=Case_Insensitive) + expect_column_names ["bar", "foo_001", "foo_1", "Foo_2", "foo_3", "foo_21", "foo_100"] <| table.sort_columns text_ordering=(Text_Ordering_Data sort_digits_as_numbers=True case_sensitive=Case_Insensitive_Data) expect_column_names ["foo_3", "foo_21", "foo_100", "foo_1", "foo_001", "bar", "Foo_2"] <| table.sort_columns Sort_Direction.Descending Test.specify "should correctly handle case-insensitive sorting" <| - expect_column_names ["bar", "foo_001", "foo_1", "foo_100", "Foo_2", "foo_21", "foo_3"] <| table.sort_columns text_ordering=(Text_Ordering case_sensitive=Case_Insensitive) + expect_column_names ["bar", "foo_001", "foo_1", "foo_100", "Foo_2", "foo_21", "foo_3"] <| table.sort_columns text_ordering=(Text_Ordering_Data case_sensitive=Case_Insensitive_Data) Test.specify "should correctly handle natural order sorting" <| - expect_column_names ["Foo_2", "bar", "foo_001", "foo_1", "foo_3", "foo_21", "foo_100"] <| table.sort_columns text_ordering=(Text_Ordering sort_digits_as_numbers=True) + expect_column_names ["Foo_2", "bar", "foo_001", "foo_1", "foo_3", "foo_21", "foo_100"] <| table.sort_columns text_ordering=(Text_Ordering_Data sort_digits_as_numbers=True) Test.specify "should correctly handle various combinations of options" <| - expect_column_names ["foo_100", "foo_21", "foo_3", "Foo_2", "foo_1", "foo_001", "bar"] <| table.sort_columns direction=Sort_Direction.Descending text_ordering=(Text_Ordering sort_digits_as_numbers=True case_sensitive=Case_Insensitive) + expect_column_names ["foo_100", "foo_21", "foo_3", "Foo_2", "foo_1", "foo_001", "bar"] <| table.sort_columns direction=Sort_Direction.Descending text_ordering=(Text_Ordering_Data sort_digits_as_numbers=True case_sensitive=Case_Insensitive_Data) Test.group prefix+"Table.rename_columns" pending=pending <| table = @@ -447,22 +448,22 @@ spec prefix table_builder test_selection pending=Nothing = Test.specify "should work by name" <| map = Map.from_vector [["alpha", "FirstColumn"], ["delta", "Another"]] expect_column_names ["FirstColumn", "beta", "gamma", "Another"] <| - table.rename_columns (Column_Name_Mapping.By_Name map (Text_Matcher True)) + table.rename_columns (Column_Name_Mapping.By_Name map (Text_Matcher_Data True)) Test.specify "should work by name case-insensitively" <| map = Map.from_vector [["ALPHA", "FirstColumn"], ["DELTA", "Another"]] expect_column_names ["FirstColumn", "beta", "gamma", "Another"] <| - table.rename_columns (Column_Name_Mapping.By_Name map (Text_Matcher Case_Insensitive)) + table.rename_columns (Column_Name_Mapping.By_Name map (Text_Matcher_Data Case_Insensitive_Data)) Test.specify "should work by name using regex" <| map = Map.from_vector [["a.*", "FirstColumn"]] expect_column_names ["FirstColumn", "beta", "gamma", "delta"] <| - table.rename_columns (Column_Name_Mapping.By_Name map Regex_Matcher) + table.rename_columns (Column_Name_Mapping.By_Name map Regex_Matcher_Data) Test.specify "should work by name using regex substitution" <| map = Map.from_vector [["a(.*)", "$1"]] expect_column_names ["lpha", "beta", "gamma", "delta"] <| - table.rename_columns (Column_Name_Mapping.By_Name map Regex_Matcher) + table.rename_columns (Column_Name_Mapping.By_Name map Regex_Matcher_Data) Test.specify "should work by column" <| vec = [[table.at "alpha", "FirstColumn"], [table.at "delta", "Another"]] @@ -473,7 +474,7 @@ spec prefix table_builder test_selection pending=Nothing = map = Column_Name_Mapping.By_Column [[table.at "alpha", "FirstColumn"], [table.at "alpha", "Another"]] action = table.rename_columns map on_problems=_ tester = expect_column_names ["FirstColumn", "beta", "gamma", "delta"] - problems = [Duplicate_Column_Selectors ["alpha"]] + problems = [Duplicate_Column_Selectors_Data ["alpha"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: unmatched names" <| @@ -481,49 +482,49 @@ spec prefix table_builder test_selection pending=Nothing = map = Column_Name_Mapping.By_Name (Map.from_vector [["alpha", "FirstColumn"], ["omicron", "Another"], [weird_name, "Fixed"]]) action = table.rename_columns map on_problems=_ tester = expect_column_names ["FirstColumn", "beta", "gamma", "delta"] - problems = [Missing_Input_Columns [weird_name, "omicron"]] + problems = [Missing_Input_Columns_Data [weird_name, "omicron"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: out of bounds indices" <| map = Column_Name_Mapping.By_Index (Map.from_vector [[0, "FirstColumn"], [-1, "Another"], [100, "Boo"], [-200, "Nothing"], [300, "Here"]]) action = table.rename_columns map on_problems=_ tester = expect_column_names ["FirstColumn", "beta", "gamma", "Another"] - problems = [Column_Indexes_Out_Of_Range [-200, 100, 300]] + problems = [Column_Indexes_Out_Of_Range_Data [-200, 100, 300]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: aliased indices" <| map = Column_Name_Mapping.By_Index (Map.from_vector [[1, "FirstColumn"], [-3, "Another"]]) action = table.rename_columns map on_problems=_ tester = expect_column_names ["alpha", "Another", "gamma", "delta"] - problems = [Input_Indices_Already_Matched [1]] + problems = [Input_Indices_Already_Matched_Data [1]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: invalid names ''" <| map = Column_Name_Mapping.By_Index (Map.from_vector [[1, ""]]) action = table.rename_columns map on_problems=_ tester = expect_column_names ["alpha", "Column_1", "gamma", "delta"] - problems = [Invalid_Output_Column_Names [""]] + problems = [Invalid_Output_Column_Names_Data [""]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: invalid names Nothing" <| map = Column_Name_Mapping.By_Position ["alpha", Nothing] action = table.rename_columns map on_problems=_ tester = expect_column_names ["alpha", "Column_1", "gamma", "delta"] - problems = [Invalid_Output_Column_Names [Nothing]] + problems = [Invalid_Output_Column_Names_Data [Nothing]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate names" <| map = Column_Name_Mapping.By_Position ["Test", "Test", "Test", "Test"] action = table.rename_columns map on_problems=_ tester = expect_column_names ["Test", "Test_1", "Test_2", "Test_3"] - problems = [Duplicate_Output_Column_Names ["Test", "Test", "Test"]] + problems = [Duplicate_Output_Column_Names_Data ["Test", "Test", "Test"]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: too many input names" <| map = Column_Name_Mapping.By_Position ["A", "B", "C", "D", "E", "F"] action = table.rename_columns map on_problems=_ tester = expect_column_names ["A", "B", "C", "D"] - problems = [Too_Many_Column_Names_Provided ["E", "F"]] + problems = [Too_Many_Column_Names_Provided_Data ["E", "F"]] Problems.test_problem_handling action problems tester order_by_pending = if pending.is_nothing.not then pending else @@ -554,7 +555,7 @@ spec prefix table_builder test_selection pending=Nothing = t2.at "alpha" . to_vector . should_equal [1, 3, 0, 2] Test.specify "should correctly handle regexes matching multiple names" <| - t1 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name ".*ta" Sort_Direction.Descending] Regex_Matcher) + t1 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name ".*ta" Sort_Direction.Descending] Regex_Matcher_Data) t1.at "beta" . to_vector . should_equal ["b", "b", "a", "a"] t1.at "delta" . to_vector . should_equal ["a1", "a03", "a2", "a10"] t1.at "gamma" . to_vector . should_equal [2, 4, 3, 1] @@ -565,7 +566,7 @@ spec prefix table_builder test_selection pending=Nothing = tester table = table.at "alpha" . to_vector . should_equal [0, 1, 2, 3] table.at "gamma" . to_vector . should_equal [4, 3, 2, 1] - problems = [Column_Indexes_Out_Of_Range [100, -200, 300]] + problems = [Column_Indexes_Out_Of_Range_Data [100, -200, 300]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate indices" <| @@ -574,7 +575,7 @@ spec prefix table_builder test_selection pending=Nothing = tester table = table.at "alpha" . to_vector . should_equal [0, 1, 2, 3] table.at "gamma" . to_vector . should_equal [4, 3, 2, 1] - problems = [Duplicate_Column_Selectors [Sort_Column.Index 0, Sort_Column.Index 0 Sort_Direction.Descending]] + problems = [Duplicate_Column_Selectors_Data [Sort_Column.Index 0, Sort_Column.Index 0 Sort_Direction.Descending]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: aliased indices" <| @@ -584,7 +585,7 @@ spec prefix table_builder test_selection pending=Nothing = table.at "beta" . to_vector . should_equal ["a", "a", "b", "b"] table.at "gamma" . to_vector . should_equal [3, 1, 4, 2] table.at "alpha" . to_vector . should_equal [1, 3, 0, 2] - problems = [Input_Indices_Already_Matched [Sort_Column.Index -9 Sort_Direction.Descending, Sort_Column.Index 2]] + problems = [Input_Indices_Already_Matched_Data [Sort_Column.Index -9 Sort_Direction.Descending, Sort_Column.Index 2]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate names" <| @@ -593,16 +594,16 @@ spec prefix table_builder test_selection pending=Nothing = tester table = table.at "alpha" . to_vector . should_equal [0, 1, 2, 3] table.at "gamma" . to_vector . should_equal [4, 3, 2, 1] - problems = [Column_Matched_By_Multiple_Selectors "alpha" [Sort_Column.Name "alpha", Sort_Column.Name "alpha" Sort_Direction.Descending]] + problems = [Column_Matched_By_Multiple_Selectors_Data "alpha" [Sort_Column.Name "alpha", Sort_Column.Name "alpha" Sort_Direction.Descending]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate matches due to case insensitivity" <| - selector = Sort_Column_Selector.By_Name [Sort_Column.Name "ALPHA", Sort_Column.Name "alpha" Sort_Direction.Descending] (Text_Matcher case_sensitive=Case_Insensitive) + selector = Sort_Column_Selector.By_Name [Sort_Column.Name "ALPHA", Sort_Column.Name "alpha" Sort_Direction.Descending] (Text_Matcher_Data case_sensitive=Case_Insensitive_Data) action = table.order_by selector on_problems=_ tester table = table.at "alpha" . to_vector . should_equal [0, 1, 2, 3] table.at "gamma" . to_vector . should_equal [4, 3, 2, 1] - problems = [Column_Matched_By_Multiple_Selectors "alpha" [Sort_Column.Name "ALPHA", Sort_Column.Name "alpha" Sort_Direction.Descending]] + problems = [Column_Matched_By_Multiple_Selectors_Data "alpha" [Sort_Column.Name "ALPHA", Sort_Column.Name "alpha" Sort_Direction.Descending]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: unmatched names" <| @@ -612,7 +613,7 @@ spec prefix table_builder test_selection pending=Nothing = tester table = table.at "alpha" . to_vector . should_equal [0, 1, 2, 3] table.at "gamma" . to_vector . should_equal [4, 3, 2, 1] - problems = [Missing_Input_Columns [Sort_Column.Name "hmm", Sort_Column.Name weird_name]] + problems = [Missing_Input_Columns_Data [Sort_Column.Name "hmm", Sort_Column.Name weird_name]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: unmatched columns" <| @@ -623,7 +624,7 @@ spec prefix table_builder test_selection pending=Nothing = selector = Sort_Column_Selector.By_Column [Sort_Column.Column bar, Sort_Column.Column weird_column, Sort_Column.Column foo] problem = table.order_by selector on_problems=Problem_Behavior.Report_Error . catch - problem.should_be_a Missing_Input_Columns + problem.should_be_a Missing_Input_Columns_Data problem.criteria.map (selector-> selector.column.name) . should_equal ["weird_column"] t2 = table.order_by selector on_problems=Problem_Behavior.Ignore @@ -710,45 +711,45 @@ spec prefix table_builder test_selection pending=Nothing = t1.at "alpha" . to_vector . should_equal [2, 1, 0, 3] Test.specify "should support natural ordering" pending=(if test_selection.natural_ordering.not then "Natural ordering is not supported.") <| - t1 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "delta"]) text_ordering=(Text_Ordering sort_digits_as_numbers=True) + t1 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "delta"]) text_ordering=(Text_Ordering_Data sort_digits_as_numbers=True) t1.at "delta" . to_vector . should_equal ["a1", "a2", "a03", "a10"] t1.at "alpha" . to_vector . should_equal [2, 1, 0, 3] - t2 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "delta"]) text_ordering=(Text_Ordering sort_digits_as_numbers=False) + t2 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "delta"]) text_ordering=(Text_Ordering_Data sort_digits_as_numbers=False) t2.at "delta" . to_vector . should_equal ["a03", "a1", "a10", "a2"] t2.at "alpha" . to_vector . should_equal [0, 2, 3, 1] Test.specify "should support case insensitive ordering" pending=(if test_selection.case_insensitive_ordering.not then "Case insensitive ordering is not supported.") <| - t1 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "eta"]) text_ordering=(Text_Ordering case_sensitive=Case_Insensitive) + t1 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "eta"]) text_ordering=(Text_Ordering_Data case_sensitive=Case_Insensitive_Data) expected = case test_selection.case_insensitive_ascii_only of True -> ["Aleph", "alpha", "Beta", "bądź"] False -> ["Aleph", "alpha", "bądź", "Beta"] t1.at "eta" . to_vector . should_equal expected - t2 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "eta"]) text_ordering=(Text_Ordering case_sensitive=True) + t2 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "eta"]) text_ordering=(Text_Ordering_Data case_sensitive=True) t2.at "eta" . to_vector . should_equal ["Aleph", "Beta", "alpha", "bądź"] - t3 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "psi"]) text_ordering=(Text_Ordering case_sensitive=Case_Insensitive) + t3 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "psi"]) text_ordering=(Text_Ordering_Data case_sensitive=Case_Insensitive_Data) t3.at "psi" . to_vector . should_equal [Nothing, "c01", "c10", "C2"] - t4 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "psi" Sort_Direction.Descending]) text_ordering=(Text_Ordering case_sensitive=True) + t4 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "psi" Sort_Direction.Descending]) text_ordering=(Text_Ordering_Data case_sensitive=True) t4.at "psi" . to_vector . should_equal ["c10", "c01", "C2", Nothing] Test.specify "should support natural and case insensitive ordering at the same time" pending=(if (test_selection.natural_ordering.not || test_selection.case_insensitive_ordering.not) then "Natural ordering or case sensitive ordering is not supported.") <| - t1 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "psi"]) text_ordering=(Text_Ordering sort_digits_as_numbers=True case_sensitive=Case_Insensitive) + t1 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "psi"]) text_ordering=(Text_Ordering_Data sort_digits_as_numbers=True case_sensitive=Case_Insensitive_Data) t1.at "psi" . to_vector . should_equal [Nothing, "c01", "C2", "c10"] - t2 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "psi"]) text_ordering=(Text_Ordering sort_digits_as_numbers=True) + t2 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "psi"]) text_ordering=(Text_Ordering_Data sort_digits_as_numbers=True) t2.at "psi" . to_vector . should_equal [Nothing, "C2", "c01", "c10"] - t3 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "psi"]) text_ordering=(Text_Ordering case_sensitive=Case_Insensitive) + t3 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "psi"]) text_ordering=(Text_Ordering_Data case_sensitive=Case_Insensitive_Data) t3.at "psi" . to_vector . should_equal [Nothing, "c01", "c10", "C2"] t4 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "psi"]) t4.at "psi" . to_vector . should_equal [Nothing, "C2", "c01", "c10"] Test.specify "text ordering settings should not affect numeric columns" <| - ordering = Text_Ordering sort_digits_as_numbers=True case_sensitive=Case_Insensitive + ordering = Text_Ordering_Data sort_digits_as_numbers=True case_sensitive=Case_Insensitive_Data t1 = table.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name "alpha"]) text_ordering=ordering t1.at "alpha" . to_vector . should_equal [0, 1, 2, 3] t1.at "gamma" . to_vector . should_equal [4, 3, 2, 1] diff --git a/test/Table_Tests/src/In_Memory_Tests.enso b/test/Table_Tests/src/In_Memory_Tests.enso index 97a4738cc054..4c6eccc7b8d0 100644 --- a/test/Table_Tests/src/In_Memory_Tests.enso +++ b/test/Table_Tests/src/In_Memory_Tests.enso @@ -7,8 +7,8 @@ import project.Csv_Spec import project.Delimited_Read_Spec import project.Delimited_Write_Spec import project.Excel_Spec -#import project.Json_Spec -#import project.Table_Spec +import project.Json_Spec +import project.Table_Spec #import project.Table_Date_Spec #import project.Aggregate_Column_Spec #import project.Aggregate_Spec @@ -19,8 +19,8 @@ in_memory_spec = Delimited_Read_Spec.spec Delimited_Write_Spec.spec Excel_Spec.spec - #Json_Spec.spec - #Table_Spec.spec + Json_Spec.spec + Table_Spec.spec #Table_Date_Spec.spec #Aggregate_Column_Spec.spec #Aggregate_Spec.spec diff --git a/test/Table_Tests/src/Table_Spec.enso b/test/Table_Tests/src/Table_Spec.enso index 0b47f28a31fc..c38b15bf74b6 100644 --- a/test/Table_Tests/src/Table_Spec.enso +++ b/test/Table_Tests/src/Table_Spec.enso @@ -4,7 +4,7 @@ from Standard.Table import all import Standard.Table.Data.Sort_Column_Selector import Standard.Table.Data.Sort_Column from Standard.Table.Data.Table as Table_Internal import Empty_Error -from Standard.Table.Errors as Table_Errors import Invalid_Output_Column_Names, Duplicate_Output_Column_Names, No_Input_Columns_Selected, Missing_Input_Columns +from Standard.Table.Errors as Table_Errors import Invalid_Output_Column_Names_Data, Duplicate_Output_Column_Names_Data, No_Input_Columns_Selected, Missing_Input_Columns_Data import Standard.Table.Data.Storage import Standard.Visualization @@ -14,16 +14,17 @@ import Standard.Test.Problems import project.Common_Table_Spec -type My x y +type My + My_Data x y My.== self that = case that of - My x1 y1 -> (self.x + self.y) == (x1 + y1) + My_Data x1 y1 -> (self.x + self.y) == (x1 + y1) _ -> False My.compare_to self that = self.x+self.y . compare_to that.x+that.y My.frobnicate self = case self of - My x1 y1 -> My y1 x1 + My_Data x1 y1 -> My_Data y1 x1 spec = Test.group "JSON construction" <| @@ -88,7 +89,7 @@ spec = col_1 = Column.from_vector 'x' [1, 2, 3] col_1.to_vector.reduce (+) . should_equal 6 - col_2 = Column.from_vector 'y' [My 1 2, My 2 3] + col_2 = Column.from_vector 'y' [My_Data 1 2, My_Data 2 3] col_2.to_vector.map (my -> my.x + my.y) . should_equal [3, 5] col_3 = Column.from_vector 'z' [False, True, False] @@ -104,8 +105,8 @@ spec = c_dec.map (+ 1.5) . to_vector . should_equal [3.4, 3.5, 2.7, 7.1, 3.4] c_bool = Column.from_vector 'x' [True, False, Nothing, True, False] c_bool.map (_.to_text) . to_vector . should_equal ["True", "False", Nothing, "True", "False"] - c_any = Column.from_vector 'x' [My 1 6, My 6 3, My 2 5, My 3 4, My 200 300] - c_any.map (_.frobnicate) . to_vector . should_equal [My 6 1, My 3 6, My 5 2, My 4 3, My 300 200] + c_any = Column.from_vector 'x' [My_Data 1 6, My_Data 6 3, My_Data 2 5, My_Data 3 4, My_Data 200 300] + c_any.map (_.frobnicate) . to_vector . should_equal [My_Data 6 1, My_Data 3 6, My_Data 5 2, My_Data 4 3, My_Data 300 200] Test.specify "should allow zipping columns with a custom function" <| b = Column.from_vector 'w' [6.3, 3.1, 5.2, 4.6, 8.0] @@ -127,8 +128,8 @@ spec = (c_dec == 1.9).to_vector.should_equal [True, False, False, False, True] c_bool = Column.from_vector 'x' [True, False, Nothing, True, False] (c_bool == False).to_vector.should_equal [False, True, Nothing, False, True] - c_any = Column.from_vector 'x' [My 1 6, My 6 3, My 2 5, My 3 4, My 200 300] - (c_any == My 7 0).to_vector.should_equal [True, False, True, True, False] + c_any = Column.from_vector 'x' [My_Data 1 6, My_Data 6 3, My_Data 2 5, My_Data 3 4, My_Data 200 300] + (c_any == My_Data 7 0).to_vector.should_equal [True, False, True, True, False] Test.specify "should switch between maps and zips based on argument type" <| a = Column.from_vector 'x' [0, 1, 7, 3, 6] @@ -354,7 +355,7 @@ spec = Test.specify 'should respect defined comparison operations for custom types' <| c_1 = ['id', [1, 2, 3, 4, 5, 6]] - c_2 = ['val', [My 1 2, My 3 4, My 2 1, My 5 2, My 7 0, My 4 -1]] + c_2 = ['val', [My_Data 1 2, My_Data 3 4, My_Data 2 1, My_Data 5 2, My_Data 7 0, My_Data 4 -1]] df = Table.new [c_1, c_2] r = df.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name 'val']) r.at 'id' . to_vector . should_equal [1,3,6,2,4,5] @@ -363,7 +364,7 @@ spec = action = df.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name 'foobar']) on_problems=_ tester table = table.at 'Id' . to_vector . should_equal [1,2,3,4,5,6] - problems = [Missing_Input_Columns [Sort_Column.Name 'foobar'], No_Input_Columns_Selected] + problems = [Missing_Input_Columns_Data [Sort_Column.Name 'foobar'], No_Input_Columns_Selected] Problems.test_problem_handling action problems tester Test.specify 'should correctly reorder all kinds of columns and leave the original columns untouched' <| @@ -407,15 +408,15 @@ spec = r_3.to_vector.should_equal [Nothing,Nothing,8,7,4,1] Test.specify 'should respect defined comparison operations for custom types' <| - c = Column.from_vector 'foo' [My 1 2, My 3 4, My 2 1, My 5 2, My 7 0, My 4 -1] + c = Column.from_vector 'foo' [My_Data 1 2, My_Data 3 4, My_Data 2 1, My_Data 5 2, My_Data 7 0, My_Data 4 -1] r = c.sort - r.to_vector.should_equal [My 1 2, My 2 1, My 4 -1, My 3 4, My 5 2, My 7 0] + r.to_vector.should_equal [My_Data 1 2, My_Data 2 1, My_Data 4 -1, My_Data 3 4, My_Data 5 2, My_Data 7 0] Test.specify 'should allow passing a custom comparator' <| - c = Column.from_vector 'foo' [My 1 2, My 2 5, My 3 4, My 6 3, Nothing, My 1 0] + c = Column.from_vector 'foo' [My_Data 1 2, My_Data 2 5, My_Data 3 4, My_Data 6 3, Nothing, My_Data 1 0] cmp a b = (a.x-a.y).abs . compare_to (b.x-b.y).abs r = c.sort comparator=cmp - r.to_vector.should_equal [My 1 2, My 3 4, My 1 0, My 2 5, My 6 3, Nothing] + r.to_vector.should_equal [My_Data 1 2, My_Data 3 4, My_Data 1 0, My_Data 2 5, My_Data 6 3, Nothing] Test.group "Concatenating Tables" <| Test.specify 'should concat tables with the same schema' <| @@ -596,7 +597,7 @@ spec = t_3 = Table.new [c_3_1, c_3_2, c_3_3] t_3.default_visualization.should_equal Visualization.Id.table - selection = Common_Table_Spec.Test_Selection supports_case_sensitive_columns=True order_by=True natural_ordering=True case_insensitive_ordering=True order_by_unicode_normalization_by_default=True + selection = Common_Table_Spec.Test_Selection_Data supports_case_sensitive_columns=True order_by=True natural_ordering=True case_insensitive_ordering=True order_by_unicode_normalization_by_default=True Common_Table_Spec.spec "[In-Memory] " table_builder=Table.new test_selection=selection Test.group "Use First Row As Names" <| @@ -618,7 +619,7 @@ spec = table = Table.new [c_0, c_2] action = table.use_first_row_as_names on_problems=_ tester = expect_column_names ["Column_1", "1"] - problems = [Invalid_Output_Column_Names [""]] + problems = [Invalid_Output_Column_Names_Data [""]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: invalid names Nothing" <| @@ -627,7 +628,7 @@ spec = table = Table.new [c_0, c_2] action = table.use_first_row_as_names on_problems=_ tester = expect_column_names ["A", "Column_1"] - problems = [Invalid_Output_Column_Names [Nothing]] + problems = [Invalid_Output_Column_Names_Data [Nothing]] Problems.test_problem_handling action problems tester Test.specify "should correctly handle problems: duplicate names" <| @@ -638,7 +639,7 @@ spec = table = Table.new [c_0, c_1, c_2, c_3] action = table.use_first_row_as_names on_problems=_ tester = expect_column_names ["A", "A_1", "A_2", "A_3"] - problems = [Duplicate_Output_Column_Names ["A", "A", "A"]] + problems = [Duplicate_Output_Column_Names_Data ["A", "A", "A"]] Problems.test_problem_handling action problems tester main = Test.Suite.run_main spec From 31066d55eb805b87315b4ced7bb469e3931bd990 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 23 Aug 2022 16:10:39 +0200 Subject: [PATCH 061/110] more passing specs --- .../src/Connection/Client_Certificate.enso | 6 +- .../0.0.0-dev/src/Connection/Connection.enso | 27 +++++---- .../src/Connection/Connection_Options.enso | 2 +- .../0.0.0-dev/src/Connection/Credentials.enso | 2 +- .../0.0.0-dev/src/Connection/Postgres.enso | 32 +++++----- .../0.0.0-dev/src/Connection/Redshift.enso | 12 ++-- .../0.0.0-dev/src/Connection/SQLite.enso | 3 +- .../0.0.0-dev/src/Connection/SSL_Mode.enso | 10 ++-- .../Database/0.0.0-dev/src/Data/Column.enso | 20 +++---- .../Database/0.0.0-dev/src/Data/Dialect.enso | 2 +- .../0.0.0-dev/src/Data/Dialect/Helpers.enso | 2 +- .../0.0.0-dev/src/Data/Dialect/Postgres.enso | 2 +- .../0.0.0-dev/src/Data/Dialect/Redshift.enso | 4 +- .../0.0.0-dev/src/Data/Dialect/SQLite.enso | 6 +- .../src/Data/Internal/Base_Generator.enso | 8 +-- .../0.0.0-dev/src/Data/Internal/Helpers.enso | 2 +- .../0.0.0-dev/src/Data/Internal/IR.enso | 59 ++++++++++--------- .../Database/0.0.0-dev/src/Data/Sql.enso | 48 +++++++-------- .../Database/0.0.0-dev/src/Data/Table.enso | 36 +++++------ .../src/Internal/Postgres/Pgpass.enso | 4 +- .../Table/0.0.0-dev/src/Data/Table.enso | 5 +- .../src/Internal/Aggregate_Column_Helper.enso | 20 +++---- test/Table_Tests/src/Aggregate_Spec.enso | 47 +++++++-------- test/Table_Tests/src/In_Memory_Tests.enso | 12 ++-- test/Table_Tests/src/Table_Date_Spec.enso | 8 +-- 25 files changed, 191 insertions(+), 188 deletions(-) diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Client_Certificate.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Client_Certificate.enso index 4d336458e74b..a77ce7c8b433 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Client_Certificate.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Client_Certificate.enso @@ -7,7 +7,7 @@ type Client_Certificate - cert_file: path to the client certificate file. - key_file: path to the client key file. - key_password: password for the client key file. - type Client_Certificate cert_file:(File|Text) key_file:(File|Text) (key_password:Text='') + Client_Certificate_Data cert_file:(File|Text) key_file:(File|Text) (key_password:Text='') ## PRIVATE Creates the JDBC properties for the client certificate. @@ -18,5 +18,5 @@ type Client_Certificate - sslpass: password for the client key file. properties : Vector properties self = - base = [Pair 'sslcert' (File.new self.cert_file).absolute.path, Pair 'sslkey' (File.new self.key_file).absolute.path] - if self.key_password == "" then base else base + [Pair 'sslpassword' self.key_password] + base = [Pair_Data 'sslcert' (File.new self.cert_file).absolute.path, Pair_Data 'sslkey' (File.new self.key_file).absolute.path] + if self.key_password == "" then base else base + [Pair_Data 'sslpassword' self.key_password] 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 3f15d517dbde..756a33738762 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 @@ -35,7 +35,7 @@ type Connection - dialect: the dialect associated with the database we are connected to. Allows accessing tables from a database. - type Connection connection_resource dialect + Connection_Data connection_resource dialect ## UNSTABLE @@ -141,7 +141,7 @@ type Connection case query of Text -> go query [] - Sql.Statement _ -> + Sql.Statement_Data _ -> compiled = query.prepare go compiled.first compiled.second @@ -248,7 +248,7 @@ type Builder Arguments: - java_builder: The underlying builder object. - type Builder_Inferred java_builder + Builder_Inferred java_builder ## PRIVATE @@ -256,7 +256,7 @@ type Builder Arguments: - java_builder: The underlying builder object. - type Builder_Double java_builder + Builder_Double java_builder ## PRIVATE @@ -264,7 +264,7 @@ type Builder Arguments: - java_builder: The underlying builder object. - type Builder_Long java_builder + Builder_Long java_builder ## PRIVATE @@ -272,7 +272,7 @@ type Builder Arguments: - java_builder: The underlying builder object. - type Builder_Boolean java_builder + Builder_Boolean java_builder ## PRIVATE @@ -321,7 +321,8 @@ type Builder Argument: - url: The URL for which the dialect could not be deduced. -type Unsupported_Dialect url +type Unsupported_Dialect + Unsupported_Dialect_Data url ## Pretty print the error about unsupported SQL dialects. Unsupported_Dialect.to_display_text : Text @@ -344,7 +345,7 @@ create_jdbc_connection url properties dialect = handle_sql_errors <| java_props.setProperty pair.first pair.second java_connection = JDBCProxy.getConnection url java_props resource = Managed_Resource.register java_connection close_connection - Connection resource dialect + Connection_Data resource dialect ## PRIVATE @@ -367,7 +368,7 @@ type Sql_Error - java_exception: The underlying exception. - related_query (optional): A string representation of a query that this error is related to. - type Sql_Error java_exception related_query=Nothing + Sql_Error_Data java_exception related_query=Nothing ## UNSTABLE @@ -393,7 +394,7 @@ type Sql_Timeout_Error - java_exception: The underlying exception. - related_query (optional): A string representation of a query that this error is related to. - type Sql_Timeout_Error java_exception related_query=Nothing + Sql_Timeout_Error_Data java_exception related_query=Nothing ## UNSTABLE @@ -419,7 +420,7 @@ type Sql_Timeout_Error - action: The computation to execute. This computation may throw SQL errors. handle_sql_errors : Any -> (Text | Nothing) -> Any ! (Sql_Error | Sql_Timeout_Error) handle_sql_errors ~action related_query=Nothing = - Panic.recover [Sql_Error, Sql_Timeout_Error] <| + Panic.recover [Sql_Error_Data, Sql_Timeout_Error_Data] <| wrap_sql_errors action related_query ## PRIVATE @@ -436,8 +437,8 @@ wrap_sql_errors ~action related_query=Nothing = Panic.catch SQLException action caught_panic-> exc = caught_panic.payload.cause case Java.is_instance exc SQLTimeoutException of - True -> Panic.throw (Sql_Timeout_Error exc related_query) - False -> Panic.throw (Sql_Error exc related_query) + True -> Panic.throw (Sql_Timeout_Error_Data exc related_query) + False -> Panic.throw (Sql_Error_Data exc related_query) ## PRIVATE Returns the default database type corresponding to an in-memory storage diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Connection_Options.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Connection_Options.enso index 132f3ff1ddd5..d9baeebba317 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Connection_Options.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Connection_Options.enso @@ -2,7 +2,7 @@ from Standard.Base import all type Connection_Options ## Hold a set of key value pairs used to configure the connection. - type Connection_Options options:Vector=[] + Connection_Options_Data options:Vector=[] ## Merge the base set of options with the overrides in this object. merge : Vector -> Vector diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Credentials.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Credentials.enso index 213cb9711084..f434cc109ef7 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Credentials.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Credentials.enso @@ -2,7 +2,7 @@ from Standard.Base import all type Credentials ## Simple username and password type. - type Credentials username:Text password:Text + Credentials_Data username:Text password:Text ## Override `to_text` to mask the password field. to_text : Text diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Postgres.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Postgres.enso index 5e30bd7f4d68..29303e845e8c 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Postgres.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Postgres.enso @@ -4,7 +4,7 @@ from Standard.Base.Data.Numbers import Parse_Error import Standard.Database.Data.Dialect import Standard.Database.Connection.Connection -from Standard.Database.Connection.Credentials import Credentials +from Standard.Database.Connection.Credentials import Credentials_Data, Credentials import Standard.Database.Connection.Connection_Options import Standard.Database.Connection.SSL_Mode from Standard.Database.Connection.SSL_Mode import all @@ -23,7 +23,7 @@ type Postgres - credentials: The credentials to use for the connection (defaults to PGPass or No Authentication). - use_ssl: Whether to use SSL (defaults to `Prefer`). - client_cert: The client certificate to use or `Nothing` if not needed. - type Postgres (host:Text=default_postgres_host) (port:Integer=default_postgres_port) (database:Text=default_postgres_database) (credentials:(Credentials|Nothing)=Nothing) (use_ssl:SSL_Mode=Prefer) (client_cert:(Client_Certificate|Nothing)=Nothing) + Postgres_Data (host:Text=default_postgres_host) (port:Integer=default_postgres_port) (database:Text=default_postgres_database) (credentials:(Credentials|Nothing)=Nothing) (use_ssl:SSL_Mode=Prefer) (client_cert:(Client_Certificate|Nothing)=Nothing) ## Build the Connection resource. @@ -48,17 +48,17 @@ type Postgres Nothing -> env_user = Environment.get "PGUSER" env_password = Environment.get "PGPASSWORD" - case Pair env_user env_password of - Pair Nothing Nothing -> + case Pair_Data env_user env_password of + Pair_Data Nothing Nothing -> Pgpass.read self.host self.port self.database - Pair Nothing _ -> + Pair_Data Nothing _ -> Error.throw (Illegal_State_Error "PGPASSWORD is set, but PGUSER is not.") - Pair username Nothing -> + Pair_Data username Nothing -> Pgpass.read self.host self.port self.database username - Pair username password -> - [Pair 'user' username, Pair 'password' password] - Credentials username password -> - [Pair 'user' username, Pair 'password' password] + Pair_Data username password -> + [Pair_Data 'user' username, Pair_Data 'password' password] + Credentials_Data username password -> + [Pair_Data 'user' username, Pair_Data 'password' password] ssl_properties = ssl_mode_to_jdbc_properties self.use_ssl @@ -77,14 +77,14 @@ type Postgres ssl_mode_to_jdbc_properties : SSL_Mode -> [Pair Text Text] ssl_mode_to_jdbc_properties use_ssl = case use_ssl of Disable -> [] - Prefer -> [Pair 'sslmode' 'prefer'] - Require -> [Pair 'sslmode' 'require'] + Prefer -> [Pair_Data 'sslmode' 'prefer'] + Require -> [Pair_Data 'sslmode' 'require'] Verify_CA cert_file -> - if cert_file.is_nothing then [Pair 'sslmode' 'verify-ca'] else - [Pair 'sslmode' 'verify-ca', Pair 'sslrootcert' (File.new cert_file).absolute.path] + if cert_file.is_nothing then [Pair_Data 'sslmode' 'verify-ca'] else + [Pair_Data 'sslmode' 'verify-ca', Pair_Data 'sslrootcert' (File.new cert_file).absolute.path] Full_Verification cert_file -> - if cert_file.is_nothing then [Pair 'sslmode' 'verify-full'] else - [Pair 'sslmode' 'verify-full', Pair 'sslrootcert' (File.new cert_file).absolute.path] + if cert_file.is_nothing then [Pair_Data 'sslmode' 'verify-full'] else + [Pair_Data 'sslmode' 'verify-full', Pair_Data 'sslrootcert' (File.new cert_file).absolute.path] ## PRIVATE default_postgres_host = Environment.get_or_else "PGHOST" "localhost" diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Redshift.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Redshift.enso index 94c7265288fe..ab334680d1e3 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Redshift.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Redshift.enso @@ -2,7 +2,7 @@ from Standard.Base import all import Standard.Database.Data.Dialect import Standard.Database.Connection.Connection -from Standard.Database.Connection.Credentials import Credentials +from Standard.Database.Connection.Credentials import Credentials, Credentials_Data import Standard.Database.Connection.Connection_Options import Standard.Database.Connection.SSL_Mode from Standard.Database.Connection.SSL_Mode import all @@ -23,7 +23,7 @@ type Redshift - credentials: The credentials to use for the connection (defaults to PGPass or No Authentication). - use_ssl: Whether to use SSL (defaults to `Require`). - client_cert: The client certificate to use or `Nothing` if not needed. - type Redshift (host:Text) (port:Integer=5439) (schema:Text='') (credentials:Credentials|AWS_Profile|AWS_Key|Nothing=Nothing) (use_ssl:(Disable|Require|Verify_CA|Full_Verification)=Require) (client_cert:Client_Certificate|Nothing=Nothing) + Redshift_Data (host:Text) (port:Integer=5439) (schema:Text='') (credentials:Credentials|AWS_Credential|Nothing=Nothing) (use_ssl:(Disable|Require|Verify_CA|Full_Verification)=Require) (client_cert:Client_Certificate|Nothing=Nothing) ## Build the Connection resource. @@ -57,7 +57,7 @@ type Redshift [Pair 'user' db_user] + (if profile == '' then [] else [Pair 'profile' profile]) AWS_Key db_user access_key secret_access_key -> [Pair 'user' db_user, Pair 'AccessKeyID' access_key, Pair 'SecretAccessKey' secret_access_key] - Credentials username password -> + Credentials_Data username password -> [Pair 'user' username, Pair 'password' password] ## Disabled as Redshift SSL settings are different to PostgreSQL. @@ -72,13 +72,13 @@ type Redshift dialect : Dialect dialect self = Dialect.redshift -type AWS_Profile +type AWS_Credential ## Access Redshift using IAM via an AWS profile. Arguments: - db_user: Redshift username to connect as. - profile: AWS profile name (if empty uses default). - type AWS_Profile db_user:Text profile:Text='' + AWS_Profile db_user:Text profile:Text='' ## Access Redshift using IAM via an AWS access key ID and secret access key. @@ -87,4 +87,4 @@ type AWS_Profile - db_user: Redshift username to connect as. - access_key: AWS access key ID. - secret_access_key: AWS secret access key. - type AWS_Key db_user:Text access_key:Text secret_access_key:Text + AWS_Key db_user:Text access_key:Text secret_access_key:Text diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/SQLite.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/SQLite.enso index 5e3793561c40..0ff4e45e61c0 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/SQLite.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/SQLite.enso @@ -6,7 +6,7 @@ import Standard.Database.Connection.Connection_Options ## Connect to a SQLite DB File or InMemory DB. type SQLite - type SQLite (location:(In_Memory|File|Text)) + SQLite_Data (location:(In_Memory|File|Text)) ## Build the Connection resource. connect : Connection_Options @@ -30,4 +30,3 @@ type SQLite ## Connect to an in-memory SQLite database. type In_Memory - type In_Memory diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/SSL_Mode.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/SSL_Mode.enso index 939b502115d4..4878a290a92d 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/SSL_Mode.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/SSL_Mode.enso @@ -2,18 +2,18 @@ from Standard.Base import all type SSL_Mode ## Do not use SSL for the connection. - type Disable + Disable ## Prefer SSL for the connection, but does not verify the server certificate. - type Prefer + Prefer ## Will use SSL but does not verify the server certificate. - type Require + Require ## Will use SSL, validating the certificate but not verifying the hostname. If `ca_file` is `Nothing`, the default CA certificate store will be used. - type Verify_CA ca_file:Nothing|File|Text=Nothing + Verify_CA ca_file:Nothing|File|Text=Nothing ## Will use SSL, validating the certificate and checking the hostname matches. If `ca_file` is `Nothing`, the default CA certificate store will be used. - type Full_Verification ca_file:Nothing|File|Text=Nothing + Full_Verification ca_file:Nothing|File|Text=Nothing diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Column.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Column.enso index cb3beda491d4..c9ff8e375788 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Column.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Column.enso @@ -33,7 +33,7 @@ type Column # type Column (name : Text) (connection : Connection) # (sql_type : Sql_Type) (expression : IR.Expression) # (context : IR.Context) - type Column name connection sql_type expression context + Column_Data name connection sql_type expression context ## UNSTABLE @@ -118,18 +118,18 @@ type Column make_binary_op self op_kind operand new_type=Nothing operand_type=Nothing = actual_new_type = new_type.if_nothing self.sql_type case operand of - Column _ _ _ other_expr _ -> + Column_Data _ _ _ other_expr _ -> case Helpers.check_integrity self operand of False -> Error.throw <| Unsupported_Database_Operation_Error "Cannot compare columns coming from different contexts. Only columns of a single table can be compared." True -> new_expr = IR.Operation op_kind [self.expression, other_expr] - Column self.name self.connection actual_new_type new_expr self.context + Column_Data self.name self.connection actual_new_type new_expr self.context _ -> actual_operand_type = operand_type.if_nothing self.sql_type other = IR.make_constant actual_operand_type operand new_expr = IR.Operation op_kind [self.expression, other] - Column self.name self.connection actual_new_type new_expr self.context + Column_Data self.name self.connection actual_new_type new_expr self.context ## PRIVATE @@ -143,7 +143,7 @@ type Column make_unary_op self op_kind new_type=Nothing = actual_new_type = new_type.if_nothing self.sql_type new_expr = IR.Operation op_kind [self.expression] - Column self.name self.connection actual_new_type new_expr self.context + Column_Data self.name self.connection actual_new_type new_expr self.context ## UNSTABLE @@ -421,7 +421,7 @@ type Column True -> new_filters = self.context.where_filters + [filter.expression] new_ctx = self.context.set_where_filters new_filters - Column self.name self.connection self.sql_type self.expression new_ctx + Column_Data self.name self.connection self.sql_type self.expression new_ctx ## UNSTABLE @@ -442,7 +442,7 @@ type Column case is_used_in_index of True -> Error.throw <| Illegal_State_Error "Cannot rename the column to "+new_name+", because it has an index with the same name." False -> - Column new_name self.connection self.sql_type self.expression self.context + Column_Data new_name self.connection self.sql_type self.expression self.context ## UNSTABLE @@ -529,7 +529,7 @@ type Aggregate_Column_Builder # type Aggregate_Column_Builder (name : Text) (connection : Connection) # (sql_type : Sql_Type) (expression : IR.Expression) # (context : IR.Context) - type Aggregate_Column_Builder name connection sql_type expression context + Aggregate_Column_Builder_Data name connection sql_type expression context ## UNSTABLE @@ -592,7 +592,7 @@ type Aggregate_Column_Builder ungrouped : Column ungrouped self = new_ctx = self.context.set_groups [] - Column self.name self.connection self.sql_type self.expression new_ctx + Column_Data self.name self.connection self.sql_type self.expression new_ctx ## PRIVATE @@ -637,5 +637,5 @@ lift_aggregate new_name connection expected_type expr context = new_col = cols.first.first new_ixes = cols.second new_ctx = IR.subquery_as_ctx subquery . set_index new_ixes - Column new_name connection new_col.sql_type new_col.expression new_ctx + Column_Data new_name connection new_col.sql_type new_col.expression new_ctx 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 660fa6809911..ddcd2cd629e6 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 @@ -19,7 +19,7 @@ type Dialect This is a fake constructor to make the compiler accept this type definition. It can and should be removed once interface definitions are allowed. - type Dialect + Dialect_Data ## PRIVATE Name of the dialect. name : Text diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Helpers.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Helpers.enso index 8f1477374735..59dd5c4e0ebf 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Helpers.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Helpers.enso @@ -26,7 +26,7 @@ import Standard.Database.Data.Sql is escaped by doubling each occurrence. make_concat make_raw_concat_expr make_contains_expr has_quote args = expected_args = if has_quote then 5 else 4 - if args.length != expected_args then Error.throw (Illegal_State_Error "Unexpected number of arguments for the concat operation.") else + if args.length != expected_args then Error.throw (Illegal_State_Error_Data "Unexpected number of arguments for the concat operation.") else expr = args.at 0 separator = args.at 1 prefix = args.at 2 diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso index 27020d175bee..20245e85e5bb 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso @@ -234,7 +234,7 @@ make_order_descriptor internal_column sort_direction text_ordering = IR.Order_Descriptor internal_column.expression sort_direction nulls_order=nulls collation=Nothing True -> IR.Order_Descriptor internal_column.expression sort_direction nulls_order=nulls collation="ucs_basic" - Case_Insensitive locale -> case locale == Locale.default of + Case_Insensitive_Data locale -> case locale == Locale.default of False -> Error.throw (Unsupported_Database_Operation_Error "Case insensitive ordering with custom locale is currently not supported. You may need to materialize the Table to perform this operation.") True -> diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Redshift.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Redshift.enso index 2dd3ebf4eb2a..796246e2d284 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Redshift.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Redshift.enso @@ -12,7 +12,7 @@ import Standard.Database.Data.Internal.Base_Generator The dialect for Redshift connections. redshift : Dialect redshift = - Redshift_Dialect Postgres.make_internal_generator_dialect + Redshift_Dialect_Data Postgres.make_internal_generator_dialect ## PRIVATE @@ -21,7 +21,7 @@ type Redshift_Dialect ## PRIVATE The dialect for Redshift connections. - type Redshift_Dialect internal_generator_dialect + Redshift_Dialect_Data internal_generator_dialect ## PRIVATE Name of the dialect. diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/SQLite.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/SQLite.enso index 1407dc83e216..ad57b633a3e8 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/SQLite.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/SQLite.enso @@ -14,7 +14,7 @@ from Standard.Database.Error import Unsupported_Database_Operation_Error The dialect of SQLite databases. sqlite : Dialect sqlite = - SQLite_Dialect make_internal_generator_dialect + SQLite_Dialect_Data make_internal_generator_dialect ## PRIVATE @@ -23,7 +23,7 @@ type SQLite_Dialect ## PRIVATE The dialect of SQLite databases. - type SQLite_Dialect internal_generator_dialect + SQLite_Dialect_Data internal_generator_dialect ## PRIVATE Name of the dialect. @@ -59,7 +59,7 @@ type SQLite_Dialect IR.Order_Descriptor internal_column.expression sort_direction collation=Nothing True -> IR.Order_Descriptor internal_column.expression sort_direction collation="BINARY" - Case_Insensitive locale -> case locale == Locale.default of + Case_Insensitive_Data locale -> case locale == Locale.default of False -> Error.throw (Unsupported_Database_Operation_Error "Case insensitive ordering with custom locale is not supported by the SQLite backend. You may need to materialize the Table to perform this operation.") True -> diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Base_Generator.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Base_Generator.enso index c417ec39e104..9f5be9e7cffe 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Base_Generator.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Base_Generator.enso @@ -24,7 +24,7 @@ type Internal_Dialect # type Internal_Dialect (operation_map : Map Text (Vector Sql.Builder -> Sql.Builder)) # (identifier_wrapper : Text -> Sql.Builder) - type Internal_Dialect operation_map wrap_identifier + Internal_Dialect_Data operation_map wrap_identifier ## PRIVATE @@ -35,7 +35,7 @@ type Internal_Dialect extend_with : Vector Any -> Internal_Dialect extend_with self mappings = new_map = mappings.fold self.operation_map (m -> el -> m.insert (el.at 0) (el.at 1)) - Internal_Dialect new_map self.wrap_identifier + Internal_Dialect_Data new_map self.wrap_identifier ## PRIVATE @@ -171,7 +171,7 @@ base_dialect = counts = [fun "COUNT", ["COUNT_ROWS", make_constant "COUNT(*)"]] nulls = [["ISNULL", make_right_unary_op "IS NULL"], ["FILLNULL", make_function "COALESCE"]] base_map = Map.from_vector (arith + logic + compare + agg + nulls + counts) - Internal_Dialect base_map wrap_in_quotes + Internal_Dialect_Data base_map wrap_in_quotes ## PRIVATE @@ -190,7 +190,7 @@ generate_expression dialect expr = case expr of op = dialect.operation_map.get_or_else kind (Error.throw <| Unsupported_Database_Operation_Error kind) parsed_args = arguments.map (generate_expression dialect) op parsed_args - IR.Order_Descriptor _ _ _ _ -> generate_order dialect expr + IR.Order_Descriptor_Data _ _ _ _ -> generate_order dialect expr ## PRIVATE diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Helpers.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Helpers.enso index c3bd4c21fbee..7983a670dfbb 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Helpers.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Helpers.enso @@ -33,7 +33,7 @@ check_integrity entity1 entity2 = as-is, otherwise it is wrapped in a singleton vector. unify_vector_singleton : (Any | Vector.Vector Any) -> Vector.Vector Any unify_vector_singleton x = case x of - Vector.Vector _ -> x + Vector.Vector_Data _ -> x _ -> [x] ## UNSTABLE diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/IR.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/IR.enso index a98f2a769529..3020193bc19b 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/IR.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/IR.enso @@ -17,7 +17,7 @@ type Expression originates from, it corresponds to the `alias` field in `from_spec`. - name: the name of the column directly in the table or its alias in a sub-query. - type Column (origin : Text) (name : Text) + Column (origin : Text) (name : Text) ## PRIVATE @@ -29,7 +29,7 @@ type Expression It is usually inferred from the expression's context. - value: the value to be interpolated; it should be a simple Number, Text or other types that are serializable for JDBC. - type Constant (sql_type : Sql.Sql_Type) (value : Any) + Constant (sql_type : Sql.Sql_Type) (value : Any) ## PRIVATE @@ -42,7 +42,7 @@ type Expression dialect. - expressions: a list of expressions which are arguments to the operation different operations support different amounts of arguments. - type Operation (kind : Text) (expressions : Vector Expression) + Operation (kind : Text) (expressions : Vector Expression) type Internal_Column ## PRIVATE @@ -53,7 +53,7 @@ type Internal_Column - name: The column name. - sql_type: The SQL type of the column. - expression: An expression for applying to the column. - type Internal_Column name sql_type expression + Internal_Column_Data name sql_type expression ## PRIVATE @@ -62,7 +62,7 @@ type Internal_Column Arguments: - new_name: The new name for the column. rename : Text -> Internal_Column - rename self new_name = Internal_Column new_name self.sql_type self.expression + rename self new_name = Internal_Column_Data new_name self.sql_type self.expression ## PRIVATE @@ -91,7 +91,7 @@ type Context - meta_index: a list of internal columns to use for joining or grouping. - limit: an optional maximum number of elements that the equery should return. - type Context (from_spec : From_Spec) (where_filters : Vector Expression) (orders : Vector Order_Descriptor) (groups : Vector Expression) (meta_index : Vector Internal_Column) (limit : Nothing | Integer) + Context_Data (from_spec : From_Spec) (where_filters : Vector Expression) (orders : Vector Order_Descriptor) (groups : Vector Expression) (meta_index : Vector Internal_Column) (limit : Nothing | Integer) ## PRIVATE @@ -101,7 +101,7 @@ type Context - new_index: The new index to set in the query. set_index : Vector Internal_Column -> Context set_index self new_index = - Context self.from_spec self.where_filters self.orders self.groups new_index self.limit + Context_Data self.from_spec self.where_filters self.orders self.groups new_index self.limit ## PRIVATE @@ -111,7 +111,7 @@ type Context - new_filters: The new filters to set in the query. set_where_filters : Vector Expression -> Context set_where_filters self new_filters = - Context self.from_spec new_filters self.orders self.groups self.meta_index self.limit + Context_Data self.from_spec new_filters self.orders self.groups self.meta_index self.limit ## PRIVATE @@ -121,7 +121,7 @@ type Context - new_orders: The new ordering clauses to set in the query. set_orders : Vector Order_Descriptor -> Context set_orders self new_orders = - Context self.from_spec self.where_filters new_orders self.groups self.meta_index self.limit + Context_Data self.from_spec self.where_filters new_orders self.groups self.meta_index self.limit ## PRIVATE @@ -138,7 +138,7 @@ type Context - new_orders: The new ordering clauses to add to the query. add_orders : Vector Order_Descriptor -> Context add_orders self new_orders = - Context self.from_spec self.where_filters new_orders+self.orders self.groups self.meta_index self.limit + Context_Data self.from_spec self.where_filters new_orders+self.orders self.groups self.meta_index self.limit ## PRIVATE @@ -148,7 +148,7 @@ type Context - new_groups: The new grouping clauses to set in the query. set_groups : Vector Expression -> Context set_groups self new_groups = - Context self.from_spec self.where_filters self.orders new_groups self.meta_index self.limit + Context_Data self.from_spec self.where_filters self.orders new_groups self.meta_index self.limit ## PRIVATE @@ -158,7 +158,7 @@ type Context - new_limit: The new limit clauses to set in the query. set_limit : (Nothing | Integer) -> Context set_limit self new_limit = - Context self.from_spec self.where_filters self.orders self.groups self.meta_index new_limit + Context_Data self.from_spec self.where_filters self.orders self.groups self.meta_index new_limit ## PRIVATE @@ -179,7 +179,7 @@ type Context as_subquery self alias column_lists = rewrite_internal_column : Internal_Column -> Internal_Column rewrite_internal_column column = - Internal_Column column.name column.sql_type (IR.Column alias column.name) + Internal_Column_Data column.name column.sql_type (IR.Column alias column.name) new_columns = column_lists.map columns-> columns.map rewrite_internal_column @@ -206,7 +206,7 @@ type From_Spec parts of the query, this is especially useful for example in self-joins, allowing to differentiate between different instances of the same table. - type From_Table (table_name : Text) (alias : Text) + From_Table (table_name : Text) (alias : Text) ## PRIVATE @@ -219,7 +219,7 @@ type From_Spec - on: a list of expressions that will be used as join conditions, these are usually be equalities between expressions from the left and right sources. - type Join (kind : Join_Kind) (left_spec : From_Spec) (right_spec : From_Spec) (on : Vector Expression) + Join (kind : Join_Kind) (left_spec : From_Spec) (right_spec : From_Spec) (on : Vector Expression) ## PRIVATE @@ -232,7 +232,7 @@ type From_Spec - context: the context for the sub-query. - alias: the name upon which the results of this sub-query can be referred to in other parts of the query. - type Sub_Query (columns : Vector (Pair Text Expression)) (context : Context) (alias : Text) + Sub_Query (columns : Vector (Pair Text Expression)) (context : Context) (alias : Text) ## PRIVATE @@ -244,7 +244,7 @@ type Join_Kind The result will contain only rows that had a match in both left and right source. - type Join_Inner + Join_Inner ## PRIVATE @@ -255,7 +255,7 @@ type Join_Kind the left source has no match on the right, it will be present exactly once in the result and the fields corresponding to the right source will be set to NULL. - type Join_Left + Join_Left ## PRIVATE @@ -266,7 +266,7 @@ type Join_Kind the right source has no match on the left, it will be present exactly once in the result and the fields corresponding to the left source will be set to NULL. - type Join_Right + Join_Right ## PRIVATE @@ -275,10 +275,11 @@ type Join_Kind The result will contain a cross product of rows from the left source with the right source. Its `on` list should be empty, instead `where_filters` in the query can be used to filter the results. - type Join_Cross + Join_Cross ## PRIVATE -type Order_Descriptor (expression : Expression) (direction : Sort_Direction) (nulls_order : Nothing | Nulls_Order = Nothing) (collation : Nothing | Text = Nothing) +type Order_Descriptor + Order_Descriptor_Data (expression : Expression) (direction : Sort_Direction) (nulls_order : Nothing | Nulls_Order = Nothing) (collation : Nothing | Text = Nothing) ## PRIVATE @@ -288,12 +289,12 @@ type Nulls_Order ## PRIVATE Null values are included before any other values in the ordering. - type Nulls_First + Nulls_First ## PRIVATE Null values are included after all other values in the ordering. - type Nulls_Last + Nulls_Last ## PRIVATE @@ -309,7 +310,7 @@ type Query is a pair whose first element is the name of the materialized column and the second element is the expression to compute. - context: The query context, see `Context` for more detail. - type Select (expressions : Vector (Pair Text Expression)) (context : Context) + Select (expressions : Vector (Pair Text Expression)) (context : Context) ## PRIVATE @@ -317,7 +318,7 @@ type Query Arguments: - context: The query context, see `Context` for more detail. - type Select_All context + Select_All context ## PRIVATE @@ -326,7 +327,7 @@ type Query Arguments: - table_name: The name of the table to insert to. - pairs: A list of pairs consisting of a column name and and expression. - type Insert table_name pairs + Insert table_name pairs ## PRIVATE @@ -337,7 +338,7 @@ type Query - table_name: The name of the tanle for which the context is being created. make_ctx_from : Text -> Context make_ctx_from table_name = - Context (From_Table table_name table_name) [] [] [] [] Nothing + Context_Data (From_Table table_name table_name) [] [] [] [] Nothing ## PRIVATE @@ -347,7 +348,7 @@ make_ctx_from table_name = - subquery: The subquery to lift into a context. subquery_as_ctx : Sub_Query -> Context subquery_as_ctx subquery = - Context subquery [] [] [] [] Nothing + Context_Data subquery [] [] [] [] Nothing ## PRIVATE @@ -389,5 +390,5 @@ substitute_origin old_origin new_origin expr = case expr of - col: The column over which to apply `f`. lift_expression_map : (Expression -> Expression) -> Internal_Column -> Internal_Column lift_expression_map f col = - Internal_Column col.name col.sql_type (f col.expression) + Internal_Column_Data col.name col.sql_type (f col.expression) diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Sql.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Sql.enso index 14f300b6823b..9e5ddebacf26 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Sql.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Sql.enso @@ -8,7 +8,7 @@ polyglot java import java.sql.Types Creates a Builder representing and empty code fragment. empty : Builder -empty = Builder (Vector_Builder.empty) +empty = Builder_Data (Vector_Builder.empty) ## UNSTABLE @@ -20,7 +20,7 @@ empty = Builder (Vector_Builder.empty) code : Text -> Builder code text = vec = if text.is_empty then [] else [Sql_Code_Part text] - Builder (Vector_Builder.from_vector vec) + Builder_Data (Vector_Builder.from_vector vec) ## UNSTABLE @@ -31,7 +31,7 @@ code text = - object: The object to be interpolated into the query as if it has the type given by `sql_type`. interpolation : Sql_Type -> Any -> Builder -interpolation sql_type object = Builder (Vector_Builder.from_vector [Sql_Interpolation sql_type object]) +interpolation sql_type object = Builder_Data (Vector_Builder.from_vector [Sql_Interpolation sql_type object]) ## UNSTABLE @@ -43,7 +43,7 @@ interpolation sql_type object = Builder (Vector_Builder.from_vector [Sql_Interpo join : Builder | Text -> Vector Builder -> Builder join separator statements = sep = case separator of - Builder _ -> separator + Builder_Data _ -> separator _ -> code separator if statements.length == 0 then empty else @@ -57,59 +57,59 @@ type Sql_Type Arguments: - typeid: a numerical type id, as defined in `java.sql.Types`. - name: a database-specific type name, used for pretty printing. - type Sql_Type typeid name + Sql_Type_Data typeid name == self that = case that of - Sql_Type that_id _ -> + Sql_Type_Data that_id _ -> self.typeid == that_id _ -> False ## The SQL representation of `Boolean` type. boolean : Sql_Type - boolean = Sql_Type Types.BOOLEAN "BOOLEAN" + boolean = Sql_Type_Data Types.BOOLEAN "BOOLEAN" ## The SQL representation of `Integer` type. integer : Sql_Type - integer = Sql_Type Types.INTEGER "INTEGER" + integer = Sql_Type_Data Types.INTEGER "INTEGER" ## The SQL representation of the `BIGINT` type. bigint : Sql_Type - bigint = Sql_Type Types.BIGINT "BIGINT" + bigint = Sql_Type_Data Types.BIGINT "BIGINT" ## The SQL representation of the `SMALLINT` type. smallint : Sql_Type - smallint = Sql_Type Types.SMALLINT "SMALLINT" + smallint = Sql_Type_Data Types.SMALLINT "SMALLINT" ## The SQL type representing decimal numbers. decimal : Sql_Type - decimal = Sql_Type Types.DECIMAL "DECIMAL" + decimal = Sql_Type_Data Types.DECIMAL "DECIMAL" ## The SQL type representing decimal numbers. real : Sql_Type - real = Sql_Type Types.REAL "REAL" + real = Sql_Type_Data Types.REAL "REAL" ## The SQL type representing double-precision floating-point numbers. double : Sql_Type - double = Sql_Type Types.DOUBLE "DOUBLE PRECISION" + double = Sql_Type_Data Types.DOUBLE "DOUBLE PRECISION" ## The SQL type representing a general numeric type. numeric : Sql_Type - numeric = Sql_Type Types.NUMERIC "NUMERIC" + numeric = Sql_Type_Data Types.NUMERIC "NUMERIC" ## The SQL type representing one of the suppported textual types. varchar : Sql_Type - varchar = Sql_Type Types.VARCHAR "VARCHAR" + varchar = Sql_Type_Data Types.VARCHAR "VARCHAR" ## UNSTABLE The SQL type representing one of the suppported textual types. It seems that JDBC treats the `TEXT` and `VARCHAR` types as interchangeable. text : Sql_Type - text = Sql_Type Types.VARCHAR "VARCHAR" + text = Sql_Type_Data Types.VARCHAR "VARCHAR" ## The SQL type representing a binary object. blob : Sql_Type - blob = Sql_Type Types.BLOB "BLOB" + blob = Sql_Type_Data Types.BLOB "BLOB" ## PRIVATE @@ -171,7 +171,7 @@ type Sql_Fragment Arguments: - code: A fragment of SQL code. # type Sql_Code_Part (code : Text) - type Sql_Code_Part code + Sql_Code_Part code ## UNSTABLE @@ -183,7 +183,7 @@ type Sql_Fragment - object: A value that will be interpolated into the query, interpreted as having the type `sql_type`. # type Sql_Interpolation (sql_type : Sql_Type) (object : Any) - type Sql_Interpolation sql_type object + Sql_Interpolation sql_type object type Statement @@ -197,7 +197,7 @@ type Statement The statement consists of SQL code with parameters and values that will be interpolated for these parameters. # type Statement (internal_fragments : Vector Sql_Fragment) - type Statement internal_fragments + Statement_Data internal_fragments ## UNSTABLE @@ -273,7 +273,7 @@ type Builder It can be used to concatenate parts of SQL code in O(1) time and at the end build the actual query in linear time. # type Builder (fragments : Vector_Builder.Vector_Builder Sql_Fragment) - type Builder fragments + Builder_Data fragments ## UNSTABLE @@ -282,7 +282,7 @@ type Builder Arguments: - other: The code fragment to append to `self`. ++ : Builder -> Builder - ++ self other = Builder (self.fragments ++ other.fragments) + ++ self other = Builder_Data (self.fragments ++ other.fragments) ## UNSTABLE @@ -296,7 +296,7 @@ type Builder build : Statement build self = fragments = optimize_fragments self.fragments.build - Statement fragments + Statement_Data fragments ## UNSTABLE @@ -318,7 +318,7 @@ type Builder prefix_if_present : Text | Builder -> Builder prefix_if_present self prefix = pref = case prefix of - Builder _ -> prefix + Builder_Data _ -> prefix _ -> code prefix if self.is_empty then self else pref++self diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso index ef33e0525c67..778c8f2f2d5d 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso @@ -14,9 +14,9 @@ import Standard.Base.System.File.Existing_File_Behavior import Standard.Table.Data.Aggregate_Column import Standard.Table.Internal.Aggregate_Column_Helper -from Standard.Database.Data.Column import Column, Aggregate_Column_Builder -from Standard.Database.Data.Internal.IR import Internal_Column -from Standard.Table.Data.Table import No_Such_Column_Error +from Standard.Database.Data.Column import Column, Column_Data, Aggregate_Column_Builder +from Standard.Database.Data.Internal.IR import Internal_Column, Internal_Column_Data +from Standard.Table.Data.Table import No_Such_Column_Error, No_Such_Column_Error_Data from Standard.Table.Data.Column_Selector import Column_Selector, By_Index from Standard.Base.Data.Text.Text_Ordering import Text_Ordering_Data from Standard.Table.Data.Data_Formatter import Data_Formatter @@ -45,7 +45,7 @@ type Table # type Table (name : Text) (connection : Connection) # (internal_columns : Vector Internal_Column) # (context : IR.Context) - type Table name connection internal_columns context + Table_Data name connection internal_columns context ## UNSTABLE @@ -91,7 +91,7 @@ type Table at self name = candidates = self.internal_columns + self.context.meta_index internal = candidates.find (p -> p.name == name) - self.make_column internal . map_error (_ -> No_Such_Column_Error name) + self.make_column internal . map_error (_ -> No_Such_Column_Error_Data name) ## Returns a new table with a chosen subset of columns, as specified by the `columns`, from the input table. Any unmatched input columns will be @@ -321,7 +321,7 @@ type Table Text -> Panic.rethrow (self.at column) _ -> if Helpers.check_integrity self column then column else - Panic.throw (Integrity_Error "Column "+column.name) + Panic.throw (Integrity_Error_Data "Column "+column.name) ## UNSTABLE @@ -342,7 +342,7 @@ type Table where self filter = case Helpers.check_integrity self filter of False -> - Error.throw (Integrity_Error "Column "+filter.name) + Error.throw (Integrity_Error_Data "Column "+filter.name) True -> new_filters = self.context.where_filters + [filter.expression] new_ctx = self.context.set_where_filters new_filters @@ -544,8 +544,8 @@ type Table Icon: join join : Table | Column -> Nothing | Text | Column | Vector (Text | Column) -> Boolean -> Text -> Text -> Table join self other on=Nothing drop_unmatched=False left_suffix='_left' right_suffix='_right' = case other of - Column _ _ _ _ _ -> self.join other.to_table on drop_unmatched left_suffix right_suffix - Table _ _ _ _ -> Panic.recover Any <| + Column_Data _ _ _ _ _ -> self.join other.to_table on drop_unmatched left_suffix right_suffix + Table_Data _ _ _ _ -> Panic.recover Any <| Panic.rethrow (Helpers.ensure_name_is_sane left_suffix && Helpers.ensure_name_is_sane right_suffix) if left_suffix == right_suffix then Panic.throw <| Illegal_State_Error "left_suffix must be different from right_suffix" @@ -614,7 +614,7 @@ type Table new_limit = Nothing new_ctx = IR.Context new_from [] [] [] new_index new_limit - Table new_table_name self.connection new_columns new_ctx + Table_Data new_table_name self.connection new_columns new_ctx ## ALIAS group, summarize @@ -733,7 +733,7 @@ type Table case preprocessed.internal_columns.is_empty of True -> internal_table = Java_Exports.make_table_without_columns self.row_count - Materialized_Table.Table internal_table + Materialized_Table.Table_Data internal_table False -> sql = preprocessed.to_sql expected_types = preprocessed.internal_columns.map .sql_type @@ -801,7 +801,7 @@ type Table # these distinctness assumptions, to avoid this renaming. ixes = freshen_columns [internal.name] self.context.meta_index new_ctx = self.context.set_index ixes - Column internal.name self.connection internal.sql_type internal.expression new_ctx + Column_Data internal.name self.connection internal.sql_type internal.expression new_ctx ## PRIVATE @@ -810,7 +810,7 @@ type Table Arguments: - columns: The columns with which to update this table. updated_columns : Vector Internal_Column -> Table - updated_columns self internal_columns = Table self.name self.connection internal_columns self.context + updated_columns self internal_columns = Table_Data self.name self.connection internal_columns self.context ## PRIVATE @@ -819,7 +819,7 @@ type Table Arguments: - ctx: The new context for this table. updated_context : Context -> Table - updated_context self ctx = Table self.name self.connection self.internal_columns ctx + updated_context self ctx = Table_Data self.name self.connection self.internal_columns ctx ## PRIVATE @@ -829,7 +829,7 @@ type Table - ctx: The new context for this table. - internal_columns: The new columns to include in the table. updated_context_and_columns : Context -> Vector Internal_Column -> Table - updated_context_and_columns self ctx internal_columns = Table self.name self.connection internal_columns ctx + updated_context_and_columns self ctx internal_columns = Table_Data self.name self.connection internal_columns ctx ## PRIVATE @@ -933,7 +933,7 @@ type Integrity_Error contexts. To use columns from different tables, you must first join them. - type Integrity_Error object_description + Integrity_Error_Data object_description # Return a readable description of this error. to_text : Text @@ -954,8 +954,8 @@ type Integrity_Error make_table : Connection -> Text -> Vector -> Table make_table connection table_name columns = ctx = IR.make_ctx_from table_name - cols = columns.map (p -> Internal_Column p.first p.second (IR.Column table_name p.first)) - Table table_name connection cols ctx + cols = columns.map (p -> Internal_Column_Data p.first p.second (IR.Column table_name p.first)) + Table_Data table_name connection cols ctx ## PRIVATE diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Internal/Postgres/Pgpass.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Internal/Postgres/Pgpass.enso index ca4a762a3dc0..1cd33927fb96 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Internal/Postgres/Pgpass.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Internal/Postgres/Pgpass.enso @@ -37,7 +37,7 @@ read host port database username=Nothing = type Pgpass_Entry ## PRIVATE - type Pgpass_Entry host port database username password + Pgpass_Entry_Data host port database username password ## PRIVATE matches : Text -> Text|Integer -> Text -> Text -> Boolean @@ -84,7 +84,7 @@ parse_file file = if line.starts_with "#" || line.is_empty then Nothing else elements = parse_line line if elements.length != 5 then Nothing else - Pgpass_Entry (elements.at 0) (elements.at 1) (elements.at 2) (elements.at 3) (elements.at 4) + Pgpass_Entry_Data (elements.at 0) (elements.at 1) (elements.at 2) (elements.at 3) (elements.at 4) File.read_text file . lines . map parse . filter (x -> x.is_nothing.not) diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso index de711954345e..292a8001ed4d 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso @@ -248,7 +248,7 @@ type Table example_at = Examples.inventory_table.at "item_name" at : Text -> Column ! No_Such_Column_Error at self name = case self.java_table.getColumnOrIndexByName name of - Nothing -> Error.throw (No_Such_Column_Error name) + Nothing -> Error.throw (No_Such_Column_Error_Data name) c -> Column.Column_Data c ## Returns a new table with a chosen subset of columns, as specified by the @@ -1128,7 +1128,8 @@ type Table Arguments: - column_name: The name of the column that doesn't exist. -type No_Such_Column_Error column_name +type No_Such_Column_Error + No_Such_Column_Error_Data column_name ## UNSTABLE diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Aggregate_Column_Helper.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Aggregate_Column_Helper.enso index 21a60cc612e0..1bc0d7a538d9 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Aggregate_Column_Helper.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Aggregate_Column_Helper.enso @@ -12,7 +12,7 @@ import Standard.Table.Data.Sort_Column import Standard.Base.Data.Ordering.Comparator -from Standard.Table.Errors import Missing_Input_Columns, Column_Indexes_Out_Of_Range, No_Output_Columns, Duplicate_Output_Column_Names, Invalid_Output_Column_Names, Invalid_Aggregation, Floating_Point_Grouping, Unquoted_Delimiter, Additional_Warnings +from Standard.Table.Errors import Missing_Input_Columns_Data, Column_Indexes_Out_Of_Range, No_Output_Columns, Duplicate_Output_Column_Names_Data, Invalid_Output_Column_Names_Data, Invalid_Aggregation_Data, Floating_Point_Grouping_Data, Unquoted_Delimiter_Data, Additional_Warnings_Data polyglot java import org.enso.table.aggregations.Aggregator polyglot java import org.enso.table.aggregations.Concatenate as ConcatenateAggregator @@ -71,15 +71,15 @@ prepare_aggregate_columns aggregates table = renamed_columns = pass_1.map_with_index i->name-> agg = valid_resolved_aggregate_columns.at i new_name = name.if_nothing (unique.make_unique (default_aggregate_column_name agg)) - Pair new_name agg + Pair_Data new_name agg # Build Problems Output if renamed_columns.is_empty then problem_builder.report_other_warning No_Output_Columns if unique.invalid_names.not_empty then - problem_builder.report_other_warning (Invalid_Output_Column_Names unique.invalid_names) + problem_builder.report_other_warning (Invalid_Output_Column_Names_Data unique.invalid_names) if unique.renames.not_empty then - problem_builder.report_other_warning (Duplicate_Output_Column_Names unique.renames) + problem_builder.report_other_warning (Duplicate_Output_Column_Names_Data unique.renames) Validated_Aggregate_Columns_Data unique_key_columns renamed_columns problem_builder.build_problemset @@ -209,7 +209,7 @@ java_aggregator name column = Shortest c _ -> ShortestOrLongestAggregator.new name c.java_column -1 Longest c _ -> ShortestOrLongestAggregator.new name c.java_column 1 Concatenate c _ join prefix suffix quote -> ConcatenateAggregator.new name c.java_column join prefix suffix quote - _ -> Error.throw (Invalid_Aggregation name -1 "Unsupported aggregation") + _ -> Error.throw (Invalid_Aggregation_Data name -1 "Unsupported aggregation") ## PRIVATE Convert Java aggregated problems to Enso Vector of equivalents @@ -219,10 +219,10 @@ parse_aggregated_problems problems = problems_array = problems.getProblems parsed = Vector.new problems_array.length i-> p = problems_array.at i - if Java.is_instance p InvalidAggregation then Invalid_Aggregation p.getColumnName (Vector.Vector p.getRows) p.getMessage else - if Java.is_instance p FloatingPointGrouping then Floating_Point_Grouping p.getColumnName (Vector.Vector p.getRows) else - if Java.is_instance p UnquotedDelimiter then Unquoted_Delimiter p.getColumnName (Vector.Vector p.getRows) else - Invalid_Aggregation Nothing -1 "Unknown Error" + if Java.is_instance p InvalidAggregation then Invalid_Aggregation_Data p.getColumnName (Vector.Vector_Data p.getRows) p.getMessage else + if Java.is_instance p FloatingPointGrouping then Floating_Point_Grouping_Data p.getColumnName (Vector.Vector_Data p.getRows) else + if Java.is_instance p UnquotedDelimiter then Unquoted_Delimiter_Data p.getColumnName (Vector.Vector_Data p.getRows) else + Invalid_Aggregation_Data Nothing -1 "Unknown Error" if problems.getCount == problems_array.length then parsed else - parsed + [Additional_Warnings (problems.getCount - problems_array.length)] + parsed + [Additional_Warnings_Data (problems.getCount - problems_array.length)] diff --git a/test/Table_Tests/src/Aggregate_Spec.enso b/test/Table_Tests/src/Aggregate_Spec.enso index 015f039f957b..3cfb8026d1ed 100644 --- a/test/Table_Tests/src/Aggregate_Spec.enso +++ b/test/Table_Tests/src/Aggregate_Spec.enso @@ -5,7 +5,7 @@ from Standard.Table.Data.Column_Selector import By_Name, By_Index import Standard.Table.Data.Sort_Column import Standard.Table.Data.Sort_Column_Selector from Standard.Table.Data.Aggregate_Column import all -from Standard.Table.Errors as Error_Module import Missing_Input_Columns, Column_Indexes_Out_Of_Range, No_Output_Columns, Duplicate_Output_Column_Names, Invalid_Output_Column_Names, Invalid_Aggregation, Floating_Point_Grouping, Unquoted_Delimiter, Additional_Warnings +from Standard.Table.Errors as Error_Module import Missing_Input_Columns_Data, Column_Indexes_Out_Of_Range_Data, No_Output_Columns, Duplicate_Output_Column_Names_Data, Invalid_Output_Column_Names_Data, Invalid_Aggregation_Data, Floating_Point_Grouping_Data, Unquoted_Delimiter_Data, Additional_Warnings_Data from Standard.Database.Error as Database_Errors import Unsupported_Database_Operation_Error import Standard.Test @@ -14,9 +14,10 @@ import Standard.Base.Error.Problem_Behavior polyglot java import java.lang.Double -type Test_Selection problem_handling=True advanced_stats=True text_concat=True text_shortest_longest=True first_last=True first_last_row_order=True std_dev=True multi_distinct=True aggregation_problems=True nan=True +type Test_Selection + Test_Selection_Data problem_handling=True advanced_stats=True text_concat=True text_shortest_longest=True first_last=True first_last_row_order=True std_dev=True multi_distinct=True aggregation_problems=True nan=True -all_tests = Test_Selection True True True True True True True True True True +all_tests = Test_Selection_Data True True True True True True True True True True spec = table = (enso_project.data / "data.csv") . read @@ -1179,49 +1180,49 @@ aggregate_spec prefix table empty_table table_builder materialize is_database te Test.specify "should raise a warning when can't find a column by name" <| action = table.aggregate [Group_By "Missing", Group_By "Index"] on_problems=_ - problems = [Missing_Input_Columns ["Missing"]] + problems = [Missing_Input_Columns_Data ["Missing"]] tester = expect_column_names ["Index"] Problems.test_problem_handling action problems tester Test.specify "should raise a warning when an invalid column index" <| action = table.aggregate [Group_By -3, Group_By "Index"] on_problems=_ - problems = [Column_Indexes_Out_Of_Range [-3]] + problems = [Column_Indexes_Out_Of_Range_Data [-3]] tester = expect_column_names ["Index"] Problems.test_problem_handling action problems tester Test.specify "should raise warnings when an invalid column index and no valid output" <| action = table.aggregate [Group_By -3] on_problems=_ - problems = [Column_Indexes_Out_Of_Range [-3], No_Output_Columns] + problems = [Column_Indexes_Out_Of_Range_Data [-3], No_Output_Columns] tester = expect_column_names [] Problems.test_problem_handling action problems tester Test.specify "should raise a warning when an invalid output name" <| action = table.aggregate [Group_By "Index" ""] on_problems=_ - problems = [Invalid_Output_Column_Names [""]] + problems = [Invalid_Output_Column_Names_Data [""]] tester = expect_column_names ["Column_1"] Problems.test_problem_handling action problems tester Test.specify "should raise a warning when a duplicate column name" <| action = table.aggregate [Group_By "Index", Group_By 0] on_problems=_ - problems = [Duplicate_Output_Column_Names ["Index"]] + problems = [Duplicate_Output_Column_Names_Data ["Index"]] tester = expect_column_names ["Index", "Index_1"] Problems.test_problem_handling action problems tester Test.specify "should raise a warning when a duplicate column name and rename default names first" <| action = table.aggregate [Group_By "Value", Group_By "Index" "Value"] on_problems=_ - problems = [Duplicate_Output_Column_Names ["Value"]] + problems = [Duplicate_Output_Column_Names_Data ["Value"]] tester = expect_column_names ["Value_1", "Value"] Problems.test_problem_handling action problems tester Test.specify "should allow partial matches on Count_Distinct" <| action = table.aggregate [Count_Distinct (By_Name ["Missing", "Value"])] on_problems=_ - problems = [Missing_Input_Columns ["Missing"]] + problems = [Missing_Input_Columns_Data ["Missing"]] tester = expect_column_names ["Count Distinct Value"] Problems.test_problem_handling action problems tester Test.specify "should ignore Count_Distinct if no columns matched" <| action = table.aggregate [Count_Distinct (By_Index [-100])] on_problems=_ - problems = [Column_Indexes_Out_Of_Range [-100], No_Output_Columns] + problems = [Column_Indexes_Out_Of_Range_Data [-100], No_Output_Columns] tester = expect_column_names [] Problems.test_problem_handling action problems tester @@ -1235,62 +1236,62 @@ aggregate_spec prefix table empty_table table_builder materialize is_database te Test.specify "should warn if grouping on a floating point" <| action = table.aggregate [Group_By 1] on_problems=_ - problems = [Floating_Point_Grouping "GroupBy" [2]] + problems = [Floating_Point_Grouping_Data "GroupBy" [2]] tester = expect_column_names ["Value"] Problems.test_problem_handling action problems tester Test.specify "should warn if totaling on a non number" <| action = table.aggregate [Sum "Text"] on_problems=_ - problems = [Invalid_Aggregation "Sum Text" [0] "Cannot convert to a number."] + problems = [Invalid_Aggregation_Data "Sum Text" [0] "Cannot convert to a number."] tester = expect_column_names ["Sum Text"] Problems.test_problem_handling action problems tester Test.specify "should warn if averaging on a non number" <| action = table.aggregate [Average "Text"] on_problems=_ - problems = [Invalid_Aggregation "Average Text" [0] "Cannot convert to a number."] + problems = [Invalid_Aggregation_Data "Average Text" [0] "Cannot convert to a number."] tester = expect_column_names ["Average Text"] Problems.test_problem_handling action problems tester Test.specify "should warn if calculating standard deviation on a non number" <| action = table.aggregate [Standard_Deviation "Text"] on_problems=_ - problems = [Invalid_Aggregation "Standard Deviation Text" [0] "Cannot convert to a number."] + problems = [Invalid_Aggregation_Data "Standard Deviation Text" [0] "Cannot convert to a number."] tester = expect_column_names ["Standard Deviation Text"] Problems.test_problem_handling action problems tester Test.specify "should warn if median on a non number" <| action = table.aggregate [Median "Text"] on_problems=_ - problems = [Invalid_Aggregation "Median Text" [0] "Cannot convert to a number."] + problems = [Invalid_Aggregation_Data "Median Text" [0] "Cannot convert to a number."] tester = expect_column_names ["Median Text"] Problems.test_problem_handling action problems tester Test.specify "should warn if trying shortest on a non text" <| action = table.aggregate [Shortest "Index"] on_problems=_ - problems = [Invalid_Aggregation "Shortest Index" [0] "Not a text value."] + problems = [Invalid_Aggregation_Data "Shortest Index" [0] "Not a text value."] tester = expect_column_names ["Shortest Index"] Problems.test_problem_handling action problems tester Test.specify "should warn if trying count empties on a non text" <| action = table.aggregate [Count_Empty "Index"] on_problems=_ - problems = [Invalid_Aggregation "Count Empty Index" [0] "Not a text value."] + problems = [Invalid_Aggregation_Data "Count Empty Index" [0] "Not a text value."] tester = expect_column_names ["Count Empty Index"] Problems.test_problem_handling action problems tester Test.specify "should warn if trying concatenate on a non text" <| action = table.aggregate [Concatenate "Index"] on_problems=_ - problems = [Invalid_Aggregation "Concatenate Index" [0] "Not a text value."] + problems = [Invalid_Aggregation_Data "Concatenate Index" [0] "Not a text value."] tester = expect_column_names ["Concatenate Index"] Problems.test_problem_handling action problems tester Test.specify "should warn if trying concatenate unquoted delimiters" <| column = Concatenate "Text" separator="," action = table.aggregate [column] on_problems=_ - problems = [Unquoted_Delimiter "Concatenate Text" [1]] + problems = [Unquoted_Delimiter_Data "Concatenate Text" [1]] tester = expect_column_names ["Concatenate Text"] Problems.test_problem_handling action problems tester Test.specify "should warn if can't compare value for Min or Max" <| action = table.aggregate [Maximum "Mixed"] on_problems=_ - problems = [Invalid_Aggregation "Maximum Mixed" [1] "Cannot compare values."] + problems = [Invalid_Aggregation_Data "Maximum Mixed" [1] "Cannot compare values."] tester = expect_column_names ["Maximum Mixed"] Problems.test_problem_handling action problems tester @@ -1305,14 +1306,14 @@ aggregate_spec prefix table empty_table table_builder materialize is_database te new_table = table.aggregate [Group_By "Key", Concatenate "Value"] problems = Warning.get_all new_table . map .value problems.length . should_equal 1 - problems.at 0 . is_an Invalid_Aggregation . should_be_true + problems.at 0 . is_an Invalid_Aggregation_Data . should_be_true problems.at 0 . rows . length . should_equal 15 Test.specify "should merge Floating Point Grouping warnings" <| new_table = table.aggregate [Group_By "Float", Count Nothing] problems = Warning.get_all new_table . map .value problems.length . should_equal 1 - problems.at 0 . is_an Floating_Point_Grouping . should_be_true + problems.at 0 . is_an Floating_Point_Grouping_Data . should_be_true problems.at 0 . rows . length . should_equal 9 if is_database then diff --git a/test/Table_Tests/src/In_Memory_Tests.enso b/test/Table_Tests/src/In_Memory_Tests.enso index 4c6eccc7b8d0..b9e7d60b8b26 100644 --- a/test/Table_Tests/src/In_Memory_Tests.enso +++ b/test/Table_Tests/src/In_Memory_Tests.enso @@ -9,9 +9,9 @@ import project.Delimited_Write_Spec import project.Excel_Spec import project.Json_Spec import project.Table_Spec -#import project.Table_Date_Spec -#import project.Aggregate_Column_Spec -#import project.Aggregate_Spec +import project.Table_Date_Spec +import project.Aggregate_Column_Spec +import project.Aggregate_Spec in_memory_spec = Column_Spec.spec @@ -21,8 +21,8 @@ in_memory_spec = Excel_Spec.spec Json_Spec.spec Table_Spec.spec - #Table_Date_Spec.spec - #Aggregate_Column_Spec.spec - #Aggregate_Spec.spec + Table_Date_Spec.spec + Aggregate_Column_Spec.spec + Aggregate_Spec.spec main = Test.Suite.run_main in_memory_spec diff --git a/test/Table_Tests/src/Table_Date_Spec.enso b/test/Table_Tests/src/Table_Date_Spec.enso index eda8481e0f6b..592bcfb87188 100644 --- a/test/Table_Tests/src/Table_Date_Spec.enso +++ b/test/Table_Tests/src/Table_Date_Spec.enso @@ -4,7 +4,7 @@ import Standard.Base.Data.Text.Line_Ending_Style import Standard.Table import Standard.Table.Data.Column import Standard.Table.IO.File_Format -from Standard.Table.Data.Data_Formatter as Data_Formatter_Module import Data_Formatter +from Standard.Table.Data.Data_Formatter as Data_Formatter_Module import Data_Formatter_Data import Standard.Test @@ -42,14 +42,14 @@ spec = Test.specify "should serialise back to input" <| expected_text = normalize_lines <| (enso_project.data / "prime_ministers.csv").read_text - delimited = Text.from expected format=(File_Format.Delimited "," line_endings=Line_Ending_Style.Unix) + delimited = Text.from expected format=(File_Format.Delimited_Data "," line_endings=Line_Ending_Style.Unix) delimited.should_equal expected_text Test.specify "should serialise dates with format" <| test_table = Table.new [c_from] expected_text = 'From\n04.05.1979\n28.11.1990\n02.05.1997\n27.06.2007\n11.05.2010\n13.07.2016\n24.07.2019\n' - data_formatter = Data_Formatter . with_datetime_formats date_formats=["dd.MM.yyyy"] - delimited = Text.from test_table format=(File_Format.Delimited "," value_formatter=data_formatter line_endings=Line_Ending_Style.Unix) + data_formatter = Data_Formatter_Data . with_datetime_formats date_formats=["dd.MM.yyyy"] + delimited = Text.from test_table format=(File_Format.Delimited_Data "," value_formatter=data_formatter line_endings=Line_Ending_Style.Unix) delimited.should_equal expected_text main = Test.Suite.run_main spec From cc29f1815e7dc0a49ff123edc282730da6a2ab7e Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 23 Aug 2022 17:31:46 +0200 Subject: [PATCH 062/110] more successes --- .../0.0.0-dev/src/Connection/Connection.enso | 18 ++++++------- .../0.0.0-dev/src/Connection/Database.enso | 4 +-- .../0.0.0-dev/src/Connection/Postgres.enso | 2 +- .../Database/0.0.0-dev/src/Data/Column.enso | 8 +++--- .../0.0.0-dev/src/Data/Dialect/Postgres.enso | 2 +- .../0.0.0-dev/src/Data/Dialect/SQLite.enso | 22 ++++++++-------- .../src/Data/Internal/Aggregate_Helper.enso | 8 +++--- .../src/Data/Internal/Base_Generator.enso | 10 +++---- .../Database/0.0.0-dev/src/Data/Table.enso | 26 +++++++++---------- .../Database/0.0.0-dev/src/Error.enso | 3 ++- .../0.0.0-dev/src/Internal/Table_Helpers.enso | 2 +- .../Standard/Table/0.0.0-dev/src/Main.enso | 2 +- test/Table_Tests/src/Aggregate_Spec.enso | 6 ++--- .../src/Database/Codegen_Spec.enso | 18 ++++++------- .../Table_Tests/src/Database/Common_Spec.enso | 4 +-- .../Helpers/Fake_Test_Connection.enso | 4 +-- test/Table_Tests/src/Database/Main.enso | 8 +++--- .../src/Database/Postgres_Spec.enso | 2 +- .../Table_Tests/src/Database/SQLite_Spec.enso | 16 ++++++------ test/Table_Tests/src/Main.enso | 4 +-- 20 files changed, 85 insertions(+), 84 deletions(-) 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 756a33738762..e74d017d5e2e 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 @@ -11,7 +11,7 @@ import Standard.Table.Data.Table as Materialized_Table import Standard.Table.Data.Storage import Standard.Table.Internal.Java_Exports import Standard.Database.Data.Internal.Base_Generator -from Standard.Database.Data.Sql import Sql_Type +from Standard.Database.Data.Sql import Sql_Type, Sql_Type_Data polyglot java import java.lang.UnsupportedOperationException polyglot java import java.util.ArrayList @@ -64,7 +64,7 @@ type Connection self.connection_resource.with connection-> metadata = connection.getMetaData schema_result_set = metadata.getCatalogs - Vector.Vector (JDBCProxy.getStringColumn schema_result_set "TABLE_CAT") + Vector.Vector_Data (JDBCProxy.getStringColumn schema_result_set "TABLE_CAT") ## Returns the list of schemas for the connection within the current database (or catalog). schemas : [Text] @@ -73,7 +73,7 @@ type Connection self.connection_resource.with connection-> metadata = connection.getMetaData schema_result_set = metadata.getSchemas - Vector.Vector (JDBCProxy.getStringColumn schema_result_set "TABLE_SCHEM") + Vector.Vector_Data (JDBCProxy.getStringColumn schema_result_set "TABLE_SCHEM") ## ADVANCED @@ -95,7 +95,7 @@ type Connection Vector.new ncols ix-> typeid = metadata.getColumnType ix+1 name = metadata.getColumnTypeName ix+1 - Sql_Type typeid name + Sql_Type_Data typeid name column_builders = column_types.map typ-> create_builder typ go has_next = if has_next.not then Nothing else @@ -165,7 +165,7 @@ type Connection name = metadata.getColumnName ix+1 typeid = metadata.getColumnType ix+1 typename = metadata.getColumnTypeName ix+1 - [name, Sql_Type typeid typename] + [name, Sql_Type_Data typeid typename] Vector.new ncols resolve_column ## PRIVATE @@ -186,7 +186,7 @@ type Connection - batch_size: Specifies how many rows should be uploaded in a single batch. upload_table : Text -> Materialized_Table -> Boolean -> Integer -> Database_Table - upload_table self name table temporary=True batch_size=1000 = Panic.recover Illegal_State_Error <| handle_sql_errors <| + upload_table self name table temporary=True batch_size=1000 = Panic.recover Illegal_State_Error_Data <| handle_sql_errors <| column_types = table.columns.map col-> default_storage_type col.storage_type column_names = table.columns.map .name col_makers = column_names.zip column_types name-> typ-> @@ -209,11 +209,11 @@ type Connection num_rows = table.row_count columns = table.columns check_rows updates_array expected_size = - updates = Vector.Vector updates_array - if updates.length != expected_size then Panic.throw <| Illegal_State_Error "The batch update unexpectedly affected "+updates.length.to_text+" rows instead of "+expected_size.to_text+"." else + updates = Vector.Vector_Data updates_array + if updates.length != expected_size then Panic.throw <| Illegal_State_Error_Data "The batch update unexpectedly affected "+updates.length.to_text+" rows instead of "+expected_size.to_text+"." else updates.each affected_rows-> if affected_rows != 1 then - Panic.throw <| Illegal_State_Error "A single update within the batch unexpectedly affected "+affected_rows.to_text+" rows." + Panic.throw <| Illegal_State_Error_Data "A single update within the batch unexpectedly affected "+affected_rows.to_text+" rows." 0.up_to num_rows . each row_id-> values = columns.map col-> col.at row_id holes = values.zip db_types diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Database.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Database.enso index eb1e6e8054ca..061b8a163ea1 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Database.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Database.enso @@ -1,6 +1,6 @@ from Standard.Base import all -from Standard.Database.Connection.Connection_Options import Connection_Options +from Standard.Database.Connection.Connection_Options import Connection_Options, Connection_Options_Data import Standard.Database.Connection.Postgres import Standard.Database.Connection.SQLite @@ -16,5 +16,5 @@ from Standard.Database.Connection.Connection import Connection, Sql_Error - details: Connection_Details to use to connect. - options: Any overriding options to use. connect : (Postgres|SQLite|Redshift) -> Connection_Options -> Connection ! Sql_Error -connect details options=Connection_Options = +connect details options=Connection_Options_Data = details.connect options diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Postgres.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Postgres.enso index 29303e845e8c..0ab807d0cb72 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Postgres.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Postgres.enso @@ -52,7 +52,7 @@ type Postgres Pair_Data Nothing Nothing -> Pgpass.read self.host self.port self.database Pair_Data Nothing _ -> - Error.throw (Illegal_State_Error "PGPASSWORD is set, but PGUSER is not.") + Error.throw (Illegal_State_Error_Data "PGPASSWORD is set, but PGUSER is not.") Pair_Data username Nothing -> Pgpass.read self.host self.port self.database username Pair_Data username password -> diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Column.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Column.enso index c9ff8e375788..ae7e61436a7e 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Column.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Column.enso @@ -68,7 +68,7 @@ type Column Converts this column into a single-column table. to_table : Table.Table to_table self = - Table.Table self.name self.connection [self.as_internal] self.context + Table.Table_Data self.name self.connection [self.as_internal] self.context ## UNSTABLE @@ -440,7 +440,7 @@ type Column True -> is_used_in_index = self.context.meta_index.exists i-> i.name == new_name case is_used_in_index of - True -> Error.throw <| Illegal_State_Error "Cannot rename the column to "+new_name+", because it has an index with the same name." + True -> Error.throw <| Illegal_State_Error_Data "Cannot rename the column to "+new_name+", because it has an index with the same name." False -> Column_Data new_name self.connection self.sql_type self.expression self.context @@ -510,7 +510,7 @@ type Column ## PRIVATE as_internal : IR.Internal_Column - as_internal self = IR.Internal_Column self.name self.sql_type self.expression + as_internal self = IR.Internal_Column_Data self.name self.sql_type self.expression type Aggregate_Column_Builder @@ -630,7 +630,7 @@ lift_aggregate new_name connection expected_type expr context = # aggregate into a subquery, thus making it safe to use it everywhere. A # more complex solution may be adopted at some point. ixes = Table.freshen_columns [new_name] context.meta_index - col = IR.Internal_Column new_name expected_type expr + col = IR.Internal_Column_Data new_name expected_type expr setup = context.as_subquery new_name+"_sub" [[col], ixes] subquery = setup.first cols = setup.second diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso index 20245e85e5bb..2add43436d3a 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso @@ -150,7 +150,7 @@ first_last_aggregators = [["FIRST", first], ["FIRST_NOT_NULL", first_not_null], ["LAST", last], ["LAST_NOT_NULL", last_not_null]] make_first_aggregator reverse ignore_null args = - if args.length < 2 then Error.throw (Illegal_State_Error "Insufficient number of arguments for the operation.") else + if args.length < 2 then Error.throw (Illegal_State_Error_Data "Insufficient number of arguments for the operation.") else result_expr = args.head order_bys = args.tail diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/SQLite.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/SQLite.enso index ad57b633a3e8..f23473fe4b09 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/SQLite.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/SQLite.enso @@ -7,7 +7,7 @@ import Standard.Database.Data.Dialect import Standard.Database.Data.Dialect.Helpers import Standard.Database.Data.Internal.Base_Generator import Standard.Database.Data.Internal.IR -from Standard.Database.Error import Unsupported_Database_Operation_Error +from Standard.Database.Error import Unsupported_Database_Operation_Error_Data ## PRIVATE @@ -53,19 +53,19 @@ type SQLite_Dialect prepare_order_descriptor : IR.Internal_Column -> Sort_Direction -> Text_Ordering -> IR.Order_Descriptor prepare_order_descriptor self internal_column sort_direction text_ordering = case internal_column.sql_type.is_likely_text of True -> - if text_ordering.sort_digits_as_numbers then Error.throw (Unsupported_Database_Operation_Error "Natural ordering is not supported by the SQLite backend. You may need to materialize the Table to perform this operation.") else + if text_ordering.sort_digits_as_numbers then Error.throw (Unsupported_Database_Operation_Error_Data "Natural ordering is not supported by the SQLite backend. You may need to materialize the Table to perform this operation.") else case text_ordering.case_sensitive of Nothing -> - IR.Order_Descriptor internal_column.expression sort_direction collation=Nothing + IR.Order_Descriptor_Data internal_column.expression sort_direction collation=Nothing True -> - IR.Order_Descriptor internal_column.expression sort_direction collation="BINARY" + IR.Order_Descriptor_Data internal_column.expression sort_direction collation="BINARY" Case_Insensitive_Data locale -> case locale == Locale.default of False -> - Error.throw (Unsupported_Database_Operation_Error "Case insensitive ordering with custom locale is not supported by the SQLite backend. You may need to materialize the Table to perform this operation.") + Error.throw (Unsupported_Database_Operation_Error_Data "Case insensitive ordering with custom locale is not supported by the SQLite backend. You may need to materialize the Table to perform this operation.") True -> - IR.Order_Descriptor internal_column.expression sort_direction collation="NOCASE" + IR.Order_Descriptor_Data internal_column.expression sort_direction collation="NOCASE" False -> - IR.Order_Descriptor internal_column.expression sort_direction collation=Nothing + IR.Order_Descriptor_Data internal_column.expression sort_direction collation=Nothing ## PRIVATE make_internal_generator_dialect = @@ -104,7 +104,7 @@ resolve_target_sql_type aggregate = case aggregate of ## PRIVATE unsupported name = - Error.throw (Unsupported_Database_Operation_Error name+" is not supported by SQLite backend. You may need to materialize the table and perform the operation in-memory.") + Error.throw (Unsupported_Database_Operation_Error_Data name+" is not supported by SQLite backend. You may need to materialize the table and perform the operation in-memory.") ## PRIVATE agg_count_is_null = Base_Generator.lift_unary_op "COUNT_IS_NULL" arg-> @@ -148,7 +148,7 @@ first_last_aggregators = ## PRIVATE window_aggregate window_type ignore_null args = - if args.length < 2 then Error.throw (Illegal_State_Error "Insufficient number of arguments for the operation.") else + if args.length < 2 then Error.throw (Illegal_State_Error_Data "Insufficient number of arguments for the operation.") else result_expr = args.head order_exprs = args.tail @@ -168,7 +168,7 @@ concat_ops = ## PRIVATE agg_count_distinct args = case args.length == 1 of True -> Sql.code "COUNT(DISTINCT (" ++ args.first ++ Sql.code "))" - False -> Error.throw (Illegal_Argument_Error "COUNT_DISTINCT supports only single arguments in SQLite.") + False -> Error.throw (Illegal_Argument_Error_Data "COUNT_DISTINCT supports only single arguments in SQLite.") ## PRIVATE agg_count_distinct_include_null args = case args.length == 1 of @@ -177,7 +177,7 @@ agg_count_distinct_include_null args = case args.length == 1 of count = Sql.code "COUNT(DISTINCT " ++ arg ++ Sql.code ")" all_nulls_case = Sql.code "CASE WHEN COUNT(CASE WHEN " ++ arg ++ Sql.code "IS NULL THEN 1 END) > 0 THEN 1 ELSE 0 END" count ++ Sql.code " + " ++ all_nulls_case - False -> Error.throw (Illegal_Argument_Error "COUNT_DISTINCT supports only single arguments in SQLite.") + False -> Error.throw (Illegal_Argument_Error_Data "COUNT_DISTINCT supports only single arguments in SQLite.") ## PRIVATE starts_with = Base_Generator.lift_binary_op "starts_with" str-> sub-> diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Aggregate_Helper.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Aggregate_Helper.enso index 14d7b1e6f1d6..ae216bd4cc4f 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Aggregate_Helper.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Aggregate_Helper.enso @@ -4,7 +4,7 @@ from Standard.Base.Data.Text.Text_Ordering import Text_Ordering_Data from Standard.Table.Data.Aggregate_Column import all import Standard.Database.Data.Internal.IR from Standard.Database.Data.Sql import Sql_Type -from Standard.Database.Error import Unsupported_Database_Operation_Error +from Standard.Database.Error import Unsupported_Database_Operation_Error_Data ## PRIVATE Creates an `Internal_Column` that computes the specified statistic. @@ -16,7 +16,7 @@ make_aggregate_column : Table -> Aggregate_Column -> Text -> IR.Internal_Column make_aggregate_column table aggregate new_name = sql_type = table.connection.dialect.resolve_target_sql_type aggregate expression = make_expression aggregate table.connection.dialect - IR.Internal_Column new_name sql_type expression + IR.Internal_Column_Data new_name sql_type expression ## PRIVATE Creates an Internal Representation of the expression that computes a @@ -38,14 +38,14 @@ make_expression aggregate dialect = Percentile p c _ -> IR.Operation "PERCENTILE" [IR.Constant Sql_Type.double p, c.expression] Mode c _ -> IR.Operation "MODE" [c.expression] First c _ ignore_nothing order_by -> case is_non_empty_selector order_by of - False -> Error.throw (Unsupported_Database_Operation_Error "`First` aggregation requires at least one `order_by` column.") + False -> Error.throw (Unsupported_Database_Operation_Error_Data "`First` aggregation requires at least one `order_by` column.") True -> order_bys = order_by.columns.map c-> dialect.prepare_order_descriptor c.column.as_internal c.direction Text_Ordering_Data case ignore_nothing of False -> IR.Operation "FIRST" [c.expression]+order_bys True -> IR.Operation "FIRST_NOT_NULL" [c.expression]+order_bys Last c _ ignore_nothing order_by -> case is_non_empty_selector order_by of - False -> Error.throw (Unsupported_Database_Operation_Error "`Last` aggregation requires at least one `order_by` column.") + False -> Error.throw (Unsupported_Database_Operation_Error_Data "`Last` aggregation requires at least one `order_by` column.") True -> order_bys = order_by.columns.map c-> dialect.prepare_order_descriptor c.column.as_internal c.direction Text_Ordering_Data case ignore_nothing of diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Base_Generator.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Base_Generator.enso index 9f5be9e7cffe..6b7237b645f8 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Base_Generator.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Internal/Base_Generator.enso @@ -51,7 +51,7 @@ make_binary_op name = op = Sql.code " "+name+" " (arguments.at 0)++op++(arguments.at 1) . paren False -> - Error.throw <| Illegal_State_Error ("Invalid amount of arguments for operation " + name) + Error.throw <| Illegal_State_Error_Data ("Invalid amount of arguments for operation " + name) ## PRIVATE @@ -66,7 +66,7 @@ make_unary_op name = True -> (Sql.code name+" ")++(arguments.at 0) . paren False -> - Error.throw <| Illegal_State_Error ("Invalid amount of arguments for operation " + name) + Error.throw <| Illegal_State_Error_Data ("Invalid amount of arguments for operation " + name) ## PRIVATE @@ -80,7 +80,7 @@ make_unary_op name = lift_unary_op : Text -> (Sql.Builder -> Sql.Builder) -> [Text, (Vector Sql.Builder -> Sql.Builder)] lift_unary_op name function = generator = arguments -> case arguments.length == 1 of - False -> Error.throw <| Illegal_State_Error ("Invalid amount of arguments for operation " + name + ".") + False -> Error.throw <| Illegal_State_Error_Data ("Invalid amount of arguments for operation " + name + ".") True -> function (arguments.at 0) [name, generator] @@ -96,7 +96,7 @@ lift_unary_op name function = lift_binary_op : Text -> (Sql.Builder -> Sql.Builder -> Sql.Builder) -> [Text, (Vector Sql.Builder -> Sql.Builder)] lift_binary_op name function = generator = arguments -> case arguments.length == 2 of - False -> Error.throw <| Illegal_State_Error ("Invalid amount of arguments for operation " + name + ".") + False -> Error.throw <| Illegal_State_Error_Data ("Invalid amount of arguments for operation " + name + ".") True -> function (arguments.at 0) (arguments.at 1) [name, generator] @@ -136,7 +136,7 @@ make_function name = make_constant : Text -> Vector Sql.Builder -> Sql.Builder make_constant code = arguments -> - if arguments.not_empty then Error.throw <| Illegal_State_Error "No arguments were expected" else + if arguments.not_empty then Error.throw <| Illegal_State_Error_Data "No arguments were expected" else Sql.code code ## PRIVATE diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso index 778c8f2f2d5d..6f959025f01f 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso @@ -21,7 +21,7 @@ from Standard.Table.Data.Column_Selector import Column_Selector, By_Index from Standard.Base.Data.Text.Text_Ordering import Text_Ordering_Data from Standard.Table.Data.Data_Formatter import Data_Formatter from Standard.Base.Error.Problem_Behavior import Problem_Behavior, Report_Warning -from Standard.Database.Error import Unsupported_Database_Operation_Error +from Standard.Database.Error import Unsupported_Database_Operation_Error_Data import Standard.Table.Data.Column_Name_Mapping import Standard.Table.Data.Position import Standard.Table.Data.Sort_Column_Selector @@ -398,9 +398,9 @@ type Table True -> is_used_in_index = self.context.meta_index.exists i-> i.name == name case is_used_in_index of - True -> Error.throw <| Illegal_State_Error "Cannot override column "+name+", because it is used as an index. Remove the index or use a different name." + True -> Error.throw <| Illegal_State_Error_Data "Cannot override column "+name+", because it is used as an index. Remove the index or use a different name." False -> - new_col = Internal_Column name column.sql_type column.expression + new_col = Internal_Column_Data name column.sql_type column.expression replace = self.internal_columns.exists (c -> c.name == name) case replace of True -> @@ -548,7 +548,7 @@ type Table Table_Data _ _ _ _ -> Panic.recover Any <| Panic.rethrow (Helpers.ensure_name_is_sane left_suffix && Helpers.ensure_name_is_sane right_suffix) if left_suffix == right_suffix then - Panic.throw <| Illegal_State_Error "left_suffix must be different from right_suffix" + Panic.throw <| Illegal_State_Error_Data "left_suffix must be different from right_suffix" kind = if drop_unmatched then IR.Join_Inner else IR.Join_Left # Prepare the left and right pairs of indices along which the join will be performed. @@ -559,7 +559,7 @@ type Table (Helpers.unify_vector_singleton on).map (self.resolve >> .as_internal) right_join_index = other.context.meta_index if left_join_index.length != right_join_index.length then - Panic.throw <| Illegal_State_Error "Cannot join with multi-indexes of different lengths." + Panic.throw <| Illegal_State_Error_Data "Cannot join with multi-indexes of different lengths." # TODO [RW] We may be able to avoid creating subqueries if there are no groups, orders or wheres, # so it may be worth optimizing that here (#1515). @@ -612,7 +612,7 @@ type Table IR.Operation "=" [l.expression, r.expression] new_from = IR.Join kind left_subquery right_subquery on_exprs new_limit = Nothing - new_ctx = IR.Context new_from [] [] [] new_index new_limit + new_ctx = IR.Context_Data new_from [] [] [] new_index new_limit Table_Data new_table_name self.connection new_columns new_ctx @@ -653,7 +653,7 @@ type Table agg = p.second new_name = p.first Aggregate_Helper.make_aggregate_column self agg new_name . catch - partitioned = results.partition (_.is_an Internal_Column) + partitioned = results.partition (_.is_an Internal_Column_Data) ## When working on join we may encounter further issues with having aggregate columns exposed directly, it may be useful to re-use the `lift_aggregate` method to push the aggregates into a @@ -671,7 +671,7 @@ type Table because we need to keep the API consistent with the in-memory table. _ = [value_formatter, column_types, on_problems] msg = "Parsing values is not supported in database tables, the table has to be materialized first with `to_dataframe`." - Error.throw (Unsupported_Database_Operation_Error msg) + Error.throw (Unsupported_Database_Operation_Error_Data msg) ## UNSTABLE @@ -727,7 +727,7 @@ type Table to_dataframe : (Integer | Nothing) -> Materialized_Table.Table to_dataframe self max_rows=Nothing = case self.context.meta_index.length > 1 of - True -> Error.throw <| Illegal_State_Error "Multi-indexes are not implemented in the dataframes, if you want to materialize such a Table, remove the index first using `set_index`." + True -> Error.throw <| Illegal_State_Error_Data "Multi-indexes are not implemented in the dataframes, if you want to materialize such a Table, remove the index first using `set_index`." False -> preprocessed = self.reset_index.limit max_rows case preprocessed.internal_columns.is_empty of @@ -760,7 +760,7 @@ type Table to_sql self = cols = self.internal_columns.map (c -> [c.name, c.expression]) case cols.is_empty of - True -> Error.throw <| Unsupported_Database_Operation_Error "Cannot generate SQL for a table with no columns." + True -> Error.throw <| Unsupported_Database_Operation_Error_Data "Cannot generate SQL for a table with no columns." False -> query = IR.Select cols self.context self.connection.dialect.generate_sql query @@ -854,14 +854,14 @@ type Table insert self values = table_name = case self.context.from_spec of IR.From_Table name _ -> name - _ -> Error.throw <| Illegal_State_Error "Inserting can only be performed on tables as returned by `access_table`, any further processing is not allowed." + _ -> Error.throw <| Illegal_State_Error_Data "Inserting can only be performed on tables as returned by `access_table`, any further processing is not allowed." # TODO [RW] before removing the PRIVATE tag, add a check that no bad stuff was done to the table as described above pairs = self.internal_columns.zip values col-> value-> [col.name, IR.Constant col.sql_type value] query = self.connection.dialect.generate_sql <| IR.Insert table_name pairs affected_rows = self.connection.execute_update query case affected_rows == 1 of - False -> Error.throw <| Illegal_State_Error "The update unexpectedly affected "+affected_rows.to_text+" rows." + False -> Error.throw <| Illegal_State_Error_Data "The update unexpectedly affected "+affected_rows.to_text+" rows." True -> Nothing ## This function writes the table into a file. @@ -1021,7 +1021,7 @@ combine_names left_names right_names left_suffix right_suffix = new_name = pair.second case new_name!=original_name && (new_names_count new_name > 1) of True -> - Panic.throw <| Illegal_State_Error "Duplicate column "+original_name+" was about to be renamed to "+new_name+" to disambiguate column names, but a column with name "+new_name+" already exists too. Please rename the columns before joining to avoid ambiguity." + Panic.throw <| Illegal_State_Error_Data "Duplicate column "+original_name+" was about to be renamed to "+new_name+" to disambiguate column names, but a column with name "+new_name+" already exists too. Please rename the columns before joining to avoid ambiguity." False -> Nothing catch_ambiguity left_pairs catch_ambiguity right_pairs diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Error.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Error.enso index ba70520315dd..61d2279aec5a 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Error.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Error.enso @@ -2,7 +2,8 @@ from Standard.Base import all ## Indicates that a requested operation is not supported, for example because a particular database backend does not support it. -type Unsupported_Database_Operation_Error message +type Unsupported_Database_Operation_Error + Unsupported_Database_Operation_Error_Data message Unsupported_Database_Operation_Error.to_display_text : Text Unsupported_Database_Operation_Error.to_display_text self = diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Table_Helpers.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Table_Helpers.enso index 0d07eaa0caff..f682ea8afe25 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Table_Helpers.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Internal/Table_Helpers.enso @@ -259,7 +259,7 @@ resolve_column_helper internal_columns selector problem_builder = case selector matched_columns = Matching.match_criteria_callback (Text_Matcher_Data case_sensitive=True) internal_columns [selector] reorder=True name_mapper=(_.name) problem_callback=problem_builder.report_missing_input_columns if matched_columns.length == 1 then matched_columns.first else if matched_columns.length == 0 then Nothing else - Panic.throw (Illegal_State_Error "A single exact match should never match more than one column. Perhaps the table breaks the invariant of unique column names?") + Panic.throw (Illegal_State_Error_Data "A single exact match should never match more than one column. Perhaps the table breaks the invariant of unique column names?") Integer -> case is_index_valid internal_columns.length selector of True -> internal_columns.at selector False -> diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso index c24aa4d6eb99..bf3a72ea335d 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso @@ -13,7 +13,7 @@ export Standard.Table.Data.Column export Standard.Table.IO.File_Read export Standard.Table.IO.File_Format -from Standard.Table.Data.Table export new, from_rows, join, concat, No_Such_Column_Error, Table, Table_Data +from Standard.Table.Data.Table export new, from_rows, join, concat, No_Such_Column_Error, No_Such_Column_Error_Data, Table, Table_Data ## ALIAS To Table diff --git a/test/Table_Tests/src/Aggregate_Spec.enso b/test/Table_Tests/src/Aggregate_Spec.enso index 3cfb8026d1ed..9a91da05467e 100644 --- a/test/Table_Tests/src/Aggregate_Spec.enso +++ b/test/Table_Tests/src/Aggregate_Spec.enso @@ -6,7 +6,7 @@ import Standard.Table.Data.Sort_Column import Standard.Table.Data.Sort_Column_Selector from Standard.Table.Data.Aggregate_Column import all from Standard.Table.Errors as Error_Module import Missing_Input_Columns_Data, Column_Indexes_Out_Of_Range_Data, No_Output_Columns, Duplicate_Output_Column_Names_Data, Invalid_Output_Column_Names_Data, Invalid_Aggregation_Data, Floating_Point_Grouping_Data, Unquoted_Delimiter_Data, Additional_Warnings_Data -from Standard.Database.Error as Database_Errors import Unsupported_Database_Operation_Error +from Standard.Database.Error as Database_Errors import Unsupported_Database_Operation_Error_Data import Standard.Test import Standard.Test.Problems @@ -1163,7 +1163,7 @@ aggregate_spec prefix table empty_table table_builder materialize is_database te materialized.columns.length . should_equal 1 materialized.columns.first.name . should_equal "Sum A" materialized.columns.first.to_vector . should_equal [6] - problems = [Unsupported_Database_Operation_Error "`First` aggregation requires at least one `order_by` column.", Unsupported_Database_Operation_Error "`Last` aggregation requires at least one `order_by` column."] + problems = [Unsupported_Database_Operation_Error_Data "`First` aggregation requires at least one `order_by` column.", Unsupported_Database_Operation_Error_Data "`Last` aggregation requires at least one `order_by` column."] Problems.test_problem_handling action problems tester Test.group prefix+"Table.aggregate should raise warnings when there are issues" pending=(resolve_pending test_selection.problem_handling pending) <| @@ -1325,7 +1325,7 @@ aggregate_spec prefix table empty_table table_builder materialize is_database te warnings = Warning.get_all result . map .value warnings.length . should_equal error_count warnings.each warning-> - warning.should_be_an Unsupported_Database_Operation_Error + warning.should_be_an Unsupported_Database_Operation_Error_Data if test_selection.first_last_row_order.not then Test.specify "with First and Last in row order" <| diff --git a/test/Table_Tests/src/Database/Codegen_Spec.enso b/test/Table_Tests/src/Database/Codegen_Spec.enso index 463136cbcb75..7e83cfe2bbbc 100644 --- a/test/Table_Tests/src/Database/Codegen_Spec.enso +++ b/test/Table_Tests/src/Database/Codegen_Spec.enso @@ -4,14 +4,14 @@ from Standard.Table.Data.Column_Selector as Column_Selector_Module import By_Nam import Standard.Table.Data.Sort_Column_Selector import Standard.Table.Data.Sort_Column from Standard.Table.Data.Aggregate_Column import all -from Standard.Table import No_Such_Column_Error -from Standard.Table.Errors as Table_Errors import No_Input_Columns_Selected, Missing_Input_Columns +from Standard.Table import No_Such_Column_Error_Data +from Standard.Table.Errors as Table_Errors import No_Input_Columns_Selected, Missing_Input_Columns_Data from Standard.Database import all from Standard.Database.Data.Sql import Sql_Type import Standard.Database.Data.Dialect import Standard.Database.Data.Table as Table_Module -from Standard.Database.Error as Database_Errors import Unsupported_Database_Operation_Error +from Standard.Database.Error as Database_Errors import Unsupported_Database_Operation_Error_Data import Standard.Test import Standard.Test.Problems @@ -55,7 +55,7 @@ spec = t3.to_sql.prepare . should_equal ['SELECT "T1"."C" AS "C", "T1"."B" AS "B", "T1"."A" AS "bar" FROM "T1" AS "T1"', []] Test.specify "should fail if at is called for a non-existent column" <| - t1.at "undefined" . should_fail_with No_Such_Column_Error + t1.at "undefined" . should_fail_with No_Such_Column_Error_Data Test.specify "should allow to limit the amount of returned results" <| t2 = t1.limit 5 @@ -66,7 +66,7 @@ spec = json = Json.from_pairs [["query", Nothing], ["message", "The table has no columns so a query cannot be generated."]] empty.to_json . should_equal json empty.columns.length . should_equal 0 - empty.to_sql . should_fail_with Unsupported_Database_Operation_Error + empty.to_sql . should_fail_with Unsupported_Database_Operation_Error_Data Test.group "[Codegen] Building Expressions" <| Test.specify "should allow building expressions from columns and constants" <| @@ -128,11 +128,11 @@ spec = Fake_Test_Connection.make Dialect.sqlite tables t1 = connection.access_table "T1" t2 = connection.access_table "T2" - (t1.set_index "X").join (t2.set_index "X") . should_fail_with Illegal_State_Error + (t1.set_index "X").join (t2.set_index "X") . should_fail_with Illegal_State_Error_Data Test.specify "should ensure that name suffixes are distinct" <| err = (t1.set_index 'A').join (t2.set_index 'D') left_suffix='foo' right_suffix='foo' - err . should_fail_with Illegal_State_Error + err . should_fail_with Illegal_State_Error_Data Test.specify "should correctly handle self-joins" <| r1 = t1.join (t1.set_index 'A') on='B' @@ -171,7 +171,7 @@ spec = action = t1.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name 'foobar']) on_problems=_ tester table = table.to_sql.prepare . should_equal ['SELECT "T1"."A" AS "A", "T1"."B" AS "B", "T1"."C" AS "C" FROM "T1" AS "T1"', []] - problems = [Missing_Input_Columns [Sort_Column.Name 'foobar'], No_Input_Columns_Selected] + problems = [Missing_Input_Columns_Data [Sort_Column.Name 'foobar'], No_Input_Columns_Selected] Problems.test_problem_handling action problems tester Test.group "Helpers" <| @@ -182,7 +182,7 @@ spec = combined.first . should_equal ["A_1", "B"] combined.second . should_equal ["A_2", "C"] - Test.expect_panic_with (Table_Module.combine_names ["A", "A_1"] ["A"] "_1" "_2") Illegal_State_Error + Test.expect_panic_with (Table_Module.combine_names ["A", "A_1"] ["A"] "_1" "_2") Illegal_State_Error_Data Test.specify "fresh_names should provide fresh names" <| used_names = ["A", "A_1"] preferred_names = ["A", "A", "B"] diff --git a/test/Table_Tests/src/Database/Common_Spec.enso b/test/Table_Tests/src/Database/Common_Spec.enso index 4faa6b2bb5e3..b1502349a31b 100644 --- a/test/Table_Tests/src/Database/Common_Spec.enso +++ b/test/Table_Tests/src/Database/Common_Spec.enso @@ -4,7 +4,7 @@ from Standard.Table.Data.Column_Selector as Column_Selector_Module import By_Nam import Standard.Table.Data.Table as Materialized_Table import Standard.Table.Data.Sort_Column_Selector import Standard.Table.Data.Sort_Column -from Standard.Table.Errors as Table_Errors import No_Input_Columns_Selected, Missing_Input_Columns +from Standard.Table.Errors as Table_Errors import No_Input_Columns_Selected, Missing_Input_Columns_Data from Standard.Table.Data.Aggregate_Column import all from Standard.Database import all @@ -245,7 +245,7 @@ spec prefix connection pending=Nothing = action = df.order_by (Sort_Column_Selector.By_Name [Sort_Column.Name 'foobar']) on_problems=_ tester table = table.at 'id' . to_vector . should_equal [1,2,3,4,5,6] - problems = [Missing_Input_Columns [Sort_Column.Name 'foobar'], No_Input_Columns_Selected] + problems = [Missing_Input_Columns_Data [Sort_Column.Name 'foobar'], No_Input_Columns_Selected] Problems.test_problem_handling action problems tester Test.specify 'should correctly reorder all kinds of columns and leave the original columns untouched' <| diff --git a/test/Table_Tests/src/Database/Helpers/Fake_Test_Connection.enso b/test/Table_Tests/src/Database/Helpers/Fake_Test_Connection.enso index 58b690950aee..d32ba363985b 100644 --- a/test/Table_Tests/src/Database/Helpers/Fake_Test_Connection.enso +++ b/test/Table_Tests/src/Database/Helpers/Fake_Test_Connection.enso @@ -5,7 +5,7 @@ import Standard.Database.Data.Table as Database_Table type Fake_Test_Connection # type Fake_Test_Connection (tables : Map Text (Vector [Text, Sql_Type])) # (dialect : Text) - type Fake_Test_Connection tables dialect + Fake_Test_Connection_Data tables dialect ## PRIVATE access_table : Text -> Database_Table @@ -34,4 +34,4 @@ type Fake_Test_Connection ## PRIVATE make dialect tables = - Fake_Test_Connection tables dialect + Fake_Test_Connection_Data tables dialect diff --git a/test/Table_Tests/src/Database/Main.enso b/test/Table_Tests/src/Database/Main.enso index 5e93566f917d..7bafa19fe257 100644 --- a/test/Table_Tests/src/Database/Main.enso +++ b/test/Table_Tests/src/Database/Main.enso @@ -4,13 +4,13 @@ import Standard.Test import project.Database.Codegen_Spec import project.Database.SQLite_Spec -import project.Database.Postgres_Spec -import project.Database.Redshift_Spec +#import project.Database.Postgres_Spec +#import project.Database.Redshift_Spec databases_spec = Codegen_Spec.spec SQLite_Spec.spec - Postgres_Spec.spec - Redshift_Spec.spec + #Postgres_Spec.spec + #Redshift_Spec.spec main = Test.Suite.run_main databases_spec diff --git a/test/Table_Tests/src/Database/Postgres_Spec.enso b/test/Table_Tests/src/Database/Postgres_Spec.enso index 3c262999d835..046c177fe6dd 100644 --- a/test/Table_Tests/src/Database/Postgres_Spec.enso +++ b/test/Table_Tests/src/Database/Postgres_Spec.enso @@ -258,7 +258,7 @@ connection_setup_spec = Test.group "[PostgreSQL] Connection setup" <| c1.jdbc_properties . should_equal <| add_ssl [] Test_Environment.unsafe_with_environment_override "PGPASSWORD" "somepassword" <| - c1.jdbc_properties . should_fail_with Illegal_State_Error + c1.jdbc_properties . should_fail_with Illegal_State_Error_Data c1.jdbc_properties.catch.message . should_equal "PGPASSWORD is set, but PGUSER is not." Test_Environment.unsafe_with_environment_override "PGUSER" "someuser" <| diff --git a/test/Table_Tests/src/Database/SQLite_Spec.enso b/test/Table_Tests/src/Database/SQLite_Spec.enso index 71ee10e78ac7..4e9da4d03947 100644 --- a/test/Table_Tests/src/Database/SQLite_Spec.enso +++ b/test/Table_Tests/src/Database/SQLite_Spec.enso @@ -4,7 +4,7 @@ import Standard.Base.Runtime.Ref import Standard.Table as Materialized_Table from Standard.Database import all -from Standard.Database.Connection.Connection import Sql_Error +from Standard.Database.Connection.Connection import Sql_Error_Data import Standard.Test @@ -16,11 +16,11 @@ import project.Aggregate_Spec sqlite_specific_spec connection = Test.group "[SQLite] Error Handling" <| Test.specify "should wrap errors" <| - connection.execute_query "foobar" . should_fail_with Sql_Error - connection.execute_update "foobar" . should_fail_with Sql_Error + connection.execute_query "foobar" . should_fail_with Sql_Error_Data + connection.execute_update "foobar" . should_fail_with Sql_Error_Data action = connection.execute_query "SELECT A FROM undefined_table" - action . should_fail_with Sql_Error + action . should_fail_with Sql_Error_Data action.catch.to_text . should_equal "There was an SQL error: '[SQLITE_ERROR] SQL error or missing database (no such table: undefined_table)'. [Query was: SELECT A FROM undefined_table]" Test.group "[SQLite] Metadata" <| @@ -59,7 +59,7 @@ sqlite_spec connection prefix = Common_Spec.spec prefix connection sqlite_specific_spec connection - common_selection = Common_Table_Spec.Test_Selection supports_case_sensitive_columns=False order_by=True natural_ordering=False case_insensitive_ordering=True case_insensitive_ascii_only=True + common_selection = Common_Table_Spec.Test_Selection_Data supports_case_sensitive_columns=False order_by=True natural_ordering=False case_insensitive_ordering=True case_insensitive_ascii_only=True Common_Table_Spec.spec prefix table_builder test_selection=common_selection ## For now `advanced_stats`, `first_last`, `text_shortest_longest` and @@ -70,7 +70,7 @@ sqlite_spec connection prefix = - creating complex nested queries using NTILE to compute the stats, - compiling SQLite library on our own and adding native extensions for the missing statistics. - selection = Aggregate_Spec.Test_Selection advanced_stats=False text_shortest_longest=False first_last=False first_last_row_order=False multi_distinct=False aggregation_problems=False nan=False + selection = Aggregate_Spec.Test_Selection_Data advanced_stats=False text_shortest_longest=False first_last=False first_last_row_order=False multi_distinct=False aggregation_problems=False nan=False agg_in_memory_table = (enso_project.data / "data.csv") . read agg_table = connection.upload_table (Name_Generator.random_name "Agg1") agg_in_memory_table empty_agg_table = connection.upload_table (Name_Generator.random_name "Agg_Empty") (agg_in_memory_table.take_start 0) @@ -82,9 +82,9 @@ spec = enso_project.data.create_directory file = enso_project.data / "sqlite_test.db" file.delete_if_exists - sqlite_spec (Database.connect (SQLite file)) "[SQLite] " + sqlite_spec (Database.connect (SQLite_Data file)) "[SQLite] " file.delete - sqlite_spec (Database.connect (SQLite In_Memory)) "[SQLite Memory] " + sqlite_spec (Database.connect (SQLite_Data In_Memory)) "[SQLite Memory] " main = Test.Suite.run_main spec diff --git a/test/Table_Tests/src/Main.enso b/test/Table_Tests/src/Main.enso index 1bf6a1bfb26f..0b12bc11daa5 100644 --- a/test/Table_Tests/src/Main.enso +++ b/test/Table_Tests/src/Main.enso @@ -3,12 +3,12 @@ from Standard.Base import all import Standard.Test import project.In_Memory_Tests -#import project.Database.Main as Database_Tests +import project.Database.Main as Database_Tests import project.File_Read_Spec import project.Data_Formatter_Spec main = Test.Suite.run_main <| In_Memory_Tests.in_memory_spec - #Database_Tests.databases_spec + Database_Tests.databases_spec File_Read_Spec.spec Data_Formatter_Spec.spec From b9f771cd529fe8b2fbae4b7a67a02e66b886a1d4 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 25 Aug 2022 13:20:01 +0200 Subject: [PATCH 063/110] rest of db specs --- .../0.0.0-dev/src/Connection/Postgres.enso | 4 +- .../src/Internal/Postgres/Pgpass.enso | 2 +- test/Table_Tests/src/Database/Main.enso | 8 +- .../src/Database/Postgres_Spec.enso | 84 +++++++++---------- .../src/Database/Redshift_Spec.enso | 8 +- 5 files changed, 53 insertions(+), 53 deletions(-) diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Postgres.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Postgres.enso index 0ab807d0cb72..6e3f88c47148 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Postgres.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Connection/Postgres.enso @@ -1,6 +1,6 @@ from Standard.Base import all -from Standard.Base.Data.Numbers import Parse_Error +from Standard.Base.Data.Numbers import Parse_Error_Data import Standard.Database.Data.Dialect import Standard.Database.Connection.Connection @@ -94,7 +94,7 @@ default_postgres_port = hardcoded_port = 5432 case Environment.get "PGPORT" of Nothing -> hardcoded_port - port -> Integer.parse port . catch Parse_Error (_->hardcoded_port) + port -> Integer.parse port . catch Parse_Error_Data (_->hardcoded_port) ## PRIVATE default_postgres_database = Environment.get_or_else "PGDATABASE" "" diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Internal/Postgres/Pgpass.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Internal/Postgres/Pgpass.enso index 1cd33927fb96..f051a4bb1cea 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Internal/Postgres/Pgpass.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Internal/Postgres/Pgpass.enso @@ -33,7 +33,7 @@ read host port database username=Nothing = entry.matches host port database username case found.catch Nothing of Nothing -> [] - entry -> [Pair 'user' entry.username, Pair 'password' entry.password] + entry -> [Pair_Data 'user' entry.username, Pair_Data 'password' entry.password] type Pgpass_Entry ## PRIVATE diff --git a/test/Table_Tests/src/Database/Main.enso b/test/Table_Tests/src/Database/Main.enso index 7bafa19fe257..5e93566f917d 100644 --- a/test/Table_Tests/src/Database/Main.enso +++ b/test/Table_Tests/src/Database/Main.enso @@ -4,13 +4,13 @@ import Standard.Test import project.Database.Codegen_Spec import project.Database.SQLite_Spec -#import project.Database.Postgres_Spec -#import project.Database.Redshift_Spec +import project.Database.Postgres_Spec +import project.Database.Redshift_Spec databases_spec = Codegen_Spec.spec SQLite_Spec.spec - #Postgres_Spec.spec - #Redshift_Spec.spec + Postgres_Spec.spec + Redshift_Spec.spec main = Test.Suite.run_main databases_spec diff --git a/test/Table_Tests/src/Database/Postgres_Spec.enso b/test/Table_Tests/src/Database/Postgres_Spec.enso index 046c177fe6dd..d87b293ac082 100644 --- a/test/Table_Tests/src/Database/Postgres_Spec.enso +++ b/test/Table_Tests/src/Database/Postgres_Spec.enso @@ -11,7 +11,7 @@ from Standard.Table.Data.Aggregate_Column import all from Standard.Database import all from Standard.Database.Connection.Connection import Sql_Error from Standard.Database.Data.Sql import Sql_Type -from Standard.Database.Internal.Postgres.Pgpass import Pgpass_Entry +from Standard.Database.Internal.Postgres.Pgpass import Pgpass_Entry_Data import Standard.Database.Internal.Postgres.Pgpass import Standard.Test @@ -108,10 +108,10 @@ run_tests connection pending=Nothing = Common_Spec.spec prefix connection pending=pending postgres_specific_spec connection pending=pending - common_selection = Common_Table_Spec.Test_Selection supports_case_sensitive_columns=True order_by_unicode_normalization_by_default=True + common_selection = Common_Table_Spec.Test_Selection_Data supports_case_sensitive_columns=True order_by_unicode_normalization_by_default=True Common_Table_Spec.spec prefix table_builder test_selection=common_selection pending=pending - selection = Aggregate_Spec.Test_Selection first_last_row_order=False aggregation_problems=False + selection = Aggregate_Spec.Test_Selection_Data first_last_row_order=False aggregation_problems=False agg_in_memory_table = (enso_project.data / "data.csv") . read agg_table = connection.upload_table (Name_Generator.random_name "Agg1") agg_in_memory_table tables.append agg_table.name @@ -133,27 +133,27 @@ table_spec = ssl_pending = if ca_cert_file.is_nothing then "PostgreSQL SSL test not configured." else Nothing Test.group "[PostgreSQL] SSL connectivity tests" pending=ssl_pending <| Test.specify "should connect without ssl parameter" <| - Database.connect (Postgres db_host db_port db_name (Credentials db_user db_password)) . should_succeed + Database.connect (Postgres_Data db_host db_port db_name (Credentials_Data db_user db_password)) . should_succeed Test.specify "should connect, requiring SSL" <| - Database.connect (Postgres db_host db_port db_name (Credentials db_user db_password) use_ssl=Require) . should_succeed + Database.connect (Postgres_Data db_host db_port db_name (Credentials_Data db_user db_password) use_ssl=Require) . should_succeed Test.specify "should connect be able to verify the certificate" <| - Database.connect (Postgres db_host db_port db_name (Credentials db_user db_password) use_ssl=(Verify_CA ca_cert_file)) . should_succeed + Database.connect (Postgres_Data db_host db_port db_name (Credentials_Data db_user db_password) use_ssl=(Verify_CA ca_cert_file)) . should_succeed ## Default certificate should not accept the self signed certificate. - ca_fail = Database.connect (Postgres db_host db_port db_name (Credentials db_user db_password) use_ssl=Verify_CA) + ca_fail = Database.connect (Postgres_Data db_host db_port db_name (Credentials_Data db_user db_password) use_ssl=Verify_CA) ca_fail.is_error . should_equal True ca_fail.catch Sql_Error . is_a Sql_Error . should_equal True Test.specify "should connect be able to verify the host name against the certificate" <| - Database.connect (Postgres db_host db_port db_name (Credentials db_user db_password) use_ssl=(Full_Verification ca_cert_file)) . should_succeed + Database.connect (Postgres_Data db_host db_port db_name (Credentials_Data db_user db_password) use_ssl=(Full_Verification ca_cert_file)) . should_succeed alternate_host = Environment.get "ENSO_DATABASE_TEST_ALTERNATE_HOST" . if_nothing <| if db_host == "127.0.0.1" then "localhost" else Nothing pending_alternate = if alternate_host.is_nothing then "Alternative host name not configured." else Nothing Test.specify "should fail to connect with alternate host name not valid in certificate" pending=pending_alternate <| - ca_fail = Database.connect (Postgres alternate_host db_port db_name (Credentials db_user db_password) use_ssl=(Full_Verification ca_cert_file)) + ca_fail = Database.connect (Postgres_Data alternate_host db_port db_name (Credentials_Data db_user db_password) use_ssl=(Full_Verification ca_cert_file)) ca_fail.is_error . should_equal True ca_fail.catch Sql_Error . is_a Sql_Error . should_equal True @@ -163,7 +163,7 @@ table_spec = connection = Error.throw message run_tests connection pending=message False -> - connection = Database.connect (Postgres (db_host_port.at 0) db_port db_name (Credentials db_user db_password)) + connection = Database.connect (Postgres_Data (db_host_port.at 0) db_port db_name (Credentials_Data db_user db_password)) run_tests connection @@ -171,22 +171,22 @@ pgpass_file = enso_project.data / "pgpass.conf" pgpass_spec = Test.group "[PostgreSQL] .pgpass" <| make_pair username password = - [Pair "user" username, Pair "password" password] + [Pair_Data "user" username, Pair_Data "password" password] Test.specify "should correctly parse the file, including escapes, blank lines and comments" <| result = Pgpass.parse_file pgpass_file result.length . should_equal 12 - e1 = Pgpass_Entry "localhost" "5432" "postgres" "postgres" "postgres" - e2 = Pgpass_Entry "192.168.4.0" "1234" "foo" "bar" "baz" - e3 = Pgpass_Entry "host with : semicolons in it? what?" "*" "*" "*" "well yes, that is possible, the :password: can contain those as well" - e4 = Pgpass_Entry ":" ":" ":" ":" ":" - e5 = Pgpass_Entry "you can escape an escape too: see \\" "*" "*" "*" "yes it is possible" - e6 = Pgpass_Entry "other escapes like \n or \? " "*" "*" "*" "are just parsed as-is" - e7 = Pgpass_Entry "a trailing escape character" "*" "*" "*" "is treated as a regular slash\" - e8 = Pgpass_Entry "passwords should preserve leading space" "*" "*" "*" " pass" - e9 = Pgpass_Entry "\:" "*" "*" "*" "\:" - e10 = Pgpass_Entry "::1" "*" "database_name" "user_that_has_no_password" "" - e11 = Pgpass_Entry "*" "*" "*" "*" "fallback_password" - e12 = Pgpass_Entry "order_matters" "1234" "this" "will_still_match_the_fallback_password" "not_this_one" + e1 = Pgpass_Entry_Data "localhost" "5432" "postgres" "postgres" "postgres" + e2 = Pgpass_Entry_Data "192.168.4.0" "1234" "foo" "bar" "baz" + e3 = Pgpass_Entry_Data "host with : semicolons in it? what?" "*" "*" "*" "well yes, that is possible, the :password: can contain those as well" + e4 = Pgpass_Entry_Data ":" ":" ":" ":" ":" + e5 = Pgpass_Entry_Data "you can escape an escape too: see \\" "*" "*" "*" "yes it is possible" + e6 = Pgpass_Entry_Data "other escapes like \n or \? " "*" "*" "*" "are just parsed as-is" + e7 = Pgpass_Entry_Data "a trailing escape character" "*" "*" "*" "is treated as a regular slash\" + e8 = Pgpass_Entry_Data "passwords should preserve leading space" "*" "*" "*" " pass" + e9 = Pgpass_Entry_Data "\:" "*" "*" "*" "\:" + e10 = Pgpass_Entry_Data "::1" "*" "database_name" "user_that_has_no_password" "" + e11 = Pgpass_Entry_Data "*" "*" "*" "*" "fallback_password" + e12 = Pgpass_Entry_Data "order_matters" "1234" "this" "will_still_match_the_fallback_password" "not_this_one" entries = [e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12] result.should_equal entries @@ -215,12 +215,12 @@ pgpass_spec = Test.group "[PostgreSQL] .pgpass" <| connection_setup_spec = Test.group "[PostgreSQL] Connection setup" <| Test.specify "should use environment variables as host, port and database defaults and fall back to hardcoded defaults" <| - c1 = Postgres "example.com" 12345 "my_db" - c2 = Postgres + c1 = Postgres_Data "example.com" 12345 "my_db" + c2 = Postgres_Data c3 = Test_Environment.unsafe_with_environment_override "PGHOST" "192.168.0.1" <| Test_Environment.unsafe_with_environment_override "PGPORT" "1000" <| Test_Environment.unsafe_with_environment_override "PGDATABASE" "ensoDB" <| - Postgres + Postgres_Data c1.host . should_equal "example.com" c1.port . should_equal 12345 @@ -240,20 +240,20 @@ connection_setup_spec = Test.group "[PostgreSQL] Connection setup" <| ## Currently we require the port to be numeric. When we support Unix-sockets, we may lift that restriction. c4 = Test_Environment.unsafe_with_environment_override "PGPORT" "foobar" <| - Postgres + Postgres_Data c4.host . should_equal "localhost" c4.port . should_equal 5432 c4.database . should_equal "" c4.jdbc_url . should_equal "jdbc:postgresql://localhost:5432" - add_ssl props = props+[Pair 'sslmode' 'prefer'] + add_ssl props = props+[Pair_Data 'sslmode' 'prefer'] Test.specify "should use the given credentials" <| - c = Postgres credentials=(Credentials "myuser" "mypass") + c = Postgres_Data credentials=(Credentials_Data "myuser" "mypass") c.jdbc_url . should_equal "jdbc:postgresql://localhost:5432" - c.jdbc_properties . should_equal <| add_ssl [Pair "user" "myuser", Pair "password" "mypass"] + c.jdbc_properties . should_equal <| add_ssl [Pair_Data "user" "myuser", Pair_Data "password" "mypass"] Test.specify "should fallback to environment variables and fill-out missing information based on the PGPASS file (if available)" <| - c1 = Postgres + c1 = Postgres_Data c1.jdbc_url . should_equal "jdbc:postgresql://localhost:5432" c1.jdbc_properties . should_equal <| add_ssl [] @@ -262,34 +262,34 @@ connection_setup_spec = Test.group "[PostgreSQL] Connection setup" <| c1.jdbc_properties.catch.message . should_equal "PGPASSWORD is set, but PGUSER is not." Test_Environment.unsafe_with_environment_override "PGUSER" "someuser" <| - c1.jdbc_properties . should_equal <| add_ssl [Pair "user" "someuser", Pair "password" "somepassword"] + c1.jdbc_properties . should_equal <| add_ssl [Pair_Data "user" "someuser", Pair_Data "password" "somepassword"] - c2 = Postgres "192.168.4.0" 1234 "foo" - c3 = Postgres "::1" 55999 "database_name" - c4 = Postgres "::1" 55999 "otherDB" + c2 = Postgres_Data "192.168.4.0" 1234 "foo" + c3 = Postgres_Data "::1" 55999 "database_name" + c4 = Postgres_Data "::1" 55999 "otherDB" c2.jdbc_properties . should_equal <| add_ssl [] c3.jdbc_properties . should_equal <| add_ssl [] c4.jdbc_properties . should_equal <| add_ssl [] Test_Environment.unsafe_with_environment_override "PGPASSFILE" pgpass_file.absolute.path <| - c2.jdbc_properties . should_equal <| add_ssl [Pair "user" "bar", Pair "password" "baz"] - c3.jdbc_properties . should_equal <| add_ssl [Pair "user" "user_that_has_no_password", Pair "password" ""] - c4.jdbc_properties . should_equal <| add_ssl [Pair "user" "*", Pair "password" "fallback_password"] + c2.jdbc_properties . should_equal <| add_ssl [Pair_Data "user" "bar", Pair_Data "password" "baz"] + c3.jdbc_properties . should_equal <| add_ssl [Pair_Data "user" "user_that_has_no_password", Pair_Data "password" ""] + c4.jdbc_properties . should_equal <| add_ssl [Pair_Data "user" "*", Pair_Data "password" "fallback_password"] Test_Environment.unsafe_with_environment_override "PGUSER" "bar" <| - c2.jdbc_properties . should_equal <| add_ssl [Pair "user" "bar", Pair "password" "baz"] + c2.jdbc_properties . should_equal <| add_ssl [Pair_Data "user" "bar", Pair_Data "password" "baz"] [c3, c4].each c-> c.jdbc_properties . should_equal <| - add_ssl [Pair "user" "*", Pair "password" "fallback_password"] + add_ssl [Pair_Data "user" "*", Pair_Data "password" "fallback_password"] Test_Environment.unsafe_with_environment_override "PGUSER" "other user" <| [c2, c3, c4].each c-> c.jdbc_properties . should_equal <| - add_ssl [Pair "user" "*", Pair "password" "fallback_password"] + add_ssl [Pair_Data "user" "*", Pair_Data "password" "fallback_password"] Test_Environment.unsafe_with_environment_override "PGPASSWORD" "other password" <| [c2, c3, c4].each c-> - c.jdbc_properties . should_equal <| add_ssl [Pair "user" "other user", Pair "password" "other password"] + c.jdbc_properties . should_equal <| add_ssl [Pair_Data "user" "other user", Pair_Data "password" "other password"] spec = table_spec diff --git a/test/Table_Tests/src/Database/Redshift_Spec.enso b/test/Table_Tests/src/Database/Redshift_Spec.enso index 842d212398d3..b4ad5e2b67a8 100644 --- a/test/Table_Tests/src/Database/Redshift_Spec.enso +++ b/test/Table_Tests/src/Database/Redshift_Spec.enso @@ -56,10 +56,10 @@ run_tests connection pending=Nothing = Common_Spec.spec prefix connection pending=pending redshift_specific_spec connection pending=pending - common_selection = Common_Table_Spec.Test_Selection supports_case_sensitive_columns=True order_by=False + common_selection = Common_Table_Spec.Test_Selection_Data supports_case_sensitive_columns=True order_by=False Common_Table_Spec.spec prefix table_builder test_selection=common_selection pending=pending - selection = Aggregate_Spec.Test_Selection text_concat=False text_shortest_longest=False first_last=False first_last_row_order=False multi_distinct=False aggregation_problems=False + selection = Aggregate_Spec.Test_Selection_Data text_concat=False text_shortest_longest=False first_last=False first_last_row_order=False multi_distinct=False aggregation_problems=False agg_in_memory_table = (enso_project.data / "data.csv") . read agg_table = connection.upload_table (Name_Generator.random_name "Agg1") agg_in_memory_table tables.append agg_table.name @@ -83,7 +83,7 @@ connect_via_json_config = db_name = uri.at 2 user = creds.get 'db_user' - Redshift db_uri db_port db_name credentials=(AWS_Key user access_key secret_key) + Redshift_Data db_uri db_port db_name credentials=(AWS_Key user access_key secret_key) connect_via_aws_environment db_host_port = db_host_port_split = uri_parse db_host_port @@ -98,7 +98,7 @@ connect_via_aws_environment db_host_port = credentials = if (access_key.is_nothing || secret_key.is_nothing) then AWS_Profile db_user (Environment.get "AWS_PROFILE" . if_nothing '') else AWS_Key db_user access_key secret_key - Redshift db_uri db_port db_name credentials=credentials + Redshift_Data db_uri db_port db_name credentials=credentials uri_parse uri = host_db_split = uri.split '/' From 00283d1ea8f19890e58beb70efd56320a80c4e51 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 25 Aug 2022 13:30:45 +0200 Subject: [PATCH 064/110] image tests --- distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image.enso | 4 ++-- .../lib/Standard/Image/0.0.0-dev/src/Data/Image/Internal.enso | 2 +- .../lib/Standard/Image/0.0.0-dev/src/Data/Matrix.enso | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image.enso index 0bf5b0577851..18e3a052834a 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image.enso @@ -102,7 +102,7 @@ type Image if (row < 0) || (row >= self.rows) then Error.throw (Matrix.Index_Out_Of_Bounds_Error self.rows self.columns row) else if (column < 0) || (column >= self.columns) then Error.throw (Matrix.Index_Out_Of_Bounds_Error self.rows self.columns column) else arr = Java_Image.get self.opencv_mat row column - Vector.Vector arr + Vector.Vector_Data arr ## UNSTABLE @@ -345,7 +345,7 @@ type Image to_vector : Vector to_vector self = arr = Java_Image.to_vector self.opencv_mat - Vector.Vector arr + Vector.Vector_Data arr ## UNSTABLE diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image/Internal.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image/Internal.enso index 6d22b3394886..0e36d6b56460 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image/Internal.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Image/Internal.enso @@ -26,7 +26,7 @@ core_op mat value function = _ -> Scalar.all value function mat scalar result - Image.Image result + Image.Image_Data result ## PRIVATE diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Matrix.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Matrix.enso index 5b4e1b91ef31..7aa35b7aa36c 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Matrix.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Data/Matrix.enso @@ -152,7 +152,7 @@ type Matrix if (row < 0) || (row >= self.rows) then Error.throw (Index_Out_Of_Bounds_Error self.rows self.columns row) else if (column < 0) || (column >= self.columns) then Error.throw (Index_Out_Of_Bounds_Error self.rows self.columns column) else arr = Java_Matrix.get self.opencv_mat row column - Vector.Vector arr + Vector.Vector_Data arr ## UNSTABLE @@ -413,7 +413,7 @@ type Matrix to_vector : Vector to_vector self = arr = Java_Matrix.to_vector self.opencv_mat - Vector.Vector arr + Vector.Vector_Data arr ## UNSTABLE From 2905f31697a77a3786b0b502eec6aef8195919b1 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 25 Aug 2022 13:35:14 +0200 Subject: [PATCH 065/110] example tests --- .../lib/Standard/Examples/0.0.0-dev/src/Main.enso | 10 ++++++---- test/Examples_Tests/src/Examples_Spec.enso | 10 +++++----- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/distribution/lib/Standard/Examples/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Examples/0.0.0-dev/src/Main.enso index d584f7b8585a..a4d0ba2a8e38 100644 --- a/distribution/lib/Standard/Examples/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Examples/0.0.0-dev/src/Main.enso @@ -22,7 +22,8 @@ import Standard.Image.Data.Matrix as Enso_Matrix Arguments: - message: The message contained in the error type. -type Example_Error_Type message +type Example_Error_Type + Example_Error_Type_Data message ## The standard library data directory. data_dir : File @@ -128,15 +129,16 @@ no_such_method : No_Such_Method_Error no_such_method = Panic.recover Any No_Methods.frobnicate . catch ## A simple error type for example purposes. -type My_Error message +type My_Error + My_Error_Data message ## Throws an error. throw_error : Nothing ! My_Error -throw_error = Error.throw <| My_Error "Example error." +throw_error = Error.throw <| My_Error_Data "Example error." ## Throws a panic. throw_panic : Nothing -throw_panic = Panic.throw <| My_Error "Example panic." +throw_panic = Panic.throw <| My_Error_Data "Example panic." ## A URL for open-source geographic data about the locations of bus-stop ads in Los Angeles. diff --git a/test/Examples_Tests/src/Examples_Spec.enso b/test/Examples_Tests/src/Examples_Spec.enso index 96af3fe1c17e..ddd28a5621c7 100644 --- a/test/Examples_Tests/src/Examples_Spec.enso +++ b/test/Examples_Tests/src/Examples_Spec.enso @@ -10,8 +10,8 @@ import Standard.Test spec = Test.group "Examples" <| Test.specify "should allow construction of Example_Error_Type" <| - val = Examples.Example_Error_Type "Oh, no! Something went wrong!" - val.should_be_an Examples.Example_Error_Type + val = Examples.Example_Error_Type_Data "Oh, no! Something went wrong!" + val.should_be_an Examples.Example_Error_Type_Data Test.specify "should allow getting the examples data directory" <| dir = Examples.data_dir @@ -58,13 +58,13 @@ spec = Test.group "Examples" <| Examples.no_such_method Test.specify "should provide a dummy error type" <| - Examples.My_Error + Examples.My_Error_Data Test.specify "should provide a method that throws an error" <| - Examples.throw_error.should_fail_with Examples.My_Error + Examples.throw_error.should_fail_with Examples.My_Error_Data Test.specify "should provide a method that throws a panic" <| - Test.expect_panic_with Examples.throw_panic Examples.My_Error + Test.expect_panic_with Examples.throw_panic Examples.My_Error_Data Test.specify "should provide a URL for some geo data" <| (Examples.geo_data_url.length > 0) . should_be_true From feb545c86dcd3fd6cc721babe3b91a7a23db0b18 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 25 Aug 2022 13:38:10 +0200 Subject: [PATCH 066/110] geo tests --- test/Geo_Tests/src/Geo_Spec.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Geo_Tests/src/Geo_Spec.enso b/test/Geo_Tests/src/Geo_Spec.enso index c0cf35fad6e0..b22288a88291 100644 --- a/test/Geo_Tests/src/Geo_Spec.enso +++ b/test/Geo_Tests/src/Geo_Spec.enso @@ -9,7 +9,7 @@ spec = Test.group "Geo Points" <| point = Geo.point 51.509865 -0.118092 Test.specify "should be able to be created as a Table" <| - point.is_a Table.Table . should_be_true + point.is_a Table.Table_Data . should_be_true Test.specify "should contain a latitude and longitude" <| point.at "latitude" . at 0 . should_equal 51.509865 point.at "longitude" . at 0 . should_equal -0.118092 From a8514fa56751a02edeebb213f2760ea9a1d21492 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 25 Aug 2022 14:08:45 +0200 Subject: [PATCH 067/110] vis tests --- .../Table/0.0.0-dev/src/Data/Column.enso | 2 +- .../Visualization/0.0.0-dev/src/Geo_Map.enso | 2 +- .../Visualization/0.0.0-dev/src/Helpers.enso | 2 +- .../0.0.0-dev/src/Histogram.enso | 6 +++--- .../0.0.0-dev/src/Scatter_Plot.enso | 21 ++++++++----------- .../0.0.0-dev/src/Table/Visualization.enso | 18 ++++++++-------- test/Visualization_Tests/src/Id_Spec.enso | 5 +++-- test/Visualization_Tests/src/Table_Spec.enso | 7 ++++--- 8 files changed, 31 insertions(+), 32 deletions(-) diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso index 211cfff09d5c..2d07ce321c2d 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso @@ -849,7 +849,7 @@ type Column example_to_table = Examples.integer_column.to_table to_table : Table.Table - to_table self = Table.Table self.java_column.toTable + to_table self = Table.Table_Data self.java_column.toTable ## UNSTABLE ADVANCED diff --git a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Geo_Map.enso b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Geo_Map.enso index 14ac9a7053eb..5dd5ac41233a 100644 --- a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Geo_Map.enso +++ b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Geo_Map.enso @@ -29,7 +29,7 @@ json_from_table table = process_to_json_text : Any -> Text process_to_json_text value = json = case value of - Table.Table _ -> json_from_table value + Table.Table_Data _ -> json_from_table value _ -> value.to_json json.to_text diff --git a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Helpers.enso b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Helpers.enso index 256f19f3178f..bfe02cfda657 100644 --- a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Helpers.enso +++ b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Helpers.enso @@ -102,7 +102,7 @@ Table.Table.all_columns : Vector Table.Table.all_columns self = index = self.index.catch_ [] index_columns = case index of - Vector.Vector _ -> index + Vector.Vector_Data _ -> index a -> [a] index_columns + self.columns diff --git a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Histogram.enso b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Histogram.enso index 0f58785ac0bf..879550a05f3d 100644 --- a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Histogram.enso +++ b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Histogram.enso @@ -55,9 +55,9 @@ from_vector vector = from_value : Any -> Update from_value value = case value of - Table.Table _ -> from_table value - Vector.Vector _ -> from_vector value - Column.Column _ -> from_table value.to_table + Table.Table_Data _ -> from_table value + Vector.Vector_Data _ -> from_vector value + Column.Column_Data _ -> from_table value.to_table _ -> from_vector value.to_vector ## PRIVATE diff --git a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Scatter_Plot.enso b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Scatter_Plot.enso index dd360554261b..02c60032946b 100644 --- a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Scatter_Plot.enso +++ b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Scatter_Plot.enso @@ -28,25 +28,22 @@ label_field = 'label' type Point_Data ## PRIVATE - type Point_Data + X ## PRIVATE - type X + Y ## PRIVATE - type Y + Color ## PRIVATE - type Color + Shape ## PRIVATE - type Shape + Label ## PRIVATE - type Label - - ## PRIVATE - type Size + Size ## PRIVATE @@ -162,9 +159,9 @@ json_from_vector vec = process_to_json_text : Any -> Text process_to_json_text value = json = case value of - Column.Column _ -> json_from_table value.to_table - Table.Table _ -> json_from_table value - Vector.Vector _ -> json_from_vector value + Column.Column_Data _ -> json_from_table value.to_table + Table.Table_Data _ -> json_from_table value + Vector.Vector_Data _ -> json_from_vector value _ -> json_from_vector value.to_vector json.to_text diff --git a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Table/Visualization.enso b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Table/Visualization.enso index bf04443a54a0..fdac358cd632 100644 --- a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Table/Visualization.enso +++ b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Table/Visualization.enso @@ -20,7 +20,7 @@ import Standard.Visualization.Helpers In case of Database backed data, it materializes a fragment of the data. prepare_visualization : Any -> Integer -> Json prepare_visualization x max_rows = Helpers.recover_errors <| case x of - Dataframe_Table.Table _ -> + Dataframe_Table.Table_Data _ -> dataframe = x.take_start max_rows all_rows_count = x.row_count included_rows = dataframe.row_count @@ -28,7 +28,7 @@ prepare_visualization x max_rows = Helpers.recover_errors <| case x of Dataframe_Column.from_vector "" (Vector.new included_rows i->i) make_json dataframe [index] all_rows_count - Database_Table.Table _ _ _ _ -> + Database_Table.Table_Data _ _ _ _ -> # Materialize a table with indices as normal columns (because dataframe does not support multi-indexing). df = x.reset_index.to_dataframe max_rows # Then split into actual columns and indices. @@ -38,25 +38,25 @@ prepare_visualization x max_rows = Helpers.recover_errors <| case x of make_json vis_df indices all_rows_count # We display columns as 1-column tables. - Dataframe_Column.Column _ -> + Dataframe_Column.Column_Data _ -> prepare_visualization x.to_table max_rows - Database_Column.Column _ _ _ _ _ -> + Database_Column.Column_Data _ _ _ _ _ -> prepare_visualization x.to_table max_rows # We display aggregates as their ungrouped counterparts. - Dataframe_Column.Aggregate_Column _ -> - ungrouped = Dataframe_Column.Column x.java_column.getColumn + Dataframe_Column.Aggregate_Column_Data _ -> + ungrouped = Dataframe_Column.Column_Data x.java_column.getColumn prepare_visualization ungrouped.to_table max_rows - Database_Column.Aggregate_Column_Builder _ _ _ _ _ -> + Database_Column.Aggregate_Column_Builder_Data _ _ _ _ _ -> prepare_visualization x.ungrouped.to_table max_rows # TODO [RW] Should we truncate Vectors? # We also visualize Vectors and arrays - Vector.Vector _ -> + Vector.Vector_Data _ -> truncated = x.take_start max_rows Json.from_pairs [["json", truncated], ["all_rows_count", x.length]] . to_text Array -> - prepare_visualization (Vector.Vector x) max_rows + prepare_visualization (Vector.Vector_Data x) max_rows # Anything else will be visualized with the JSON or matrix visualization _ -> diff --git a/test/Visualization_Tests/src/Id_Spec.enso b/test/Visualization_Tests/src/Id_Spec.enso index a3f26e65175b..f595615e16ac 100644 --- a/test/Visualization_Tests/src/Id_Spec.enso +++ b/test/Visualization_Tests/src/Id_Spec.enso @@ -4,7 +4,8 @@ import Standard.Visualization import Standard.Test -type My_Type my_field +type My_Type + My_Type_Data my_field spec = Test.group "Serializable Visualization Identifiers" <| @@ -29,7 +30,7 @@ spec = Test.group "Serializable Visualization Identifiers" <| v_2.to_json.should_equal (expected "Standard.Base" "Other Vis") Test.specify "specifies default JSON visualization for any type" - My_Type 30 . default_visualization . should_equal Visualization.Id.json + My_Type_Data 30 . default_visualization . should_equal Visualization.Id.json [1,2,3].default_visualization.should_equal Visualization.Id.json "foobar".default_visualization.should_equal Visualization.Id.json diff --git a/test/Visualization_Tests/src/Table_Spec.enso b/test/Visualization_Tests/src/Table_Spec.enso index aa6265e4665f..a172fa73566b 100644 --- a/test/Visualization_Tests/src/Table_Spec.enso +++ b/test/Visualization_Tests/src/Table_Spec.enso @@ -13,7 +13,8 @@ import Standard.Test polyglot java import java.util.UUID type Foo - type Foo x + Foo_Data x + to_json : Json to_json self = Json.from_pairs [["x", self.x]] @@ -88,8 +89,8 @@ visualization_spec connection = vis . should_equal json.to_text Test.specify "should handle other datatypes" <| - vis = Visualization.prepare_visualization (Foo 42) 2 - json = Json.from_pairs [["json", (Foo 42)]] + vis = Visualization.prepare_visualization (Foo_Data 42) 2 + json = Json.from_pairs [["json", (Foo_Data 42)]] vis . should_equal json.to_text spec = From e992f0c6aebcd33337ab91fd6776b2e238fb9279 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 25 Aug 2022 14:42:19 +0200 Subject: [PATCH 068/110] progress on compiler specs --- .../interpreter/test/DebuggingEnsoTest.java | 4 +- .../pass/analyse/GatherDiagnosticsTest.scala | 4 +- .../test/pass/desugar/ComplexTypeTest.scala | 138 +++++------------- .../test/pass/resolve/GlobalNamesTest.scala | 3 +- .../pass/resolve/ModuleAnnotationsTest.scala | 10 +- 5 files changed, 48 insertions(+), 111 deletions(-) diff --git a/engine/runtime/src/test/java/org/enso/interpreter/test/DebuggingEnsoTest.java b/engine/runtime/src/test/java/org/enso/interpreter/test/DebuggingEnsoTest.java index 4fa6fcf56020..f07534c52ef3 100644 --- a/engine/runtime/src/test/java/org/enso/interpreter/test/DebuggingEnsoTest.java +++ b/engine/runtime/src/test/java/org/enso/interpreter/test/DebuggingEnsoTest.java @@ -91,8 +91,8 @@ public void unsafeRecursiveAtom() throws Exception { import Standard.Base.Runtime.Unsafe type Gen - type Empty - type Generator a:Int tail:Gen + Empty + Generator a:Int tail:Gen ones : Gen ones = diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/GatherDiagnosticsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/GatherDiagnosticsTest.scala index cd2bf9bf5da9..455dbbbc3a98 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/GatherDiagnosticsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/GatherDiagnosticsTest.scala @@ -121,8 +121,8 @@ class GatherDiagnosticsTest extends CompilerTest { val ir = """ |type Foo - | type Bar1 - | type Bar2 + | Bar1 + | Bar2 | | foo x = | unused = 0 diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala index 3fb6175c091b..3da3d1c69f56 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala @@ -5,7 +5,6 @@ import org.enso.compiler.context.ModuleContext import org.enso.compiler.core.IR import org.enso.compiler.core.IR.Module.Scope.Definition import org.enso.compiler.pass.desugar.ComplexType -import org.enso.compiler.pass.resolve.ModuleAnnotations import org.enso.compiler.pass.{PassConfiguration, PassGroup, PassManager} import org.enso.compiler.test.CompilerTest @@ -57,7 +56,7 @@ class ComplexTypeTest extends CompilerTest { """ |type Maybe | Nothing - | type Just a + | Just a | | invalid_sig : Int | @@ -72,141 +71,78 @@ class ComplexTypeTest extends CompilerTest { | bad_trailing_sig : Double |""".stripMargin.preprocessModule.desugar - "have their atoms desugared to top-level atoms" in { + "have their atoms desugared" in { val ir = """ |type MyType - | type Foo - | type Bar - |""".stripMargin.preprocessModule.desugar - - exactly(2, ir.bindings) shouldBe a[Definition.Data] - ir.bindings(0) - .asInstanceOf[Definition.Type] - .name - .name shouldEqual "MyType" - ir.bindings(1).asInstanceOf[Definition.Data].name.name shouldEqual "Foo" - ir.bindings(2).asInstanceOf[Definition.Data].name.name shouldEqual "Bar" - } - - "have annotations on the type desugared to annotations on the defined" in { - val ir = - """@Builtin_Type - |type My_Type | Foo - | type Bar + | Bar |""".stripMargin.preprocessModule.desugar - - exactly(1, ir.bindings) shouldBe a[Definition.Data] - ir.bindings(1) - .asInstanceOf[Definition.Data] - .unsafeGetMetadata(ModuleAnnotations, "") - .annotations - .head - .name shouldEqual "@Builtin_Type" + val tp = ir.bindings(0).asInstanceOf[Definition.Type] + tp.name.name shouldEqual "MyType" + tp.members(0).name.name shouldEqual "Foo" + tp.members(1).name.name shouldEqual "Bar" } - "have their methods desugared to methods on included atoms" in { - ir.bindings(4) shouldBe an[Definition.Method.Binding] - val justIsJust = ir.bindings(4).asInstanceOf[Definition.Method.Binding] - justIsJust.methodName.name shouldEqual "is_just" - justIsJust.typeName.get.name shouldEqual "Nothing" - - ir.bindings(8) shouldBe an[Definition.Method.Binding] - val justF = ir.bindings(8).asInstanceOf[Definition.Method.Binding] - justF.methodName.name shouldEqual "f" - justF.typeName.get.name shouldEqual "Nothing" + "have their methods desugared to binding methods" in { +// println(ir.pretty) + ir.bindings(3) shouldBe an[Definition.Method.Binding] + val isJust = ir.bindings(3).asInstanceOf[Definition.Method.Binding] + isJust.methodName.name shouldEqual "is_just" + isJust.typeName.get.name shouldEqual "Maybe" + + ir.bindings(5) shouldBe an[Definition.Method.Binding] + val f = ir.bindings(5).asInstanceOf[Definition.Method.Binding] + f.methodName.name shouldEqual "f" + f.typeName.get.name shouldEqual "Maybe" } - "have their methods desugared to methods on the defined atoms" in { - ir.bindings(6) shouldBe an[Definition.Method.Binding] - val justIsJust = ir.bindings(6).asInstanceOf[Definition.Method.Binding] - justIsJust.methodName.name shouldEqual "is_just" - justIsJust.typeName.get.name shouldEqual "Just" - - ir.bindings(10) shouldBe an[Definition.Method.Binding] - val justF = ir.bindings(10).asInstanceOf[Definition.Method.Binding] - justF.methodName.name shouldEqual "f" - justF.typeName.get.name shouldEqual "Just" - } "have type signatures copied to above each method" in { - ir.bindings(3) shouldBe an[IR.Type.Ascription] - ir.bindings(7) shouldBe an[IR.Type.Ascription] - ir.bindings(5) shouldBe an[IR.Type.Ascription] - ir.bindings(9) shouldBe an[IR.Type.Ascription] + ir.bindings(2) shouldBe an[IR.Type.Ascription] + ir.bindings(4) shouldBe an[IR.Type.Ascription] - val nothingIsJustSigName = ir - .bindings(3) + val isJustSigName = ir + .bindings(2) .asInstanceOf[IR.Type.Ascription] .typed .asInstanceOf[IR.Name.MethodReference] - val nothingIsJustMethodName = ir - .bindings(4) + val isJustMethodName = ir + .bindings(3) .asInstanceOf[Definition.Method.Binding] .methodReference assert( - nothingIsJustSigName isSameReferenceAs nothingIsJustMethodName, + isJustSigName isSameReferenceAs isJustMethodName, "The type signature and method did not have the same reference." ) - val nothingFSigName = ir - .bindings(7) + val fSigName = ir + .bindings(4) .asInstanceOf[IR.Type.Ascription] .typed .asInstanceOf[IR.Name.MethodReference] - val nothingFMethodName = ir - .bindings(8) - .asInstanceOf[Definition.Method.Binding] - .methodReference - - assert( - nothingFSigName isSameReferenceAs nothingFMethodName, - "The type signature and method did not have the same reference." - ) - - val justIsJustSigName = ir + val fMethodName = ir .bindings(5) - .asInstanceOf[IR.Type.Ascription] - .typed - .asInstanceOf[IR.Name.MethodReference] - val justIsJustMethodName = ir - .bindings(6) - .asInstanceOf[Definition.Method.Binding] - .methodReference - - assert( - justIsJustSigName isSameReferenceAs justIsJustMethodName, - "The type signature and method did not have the same reference." - ) - - val justFSigName = ir - .bindings(9) - .asInstanceOf[IR.Type.Ascription] - .typed - .asInstanceOf[IR.Name.MethodReference] - val justFMethodName = ir - .bindings(10) .asInstanceOf[Definition.Method.Binding] .methodReference assert( - justFSigName isSameReferenceAs justFMethodName, + fSigName isSameReferenceAs fMethodName, "The type signature and method did not have the same reference." ) } "leave un-associated signatures intact" in { - ir.bindings(2) shouldBe an[IR.Type.Ascription] - ir.bindings(2) + ir.bindings(1) shouldBe an[IR.Type.Ascription] + ir.bindings(1) .asInstanceOf[IR.Type.Ascription] .typed .asInstanceOf[IR.Name.Literal] .name shouldEqual "invalid_sig" - ir.bindings(11) shouldBe an[IR.Type.Ascription] - ir.bindings(11) + ir.bindings(6) shouldBe an[IR.Type.Ascription] + ir.bindings(6) .asInstanceOf[IR.Type.Ascription] .typed .asInstanceOf[IR.Name.Literal] @@ -221,7 +157,7 @@ class ComplexTypeTest extends CompilerTest { """ |type Foo | Bar - | type Baz + | Baz | | g a = this + a | @@ -229,9 +165,9 @@ class ComplexTypeTest extends CompilerTest { |""".stripMargin.preprocessModule.desugar "have their types translated untouched" in { - ir.bindings(1) shouldBe a[Definition.Data] - val atom = ir.bindings(1).asInstanceOf[Definition.Data] - atom.name.name shouldEqual "Baz" + ir.bindings(0) shouldBe a[Definition.Type] + val tp = ir.bindings(0).asInstanceOf[Definition.Type] + tp.members(1).name.name shouldEqual "Baz" } "have their errors translated untouched" in { diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GlobalNamesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GlobalNamesTest.scala index 9df8e65f7be1..f51d57954563 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GlobalNamesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GlobalNamesTest.scala @@ -71,7 +71,8 @@ class GlobalNamesTest extends CompilerTest { | x8 = Does_Not_Exist 32 | 0 | - |type My_Cons a b c + |type My + | My_Cons a b c | |constant = 2 | diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/ModuleAnnotationsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/ModuleAnnotationsTest.scala index 068c28fa029a..cf30d4aaf0e3 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/ModuleAnnotationsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/ModuleAnnotationsTest.scala @@ -60,7 +60,7 @@ class ModuleAnnotationsTest extends CompilerTest { |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 1 - ir.bindings.head shouldBe a[Definition.Data] + ir.bindings.head shouldBe a[Definition.SugaredType] val anns = ir.bindings.head.unsafeGetMetadata(ModuleAnnotations, "").annotations anns.length shouldEqual 2 @@ -109,7 +109,7 @@ class ModuleAnnotationsTest extends CompilerTest { |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 2 - ir.bindings(1) shouldBe a[Definition.Data] + ir.bindings(1) shouldBe a[Definition.SugaredType] val anns = ir.bindings(1).unsafeGetMetadata(ModuleAnnotations, "").annotations anns.length shouldEqual 1 @@ -125,7 +125,7 @@ class ModuleAnnotationsTest extends CompilerTest { """@My_Annotation |type Foo | @My_Annotation - | type Bar + | Bar |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 1 @@ -144,7 +144,7 @@ class ModuleAnnotationsTest extends CompilerTest { "associate annotations with method definitions" in { val ir = """type Foo - | type Foo + | Foo | | @My_Annotation | my_method a = a @@ -170,7 +170,7 @@ class ModuleAnnotationsTest extends CompilerTest { |type Foo | @My_Annotation | ## Doc comment - | type Foo + | Foo |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 1 From aef3e23e2511f8b1fa31a83308d842b869c55e1a Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 25 Aug 2022 16:36:10 +0200 Subject: [PATCH 069/110] more compiler tests pass --- .../pass/analyse/BindingAnalysis.scala | 4 +-- .../pass/resolve/OverloadsResolution.scala | 4 +++ .../test/pass/analyse/AliasAnalysisTest.scala | 16 ++++++---- .../pass/analyse/BindingAnalysisTest.scala | 17 +++++++---- .../test/pass/desugar/ComplexTypeTest.scala | 12 +++----- .../resolve/OverloadsResolutionTest.scala | 29 ------------------- .../pass/resolve/TypeSignaturesTest.scala | 14 ++++----- 7 files changed, 39 insertions(+), 57 deletions(-) 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 02a15adf67b1..65c77d3bf7fe 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 @@ -85,12 +85,12 @@ case object BindingAnalysis extends IRPass { case Some(IR.Name.Qualified(List(), _, _, _)) => Some(ref.methodName.name) case Some(IR.Name.Qualified(List(n), _, _, _)) => - val shadowed = definedConstructors.exists(_.name == n.name) + val shadowed = definedSumTypes.exists(_.name == n.name) if (!shadowed && n.name == moduleContext.module.getName.item) Some(ref.methodName.name) else None case Some(IR.Name.Literal(n, _, _, _, _)) => - val shadowed = definedConstructors.exists(_.name == n) + val shadowed = definedSumTypes.exists(_.name == n) if (!shadowed && n == moduleContext.module.getName.item) Some(ref.methodName.name) else None diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala index ee6b1e27755b..c2a8b069ab9c 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala @@ -54,6 +54,8 @@ case object OverloadsResolution extends IRPass { case tp: IR.Module.Scope.Definition.Type => tp } + println("TYPES " + types) + val newTypes: List[IR.Module.Scope.Definition] = types.map(tp => { if (seenTypes.contains(tp.name.name)) { IR.Error.Redefined.Type(tp.name, tp.location) @@ -63,6 +65,8 @@ case object OverloadsResolution extends IRPass { } }) + println("NEW TYPES " + newTypes) + val methods = ir.bindings.collect { case meth: IR.Module.Scope.Definition.Method.Explicit => seenMethods = seenMethods + (meth.typeName.map(_.name) -> Set()) diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/AliasAnalysisTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/AliasAnalysisTest.scala index 73ae61561333..ce1bb76b0156 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/AliasAnalysisTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/AliasAnalysisTest.scala @@ -3,7 +3,7 @@ package org.enso.compiler.test.pass.analyse import org.enso.compiler.Passes import org.enso.compiler.context.{FreshNameSupply, InlineContext, ModuleContext} import org.enso.compiler.core.IR -import org.enso.compiler.core.IR.Module.Scope.Definition.{Data, Method} +import org.enso.compiler.core.IR.Module.Scope.Definition.Method import org.enso.compiler.core.IR.Pattern import org.enso.compiler.pass.PassConfiguration._ import org.enso.compiler.pass.analyse.AliasAnalysis @@ -397,17 +397,23 @@ class AliasAnalysisTest extends CompilerTest { val goodAtom = """ - |type MyAtom a b (c=a) + |type M + | MyAtom a b (c=a) |""".stripMargin.preprocessModule.analyse.bindings.head - .asInstanceOf[Data] + .asInstanceOf[IR.Module.Scope.Definition.Type] + .members + .head val goodMeta = goodAtom.getMetadata(AliasAnalysis) val goodGraph = goodMeta.get.unsafeAs[AliasAnalysis.Info.Scope.Root].graph val badAtom = """ - |type MyAtom a=b b + |type M + | MyAtom a=b b |""".stripMargin.preprocessModule.analyse.bindings.head - .asInstanceOf[Data] + .asInstanceOf[IR.Module.Scope.Definition.Type] + .members + .head val badMeta = badAtom.getMetadata(AliasAnalysis) val badGraph = badMeta.get.unsafeAs[AliasAnalysis.Info.Scope.Root].graph diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/BindingAnalysisTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/BindingAnalysisTest.scala index a320e81032a5..1a23451f40fe 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/BindingAnalysisTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/analyse/BindingAnalysisTest.scala @@ -7,7 +7,8 @@ import org.enso.compiler.data.BindingsMap.{ Cons, ModuleMethod, ModuleReference, - PolyglotSymbol + PolyglotSymbol, + Type } import org.enso.compiler.pass.analyse.BindingAnalysis import org.enso.compiler.pass.{PassConfiguration, PassGroup, PassManager} @@ -57,7 +58,8 @@ class BindingAnalysisTest extends CompilerTest { |polyglot java import foo.bar.baz.MyClass |polyglot java import foo.bar.baz.OtherClass as Renamed_Class | - |type Foo a b c + |type Foo + | Mk_Foo a b c |type Bar |type Baz x y | @@ -74,11 +76,14 @@ class BindingAnalysisTest extends CompilerTest { val metadata = ir.unsafeGetMetadata(BindingAnalysis, "Should exist.") - metadata.constructors shouldEqual List( - Cons("Foo", 3, false), - Cons("Bar", 0, true), - Cons("Baz", 2, false) + metadata.types shouldEqual List( + Type("Foo", List("Mk_Foo"), false), + Type("Bar", List(), false), + Type("Baz", List(), false) ) + + metadata.constructors shouldEqual List(Cons("Mk_Foo", 3, false)) + metadata.polyglotSymbols shouldEqual List( PolyglotSymbol("MyClass"), PolyglotSymbol("Renamed_Class") diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala index 3da3d1c69f56..2fc9b1793ef7 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala @@ -177,14 +177,10 @@ class ComplexTypeTest extends CompilerTest { } "have their valid methods desugared" in { - ir.bindings(2) shouldBe a[Definition.Method.Binding] - ir.bindings(3) shouldBe a[Definition.Method.Binding] - val methodOnBar = ir.bindings(2).asInstanceOf[Definition.Method.Binding] - val methodOnBaz = ir.bindings(3).asInstanceOf[Definition.Method.Binding] - methodOnBar.typeName.get.name shouldEqual "Bar" - methodOnBar.methodName.name shouldEqual "g" - methodOnBaz.typeName.get.name shouldEqual "Baz" - methodOnBaz.methodName.name shouldEqual "g" + ir.bindings(1) shouldBe a[Definition.Method.Binding] + val method = ir.bindings(1).asInstanceOf[Definition.Method.Binding] + method.typeName.get.name shouldEqual "Foo" + method.methodName.name shouldEqual "g" } } } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/OverloadsResolutionTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/OverloadsResolutionTest.scala index cd813c6eb481..c2d40f286ad1 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/OverloadsResolutionTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/OverloadsResolutionTest.scala @@ -138,33 +138,4 @@ class OverloadsResolutionTest extends CompilerTest { } } - "Atom overloads method resolution" should { - implicit val ctx: ModuleContext = mkModuleContext - - val atomName = "Foo" - val methodName = atomName.toLowerCase - - val ir = - s"""| - |type $atomName - |$methodName = 0 - |Unit.$methodName = 1 - |""".stripMargin.preprocessModule.resolve - - "detect overloads within a given module" in { - exactly(1, ir.bindings) shouldBe an[ - IR.Error.Redefined.MethodClashWithAtom - ] - } - - "replace all overloads by an error node" in { - ir.bindings(1) shouldBe an[IR.Error.Redefined.MethodClashWithAtom] - ir.bindings(1) - .asInstanceOf[IR.Error.Redefined.MethodClashWithAtom] - .methodName - .name shouldEqual methodName - ir.bindings(2) shouldBe an[IR.Module.Scope.Definition.Method.Explicit] - } - } - } diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/TypeSignaturesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/TypeSignaturesTest.scala index e48c2f01a9e8..72872aea80fd 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/TypeSignaturesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/TypeSignaturesTest.scala @@ -152,7 +152,7 @@ class TypeSignaturesTest extends CompilerTest { val ir = """ |type MyType - | type MyAtom + | MyAtom | | ## is atom | is_atom : this -> Boolean @@ -161,12 +161,12 @@ class TypeSignaturesTest extends CompilerTest { | error_signature : Int |""".stripMargin.preprocessModule.resolve - ir.bindings.length shouldEqual 4 - ir.bindings(1) shouldBe an[IR.Module.Scope.Definition.Data] - ir.bindings(2) shouldBe an[IR.Module.Scope.Definition.Method] - ir.bindings(2).getMetadata(TypeSignatures) shouldBe defined - ir.bindings(2).getMetadata(DocumentationComments) shouldBe defined - ir.bindings(3) shouldBe an[IR.Error.Unexpected.TypeSignature] + ir.bindings.length shouldEqual 3 + ir.bindings(0) shouldBe an[IR.Module.Scope.Definition.Type] + ir.bindings(1) shouldBe an[IR.Module.Scope.Definition.Method] + ir.bindings(1).getMetadata(TypeSignatures) shouldBe defined + ir.bindings(1).getMetadata(DocumentationComments) shouldBe defined + ir.bindings(2) shouldBe an[IR.Error.Unexpected.TypeSignature] } "recurse into bodies" in { From c662f05831b5e6f88d6fefe6ad8d839de0ea2f9f Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 25 Aug 2022 17:12:49 +0200 Subject: [PATCH 070/110] test progress --- .../enso/compiler/pass/desugar/ComplexType.scala | 13 +++++++++++-- .../compiler/pass/resolve/OverloadsResolution.scala | 4 ---- .../pass/resolve/DocumentationCommentsTest.scala | 10 ++++++---- 3 files changed, 17 insertions(+), 10 deletions(-) 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 a7fb81d00833..82c7f17f00e1 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 @@ -20,7 +20,11 @@ import org.enso.compiler.pass.optimise.{ ApplicationSaturation, LambdaConsolidate } -import org.enso.compiler.pass.resolve.{IgnoredBindings, ModuleAnnotations} +import org.enso.compiler.pass.resolve.{ + DocumentationComments, + IgnoredBindings, + ModuleAnnotations +} import org.enso.compiler.core.ir.MetadataStorage._ import scala.annotation.unused @@ -198,7 +202,12 @@ case object ComplexType extends IRPass { .map(ann => sumType.updateMetadata(ModuleAnnotations -->> ann)) .getOrElse(sumType) - withAnnotations :: allEntities + val withDoc = typ + .getMetadata(DocumentationComments) + .map(ann => withAnnotations.updateMetadata(DocumentationComments -->> ann)) + .getOrElse(sumType) + + withDoc :: allEntities } /** Generates a method definition from a definition in complex type def body. diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala index c2a8b069ab9c..ee6b1e27755b 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala @@ -54,8 +54,6 @@ case object OverloadsResolution extends IRPass { case tp: IR.Module.Scope.Definition.Type => tp } - println("TYPES " + types) - val newTypes: List[IR.Module.Scope.Definition] = types.map(tp => { if (seenTypes.contains(tp.name.name)) { IR.Error.Redefined.Type(tp.name, tp.location) @@ -65,8 +63,6 @@ case object OverloadsResolution extends IRPass { } }) - println("NEW TYPES " + newTypes) - val methods = ir.bindings.collect { case meth: IR.Module.Scope.Definition.Method.Explicit => seenMethods = seenMethods + (meth.typeName.map(_.name) -> Set()) diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala index c074b7365b23..37be085abb02 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala @@ -73,7 +73,7 @@ class DocumentationCommentsTest extends CompilerTest with Inside { */ def getDoc(ir: IR): String = { val meta = ir.getMetadata(DocumentationComments) - meta shouldBe defined +// meta.shouldBe(defined) meta.get.documentation } @@ -95,7 +95,7 @@ class DocumentationCommentsTest extends CompilerTest with Inside { "be associated with atoms and methods" in { ir.bindings.length shouldEqual 2 - ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Data] + ir.bindings.head shouldBe an[IR.Module.Scope.Definition.SugaredType] ir.bindings(1) shouldBe an[IR.Module.Scope.Definition.Method] getDoc(ir.bindings.head) shouldEqual " This is doc for My_Atom" @@ -317,13 +317,14 @@ class DocumentationCommentsTest extends CompilerTest with Inside { implicit val moduleContext: ModuleContext = buildModuleContext(freshNameSupply = Some(new FreshNameSupply)) + println("TUTEJ") val ir = """## Module Docs | |## the type Foo |type Foo | ## the constructor Bar - | type Bar + | Bar | | ## a method | foo : Any -> Any @@ -341,7 +342,8 @@ class DocumentationCommentsTest extends CompilerTest with Inside { |""".stripMargin.preprocessModule val t1 = ir.bindings.head - getDoc(t1) shouldEqual " the constructor Bar" + println("IN TEST " + ir.bindings.head.getClass.getSimpleName) + getDoc(t1) shouldEqual " the type Foo" inside(ir.bindings(1)) { case method: IR.Module.Scope.Definition.Method.Explicit => getDoc(method) shouldEqual " a method" From b969fdde7efc228a52a9daa179d35456214ca819 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 25 Aug 2022 18:54:24 +0200 Subject: [PATCH 071/110] fix suggestion builder --- .../compiler/context/SuggestionBuilder.scala | 108 ++++++----- .../test/context/SuggestionBuilderTest.scala | 175 ++++++++---------- .../test/semantic/TypeSignaturesTest.scala | 8 +- .../scala/org/enso/std/test/BooleanTest.scala | 24 --- 4 files changed, 150 insertions(+), 165 deletions(-) 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 b471e0918d38..897b8efb31e3 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 @@ -42,10 +42,37 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { val ir = scope.queue.dequeue() val doc = ir.getMetadata(DocumentationComments).map(_.documentation) ir match { - case IR.Module.Scope.Definition.Data(name, arguments, _, _, _) => - val suggestions = - buildAtom(module, name.name, arguments, doc) - go(tree ++= suggestions.map(Tree.Node(_, Vector())), scope) + case IR.Module.Scope.Definition.Type(tpName, _, List(), _, _, _) => + val cons = + buildAtomConstructor(module, tpName.name, tpName.name, Seq(), doc) + go(tree ++= Vector(Tree.Node(cons, Vector())), scope) + + case IR.Module.Scope.Definition.Type(tpName, _, members, _, _, _) => + val conses = members.map { + case data @ IR.Module.Scope.Definition.Data( + name, + arguments, + _, + _, + _ + ) => + buildAtomConstructor( + module, + tpName.name, + name.name, + arguments, + data.getMetadata(DocumentationComments).map(_.documentation) + ) + } + val getters = members + .flatMap(_.arguments) + .map(_.name.name) + .distinct + .map(buildGetter(module, tpName.name, _)) + + val tpSuggestions = conses ++ getters + + go(tree ++= tpSuggestions.map(Tree.Node(_, Vector())), scope) case IR.Module.Scope.Definition.Method .Explicit( @@ -58,7 +85,9 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { val typeSignature = ir.getMetadata(TypeSignatures) val selfTypeOpt = typePtr match { case Some(typePtr) => - typePtr.getMetadata(MethodDefinitions).map(_.target.qualifiedName) + typePtr + .getMetadata(MethodDefinitions) + .map(_.target.qualifiedName) case None => Some(module) } @@ -66,7 +95,7 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { buildMethod( body.getExternalId, module, - methodName, + methodName.name, selfType, args, doc, @@ -161,7 +190,7 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { private def buildMethod( externalId: Option[IR.ExternalId], module: QualifiedName, - name: IR.Name, + name: String, selfType: QualifiedName, args: Seq[IR.DefinitionArgument], doc: Option[String], @@ -173,7 +202,7 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { Suggestion.Method( externalId = externalId, module = module.toString, - name = name.name, + name = name, arguments = methodArgs, selfType = selfType.toString, returnType = buildReturnType(returnTypeDef), @@ -254,19 +283,10 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { documentation = doc ) - /** Build suggestions for an atom definition. */ - private def buildAtom( - module: QualifiedName, - name: String, - arguments: Seq[IR.DefinitionArgument], - doc: Option[String] - ): Seq[Suggestion] = - buildAtomConstructor(module, name, arguments, doc) +: - buildAtomGetters(module, name, arguments) - /** Build an atom constructor. */ private def buildAtomConstructor( module: QualifiedName, + tp: String, name: String, arguments: Seq[IR.DefinitionArgument], doc: Option[String] @@ -276,34 +296,33 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { module = module.toString, name = name, arguments = arguments.map(buildArgument), - returnType = module.createChild(name).toString, + returnType = module.createChild(tp).toString, documentation = doc ) /** Build getter methods from atom arguments. */ - private def buildAtomGetters( + private def buildGetter( module: QualifiedName, - name: String, - arguments: Seq[IR.DefinitionArgument] - ): Seq[Suggestion] = - arguments.map { argument => - val thisArg = IR.DefinitionArgument.Specified( - name = IR.Name.Self(argument.name.location), - ascribedType = None, - defaultValue = None, - suspended = false, - location = argument.location - ) - buildMethod( - externalId = None, - module = module, - name = argument.name, - selfType = module.createChild(name), - args = Seq(thisArg), - doc = None, - typeSignature = None - ) - } + typeName: String, + getterName: String + ): Suggestion = { + val thisArg = IR.DefinitionArgument.Specified( + name = IR.Name.Self(None), + ascribedType = None, + defaultValue = None, + suspended = false, + location = None + ) + buildMethod( + externalId = None, + module = module, + name = getterName, + selfType = module.createChild(typeName), + args = Seq(thisArg), + doc = None, + typeSignature = None + ) + } private def buildResolvedUnionTypeName( resolvedName: BindingsMap.ResolvedName @@ -482,9 +501,10 @@ final class SuggestionBuilder[A: IndexedSource](val source: A) { ) private def pluckVariants(arg: TypeArg): Seq[String] = arg match { - case TypeArg.Sum(_, variants) => variants.flatMap(pluckVariants) - case TypeArg.Value(n) => Seq(n.toString) - case _ => Seq() + case TypeArg.Sum(Some(n), List()) => Seq(n.toString) + case TypeArg.Sum(_, variants) => variants.flatMap(pluckVariants) + case TypeArg.Value(n) => Seq(n.toString) + case _ => Seq() } /** Build the name of type argument. diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/context/SuggestionBuilderTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/context/SuggestionBuilderTest.scala index e81f14ca278f..68bbd28f634b 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/context/SuggestionBuilderTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/context/SuggestionBuilderTest.scala @@ -350,7 +350,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { val code = """type MyType | - |MyType.bar a b = a + b + |MyType.bar self a b = a + b |""".stripMargin val module = code.preprocessModule @@ -407,7 +407,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { | |## My bar |MyAtom.bar : Number -> Number -> Number - |MyAtom.bar a b = a + b + |MyAtom.bar self a b = a + b |""".stripMargin val module = code.preprocessModule @@ -494,8 +494,8 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { val code = """type My_Atom - | type Variant_1 - | type Variant_2 + | Variant_1 + | Variant_2 | |type Other_Atom | @@ -513,7 +513,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "Variant_1", arguments = Seq(), - returnType = "Unnamed.Test.Variant_1", + returnType = "Unnamed.Test.My_Atom", documentation = None ), Vector() @@ -524,7 +524,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "Variant_2", arguments = Seq(), - returnType = "Unnamed.Test.Variant_2", + returnType = "Unnamed.Test.My_Atom", documentation = None ), Vector() @@ -639,7 +639,14 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "foo", arguments = Seq( Suggestion.Argument("self", "Unnamed.Test", false, false, None), - Suggestion.Argument("a", "Unnamed.Test.A", false, false, None) + Suggestion.Argument( + "a", + "Unnamed.Test.A", + false, + false, + None, + Some(List("Unnamed.Test.A")) + ) ), selfType = "Unnamed.Test", returnType = "Unnamed.Test.A", @@ -716,14 +723,15 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { pending val code = """type MyMaybe - | type Some a - | type None + | Some a + | None | - |type Newtype x + |type New + | Newtype x | |## My conversion method - |Newtype.from : MyMaybe -> Newtype - |Newtype.from opt = case opt of + |New.from : MyMaybe -> New + |New.from opt = case opt of | Some a -> Newtype a | None -> Newtype 0 |""".stripMargin @@ -781,7 +789,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { Suggestion .Argument("x", SuggestionBuilder.Any, false, false, None) ), - returnType = "Unnamed.Test.Newtype", + returnType = "Unnamed.Test.New", documentation = None ), Vector() @@ -793,9 +801,9 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "x", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.Newtype", false, false, None) + .Argument("self", "Unnamed.Test.New", false, false, None) ), - selfType = "Unnamed.Test.NewType", + selfType = "Unnamed.Test.New", returnType = SuggestionBuilder.Any, documentation = None ), @@ -1013,7 +1021,14 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "foo", arguments = Seq( Suggestion - .Argument("a", "Unnamed.Test.A", false, false, None) + .Argument( + "a", + "Unnamed.Test.A", + false, + false, + None, + Some(List("Unnamed.Test.A")) + ) ), returnType = "Unnamed.Test.A", scope = Suggestion.Scope( @@ -1226,7 +1241,9 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { "build atom simple" in { - val code = """type MyType a b""" + val code = + """type MyType + | MkMyType a b""".stripMargin val module = code.preprocessModule build(code, module) shouldEqual Tree.Root( @@ -1236,7 +1253,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { Suggestion.Atom( externalId = None, module = "Unnamed.Test", - name = "MyType", + name = "MkMyType", arguments = Seq( Suggestion .Argument("a", SuggestionBuilder.Any, false, false, None), @@ -1288,7 +1305,9 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { """## Module doc | |## My sweet type - |type MyType a b""".stripMargin + |type Mtp + | ## My sweet atom + | MyType a b""".stripMargin val module = code.preprocessModule build(code, module) shouldEqual Tree.Root( @@ -1305,8 +1324,8 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { Suggestion .Argument("b", SuggestionBuilder.Any, false, false, None) ), - returnType = "Unnamed.Test.MyType", - documentation = Some(" My sweet type") + returnType = "Unnamed.Test.Mtp", + documentation = Some(" My sweet atom") ), Vector() ), @@ -1317,9 +1336,9 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.MyType", false, false, None) + .Argument("self", "Unnamed.Test.Mtp", false, false, None) ), - selfType = "Unnamed.Test.MyType", + selfType = "Unnamed.Test.Mtp", returnType = SuggestionBuilder.Any, documentation = None ), @@ -1332,9 +1351,9 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "b", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.MyType", false, false, None) + .Argument("self", "Unnamed.Test.Mtp", false, false, None) ), - selfType = "Unnamed.Test.MyType", + selfType = "Unnamed.Test.Mtp", returnType = SuggestionBuilder.Any, documentation = None ), @@ -1348,8 +1367,8 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { val code = """type Maybe - | type Nothing - | type Just a""".stripMargin + | Nothing + | Just a""".stripMargin val module = code.preprocessModule build(code, module) shouldEqual Tree.Root( @@ -1361,7 +1380,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "Nothing", arguments = Seq(), - returnType = "Unnamed.Test.Nothing", + returnType = "Unnamed.Test.Maybe", documentation = None ), Vector() @@ -1375,7 +1394,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { Suggestion .Argument("a", SuggestionBuilder.Any, false, false, None) ), - returnType = "Unnamed.Test.Just", + returnType = "Unnamed.Test.Maybe", documentation = None ), Vector() @@ -1387,9 +1406,9 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.Just", false, false, None) + .Argument("self", "Unnamed.Test.Maybe", false, false, None) ), - selfType = "Unnamed.Test.Just", + selfType = "Unnamed.Test.Maybe", returnType = SuggestionBuilder.Any, documentation = None ), @@ -1407,9 +1426,9 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { |## When in doubt |type Maybe | ## Nothing here - | type Nothing + | Nothing | ## Something there - | type Just a""".stripMargin + | Just a""".stripMargin val module = code.preprocessModule build(code, module) shouldEqual Tree.Root( @@ -1421,7 +1440,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "Nothing", arguments = Seq(), - returnType = "Unnamed.Test.Nothing", + returnType = "Unnamed.Test.Maybe", documentation = Some(" Nothing here") ), Vector() @@ -1435,7 +1454,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { Suggestion .Argument("a", SuggestionBuilder.Any, false, false, None) ), - returnType = "Unnamed.Test.Just", + returnType = "Unnamed.Test.Maybe", documentation = Some(" Something there") ), Vector() @@ -1447,9 +1466,9 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.Just", false, false, None) + .Argument("self", "Unnamed.Test.Maybe", false, false, None) ), - selfType = "Unnamed.Test.Just", + selfType = "Unnamed.Test.Maybe", returnType = SuggestionBuilder.Any, documentation = None ), @@ -1463,9 +1482,9 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { val code = """type List | ## And more - | type Cons + | Cons | ## End - | type Nil + | Nil | | ## a method | empty : List @@ -1482,7 +1501,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "Cons", arguments = Seq(), - returnType = "Unnamed.Test.Cons", + returnType = "Unnamed.Test.List", documentation = Some(" And more") ), Vector() @@ -1493,23 +1512,8 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "Nil", arguments = Seq(), - returnType = "Unnamed.Test.Nil", - documentation = Some(" End") - ), - Vector() - ), - Tree.Node( - Suggestion.Method( - externalId = None, - module = "Unnamed.Test", - name = "empty", - arguments = Seq( - Suggestion - .Argument("self", "Unnamed.Test.Cons", false, false, None) - ), - selfType = "Unnamed.Test.Cons", returnType = "Unnamed.Test.List", - documentation = Some(" a method") + documentation = Some(" End") ), Vector() ), @@ -1520,9 +1524,9 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "empty", arguments = Seq( Suggestion - .Argument("self", "Unnamed.Test.Nil", false, false, None) + .Argument("self", "Unnamed.Test.List", false, false, None) ), - selfType = "Unnamed.Test.Nil", + selfType = "Unnamed.Test.List", returnType = "Unnamed.Test.List", documentation = Some(" a method") ), @@ -1535,8 +1539,8 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { "build type with methods, without type signatures" in { val code = """type Maybe - | type Nothing - | type Just a + | Nothing + | Just a | | map self f = case self of | Just a -> Just (f a) @@ -1552,7 +1556,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { module = "Unnamed.Test", name = "Nothing", arguments = Seq(), - returnType = "Unnamed.Test.Nothing", + returnType = "Unnamed.Test.Maybe", documentation = None ), Vector() @@ -1566,7 +1570,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { Suggestion .Argument("a", SuggestionBuilder.Any, false, false, None) ), - returnType = "Unnamed.Test.Just", + returnType = "Unnamed.Test.Maybe", documentation = None ), Vector() @@ -1578,9 +1582,9 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "a", arguments = List( Suggestion - .Argument("self", "Unnamed.Test.Just", false, false, None) + .Argument("self", "Unnamed.Test.Maybe", false, false, None) ), - selfType = "Unnamed.Test.Just", + selfType = "Unnamed.Test.Maybe", returnType = SuggestionBuilder.Any, documentation = None ), @@ -1593,28 +1597,11 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { name = "map", arguments = Seq( Suggestion - .Argument("self", "Unnamed.Test.Nothing", false, false, None), + .Argument("self", "Unnamed.Test.Maybe", false, false, None), Suggestion .Argument("f", SuggestionBuilder.Any, false, false, None) ), - selfType = "Unnamed.Test.Nothing", - returnType = SuggestionBuilder.Any, - documentation = None - ), - Vector() - ), - Tree.Node( - Suggestion.Method( - externalId = None, - module = "Unnamed.Test", - name = "map", - arguments = Seq( - Suggestion - .Argument("self", "Unnamed.Test.Just", false, false, None), - Suggestion - .Argument("f", SuggestionBuilder.Any, false, false, None) - ), - selfType = "Unnamed.Test.Just", + selfType = "Unnamed.Test.Maybe", returnType = SuggestionBuilder.Any, documentation = None ), @@ -1626,7 +1613,8 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { "build module with simple atom" in { val code = - """type MyType a b + """type MyType + | MkMyType a b | |main = IO.println "Hello!"""".stripMargin val module = code.preprocessModule @@ -1638,7 +1626,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { Suggestion.Atom( externalId = None, module = "Unnamed.Test", - name = "MyType", + name = "MkMyType", arguments = Seq( Suggestion .Argument("a", SuggestionBuilder.Any, false, false, None), @@ -1698,7 +1686,8 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { "build module with an atom named as module" in { val code = - """type Test a + """type Test + | Mk_Test a | |main = IO.println "Hello!"""".stripMargin val module = code.preprocessModule @@ -1710,7 +1699,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { Suggestion.Atom( externalId = None, module = "Unnamed.Test", - name = "Test", + name = "Mk_Test", arguments = Seq( Suggestion .Argument("a", SuggestionBuilder.Any, false, false, None) @@ -1754,7 +1743,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { "build module with overloaded functions" in { val code = """type A - | type A + | Mk_A | quux : A -> A | quux self x = x | @@ -1774,7 +1763,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { .Atom( externalId = None, module = "Unnamed.Test", - name = "A", + name = "Mk_A", arguments = List(), returnType = "Unnamed.Test.A", documentation = None @@ -1795,7 +1784,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { false, false, None, - Some(List("Unnamed.Test.A")) + Some(List("Unnamed.Test.Mk_A")) ) ), selfType = "Unnamed.Test.A", @@ -1817,7 +1806,7 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { false, false, None, - Some(List("Unnamed.Test.A")) + Some(List("Unnamed.Test.Mk_A")) ) ), selfType = "Unnamed.Test", @@ -2012,8 +2001,8 @@ class SuggestionBuilderTest extends AnyWordSpecLike with Matchers { "provide type variants when applicable" in { val code = """type My_Tp - | type Variant_A - | type Variant_B + | Variant_A + | Variant_B | |foo : My_Tp -> My_Tp |foo arg = arg.do_sth""".stripMargin diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala index 637908ddfaee..c47ad269ffd2 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/semantic/TypeSignaturesTest.scala @@ -136,8 +136,8 @@ class TypeSignaturesTest |type Util_2 | |type Util_Sum - | type Util_Sum_1 - | type Util_Sum_2 + | Util_Sum_1 + | Util_Sum_2 |""".stripMargin ) @@ -181,8 +181,8 @@ class TypeSignaturesTest |type B | |type C - | type X - | type D + | X + | D | |foo : A -> B -> C -> X -> D |foo a = 42""".stripMargin 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 300e479bf3ba..7aa558364290 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 @@ -54,30 +54,6 @@ class BooleanTest extends InterpreterTest { eval(code) shouldEqual 3 } - "support per-constructor method overloads" in { - val code = - """from Standard.Base.Data.Boolean import all - | - |True.to_num = 1 - |False.to_num = 2 - | - |main = True.to_num + False.to_num - |""".stripMargin - eval(code) shouldEqual 3 - } - - "support per-single-constructor method overloads" in { - val code = - """from Standard.Base.Data.Boolean import all - | - |Boolean.Boolean.to_num = 2 - |True.to_num = 1 - | - |main = True.to_num + False.to_num - |""".stripMargin - eval(code) shouldEqual 3 - } - "support logical AND and OR operators" in { val code = """from Standard.Base.Data.Boolean import all From 072abaa50290ca0fc3d05c6cac2ef0f6ec292b5c Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Thu, 25 Aug 2022 19:12:03 +0200 Subject: [PATCH 072/110] keep fixing tests --- .../scala/org/enso/compiler/core/IR.scala | 4 ++-- .../enso/compiler/pass/analyse/TailCall.scala | 3 ++- .../resolve/GenerateDocumentationTest.scala | 2 +- .../pass/resolve/MethodDefinitionsTest.scala | 22 +++++++++---------- .../test/pass/resolve/PatternsTest.scala | 3 ++- .../OverloadsResolutionErrorTest.scala | 19 ---------------- 6 files changed, 18 insertions(+), 35 deletions(-) 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 3525076bb23d..5a97bdce57bd 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 @@ -1035,7 +1035,7 @@ object IR { /** @inheritdoc */ override def toString: String = s""" - |IR.Module.Scope.Definition.UnionType( + |IR.Module.Scope.Definition.Type( |name = $name, |params = $params, |members = $members, @@ -1269,7 +1269,7 @@ object IR { /** @inheritdoc */ override def toString: String = s""" - |IR.Module.Scope.Definition.Type( + |IR.Module.Scope.Definition.SugaredType( |name = $name, |arguments = $arguments, |body = $body, diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/TailCall.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/TailCall.scala index 28aed17c9c48..fa03323f6393 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/TailCall.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/TailCall.scala @@ -110,7 +110,8 @@ case object TailCall extends IRPass { "Sugared method definitions should not occur during tail call " + "analysis." ) - case _: IR.Module.Scope.Definition.Type => definition + case _: IR.Module.Scope.Definition.Type => + definition.updateMetadata(this -->> TailPosition.Tail) case _: IR.Module.Scope.Definition.SugaredType => throw new CompilerError( "Complex type definitions should not be present during " + diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GenerateDocumentationTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GenerateDocumentationTest.scala index a0130182e85f..b8ab9d258989 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GenerateDocumentationTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GenerateDocumentationTest.scala @@ -97,7 +97,7 @@ class GenerateDocumentationTest extends CompilerTest with Inside { |""".stripMargin.preprocessModule.resolve ir.bindings.length shouldEqual 2 - ir.bindings(0) shouldBe an[IR.Module.Scope.Definition.Data] + ir.bindings(0) shouldBe an[IR.Module.Scope.Definition.Type] ir.bindings(1) shouldBe an[IR.Module.Scope.Definition.Method] getDoc(ir.bindings(0)) shouldEqual DocParserWrapper.runOnPureDoc( diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/MethodDefinitionsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/MethodDefinitionsTest.scala index 596352981809..dd07f8406e5e 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/MethodDefinitionsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/MethodDefinitionsTest.scala @@ -4,7 +4,7 @@ import org.enso.compiler.Passes import org.enso.compiler.context.{FreshNameSupply, ModuleContext} import org.enso.compiler.core.IR import org.enso.compiler.data.BindingsMap -import org.enso.compiler.data.BindingsMap.{Cons, ModuleReference} +import org.enso.compiler.data.BindingsMap.{ModuleReference, Type} import org.enso.compiler.pass.resolve.MethodDefinitions import org.enso.compiler.pass.{PassConfiguration, PassGroup, PassManager} import org.enso.compiler.test.CompilerTest @@ -77,9 +77,9 @@ class MethodDefinitionsTest extends CompilerTest { .get .getMetadata(MethodDefinitions) shouldEqual Some( BindingsMap.Resolution( - BindingsMap.ResolvedConstructor( + BindingsMap.ResolvedType( ModuleReference.Concrete(ctx.module), - Cons("Foo", 3, false) + Type("Foo", List(), false) ) ) ) @@ -112,17 +112,17 @@ class MethodDefinitionsTest extends CompilerTest { MethodDefinitions ) shouldEqual Some( BindingsMap.Resolution( - BindingsMap.ResolvedConstructor( + BindingsMap.ResolvedType( ModuleReference.Concrete(ctx.module), - Cons("Foo", 3, false) + Type("Foo", List(), false) ) ) ) conv1.sourceTypeName.getMetadata(MethodDefinitions) shouldEqual Some( BindingsMap.Resolution( - BindingsMap.ResolvedConstructor( + BindingsMap.ResolvedType( ModuleReference.Concrete(ctx.module), - Cons("Bar", 0, true) + Type("Bar", List(), false) ) ) ) @@ -134,9 +134,9 @@ class MethodDefinitionsTest extends CompilerTest { MethodDefinitions ) shouldEqual Some( BindingsMap.Resolution( - BindingsMap.ResolvedConstructor( + BindingsMap.ResolvedType( ModuleReference.Concrete(ctx.module), - Cons("Bar", 0, true) + Type("Bar", List(), false) ) ) ) @@ -148,9 +148,9 @@ class MethodDefinitionsTest extends CompilerTest { conv3.methodReference.typePointer.get shouldBe an[IR.Error.Resolution] conv3.sourceTypeName.getMetadata(MethodDefinitions) shouldEqual Some( BindingsMap.Resolution( - BindingsMap.ResolvedConstructor( + BindingsMap.ResolvedType( ModuleReference.Concrete(ctx.module), - Cons("Foo", 3, false) + Type("Foo", List(), false) ) ) ) diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/PatternsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/PatternsTest.scala index 8f1d6e4f8d0f..9457edff4f08 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/PatternsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/PatternsTest.scala @@ -61,7 +61,8 @@ class PatternsTest extends CompilerTest { val ir = """ - |type Foo a b c + |type F + | Foo a b c | |main = case this of | Foo a b c -> a + b + c 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 e637f87985b2..b2be6cb808d9 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 @@ -57,24 +57,5 @@ class OverloadsResolutionErrorTest extends InterpreterTest { ) } - "result in an error at runtime for methods overloading atoms" in { - val code = - """ - |type Foo - |foo = 0 - |""".stripMargin.linesIterator.mkString("\n") - - the[InterpreterException] thrownBy eval(code) should have message - "Compilation aborted due to errors." - - val diagnostics = consumeOut - diagnostics - .filterNot(_.contains("Compiler encountered")) - .filterNot(_.contains("In module")) - .toSet shouldEqual Set( - "Test[3:1-3:7]: Method definitions with the same name as atoms are not supported. Method foo clashes with the atom Foo in this module." - ) - } - } } From 2be4b19e2671ddf9810fd94e9f6e8d2e1bbd7de0 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 26 Aug 2022 15:32:49 +0200 Subject: [PATCH 073/110] fix deserializing AA metadata --- .../compiler/pass/analyse/AliasAnalysis.scala | 84 +++++++++++-------- 1 file changed, 49 insertions(+), 35 deletions(-) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala index 1981f55536fa..7c08a5ba82c9 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/analyse/AliasAnalysis.scala @@ -135,48 +135,62 @@ case object AliasAnalysis extends IRPass { sourceIr: T, copyOfIr: T ): T = { + def doCopy(sourceBinding: IR, copyBinding: IR): Unit = { + val sourceRootScopeGraphOpt = sourceBinding + .getMetadata(this) + + sourceRootScopeGraphOpt.foreach { sourceRootScopeGraphScope => + val sourceRootScopeGraph = + sourceRootScopeGraphScope.asInstanceOf[Info.Scope.Root].graph + + val scopeMapping = mutable.Map[Scope, Scope]() + val copyRootScopeGraph = + sourceRootScopeGraph.deepCopy(scopeMapping) + + val sourceNodes = sourceBinding.preorder + val copyNodes = copyBinding.preorder + + val matchedNodes = sourceNodes.lazyZip(copyNodes) + + matchedNodes.foreach { case (sourceNode, copyNode) => + sourceNode.getMetadata(this) match { + case Some(meta) => + val newMeta = meta match { + case root: Info.Scope.Root => + root.copy(graph = copyRootScopeGraph) + case child: Info.Scope.Child => + child.copy( + graph = copyRootScopeGraph, + scope = child.scope.deepCopy(scopeMapping) + ) + case occ: Info.Occurrence => + occ.copy(graph = copyRootScopeGraph) + } + copyNode.updateMetadata(this -->> newMeta) + case None => + } + } + } + } + (sourceIr, copyOfIr) match { case (sourceIr: IR.Module, copyOfIr: IR.Module) => val sourceBindings = sourceIr.bindings val copyBindings = copyOfIr.bindings val zippedBindings = sourceBindings.lazyZip(copyBindings) - zippedBindings.foreach { case (sourceBinding, copyBinding) => - val sourceRootScopeGraphOpt = sourceBinding - .getMetadata(this) - - sourceRootScopeGraphOpt.map { sourceRootScopeGraphScope => - val sourceRootScopeGraph = - sourceRootScopeGraphScope.asInstanceOf[Info.Scope.Root].graph - - val scopeMapping = mutable.Map[Scope, Scope]() - val copyRootScopeGraph = - sourceRootScopeGraph.deepCopy(scopeMapping) - - val sourceNodes = sourceBinding.preorder - val copyNodes = copyBinding.preorder - - val matchedNodes = sourceNodes.lazyZip(copyNodes) - - matchedNodes.foreach { case (sourceNode, copyNode) => - sourceNode.getMetadata(this) match { - case Some(meta) => - val newMeta = meta match { - case root: Info.Scope.Root => - root.copy(graph = copyRootScopeGraph) - case child: Info.Scope.Child => - child.copy( - graph = copyRootScopeGraph, - scope = child.scope.deepCopy(scopeMapping) - ) - case occ: Info.Occurrence => - occ.copy(graph = copyRootScopeGraph) - } - copyNode.updateMetadata(this -->> newMeta) - case None => - } + zippedBindings.foreach { + case ( + source: IR.Module.Scope.Definition.Type, + copy: IR.Module.Scope.Definition.Type + ) => + doCopy(source, copy) + source.members.lazyZip(copy.members).foreach { + case (source, copy) => + doCopy(source, copy) } - } + case (sourceBinding, copyBinding) => + doCopy(sourceBinding, copyBinding) } copyOfIr.asInstanceOf[T] case _ => copyOfIr From b0d573f54c62e183efcdf458300fcfb59cb18332 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 26 Aug 2022 15:51:41 +0200 Subject: [PATCH 074/110] last of runtime tests --- .../compiler/test/codegen/AstToIrTest.scala | 77 +++++++------------ 1 file changed, 29 insertions(+), 48 deletions(-) diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala index b981177ec6e2..5beadba0c95c 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/codegen/AstToIrTest.scala @@ -2,6 +2,7 @@ package org.enso.compiler.test.codegen import org.enso.compiler.core.IR import org.enso.compiler.core.IR.Error.Syntax +import org.enso.compiler.core.IR.Module.Scope.Definition.SugaredType import org.enso.compiler.test.CompilerTest import org.scalatest.Inside @@ -495,26 +496,32 @@ class AstToIrTest extends CompilerTest with Inside { } "AST translation for atom definitions" should { - "work for atoms with no arguments" in { + "work for types with no arguments" in { val ir = """ |type My_Type |""".stripMargin.toIrModule - ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Data] - val atom = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Data] - atom.name.name shouldEqual "My_Type" + ir.bindings.head shouldBe an[IR.Module.Scope.Definition.SugaredType] + val tp = + ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.SugaredType] + tp.name.name shouldEqual "My_Type" } - "work for atoms with arguments" in { + "work for types with arguments" in { val ir = """ - |type My_Type a b c + |type My_Type x + | Data a b c |""".stripMargin.toIrModule - ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Data] - val atom = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Data] - atom.name.name shouldEqual "My_Type" + ir.bindings.head shouldBe an[IR.Module.Scope.Definition.SugaredType] + val atom = ir.bindings.head + .asInstanceOf[IR.Module.Scope.Definition.SugaredType] + .body + .head + .asInstanceOf[IR.Module.Scope.Definition.Data] + atom.name.name shouldEqual "Data" val args = atom.arguments args.length shouldEqual 3 args.head.name.name shouldEqual "a" @@ -522,24 +529,6 @@ class AstToIrTest extends CompilerTest with Inside { args(2).name.name shouldEqual "c" } - "work for atoms with default arguments" in { - val ir = - """ - |type My_Type (a = 1) - |""".stripMargin.toIrModule - - ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Data] - val atom = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Data] - atom.name.name shouldEqual "My_Type" - val args = atom.arguments - args.length shouldEqual 1 - val firstArg = args.head - firstArg.name.name shouldEqual "a" - firstArg.ascribedType should not be defined - firstArg.defaultValue shouldBe defined - firstArg.suspended shouldBe false - } - "raise an error for atoms with lazy arguments" in { val ir = """ @@ -554,12 +543,17 @@ class AstToIrTest extends CompilerTest with Inside { "work for atoms with ascribed arguments" in { val ir = """ - |type My_Type a:b (c : d = 1) + |type My_Type + | Data a:b (c : d = 1) |""".stripMargin.toIrModule - ir.bindings.head shouldBe an[IR.Module.Scope.Definition.Data] - val atom = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.Data] - atom.name.name shouldEqual "My_Type" + ir.bindings.head shouldBe an[IR.Module.Scope.Definition.SugaredType] + val atom = ir.bindings.head + .asInstanceOf[SugaredType] + .body + .head + .asInstanceOf[IR.Module.Scope.Definition.Data] + atom.name.name shouldEqual "Data" val args = atom.arguments args.length shouldEqual 2 @@ -606,7 +600,7 @@ class AstToIrTest extends CompilerTest with Inside { |type MyAtom a b |""".stripMargin.toIrModule.bindings.head - ir shouldBe an[IR.Module.Scope.Definition.Data] + ir shouldBe an[IR.Module.Scope.Definition.SugaredType] } "translate complex type defs properly" in { @@ -614,7 +608,7 @@ class AstToIrTest extends CompilerTest with Inside { """ |type Maybe | Nothing - | type Just a + | Just a | | is_just = case this of | Just _ -> true @@ -630,7 +624,7 @@ class AstToIrTest extends CompilerTest with Inside { typeDef.name.name shouldEqual "Maybe" typeDef.arguments.length shouldEqual 0 - typeDef.body.head shouldBe an[IR.Name.Literal] + typeDef.body.head shouldBe an[IR.Module.Scope.Definition.Data] typeDef.body(1) shouldBe an[IR.Module.Scope.Definition.Data] typeDef.body(2) shouldBe an[IR.Expression.Binding] typeDef.body(3) shouldBe an[IR.Function.Binding] @@ -667,19 +661,6 @@ class AstToIrTest extends CompilerTest with Inside { .reason shouldBe an[IR.Error.Syntax.UnexpectedDeclarationInType.type] } - "disallow definitions with 'type' arguments" in { - val ir = - """ - |type Maybe a - | Nothing - | type Just a - |""".stripMargin.toIrModule.bindings.head - - ir shouldBe an[IR.Error.Syntax] - ir.asInstanceOf[IR.Error.Syntax] - .reason shouldBe an[IR.Error.Syntax.InvalidTypeDefinition.type] - } - "allow defining methods with operator names" in { val body = """ @@ -987,7 +968,7 @@ class AstToIrTest extends CompilerTest with Inside { |""".stripMargin.toIrModule ir.bindings.head shouldBe an[IR.Name.Annotation] - ir.bindings(1) shouldBe an[IR.Module.Scope.Definition.Data] + ir.bindings(1) shouldBe an[IR.Module.Scope.Definition.SugaredType] } "support annotations inside complex type bodies" in { From d44d321a5c7b6d75db3b9f857f4fad05056fe61c Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 26 Aug 2022 16:32:19 +0200 Subject: [PATCH 075/110] fix runtime instrument, progress on tests --- .../test/instrument/ReplTest.scala | 15 ++-- .../test/instrument/RuntimeErrorsTest.scala | 2 +- .../test/instrument/RuntimeServerTest.scala | 86 +++---------------- .../runtime/scope/ModuleScope.java | 7 +- .../interpreter/service/ExecutionService.java | 13 ++- .../error/ConstructorNotFoundException.java | 23 ----- .../service/error/TypeNotFoundException.java | 23 +++++ .../job/ProgramExecutionSupport.scala | 4 +- 8 files changed, 58 insertions(+), 115 deletions(-) delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/service/error/ConstructorNotFoundException.java create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/service/error/TypeNotFoundException.java diff --git a/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala b/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala index 5195116bf2c8..4631ebcf539d 100644 --- a/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala +++ b/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/ReplTest.scala @@ -75,17 +75,20 @@ class ReplTest |polyglot java import java.util.regex.Pattern |import Standard.Base.Runtime.Debug | - |type Foo a b + |type A + | Foo a b | - |Foo.to_text self = "{" + self.a.to_text + ": " + self.b + "}" + |A.to_text self = "{" + self.a.to_text + ": " + self.b + "}" | - |type Bar x + |type B + | Bar x | - |Bar.to_text self = 42 + |B.to_text self = 42 | - |type Baz x + |type C + | Baz x | - |Baz.to_text self a b c = a+b+c + |C.to_text self a b c = a+b+c | |main = | x = Debug.breakpoint diff --git a/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala b/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala index b8b926e86612..a3330169a334 100644 --- a/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala +++ b/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeErrorsTest.scala @@ -622,7 +622,7 @@ class RuntimeErrorsTest context.executionComplete(contextId) ) context.consumeOut shouldEqual List( - "(Error: (Arithmetic_Error 'Cannot divide by zero.'))" + "(Error: (Arithmetic_Error_Data 'Cannot divide by zero.'))" ) // Modify the file diff --git a/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index d85f72876128..d9a161e8b04b 100644 --- a/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -493,20 +493,20 @@ class RuntimeServerTest val moduleName = "Enso_Test.Test.Main" val metadata = new Metadata - val idMain = metadata.addItem(103, 116) - val idMainX = metadata.addItem(130, 8) - val idMainY = metadata.addItem(147, 3) - val idMainM = metadata.addItem(159, 5) - val idMainP = metadata.addItem(173, 5) - val idMainQ = metadata.addItem(187, 5) - val idMainF = metadata.addItem(209, 9) + val idMain = metadata.addItem(99, 116) + val idMainX = metadata.addItem(126, 8) + val idMainY = metadata.addItem(143, 3) + val idMainM = metadata.addItem(155, 5) + val idMainP = metadata.addItem(169, 5) + val idMainQ = metadata.addItem(183, 5) + val idMainF = metadata.addItem(205, 9) val code = """import Standard.Base.IO |import Enso_Test.Test.A | - |type Quux - | type Quux + |type QuuxT + | Quux | | foo = 42 | @@ -526,7 +526,7 @@ class RuntimeServerTest val aCode = """ - |type A + |type AT | type A un_a | | foo = 11 @@ -2267,7 +2267,7 @@ class RuntimeServerTest Api.ExecutionFailed( contextId, Api.ExecutionResult.Failure( - "Constructor Unexpected not found in module Enso_Test.Test.Main.", + "Type Unexpected not found in module Enso_Test.Test.Main.", Some(mainFile) ) ) @@ -2617,66 +2617,6 @@ class RuntimeServerTest ) } - it should "return error when method name clashes with atom" in { - val contextId = UUID.randomUUID() - val requestId = UUID.randomUUID() - val moduleName = "Enso_Test.Test.Main" - val metadata = new Metadata - - val code = - """type Foo - |foo = 0 - |main = 0 - |""".stripMargin.linesIterator.mkString("\n") - val contents = metadata.appendToCode(code) - val mainFile = context.writeMain(contents) - - // create context - context.send(Api.Request(requestId, Api.CreateContextRequest(contextId))) - context.receive shouldEqual Some( - Api.Response(requestId, Api.CreateContextResponse(contextId)) - ) - - // Open the new file - context.send( - Api.Request(Api.OpenFileNotification(mainFile, contents)) - ) - context.receiveNone shouldEqual None - - // push main - context.send( - Api.Request( - requestId, - Api.PushContextRequest( - contextId, - Api.StackItem.ExplicitCall( - Api.MethodPointer(moduleName, "Enso_Test.Test.Main", "main"), - None, - Vector() - ) - ) - ) - ) - context.receiveN(3) should contain theSameElementsAs Seq( - Api.Response(requestId, Api.PushContextResponse(contextId)), - Api.Response( - Api.ExecutionUpdate( - contextId, - Seq( - Api.ExecutionResult.Diagnostic.error( - "Method definitions with the same name as atoms are not supported. Method foo clashes with the atom Foo in this module.", - Some(mainFile), - Some(model.Range(model.Position(1, 0), model.Position(1, 7))), - None, - Vector() - ) - ) - ) - ), - context.executionComplete(contextId) - ) - } - it should "return error with a stack trace" in { val contextId = UUID.randomUUID() val requestId = UUID.randomUUID() @@ -3018,8 +2958,8 @@ class RuntimeServerTest context.executionComplete(contextId) ) context.consumeOut shouldEqual List( - "(Error: (Syntax_Error 'Unrecognized token.'))", - "(Syntax_Error 'Unrecognized token.')" + "(Error: (Syntax_Error_Data 'Unrecognized token.'))", + "(Syntax_Error_Data 'Unrecognized token.')" ) } 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 9499b413280c..a09280aa877e 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 @@ -82,9 +82,6 @@ public Set getImports() { * @return the atom constructor associated with {@code name}, or {@link Optional#empty()} */ public Optional getLocalConstructor(String name) { - // if (associatedType.getName().equals(name)) { - // return Optional.of(associatedType); - // } return Optional.ofNullable(this.constructors.get(name)); } @@ -293,6 +290,9 @@ public Map getTypes() { } public Optional getType(String name) { + if (associatedType.getName().equals(name)) { + return Optional.of(associatedType); + } return Optional.ofNullable(types.get(name)); } @@ -322,6 +322,7 @@ public void reset() { exports = new HashSet<>(); methods = new HashMap<>(); constructors = new HashMap<>(); + types = new HashMap<>(); conversions = new HashMap<>(); polyglotSymbols = new HashMap<>(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java b/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java index b7ea44f1e0e5..c187ce116dfe 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java @@ -21,13 +21,12 @@ import org.enso.interpreter.node.expression.builtin.text.util.TypeToDisplayTextNodeGen; import org.enso.interpreter.runtime.Context; import org.enso.interpreter.runtime.Module; -import org.enso.interpreter.runtime.callable.atom.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.error.PanicException; import org.enso.interpreter.runtime.scope.ModuleScope; import org.enso.interpreter.runtime.state.data.EmptyMap; -import org.enso.interpreter.service.error.ConstructorNotFoundException; +import org.enso.interpreter.service.error.TypeNotFoundException; import org.enso.interpreter.service.error.FailedToApplyEditsException; import org.enso.interpreter.service.error.MethodNotFoundException; import org.enso.interpreter.service.error.ModuleNotFoundException; @@ -89,13 +88,13 @@ public TruffleLogger getLogger() { private FunctionCallInstrumentationNode.FunctionCall prepareFunctionCall( Module module, String typeName, String methodName) - throws ConstructorNotFoundException, MethodNotFoundException { + throws TypeNotFoundException, MethodNotFoundException { ModuleScope scope = module.compileScope(context); Type type = scope .getType(typeName) .orElseThrow( - () -> new ConstructorNotFoundException(module.getName().toString(), typeName)); + () -> new TypeNotFoundException(module.getName().toString(), typeName)); Function function = scope.lookupMethodDefinition(type, methodName); if (function == null) { throw new MethodNotFoundException(module.getName().toString(), type, methodName); @@ -189,7 +188,7 @@ public void execute( */ public void execute( String moduleName, - String consName, + String typeName, String methodName, RuntimeCache cache, MethodCallsCache methodCallsCache, @@ -199,12 +198,12 @@ public void execute( Consumer onComputedCallback, Consumer onCachedCallback, Consumer onExceptionalCallback) - throws ArityException, ConstructorNotFoundException, MethodNotFoundException, + throws ArityException, TypeNotFoundException, MethodNotFoundException, ModuleNotFoundException, UnsupportedMessageException, UnsupportedTypeException { Module module = context.findModule(moduleName).orElseThrow(() -> new ModuleNotFoundException(moduleName)); FunctionCallInstrumentationNode.FunctionCall call = - prepareFunctionCall(module, consName, methodName); + prepareFunctionCall(module, typeName, methodName); execute( module, call, diff --git a/engine/runtime/src/main/java/org/enso/interpreter/service/error/ConstructorNotFoundException.java b/engine/runtime/src/main/java/org/enso/interpreter/service/error/ConstructorNotFoundException.java deleted file mode 100644 index e1f07a63ab34..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/service/error/ConstructorNotFoundException.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.enso.interpreter.service.error; - -/** Thrown when the constructor can not be found for a given module. */ -public class ConstructorNotFoundException extends RuntimeException implements ServiceException { - - private final String module; - - /** - * Create new instance of this error. - * - * @param module the qualified module name. - * @param constructor the name of the non-existent constructor. - */ - public ConstructorNotFoundException(String module, String constructor) { - super("Constructor " + constructor + " not found in module " + module + "."); - this.module = module; - } - - /** @return moudle name. */ - public String getModule() { - return module; - } -} diff --git a/engine/runtime/src/main/java/org/enso/interpreter/service/error/TypeNotFoundException.java b/engine/runtime/src/main/java/org/enso/interpreter/service/error/TypeNotFoundException.java new file mode 100644 index 000000000000..dd87d13588e6 --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/service/error/TypeNotFoundException.java @@ -0,0 +1,23 @@ +package org.enso.interpreter.service.error; + +/** Thrown when the constructor can not be found for a given module. */ +public class TypeNotFoundException extends RuntimeException implements ServiceException { + + private final String module; + + /** + * Create new instance of this error. + * + * @param module the qualified module name. + * @param type the name of the non-existent type. + */ + public TypeNotFoundException(String module, String type) { + super("Type " + type + " not found in module " + module + "."); + this.module = module; + } + + /** @return module name. */ + public String getModule() { + return module; + } +} diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ProgramExecutionSupport.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ProgramExecutionSupport.scala index e2d2df78df17..62221b6e7d3a 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ProgramExecutionSupport.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ProgramExecutionSupport.scala @@ -31,7 +31,7 @@ import org.enso.interpreter.runtime.error.{DataflowError, PanicSentinel} import org.enso.interpreter.runtime.`type`.Types import org.enso.interpreter.runtime.control.ThreadInterruptedException import org.enso.interpreter.service.error.{ - ConstructorNotFoundException, + TypeNotFoundException, MethodNotFoundException, ModuleNotFoundForExpressionIdException, ServiceException, @@ -290,7 +290,7 @@ object ProgramExecutionSupport { def getFailureOutcome(implicit ctx: RuntimeContext ): PartialFunction[Throwable, Api.ExecutionResult.Failure] = { - case ex: ConstructorNotFoundException => + case ex: TypeNotFoundException => Api.ExecutionResult.Failure( ex.getMessage, findFileByModuleName(ex.getModule) From 678ed84ea1dc728e6a5838c93d9c9d63d8bccb35 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 26 Aug 2022 16:52:55 +0200 Subject: [PATCH 076/110] all tests pass --- .../interpreter/test/instrument/RuntimeServerTest.scala | 6 +++--- .../test/instrument/RuntimeSuggestionUpdatesTest.scala | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala b/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala index d9a161e8b04b..32dd07752372 100644 --- a/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala +++ b/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeServerTest.scala @@ -527,7 +527,7 @@ class RuntimeServerTest val aCode = """ |type AT - | type A un_a + | A un_a | | foo = 11 | @@ -571,7 +571,7 @@ class RuntimeServerTest ConstantsGen.INTEGER, Api.MethodPointer( "Enso_Test.Test.Main", - "Enso_Test.Test.Main.Quux", + "Enso_Test.Test.Main.QuuxT", "foo" ) ), @@ -586,7 +586,7 @@ class RuntimeServerTest contextId, idMainP, ConstantsGen.INTEGER, - Api.MethodPointer("Enso_Test.Test.A", "Enso_Test.Test.A.A", "foo") + Api.MethodPointer("Enso_Test.Test.A", "Enso_Test.Test.A.AT", "foo") ), TestMessages.update( contextId, diff --git a/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala b/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala index 9f14af312f7a..e06ba713e231 100644 --- a/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala +++ b/engine/runtime-with-instruments/src/test/scala/org/enso/interpreter/test/instrument/RuntimeSuggestionUpdatesTest.scala @@ -873,7 +873,7 @@ class RuntimeSuggestionUpdatesTest """from Standard.Base.Data.Numbers import Integer | |type MyType - | type MkA a + | MkA a | |Integer.fortytwo self = 42 | @@ -943,7 +943,7 @@ class RuntimeSuggestionUpdatesTest Suggestion .Argument("a", ConstantsGen.ANY, false, false, None) ), - "Enso_Test.Test.A.MkA", + "Enso_Test.Test.A.MyType", None, None, None @@ -962,13 +962,13 @@ class RuntimeSuggestionUpdatesTest Suggestion .Argument( "self", - "Enso_Test.Test.A.MkA", + "Enso_Test.Test.A.MyType", false, false, None ) ), - "Enso_Test.Test.A.MkA", + "Enso_Test.Test.A.MyType", ConstantsGen.ANY, None, None, From d040c7780fd8c71a6f0f276b4823192649063eeb Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 26 Aug 2022 17:15:17 +0200 Subject: [PATCH 077/110] ALL tests --- .../main/java/org/enso/polyglot/MethodNames.java | 5 ++++- .../main/scala/org/enso/polyglot/Module.scala | 7 +++++-- .../test/scala/org/enso/polyglot/ApiTest.scala | 16 +++++++++------- .../org/enso/polyglot/ModuleManagementTest.scala | 12 ++++++------ .../src/main/scala/org/enso/runner/Main.scala | 2 +- .../org/enso/interpreter/runtime/Module.java | 15 ++++++++++++--- .../enso/interpreter/test/InterpreterTest.scala | 2 +- .../org/enso/interpreter/test/PackageTest.scala | 2 +- .../test/semantic/CodeLocationsTest.scala | 2 +- 9 files changed, 40 insertions(+), 23 deletions(-) diff --git a/engine/polyglot-api/src/main/java/org/enso/polyglot/MethodNames.java b/engine/polyglot-api/src/main/java/org/enso/polyglot/MethodNames.java index 163951d1af1c..4debebf59541 100644 --- a/engine/polyglot-api/src/main/java/org/enso/polyglot/MethodNames.java +++ b/engine/polyglot-api/src/main/java/org/enso/polyglot/MethodNames.java @@ -13,8 +13,11 @@ public static class TopScope { public static class Module { public static final String EVAL_EXPRESSION = "eval_expression"; - public static final String GET_ASSOCIATED_CONSTRUCTOR = "get_associated_constructor"; + public static final String GET_ASSOCIATED_TYPE = "get_associated_type"; public static final String GET_CONSTRUCTOR = "get_constructor"; + + public static final String GET_TYPE = "get_type"; + public static final String GET_METHOD = "get_method"; public static final String GET_NAME = "get_name"; public static final String REPARSE = "reparse"; diff --git a/engine/polyglot-api/src/main/scala/org/enso/polyglot/Module.scala b/engine/polyglot-api/src/main/scala/org/enso/polyglot/Module.scala index 83a172f6ee9e..eb1a5ae0eab0 100644 --- a/engine/polyglot-api/src/main/scala/org/enso/polyglot/Module.scala +++ b/engine/polyglot-api/src/main/scala/org/enso/polyglot/Module.scala @@ -15,8 +15,8 @@ class Module(private val value: Value) { /** @return the associated type of this module */ - def getAssociatedConstructor: Value = - value.invokeMember(GET_ASSOCIATED_CONSTRUCTOR) + def getAssociatedType: Value = + value.invokeMember(GET_ASSOCIATED_TYPE) /** Gets a constructor definition by name. * @@ -26,6 +26,9 @@ class Module(private val value: Value) { def getConstructor(name: String): Value = value.invokeMember(GET_CONSTRUCTOR, name) + def getType(name: String): Value = + value.invokeMember(GET_TYPE, name) + /** Gets a method by the type it's defined on and name. * * @param constructor the constructor the method is defined on diff --git a/engine/polyglot-api/src/test/scala/org/enso/polyglot/ApiTest.scala b/engine/polyglot-api/src/test/scala/org/enso/polyglot/ApiTest.scala index 0257a3215a94..524de12ca15e 100644 --- a/engine/polyglot-api/src/test/scala/org/enso/polyglot/ApiTest.scala +++ b/engine/polyglot-api/src/test/scala/org/enso/polyglot/ApiTest.scala @@ -27,10 +27,10 @@ class ApiTest extends AnyFlatSpec with Matchers { |bar = x -> foo x + 1 |""".stripMargin val module = executionContext.evalModule(code, "Test") - val associatedConstructor = module.getAssociatedConstructor + val associatedConstructor = module.getAssociatedType val barFunction = module.getMethod(associatedConstructor, "bar").get val result = barFunction.execute( - associatedConstructor.newInstance(), + associatedConstructor, 10L.asInstanceOf[AnyRef] ) result.asLong shouldEqual 12 @@ -39,19 +39,21 @@ class ApiTest extends AnyFlatSpec with Matchers { "Parsing a file and calling a method on an arbitrary atom" should "be possible" in { val code = """ - |type Vector x y z + |type Vector + | Vec x y z | |Vector.squares self = case self of - | Vector x y z -> Vector x*x y*y z*z + | Vec x y z -> Vec x*x y*y z*z | |Vector.sum self = case self of - | Vector x y z -> x + y + z + | Vec x y z -> x + y + z | |Vector.squareNorm self = self.squares.sum |""".stripMargin val module = executionContext.evalModule(code, "Test") - val vectorCons = module.getConstructor("Vector") - val squareNorm = module.getMethod(vectorCons, "squareNorm").get + val vectorCons = module.getConstructor("Vec") + val squareNorm = + module.getMethod(module.getType("Vector"), "squareNorm").get val testVector = vectorCons.newInstance( 1L.asInstanceOf[AnyRef], 2L.asInstanceOf[AnyRef], diff --git a/engine/polyglot-api/src/test/scala/org/enso/polyglot/ModuleManagementTest.scala b/engine/polyglot-api/src/test/scala/org/enso/polyglot/ModuleManagementTest.scala index 088c3a2aae6e..06b07f0900f5 100644 --- a/engine/polyglot-api/src/test/scala/org/enso/polyglot/ModuleManagementTest.scala +++ b/engine/polyglot-api/src/test/scala/org/enso/polyglot/ModuleManagementTest.scala @@ -59,7 +59,7 @@ class ModuleManagementTest val mainModule = ctx.executionContext.getTopScope.getModule("Enso_Test.Test.Main") - val assocCons = mainModule.getAssociatedConstructor + val assocCons = mainModule.getAssociatedType val mainFun1 = mainModule.getMethod(assocCons, "main").get mainFun1.execute().asLong() shouldEqual 12345L @@ -80,7 +80,7 @@ class ModuleManagementTest val mainModule = ctx.executionContext.getTopScope.getModule("Enso_Test.Test.Main") - val assocCons = mainModule.getAssociatedConstructor + val assocCons = mainModule.getAssociatedType val mainFun1 = mainModule.getMethod(assocCons, "main").get mainFun1.execute().asLong() shouldEqual 123L @@ -127,7 +127,7 @@ class ModuleManagementTest ) val mainModule = topScope.getModule("Enso_Test.Test.Main") - val assocCons = mainModule.getAssociatedConstructor + val assocCons = mainModule.getAssociatedType val mainFun = mainModule.getMethod(assocCons, "main").get mainFun.execute().asLong shouldEqual 11L } @@ -156,7 +156,7 @@ class ModuleManagementTest |""".stripMargin) val mainModule = topScope.getModule("Enso_Test.Test.Main") - val assocCons = mainModule.getAssociatedConstructor + val assocCons = mainModule.getAssociatedType val mainFun = mainModule.getMethod(assocCons, "main").get mainFun.execute().asLong shouldEqual 21L } @@ -174,7 +174,7 @@ class ModuleManagementTest |""".stripMargin, "X" ) - val mod1AssocCons = mod1.getAssociatedConstructor + val mod1AssocCons = mod1.getAssociatedType val mod1Main = mod1.getMethod(mod1AssocCons, "bar").get mod1Main.execute(mod1AssocCons).asLong shouldEqual 124 @@ -189,7 +189,7 @@ class ModuleManagementTest "X2" ) val exception = - the[PolyglotException] thrownBy mod2.getAssociatedConstructor + the[PolyglotException] thrownBy mod2.getAssociatedType exception.getMessage shouldEqual "Compilation aborted due to errors." } diff --git a/engine/runner/src/main/scala/org/enso/runner/Main.scala b/engine/runner/src/main/scala/org/enso/runner/Main.scala index f9b0633eb197..25c6007c6066 100644 --- a/engine/runner/src/main/scala/org/enso/runner/Main.scala +++ b/engine/runner/src/main/scala/org/enso/runner/Main.scala @@ -754,7 +754,7 @@ object Main { mainMethodName: String = "main" ): Unit = { try { - val mainCons = mainModule.getAssociatedConstructor + val mainCons = mainModule.getAssociatedType val mainFun = mainModule.getMethod(mainCons, mainMethodName) mainFun match { case Some(main) => main.execute() 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 30e78f19c45e..86f5b7287c68 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 @@ -573,6 +573,12 @@ private static AtomConstructor getConstructor(ModuleScope scope, Object[] args) return scope.getConstructors().get(name); } + private static Type getType(ModuleScope scope, Object[] args) + throws ArityException, UnsupportedTypeException { + String name = Types.extractArguments(args, String.class); + return scope.getTypes().get(name); + } + private static Module reparse(Module module, Object[] args, Context context) throws ArityException { Types.extractArguments(args); @@ -653,6 +659,9 @@ static Object doInvoke( case MethodNames.Module.GET_CONSTRUCTOR: scope = module.compileScope(context); return getConstructor(scope, arguments); + case MethodNames.Module.GET_TYPE: + scope = module.compileScope(context); + return getType(scope, arguments); case MethodNames.Module.REPARSE: return reparse(module, arguments, context); case MethodNames.Module.GENERATE_DOCS: @@ -663,7 +672,7 @@ static Object doInvoke( return setSource(module, arguments, context); case MethodNames.Module.SET_SOURCE_FILE: return setSourceFile(module, arguments, context); - case MethodNames.Module.GET_ASSOCIATED_CONSTRUCTOR: + case MethodNames.Module.GET_ASSOCIATED_TYPE: scope = module.compileScope(context); return getAssociatedType(scope, arguments); case MethodNames.Module.EVAL_EXPRESSION: @@ -698,7 +707,7 @@ boolean isMemberInvocable(String member) { || member.equals(MethodNames.Module.REPARSE) || member.equals(MethodNames.Module.SET_SOURCE) || member.equals(MethodNames.Module.SET_SOURCE_FILE) - || member.equals(MethodNames.Module.GET_ASSOCIATED_CONSTRUCTOR) + || member.equals(MethodNames.Module.GET_ASSOCIATED_TYPE) || member.equals(MethodNames.Module.EVAL_EXPRESSION); } @@ -716,7 +725,7 @@ Object getMembers(boolean includeInternal) { MethodNames.Module.REPARSE, MethodNames.Module.SET_SOURCE, MethodNames.Module.SET_SOURCE_FILE, - MethodNames.Module.GET_ASSOCIATED_CONSTRUCTOR, + MethodNames.Module.GET_ASSOCIATED_TYPE, MethodNames.Module.EVAL_EXPRESSION); } } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/InterpreterTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/InterpreterTest.scala index bd3cde99f274..0d2890ea2434 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/InterpreterTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/InterpreterTest.scala @@ -171,7 +171,7 @@ trait InterpreterRunner { val module = InterpreterException.rethrowPolyglot( interpreterContext.executionContext.evalModule(code, "Test") ) - val assocCons = module.getAssociatedConstructor + val assocCons = module.getAssociatedType val mainFunction = module.getMethod(assocCons, "main").get MainMethod(assocCons, mainFunction) } diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/PackageTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/PackageTest.scala index e8a504606d6d..9fac79866d8d 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/PackageTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/PackageTest.scala @@ -43,7 +43,7 @@ trait PackageTest extends AnyFlatSpec with Matchers with ValueEquality { InterpreterException.rethrowPolyglot { val topScope = executionContext.getTopScope val mainModuleScope = topScope.getModule(mainModule.toString) - val assocCons = mainModuleScope.getAssociatedConstructor + val assocCons = mainModuleScope.getAssociatedType val mainFun = mainModuleScope.getMethod(assocCons, "main").get mainFun.execute() } 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 633f8aa8e4ad..b17136ce9e39 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 @@ -216,7 +216,7 @@ class CodeLocationsTest extends InterpreterTest { |""".stripMargin val mod = interpreterContext.executionContext.evalModule(code, "Test") - val tpe = mod.getAssociatedConstructor + val tpe = mod.getAssociatedType val method = mod.getMethod(tpe, "foo").get method.value.invokeMember( MethodNames.Function.GET_SOURCE_START From 21fc962e7cdfab15d2144cea734eff72fe5807ab Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 26 Aug 2022 23:08:52 +0200 Subject: [PATCH 078/110] fix all of Base once again, after merge.... --- .../0.0.0-dev/src/Data/Time/Day_Of_Week.enso | 20 +++--- .../Base/0.0.0-dev/src/Data/Vector.enso | 62 ++++++++-------- .../src/Polyglot/Proxy_Polyglot_Array.enso | 2 +- .../node/callable/InvokeMethodNode.java | 67 +++++++++-------- .../text/util/TypeToDisplayTextNode.java | 2 +- .../expression/foreign/CoerceNothing.java | 2 +- .../interpreter/runtime/builtin/Builtins.java | 8 ++- .../runtime/data/EnsoDateTime.java | 48 ++----------- .../runtime/data/EnsoTimeOfDay.java | 47 ++---------- .../runtime/data/EnsoTimeZone.java | 49 ++----------- .../interpreter/service/ExecutionService.java | 14 ++-- .../enso/compiler/codegen/IrToTruffle.scala | 9 +-- .../compiler/pass/resolve/GlobalNames.scala | 26 ------- test/Tests/src/Data/Array_Spec.enso | 4 +- test/Tests/src/Data/Range_Spec.enso | 8 +-- test/Tests/src/Data/Text/Encoding_Spec.enso | 2 +- .../src/Data/Text/Text_Sub_Range_Spec.enso | 18 ++--- test/Tests/src/Data/Time/Date_Spec.enso | 2 +- test/Tests/src/Data/Time/Date_Time_Spec.enso | 12 ++-- .../Tests/src/Data/Time/Time_Of_Day_Spec.enso | 6 +- test/Tests/src/Data/Time/Time_Zone_Spec.enso | 2 +- .../src/Data/Vector/Slicing_Helpers_Spec.enso | 20 +++--- test/Tests/src/Data/Vector_Spec.enso | 72 +++++++++---------- test/Tests/src/Semantic/Conversion_Spec.enso | 2 +- test/Tests/src/Semantic/Names_Spec.enso | 2 +- 25 files changed, 193 insertions(+), 313 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Day_Of_Week.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Day_Of_Week.enso index 710e56e39c41..7c9fea48ffa0 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Day_Of_Week.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Time/Day_Of_Week.enso @@ -1,19 +1,19 @@ from Standard.Base import all type Day_Of_Week - type Sunday + Sunday - type Monday + Monday - type Tuesday + Tuesday - type Wednesday + Wednesday - type Thursday + Thursday - type Friday + Friday - type Saturday + Saturday ## Convert the Day_Of_Week to an Integer @@ -31,7 +31,7 @@ type Day_Of_Week Friday -> 5 Saturday -> 6 - shifted = if first_day == Day_Of_Week.Sunday then day_number else + shifted = if first_day == Sunday then day_number else (day_number + 7 - (first_day.to_integer start_at_zero=True)) % 7 shifted + if start_at_zero then 0 else 1 @@ -42,7 +42,7 @@ type Day_Of_Week - `that`: The first day of the week. - `first_day`: The first day of the week. - `start_at_zero`: If True, first day of the week is 0 otherwise is 1. -Day_Of_Week.from (that : Integer) (first_day:Day_Of_Week=Sunday) (start_at_zero:Boolean=False) = +from (that : Integer) (first_day:Day_Of_Week=Sunday) (start_at_zero:Boolean=False) = shifted = if start_at_zero then that else that - 1 case (shifted < 0) || (shifted > 6) of @@ -51,7 +51,7 @@ Day_Of_Week.from (that : Integer) (first_day:Day_Of_Week=Sunday) (start_at_zero: message = "Invalid day of week (must be " + valid_range + ")." Error.throw (Illegal_Argument_Error message) False -> - day_number = if first_day == Day_Of_Week.Sunday then shifted else + day_number = if first_day == Sunday then shifted else (shifted + (first_day.to_integer start_at_zero=True)) % 7 [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday].at day_number 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 3c0081308dfc..66b32106be61 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 @@ -92,10 +92,10 @@ new_builder (capacity=10) = Builder.new capacity A vector allows to store an arbitrary number of elements in linear memory. It is the recommended data structure for most applications. from_polyglot_array : Any -> Vector Any -from_polyglot_array arr = Vector (Proxy_Polyglot_Array.Proxy_Polyglot_Array arr) +from_polyglot_array arr = Vector_Data (Proxy_Polyglot_Array.Proxy_Polyglot_Array_Data arr) ## The basic, immutable, vector type. -type Vector +type Vector a ## ADVANCED @@ -115,13 +115,13 @@ type Vector A vector containing 50 elements, each being the number `42`, can be created by: Vector.fill length=50 item=42 - type Vector_Data storage + Vector_Data storage ## PRIVATE to_array self = arr = self.storage.to_array case Meta.meta arr of - Meta.Primitive _ -> arr + Meta.Primitive_Data _ -> arr _ -> len = self.storage.length a = Array.new len @@ -680,15 +680,15 @@ type Vector If a `Range`, the selection is specified by two indices, from and to. take : (Index_Sub_Range | Range) -> Vector Any take self range=(First 1) = case range of - Range _ _ _ -> self.take (By_Index range) + Range_Data _ _ _ -> self.take (By_Index range) First count -> self.slice 0 (Math.min self.length count) Last count -> self.slice self.length-count self.length While predicate -> end = 0.up_to self.length . find i-> (predicate (self.at i)).not if end.is_nothing then self else self.slice 0 end - By_Index one_or_many_descriptors -> Panic.recover [Index_Out_Of_Bounds_Error, Illegal_Argument_Error] <| + By_Index one_or_many_descriptors -> Panic.recover [Index_Out_Of_Bounds_Error_Data, Illegal_Argument_Error_Data] <| indices = case one_or_many_descriptors of - Vector _ -> one_or_many_descriptors + Vector_Data _ -> one_or_many_descriptors _ -> [one_or_many_descriptors] trimmed = resolve_ranges indices self.length slice_ranges self trimmed @@ -696,9 +696,9 @@ type Vector rng = Random.new seed Random.sample self count rng Every step start -> - if step <= 0 then Error.throw (Illegal_Argument_Error "Step within Every must be positive.") else + if step <= 0 then Error.throw (Illegal_Argument_Error_Data "Step within Every must be positive.") else if start >= self.length then [] else - range = Range start self.length step + range = Range_Data start self.length step self.take (By_Index range) ## Creates a new vector with only the specified range of elements from the @@ -711,15 +711,15 @@ type Vector If a `Range`, the selection is specified by two indices, from and to. drop : (Index_Sub_Range | Range) -> Vector Any drop self range=(First 1) = case range of - Range _ _ _ -> self.drop (By_Index range) + Range_Data _ _ _ -> self.drop (By_Index range) First count -> self.slice count self.length Last count -> self.slice 0 self.length-count While predicate -> end = 0.up_to self.length . find i-> (predicate (self.at i)).not if end.is_nothing then [] else self.slice end self.length - By_Index one_or_many_descriptors -> Panic.recover [Index_Out_Of_Bounds_Error, Illegal_Argument_Error] <| + By_Index one_or_many_descriptors -> Panic.recover [Index_Out_Of_Bounds_Error_Data, Illegal_Argument_Error_Data] <| indices = case one_or_many_descriptors of - Vector _ -> one_or_many_descriptors + Vector_Data _ -> one_or_many_descriptors _ -> [one_or_many_descriptors] trimmed = resolve_ranges indices self.length normalized = normalize_ranges trimmed @@ -730,9 +730,9 @@ type Vector indices_to_drop = Random.random_indices self.length count rng self.drop (By_Index indices_to_drop) Every step start -> - if step <= 0 then Error.throw (Illegal_Argument_Error "Step within Every must be positive.") else + if step <= 0 then Error.throw (Illegal_Argument_Error_Data "Step within Every must be positive.") else if start >= self.length then self else - range = Range start self.length step + range = Range_Data start self.length step self.drop (By_Index range) ## Performs a pair-wise operation passed in `function` on consecutive @@ -1017,7 +1017,7 @@ type Builder and get wrong error propagation. Instead we may want to have a `Ref` inside of the Builder. Any error detected during `append` could set that `Ref` and then `to_vector` could propagate that error. - type Builder_Data java_builder + Builder_Data java_builder ## Creates a new builder. @@ -1192,15 +1192,15 @@ resolve_ranges ranges length = trim descriptor = case descriptor of Integer -> actual_index = if descriptor < 0 then length + descriptor else descriptor - if (actual_index < 0) || (actual_index >= length) then Panic.throw (Index_Out_Of_Bounds_Error descriptor length) else + if (actual_index < 0) || (actual_index >= length) then Panic.throw (Index_Out_Of_Bounds_Error_Data descriptor length) else actual_index - Range start end step -> - if step <= 0 then Panic.throw (Illegal_Argument_Error "Range step must be positive.") else - if (start < 0) || (end < 0) then Panic.throw (Illegal_Argument_Error "Range start and end must not be negative.") else - if start >= length then Panic.throw (Index_Out_Of_Bounds_Error start length) else + Range_Data start end step -> + if step <= 0 then Panic.throw (Illegal_Argument_Error_Data "Range step must be positive.") else + if (start < 0) || (end < 0) then Panic.throw (Illegal_Argument_Error_Data "Range start and end must not be negative.") else + if start >= length then Panic.throw (Index_Out_Of_Bounds_Error_Data start length) else actual_end = Math.min end length - if actual_end < start then Range start start step else - Range start actual_end step + if actual_end < start then Range_Data start start step else + Range_Data start actual_end step ranges.map trim ## PRIVATE @@ -1214,7 +1214,7 @@ slice_ranges vector ranges = if ranges.length != 1 then slice_many_ranges vector ranges else case ranges.first of Integer -> [vector.unsafe_at ranges.first] - Range start end step -> case step == 1 of + Range_Data start end step -> case step == 1 of True -> vector.slice start end False -> slice_many_ranges vector ranges @@ -1223,12 +1223,12 @@ slice_ranges vector ranges = slice_many_ranges vector ranges = new_length = ranges.fold 0 acc-> descriptor-> case descriptor of Integer -> acc+1 - Range _ _ _ -> acc+descriptor.length + Range_Data _ _ _ -> acc+descriptor.length builder = new_builder new_length ranges.each descriptor-> case descriptor of Integer -> builder.append (vector.unsafe_at descriptor) - Range start end step -> case step == 1 of + Range_Data start end step -> case step == 1 of True -> builder.append_vector_range vector start end False -> @@ -1243,11 +1243,11 @@ slice_many_ranges vector ranges = single-element ranges. normalize_ranges descriptors = normalize descriptor = case descriptor of - Integer -> [Range descriptor descriptor+1] - Range _ _ _ -> + Integer -> [Range_Data descriptor descriptor+1] + Range_Data _ _ _ -> if descriptor.step == 1 then [descriptor] else descriptor.to_vector.map ix-> - Range ix ix+1 + Range_Data ix ix+1 descriptors.flat_map normalize ## PRIVATE @@ -1266,9 +1266,9 @@ normalize_ranges descriptors = invert_range_selection : Vector Range -> Integer -> Boolean -> Vector Range invert_range_selection ranges length needs_sorting = sorted = if needs_sorting then sort_and_merge_ranges ranges else ranges - ranges_with_sentinels = [Range 0 0] + sorted + [Range length length] + ranges_with_sentinels = [Range_Data 0 0] + sorted + [Range_Data length length] ranges_with_sentinels.zip ranges_with_sentinels.tail prev-> next-> - Range prev.end next.start + Range_Data prev.end next.start ## PRIVATE Returns a new sorted list of ranges where intersecting ranges have been @@ -1283,7 +1283,7 @@ sort_and_merge_ranges ranges = sorted.tail.each range-> current = current_ref.get case range.start <= current.end of - True -> current_ref.put (Range current.start (Math.max current.end range.end)) + True -> current_ref.put (Range_Data current.start (Math.max current.end range.end)) False -> builder.append current current_ref.put range diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot/Proxy_Polyglot_Array.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot/Proxy_Polyglot_Array.enso index 6f83d7439806..882dfc6c4dd0 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot/Proxy_Polyglot_Array.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Polyglot/Proxy_Polyglot_Array.enso @@ -5,7 +5,7 @@ from Standard.Base import Polyglot, Array Wrapper for Polyglot Arrays type Proxy_Polyglot_Array - type Proxy_Polyglot_Array arr + Proxy_Polyglot_Array_Data arr ## Returns the number of elements stored in this Polyglot Array. diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeMethodNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeMethodNode.java index b5132b402d6d..1b97a7ec03dd 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeMethodNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeMethodNode.java @@ -238,8 +238,8 @@ Stateful doConvertText( @Specialization( guards = { - "!methods.hasType(self)", - "!methods.hasSpecialDispatch(self)", + "!types.hasType(self)", + "!types.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == CONVERT_TO_DATE" }) Stateful doConvertDate( @@ -248,8 +248,8 @@ Stateful doConvertDate( UnresolvedSymbol symbol, Object self, Object[] arguments, + @CachedLibrary(limit="10") TypesLibrary types, @CachedLibrary(limit = "10") InteropLibrary interop, - @CachedLibrary(limit = "10") TypesLibrary methods, @Cached MethodResolverNode methodResolverNode) { var ctx = Context.get(this); try { @@ -266,8 +266,8 @@ Stateful doConvertDate( @Specialization( guards = { - "!methods.hasFunctionalDispatch(self)", - "!methods.hasSpecialDispatch(self)", + "!types.hasType(self)", + "!types.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == CONVERT_TO_DATE_TIME" }) Stateful doConvertDateTime( @@ -276,27 +276,29 @@ Stateful doConvertDateTime( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, - @CachedLibrary(limit = "1") MethodDispatchLibrary dateDispatch, - @CachedLibrary(limit = "10") InteropLibrary interop) { + @CachedLibrary(limit="10") TypesLibrary types, + @CachedLibrary(limit = "10") InteropLibrary interop, + @Cached MethodResolverNode methodResolverNode) { var ctx = Context.get(this); try { var hostLocalDate = interop.asDate(self); var hostLocalTime = interop.asTime(self); var hostZonedDateTime = hostLocalDate.atTime(hostLocalTime).atZone(ZoneId.systemDefault()); var dateTime = new EnsoDateTime(hostZonedDateTime); - Function function = dateDispatch.getFunctionalDispatch(dateTime, symbol); + Function function = + methodResolverNode.expectNonNull(dateTime, ctx.getBuiltins().dateTime(), symbol); + arguments[0] = dateTime; return invokeFunctionNode.execute(function, frame, state, arguments); - } catch (MethodDispatchLibrary.NoSuchMethodException | UnsupportedMessageException e) { + } catch (UnsupportedMessageException e) { throw new PanicException(ctx.getBuiltins().error().makeNoSuchMethodError(self, symbol), this); } } @Specialization( guards = { - "!methods.hasFunctionalDispatch(self)", - "!methods.hasSpecialDispatch(self)", + "!types.hasType(self)", + "!types.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == CONVERT_TO_ZONED_DATE_TIME" }) Stateful doConvertZonedDateTime( @@ -305,27 +307,28 @@ Stateful doConvertZonedDateTime( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, - @CachedLibrary(limit = "1") MethodDispatchLibrary dateDispatch, - @CachedLibrary(limit = "10") InteropLibrary interop) { + @CachedLibrary(limit="10") TypesLibrary types, + @CachedLibrary(limit = "10") InteropLibrary interop, + @Cached MethodResolverNode methodResolverNode) { var ctx = Context.get(this); try { var hostLocalDate = interop.asDate(self); var hostLocalTime = interop.asTime(self); var hostZone = interop.asTimeZone(self); var dateTime = new EnsoDateTime(hostLocalDate.atTime(hostLocalTime).atZone(hostZone)); - Function function = dateDispatch.getFunctionalDispatch(dateTime, symbol); + Function function = + methodResolverNode.expectNonNull(dateTime, ctx.getBuiltins().dateTime(), symbol); arguments[0] = dateTime; return invokeFunctionNode.execute(function, frame, state, arguments); - } catch (MethodDispatchLibrary.NoSuchMethodException | UnsupportedMessageException e) { + } catch (UnsupportedMessageException e) { throw new PanicException(ctx.getBuiltins().error().makeNoSuchMethodError(self, symbol), this); } } @Specialization( guards = { - "!methods.hasFunctionalDispatch(self)", - "!methods.hasSpecialDispatch(self)", + "!types.hasType(self)", + "!types.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == CONVERT_TO_TIME_ZONE" }) Stateful doConvertZone( @@ -334,25 +337,26 @@ Stateful doConvertZone( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, - @CachedLibrary(limit = "1") MethodDispatchLibrary dateDispatch, - @CachedLibrary(limit = "10") InteropLibrary interop) { + @CachedLibrary(limit="10") TypesLibrary types, + @CachedLibrary(limit = "10") InteropLibrary interop, + @Cached MethodResolverNode methodResolverNode) { var ctx = Context.get(this); try { var hostZone = interop.asTimeZone(self); var dateTime = new EnsoTimeZone(hostZone); - Function function = dateDispatch.getFunctionalDispatch(dateTime, symbol); + Function function = + methodResolverNode.expectNonNull(dateTime, ctx.getBuiltins().timeZone(), symbol); arguments[0] = dateTime; return invokeFunctionNode.execute(function, frame, state, arguments); - } catch (MethodDispatchLibrary.NoSuchMethodException | UnsupportedMessageException e) { + } catch (UnsupportedMessageException e) { throw new PanicException(ctx.getBuiltins().error().makeNoSuchMethodError(self, symbol), this); } } @Specialization( guards = { - "!methods.hasFunctionalDispatch(self)", - "!methods.hasSpecialDispatch(self)", + "!types.hasType(self)", + "!types.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == CONVERT_TO_TIME_OF_DAY" }) Stateful doConvertTimeOfDay( @@ -361,17 +365,18 @@ Stateful doConvertTimeOfDay( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit = "10") MethodDispatchLibrary methods, - @CachedLibrary(limit = "1") MethodDispatchLibrary dateDispatch, - @CachedLibrary(limit = "10") InteropLibrary interop) { + @CachedLibrary(limit="10") TypesLibrary types, + @CachedLibrary(limit = "10") InteropLibrary interop, + @Cached MethodResolverNode methodResolverNode) { var ctx = Context.get(this); try { var hostLocalTime = interop.asTime(self); var dateTime = new EnsoTimeOfDay(hostLocalTime); - Function function = dateDispatch.getFunctionalDispatch(dateTime, symbol); + Function function = + methodResolverNode.expectNonNull(dateTime, ctx.getBuiltins().timeOfDay(), symbol); arguments[0] = dateTime; return invokeFunctionNode.execute(function, frame, state, arguments); - } catch (MethodDispatchLibrary.NoSuchMethodException | UnsupportedMessageException e) { + } catch (UnsupportedMessageException e) { throw new PanicException(ctx.getBuiltins().error().makeNoSuchMethodError(self, symbol), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/TypeToDisplayTextNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/TypeToDisplayTextNode.java index ffd6377cf2eb..ce057c2fb148 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/TypeToDisplayTextNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/text/util/TypeToDisplayTextNode.java @@ -49,7 +49,7 @@ String doDisplay( } else if (TypesGen.isAtom(value)) { return TypesGen.asAtom(value).getConstructor().getName(); } else if (TypesGen.isAtomConstructor(value)) { - return TypesGen.asAtomConstructor(value).getName(); + return TypesGen.asAtomConstructor(value).getName() + " (Constructor)"; } else if (TypesGen.isType(value)) { return TypesGen.asType(value).getName(); } else if (TypesGen.isDataflowError(value)) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/foreign/CoerceNothing.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/foreign/CoerceNothing.java index 2ac37422481e..b8c72c3ebb84 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/foreign/CoerceNothing.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/foreign/CoerceNothing.java @@ -23,7 +23,7 @@ public static CoerceNothing build() { @Specialization(guards = "interop.isNull(value)") public Object doNothing(Object value, @CachedLibrary(limit = "1") InteropLibrary interop) { - return Context.get(this).getBuiltins().nothing().newInstance(); + return Context.get(this).getBuiltins().nothing(); } @Fallback 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 52c0692fe756..ed65432dbad0 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 @@ -315,9 +315,9 @@ private Map>> readBuiltinMethodsMetad * @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(Type type, String methodName, Language language) { + public Optional getBuiltinFunction(String type, String methodName, Language language) { // TODO: move away from String mapping once Builtins is gone - Map> atomNodes = builtinMethodNodes.get(type.getName()); + Map> atomNodes = builtinMethodNodes.get(type); if (atomNodes == null) return Optional.empty(); Class clazz = atomNodes.get(methodName); if (clazz == null) return Optional.empty(); @@ -330,6 +330,10 @@ public Optional getBuiltinFunction(Type type, String methodName, Langu } } + public Optional getBuiltinFunction(Type type, String methodName, Language language) { + return getBuiltinFunction(type.getName(), methodName, language); + } + public T getBuiltinType(Class clazz) { @SuppressWarnings("unchecked") T t = (T) builtins.get(clazz); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDateTime.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDateTime.java index f14e53027b7c..e82877f97a95 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDateTime.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoDateTime.java @@ -1,8 +1,6 @@ package org.enso.interpreter.runtime.data; import com.oracle.truffle.api.CompilerDirectives; -import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.library.CachedLibrary; @@ -11,10 +9,8 @@ import org.enso.interpreter.dsl.Builtin; import org.enso.interpreter.node.expression.builtin.error.PolyglotError; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.text.Text; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import java.time.*; import java.time.format.DateTimeFormatter; @@ -23,7 +19,7 @@ import java.time.temporal.TemporalAccessor; @ExportLibrary(InteropLibrary.class) -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) @Builtin(pkg = "date", name = "DateTime", stdlibName = "Standard.Base.Data.Time.Date_Time") public final class EnsoDateTime implements TruffleObject { private final ZonedDateTime dateTime; @@ -56,10 +52,7 @@ public static EnsoDateTime now() { name = "parse_builtin", description = "Constructs a new DateTime from text with optional pattern") @Builtin.Specialize - @Builtin.WrapException( - from = DateTimeParseException.class, - to = PolyglotError.class, - propagate = true) + @Builtin.WrapException(from = DateTimeParseException.class, to = PolyglotError.class) public static EnsoDateTime parse(String text) { TemporalAccessor time = TIME_FORMAT.parseBest(text, ZonedDateTime::from, LocalDateTime::from); if (time instanceof ZonedDateTime) { @@ -73,7 +66,7 @@ public static EnsoDateTime parse(String text) { @Builtin.Method( name = "new_builtin", description = "Constructs a new Date from a year, month, and day") - @Builtin.WrapException(from = DateTimeException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = DateTimeException.class, to = PolyglotError.class) public static EnsoDateTime create( long year, long month, @@ -223,40 +216,13 @@ ZoneId asTimeZone() { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - @CompilerDirectives.TruffleBoundary - static Function doResolve(InteropLibrary my, UnresolvedSymbol symbol) { - Context context = Context.get(my); - return symbol.resolveFor(context.getBuiltins().dateTime(), context.getBuiltins().any()); - } - - @Specialization( - guards = {"cachedSymbol == symbol", "function != null"}, - limit = "3") - static Function resolveCached( - EnsoDateTime self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @CachedLibrary("self") InteropLibrary mySelf, - @Cached("doResolve(mySelf, cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve( - EnsoDateTime self, UnresolvedSymbol symbol, @CachedLibrary("self") InteropLibrary mySelf) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(mySelf, symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().dateTime(); } @ExportMessage diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeOfDay.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeOfDay.java index ba6e03e6933c..58a600394b0b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeOfDay.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeOfDay.java @@ -1,8 +1,5 @@ package org.enso.interpreter.runtime.data; -import com.oracle.truffle.api.CompilerDirectives; -import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.interop.UnsupportedMessageException; @@ -12,10 +9,8 @@ import org.enso.interpreter.dsl.Builtin; import org.enso.interpreter.node.expression.builtin.error.PolyglotError; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.text.Text; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import java.time.DateTimeException; import java.time.LocalDate; @@ -24,7 +19,7 @@ import java.time.format.DateTimeParseException; @ExportLibrary(InteropLibrary.class) -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) @Builtin(pkg = "date", name = "TimeOfDay", stdlibName = "Standard.Base.Data.Time.Time_Of_Day") public class EnsoTimeOfDay implements TruffleObject { private LocalTime localTime; @@ -39,14 +34,13 @@ public EnsoTimeOfDay(LocalTime localTime) { @Builtin.Specialize @Builtin.WrapException( from = DateTimeParseException.class, - to = PolyglotError.class, - propagate = true) + to = PolyglotError.class) public static EnsoTimeOfDay parse(String text) { return new EnsoTimeOfDay(LocalTime.parse(text)); } @Builtin.Method(name = "new_builtin", description = "Constructs a new Time_OF_Day from an hour") - @Builtin.WrapException(from = DateTimeException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = DateTimeException.class, to = PolyglotError.class) public static EnsoTimeOfDay create(long hour, long minute, long second, long nanosecond) { return new EnsoTimeOfDay( LocalTime.of( @@ -125,39 +119,12 @@ LocalDate asDate() throws UnsupportedMessageException { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - @CompilerDirectives.TruffleBoundary - static Function doResolve(InteropLibrary my, UnresolvedSymbol symbol) { - Context context = Context.get(my); - return symbol.resolveFor(context.getBuiltins().timeOfDay(), context.getBuiltins().any()); - } - - @Specialization( - guards = {"cachedSymbol == symbol", "function != null"}, - limit = "3") - static Function resolveCached( - EnsoTimeOfDay self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @CachedLibrary("self") InteropLibrary mySelf, - @Cached("doResolve(mySelf, cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve( - EnsoTimeOfDay self, UnresolvedSymbol symbol, @CachedLibrary("self") InteropLibrary mySelf) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(mySelf, symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().timeOfDay(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeZone.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeZone.java index fcd3e0fc90d9..06ac036d6f15 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeZone.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeZone.java @@ -1,8 +1,5 @@ package org.enso.interpreter.runtime.data; -import com.oracle.truffle.api.CompilerDirectives; -import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.library.CachedLibrary; @@ -11,10 +8,8 @@ import org.enso.interpreter.dsl.Builtin; import org.enso.interpreter.node.expression.builtin.error.PolyglotError; import org.enso.interpreter.runtime.Context; -import org.enso.interpreter.runtime.callable.UnresolvedSymbol; -import org.enso.interpreter.runtime.callable.function.Function; import org.enso.interpreter.runtime.data.text.Text; -import org.enso.interpreter.runtime.library.dispatch.MethodDispatchLibrary; +import org.enso.interpreter.runtime.library.dispatch.TypesLibrary; import java.time.DateTimeException; import java.time.ZoneId; @@ -22,7 +17,7 @@ import java.time.zone.ZoneRulesException; @ExportLibrary(InteropLibrary.class) -@ExportLibrary(MethodDispatchLibrary.class) +@ExportLibrary(TypesLibrary.class) @Builtin(pkg = "date", name = "TimeZone", stdlibName = "Standard.Base.Data.Time.Time_Zone") public final class EnsoTimeZone implements TruffleObject { private final ZoneId zone; @@ -38,10 +33,7 @@ public Text zoneId() { @Builtin.Method(name = "parse_builtin", description = "Parse the ID producing a Time_Zone.") @Builtin.Specialize - @Builtin.WrapException( - from = ZoneRulesException.class, - to = PolyglotError.class, - propagate = true) + @Builtin.WrapException(from = ZoneRulesException.class, to = PolyglotError.class) public static EnsoTimeZone parse(String text) { return new EnsoTimeZone(ZoneId.of(text)); } @@ -50,7 +42,7 @@ public static EnsoTimeZone parse(String text) { name = "new_builtin", description = "Obtains an instance of `Time_Zone` using an offset in hours, minutes and seconds from the UTC zone.") - @Builtin.WrapException(from = DateTimeException.class, to = PolyglotError.class, propagate = true) + @Builtin.WrapException(from = DateTimeException.class, to = PolyglotError.class) public static EnsoTimeZone create(long hours, long minutes, long seconds) { return new EnsoTimeZone( ZoneOffset.ofHoursMinutesSeconds( @@ -73,39 +65,12 @@ ZoneId asTimeZone() { } @ExportMessage - boolean hasFunctionalDispatch() { + boolean hasType() { return true; } @ExportMessage - static class GetFunctionalDispatch { - @CompilerDirectives.TruffleBoundary - static Function doResolve(InteropLibrary my, UnresolvedSymbol symbol) { - Context context = Context.get(my); - return symbol.resolveFor(context.getBuiltins().timeZone(), context.getBuiltins().any()); - } - - @Specialization( - guards = {"cachedSymbol == symbol", "function != null"}, - limit = "3") - static Function resolveCached( - EnsoTimeZone self, - UnresolvedSymbol symbol, - @Cached("symbol") UnresolvedSymbol cachedSymbol, - @CachedLibrary("self") InteropLibrary mySelf, - @Cached("doResolve(mySelf, cachedSymbol)") Function function) { - return function; - } - - @Specialization(replaces = "resolveCached") - static Function resolve( - EnsoTimeZone self, UnresolvedSymbol symbol, @CachedLibrary("self") InteropLibrary mySelf) - throws MethodDispatchLibrary.NoSuchMethodException { - Function function = doResolve(mySelf, symbol); - if (function == null) { - throw new MethodDispatchLibrary.NoSuchMethodException(); - } - return function; - } + Type getType(@CachedLibrary("this") TypesLibrary thisLib) { + return Context.get(thisLib).getBuiltins().timeZone(); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java b/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java index 0e8f0cf92b16..4f1cd520d9e4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java @@ -79,12 +79,16 @@ public ExecutionService( this.connectedLockManager = connectedLockManager; } - /** @return the language context. */ + /** + * @return the language context. + */ public Context getContext() { return context; } - /** @return the execution service logger. */ + /** + * @return the execution service logger. + */ public TruffleLogger getLogger() { return logger; } @@ -96,14 +100,12 @@ public FunctionCallInstrumentationNode.FunctionCall prepareFunctionCall( Type type = scope .getType(typeName) - .orElseThrow( - () -> new TypeNotFoundException(module.getName().toString(), typeName)); + .orElseThrow(() -> new TypeNotFoundException(module.getName().toString(), typeName)); Function function = scope.lookupMethodDefinition(type, methodName); if (function == null) { throw new MethodNotFoundException(module.getName().toString(), type, methodName); } - Object[] arguments = - MAIN_METHOD.equals(methodName) ? new Object[] {} : new Object[] {atomConstructor}; + Object[] arguments = MAIN_METHOD.equals(methodName) ? new Object[] {} : new Object[] {type}; return new FunctionCallInstrumentationNode.FunctionCall(function, EmptyMap.create(), arguments); } 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 66624df3ea42..ef99377476a9 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 @@ -247,7 +247,7 @@ class IrToTruffle( ) } } - val tp = moduleScope.getType(tpDef.name.name).get() + val tp = moduleScope.getTypes.get(tpDef.name.name) tp.generateGetters(atomConstructors.asJava) } @@ -492,10 +492,7 @@ class IrToTruffle( definitionModule .unsafeAsModule() .getScope - .getType(tp.name) - .orElseGet(() => - throw new CompilerError(s"Type ${tp.name} not found in codegen.") - ) + .getTypes.get(tp.name) case BindingsMap.ResolvedModule(module) => module.unsafeAsModule().getScope.getAssociatedType case BindingsMap.ResolvedConstructor(_, _) => @@ -613,7 +610,7 @@ class IrToTruffle( resolution match { case BindingsMap.ResolvedType(module, tp) => val runtimeTp = - module.unsafeAsModule().getScope.getType(tp.name).get() + module.unsafeAsModule().getScope.getTypes.get(tp.name) val fun = mkTypeGetter(runtimeTp) moduleScope.registerMethod( moduleScope.getAssociatedType, diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala index cfd42e3b9cb2..46f1740ebb71 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/GlobalNames.scala @@ -156,21 +156,6 @@ case object GlobalNames extends IRPass { fun.passData.remove(ExpressionAnnotations) app } - case Right(res @ BindingsMap.ResolvedType(_, tp)) => - val warned = if (tp.members.nonEmpty) { -// lit.addDiagnostic( -// IR.Warning.NonUnitTypeUsedOnValueLevel( -// lit, -// if (isInsideApplication) { -// "a constructor position" -// } else { "an argument position" } -// ) -// ) - lit - } else { - lit - } - warned.updateMetadata(this -->> BindingsMap.Resolution(res)) case Right(value) => lit.updateMetadata(this -->> BindingsMap.Resolution(value)) } @@ -244,17 +229,6 @@ case object GlobalNames extends IRPass { } yield (thisArgPos, funAsVar, cons) val newApp = appData.flatMap { - case (_, _, BindingsMap.ResolvedType(_, tp)) => - if (tp.members.nonEmpty) { - Some( - app - .copy(function = processedFun, arguments = processedArgs) -// .addDiagnostic( -// IR.Warning -// .NonUnitTypeUsedOnValueLevel(funAsVar, "a qualified call") -// ) - ) - } else { None } case ( thisArgPos, funAsVar, diff --git a/test/Tests/src/Data/Array_Spec.enso b/test/Tests/src/Data/Array_Spec.enso index fbd4cc41aa7b..7808f2240a45 100644 --- a/test/Tests/src/Data/Array_Spec.enso +++ b/test/Tests/src/Data/Array_Spec.enso @@ -49,7 +49,7 @@ spec = arr = make_enso_array (Vector.fill 1000 0) text = arr.to_default_visualization_data json = Json.parse text - as_vec = json.into (Vector.Vector Number) + as_vec = json.into (Vector.Vector_Data Number) as_vec.should_equal <| Vector.fill 100 0 Test.group "Polyglot Arrays" <| @@ -59,7 +59,7 @@ spec = arr = make_java_array (Vector.fill 1000 0) text = arr.to_default_visualization_data json = Json.parse text - as_vec = json.into (Vector.Vector Number) + as_vec = json.into (Vector.Vector_Data Number) as_vec.should_equal <| Vector.fill 100 0 main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Range_Spec.enso b/test/Tests/src/Data/Range_Spec.enso index 46dc48db2dbe..81ed2f26b375 100644 --- a/test/Tests/src/Data/Range_Spec.enso +++ b/test/Tests/src/Data/Range_Spec.enso @@ -80,13 +80,13 @@ spec = Test.group "Range" <| Test.specify "should allow iteration with index" <| vec_mut = Vector.new_builder 5.up_to 8 . each_with_index ix-> elem-> - vec_mut.append (Pair ix elem) - vec_mut.to_vector . should_equal [Pair 0 5, Pair 1 6, Pair 2 7] + vec_mut.append (Pair_Data ix elem) + vec_mut.to_vector . should_equal [Pair_Data 0 5, Pair_Data 1 6, Pair_Data 2 7] vec_mut_2 = Vector.new_builder 5.up_to 10 . with_step 2 . each_with_index ix-> elem-> - vec_mut_2.append (Pair ix elem) - vec_mut_2.to_vector . should_equal [Pair 0 5, Pair 1 7, Pair 2 9] + vec_mut_2.append (Pair_Data ix elem) + vec_mut_2.to_vector . should_equal [Pair_Data 0 5, Pair_Data 1 7, Pair_Data 2 9] Test.specify "should be able to be folded" <| 1.up_to 6 . fold 0 (+) . should_equal 15 Test.specify "should check all" <| diff --git a/test/Tests/src/Data/Text/Encoding_Spec.enso b/test/Tests/src/Data/Text/Encoding_Spec.enso index 0285586be5fa..0ef9b33704f8 100644 --- a/test/Tests/src/Data/Text/Encoding_Spec.enso +++ b/test/Tests/src/Data/Text/Encoding_Spec.enso @@ -1,6 +1,6 @@ from Standard.Base import all -from Standard.Base.Data.Text.Encoding as Encoding_Module import all_character_sets, all_encodings +from Standard.Base.Data.Text.Encoding import all_character_sets, all_encodings, Encoding, Encoding_Data import Standard.Test import Standard.Test.Problems diff --git a/test/Tests/src/Data/Text/Text_Sub_Range_Spec.enso b/test/Tests/src/Data/Text/Text_Sub_Range_Spec.enso index c608538ae785..6b90dd8a4ec6 100644 --- a/test/Tests/src/Data/Text/Text_Sub_Range_Spec.enso +++ b/test/Tests/src/Data/Text/Text_Sub_Range_Spec.enso @@ -1,6 +1,6 @@ from Standard.Base import all -from Standard.Base.Data.Text.Text_Sub_Range_Data import all +from Standard.Base.Data.Text.Text_Sub_Range import all import Standard.Test @@ -23,18 +23,18 @@ spec = Test.group "Text_Sub_Range_Data" <| Test.specify "should correctly split a text into grapheme cluster ranges expressed in codepoint indices" <| character_ranges "" . should_equal [] - character_ranges "A" . should_equal [Range_Data_Data 0 1] - character_ranges "abc" . should_equal [Range_Data_Data 0 1, Range_Data_Data 1 2, Range_Data_Data 2 3] - character_ranges 'śs\u0301S' . should_equal [Range_Data_Data 0 1, Range_Data_Data 1 3, Range_Data_Data 3 4] + character_ranges "A" . should_equal [Range_Data 0 1] + character_ranges "abc" . should_equal [Range_Data 0 1, Range_Data 1 2, Range_Data 2 3] + character_ranges 'śs\u0301S' . should_equal [Range_Data 0 1, Range_Data 1 3, Range_Data 3 4] kshi = '\u0915\u094D\u0937\u093F' facepalm = '\u{1F926}\u{1F3FC}\u200D\u2642\uFE0F' accent_1 = '\u00E9' accent_2 = '\u0065\u{301}' - character_ranges kshi . should_equal [Range_Data_Data 0 4] - character_ranges facepalm . should_equal [Range_Data_Data 0 7] - character_ranges accent_1 . should_equal [Range_Data_Data 0 1] - character_ranges accent_2 . should_equal [Range_Data_Data 0 2] - character_ranges kshi+facepalm+accent_1+accent_2 . should_equal [Range_Data_Data 0 4, Range_Data_Data 4 11, Range_Data_Data 11 12, Range_Data_Data 12 14] + character_ranges kshi . should_equal [Range_Data 0 4] + character_ranges facepalm . should_equal [Range_Data 0 7] + character_ranges accent_1 . should_equal [Range_Data 0 1] + character_ranges accent_2 . should_equal [Range_Data 0 2] + character_ranges kshi+facepalm+accent_1+accent_2 . should_equal [Range_Data 0 4, Range_Data 4 11, Range_Data 11 12, Range_Data 12 14] main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Time/Date_Spec.enso b/test/Tests/src/Data/Time/Date_Spec.enso index eb064f39dd5c..446879a74c45 100644 --- a/test/Tests/src/Data/Time/Date_Spec.enso +++ b/test/Tests/src/Data/Time/Date_Spec.enso @@ -158,7 +158,7 @@ js_array_date year month=1 day=1 = js_set_zone arr.at(0) java_parse date_text pattern=Nothing = - Panic.catch Polyglot_Error handler=(err -> Error.throw (Time_Error_Data err.payload.cause.getMessage)) <| + Panic.catch Polyglot_Error_Data handler=(err -> Error.throw (Time_Error_Data err.payload.cause.getMessage)) <| if pattern.is_nothing then LocalDate.parse date_text else formatter = DateTimeFormatter.ofPattern pattern LocalDate.parse date_text formatter diff --git a/test/Tests/src/Data/Time/Date_Time_Spec.enso b/test/Tests/src/Data/Time/Date_Time_Spec.enso index 8f9de8fb3ba5..6b1acf937bbf 100644 --- a/test/Tests/src/Data/Time/Date_Time_Spec.enso +++ b/test/Tests/src/Data/Time/Date_Time_Spec.enso @@ -301,7 +301,7 @@ spec_with name create_new_datetime parse_datetime nanoseconds_loss_in_precision= Date_Part_Spec.spec name create_new_datetime js_datetime year month=1 day=1 hour=0 minute=0 second=0 nanosecond=0 zone=Time_Zone.system = - Panic.catch Any (js_datetime_with_zone year month day hour minute second nanosecond zone) (err -> Error.throw (Time_Error err.payload.cause)) + Panic.catch Any (js_datetime_with_zone year month day hour minute second nanosecond zone) (err -> Error.throw (Time_Error_Data err.payload.cause)) # This ensures that date returned by javascript has the right timezone specified by the zone parameter. # Javascript's toLocaleString will accept the timezone but it will just adapt the datetime while keeping the local timezone. @@ -324,7 +324,7 @@ js_parse text format=Nothing = js_datetime d.year d.month d.day d.hour d.minute d.second d.nanosecond d.zone js_array_datetime year month=1 day=1 hour=0 minute=0 second=0 nanosecond=0 zone=Time_Zone.system = - arr = Panic.catch Any (js_array_datetimeCreate year month day hour minute second nanosecond) (err -> Error.throw (Time_Error err.payload.cause)) + arr = Panic.catch Any (js_array_datetimeCreate year month day hour minute second nanosecond) (err -> Error.throw (Time_Error_Data err.payload.cause)) js_set_zone arr.at(0) zone foreign js js_array_datetimeCreate year month day hour minute second nanosecond = """ @@ -334,14 +334,14 @@ foreign js js_array_datetimeCreate year month day hour minute second nanosecond return [ new Date(year, month - 1, day, hour, minute, second, nanosecond / 1000000) ]; java_datetime year month=1 day=1 hour=0 minute=0 second=0 nanosecond=0 zone=Time_Zone.system = - Panic.catch Any (ZonedDateTime.of year month day hour minute second nanosecond zone) (err -> Error.throw (Time_Error <| err.payload.to_display_text.drop (Text_Sub_Range.First 16))) + Panic.catch Any (ZonedDateTime.of year month day hour minute second nanosecond zone) (err -> Error.throw (Time_Error_Data <| err.payload.to_display_text.drop (Text_Sub_Range.First 16))) maybe_parse_java_zoned text pattern=Nothing = if pattern == Nothing then ZonedDateTime.parse text else ZonedDateTime.parse text pattern parse_java_local original_error text pattern=Nothing = - Panic.catch Polyglot_Error handler=(_ -> Error.throw (Time_Error original_error.payload.cause.getMessage)) <| + Panic.catch Polyglot_Error_Data handler=(_ -> Error.throw (Time_Error_Data original_error.payload.cause.getMessage)) <| if pattern.is_nothing then LocalDateTime.parse text else formatter = DateTimeFormatter.ofPattern pattern LocalDateTime.parse text (formatter.withLocale Locale.default.java_locale) @@ -349,8 +349,8 @@ parse_java_local original_error text pattern=Nothing = java_parse date_text_raw pattern=Nothing = utc_replaced = date_text_raw.replace "[UTC]" "Z" date_text = if utc_replaced.ends_with "ZZ" then date_text_raw else utc_replaced - if pattern == Nothing then Panic.catch Polyglot_Error (maybe_parse_java_zoned date_text) (err -> parse_java_local err date_text pattern) else + if pattern == Nothing then Panic.catch Polyglot_Error_Data (maybe_parse_java_zoned date_text) (err -> parse_java_local err date_text pattern) else formatter = DateTimeFormatter.ofPattern(pattern) - Panic.catch Polyglot_Error (maybe_parse_java_zoned date_text formatter) (err -> parse_java_local err date_text pattern) + Panic.catch Polyglot_Error_Data (maybe_parse_java_zoned date_text formatter) (err -> parse_java_local err date_text pattern) main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Time/Time_Of_Day_Spec.enso b/test/Tests/src/Data/Time/Time_Of_Day_Spec.enso index 7fa1105c044a..369b8e10a610 100644 --- a/test/Tests/src/Data/Time/Time_Of_Day_Spec.enso +++ b/test/Tests/src/Data/Time/Time_Of_Day_Spec.enso @@ -1,6 +1,6 @@ from Standard.Base import all import Standard.Base.Data.Time.Duration -from Standard.Base.Error.Common import Time_Error +from Standard.Base.Error.Common import Time_Error_Data import Standard.Test @@ -120,10 +120,10 @@ enso_time hour minute=0 second=0 nanoOfSecond=0 = Time_Of_Day.new hour minute second nanoOfSecond java_time hour minute=0 second=0 nanoOfSecond=0 = - Panic.catch Any (LocalTime.of hour minute second nanoOfSecond) (err -> Error.throw (Time_Error <| err.payload.to_display_text.drop (Text_Sub_Range.First 16))) + Panic.catch Any (LocalTime.of hour minute second nanoOfSecond) (err -> Error.throw (Time_Error_Data <| err.payload.to_display_text.drop (Text_Sub_Range.First 16))) java_parse time_text pattern=Nothing = - Panic.catch Polyglot_Error handler=(err -> Error.throw (Time_Error err.payload.cause.getMessage)) <| + Panic.catch Polyglot_Error_Data handler=(err -> Error.throw (Time_Error_Data err.payload.cause.getMessage)) <| if pattern.is_nothing then LocalTime.parse time_text else formatter = DateTimeFormatter.ofPattern pattern LocalTime.parse time_text (formatter.withLocale Locale.default.java_locale) diff --git a/test/Tests/src/Data/Time/Time_Zone_Spec.enso b/test/Tests/src/Data/Time/Time_Zone_Spec.enso index 770e5fcfdc1d..ba4670501036 100644 --- a/test/Tests/src/Data/Time/Time_Zone_Spec.enso +++ b/test/Tests/src/Data/Time/Time_Zone_Spec.enso @@ -32,7 +32,7 @@ spec = Json.from_pairs [["type", "Time_Zone"], ["id", "UTC"]] Test.specify "should throw error when parsing invalid zone id" <| case Time_Zone.parse "foo" . catch of - Time_Error msg -> + Time_Error_Data msg -> msg . should_equal "Unknown time-zone ID: foo" result -> Test.fail ("Unexpected result: " + result.to_text) diff --git a/test/Tests/src/Data/Vector/Slicing_Helpers_Spec.enso b/test/Tests/src/Data/Vector/Slicing_Helpers_Spec.enso index bc61694b5d31..0860ec73eac5 100644 --- a/test/Tests/src/Data/Vector/Slicing_Helpers_Spec.enso +++ b/test/Tests/src/Data/Vector/Slicing_Helpers_Spec.enso @@ -6,15 +6,15 @@ spec = Test.group "Vector Slicing Helpers" <| Test.specify "should be able to sort correctly merge neighboring sequences" <| merge = Vector.sort_and_merge_ranges merge [] . should_equal [] - merge [Range 0 0] . should_equal [] - merge [Range 0 10] . should_equal [Range 0 10] - merge [Range 0 10, Range 2 4] . should_equal [Range 0 10] - merge [Range 0 5, Range 5 10] . should_equal [Range 0 10] - merge [Range 5 10, Range 0 0, Range 0 1, Range 1 5] . should_equal [Range 0 10] - merge [Range 0 1, Range 1 2] . should_equal [Range 0 2] - merge [Range 6 7, Range 7 8, Range 5 5, Range 0 1, Range 2 3] . should_equal [Range 0 1, Range 2 3, Range 6 8] - merge [Range 5 10, Range 3 6, Range 3 6, Range 3 5, Range 3 7, Range 0 1] . should_equal [Range 0 1, Range 3 10] - merge [Range 0 1, Range 0 1] . should_equal [Range 0 1] - merge [Range 0 1, Range 1 2] . should_equal [Range 0 2] + merge [Range_Data 0 0] . should_equal [] + merge [Range_Data 0 10] . should_equal [Range_Data 0 10] + merge [Range_Data 0 10, Range_Data 2 4] . should_equal [Range_Data 0 10] + merge [Range_Data 0 5, Range_Data 5 10] . should_equal [Range_Data 0 10] + merge [Range_Data 5 10, Range_Data 0 0, Range_Data 0 1, Range_Data 1 5] . should_equal [Range_Data 0 10] + merge [Range_Data 0 1, Range_Data 1 2] . should_equal [Range_Data 0 2] + merge [Range_Data 6 7, Range_Data 7 8, Range_Data 5 5, Range_Data 0 1, Range_Data 2 3] . should_equal [Range_Data 0 1, Range_Data 2 3, Range_Data 6 8] + merge [Range_Data 5 10, Range_Data 3 6, Range_Data 3 6, Range_Data 3 5, Range_Data 3 7, Range_Data 0 1] . should_equal [Range_Data 0 1, Range_Data 3 10] + merge [Range_Data 0 1, Range_Data 0 1] . should_equal [Range_Data 0 1] + merge [Range_Data 0 1, Range_Data 1 2] . should_equal [Range_Data 0 2] main = Test.Suite.run_main spec diff --git a/test/Tests/src/Data/Vector_Spec.enso b/test/Tests/src/Data/Vector_Spec.enso index 841c2092dd4e..2a2d93793261 100644 --- a/test/Tests/src/Data/Vector_Spec.enso +++ b/test/Tests/src/Data/Vector_Spec.enso @@ -218,23 +218,23 @@ spec = Test.group "Vectors" <| vec.take . should_equal [1] vec.drop . should_equal [2, 3, 4, 5, 6] - vec.take (Range 2 4) . should_equal [3, 4] - vec.take (Range 0 0) . should_equal [] - vec.take (Range 100 100) . should_fail_with Index_Out_Of_Bounds_Error - vec.take (Range 100 100) . catch . should_equal (Index_Out_Of_Bounds_Error 100 6) - vec.take (Range 0 100) . should_equal vec - [].take (Range 0 0) . should_fail_with Index_Out_Of_Bounds_Error - [].take (Range 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error 0 0) - vec.take (Range 100 99) . should_fail_with Index_Out_Of_Bounds_Error - - vec.drop (Range 2 4) . should_equal [1, 2, 5, 6] - vec.drop (Range 0 0) . should_equal vec - vec.drop (Range 100 100) . should_fail_with Index_Out_Of_Bounds_Error - vec.drop (Range 100 100) . catch . should_equal (Index_Out_Of_Bounds_Error 100 6) - vec.drop (Range 0 100) . should_equal [] - [].drop (Range 0 0) . should_fail_with Index_Out_Of_Bounds_Error - [].drop (Range 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error 0 0) - vec.drop (Range 100 99) . should_fail_with Index_Out_Of_Bounds_Error + vec.take (Range_Data 2 4) . should_equal [3, 4] + vec.take (Range_Data 0 0) . should_equal [] + vec.take (Range_Data 100 100) . should_fail_with Index_Out_Of_Bounds_Error_Data + vec.take (Range_Data 100 100) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 100 6) + vec.take (Range_Data 0 100) . should_equal vec + [].take (Range_Data 0 0) . should_fail_with Index_Out_Of_Bounds_Error_Data + [].take (Range_Data 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 0 0) + vec.take (Range_Data 100 99) . should_fail_with Index_Out_Of_Bounds_Error_Data + + vec.drop (Range_Data 2 4) . should_equal [1, 2, 5, 6] + vec.drop (Range_Data 0 0) . should_equal vec + vec.drop (Range_Data 100 100) . should_fail_with Index_Out_Of_Bounds_Error_Data + vec.drop (Range_Data 100 100) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 100 6) + vec.drop (Range_Data 0 100) . should_equal [] + [].drop (Range_Data 0 0) . should_fail_with Index_Out_Of_Bounds_Error_Data + [].drop (Range_Data 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 0 0) + vec.drop (Range_Data 100 99) . should_fail_with Index_Out_Of_Bounds_Error_Data vec.take (First 4) . should_equal first_four vec.take (First 0) . should_equal [] @@ -262,8 +262,8 @@ spec = Test.group "Vectors" <| vec.take (Every 2 first=100) . should_equal [] vec.take (Every 200) . should_equal [1] [].take (Every 2) . should_equal [] - vec.take (Every 0) . should_fail_with Illegal_Argument_Error - [].take (Every 0) . should_fail_with Illegal_Argument_Error + vec.take (Every 0) . should_fail_with Illegal_Argument_Error_Data + [].take (Every 0) . should_fail_with Illegal_Argument_Error_Data vec.drop (Every 3) . should_equal [2, 3, 5, 6] vec.drop (Every 3 first=1) . should_equal [1, 3, 4, 6] @@ -271,31 +271,31 @@ spec = Test.group "Vectors" <| vec.drop (Every 2 first=100) . should_equal vec vec.drop (Every 200) . should_equal [2, 3, 4, 5, 6] [].drop (Every 2) . should_equal [] - vec.drop (Every 0) . should_fail_with Illegal_Argument_Error - [].drop (Every 0) . should_fail_with Illegal_Argument_Error + vec.drop (Every 0) . should_fail_with Illegal_Argument_Error_Data + [].drop (Every 0) . should_fail_with Illegal_Argument_Error_Data vec.take (By_Index 0) . should_equal [1] - [].take (By_Index 0) . should_fail_with Index_Out_Of_Bounds_Error + [].take (By_Index 0) . should_fail_with Index_Out_Of_Bounds_Error_Data vec.take (By_Index []) . should_equal [] vec.take (By_Index [-1, -1]) . should_equal [6, 6] - vec.take (By_Index [0, 0, Range 3 100]) . should_equal [1, 1, 4, 5, 6] - vec.take (Range 0 100 2) . should_equal [1, 3, 5] - vec.take (By_Index [Range 0 100 2, Range 1 6 2]) . should_equal [1, 3, 5, 2, 4, 6] - vec.take (By_Index [Range 1 3, Range 2 5]) . should_equal [2, 3, 3, 4, 5] - vec.take (By_Index [Range 2 5, Range 1 3]) . should_equal [3, 4, 5, 2, 3] - vec.take (By_Index [0, 1, Range 100 200]) . should_fail_with Index_Out_Of_Bounds_Error - vec.take (By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error + vec.take (By_Index [0, 0, Range_Data 3 100]) . should_equal [1, 1, 4, 5, 6] + vec.take (Range_Data 0 100 2) . should_equal [1, 3, 5] + vec.take (By_Index [Range_Data 0 100 2, Range_Data 1 6 2]) . should_equal [1, 3, 5, 2, 4, 6] + vec.take (By_Index [Range_Data 1 3, Range_Data 2 5]) . should_equal [2, 3, 3, 4, 5] + vec.take (By_Index [Range_Data 2 5, Range_Data 1 3]) . should_equal [3, 4, 5, 2, 3] + vec.take (By_Index [0, 1, Range_Data 100 200]) . should_fail_with Index_Out_Of_Bounds_Error_Data + vec.take (By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error_Data vec.drop (By_Index 0) . should_equal [2, 3, 4, 5, 6] vec.drop (By_Index []) . should_equal vec vec.drop (By_Index [-1, -1]) . should_equal [1, 2, 3, 4, 5] - vec.drop (By_Index [0, 0, Range 3 100]) . should_equal [2, 3] - vec.drop (Range 0 100 2) . should_equal [2, 4, 6] - vec.drop (By_Index [Range 0 100 2, Range 1 6 2]) . should_equal [] - vec.drop (By_Index [Range 1 3, Range 2 5]) . should_equal [1, 6] - vec.drop (By_Index [Range 2 5, Range 1 3]) . should_equal [1, 6] - vec.drop (By_Index [0, 1, Range 100 200]) . should_fail_with Index_Out_Of_Bounds_Error - vec.drop (By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error + vec.drop (By_Index [0, 0, Range_Data 3 100]) . should_equal [2, 3] + vec.drop (Range_Data 0 100 2) . should_equal [2, 4, 6] + vec.drop (By_Index [Range_Data 0 100 2, Range_Data 1 6 2]) . should_equal [] + vec.drop (By_Index [Range_Data 1 3, Range_Data 2 5]) . should_equal [1, 6] + vec.drop (By_Index [Range_Data 2 5, Range_Data 1 3]) . should_equal [1, 6] + vec.drop (By_Index [0, 1, Range_Data 100 200]) . should_fail_with Index_Out_Of_Bounds_Error_Data + vec.drop (By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error_Data [1, 3, 5, 6, 8, 9, 10, 11, 13].take (While (x-> x%2 == 1)) . should_equal [1, 3, 5] [1, 2, 3] . take (While (_ > 10)) . should_equal [] diff --git a/test/Tests/src/Semantic/Conversion_Spec.enso b/test/Tests/src/Semantic/Conversion_Spec.enso index d84476c47d97..eb9bf30506c1 100644 --- a/test/Tests/src/Semantic/Conversion_Spec.enso +++ b/test/Tests/src/Semantic/Conversion_Spec.enso @@ -28,7 +28,7 @@ Foo.from (that:Function) = Foo_Data (that 5) Foo.from (that:Boolean) = Foo_Data that Foo.from (that:Array) = Foo_Data that.length -Not_Foo.from (that:Boolean) = Not_Foo_Data True +Not_Foo.from (_:Boolean) = Not_Foo_Data True Not_Foo.from (_:Any) = Not_Foo_Data "ANY!!!" Foo.from (_:Quaffle) = Foo_Data "quaffle" diff --git a/test/Tests/src/Semantic/Names_Spec.enso b/test/Tests/src/Semantic/Names_Spec.enso index 3fa0f51682a8..d36c40748e10 100644 --- a/test/Tests/src/Semantic/Names_Spec.enso +++ b/test/Tests/src/Semantic/Names_Spec.enso @@ -1,6 +1,6 @@ from Standard.Base import all -from project.Semantic.Names.Definitions import another_method, another_constant, method_with_local_vars, Bar +from project.Semantic.Names.Definitions import another_method, another_constant, method_with_local_vars, Bar_Data, Bar import project.Semantic.Names.Definitions import Standard.Test From aa73059ec2573f5079f5522a3d0ecccdf35a2d5b Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Fri, 26 Aug 2022 23:34:28 +0200 Subject: [PATCH 079/110] fix all of table again... --- .../lib/Standard/Database/0.0.0-dev/src/Data/Table.enso | 6 +++--- .../lib/Standard/Database/0.0.0-dev/src/Main.enso | 8 ++++---- .../lib/Standard/Table/0.0.0-dev/src/Data/Table.enso | 2 +- distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso | 3 ++- distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso | 2 +- test/Table_Tests/src/Common_Table_Spec.enso | 4 ++-- test/Table_Tests/src/Data_Formatter_Spec.enso | 2 +- test/Table_Tests/src/Delimited_Write_Spec.enso | 2 +- test/Table_Tests/src/Excel_Spec.enso | 3 ++- 9 files changed, 17 insertions(+), 15 deletions(-) diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso index 6e996723d42f..dbb8c696191d 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso @@ -16,9 +16,9 @@ import Standard.Table.Internal.Problem_Builder import Standard.Table.Data.Aggregate_Column import Standard.Table.Internal.Aggregate_Column_Helper -from Standard.Database.Data.Column import Column, Aggregate_Column_Builder -from Standard.Database.Data.Internal.IR import Internal_Column -from Standard.Table.Errors import No_Such_Column_Error +from Standard.Database.Data.Column import Column, Aggregate_Column_Builder, Column_Data +from Standard.Database.Data.Internal.IR import Internal_Column, Internal_Column_Data +from Standard.Table.Errors import No_Such_Column_Error, No_Such_Column_Error_Data from Standard.Table.Data.Column_Selector import Column_Selector, By_Index from Standard.Table.Data.Data_Formatter import Data_Formatter from Standard.Database.Error import Unsupported_Database_Operation_Error_Data diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Main.enso index a2e201f50cb4..6636b205664e 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Main.enso @@ -18,11 +18,11 @@ export Standard.Database.Data.Column export Standard.Database.Connection.SSL_Mode from Standard.Database.Connection.Connection export Sql_Error, Sql_Timeout_Error -from Standard.Database.Connection.Credentials export Credentials +from Standard.Database.Connection.Credentials export Credentials, Credentials_Data from Standard.Database.Connection.Client_Certificate export Client_Certificate from Standard.Database.Connection.Connection_Options export Connection_Options from Standard.Database.Connection.Database export connect -from Standard.Database.Connection.Postgres export Postgres -from Standard.Database.Connection.SQLite export SQLite, In_Memory -from Standard.Database.Connection.Redshift export Redshift, AWS_Profile, AWS_Key +from Standard.Database.Connection.Postgres export Postgres, Postgres_Data +from Standard.Database.Connection.SQLite export SQLite, SQLite_Data, In_Memory +from Standard.Database.Connection.Redshift export Redshift, Redshift_Data, AWS_Profile, AWS_Key diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso index 4956a08844ce..2e7c4a1b5790 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso @@ -16,7 +16,7 @@ import Standard.Table.Internal.Problem_Builder from Standard.Table.Data.Column_Selector import Column_Selector, By_Index from Standard.Table.Data.Column_Type_Selection import Column_Type_Selection, Auto from Standard.Table.Data.Data_Formatter import Data_Formatter, Data_Formatter_Data -from Standard.Table.Errors import Missing_Input_Columns, Column_Indexes_Out_Of_Range, Duplicate_Type_Selector, No_Index_Set_Error, No_Such_Column_Error +from Standard.Table.Errors import Missing_Input_Columns, Column_Indexes_Out_Of_Range, Duplicate_Type_Selector, No_Index_Set_Error, No_Such_Column_Error, No_Such_Column_Error_Data import Standard.Table.Data.Match_Columns import Standard.Table.Data.Column_Name_Mapping diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso index 81dd7b38ed6c..33fe715782bb 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Errors.enso @@ -250,7 +250,8 @@ Column_Name_Mismatch.handle_java_exception = Arguments: - column_name: The name of the column that doesn't exist. -type No_Such_Column_Error column_name +type No_Such_Column_Error + No_Such_Column_Error_Data column_name ## UNSTABLE diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso index 6dfa39c82155..f278640ee388 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso @@ -29,7 +29,7 @@ export project.IO.File_Format export project.IO.Quote_Style from project.IO.Excel export Excel_Section, Excel_Range -from project.Data.Data_Formatter export Data_Formatter +from project.Data.Data_Formatter export Data_Formatter, Data_Formatter_Data import Standard.Geo.Geo_Json diff --git a/test/Table_Tests/src/Common_Table_Spec.enso b/test/Table_Tests/src/Common_Table_Spec.enso index 1318d9d81df2..4471db974a26 100644 --- a/test/Table_Tests/src/Common_Table_Spec.enso +++ b/test/Table_Tests/src/Common_Table_Spec.enso @@ -52,7 +52,7 @@ spec prefix table_builder test_selection pending=Nothing = column_1.name . should_equal "bar" column_1.to_vector . should_equal [4, 5, 6] - table.at "nonexistent column name" . should_fail_with No_Such_Column_Error + table.at "nonexistent column name" . should_fail_with No_Such_Column_Error_Data Test.specify "should allow selecting columns by index" <| column_1 = table.at column_1.name . should_equal "foo" @@ -66,7 +66,7 @@ spec prefix table_builder test_selection pending=Nothing = column_3.name . should_equal "abcd123" column_3.to_vector . should_equal [19, 20, 21] - table.at 100 . should_fail_with Index_Out_Of_Bounds_Error + table.at 100 . should_fail_with Index_Out_Of_Bounds_Error_Data Test.group prefix+"Table.column_count" pending=pending <| Test.specify "should allow getting the column count" <| diff --git a/test/Table_Tests/src/Data_Formatter_Spec.enso b/test/Table_Tests/src/Data_Formatter_Spec.enso index 3d11e7a30c73..b12940ed3a41 100644 --- a/test/Table_Tests/src/Data_Formatter_Spec.enso +++ b/test/Table_Tests/src/Data_Formatter_Spec.enso @@ -1,7 +1,7 @@ from Standard.Base import all import Standard.Table -from Standard.Table import Column, Data_Formatter, Quote_Style +from Standard.Table import Column, Data_Formatter_Data, Quote_Style from Standard.Table.Errors import all import Standard.Test diff --git a/test/Table_Tests/src/Delimited_Write_Spec.enso b/test/Table_Tests/src/Delimited_Write_Spec.enso index cac74daa593e..a6ed0718be61 100644 --- a/test/Table_Tests/src/Delimited_Write_Spec.enso +++ b/test/Table_Tests/src/Delimited_Write_Spec.enso @@ -3,7 +3,7 @@ import Standard.Base.System from Standard.Base.Error.Problem_Behavior import all import Standard.Table -from Standard.Table import Column, Data_Formatter, Quote_Style, Column_Name_Mapping, Match_Columns +from Standard.Table import Column, Data_Formatter, Data_Formatter_Data, Quote_Style, Column_Name_Mapping, Match_Columns from Standard.Table.Errors import all from Standard.Table.IO.File_Format import Delimited_Data from Standard.Table.Data.Column_Selector as Column_Selector_Module import By_Name diff --git a/test/Table_Tests/src/Excel_Spec.enso b/test/Table_Tests/src/Excel_Spec.enso index fbdcc2eefef4..02f7822745bb 100644 --- a/test/Table_Tests/src/Excel_Spec.enso +++ b/test/Table_Tests/src/Excel_Spec.enso @@ -4,7 +4,8 @@ from Standard.Base.System.File import File_Already_Exists_Error from Standard.Base.Error.Problem_Behavior import all import Standard.Table -from Standard.Table import File_Format, Match_Columns, Column_Name_Mapping, Data_Formatter, Excel_Range +from Standard.Table import File_Format, Match_Columns, Column_Name_Mapping, Data_Formatter, Excel_Range, Data_Formatter_Data + from Standard.Table.Data.Column_Selector as Column_Selector_Module import By_Index from Standard.Table.IO.Excel import Sheet_Names, Range_Names, Sheet, Cell_Range from Standard.Table.Errors as Table_Errors import Invalid_Output_Column_Names_Data, Duplicate_Output_Column_Names_Data, Invalid_Location_Data, Range_Exceeded_Data, Existing_Data_Data, Column_Count_Mismatch_Data, Column_Name_Mismatch_Data From 214081e4a7d3d03750434e9efbc3872f7d3948c1 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Sat, 27 Aug 2022 11:06:27 +0200 Subject: [PATCH 080/110] Update distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Radosław Waśko --- distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso index ed84bb7eb025..79ce5e3fd63f 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Any.enso @@ -89,7 +89,7 @@ type Any if langs_match.not then False else o_1.equals o_2 Pair_Data (Meta.Unresolved_Symbol_Data _) (Meta.Unresolved_Symbol_Data _) -> (self_meta.name == that_meta.name) && (self_meta.scope == that_meta.scope) - ## Pair_Datatructor comparison is covered by the identity equality. + ## Constructor comparison is covered by the identity equality. Primitive objects should define their own equality. Therefore, there are no more cases to handle in self method. _ -> False From cdbfe6af3564ed7642f4a3a5ee4b0d39d0ca3b75 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 29 Aug 2022 13:56:34 +0200 Subject: [PATCH 081/110] another merge --- .../0.0.0-dev/src/Data/Index_Sub_Range.enso | 46 +++--- .../Database/0.0.0-dev/src/Data/Table.enso | 4 +- .../Table/0.0.0-dev/src/Data/Column.enso | 2 +- .../Table/0.0.0-dev/src/Data/Table.enso | 2 +- test/Table_Tests/src/Common_Table_Spec.enso | 154 +++++++++--------- test/Table_Tests/src/Data_Formatter_Spec.enso | 8 +- 6 files changed, 108 insertions(+), 108 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Index_Sub_Range.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Index_Sub_Range.enso index 141c7f3bcc1c..415402b3bfee 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Index_Sub_Range.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Index_Sub_Range.enso @@ -55,15 +55,15 @@ resolve_ranges ranges length = trim descriptor = case descriptor of Integer -> actual_index = if descriptor < 0 then length + descriptor else descriptor - if (actual_index < 0) || (actual_index >= length) then Panic.throw (Index_Out_Of_Bounds_Error descriptor length) else + if (actual_index < 0) || (actual_index >= length) then Panic.throw (Index_Out_Of_Bounds_Error_Data descriptor length) else actual_index - Range start end step -> - if step <= 0 then Panic.throw (Illegal_Argument_Error "Range step must be positive.") else - if (start < 0) || (end < 0) then Panic.throw (Illegal_Argument_Error "Range start and end must not be negative.") else - if start >= length then Panic.throw (Index_Out_Of_Bounds_Error start length) else + Range_Data start end step -> + if step <= 0 then Panic.throw (Illegal_Argument_Error_Data "Range step must be positive.") else + if (start < 0) || (end < 0) then Panic.throw (Illegal_Argument_Error_Data "Range start and end must not be negative.") else + if start >= length then Panic.throw (Index_Out_Of_Bounds_Error_Data start length) else actual_end = Math.min end length - if actual_end < start then Range start start step else - Range start actual_end step + if actual_end < start then Range_Data start start step else + Range_Data start actual_end step ranges.map trim ## PRIVATE @@ -73,11 +73,11 @@ resolve_ranges ranges length = single-element ranges. normalize_ranges descriptors = normalize descriptor = case descriptor of - Integer -> [Range descriptor descriptor+1] - Range _ _ _ -> + Integer -> [Range_Data descriptor descriptor+1] + Range_Data _ _ _ -> if descriptor.step == 1 then [descriptor] else descriptor.to_vector.map ix-> - Range ix ix+1 + Range_Data ix ix+1 descriptors.flat_map normalize ## PRIVATE @@ -96,9 +96,9 @@ normalize_ranges descriptors = invert_range_selection : Vector Range -> Integer -> Boolean -> Vector Range invert_range_selection ranges length needs_sorting = sorted = if needs_sorting then sort_and_merge_ranges ranges else ranges - ranges_with_sentinels = [Range 0 0] + sorted + [Range length length] + ranges_with_sentinels = [Range_Data 0 0] + sorted + [Range_Data length length] ranges_with_sentinels.zip ranges_with_sentinels.tail prev-> next-> - Range prev.end next.start + Range_Data prev.end next.start ## PRIVATE Returns a new sorted list of ranges where intersecting ranges have been @@ -113,7 +113,7 @@ sort_and_merge_ranges ranges = sorted.tail.each range-> current = current_ref.get case range.start <= current.end of - True -> current_ref.put (Range current.start (Math.max current.end range.end)) + True -> current_ref.put (Range_Data current.start (Math.max current.end range.end)) False -> builder.append current current_ref.put range @@ -147,16 +147,16 @@ sort_and_merge_ranges ranges = - range: The `Index_Sub_Range` to take from the collection. take_helper : Integer -> (Integer -> Any) -> (Integer -> Integer -> Any) -> (Vector (Integer | Range) -> Vector Any) -> Index_Sub_Range -> Any take_helper length at single_slice slice_ranges index_sub_range = case index_sub_range of - Range _ _ _ -> take_helper length at single_slice slice_ranges (By_Index index_sub_range) + Range_Data _ _ _ -> take_helper length at single_slice slice_ranges (By_Index index_sub_range) First count -> single_slice 0 (Math.min length count) Last count -> single_slice length-count length While predicate -> end = 0.up_to length . find i-> (predicate (at i)).not true_end = if end.is_nothing then length else end single_slice 0 true_end - By_Index one_or_many_descriptors -> Panic.recover [Index_Out_Of_Bounds_Error, Illegal_Argument_Error] <| + By_Index one_or_many_descriptors -> Panic.recover [Index_Out_Of_Bounds_Error_Data, Illegal_Argument_Error_Data] <| indices = case one_or_many_descriptors of - Vector.Vector _ -> one_or_many_descriptors + Vector.Vector_Data _ -> one_or_many_descriptors _ -> [one_or_many_descriptors] trimmed = resolve_ranges indices length slice_ranges trimmed @@ -165,9 +165,9 @@ take_helper length at single_slice slice_ranges index_sub_range = case index_sub indices_to_take = Random.random_indices length count rng take_helper length at single_slice slice_ranges (By_Index indices_to_take) Every step start -> - if step <= 0 then Error.throw (Illegal_Argument_Error "Step within Every must be positive.") else + if step <= 0 then Error.throw (Illegal_Argument_Error_Data "Step within Every must be positive.") else if start >= length then single_slice 0 0 else - range = Range start length step + range = Range_Data start length step take_helper length at single_slice slice_ranges (By_Index range) ## PRIVATE @@ -196,16 +196,16 @@ take_helper length at single_slice slice_ranges index_sub_range = case index_sub - range: The `Index_Sub_Range` to drop from the collection. drop_helper : Integer -> (Integer -> Any) -> (Integer -> Integer -> Any) -> (Vector (Integer | Range) -> Vector Any) -> Index_Sub_Range -> Any drop_helper length at single_slice slice_ranges index_sub_range = case index_sub_range of - Range _ _ _ -> drop_helper length at single_slice slice_ranges (By_Index index_sub_range) + Range_Data _ _ _ -> drop_helper length at single_slice slice_ranges (By_Index index_sub_range) First count -> single_slice count length Last count -> single_slice 0 length-count While predicate -> end = 0.up_to length . find i-> (predicate (at i)).not true_end = if end.is_nothing then length else end single_slice true_end length - By_Index one_or_many_descriptors -> Panic.recover [Index_Out_Of_Bounds_Error, Illegal_Argument_Error] <| + By_Index one_or_many_descriptors -> Panic.recover [Index_Out_Of_Bounds_Error_Data, Illegal_Argument_Error_Data] <| indices = case one_or_many_descriptors of - Vector.Vector _ -> one_or_many_descriptors + Vector.Vector_Data _ -> one_or_many_descriptors _ -> [one_or_many_descriptors] trimmed = resolve_ranges indices length normalized = normalize_ranges trimmed @@ -216,7 +216,7 @@ drop_helper length at single_slice slice_ranges index_sub_range = case index_sub indices_to_drop = Random.random_indices length count rng drop_helper length at single_slice slice_ranges (By_Index indices_to_drop) Every step start -> - if step <= 0 then Error.throw (Illegal_Argument_Error "Step within Every must be positive.") else + if step <= 0 then Error.throw (Illegal_Argument_Error_Data "Step within Every must be positive.") else if start >= length then single_slice 0 length else - range = Range start length step + range = Range_Data start length step drop_helper length at single_slice slice_ranges (By_Index range) diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso index f4c3ea397840..936ee1be574a 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Table.enso @@ -364,7 +364,7 @@ type Table take self range=(First 1) = _ = range msg = "`Table.take` is not yet implemented." - Error.throw (Unsupported_Database_Operation_Error msg) + Error.throw (Unsupported_Database_Operation_Error_Data msg) ## UNSTABLE Creates a new Table from the input with the specified range of rows @@ -377,7 +377,7 @@ type Table drop self range=(First 1) = _ = range msg = "`Table.drop` is not yet implemented." - Error.throw (Unsupported_Database_Operation_Error msg) + Error.throw (Unsupported_Database_Operation_Error_Data msg) ## UNSTABLE diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso index 176660df9bec..e9c0be416b7a 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Column.enso @@ -1380,4 +1380,4 @@ get_item_string column ix = A helper to create a new table consisting of slices of the original table. slice_ranges column ranges = normalized = Index_Sub_Range.normalize_ranges ranges - Column (column.java_column.slice normalized.to_array) + Column_Data (column.java_column.slice normalized.to_array) diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso index 495d1056c4a5..5547fe1f96ab 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Data/Table.enso @@ -1159,4 +1159,4 @@ Text.from (that : Table) (format:File_Format.Delimited|File_Format.Fixed_Width = A helper to create a new table consisting of slices of the original table. slice_ranges table ranges = normalized = Index_Sub_Range.normalize_ranges ranges - Table (table.java_table.slice normalized.to_array) + Table_Data (table.java_table.slice normalized.to_array) diff --git a/test/Table_Tests/src/Common_Table_Spec.enso b/test/Table_Tests/src/Common_Table_Spec.enso index 1328eeb1d36e..c1e346097825 100644 --- a/test/Table_Tests/src/Common_Table_Spec.enso +++ b/test/Table_Tests/src/Common_Table_Spec.enso @@ -13,7 +13,7 @@ import Standard.Test.Problems from project.Util import all type Test_Selection - Test_Selection_Data supports_case_sensitive_columns=True order_by=True natural_ordering=False case_insensitive_ordering=True order_by_unicode_normalization_by_default=False case_insensitive_ascii_only=False + Test_Selection_Data supports_case_sensitive_columns=True order_by=True natural_ordering=False case_insensitive_ordering=True order_by_unicode_normalization_by_default=False case_insensitive_ascii_only=False take_drop=True ## A common test suite for shared operations on the Table API. @@ -815,48 +815,48 @@ spec prefix table_builder test_selection pending=Nothing = table.drop (Last 100) . should_equal empty Test.specify "should allow selecting rows by ranges or indices" <| - table.take (Range 2 4) . at "beta" . to_vector . should_equal ["C", "D"] - table.take (Range 0 0) . should_equal empty - table.take (Range 100 100) . should_fail_with Index_Out_Of_Bounds_Error - table.take (Range 100 100) . catch . should_equal (Index_Out_Of_Bounds_Error 100 8) - table.take (Range 0 100) . should_equal table - table.take (Range 0 table.row_count) . should_equal table - empty.take (Range 0 0) . should_fail_with Index_Out_Of_Bounds_Error - empty.take (Range 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error 0 0) - table.take (Range 100 99) . should_fail_with Index_Out_Of_Bounds_Error - - table.drop (Range 2 4) . at "alpha" . to_vector . should_equal [1, 2, 5, 6, 7, 8] - table.drop (Range 0 0) . should_equal table - table.drop (Range 100 100) . should_fail_with Index_Out_Of_Bounds_Error - table.drop (Range 100 100) . catch . should_equal (Index_Out_Of_Bounds_Error 100 8) - table.drop (Range 0 100) . should_equal empty - table.drop (Range 0 table.row_count) . should_equal empty - empty.drop (Range 0 0) . should_fail_with Index_Out_Of_Bounds_Error - empty.drop (Range 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error 0 0) - table.drop (Range 100 99) . should_fail_with Index_Out_Of_Bounds_Error + table.take (Range_Data 2 4) . at "beta" . to_vector . should_equal ["C", "D"] + table.take (Range_Data 0 0) . should_equal empty + table.take (Range_Data 100 100) . should_fail_with Index_Out_Of_Bounds_Error_Data + table.take (Range_Data 100 100) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 100 8) + table.take (Range_Data 0 100) . should_equal table + table.take (Range_Data 0 table.row_count) . should_equal table + empty.take (Range_Data 0 0) . should_fail_with Index_Out_Of_Bounds_Error_Data + empty.take (Range_Data 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 0 0) + table.take (Range_Data 100 99) . should_fail_with Index_Out_Of_Bounds_Error_Data + + table.drop (Range_Data 2 4) . at "alpha" . to_vector . should_equal [1, 2, 5, 6, 7, 8] + table.drop (Range_Data 0 0) . should_equal table + table.drop (Range_Data 100 100) . should_fail_with Index_Out_Of_Bounds_Error_Data + table.drop (Range_Data 100 100) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 100 8) + table.drop (Range_Data 0 100) . should_equal empty + table.drop (Range_Data 0 table.row_count) . should_equal empty + empty.drop (Range_Data 0 0) . should_fail_with Index_Out_Of_Bounds_Error_Data + empty.drop (Range_Data 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 0 0) + table.drop (Range_Data 100 99) . should_fail_with Index_Out_Of_Bounds_Error_Data table.take (Index_Sub_Range.By_Index 0) . at "beta" . to_vector . should_equal ["A"] - empty.take (Index_Sub_Range.By_Index 0) . should_fail_with Index_Out_Of_Bounds_Error + empty.take (Index_Sub_Range.By_Index 0) . should_fail_with Index_Out_Of_Bounds_Error_Data table.take (Index_Sub_Range.By_Index []) . should_equal empty table.take (Index_Sub_Range.By_Index [-1, -1]) . at "beta" . to_vector . should_equal ["H", "H"] - table.take (Index_Sub_Range.By_Index [0, 0, Range 3 100]) . at "alpha" . to_vector . should_equal [1, 1, 4, 5, 6, 7, 8] - table.take (Range 0 100 2) . at "alpha" . to_vector . should_equal [1, 3, 5, 7] - table.take (Index_Sub_Range.By_Index [Range 0 100 2, Range 1 6 2]) . at "alpha" . to_vector . should_equal [1, 3, 5, 7, 2, 4, 6] - table.take (Index_Sub_Range.By_Index [Range 1 3, Range 2 5]) . at "alpha" . to_vector . should_equal [2, 3, 3, 4, 5] - table.take (Index_Sub_Range.By_Index [Range 2 5, Range 1 3]) . at "alpha" . to_vector . should_equal [3, 4, 5, 2, 3] - table.take (Index_Sub_Range.By_Index [0, 1, Range 100 200]) . should_fail_with Index_Out_Of_Bounds_Error - table.take (Index_Sub_Range.By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error + table.take (Index_Sub_Range.By_Index [0, 0, Range_Data 3 100]) . at "alpha" . to_vector . should_equal [1, 1, 4, 5, 6, 7, 8] + table.take (Range_Data 0 100 2) . at "alpha" . to_vector . should_equal [1, 3, 5, 7] + table.take (Index_Sub_Range.By_Index [Range_Data 0 100 2, Range_Data 1 6 2]) . at "alpha" . to_vector . should_equal [1, 3, 5, 7, 2, 4, 6] + table.take (Index_Sub_Range.By_Index [Range_Data 1 3, Range_Data 2 5]) . at "alpha" . to_vector . should_equal [2, 3, 3, 4, 5] + table.take (Index_Sub_Range.By_Index [Range_Data 2 5, Range_Data 1 3]) . at "alpha" . to_vector . should_equal [3, 4, 5, 2, 3] + table.take (Index_Sub_Range.By_Index [0, 1, Range_Data 100 200]) . should_fail_with Index_Out_Of_Bounds_Error_Data + table.take (Index_Sub_Range.By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error_Data table.drop (Index_Sub_Range.By_Index 0) . at "alpha" . to_vector . should_equal [2, 3, 4, 5, 6, 7, 8] table.drop (Index_Sub_Range.By_Index []) . should_equal table table.drop (Index_Sub_Range.By_Index [-1, -1]) . at "alpha" . to_vector . should_equal [1, 2, 3, 4, 5, 6, 7] - table.drop (Index_Sub_Range.By_Index [0, 0, Range 3 100]) . at "alpha" . to_vector . should_equal [2, 3] - table.drop (Range 0 100 2) . at "alpha" . to_vector . should_equal [2, 4, 6, 8] - table.drop (Index_Sub_Range.By_Index [Range 0 100 2, Range 1 6 2]) . at "alpha" . to_vector . should_equal [8] - table.drop (Index_Sub_Range.By_Index [Range 1 3, Range 2 5]) . at "alpha" . to_vector . should_equal [1, 6, 7, 8] - table.drop (Index_Sub_Range.By_Index [Range 2 5, Range 1 3]) . at "alpha" . to_vector . should_equal [1, 6, 7, 8] - table.drop (Index_Sub_Range.By_Index [0, 1, Range 100 200]) . should_fail_with Index_Out_Of_Bounds_Error - table.drop (Index_Sub_Range.By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error + table.drop (Index_Sub_Range.By_Index [0, 0, Range_Data 3 100]) . at "alpha" . to_vector . should_equal [2, 3] + table.drop (Range_Data 0 100 2) . at "alpha" . to_vector . should_equal [2, 4, 6, 8] + table.drop (Index_Sub_Range.By_Index [Range_Data 0 100 2, Range_Data 1 6 2]) . at "alpha" . to_vector . should_equal [8] + table.drop (Index_Sub_Range.By_Index [Range_Data 1 3, Range_Data 2 5]) . at "alpha" . to_vector . should_equal [1, 6, 7, 8] + table.drop (Index_Sub_Range.By_Index [Range_Data 2 5, Range_Data 1 3]) . at "alpha" . to_vector . should_equal [1, 6, 7, 8] + table.drop (Index_Sub_Range.By_Index [0, 1, Range_Data 100 200]) . should_fail_with Index_Out_Of_Bounds_Error_Data + table.drop (Index_Sub_Range.By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error_Data Test.specify "should allow selecting every Nth row" <| table.take (Every 1) . should_equal table @@ -866,8 +866,8 @@ spec prefix table_builder test_selection pending=Nothing = table.take (Every 2 first=100) . at "alpha" . to_vector . should_equal [] table.take (Every 200) . at "alpha" . to_vector . should_equal [1] empty.take (Every 2) . should_equal empty - table.take (Every 0) . should_fail_with Illegal_Argument_Error - empty.take (Every 0) . should_fail_with Illegal_Argument_Error + table.take (Every 0) . should_fail_with Illegal_Argument_Error_Data + empty.take (Every 0) . should_fail_with Illegal_Argument_Error_Data table.drop (Every 1) . should_equal empty table.drop (Every 3) . at "alpha" . to_vector . should_equal [2, 3, 5, 6, 8] @@ -876,8 +876,8 @@ spec prefix table_builder test_selection pending=Nothing = table.drop (Every 2 first=100) . should_equal table table.drop (Every 200) . at "beta" . to_vector . should_equal ["B", "C", "D", "E", "F", "G", "H"] empty.drop (Every 2) . should_equal empty - table.drop (Every 0) . should_fail_with Illegal_Argument_Error - empty.drop (Every 0) . should_fail_with Illegal_Argument_Error + table.drop (Every 0) . should_fail_with Illegal_Argument_Error_Data + empty.drop (Every 0) . should_fail_with Illegal_Argument_Error_Data Test.specify "should allow sampling rows" <| empty = table_builder [["X", []]] @@ -945,48 +945,48 @@ spec prefix table_builder test_selection pending=Nothing = alpha.drop (Last 100) . should_equal empty_alpha Test.specify "should allow selecting rows by ranges or indices" <| - beta.take (Range 2 4) . to_vector . should_equal ["C", "D"] - beta.take (Range 0 0) . should_equal empty_beta - beta.take (Range 100 100) . should_fail_with Index_Out_Of_Bounds_Error - beta.take (Range 100 100) . catch . should_equal (Index_Out_Of_Bounds_Error 100 8) - beta.take (Range 0 100) . should_equal beta - beta.take (Range 0 table.row_count) . should_equal beta - empty_beta.take (Range 0 0) . should_fail_with Index_Out_Of_Bounds_Error - empty_beta.take (Range 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error 0 0) - beta.take (Range 100 99) . should_fail_with Index_Out_Of_Bounds_Error - - alpha.drop (Range 2 4) . to_vector . should_equal [1, 2, 5, 6, 7, 8] - alpha.drop (Range 0 0) . should_equal alpha - alpha.drop (Range 100 100) . should_fail_with Index_Out_Of_Bounds_Error - alpha.drop (Range 100 100) . catch . should_equal (Index_Out_Of_Bounds_Error 100 8) - alpha.drop (Range 0 100) . should_equal empty_alpha - alpha.drop (Range 0 table.row_count) . should_equal empty_alpha - empty_alpha.drop (Range 0 0) . should_fail_with Index_Out_Of_Bounds_Error - empty_alpha.drop (Range 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error 0 0) - alpha.drop (Range 100 99) . should_fail_with Index_Out_Of_Bounds_Error + beta.take (Range_Data 2 4) . to_vector . should_equal ["C", "D"] + beta.take (Range_Data 0 0) . should_equal empty_beta + beta.take (Range_Data 100 100) . should_fail_with Index_Out_Of_Bounds_Error_Data + beta.take (Range_Data 100 100) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 100 8) + beta.take (Range_Data 0 100) . should_equal beta + beta.take (Range_Data 0 table.row_count) . should_equal beta + empty_beta.take (Range_Data 0 0) . should_fail_with Index_Out_Of_Bounds_Error_Data + empty_beta.take (Range_Data 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 0 0) + beta.take (Range_Data 100 99) . should_fail_with Index_Out_Of_Bounds_Error_Data + + alpha.drop (Range_Data 2 4) . to_vector . should_equal [1, 2, 5, 6, 7, 8] + alpha.drop (Range_Data 0 0) . should_equal alpha + alpha.drop (Range_Data 100 100) . should_fail_with Index_Out_Of_Bounds_Error_Data + alpha.drop (Range_Data 100 100) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 100 8) + alpha.drop (Range_Data 0 100) . should_equal empty_alpha + alpha.drop (Range_Data 0 table.row_count) . should_equal empty_alpha + empty_alpha.drop (Range_Data 0 0) . should_fail_with Index_Out_Of_Bounds_Error_Data + empty_alpha.drop (Range_Data 0 0) . catch . should_equal (Index_Out_Of_Bounds_Error_Data 0 0) + alpha.drop (Range_Data 100 99) . should_fail_with Index_Out_Of_Bounds_Error_Data beta.take (Index_Sub_Range.By_Index 0) . to_vector . should_equal ["A"] - empty_beta.take (Index_Sub_Range.By_Index 0) . should_fail_with Index_Out_Of_Bounds_Error + empty_beta.take (Index_Sub_Range.By_Index 0) . should_fail_with Index_Out_Of_Bounds_Error_Data beta.take (Index_Sub_Range.By_Index []) . should_equal empty_beta beta.take (Index_Sub_Range.By_Index [-1, -1]) . to_vector . should_equal ["H", "H"] - alpha.take (Index_Sub_Range.By_Index [0, 0, Range 3 100]) . to_vector . should_equal [1, 1, 4, 5, 6, 7, 8] - alpha.take (Range 0 100 2) . to_vector . should_equal [1, 3, 5, 7] - alpha.take (Index_Sub_Range.By_Index [Range 0 100 2, Range 1 6 2]) . to_vector . should_equal [1, 3, 5, 7, 2, 4, 6] - alpha.take (Index_Sub_Range.By_Index [Range 1 3, Range 2 5]) . to_vector . should_equal [2, 3, 3, 4, 5] - alpha.take (Index_Sub_Range.By_Index [Range 2 5, Range 1 3]) . to_vector . should_equal [3, 4, 5, 2, 3] - alpha.take (Index_Sub_Range.By_Index [0, 1, Range 100 200]) . should_fail_with Index_Out_Of_Bounds_Error - alpha.take (Index_Sub_Range.By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error + alpha.take (Index_Sub_Range.By_Index [0, 0, Range_Data 3 100]) . to_vector . should_equal [1, 1, 4, 5, 6, 7, 8] + alpha.take (Range_Data 0 100 2) . to_vector . should_equal [1, 3, 5, 7] + alpha.take (Index_Sub_Range.By_Index [Range_Data 0 100 2, Range_Data 1 6 2]) . to_vector . should_equal [1, 3, 5, 7, 2, 4, 6] + alpha.take (Index_Sub_Range.By_Index [Range_Data 1 3, Range_Data 2 5]) . to_vector . should_equal [2, 3, 3, 4, 5] + alpha.take (Index_Sub_Range.By_Index [Range_Data 2 5, Range_Data 1 3]) . to_vector . should_equal [3, 4, 5, 2, 3] + alpha.take (Index_Sub_Range.By_Index [0, 1, Range_Data 100 200]) . should_fail_with Index_Out_Of_Bounds_Error_Data + alpha.take (Index_Sub_Range.By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error_Data alpha.drop (Index_Sub_Range.By_Index 0) . to_vector . should_equal [2, 3, 4, 5, 6, 7, 8] alpha.drop (Index_Sub_Range.By_Index []) . should_equal alpha alpha.drop (Index_Sub_Range.By_Index [-1, -1]) . to_vector . should_equal [1, 2, 3, 4, 5, 6, 7] - alpha.drop (Index_Sub_Range.By_Index [0, 0, Range 3 100]) . to_vector . should_equal [2, 3] - alpha.drop (Range 0 100 2) . to_vector . should_equal [2, 4, 6, 8] - alpha.drop (Index_Sub_Range.By_Index [Range 0 100 2, Range 1 6 2]) . to_vector . should_equal [8] - alpha.drop (Index_Sub_Range.By_Index [Range 1 3, Range 2 5]) . to_vector . should_equal [1, 6, 7, 8] - alpha.drop (Index_Sub_Range.By_Index [Range 2 5, Range 1 3]) . to_vector . should_equal [1, 6, 7, 8] - alpha.drop (Index_Sub_Range.By_Index [0, 1, Range 100 200]) . should_fail_with Index_Out_Of_Bounds_Error - alpha.drop (Index_Sub_Range.By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error + alpha.drop (Index_Sub_Range.By_Index [0, 0, Range_Data 3 100]) . to_vector . should_equal [2, 3] + alpha.drop (Range_Data 0 100 2) . to_vector . should_equal [2, 4, 6, 8] + alpha.drop (Index_Sub_Range.By_Index [Range_Data 0 100 2, Range_Data 1 6 2]) . to_vector . should_equal [8] + alpha.drop (Index_Sub_Range.By_Index [Range_Data 1 3, Range_Data 2 5]) . to_vector . should_equal [1, 6, 7, 8] + alpha.drop (Index_Sub_Range.By_Index [Range_Data 2 5, Range_Data 1 3]) . to_vector . should_equal [1, 6, 7, 8] + alpha.drop (Index_Sub_Range.By_Index [0, 1, Range_Data 100 200]) . should_fail_with Index_Out_Of_Bounds_Error_Data + alpha.drop (Index_Sub_Range.By_Index 100) . should_fail_with Index_Out_Of_Bounds_Error_Data Test.specify "should allow selecting every Nth row" <| alpha.take (Every 1) . should_equal alpha @@ -996,8 +996,8 @@ spec prefix table_builder test_selection pending=Nothing = alpha.take (Every 2 first=100) . to_vector . should_equal [] alpha.take (Every 200) . to_vector . should_equal [1] empty_beta.take (Every 2) . should_equal empty_beta - beta.take (Every 0) . should_fail_with Illegal_Argument_Error - empty_beta.take (Every 0) . should_fail_with Illegal_Argument_Error + beta.take (Every 0) . should_fail_with Illegal_Argument_Error_Data + empty_beta.take (Every 0) . should_fail_with Illegal_Argument_Error_Data alpha.drop (Every 1) . should_equal empty_alpha alpha.drop (Every 3) . to_vector . should_equal [2, 3, 5, 6, 8] @@ -1006,8 +1006,8 @@ spec prefix table_builder test_selection pending=Nothing = alpha.drop (Every 2 first=100) . should_equal alpha beta.drop (Every 200) . to_vector . should_equal ["B", "C", "D", "E", "F", "G", "H"] empty_beta.drop (Every 2) . should_equal empty_beta - beta.drop (Every 0) . should_fail_with Illegal_Argument_Error - empty_beta.drop (Every 0) . should_fail_with Illegal_Argument_Error + beta.drop (Every 0) . should_fail_with Illegal_Argument_Error_Data + empty_beta.drop (Every 0) . should_fail_with Illegal_Argument_Error_Data Test.specify "should allow sampling rows" <| three = table_builder [["X", ["a", "a", "a"]]] . at "X" diff --git a/test/Table_Tests/src/Data_Formatter_Spec.enso b/test/Table_Tests/src/Data_Formatter_Spec.enso index 1ceb776e661a..50204e2133f4 100644 --- a/test/Table_Tests/src/Data_Formatter_Spec.enso +++ b/test/Table_Tests/src/Data_Formatter_Spec.enso @@ -85,18 +85,18 @@ spec = formatter.parse "000.0" . should_equal 0.0 Test.specify "should parse booleans" <| - formatter = Data_Formatter + formatter = Data_Formatter_Data formatter.parse "True" . should_equal True formatter.parse "False" . should_equal False Test.specify "should allow custom boolean formats" <| - formatter = Data_Formatter true_values=["YES", "1", "true"] false_values=["NO", "0", "false"] + formatter = Data_Formatter_Data true_values=["YES", "1", "true"] false_values=["NO", "0", "false"] formatter.parse "YES" . should_equal True formatter.parse "NO" . should_equal False - (Data_Formatter true_values=[] false_values=[]).parse "True" datatype=Boolean . should_equal Nothing + (Data_Formatter_Data true_values=[] false_values=[]).parse "True" datatype=Boolean . should_equal Nothing Test.specify "should parse dates" <| - formatter = Data_Formatter + formatter = Data_Formatter_Data formatter.parse "2022-01-01" . should_equal (Date.new 2022) formatter.parse "2020-05-07" . should_equal (Date.new 2020 5 7) formatter.parse "1999-01-01 00:00:00" . should_equal (Date_Time.new 1999) From 0852efaa69214e7c98d411aa90dd40aef58c71a1 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 29 Aug 2022 14:49:58 +0200 Subject: [PATCH 082/110] try a thingy --- build.sbt | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/build.sbt b/build.sbt index d2d3d4b142bb..ff06e7a57a14 100644 --- a/build.sbt +++ b/build.sbt @@ -5,8 +5,11 @@ import sbt.Keys.{libraryDependencies, scalacOptions} import sbt.addCompilerPlugin import sbt.complete.DefaultParsers._ import sbt.complete.Parser -import sbtcrossproject.CrossPlugin.autoImport.{CrossType, crossProject} -import src.main.scala.licenses.{DistributionDescription, SBTDistributionComponent} +import sbtcrossproject.CrossPlugin.autoImport.{crossProject, CrossType} +import src.main.scala.licenses.{ + DistributionDescription, + SBTDistributionComponent +} import java.io.File @@ -14,9 +17,9 @@ import java.io.File // === Global Configuration =================================================== // ============================================================================ -val scalacVersion = "2.13.8" -val graalVersion = "21.3.0" -val javaVersion = "11" +val scalacVersion = "2.13.8" +val graalVersion = "21.3.0" +val javaVersion = "11" val defaultDevEnsoVersion = "0.0.0-dev" val ensoVersion = sys.env.getOrElse( "ENSO_VERSION", @@ -713,11 +716,11 @@ lazy val `profiling-utils` = project "org.netbeans.api" % "org-netbeans-modules-sampler" % netbeansApiVersion exclude ("org.netbeans.api", "org-openide-loaders") exclude ("org.netbeans.api", "org-openide-nodes") - exclude("org.netbeans.api", "org-netbeans-api-progress-nb") - exclude("org.netbeans.api", "org-netbeans-api-progress") - exclude("org.netbeans.api", "org-openide-util-lookup") - exclude("org.netbeans.api", "org-openide-util") - exclude("org.netbeans.api", "org-openide-dialogs") + exclude ("org.netbeans.api", "org-netbeans-api-progress-nb") + exclude ("org.netbeans.api", "org-netbeans-api-progress") + exclude ("org.netbeans.api", "org-openide-util-lookup") + exclude ("org.netbeans.api", "org-openide-util") + exclude ("org.netbeans.api", "org-openide-dialogs") exclude ("org.netbeans.api", "org-openide-filesystems") exclude ("org.netbeans.api", "org-openide-util-ui") exclude ("org.netbeans.api", "org-openide-awt") @@ -1003,11 +1006,11 @@ val truffleRunOptions = if (java.lang.Boolean.getBoolean("bench.compileOnly")) { } else { Seq( "-Dpolyglot.engine.IterativePartialEscape=true", - "-Dpolyglot.engine.BackgroundCompilation=false" + "-Dpolyglot.engine.BackgroundCompilation=false", + "-Dbench.compileOnly=true" ) } - val truffleRunOptionsSettings = Seq( fork := true, javaOptions ++= truffleRunOptions @@ -1294,6 +1297,7 @@ lazy val runtime = (project in file("engine/runtime")) ) .settings( (Compile / compile) := (Compile / compile) + .dependsOn(Compile / clean) .dependsOn(Def.task { (Compile / sourceManaged).value.mkdirs }) .value ) From c1b22d47443399b3b4e64f65527bc15378c958af Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 29 Aug 2022 14:58:21 +0200 Subject: [PATCH 083/110] atomic hack --- build.sbt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.sbt b/build.sbt index ff06e7a57a14..88f65433c8e2 100644 --- a/build.sbt +++ b/build.sbt @@ -1297,7 +1297,7 @@ lazy val runtime = (project in file("engine/runtime")) ) .settings( (Compile / compile) := (Compile / compile) - .dependsOn(Compile / clean) + .dependsOn(clean) // CI HACK: REMOVE IT ASAP .dependsOn(Def.task { (Compile / sourceManaged).value.mkdirs }) .value ) From 4d78453d8dfadc389f1dbf18fad6de5e8ffaeba2 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 29 Aug 2022 16:05:46 +0200 Subject: [PATCH 084/110] case? --- distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso index 77bf13f46746..acb860a35e21 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Network/URI.enso @@ -1,6 +1,6 @@ from Standard.Base import all -import Standard.Base.Network.Uri.Internal +import Standard.Base.Network.URI.Internal polyglot java import java.net.URI as Java_URI polyglot java import java.util.Optional From 05124b534cce07932a872e0f3bdfe27642c35edb Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 29 Aug 2022 16:38:59 +0200 Subject: [PATCH 085/110] everybody is ci-fighting --- build.sbt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/build.sbt b/build.sbt index 88f65433c8e2..a8689103acde 100644 --- a/build.sbt +++ b/build.sbt @@ -1295,9 +1295,13 @@ lazy val runtime = (project in file("engine/runtime")) "org.typelevel" %% "kind-projector" % kindProjectorVersion cross CrossVersion.full ) ) + .settings( + (Compile / compile / streams) := (Compile / compile / streams).dependsOn( + Def.taskDyn { Def.task { (Runtime/clean).value } } + ).value// CI HACK: REMOVE IT ASAP + ) .settings( (Compile / compile) := (Compile / compile) - .dependsOn(clean) // CI HACK: REMOVE IT ASAP .dependsOn(Def.task { (Compile / sourceManaged).value.mkdirs }) .value ) From 50df2c962653fbd4f764db7acfbd79b9c824d00a Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 29 Aug 2022 17:19:26 +0200 Subject: [PATCH 086/110] fix postgres --- .../Database/0.0.0-dev/src/Data/Dialect/Postgres.enso | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso index 11759d17c9ae..549f36466d0d 100644 --- a/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso +++ b/distribution/lib/Standard/Database/0.0.0-dev/src/Data/Dialect/Postgres.enso @@ -184,7 +184,7 @@ concat_ops = ## PRIVATE -agg_count_distinct args = if args.is_empty then (Error.throw (Illegal_Argument_Error "COUNT_DISTINCT requires at least one argument.")) else +agg_count_distinct args = if args.is_empty then (Error.throw (Illegal_Argument_Error_Data "COUNT_DISTINCT requires at least one argument.")) else case args.length == 1 of True -> ## A single null value will be skipped. @@ -231,15 +231,15 @@ make_order_descriptor internal_column sort_direction text_ordering = if text_ordering.sort_digits_as_numbers then Error.throw (Unsupported_Database_Operation_Error "Natural ordering is currently not supported. You may need to materialize the Table to perform this operation.") else case text_ordering.case_sensitive of Nothing -> - IR.Order_Descriptor internal_column.expression sort_direction nulls_order=nulls collation=Nothing + IR.Order_Descriptor_Data internal_column.expression sort_direction nulls_order=nulls collation=Nothing True -> - IR.Order_Descriptor internal_column.expression sort_direction nulls_order=nulls collation="ucs_basic" + IR.Order_Descriptor_Data internal_column.expression sort_direction nulls_order=nulls collation="ucs_basic" Case_Insensitive_Data locale -> case locale == Locale.default of False -> Error.throw (Unsupported_Database_Operation_Error "Case insensitive ordering with custom locale is currently not supported. You may need to materialize the Table to perform this operation.") True -> upper = IR.Operation "UPPER" [internal_column.expression] folded_expression = IR.Operation "LOWER" [upper] - IR.Order_Descriptor folded_expression sort_direction nulls_order=nulls collation=Nothing + IR.Order_Descriptor_Data folded_expression sort_direction nulls_order=nulls collation=Nothing False -> - IR.Order_Descriptor internal_column.expression sort_direction nulls_order=nulls collation=Nothing + IR.Order_Descriptor_Data internal_column.expression sort_direction nulls_order=nulls collation=Nothing From eb8c6ecafcd22551e17231b98bcad36cf2dc8681 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 29 Aug 2022 17:52:47 +0200 Subject: [PATCH 087/110] fix geo tests --- test/Geo_Tests/src/Geo_Spec.enso | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Geo_Tests/src/Geo_Spec.enso b/test/Geo_Tests/src/Geo_Spec.enso index b22288a88291..90bec9764d4a 100644 --- a/test/Geo_Tests/src/Geo_Spec.enso +++ b/test/Geo_Tests/src/Geo_Spec.enso @@ -1,5 +1,5 @@ from Standard.Base import all -from Standard.Table import Table +from Standard.Table.Data.Table import Table_Data import Standard.Geo @@ -9,7 +9,7 @@ spec = Test.group "Geo Points" <| point = Geo.point 51.509865 -0.118092 Test.specify "should be able to be created as a Table" <| - point.is_a Table.Table_Data . should_be_true + point.is_a Table_Data . should_be_true Test.specify "should contain a latitude and longitude" <| point.at "latitude" . at 0 . should_equal 51.509865 point.at "longitude" . at 0 . should_equal -0.118092 From 38ffadda72d33bb2f50a54cb068aa9ee2a183f23 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 29 Aug 2022 18:16:35 +0200 Subject: [PATCH 088/110] more fixes --- distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso | 2 +- .../Visualization/0.0.0-dev/src/File_Upload.enso | 5 +++-- .../Visualization/0.0.0-dev/src/Scatter_Plot.enso | 9 +++++---- .../Visualization/0.0.0-dev/src/Table/Visualization.enso | 2 +- test/Visualization_Tests/src/Sql_Spec.enso | 2 +- test/Visualization_Tests/src/Table_Spec.enso | 4 ++-- test/Visualization_Tests/src/Visualization_Spec.enso | 4 ++-- 7 files changed, 15 insertions(+), 13 deletions(-) diff --git a/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso b/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso index f278640ee388..ed154a035bc8 100644 --- a/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso +++ b/distribution/lib/Standard/Table/0.0.0-dev/src/Main.enso @@ -16,7 +16,7 @@ import project.IO.Quote_Style import project.Errors -from project.Data.Table export new, from_rows, join, concat, Table +from project.Data.Table export new, from_rows, join, concat, Table, Table_Data export project.Data.Column export project.Data.Column_Selector export project.Data.Sort_Column diff --git a/distribution/lib/Standard/Visualization/0.0.0-dev/src/File_Upload.enso b/distribution/lib/Standard/Visualization/0.0.0-dev/src/File_Upload.enso index 55504d025037..2afa2d499141 100644 --- a/distribution/lib/Standard/Visualization/0.0.0-dev/src/File_Upload.enso +++ b/distribution/lib/Standard/Visualization/0.0.0-dev/src/File_Upload.enso @@ -9,7 +9,7 @@ from Standard.Base import all - `path`: The path to which the file is being uploaded. file_uploading : (File.File | Text) -> File.File ! File_Being_Uploaded file_uploading path = - err = File_Being_Uploaded <| case path of + err = File_Being_Uploaded_Data <| case path of Text -> path File.File -> path.path _ -> "" @@ -21,4 +21,5 @@ file_uploading path = Arguments: - file_path: The path at which the file is being uploaded. -type File_Being_Uploaded file_path +type File_Being_Uploaded + File_Being_Uploaded_Data file_path diff --git a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Scatter_Plot.enso b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Scatter_Plot.enso index f289a96dd0ae..52b2db82094f 100644 --- a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Scatter_Plot.enso +++ b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Scatter_Plot.enso @@ -150,7 +150,8 @@ bound_data bounds data = case bounds of min_x<=x && x<=max_x && min_y<=y && y<=max_y -type Extreme min_x max_x min_y max_y +type Extreme + Extreme_Data min_x max_x min_y max_y ## PRIVATE limit_data limit data = case limit of @@ -164,11 +165,11 @@ limit_data limit data = case limit of new_min_y = if y current.min_y.second > y point then [idx, point] else current.min_y new_max_x = if x current.max_x.second < x point then [idx, point] else current.max_x new_max_y = if y current.max_y.second < y point then [idx, point] else current.max_y - Extreme new_min_x new_max_x new_min_y new_max_y + Extreme_Data new_min_x new_max_x new_min_y new_max_y first = [0, data.first] - bounds = case data.fold_with_index (Extreme first first first first) update_extreme of - Extreme min_x max_x min_y max_y -> [min_x, max_x, min_y, max_y] + bounds = case data.fold_with_index (Extreme_Data first first first first) update_extreme of + Extreme_Data min_x max_x min_y max_y -> [min_x, max_x, min_y, max_y] _ -> [] extreme = Map.from_vector bounds . values diff --git a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Table/Visualization.enso b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Table/Visualization.enso index 1c21f9174dbf..73f5e78d1f78 100644 --- a/distribution/lib/Standard/Visualization/0.0.0-dev/src/Table/Visualization.enso +++ b/distribution/lib/Standard/Visualization/0.0.0-dev/src/Table/Visualization.enso @@ -52,7 +52,7 @@ prepare_visualization x max_rows = Helpers.recover_errors <| case x of # TODO [RW] Should we truncate Vectors? # We also visualize Vectors and arrays - Vector.Vector _ -> + Vector.Vector_Data _ -> truncated = x.take (First max_rows) Json.from_pairs [["json", truncated], ["all_rows_count", x.length]] . to_text Array -> diff --git a/test/Visualization_Tests/src/Sql_Spec.enso b/test/Visualization_Tests/src/Sql_Spec.enso index 3aafe78c5b14..ae89711aa600 100644 --- a/test/Visualization_Tests/src/Sql_Spec.enso +++ b/test/Visualization_Tests/src/Sql_Spec.enso @@ -22,7 +22,7 @@ spec = enso_project.data.create_directory file = enso_project.data / "sqlite_test.db" file.delete_if_exists - connection = Database.connect (SQLite file) + connection = Database.connect (SQLite_Data file) visualization_spec connection connection.close file.delete diff --git a/test/Visualization_Tests/src/Table_Spec.enso b/test/Visualization_Tests/src/Table_Spec.enso index fd176e608871..0863773246b5 100644 --- a/test/Visualization_Tests/src/Table_Spec.enso +++ b/test/Visualization_Tests/src/Table_Spec.enso @@ -32,7 +32,7 @@ visualization_spec connection = Test.group "Table Visualization" <| Test.specify "should wrap internal errors" <| - bad_table = Database_Table.Table Nothing Nothing Nothing Nothing + bad_table = Database_Table.Table_Data Nothing Nothing Nothing Nothing vis = Visualization.prepare_visualization bad_table 2 json = Json.from_pairs [["error", "Method `meta_index` of Nothing could not be found."]] vis . should_equal json.to_text @@ -97,7 +97,7 @@ spec = enso_project.data.create_directory file = enso_project.data / "sqlite_test.db" file.delete_if_exists - connection = Database.connect (SQLite file) + connection = Database.connect (SQLite_Data file) visualization_spec connection connection.close file.delete diff --git a/test/Visualization_Tests/src/Visualization_Spec.enso b/test/Visualization_Tests/src/Visualization_Spec.enso index 8f4b4395743f..c9288b180a50 100644 --- a/test/Visualization_Tests/src/Visualization_Spec.enso +++ b/test/Visualization_Tests/src/Visualization_Spec.enso @@ -6,11 +6,11 @@ import Standard.Visualization import Standard.Test -from Standard.Visualization.File_Upload import File_Being_Uploaded +from Standard.Visualization.File_Upload import File_Being_Uploaded_Data spec = Test.group "File uploads" <| Test.specify "should be able to be signalled as uploading" <| - Visualization.file_uploading "file" . should_fail_with File_Being_Uploaded + Visualization.file_uploading "file" . should_fail_with File_Being_Uploaded_Data Test.specify "should work whether a textual or file path is provided" <| result_file = Visualization.file_uploading Examples.csv . catch From 7b82ac42de8e6a67d00bf13fb4de4b16183c608c Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Mon, 29 Aug 2022 19:22:49 +0200 Subject: [PATCH 089/110] revert hackering --- build.sbt | 32 ++++++++++++-------------------- 1 file changed, 12 insertions(+), 20 deletions(-) diff --git a/build.sbt b/build.sbt index a8689103acde..d2d3d4b142bb 100644 --- a/build.sbt +++ b/build.sbt @@ -5,11 +5,8 @@ import sbt.Keys.{libraryDependencies, scalacOptions} import sbt.addCompilerPlugin import sbt.complete.DefaultParsers._ import sbt.complete.Parser -import sbtcrossproject.CrossPlugin.autoImport.{crossProject, CrossType} -import src.main.scala.licenses.{ - DistributionDescription, - SBTDistributionComponent -} +import sbtcrossproject.CrossPlugin.autoImport.{CrossType, crossProject} +import src.main.scala.licenses.{DistributionDescription, SBTDistributionComponent} import java.io.File @@ -17,9 +14,9 @@ import java.io.File // === Global Configuration =================================================== // ============================================================================ -val scalacVersion = "2.13.8" -val graalVersion = "21.3.0" -val javaVersion = "11" +val scalacVersion = "2.13.8" +val graalVersion = "21.3.0" +val javaVersion = "11" val defaultDevEnsoVersion = "0.0.0-dev" val ensoVersion = sys.env.getOrElse( "ENSO_VERSION", @@ -716,11 +713,11 @@ lazy val `profiling-utils` = project "org.netbeans.api" % "org-netbeans-modules-sampler" % netbeansApiVersion exclude ("org.netbeans.api", "org-openide-loaders") exclude ("org.netbeans.api", "org-openide-nodes") - exclude ("org.netbeans.api", "org-netbeans-api-progress-nb") - exclude ("org.netbeans.api", "org-netbeans-api-progress") - exclude ("org.netbeans.api", "org-openide-util-lookup") - exclude ("org.netbeans.api", "org-openide-util") - exclude ("org.netbeans.api", "org-openide-dialogs") + exclude("org.netbeans.api", "org-netbeans-api-progress-nb") + exclude("org.netbeans.api", "org-netbeans-api-progress") + exclude("org.netbeans.api", "org-openide-util-lookup") + exclude("org.netbeans.api", "org-openide-util") + exclude("org.netbeans.api", "org-openide-dialogs") exclude ("org.netbeans.api", "org-openide-filesystems") exclude ("org.netbeans.api", "org-openide-util-ui") exclude ("org.netbeans.api", "org-openide-awt") @@ -1006,11 +1003,11 @@ val truffleRunOptions = if (java.lang.Boolean.getBoolean("bench.compileOnly")) { } else { Seq( "-Dpolyglot.engine.IterativePartialEscape=true", - "-Dpolyglot.engine.BackgroundCompilation=false", - "-Dbench.compileOnly=true" + "-Dpolyglot.engine.BackgroundCompilation=false" ) } + val truffleRunOptionsSettings = Seq( fork := true, javaOptions ++= truffleRunOptions @@ -1295,11 +1292,6 @@ lazy val runtime = (project in file("engine/runtime")) "org.typelevel" %% "kind-projector" % kindProjectorVersion cross CrossVersion.full ) ) - .settings( - (Compile / compile / streams) := (Compile / compile / streams).dependsOn( - Def.taskDyn { Def.task { (Runtime/clean).value } } - ).value// CI HACK: REMOVE IT ASAP - ) .settings( (Compile / compile) := (Compile / compile) .dependsOn(Def.task { (Compile / sourceManaged).value.mkdirs }) From 40cbb70c891ac2429ef23b26fedfb05f581f2910 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 15:33:22 +0200 Subject: [PATCH 090/110] format it --- .../IndirectInvokeConversionNode.java | 4 +- .../callable/IndirectInvokeMethodNode.java | 4 +- .../node/callable/InvokeMethodNode.java | 26 ++++----- .../controlflow/caseexpr/ArrayBranchNode.java | 2 +- .../builtin/UniquelyConstructibleBuiltin.java | 2 +- .../expression/builtin/mutable/CopyNode.java | 3 +- .../expression/builtin/number/BigInteger.java | 8 +-- .../expression/builtin/number/Decimal.java | 8 +-- .../expression/builtin/number/Integer.java | 8 +-- .../builtin/number/SmallInteger.java | 8 +-- .../expression/builtin/ordering/Ordering.java | 24 ++------ .../org/enso/interpreter/runtime/Module.java | 56 +++++-------------- .../interpreter/runtime/builtin/Builtins.java | 52 +++++------------ .../interpreter/runtime/builtin/Error.java | 9 +-- .../interpreter/runtime/builtin/Number.java | 20 ++----- .../interpreter/runtime/builtin/System.java | 4 +- .../runtime/callable/UnresolvedSymbol.java | 4 +- .../callable/atom/AtomConstructor.java | 8 +-- .../runtime/callable/function/Function.java | 8 +-- .../enso/interpreter/runtime/data/Array.java | 16 ++---- .../runtime/data/EnsoTimeOfDay.java | 4 +- .../runtime/data/ManagedResource.java | 8 +-- .../enso/interpreter/runtime/data/Ref.java | 4 +- .../interpreter/runtime/data/text/Text.java | 16 ++---- .../runtime/number/EnsoBigInteger.java | 4 +- .../runtime/scope/ModuleScope.java | 24 ++------ .../interpreter/runtime/system/System.java | 4 +- .../interpreter/service/ExecutionService.java | 8 +-- .../org/enso/compiler/codegen/AstView.scala | 2 - .../enso/compiler/codegen/IrToTruffle.scala | 6 +- .../codegen/RuntimeStubsGenerator.scala | 4 +- .../scala/org/enso/compiler/core/IR.scala | 9 ++- .../compiler/pass/desugar/ComplexType.scala | 4 +- .../pass/resolve/ModuleAnnotations.scala | 4 +- .../pass/resolve/OverloadsResolution.scala | 2 +- .../compiler/phase/ExportsResolution.scala | 2 +- .../enso/compiler/phase/StubIrBuilder.scala | 2 +- .../job/ProgramExecutionSupport.scala | 2 +- .../test/pass/desugar/ComplexTypeTest.scala | 1 - .../resolve/DocumentationCommentsTest.scala | 3 +- .../resolve/GenerateDocumentationTest.scala | 3 +- .../interpreter/test/InterpreterTest.scala | 2 +- .../semantic/CompileDiagnosticsTest.scala | 4 +- .../builtins/ExecuteMethodImplGenerator.java | 5 +- .../dsl/builtins/MethodGenerator.java | 3 +- .../builtins/MethodNodeClassGenerator.java | 9 +-- .../builtins/SpecializedMethodsGenerator.java | 3 +- 47 files changed, 136 insertions(+), 280 deletions(-) diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeConversionNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeConversionNode.java index 0f5bbd21eb34..5912e49e3482 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeConversionNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeConversionNode.java @@ -26,9 +26,7 @@ @ImportStatic({HostMethodCallNode.PolyglotCallType.class, HostMethodCallNode.class}) public abstract class IndirectInvokeConversionNode extends Node { - /** - * @return a new indirect method invocation node - */ + /** @return a new indirect method invocation node */ public static IndirectInvokeConversionNode build() { return IndirectInvokeConversionNodeGen.create(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeMethodNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeMethodNode.java index a1b33c6c7ac9..7bdb2d3f257c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeMethodNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/IndirectInvokeMethodNode.java @@ -31,9 +31,7 @@ @ImportStatic({HostMethodCallNode.PolyglotCallType.class, HostMethodCallNode.class}) public abstract class IndirectInvokeMethodNode extends Node { - /** - * @return a new indirect method invocation node - */ + /** @return a new indirect method invocation node */ public static IndirectInvokeMethodNode build() { return IndirectInvokeMethodNodeGen.create(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeMethodNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeMethodNode.java index 1b97a7ec03dd..1de0aac138e7 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeMethodNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/callable/InvokeMethodNode.java @@ -248,7 +248,7 @@ Stateful doConvertDate( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit="10") TypesLibrary types, + @CachedLibrary(limit = "10") TypesLibrary types, @CachedLibrary(limit = "10") InteropLibrary interop, @Cached MethodResolverNode methodResolverNode) { var ctx = Context.get(this); @@ -266,8 +266,8 @@ Stateful doConvertDate( @Specialization( guards = { - "!types.hasType(self)", - "!types.hasSpecialDispatch(self)", + "!types.hasType(self)", + "!types.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == CONVERT_TO_DATE_TIME" }) Stateful doConvertDateTime( @@ -276,7 +276,7 @@ Stateful doConvertDateTime( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit="10") TypesLibrary types, + @CachedLibrary(limit = "10") TypesLibrary types, @CachedLibrary(limit = "10") InteropLibrary interop, @Cached MethodResolverNode methodResolverNode) { var ctx = Context.get(this); @@ -297,8 +297,8 @@ Stateful doConvertDateTime( @Specialization( guards = { - "!types.hasType(self)", - "!types.hasSpecialDispatch(self)", + "!types.hasType(self)", + "!types.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == CONVERT_TO_ZONED_DATE_TIME" }) Stateful doConvertZonedDateTime( @@ -307,7 +307,7 @@ Stateful doConvertZonedDateTime( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit="10") TypesLibrary types, + @CachedLibrary(limit = "10") TypesLibrary types, @CachedLibrary(limit = "10") InteropLibrary interop, @Cached MethodResolverNode methodResolverNode) { var ctx = Context.get(this); @@ -327,8 +327,8 @@ Stateful doConvertZonedDateTime( @Specialization( guards = { - "!types.hasType(self)", - "!types.hasSpecialDispatch(self)", + "!types.hasType(self)", + "!types.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == CONVERT_TO_TIME_ZONE" }) Stateful doConvertZone( @@ -337,7 +337,7 @@ Stateful doConvertZone( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit="10") TypesLibrary types, + @CachedLibrary(limit = "10") TypesLibrary types, @CachedLibrary(limit = "10") InteropLibrary interop, @Cached MethodResolverNode methodResolverNode) { var ctx = Context.get(this); @@ -355,8 +355,8 @@ Stateful doConvertZone( @Specialization( guards = { - "!types.hasType(self)", - "!types.hasSpecialDispatch(self)", + "!types.hasType(self)", + "!types.hasSpecialDispatch(self)", "getPolyglotCallType(self, symbol.getName(), interop) == CONVERT_TO_TIME_OF_DAY" }) Stateful doConvertTimeOfDay( @@ -365,7 +365,7 @@ Stateful doConvertTimeOfDay( UnresolvedSymbol symbol, Object self, Object[] arguments, - @CachedLibrary(limit="10") TypesLibrary types, + @CachedLibrary(limit = "10") TypesLibrary types, @CachedLibrary(limit = "10") InteropLibrary interop, @Cached MethodResolverNode methodResolverNode) { var ctx = Context.get(this); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ArrayBranchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ArrayBranchNode.java index b4bd857dd7f9..9cd3482af98b 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ArrayBranchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/controlflow/caseexpr/ArrayBranchNode.java @@ -31,7 +31,7 @@ public abstract class ArrayBranchNode extends BranchNode { * @return an array branch node */ public static ArrayBranchNode build(Type array, RootCallTarget branch) { - return ArrayBranchNodeGen.create(array, branch); + return ArrayBranchNodeGen.create(array, branch); } @Specialization diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/UniquelyConstructibleBuiltin.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/UniquelyConstructibleBuiltin.java index 1a31a388666d..f12a1461babf 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/UniquelyConstructibleBuiltin.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/UniquelyConstructibleBuiltin.java @@ -15,7 +15,7 @@ public final AtomConstructor getUniqueConstructor() { @Override protected final List getDeclaredConstructors() { - return List.of(new Cons( getName() + "_Data", getConstructorParamNames())); + return List.of(new Cons(getName() + "_Data", getConstructorParamNames())); } protected abstract List getConstructorParamNames(); 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 e87a27a90b67..3e742796e2e5 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 @@ -61,7 +61,6 @@ Object doPolyglotArray( @Fallback Object doOther(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.array(), src, "src"), this); + throw new PanicException(builtins.error().makeTypeError(builtins.array(), src, "src"), this); } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java index 6d8787459c9b..ef68428998f9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/BigInteger.java @@ -5,8 +5,8 @@ @BuiltinType public class BigInteger extends Builtin { - @Override - protected Class getSuperType() { - return Integer.class; - } + @Override + protected Class getSuperType() { + return Integer.class; + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java index 19c98922a357..77042f209fbc 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Decimal.java @@ -5,8 +5,8 @@ @BuiltinType(name = "Standard.Base.Data.Numbers.Decimal") public class Decimal extends Builtin { - @Override - protected Class getSuperType() { - return Number.class; - } + @Override + protected Class getSuperType() { + return Number.class; + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java index 66e233968901..2204ae3062c6 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/Integer.java @@ -5,8 +5,8 @@ @BuiltinType(name = "Standard.Base.Data.Numbers.Integer") public class Integer extends Builtin { - @Override - protected Class getSuperType() { - return Number.class; - } + @Override + protected Class getSuperType() { + return Number.class; + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java index e832ac5391d9..78b7201aa890 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/number/SmallInteger.java @@ -5,8 +5,8 @@ @BuiltinType public class SmallInteger extends Builtin { - @Override - protected Class getSuperType() { - return Integer.class; - } + @Override + protected Class getSuperType() { + return Integer.class; + } } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java index 10c98a32fb3d..af4e845d595c 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/ordering/Ordering.java @@ -31,44 +31,32 @@ public Atom fromJava(int ord) { } } - /** - * @return the Less constructor - */ + /** @return the Less constructor */ public AtomConstructor less() { return getConstructors()[0]; } - /** - * @return the Equal constructor - */ + /** @return the Equal constructor */ public AtomConstructor equal() { return getConstructors()[1]; } - /** - * @return the Greater constructor - */ + /** @return the Greater constructor */ public AtomConstructor greater() { return getConstructors()[2]; } - /** - * @return a new instance of Less - */ + /** @return a new instance of Less */ public Atom newLess() { return less().newInstance(); } - /** - * @return a new instance of Equal - */ + /** @return a new instance of Equal */ public Atom newEqual() { return equal().newInstance(); } - /** - * @return a new instance of Greater - */ + /** @return a new instance of Greater */ public Atom newGreater() { return greater().newInstance(); } 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 86f5b7287c68..c40190a3fb6c 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 @@ -214,16 +214,12 @@ public void unsetLiteralSource() { this.compilationStage = CompilationStage.INITIAL; } - /** - * @return the literal source of this module. - */ + /** @return the literal source of this module. */ public Rope getLiteralSource() { return sources.rope(); } - /** - * @return true if this module represents a synthetic (compiler-generated) module - */ + /** @return true if this module represents a synthetic (compiler-generated) module */ public boolean isSynthetic() { return synthetic; } @@ -315,9 +311,7 @@ private void disposeInteractive() { } } - /** - * @return the location of this module. - */ + /** @return the location of this module. */ public String getPath() { return sources.getPath(); } @@ -402,16 +396,12 @@ private void compile(Context context) throws IOException { context.getCompiler().run(this); } - /** - * @return IR defined by this module. - */ + /** @return IR defined by this module. */ public IR.Module getIr() { return ir; } - /** - * @return the current compilation stage of this module. - */ + /** @return the current compilation stage of this module. */ public CompilationStage getCompilationStage() { return compilationStage; } @@ -440,16 +430,12 @@ public void unsafeSetIr(IR.Module ir) { this.ir = ir; } - /** - * @return the runtime scope of this module. - */ + /** @return the runtime scope of this module. */ public ModuleScope getScope() { return scope; } - /** - * @return the qualified name of this module. - */ + /** @return the qualified name of this module. */ public QualifiedName getName() { return name; } @@ -467,9 +453,7 @@ public void renameProject(String newName) { this.name = name.renameProject(newName); } - /** - * @return the indexed flag. - */ + /** @return the indexed flag. */ public boolean isIndexed() { return isIndexed; } @@ -479,16 +463,12 @@ public void setIndexed(boolean indexed) { isIndexed = indexed; } - /** - * @return the source file of this module. - */ + /** @return the source file of this module. */ public TruffleFile getSourceFile() { return sources.file(); } - /** - * @return {@code true} if the module is interactive, {@code false} otherwise - */ + /** @return {@code true} if the module is interactive, {@code false} otherwise */ public boolean isInteractive() { return patchedValues != null; } @@ -503,23 +483,17 @@ public void unsafeBuildIrStub() { compilationStage = CompilationStage.AFTER_CODEGEN; } - /** - * @return the cache for this module - */ + /** @return the cache for this module */ public ModuleCache getCache() { return cache; } - /** - * @return {@code true} if the module was loaded from the cache, {@code false} otherwise - */ + /** @return {@code true} if the module was loaded from the cache, {@code false} otherwise */ public boolean wasLoadedFromCache() { return wasLoadedFromCache; } - /** - * @param wasLoadedFromCache whether or not the module was loaded from the cache - */ + /** @param wasLoadedFromCache whether or not the module was loaded from the cache */ public void setLoadedFromCache(boolean wasLoadedFromCache) { this.wasLoadedFromCache = wasLoadedFromCache; } @@ -532,9 +506,7 @@ public boolean hasCrossModuleLinks() { return hasCrossModuleLinks; } - /** - * @param hasCrossModuleLinks whether or not the module has cross-module links restored - */ + /** @param hasCrossModuleLinks whether or not the module has cross-module links restored */ public void setHasCrossModuleLinks(boolean hasCrossModuleLinks) { this.hasCrossModuleLinks = hasCrossModuleLinks; } 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 ed65432dbad0..2e2d9e4516ab 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 @@ -155,9 +155,7 @@ private void registerBuiltinMethods(ModuleScope scope, Language language) { } } - /** - * @return {@code true} if the IR has been initialized, otherwise {@code false} - */ + /** @return {@code true} if the IR has been initialized, otherwise {@code false} */ public boolean isIrInitialized() { return this.module.getIr() != null; } @@ -380,23 +378,17 @@ public Number number() { return number; } - /** - * @return the container for boolean constructors. - */ + /** @return the container for boolean constructors. */ public Boolean bool() { return bool; } - /** - * @return the ManagedResource constructor. - */ + /** @return the ManagedResource constructor. */ public Type managedResource() { return managedResource.getType(); } - /** - * @return the builtin Error types container. - */ + /** @return the builtin Error types container. */ public Error error() { return error; } @@ -474,65 +466,47 @@ public Type debug() { return debug.getType(); } - /** - * @return the {@code Project_Description} atom constructor - */ + /** @return the {@code Project_Description} atom constructor */ public ProjectDescription getProjectDescription() { return projectDescription; } - /** - * @return the {@code System} atom constructor. - */ + /** @return the {@code System} atom constructor. */ public System system() { return system; } - /** - * @return the Array constructor. - */ + /** @return the Array constructor. */ public Type array() { return array.getType(); } - /** - * @return the Ref constructor. - */ + /** @return the Ref constructor. */ public Type ref() { return ref.getType(); } - /** - * @return the container for polyglot-related builtins. - */ + /** @return the container for polyglot-related builtins. */ public Type polyglot() { return polyglot.getType(); } - /** - * @return the {@code Caught_Panic} atom constructor - */ + /** @return the {@code Caught_Panic} atom constructor */ public CaughtPanic caughtPanic() { return this.error.caughtPanic(); } - /** - * @return the {@code Panic} atom constructor - */ + /** @return the {@code Panic} atom constructor */ public Type panic() { return this.error.panic(); } - /** - * @return the container for ordering-related builtins - */ + /** @return the container for ordering-related builtins */ public Ordering ordering() { return ordering; } - /** - * @return the container for the dataflow error-related builtins - */ + /** @return the container for the dataflow error-related builtins */ public Type dataflowError() { return dataflowError.getType(); } 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 f0f8d78f306b..19be3d99758f 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 @@ -139,9 +139,7 @@ private Atom makeArithmeticError(Text reason) { return arithmeticError.newInstance(reason); } - /** - * @return An arithmetic error representing a too-large shift for the bit shift. - */ + /** @return An arithmetic error representing a too-large shift for the bit shift. */ public Atom getShiftAmountTooLargeError() { if (arithmeticErrorShiftTooBig == null) { transferToInterpreterAndInvalidate(); @@ -150,9 +148,7 @@ public Atom getShiftAmountTooLargeError() { return arithmeticErrorShiftTooBig; } - /** - * @return An Arithmetic error representing a division by zero. - */ + /** @return An Arithmetic error representing a division by zero. */ public Atom getDivideByZeroError() { if (arithmeticErrorDivideByZero == null) { transferToInterpreterAndInvalidate(); @@ -208,5 +204,4 @@ public Atom makeModuleDoesNotExistError(String name) { public Atom makeNotInvokableError(Object target) { return notInvokableError.newInstance(target); } - } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/Number.java index dd762f25b903..1430e131cca3 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 @@ -25,37 +25,27 @@ public Number(Builtins builtins) { decimal = builtins.getBuiltinType(Decimal.class); } - /** - * @return the Int64 atom constructor. - */ + /** @return the Int64 atom constructor. */ public Type getSmallInteger() { return smallInteger.getType(); } - /** - * @return the Big_Integer atom constructor. - */ + /** @return the Big_Integer atom constructor. */ public Type getBigInteger() { return bigInteger.getType(); } - /** - * @return the Integer atom constructor - */ + /** @return the Integer atom constructor */ public Type getInteger() { return integer.getType(); } - /** - * @return the Number atom constructor - */ + /** @return the Number atom constructor */ public Type getNumber() { return number.getType(); } - /** - * @return the Decimal atom constructor - */ + /** @return the Decimal atom constructor */ public Type getDecimal() { return decimal.getType(); } 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 47d511891951..11592f0db7e3 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 @@ -14,9 +14,7 @@ public System(Builtins builtins) { systemProcessResult = builtins.getBuiltinType(SystemProcessResult.class); } - /** - * @return the atom constructor for {@code Process_Result}. - */ + /** @return the atom constructor for {@code Process_Result}. */ 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/callable/UnresolvedSymbol.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedSymbol.java index 2fc272f3f9ea..6fcf325f493a 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedSymbol.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/UnresolvedSymbol.java @@ -40,9 +40,7 @@ public String getName() { return name; } - /** - * @return the scope this symbol was used in. - */ + /** @return the scope this symbol was used in. */ public ModuleScope getScope() { return scope; } 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 a25f28e75a08..6dca2145fdec 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 @@ -258,16 +258,12 @@ String toDisplayString(boolean allowSideEffects) { return "Constructor<" + name + ">"; } - /** - * @return the fully qualified name of this constructor. - */ + /** @return the fully qualified name of this constructor. */ public QualifiedName getQualifiedName() { return definitionScope.getModule().getName().createChild(getName()); } - /** - * @return the fields defined by this constructor. - */ + /** @return the fields defined by this constructor. */ public ArgumentDefinition[] getFields() { return constructorFunction.getSchema().getArgumentInfos(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/Function.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/Function.java index bac5f04dfbfa..d479baf3a803 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/Function.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/callable/function/Function.java @@ -116,16 +116,12 @@ public RootCallTarget getCallTarget() { return callTarget; } - /** - * @return the name of this function. - */ + /** @return the name of this function. */ public String getName() { return getCallTarget().getRootNode().getName(); } - /** - * @return the source section this function was defined in. - */ + /** @return the source section this function was defined in. */ public SourceSection getSourceSection() { return getCallTarget().getRootNode().getSourceSection(); } 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 eaefa5b12519..d428ea01e5c7 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 @@ -58,9 +58,7 @@ public Array(long size) { this.items = new Object[(int) size]; } - /** - * @return the elements of this array as a java array. - */ + /** @return the elements of this array as a java array. */ public Object[] getItems() { return items; } @@ -90,25 +88,19 @@ public Object readArrayElement(long index) throws InvalidArrayIndexException { return items[(int) index]; } - /** - * @return the size of this array - */ + /** @return the size of this array */ @Builtin.Method(description = "Returns the size of this array.") public long length() { return this.getItems().length; } - /** - * @return an empty array - */ + /** @return an empty array */ @Builtin.Method(description = "Creates an empty Array") public static Object empty() { return new Array(); } - /** - * @return an identity array - */ + /** @return an identity array */ @Builtin.Method(description = "Identity on arrays, implemented for protocol completeness.") public Object toArray() { return this; diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeOfDay.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeOfDay.java index 58a600394b0b..21935c571ca4 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeOfDay.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/EnsoTimeOfDay.java @@ -32,9 +32,7 @@ public EnsoTimeOfDay(LocalTime localTime) { name = "parse_builtin", description = "Constructs a new DateTime from text with optional pattern") @Builtin.Specialize - @Builtin.WrapException( - from = DateTimeParseException.class, - to = PolyglotError.class) + @Builtin.WrapException(from = DateTimeParseException.class, to = PolyglotError.class) public static EnsoTimeOfDay parse(String text) { return new EnsoTimeOfDay(LocalTime.parse(text)); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/ManagedResource.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/ManagedResource.java index 2f6a92304860..98f4b71061c5 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/ManagedResource.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/ManagedResource.java @@ -28,16 +28,12 @@ public ManagedResource(Object resource) { this.phantomReference = null; } - /** - * @return the underlying resource - */ + /** @return the underlying resource */ public Object getResource() { return resource; } - /** - * @return the phantom reference tracking this managed resource - */ + /** @return the phantom reference tracking this managed resource */ public PhantomReference getPhantomReference() { return phantomReference; } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Ref.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Ref.java index 7ca86fbfc889..aaf241da9835 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Ref.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Ref.java @@ -24,9 +24,7 @@ public Ref(Object value) { this.value = value; } - /** - * @return the current value of the reference. - */ + /** @return the current value of the reference. */ @Builtin.Method(name = "get", description = "Gets the value stored in the reference") public Object getValue() { return value; 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 781c558b02e7..8f384d1774aa 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 @@ -135,23 +135,17 @@ String toDisplayString( return "'" + replaced + "'"; } - /** - * @return true if this text wraps a string literal and does not require any optimization. - */ + /** @return true if this text wraps a string literal and does not require any optimization. */ public boolean isFlat() { return isFlat; } - /** - * @param flat the new value of the isFlat flag. - */ + /** @param flat the new value of the isFlat flag. */ public void setFlat(boolean flat) { isFlat = flat; } - /** - * @return the contents of this text. - */ + /** @return the contents of this text. */ public Object getContents() { return contents; } @@ -165,9 +159,7 @@ public void setContents(Object contents) { this.contents = contents; } - /** - * @return the lock required for modification of this text. - */ + /** @return the lock required for modification of this text. */ public Lock getLock() { return lock; } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/number/EnsoBigInteger.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/number/EnsoBigInteger.java index 1cb876530a72..b3babe502425 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/number/EnsoBigInteger.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/number/EnsoBigInteger.java @@ -28,9 +28,7 @@ public EnsoBigInteger(BigInteger value) { this.value = value; } - /** - * @return the contained {@link BigInteger}. - */ + /** @return the contained {@link BigInteger}. */ public BigInteger getValue() { return value; } 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 a09280aa877e..cf8a5dc3e9cb 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 @@ -54,23 +54,17 @@ public void registerType(Type type) { types.put(type.getName(), type); } - /** - * @return the associated type of this module. - */ + /** @return the associated type of this module. */ public Type getAssociatedType() { return associatedType; } - /** - * @return the module associated with this scope. - */ + /** @return the module associated with this scope. */ public Module getModule() { return module; } - /** - * @return the set of modules imported by this module. - */ + /** @return the set of modules imported by this module. */ public Set getImports() { return imports; } @@ -296,23 +290,17 @@ public Optional getType(String name) { return Optional.ofNullable(types.get(name)); } - /** - * @return the raw method map held by this module - */ + /** @return the raw method map held by this module */ public Map> getMethods() { return methods; } - /** - * @return the raw conversions map held by this module - */ + /** @return the raw conversions map held by this module */ public Map> getConversions() { return conversions; } - /** - * @return the polyglot symbols imported into this scope. - */ + /** @return the polyglot symbols imported into this scope. */ public Map getPolyglotSymbols() { return polyglotSymbols; } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/system/System.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/system/System.java index 75d425a836f6..87f98be3f59f 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/system/System.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/system/System.java @@ -51,9 +51,7 @@ public static void exit(long code) { @Builtin.Specialize @Builtin.Method(description = "Create a system process, returning the exit code.") @Builtin.WrapException(from = IOException.class, to = PanicException.class) - @Builtin.WrapException( - from = InterruptedException.class, - to = PanicException.class) + @Builtin.WrapException(from = InterruptedException.class, to = PanicException.class) @CompilerDirectives.TruffleBoundary public static Atom createProcess( Context ctx, diff --git a/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java b/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java index 4f1cd520d9e4..4d3a518d4924 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/service/ExecutionService.java @@ -79,16 +79,12 @@ public ExecutionService( this.connectedLockManager = connectedLockManager; } - /** - * @return the language context. - */ + /** @return the language context. */ public Context getContext() { return context; } - /** - * @return the execution service logger. - */ + /** @return the execution service logger. */ public TruffleLogger getLogger() { return logger; } diff --git a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala index ba46160e8865..b8c3fdd4417a 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/codegen/AstView.scala @@ -479,8 +479,6 @@ object AstView { } } - - /** A union type for application matchers. */ sealed trait MethodOrExpr 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 ef99377476a9..939d301912dc 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 @@ -492,7 +492,8 @@ class IrToTruffle( definitionModule .unsafeAsModule() .getScope - .getTypes.get(tp.name) + .getTypes + .get(tp.name) case BindingsMap.ResolvedModule(module) => module.unsafeAsModule().getScope.getAssociatedType case BindingsMap.ResolvedConstructor(_, _) => @@ -1185,7 +1186,8 @@ class IrToTruffle( if (c == null) { throw new CompilerError(s"Constructor for $cons is null") } - ConstructorNode.build(c + ConstructorNode.build( + c // definitionModule // .unsafeAsModule() // .getScope 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 18da73cf57bc..58f407dc868c 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 @@ -31,7 +31,9 @@ class RuntimeStubsGenerator(builtins: Builtins) { throw new CompilerError("Unknown @Builtin_Type " + tp.name) } if ( - Set(tp.members: _*) != Set(builtinType.getConstructors.toIndexedSeq: _*) + Set(tp.members: _*) != Set( + builtinType.getConstructors.toIndexedSeq: _* + ) .map(_.getName) ) { throw new CompilerError( 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 35bb72f83f48..5fb7d840c0a8 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 @@ -6706,7 +6706,8 @@ object IR { override def diagnosticKeys(): Array[Any] = Array(ir.showCode(), reason) } - case class NonUnitTypeUsedOnValueLevel(ir: IR.Name, context: String) extends Warning { + case class NonUnitTypeUsedOnValueLevel(ir: IR.Name, context: String) + extends Warning { /** @return a human-readable description of this error condition. */ @@ -7010,7 +7011,7 @@ object IR { s"but polyglot symbols are not allowed in $context." } - /** An error coming from an unexpected occurence of a constructor. + /** An error coming from an unexpected occurence of a constructor. * * @param context the description of a context in which the error * happened. @@ -7018,11 +7019,9 @@ object IR { case class UnexpectedConstructor(context: String) extends Reason { override def explain(originalName: Name): String = s"The name ${originalName.name} resolved to a constructor, " + - s"but constructors are not allowed in $context." + s"but constructors are not allowed in $context." } - - /** An error coming from an unexpected occurence of a static method. * * @param context the description of a context in which the error 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 82c7f17f00e1..9406d0167d3d 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 @@ -204,7 +204,9 @@ case object ComplexType extends IRPass { val withDoc = typ .getMetadata(DocumentationComments) - .map(ann => withAnnotations.updateMetadata(DocumentationComments -->> ann)) + .map(ann => + withAnnotations.updateMetadata(DocumentationComments -->> ann) + ) .getOrElse(sumType) withDoc :: allEntities diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/ModuleAnnotations.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/ModuleAnnotations.scala index 479aff80c1e0..e7b3a75aa392 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/ModuleAnnotations.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/ModuleAnnotations.scala @@ -72,7 +72,9 @@ case object ModuleAnnotations extends IRPass { * @param typ the type in which to resolve annotations * @return `typ` with all top-level annotations resolved */ - def resolveComplexType(typ: Definition.SugaredType): Definition.SugaredType = { + def resolveComplexType( + typ: Definition.SugaredType + ): Definition.SugaredType = { var lastAnnotations: Seq[IR.Name.Annotation] = Seq() val newBodyElems = typ.body.flatMap { case ann: Name.Annotation => diff --git a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala index ee6b1e27755b..f0ae65d7a343 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/pass/resolve/OverloadsResolution.scala @@ -47,7 +47,7 @@ case object OverloadsResolution extends IRPass { ir: IR.Module, @unused moduleContext: ModuleContext ): IR.Module = { - var seenTypes: Set[String] = Set() + var seenTypes: Set[String] = Set() var seenMethods: Map[Option[String], Set[String]] = Map() val types = ir.bindings.collect { diff --git a/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala b/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala index 7793e672ba8c..2aca47ce6e8d 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/phase/ExportsResolution.scala @@ -167,7 +167,7 @@ class ExportsResolution { modules.foreach { module => val bindings = getBindings(module) val ownTypes = bindings.types.map { tp => - val sym = List(ResolvedType(ModuleReference.Concrete(module), tp)) + val sym = List(ResolvedType(ModuleReference.Concrete(module), tp)) (tp.name, sym) } val ownMethods = bindings.moduleMethods.map { method => diff --git a/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala b/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala index 0dc3cdea9fea..4e8cfcbcef11 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/phase/StubIrBuilder.scala @@ -57,7 +57,7 @@ object StubIrBuilder { moduleMethods, ModuleReference.Concrete(module) ) - meta.exportedSymbols = exportedBindings.toMap + meta.exportedSymbols = exportedBindings.toMap ir.updateMetadata(BindingAnalysis -->> meta) } } diff --git a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ProgramExecutionSupport.scala b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ProgramExecutionSupport.scala index 087aa34a75fe..c4a568af400c 100644 --- a/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ProgramExecutionSupport.scala +++ b/engine/runtime/src/main/scala/org/enso/interpreter/instrument/job/ProgramExecutionSupport.scala @@ -31,10 +31,10 @@ import org.enso.interpreter.runtime.error.{DataflowError, PanicSentinel} import org.enso.interpreter.runtime.`type`.Types import org.enso.interpreter.runtime.control.ThreadInterruptedException import org.enso.interpreter.service.error.{ - TypeNotFoundException, MethodNotFoundException, ModuleNotFoundForExpressionIdException, ServiceException, + TypeNotFoundException, VisualisationException } import org.enso.polyglot.LanguageInfo diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala index 2fc9b1793ef7..0b716d8459e4 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/desugar/ComplexTypeTest.scala @@ -97,7 +97,6 @@ class ComplexTypeTest extends CompilerTest { f.typeName.get.name shouldEqual "Maybe" } - "have type signatures copied to above each method" in { ir.bindings(2) shouldBe an[IR.Type.Ascription] ir.bindings(4) shouldBe an[IR.Type.Ascription] diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala index 37be085abb02..1e89fb20d112 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/DocumentationCommentsTest.scala @@ -279,7 +279,8 @@ class DocumentationCommentsTest extends CompilerTest with Inside { | ## the return | 0 |""".stripMargin.preprocessModule.resolve - val tp = ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.SugaredType] + val tp = + ir.bindings.head.asInstanceOf[IR.Module.Scope.Definition.SugaredType] getDoc(tp) shouldEqual " the type Foo" val t1 = tp.body.head getDoc(t1) shouldEqual " the constructor Bar" diff --git a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GenerateDocumentationTest.scala b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GenerateDocumentationTest.scala index b8ab9d258989..bb4d0dc61f93 100644 --- a/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GenerateDocumentationTest.scala +++ b/engine/runtime/src/test/scala/org/enso/compiler/test/pass/resolve/GenerateDocumentationTest.scala @@ -191,7 +191,8 @@ class GenerateDocumentationTest extends CompilerTest with Inside { | ## the return | 0 |""".stripMargin.preprocessModule.resolve - val tp = ir.bindings(0).asInstanceOf[IR.Module.Scope.Definition.SugaredType] + val tp = + ir.bindings(0).asInstanceOf[IR.Module.Scope.Definition.SugaredType] getDoc(tp) shouldEqual DocParserWrapper.runOnPureDoc( " the type Foo" ) diff --git a/engine/runtime/src/test/scala/org/enso/interpreter/test/InterpreterTest.scala b/engine/runtime/src/test/scala/org/enso/interpreter/test/InterpreterTest.scala index 1d80f1257a0d..ce0f7b681e29 100644 --- a/engine/runtime/src/test/scala/org/enso/interpreter/test/InterpreterTest.scala +++ b/engine/runtime/src/test/scala/org/enso/interpreter/test/InterpreterTest.scala @@ -67,7 +67,7 @@ case class IdsInstrumenter(instrument: CodeIdsTestInstrument) { if (!listener.isSuccessful) { Assertions.fail( s"Node with id ${listener.getId} does not exist or did not return the" + - s" correct value (expected ${listener.getExpectedResult}." + s" correct value (expected ${listener.getExpectedResult}." ) } } 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 8e019859acd9..3dd8643908f7 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 @@ -44,7 +44,9 @@ class CompileDiagnosticsTest extends InterpreterTest { | |main = Panic.catch_primitive foo caught_panic->caught_panic.payload.to_text |""".stripMargin - eval(code) shouldEqual "(Compile_Error_Data 'Variable x is being redefined.')" + eval( + code + ) shouldEqual "(Compile_Error_Data 'Variable x is being redefined.')" } "surface non-existent variable errors in the language" in { diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/ExecuteMethodImplGenerator.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/ExecuteMethodImplGenerator.java index b9eed95b8ae5..916db80c8648 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/ExecuteMethodImplGenerator.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/ExecuteMethodImplGenerator.java @@ -136,10 +136,7 @@ private boolean needsContext(List params) { return result || params.stream().anyMatch(p -> p.needsToHostTranslation()); } - public List generate( - ProcessingEnvironment processingEnv, - String name, - String owner) { + public List generate(ProcessingEnvironment processingEnv, String name, String owner) { SafeWrapException[] exceptionWrappers = wrapExceptions(processingEnv, method); boolean wrapsExceptions = exceptionWrappers.length != 0; diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodGenerator.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodGenerator.java index 558687b645b7..9ed8b9bb75b1 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodGenerator.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodGenerator.java @@ -229,8 +229,7 @@ private SafeWrapException[] extractClassElementFromAnnotationContainer( } } if (valueFrom != null && valueTo != null) { - SafeWrapException converted = - new SafeWrapException(valueFrom, valueTo); + SafeWrapException converted = new SafeWrapException(valueFrom, valueTo); wrappedExceptions.add(converted); } } diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodNodeClassGenerator.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodNodeClassGenerator.java index a68ed5b57982..2e9a45fa7071 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodNodeClassGenerator.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/MethodNodeClassGenerator.java @@ -19,9 +19,7 @@ public abstract class MethodNodeClassGenerator { ClassName stdlibOwner; public MethodNodeClassGenerator( - ClassName builtinNode, - ClassName ownerClazz, - ClassName stdlibOwner) { + ClassName builtinNode, ClassName ownerClazz, ClassName stdlibOwner) { this.builtinNode = builtinNode; this.ownerClazz = ownerClazz; this.stdlibOwner = stdlibOwner; @@ -76,10 +74,7 @@ public void generate( out.println("public class " + builtinNode.jvmFriendlyName() + " extends Node {"); out.println(); } - for (String line : - methodsGen() - .generate( - processingEnv, ownerMethodName, ownerClazz.name())) { + for (String line : methodsGen().generate(processingEnv, ownerMethodName, ownerClazz.name())) { out.println(" " + line); } out.println(); diff --git a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializedMethodsGenerator.java b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializedMethodsGenerator.java index 482e705f87d5..1895c0785444 100644 --- a/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializedMethodsGenerator.java +++ b/lib/scala/interpreter-dsl/src/main/java/org/enso/interpreter/dsl/builtins/SpecializedMethodsGenerator.java @@ -280,8 +280,7 @@ protected List specialize( specializationDeclaration.add(" " + line); } for (int i = 0; i < methodInfo.exceptionWrappers.length; i++) { - specializationDeclaration.addAll( - methodInfo.exceptionWrappers[i].toCatchClause()); + specializationDeclaration.addAll(methodInfo.exceptionWrappers[i].toCatchClause()); } specializationDeclaration.add(" }"); } else { From 552166fe2362cecb13d6567d4348b92f685a3bc1 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 15:36:31 +0200 Subject: [PATCH 091/110] changelog it --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf69b661a3f0..5bed8dcbf929 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -338,6 +338,8 @@ - [Support pattern matching on constants][3641] - [Builtin Date_Time, Time_Of_Day and Zone types for better polyglot support][3658] +- [Implement new specification of data types: `type` has a runtime + representation, every atom has a type][3671] [3227]: https://github.com/enso-org/enso/pull/3227 [3248]: https://github.com/enso-org/enso/pull/3248 @@ -381,6 +383,7 @@ [3637]: https://github.com/enso-org/enso/pull/3637 [3641]: https://github.com/enso-org/enso/pull/3641 [3658]: https://github.com/enso-org/enso/pull/3658 +[3671]: https://github.com/enso-org/enso/pull/3671 # Enso 2.0.0-alpha.18 (2021-10-12) From 034b74f98f2e0adaee7fc3bcf3f6921b7dfe78a4 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 20:49:47 +0200 Subject: [PATCH 092/110] some CR feedback; --- .../atom/GetFieldWithMatchNode.java | 6 +- .../node/expression/builtin/Builtin.java | 8 +-- .../builtin/error/NoSuchFieldError.java | 14 +++++ .../interpreter/runtime/builtin/Builtins.java | 59 ++++++++++++++----- .../interpreter/runtime/builtin/Error.java | 15 ++++- .../enso/interpreter/runtime/data/Type.java | 17 +++--- .../library/dispatch/TypesLibrary.java | 8 +-- .../runtime/library/types/TypesLibrary.java | 28 --------- .../enso/compiler/codegen/IrToTruffle.scala | 11 +--- .../pass/analyse/BindingAnalysis.scala | 1 - 10 files changed, 93 insertions(+), 74 deletions(-) create mode 100644 engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchFieldError.java delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/library/types/TypesLibrary.java diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldWithMatchNode.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldWithMatchNode.java index f97115a7daa2..4dc55a529f96 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldWithMatchNode.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/atom/GetFieldWithMatchNode.java @@ -10,6 +10,7 @@ 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.data.text.Text; import org.enso.interpreter.runtime.data.Type; import org.enso.interpreter.runtime.error.PanicException; import org.enso.interpreter.runtime.state.Stateful; @@ -35,6 +36,7 @@ public int getIndex() { } private final String name; + private final Text nameText; private final Type type; private final @CompilerDirectives.CompilationFinal(dimensions = 1) GetterPair[] getterPairs; @@ -49,6 +51,7 @@ public GetFieldWithMatchNode( super(language); this.name = name; this.type = type; + this.nameText = Text.create(name); this.getterPairs = getterPairs; } @@ -64,7 +67,8 @@ public Stateful execute(VirtualFrame frame) { } } throw new PanicException( - Context.get(this).getBuiltins().error().makeInexhaustivePatternMatchError(atom), this); + Context.get(this).getBuiltins().error().getNoSuchFieldError().newInstance(atom, nameText), + this); } @Override diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java index 2fada37bd6eb..2aa42abe72e9 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/Builtin.java @@ -1,8 +1,8 @@ package org.enso.interpreter.node.expression.builtin; import com.oracle.truffle.api.CompilerDirectives; +import org.enso.interpreter.Language; 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.Type; import org.enso.interpreter.runtime.scope.ModuleScope; @@ -51,12 +51,12 @@ protected List getDeclaredConstructors() { return List.of(); } - public final void initialize(ModuleScope scope, Map, Builtin> builtins) { + public final void initialize(Language language, ModuleScope scope, Map, Builtin> builtins) { if (type == null) { Type supertype = null; if (getSuperType() != null) { var s = builtins.get(getSuperType()); - s.initialize(scope, builtins); + s.initialize(language, scope, builtins); supertype = s.getType(); } type = new Type(name, scope, supertype, true); @@ -68,7 +68,7 @@ public final void initialize(ModuleScope scope, Map, Bu constructors[i] = conses.get(i).build(scope, type); } } - type.generateGetters(Arrays.asList(constructors)); + type.generateGetters(language, Arrays.asList(constructors)); postInitialize(); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchFieldError.java b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchFieldError.java new file mode 100644 index 000000000000..aeded5abc55f --- /dev/null +++ b/engine/runtime/src/main/java/org/enso/interpreter/node/expression/builtin/error/NoSuchFieldError.java @@ -0,0 +1,14 @@ +package org.enso.interpreter.node.expression.builtin.error; + +import org.enso.interpreter.dsl.BuiltinType; +import org.enso.interpreter.node.expression.builtin.UniquelyConstructibleBuiltin; + +import java.util.List; + +@BuiltinType +public class NoSuchFieldError extends UniquelyConstructibleBuiltin { + @Override + protected List getConstructorParamNames() { + return List.of("value", "field_name"); + } +} 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 2e2d9e4516ab..9d6f65b6eaf6 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 @@ -93,7 +93,7 @@ public Builtins(Context context) { module = Module.empty(QualifiedName.fromString(MODULE_NAME), null, null); scope = module.compileScope(context); - builtins = readBuiltinTypesMetadata(scope); + builtins = readBuiltinTypesMetadata(language, scope); builtinsByName = builtins.values().stream().collect(Collectors.toMap(v -> v.getType().getName(), v -> v)); builtinMethodNodes = readBuiltinMethodsMetadata(scope); @@ -155,7 +155,9 @@ private void registerBuiltinMethods(ModuleScope scope, Language language) { } } - /** @return {@code true} if the IR has been initialized, otherwise {@code false} */ + /** + * @return {@code true} if the IR has been initialized, otherwise {@code false} + */ public boolean isIrInitialized() { return this.module.getIr() != null; } @@ -194,7 +196,8 @@ public void initializeBuiltinsIr(FreshNameSupply freshNameSupply, Passes passes) * * @param scope Builtins scope */ - private Map, Builtin> readBuiltinTypesMetadata(ModuleScope scope) { + private Map, Builtin> readBuiltinTypesMetadata( + Language language, ModuleScope scope) { ClassLoader classLoader = getClass().getClassLoader(); List lines; try (InputStream resource = classLoader.getResourceAsStream(TypeProcessor.META_PATH)) { @@ -230,7 +233,7 @@ private Map, Builtin> readBuiltinTypesMetadata(ModuleSc } }) .collect(Collectors.toMap(Builtin::getClass, b -> b)); - builtins.values().forEach(b -> b.initialize(scope, builtins)); + builtins.values().forEach(b -> b.initialize(language, scope, builtins)); return builtins; } @@ -378,17 +381,23 @@ public Number number() { return number; } - /** @return the container for boolean constructors. */ + /** + * @return the container for boolean constructors. + */ public Boolean bool() { return bool; } - /** @return the ManagedResource constructor. */ + /** + * @return the ManagedResource constructor. + */ public Type managedResource() { return managedResource.getType(); } - /** @return the builtin Error types container. */ + /** + * @return the builtin Error types container. + */ public Error error() { return error; } @@ -466,47 +475,65 @@ public Type debug() { return debug.getType(); } - /** @return the {@code Project_Description} atom constructor */ + /** + * @return the {@code Project_Description} atom constructor + */ public ProjectDescription getProjectDescription() { return projectDescription; } - /** @return the {@code System} atom constructor. */ + /** + * @return the {@code System} atom constructor. + */ public System system() { return system; } - /** @return the Array constructor. */ + /** + * @return the Array constructor. + */ public Type array() { return array.getType(); } - /** @return the Ref constructor. */ + /** + * @return the Ref constructor. + */ public Type ref() { return ref.getType(); } - /** @return the container for polyglot-related builtins. */ + /** + * @return the container for polyglot-related builtins. + */ public Type polyglot() { return polyglot.getType(); } - /** @return the {@code Caught_Panic} atom constructor */ + /** + * @return the {@code Caught_Panic} atom constructor + */ public CaughtPanic caughtPanic() { return this.error.caughtPanic(); } - /** @return the {@code Panic} atom constructor */ + /** + * @return the {@code Panic} atom constructor + */ public Type panic() { return this.error.panic(); } - /** @return the container for ordering-related builtins */ + /** + * @return the container for ordering-related builtins + */ public Ordering ordering() { return ordering; } - /** @return the container for the dataflow error-related builtins */ + /** + * @return the container for the dataflow error-related builtins + */ public Type dataflowError() { return dataflowError.getType(); } 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 19be3d99758f..e79e83f59d6d 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 @@ -2,6 +2,7 @@ import com.oracle.truffle.api.CompilerDirectives; import org.enso.interpreter.node.expression.builtin.error.*; +import org.enso.interpreter.node.expression.builtin.error.NoSuchFieldError; import org.enso.interpreter.node.expression.builtin.error.NoSuchMethodError; import org.enso.interpreter.runtime.callable.UnresolvedConversion; import org.enso.interpreter.runtime.callable.UnresolvedSymbol; @@ -32,6 +33,7 @@ public class Error { private final ModuleDoesNotExist moduleDoesNotExistError; private final NotInvokableError notInvokableError; private final InvalidConversionTargetError invalidConversionTargetError; + private final NoSuchFieldError noSuchFieldError; private final Panic panic; private final CaughtPanic caughtPanic; @@ -61,6 +63,7 @@ public Error(Builtins builtins, Context context) { moduleDoesNotExistError = builtins.getBuiltinType(ModuleDoesNotExist.class); notInvokableError = builtins.getBuiltinType(NotInvokableError.class); invalidConversionTargetError = builtins.getBuiltinType(InvalidConversionTargetError.class); + noSuchFieldError = builtins.getBuiltinType(NoSuchFieldError.class); panic = builtins.getBuiltinType(Panic.class); caughtPanic = builtins.getBuiltinType(CaughtPanic.class); } @@ -104,6 +107,10 @@ public Atom makeNoSuchMethodError(Object target, UnresolvedSymbol symbol) { return noSuchMethodError.newInstance(target, symbol); } + public NoSuchFieldError getNoSuchFieldError() { + return noSuchFieldError; + } + public Atom makeNoSuchConversionError( Object target, Object that, UnresolvedConversion conversion) { return noSuchConversionError.newInstance(target, that, conversion); @@ -139,7 +146,9 @@ private Atom makeArithmeticError(Text reason) { return arithmeticError.newInstance(reason); } - /** @return An arithmetic error representing a too-large shift for the bit shift. */ + /** + * @return An arithmetic error representing a too-large shift for the bit shift. + */ public Atom getShiftAmountTooLargeError() { if (arithmeticErrorShiftTooBig == null) { transferToInterpreterAndInvalidate(); @@ -148,7 +157,9 @@ public Atom getShiftAmountTooLargeError() { return arithmeticErrorShiftTooBig; } - /** @return An Arithmetic error representing a division by zero. */ + /** + * @return An Arithmetic error representing a division by zero. + */ public Atom getDivideByZeroError() { if (arithmeticErrorDivideByZero == null) { transferToInterpreterAndInvalidate(); diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java index 2b915323087b..c1a6efb99857 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/data/Type.java @@ -4,20 +4,18 @@ import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.RootCallTarget; import com.oracle.truffle.api.Truffle; -import com.oracle.truffle.api.dsl.Cached; -import com.oracle.truffle.api.dsl.Specialization; import com.oracle.truffle.api.interop.InteropLibrary; import com.oracle.truffle.api.interop.TruffleObject; import com.oracle.truffle.api.library.CachedLibrary; import com.oracle.truffle.api.library.ExportLibrary; import com.oracle.truffle.api.library.ExportMessage; import com.oracle.truffle.api.nodes.RootNode; +import org.enso.interpreter.Constants; +import org.enso.interpreter.Language; import org.enso.interpreter.node.expression.atom.ConstantNode; import org.enso.interpreter.node.expression.atom.GetFieldNode; import org.enso.interpreter.node.expression.atom.GetFieldWithMatchNode; import org.enso.interpreter.runtime.Context; -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.AtomConstructor; import org.enso.interpreter.runtime.callable.function.Function; @@ -99,7 +97,7 @@ public Type getSupertype() { return supertype; } - public void generateGetters(List constructors) { + public void generateGetters(Language language, List constructors) { if (gettersGenerated) return; gettersGenerated = true; var roots = new HashMap(); @@ -119,7 +117,7 @@ public void generateGetters(List constructors) { roots.put( name, new GetFieldWithMatchNode( - null, name, this, fields.toArray(new GetFieldWithMatchNode.GetterPair[0]))); + language, name, this, fields.toArray(new GetFieldWithMatchNode.GetterPair[0]))); }); } else { var cons = constructors.get(0); @@ -128,7 +126,7 @@ public void generateGetters(List constructors) { field -> { roots.put( field.getName(), - new GetFieldNode(null, field.getPosition(), this, field.getName())); + new GetFieldNode(language, field.getPosition(), this, field.getName())); }); } roots.forEach( @@ -139,7 +137,10 @@ public void generateGetters(List constructors) { callTarget, null, new FunctionSchema( - new ArgumentDefinition(0, "this", ArgumentDefinition.ExecutionMode.EXECUTE))); + new ArgumentDefinition( + 0, + Constants.Names.SELF_ARGUMENT, + ArgumentDefinition.ExecutionMode.EXECUTE))); definitionScope.registerMethod(this, name, f); }); } diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/TypesLibrary.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/TypesLibrary.java index cebed2a59848..b22181f34333 100644 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/TypesLibrary.java +++ b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/dispatch/TypesLibrary.java @@ -59,12 +59,10 @@ public boolean hasSpecialDispatch(Object receiver) { } /** - * Looks up the method definition for the given receiver and symbol + * Returns the receiver Type. * - * @param receiver the method call receiver - * @param symbol the symbol being dispatched - * @return the corresponding function definition - * @throws NoSuchMethodException if the function definition could not be found + * @param receiver the typed object + * @return the corresponding type */ @GenerateLibrary.Abstract(ifExported = {"hasType"}) public Type getType(Object receiver) { diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/types/TypesLibrary.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/types/TypesLibrary.java deleted file mode 100644 index cc96afbe2d2b..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/library/types/TypesLibrary.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.enso.interpreter.runtime.library.types; - -import com.oracle.truffle.api.library.GenerateLibrary; -import com.oracle.truffle.api.library.Library; -import com.oracle.truffle.api.library.LibraryFactory; -import org.enso.interpreter.runtime.data.Type; - -@GenerateLibrary -public abstract class TypesLibrary extends Library { - public static LibraryFactory getFactory() { - return FACTORY; - } - - public static TypesLibrary getUncached() { - return FACTORY.getUncached(); - } - - private static final LibraryFactory FACTORY = - LibraryFactory.resolve(TypesLibrary.class); - - public Type getType(Object receiver) { - return null; - } - - public boolean hasSpecialMethodDispatch(Object receiver) { - return false; - } -} 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 939d301912dc..625278b65515 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 @@ -248,7 +248,7 @@ class IrToTruffle( } } val tp = moduleScope.getTypes.get(tpDef.name.name) - tp.generateGetters(atomConstructors.asJava) + tp.generateGetters(language, atomConstructors.asJava) } // Register the method definitions in scope @@ -1186,14 +1186,7 @@ class IrToTruffle( if (c == null) { throw new CompilerError(s"Constructor for $cons is null") } - ConstructorNode.build( - c -// definitionModule -// .unsafeAsModule() -// .getScope -// .getConstructors -// .get(cons.name) - ) + ConstructorNode.build(c) case BindingsMap.ResolvedModule(module) => ConstantObjectNode.build( module.unsafeAsModule().getScope.getAssociatedType 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 65c77d3bf7fe..2d25418bf305 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 @@ -64,7 +64,6 @@ case object BindingAnalysis extends IRPass { val definedConstructors = ir.bindings.flatMap { case tp: IR.Module.Scope.Definition.Type => - // FIXME: move to a different pass tp.members.map { cons => BindingsMap.Cons( cons.name.name, From 06dc4e0eb80cb73dc6d73f8dc170fa7b401ad561 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 20:51:51 +0200 Subject: [PATCH 093/110] Update distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso Co-authored-by: James Dunkerley --- distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso index baea89499e5e..e3a4c9336e4b 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso @@ -116,7 +116,7 @@ type Write_Flag Sets the luma quality level used when writing a JPEG. Arguments: - - value: A quality value from 0 to 100 (the higher, the better). + - val: A quality value from 0 to 100 (the higher, the better). Write_Jpeg_Luma_Quality val=0 ## UNSTABLE From a52c828d010ea4a8d4720c16196ba59af5c648b7 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 20:52:03 +0200 Subject: [PATCH 094/110] Update distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso Co-authored-by: James Dunkerley --- distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso index e3a4c9336e4b..dbfee141c21e 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso @@ -124,7 +124,7 @@ type Write_Flag Sets the chroma quality level used when writing a JPEG. Arguments: - - value: A quality value from 0 to 100 (the higher, the better). + - val: A quality value from 0 to 100 (the higher, the better). Write_Jpeg_Chroma_Quality val=0 ## UNSTABLE From 48c8bd91ae5d15df980b58483df3993852ca13c4 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 20:52:49 +0200 Subject: [PATCH 095/110] Update test/Table_Tests/src/Data_Formatter_Spec.enso Co-authored-by: James Dunkerley --- test/Table_Tests/src/Data_Formatter_Spec.enso | 1 - 1 file changed, 1 deletion(-) diff --git a/test/Table_Tests/src/Data_Formatter_Spec.enso b/test/Table_Tests/src/Data_Formatter_Spec.enso index 50204e2133f4..e479e1e1ae6b 100644 --- a/test/Table_Tests/src/Data_Formatter_Spec.enso +++ b/test/Table_Tests/src/Data_Formatter_Spec.enso @@ -17,7 +17,6 @@ type Custom_Type_With_To_Text to_text self = "[CUSTOM = " + self.field.to_text + "]" type Custom_Type_With_Error - Custom_Type_With_Error_Data to_text : Text to_text self = Error.throw (Illegal_State_Error_Data "foo_error") From 8ecf7a1140ac1b4d4b361711b2fad5fff5400c8a Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 20:53:01 +0200 Subject: [PATCH 096/110] Update test/Table_Tests/src/Data_Formatter_Spec.enso Co-authored-by: James Dunkerley --- test/Table_Tests/src/Data_Formatter_Spec.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Table_Tests/src/Data_Formatter_Spec.enso b/test/Table_Tests/src/Data_Formatter_Spec.enso index e479e1e1ae6b..ec625d5f3c16 100644 --- a/test/Table_Tests/src/Data_Formatter_Spec.enso +++ b/test/Table_Tests/src/Data_Formatter_Spec.enso @@ -192,7 +192,7 @@ spec = Test.specify "should correctly pass through errors from custom type's `.to_text` method" pending="TODO: figure out the desired behavior, see: https://www.pivotaltracker.com/story/show/182522644" <| formatter = Data_Formatter_Data - formatter.format Custom_Type_With_Error_Data . should_fail_with Illegal_State_Error_Data + formatter.format Custom_Type_With_Error . should_fail_with Illegal_State_Error_Data Test.expect_panic_with (formatter.format Custom_Type_With_Panic_Data) Illegal_State_Error_Data Test.group "DataFormatter builders" <| From 4d9958a3ef7e6cf8d2befbcdb6c6a55dbea1da24 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 20:53:20 +0200 Subject: [PATCH 097/110] Update test/Table_Tests/src/Data_Formatter_Spec.enso Co-authored-by: James Dunkerley --- test/Table_Tests/src/Data_Formatter_Spec.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Table_Tests/src/Data_Formatter_Spec.enso b/test/Table_Tests/src/Data_Formatter_Spec.enso index ec625d5f3c16..55ebf046f2c9 100644 --- a/test/Table_Tests/src/Data_Formatter_Spec.enso +++ b/test/Table_Tests/src/Data_Formatter_Spec.enso @@ -193,7 +193,7 @@ spec = Test.specify "should correctly pass through errors from custom type's `.to_text` method" pending="TODO: figure out the desired behavior, see: https://www.pivotaltracker.com/story/show/182522644" <| formatter = Data_Formatter_Data formatter.format Custom_Type_With_Error . should_fail_with Illegal_State_Error_Data - Test.expect_panic_with (formatter.format Custom_Type_With_Panic_Data) Illegal_State_Error_Data + Test.expect_panic_with (formatter.format Custom_Type_With_Panic) Illegal_State_Error_Data Test.group "DataFormatter builders" <| # We create a formatter with all non-default values to ensure that the builders keep the existing values of other properties instead of switching to the constructor's defaults. From ec17e7f6ee955f005b1432ffe357d272291801c8 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 20:53:31 +0200 Subject: [PATCH 098/110] Update test/Table_Tests/src/Excel_Spec.enso Co-authored-by: James Dunkerley --- test/Table_Tests/src/Excel_Spec.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Table_Tests/src/Excel_Spec.enso b/test/Table_Tests/src/Excel_Spec.enso index 02f7822745bb..367c5f5bd113 100644 --- a/test/Table_Tests/src/Excel_Spec.enso +++ b/test/Table_Tests/src/Excel_Spec.enso @@ -4,7 +4,7 @@ from Standard.Base.System.File import File_Already_Exists_Error from Standard.Base.Error.Problem_Behavior import all import Standard.Table -from Standard.Table import File_Format, Match_Columns, Column_Name_Mapping, Data_Formatter, Excel_Range, Data_Formatter_Data +from Standard.Table import File_Format, Match_Columns, Column_Name_Mapping, Excel_Range, Data_Formatter_Data from Standard.Table.Data.Column_Selector as Column_Selector_Module import By_Index from Standard.Table.IO.Excel import Sheet_Names, Range_Names, Sheet, Cell_Range From 9cfe2b0839cc5cf3f31b1889d4bc7eccc5337228 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 20:53:38 +0200 Subject: [PATCH 099/110] Update test/Tests/src/Semantic/Names_Spec.enso Co-authored-by: James Dunkerley --- test/Tests/src/Semantic/Names_Spec.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Tests/src/Semantic/Names_Spec.enso b/test/Tests/src/Semantic/Names_Spec.enso index d36c40748e10..d2bd727df149 100644 --- a/test/Tests/src/Semantic/Names_Spec.enso +++ b/test/Tests/src/Semantic/Names_Spec.enso @@ -1,6 +1,6 @@ from Standard.Base import all -from project.Semantic.Names.Definitions import another_method, another_constant, method_with_local_vars, Bar_Data, Bar +from project.Semantic.Names.Definitions import another_method, another_constant, method_with_local_vars, Bar_Data import project.Semantic.Names.Definitions import Standard.Test From 9a842178f7e876dcffa5832cc05c87a6bbe6b63b Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 20:59:15 +0200 Subject: [PATCH 100/110] stuff --- .../src/main/scala/org/enso/runner/Main.scala | 6 ++-- .../runtime/builtin/BuiltinType.java | 31 ------------------- 2 files changed, 3 insertions(+), 34 deletions(-) delete mode 100644 engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java diff --git a/engine/runner/src/main/scala/org/enso/runner/Main.scala b/engine/runner/src/main/scala/org/enso/runner/Main.scala index 700dc7a3aa62..13d9e9b280e1 100644 --- a/engine/runner/src/main/scala/org/enso/runner/Main.scala +++ b/engine/runner/src/main/scala/org/enso/runner/Main.scala @@ -754,11 +754,11 @@ object Main { mainMethodName: String = "main" ): Unit = { try { - val mainCons = mainModule.getAssociatedType - val mainFun = mainModule.getMethod(mainCons, mainMethodName) + val mainType = mainModule.getAssociatedType + val mainFun = mainModule.getMethod(mainType, mainMethodName) mainFun match { case Some(main) if mainMethodName != "main" => - main.execute(mainCons.newInstance()) + main.execute(mainType.newInstance()) case Some(main) => main.execute() case None => diff --git a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java b/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java deleted file mode 100644 index 1d9f3bcfff57..000000000000 --- a/engine/runtime/src/main/java/org/enso/interpreter/runtime/builtin/BuiltinType.java +++ /dev/null @@ -1,31 +0,0 @@ -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.data.Type; - -import static com.oracle.truffle.api.CompilerDirectives.transferToInterpreterAndInvalidate; - -public class BuiltinType { - private final Builtins builtins; - private final Class clazz; - - @CompilerDirectives.CompilationFinal Type type; - - public BuiltinType(Builtins builtins, Class clazz) { - this.builtins = builtins; - this.clazz = clazz; - } - - public Type getType() { - if (type == null) { - transferToInterpreterAndInvalidate(); - type = builtins.getBuiltinType(clazz).getType(); - } - return type; - } - - // Atom newInstance(Object... args) { - // return getType().newInstance(args); - // } -} From 65e2582ded713281a6993775753ca4b59b458443 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 21:00:30 +0200 Subject: [PATCH 101/110] . --- .../src/test/scala/org/enso/polyglot/ApiTest.scala | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/engine/polyglot-api/src/test/scala/org/enso/polyglot/ApiTest.scala b/engine/polyglot-api/src/test/scala/org/enso/polyglot/ApiTest.scala index 524de12ca15e..18e3b2823234 100644 --- a/engine/polyglot-api/src/test/scala/org/enso/polyglot/ApiTest.scala +++ b/engine/polyglot-api/src/test/scala/org/enso/polyglot/ApiTest.scala @@ -27,10 +27,10 @@ class ApiTest extends AnyFlatSpec with Matchers { |bar = x -> foo x + 1 |""".stripMargin val module = executionContext.evalModule(code, "Test") - val associatedConstructor = module.getAssociatedType - val barFunction = module.getMethod(associatedConstructor, "bar").get + val associatedType = module.getAssociatedType + val barFunction = module.getMethod(associatedType, "bar").get val result = barFunction.execute( - associatedConstructor, + associatedType, 10L.asInstanceOf[AnyRef] ) result.asLong shouldEqual 12 From fdf06a98e134a8ada2afe3dddfc36b8af3f9e9f5 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 21:42:05 +0200 Subject: [PATCH 102/110] Update distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso Co-authored-by: James Dunkerley --- distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso index dbfee141c21e..125ff9d12e25 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso @@ -132,7 +132,7 @@ type Write_Flag Sets the compression level used when writing a PNG. Arguments: - - value: A compression level from 0 to 9. A higher value means a smaller + - val: A compression level from 0 to 9. A higher value means a smaller size but a longer compression time. Write_Png_Compression val=3 From c91dc4598466156c0165643f515bb16ef597dc70 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 21:42:14 +0200 Subject: [PATCH 103/110] Update distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso Co-authored-by: James Dunkerley --- distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso index 125ff9d12e25..a78f57c96302 100644 --- a/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso +++ b/distribution/lib/Standard/Image/0.0.0-dev/src/Codecs.enso @@ -141,7 +141,7 @@ type Write_Flag Sets the quality used when writing a WEBP image. Arguments: - - value: A quality from 0 to 100 (the higher, the better). A quality + - val: A quality from 0 to 100 (the higher, the better). A quality above 100 indicates that the encoder should use lossless compression. Write_Webp_Quality val=101 From 83060ef6a3b72396b4e1d5e4d7492a40b4bd5677 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 21:46:12 +0200 Subject: [PATCH 104/110] Update test/Table_Tests/src/Excel_Spec.enso Co-authored-by: James Dunkerley --- test/Table_Tests/src/Excel_Spec.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Table_Tests/src/Excel_Spec.enso b/test/Table_Tests/src/Excel_Spec.enso index 367c5f5bd113..7ea1a91573d8 100644 --- a/test/Table_Tests/src/Excel_Spec.enso +++ b/test/Table_Tests/src/Excel_Spec.enso @@ -371,7 +371,7 @@ spec_write suffix test_sheet_name = out_bak.delete_if_exists spec = - Test.group 'Excel_Data Range' <| + Test.group 'Excel Range' <| check_range excel_range sheet_name tlbr_vector single_cell=False = excel_range.sheet_name . should_equal sheet_name excel_range.top_row . should_equal (tlbr_vector.at 0) From 3ebf4a873cf0261895326e830631110173febde0 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 21:46:19 +0200 Subject: [PATCH 105/110] Update test/Tests/src/Data/Text_Spec.enso Co-authored-by: James Dunkerley --- test/Tests/src/Data/Text_Spec.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Tests/src/Data/Text_Spec.enso b/test/Tests/src/Data/Text_Spec.enso index 93f20284b96a..bd06c5e4fb8a 100644 --- a/test/Tests/src/Data/Text_Spec.enso +++ b/test/Tests/src/Data/Text_Spec.enso @@ -45,7 +45,7 @@ Manual.to_text self = "[[[MyREP " + self.b.to_text + "]]]" - Casing is locale-dependent. The pair of `i - I` is handled differently in Turkish and Azerbaijani - instead there are two separate pairs: 'İ - i' and 'I - ı'. - - Handling of out of range_Data indices should be checked. In particular, often + - Handling of out of range indices should be checked. In particular, often the index `text.length` should still be valid to point just right at the end of the text. Moreover, negative indices are usually allowed to index from the back. From 1bf52b8f3a485ee8fd861dde3b5925014d0efc37 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 21:47:03 +0200 Subject: [PATCH 106/110] continue --- .../lib/Standard/Base/0.0.0-dev/src/Data/Json.enso | 8 +++++--- .../Table/0.0.0-dev/src/Internal/Delimited_Reader.enso | 1 - 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso index 30fdff3a5e91..ef132a500cad 100644 --- a/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso +++ b/distribution/lib/Standard/Base/0.0.0-dev/src/Data/Json.enso @@ -155,9 +155,11 @@ type Json example_get = Examples.json_object.get "title" get : Text -> Json ! No_Such_Field_Error - get self field = self.fields.get field . map_error case _ of - Map.No_Value_For_Key_Error_Data _ -> No_Such_Field_Error_Data field - x -> x + get self field = case self of + Object _ -> self.fields.get field . map_error case _ of + Map.No_Value_For_Key_Error_Data _ -> No_Such_Field_Error_Data field + x -> x + _ -> Error.throw (Illegal_Argument_Error_Data "Json.get: self must be an Object") ## UNSTABLE 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 96aa8aeff093..bb71e445b977 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 @@ -104,7 +104,6 @@ prepare_delimited_reader java_reader format max_columns on_problems newline_over Nothing -> -1 Integer -> format.row_limit _ -> - IO.println format.row_limit Error.throw (Illegal_Argument_Error_Data "`row_limit` should be Integer or Nothing.") warnings_as_errors = on_problems == Report_Error quote_characters = case format.quote_style of From 8ff4f9ed74030774367587f52cea345b0eaf3375 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Tue, 30 Aug 2022 21:55:22 +0200 Subject: [PATCH 107/110] fmt --- .../lib/Standard/Test/0.0.0-dev/src/Main.enso | 2 +- .../interpreter/runtime/builtin/Builtins.java | 52 +++++-------------- .../interpreter/runtime/builtin/Error.java | 8 +-- 3 files changed, 16 insertions(+), 46 deletions(-) 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 5997790e6a12..02d9b88d5f04 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 @@ -234,7 +234,7 @@ Any.should_fail_with self matcher frames_to_skip=0 = Error.should_fail_with : Any -> Integer -> Assertion Error.should_fail_with self matcher frames_to_skip=0 = caught = self.catch - if (caught == matcher) || caught.is_a matcher then Nothing else + if caught.is_a matcher then Nothing else loc = Meta.get_source_location 2+frames_to_skip fail ("Expected error "+matcher.to_text+", but error " + caught.to_text + " has been returned (at " + loc + ").") 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 9d6f65b6eaf6..13d96e0c4295 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 @@ -155,9 +155,7 @@ private void registerBuiltinMethods(ModuleScope scope, Language language) { } } - /** - * @return {@code true} if the IR has been initialized, otherwise {@code false} - */ + /** @return {@code true} if the IR has been initialized, otherwise {@code false} */ public boolean isIrInitialized() { return this.module.getIr() != null; } @@ -381,23 +379,17 @@ public Number number() { return number; } - /** - * @return the container for boolean constructors. - */ + /** @return the container for boolean constructors. */ public Boolean bool() { return bool; } - /** - * @return the ManagedResource constructor. - */ + /** @return the ManagedResource constructor. */ public Type managedResource() { return managedResource.getType(); } - /** - * @return the builtin Error types container. - */ + /** @return the builtin Error types container. */ public Error error() { return error; } @@ -475,65 +467,47 @@ public Type debug() { return debug.getType(); } - /** - * @return the {@code Project_Description} atom constructor - */ + /** @return the {@code Project_Description} atom constructor */ public ProjectDescription getProjectDescription() { return projectDescription; } - /** - * @return the {@code System} atom constructor. - */ + /** @return the {@code System} atom constructor. */ public System system() { return system; } - /** - * @return the Array constructor. - */ + /** @return the Array constructor. */ public Type array() { return array.getType(); } - /** - * @return the Ref constructor. - */ + /** @return the Ref constructor. */ public Type ref() { return ref.getType(); } - /** - * @return the container for polyglot-related builtins. - */ + /** @return the container for polyglot-related builtins. */ public Type polyglot() { return polyglot.getType(); } - /** - * @return the {@code Caught_Panic} atom constructor - */ + /** @return the {@code Caught_Panic} atom constructor */ public CaughtPanic caughtPanic() { return this.error.caughtPanic(); } - /** - * @return the {@code Panic} atom constructor - */ + /** @return the {@code Panic} atom constructor */ public Type panic() { return this.error.panic(); } - /** - * @return the container for ordering-related builtins - */ + /** @return the container for ordering-related builtins */ public Ordering ordering() { return ordering; } - /** - * @return the container for the dataflow error-related builtins - */ + /** @return the container for the dataflow error-related builtins */ public Type dataflowError() { return dataflowError.getType(); } 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 e79e83f59d6d..f10d7086adb7 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 @@ -146,9 +146,7 @@ private Atom makeArithmeticError(Text reason) { return arithmeticError.newInstance(reason); } - /** - * @return An arithmetic error representing a too-large shift for the bit shift. - */ + /** @return An arithmetic error representing a too-large shift for the bit shift. */ public Atom getShiftAmountTooLargeError() { if (arithmeticErrorShiftTooBig == null) { transferToInterpreterAndInvalidate(); @@ -157,9 +155,7 @@ public Atom getShiftAmountTooLargeError() { return arithmeticErrorShiftTooBig; } - /** - * @return An Arithmetic error representing a division by zero. - */ + /** @return An Arithmetic error representing a division by zero. */ public Atom getDivideByZeroError() { if (arithmeticErrorDivideByZero == null) { transferToInterpreterAndInvalidate(); From f733104afebb53b13714a0143ce874e166cdde5b Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 31 Aug 2022 00:08:30 +0200 Subject: [PATCH 108/110] fix tests --- test/Tests/src/Semantic/Names_Spec.enso | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Tests/src/Semantic/Names_Spec.enso b/test/Tests/src/Semantic/Names_Spec.enso index d2bd727df149..d36c40748e10 100644 --- a/test/Tests/src/Semantic/Names_Spec.enso +++ b/test/Tests/src/Semantic/Names_Spec.enso @@ -1,6 +1,6 @@ from Standard.Base import all -from project.Semantic.Names.Definitions import another_method, another_constant, method_with_local_vars, Bar_Data +from project.Semantic.Names.Definitions import another_method, another_constant, method_with_local_vars, Bar_Data, Bar import project.Semantic.Names.Definitions import Standard.Test From c73fea5380d5815031b9640597c70a161179a8d2 Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 31 Aug 2022 00:12:30 +0200 Subject: [PATCH 109/110] fmt --- .../src/test/scala/org/enso/polyglot/ApiTest.scala | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/engine/polyglot-api/src/test/scala/org/enso/polyglot/ApiTest.scala b/engine/polyglot-api/src/test/scala/org/enso/polyglot/ApiTest.scala index 18e3b2823234..2cb9c0eb00d9 100644 --- a/engine/polyglot-api/src/test/scala/org/enso/polyglot/ApiTest.scala +++ b/engine/polyglot-api/src/test/scala/org/enso/polyglot/ApiTest.scala @@ -26,9 +26,9 @@ class ApiTest extends AnyFlatSpec with Matchers { |foo = x -> x + 1 |bar = x -> foo x + 1 |""".stripMargin - val module = executionContext.evalModule(code, "Test") + val module = executionContext.evalModule(code, "Test") val associatedType = module.getAssociatedType - val barFunction = module.getMethod(associatedType, "bar").get + val barFunction = module.getMethod(associatedType, "bar").get val result = barFunction.execute( associatedType, 10L.asInstanceOf[AnyRef] From 2ee29c0528119a0e13d8d4a91dfd9ea109a5591a Mon Sep 17 00:00:00 2001 From: Marcin Kostrzewa Date: Wed, 31 Aug 2022 00:15:33 +0200 Subject: [PATCH 110/110] missing foc --- .../main/scala/org/enso/compiler/PackageRepository.scala | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/engine/runtime/src/main/scala/org/enso/compiler/PackageRepository.scala b/engine/runtime/src/main/scala/org/enso/compiler/PackageRepository.scala index da63bfc42a3b..4bf9e37bd2c8 100644 --- a/engine/runtime/src/main/scala/org/enso/compiler/PackageRepository.scala +++ b/engine/runtime/src/main/scala/org/enso/compiler/PackageRepository.scala @@ -94,6 +94,12 @@ trait PackageRepository { */ def registerModuleCreatedInRuntime(module: Module): Unit + /** Register an empty package with the given name. Used for populating artificially, + * e.g. in tests. + * + * @param namespace the namespace of the created package. + * @param name the name of the created package. + */ def registerSyntheticPackage(namespace: String, name: String): Unit /** Removes a module with the given name from the list of loaded modules. */