From 01f328e8fdb5a8f051f7a11a6d19830a372597f7 Mon Sep 17 00:00:00 2001 From: Evan Ovadia <> Date: Thu, 6 Jul 2023 12:02:43 -0400 Subject: [PATCH 1/5] Merging regions: Function/kind exports and externs --- .../dev/vale/instantiating/Instantiator.scala | 15 +- .../test/dev/vale/ClosureTests.scala | 6 +- .../test/dev/vale/InferTemplateTests.scala | 2 +- .../src/dev/vale/simplifying/Hammer.scala | 12 +- .../src/dev/vale/typing/ArrayCompiler.scala | 2 +- .../src/dev/vale/typing/Compiler.scala | 242 ++++++++++++++++-- .../src/dev/vale/typing/CompilerOutputs.scala | 12 +- .../src/dev/vale/typing/ConvertHelper.scala | 2 +- .../src/dev/vale/typing/EdgeCompiler.scala | 2 +- .../src/dev/vale/typing/InferCompiler.scala | 2 +- .../dev/vale/typing/OverloadResolver.scala | 5 +- .../src/dev/vale/typing/ast/ast.scala | 19 +- .../src/dev/vale/typing/ast/citizens.scala | 2 + .../vale/typing/citizen/ImplCompiler.scala | 2 +- .../vale/typing/citizen/StructCompiler.scala | 2 +- .../typing/citizen/StructCompilerCore.scala | 32 --- .../expression/ExpressionCompiler.scala | 2 +- .../typing/function/DestructorCompiler.scala | 2 +- .../typing/function/FunctionCompiler.scala | 15 +- .../FunctionCompilerClosureOrLightLayer.scala | 2 +- .../function/FunctionCompilerCore.scala | 53 ++-- .../FunctionCompilerMiddleLayer.scala | 2 +- .../FunctionCompilerSolvingLayer.scala | 3 +- .../typing/macros/AbstractBodyMacro.scala | 2 +- .../vale/typing/macros/FunctorHelper.scala | 2 +- .../macros/StructConstructorMacro.scala | 3 +- .../src/dev/vale/typing/names/names.scala | 10 + .../dev/vale/typing/CompilerLambdaTests.scala | 4 +- .../dev/vale/typing/CompilerSolverTests.scala | 23 +- .../test/dev/vale/typing/CompilerTests.scala | 42 +-- 30 files changed, 369 insertions(+), 155 deletions(-) diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala index 7bb7a96fe..695ddbf1e 100644 --- a/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala @@ -93,8 +93,8 @@ object Instantiator { val monouts = new InstantiatedOutputs() - kindExportsT.foreach({ case KindExportT(range, tyype, packageCoordinate, exportedName) => - val packageName = IdT(packageCoordinate, Vector(), interner.intern(PackageTopLevelNameT())) + kindExportsT.foreach({ case KindExportT(range, tyype, packageId, exportedName) => + val packageName = IdT(packageId.packageCoord, Vector(), interner.intern(PackageTopLevelNameT())) val exportName = packageName.addStep(interner.intern(ExportNameT(interner.intern(ExportTemplateNameT(range.begin))))) val exportTemplateName = TemplataCompiler.getExportTemplate(exportName) @@ -112,12 +112,12 @@ object Instantiator { KindExportT( range, instantiator.translateKind(tyype), - packageCoordinate, + packageId, exportedName) }) - functionExportsT.foreach({ case FunctionExportT(range, prototype, packageCoordinate, exportedName) => - val packageName = IdT(packageCoordinate, Vector(), interner.intern(PackageTopLevelNameT())) + functionExportsT.foreach({ case FunctionExportT(range, prototype, packageId, exportedName) => + val packageName = IdT(packageId.packageCoord, Vector(), interner.intern(PackageTopLevelNameT())) val exportName = packageName.addStep( interner.intern(ExportNameT(interner.intern(ExportTemplateNameT(range.begin))))) @@ -136,7 +136,7 @@ object Instantiator { FunctionExportT( range, instantiator.translatePrototype(prototype), - packageCoordinate, + packageId, exportedName) }) @@ -1934,10 +1934,11 @@ class Instantiator( def translateParameter( param: ParameterT): ParameterT = { - val ParameterT(name, virtuality, tyype) = param + val ParameterT(name, virtuality, preChecked, tyype) = param ParameterT( translateVarName(name), virtuality, + preChecked, translateCoord(tyype)) } diff --git a/Frontend/IntegrationTests/test/dev/vale/ClosureTests.scala b/Frontend/IntegrationTests/test/dev/vale/ClosureTests.scala index 80e29e793..e260b37ba 100644 --- a/Frontend/IntegrationTests/test/dev/vale/ClosureTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/ClosureTests.scala @@ -242,12 +242,12 @@ class ClosureTests extends FunSuite with Matchers { val coutputs = compile.expectCompilerOutputs() val closureStruct = - coutputs.structs.find(struct => { + vassertOne(coutputs.structs.filter(struct => { struct.instantiatedCitizen.id.localName match { - case LambdaCitizenNameT(_) => true + case LambdaCitizenNameT(LambdaCitizenTemplateNameT(CodeLocationS(FileCoordinate(PackageCoordinate(StrI("test"),Vector()), _), _))) => true case _ => false } - }).get + })) closureStruct.mutability match { case MutabilityTemplataT(MutableT) => } diff --git a/Frontend/IntegrationTests/test/dev/vale/InferTemplateTests.scala b/Frontend/IntegrationTests/test/dev/vale/InferTemplateTests.scala index 8efaae774..de1cb5924 100644 --- a/Frontend/IntegrationTests/test/dev/vale/InferTemplateTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/InferTemplateTests.scala @@ -23,7 +23,7 @@ class InferTemplateTests extends FunSuite with Matchers { val moo = compile.expectCompilerOutputs().lookupFunction("moo") moo.header.params match { - case Vector(ParameterT(CodeVarNameT(StrI("m")), _, CoordT(BorrowT,_, _))) => + case Vector(ParameterT(CodeVarNameT(StrI("m")), _, _, CoordT(BorrowT,_, _))) => } val main = compile.expectCompilerOutputs().lookupFunction("main") Collector.only(main, { diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hammer.scala index aa5b3f109..319573587 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hammer.scala @@ -196,14 +196,14 @@ class Hammer(interner: Interner, keywords: Keywords) { // val emptyPackStructRefH = structHammer.translateStructRef(hinputs, hamuts, emptyPackStructRef) // vassert(emptyPackStructRefH == ProgramH.emptyTupleStructRef) - kindExports.foreach({ case KindExportT(_, tyype, packageCoordinate, exportName) => + kindExports.foreach({ case KindExportT(_, tyype, packageId, exportName) => val kindH = typeHammer.translateKind(hinputs, hamuts, tyype) - hamuts.addKindExport(kindH, packageCoordinate, exportName) + hamuts.addKindExport(kindH, packageId.packageCoord, exportName) }) - functionExports.foreach({ case FunctionExportT(_, prototype, packageCoordinate, exportName) => + functionExports.foreach({ case FunctionExportT(_, prototype, packageId, exportName) => val prototypeH = typeHammer.translatePrototype(hinputs, hamuts, prototype) - hamuts.addFunctionExport(prototypeH, packageCoordinate, exportName) + hamuts.addFunctionExport(prototypeH, packageId.packageCoord, exportName) }) kindExterns.foreach({ case KindExternT(tyype, packageCoordinate, exportName) => @@ -211,9 +211,9 @@ class Hammer(interner: Interner, keywords: Keywords) { hamuts.addKindExtern(kindH, packageCoordinate, exportName) }) - functionExterns.foreach({ case FunctionExternT(_, prototype, packageCoordinate, exportName) => + functionExterns.foreach({ case FunctionExternT(_, externPlaceholderedId, prototype, exportName) => val prototypeH = typeHammer.translatePrototype(hinputs, hamuts, prototype) - hamuts.addFunctionExtern(prototypeH, packageCoordinate, exportName) + hamuts.addFunctionExtern(prototypeH, externPlaceholderedId.packageCoord, exportName) }) // We generate the names here first, so that externs get the first chance at having diff --git a/Frontend/TypingPass/src/dev/vale/typing/ArrayCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/ArrayCompiler.scala index f56ea6503..ebd98e7a7 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/ArrayCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/ArrayCompiler.scala @@ -17,7 +17,7 @@ import dev.vale.typing.names._ import dev.vale.typing.templata._ import dev.vale.typing.ast._ import dev.vale.typing.citizen.StructCompilerCore -import dev.vale.typing.function.FunctionCompiler.EvaluateFunctionSuccess +import dev.vale.typing.function._ import dev.vale.typing.types._ import dev.vale.typing.templata._ diff --git a/Frontend/TypingPass/src/dev/vale/typing/Compiler.scala b/Frontend/TypingPass/src/dev/vale/typing/Compiler.scala index 3e74e7ce0..11f3a6447 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/Compiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/Compiler.scala @@ -9,7 +9,7 @@ import dev.vale.postparsing._ import dev.vale.typing.OverloadResolver.FindFunctionFailure import dev.vale.typing.citizen._ import dev.vale.typing.expression.{ExpressionCompiler, IExpressionCompilerDelegate} -import dev.vale.typing.function.{DestructorCompiler, FunctionCompiler, FunctionCompilerCore, IFunctionCompilerDelegate, VirtualCompiler} +import dev.vale.typing.function._ import dev.vale.typing.infer.IInfererDelegate import dev.vale.typing.types._ import dev.vale.highertyping._ @@ -31,7 +31,7 @@ import dev.vale.typing.expression.LocalHelper import dev.vale.typing.types._ import dev.vale.typing.templata._ import dev.vale.typing.function.FunctionCompiler -import dev.vale.typing.function.FunctionCompiler.{EvaluateFunctionSuccess, IEvaluateFunctionResult} +import dev.vale.typing.function.FunctionCompiler._ import dev.vale.typing.macros.citizen.StructDropMacro import dev.vale.typing.macros.ssa.SSALenMacro @@ -645,7 +645,7 @@ class Compiler( functionTemplata: FunctionTemplataT, explicitTemplateArgs: Vector[ITemplataT[ITemplataType]], args: Vector[CoordT]): - FunctionCompiler.IEvaluateFunctionResult = { + IEvaluateFunctionResult = { functionCompiler.evaluateTemplatedFunctionFromCallForPrototype( coutputs, callRange, callLocation, callingEnv, functionTemplata, explicitTemplateArgs, args, true) } @@ -658,7 +658,7 @@ class Compiler( functionTemplata: FunctionTemplataT, explicitTemplateArgs: Vector[ITemplataT[ITemplataType]], args: Vector[CoordT]): - FunctionCompiler.IEvaluateFunctionResult = { + IEvaluateFunctionResult = { functionCompiler.evaluateGenericLightFunctionFromCallForPrototype( coutputs, callRange, callLocation, callingEnv, functionTemplata, explicitTemplateArgs, args) } @@ -840,16 +840,90 @@ class Compiler( // Indexing phase globalEnv.nameToTopLevelEnvironment.foreach({ case (packageId, templatas) => - val env = PackageEnvironmentT.makeTopLevelEnvironment(globalEnv, packageId) + val packageEnv = PackageEnvironmentT.makeTopLevelEnvironment(globalEnv, packageId) templatas.entriesByNameT.map({ case (name, entry) => entry match { case StructEnvEntry(structA) => { - val templata = StructDefinitionTemplataT(env, structA) + val templata = StructDefinitionTemplataT(packageEnv, structA) structCompiler.compileStruct(coutputs, List(), LocationInDenizen(Vector()), templata) + + val maybeExport = + structA.attributes.collectFirst { case e@ExportS(_) => e } + maybeExport match { + case None => + case Some(ExportS(packageCoordinate)) => { + val templateName = interner.intern(ExportTemplateNameT(structA.range.begin)) + val templateId = IdT(packageId.packageCoord, Vector(), templateName) + val exportOuterEnv = + ExportEnvironmentT( + globalEnv, packageEnv, templateId, TemplatasStore(templateId, Map(), Map())) + + val placeholderedExportName = interner.intern(ExportNameT(templateName)) + val placeholderedExportId = templateId.copy(localName = placeholderedExportName) + val exportEnv = + ExportEnvironmentT( + globalEnv, packageEnv, placeholderedExportId, TemplatasStore(placeholderedExportId, Map(), Map())) + + val exportPlaceholderedKind = + structCompiler.resolveStruct( + coutputs, exportEnv, List(structA.range), LocationInDenizen(Vector()), templata, Vector()) match { + case ResolveSuccess(kind) => kind + case ResolveFailure(range, reason) => { + vimpl() // DO NOT SUBMIT + } + } + + val exportName = + structA.name match { + case TopLevelCitizenDeclarationNameS(name, range) => name + case other => vwat(other) + } + + coutputs.addKindExport( + structA.range, exportPlaceholderedKind, placeholderedExportId, exportName) + } + } } case InterfaceEnvEntry(interfaceA) => { - val templata = InterfaceDefinitionTemplataT(env, interfaceA) + val templata = InterfaceDefinitionTemplataT(packageEnv, interfaceA) structCompiler.compileInterface(coutputs, List(), LocationInDenizen(Vector()), templata) + + val maybeExport = + interfaceA.attributes.collectFirst { case e@ExportS(_) => e } + maybeExport match { + case None => + case Some(ExportS(packageCoordinate)) => { + val templateName = interner.intern(ExportTemplateNameT(interfaceA.range.begin)) + val templateId = IdT(packageId.packageCoord, Vector(), templateName) + val exportOuterEnv = + ExportEnvironmentT( + globalEnv, packageEnv, templateId, TemplatasStore(templateId, Map(), Map())) + + val placeholderedExportName = interner.intern(ExportNameT(templateName)) + val placeholderedExportId = templateId.copy(localName = placeholderedExportName) + val exportEnv = + ExportEnvironmentT( + globalEnv, packageEnv, placeholderedExportId, TemplatasStore(placeholderedExportId, Map(), Map())) + + val exportPlaceholderedKind = + structCompiler.resolveInterface( + coutputs, exportEnv, List(interfaceA.range), LocationInDenizen(Vector()), templata, Vector()) match { + case ResolveSuccess(kind) => kind + case ResolveFailure(range, reason) => { + vimpl() // DO NOT SUBMIT + } + } + + val exportName = + interfaceA.name match { + case TopLevelCitizenDeclarationNameS(name, range) => name + case other => vwat(other) + } + + coutputs.addKindExport( + interfaceA.range, exportPlaceholderedKind, placeholderedExportId, exportName) + } + } } case _ => } @@ -871,12 +945,143 @@ class Compiler( globalEnv.nameToTopLevelEnvironment.foreach({ // Anything in global scope should be compiled case (packageId @ IdT(_, Vector(), PackageTopLevelNameT()), templatas) => { - val env = PackageEnvironmentT.makeTopLevelEnvironment(globalEnv, packageId) + val packageEnv = PackageEnvironmentT.makeTopLevelEnvironment(globalEnv, packageId) templatas.entriesByNameT.map({ case (name, entry) => entry match { case FunctionEnvEntry(functionA) => { + val templata = FunctionTemplataT(packageEnv, functionA) + val header = functionCompiler.evaluateGenericFunctionFromNonCall( - coutputs, List(), LocationInDenizen(Vector()), FunctionTemplataT(env, functionA), true) + coutputs, List(), LocationInDenizen(Vector()), templata, true) + + functionA.attributes.collectFirst({ case e @ ExternS(_) => e }) match { + case None => + case Some(ExternS(packageCoord)) => { + val externName = + functionA.name match { + case FunctionNameS(name, range) => name + case other => vwat(other) + } + + val templateName = interner.intern(ExternTemplateNameT(functionA.range.begin)) + val templateId = IdT(packageId.packageCoord, Vector(), templateName) + + val placeholderedExternName = interner.intern(ExternNameT(templateName)) + val placeholderedExternId = templateId.copy(localName = placeholderedExternName) + val externEnv = + ExternEnvironmentT( + globalEnv, packageEnv, placeholderedExternId, TemplatasStore(placeholderedExternId, Map(), Map())) + // We evaluate this and then don't do anything for it on purpose, we just do + // this to cause the compiler to make instantiation bounds for all the types + // in terms of this extern. That way, further below, when we do the + // substituting templatas, the bounds are already made for these types. + val externPlaceholderedWrapperPrototype = + functionCompiler.evaluateGenericLightFunctionFromCallForPrototype( + coutputs, + List(functionA.range), + LocationInDenizen(Vector()), + externEnv, + templata, + Vector(), + Vector()) match { + case EvaluateFunctionSuccess(prototype, inferences) => prototype.prototype + case EvaluateFunctionFailure(reason) => { + throw CompileErrorExceptionT(CouldntEvaluateFunction(List(functionA.range), reason)) + } + } + +// val externPerspectivedParams = +// header.params.map(_.tyype).map(typeT => { +// TemplataCompiler.substituteTemplatasInCoord( +// coutputs, +// interner, +// keywords, +// TemplataCompiler.getTemplate(header.id), +// Vector(regionPlaceholder), +// InheritBoundsFromTypeItself, +// typeT) +// }) +// val externPerspectivedReturn = +// TemplataCompiler.substituteTemplatasInCoord( +// coutputs, +// interner, +// keywords, +// TemplataCompiler.getTemplate(header.id), +// Vector(regionPlaceholder), +// InheritBoundsFromTypeItself, +// header.returnType) +// val externFunctionId = +// IdT( +// packageCoord, +// Vector.empty, +// interner.intern(ExternFunctionNameT( +// externName, externPerspectivedParams))) +// val externPrototype = PrototypeT(externFunctionId, externPerspectivedReturn) + + // We don't actually want to call the wrapper function, we want to call the extern. + // The extern's prototype is always similar to the wrapper function, so we do + // a straightforward replace of the names. + // We don't have to worry about placeholders, they're already phrased in terms + // of the calling FunctionExternT. + val externPrototype = + externPlaceholderedWrapperPrototype match { + case PrototypeT(IdT(packageCoord, steps, FunctionNameT(FunctionTemplateNameT(humanName, codeLocation), templateArgs, params)), returnType) => { + PrototypeT( + IdT( + packageCoord, + steps, + interner.intern(ExternFunctionNameT(humanName, params))), + returnType) + } + case other => vwat(other) + } + // Though, we do need to add some instantiation bounds for this new IdT we + // just made. + coutputs.addInstantiationBounds( + externPrototype.id, + vassertSome(coutputs.getInstantiationBounds(externPlaceholderedWrapperPrototype.id))) + + coutputs.addFunctionExtern( + functionA.range, placeholderedExternId, externPrototype, externName) + } + } + + val maybeExport = + functionA.attributes.collectFirst { case e@ExportS(_) => e } + maybeExport match { + case None => + case Some(ExportS(packageCoordinate)) => { + val templateName = interner.intern(ExportTemplateNameT(functionA.range.begin)) + val templateId = IdT(packageId.packageCoord, Vector(), templateName) + val exportOuterEnv = + ExportEnvironmentT( + globalEnv, packageEnv, templateId, TemplatasStore(templateId, Map(), Map())) + + val placeholderedExportName = interner.intern(ExportNameT(templateName)) + val placeholderedExportId = templateId.copy(localName = placeholderedExportName) + val exportEnv = + ExportEnvironmentT( + globalEnv, packageEnv, placeholderedExportId, TemplatasStore(placeholderedExportId, Map(), Map())) + + val exportPlaceholderedPrototype = + functionCompiler.evaluateGenericLightFunctionFromCallForPrototype( + coutputs, List(functionA.range), LocationInDenizen(Vector()), exportEnv, templata, Vector(), Vector()) match { + case EvaluateFunctionSuccess(prototype, inferences) => prototype.prototype + case EvaluateFunctionFailure(reason) => { + throw CompileErrorExceptionT(CouldntEvaluateFunction(List(functionA.range), reason)) + } + } + + val exportName = + functionA.name match { + case FunctionNameS(name, range) => name + case other => vwat(other) + } + + coutputs.addFunctionExport( + functionA.range, exportPlaceholderedPrototype, placeholderedExportId, exportName) + } + } } case _ => } @@ -908,11 +1113,12 @@ class Compiler( val CompleteCompilerSolve(_, templataByRune, _, Vector()) = inferCompiler.solveExpectComplete( - InferEnv(exportEnv, List(range), LocationInDenizen(Vector()), exportEnv), coutputs, rules, runeToType, List(range), LocationInDenizen(Vector()), Vector(), Vector(), true, true, Vector()) - val kind = + InferEnv(exportEnv, List(range), LocationInDenizen(Vector()), exportEnv), + coutputs, rules, runeToType, List(range), + LocationInDenizen(Vector()), Vector(), Vector(), true, true, Vector()) templataByRune.get(typeRuneT.rune) match { case Some(KindTemplataT(kind)) => { - coutputs.addKindExport(range, kind, range.file.packageCoordinate, exportedName) + coutputs.addKindExport(range, kind, placeholderedExportId, exportedName) } case Some(prototype) => { vimpl() @@ -1162,7 +1368,7 @@ class Compiler( def ensureDeepExports(coutputs: CompilerOutputs): Unit = { val packageToKindToExport = coutputs.getKindExports - .map(kindExport => (kindExport.packageCoordinate, kindExport.tyype, kindExport)) + .map(kindExport => (kindExport.id.packageCoord, kindExport.tyype, kindExport)) .groupBy(_._1) .mapValues( _.map(x => (x._2, x._3)) @@ -1175,30 +1381,30 @@ class Compiler( throw CompileErrorExceptionT( TypeExportedMultipleTimes( List(exports.head.range), - exports.head.packageCoordinate, + exports.head.id.packageCoord, exports)) } })) coutputs.getFunctionExports.foreach(funcExport => { - val exportedKindToExport = packageToKindToExport.getOrElse(funcExport.packageCoordinate, Map()) + val exportedKindToExport = packageToKindToExport.getOrElse(funcExport.exportId.packageCoord, Map()) (Vector(funcExport.prototype.returnType) ++ funcExport.prototype.paramTypes) .foreach(paramType => { if (!Compiler.isPrimitive(paramType.kind) && !exportedKindToExport.contains(paramType.kind)) { throw CompileErrorExceptionT( ExportedFunctionDependedOnNonExportedKind( - List(funcExport.range), funcExport.packageCoordinate, funcExport.prototype.toSignature, paramType.kind)) + List(funcExport.range), funcExport.exportId.packageCoord, funcExport.prototype.toSignature, paramType.kind)) } }) }) coutputs.getFunctionExterns.foreach(functionExtern => { - val exportedKindToExport = packageToKindToExport.getOrElse(functionExtern.packageCoordinate, Map()) + val exportedKindToExport = packageToKindToExport.getOrElse(functionExtern.externPlaceholderedId.packageCoord, Map()) (Vector(functionExtern.prototype.returnType) ++ functionExtern.prototype.paramTypes) .foreach(paramType => { if (!Compiler.isPrimitive(paramType.kind) && !exportedKindToExport.contains(paramType.kind)) { throw CompileErrorExceptionT( ExternFunctionDependedOnNonExportedKind( - List(functionExtern.range), functionExtern.packageCoordinate, functionExtern.prototype.toSignature, paramType.kind)) + List(functionExtern.range), functionExtern.externPlaceholderedId.packageCoord, functionExtern.prototype.toSignature, paramType.kind)) } }) }) diff --git a/Frontend/TypingPass/src/dev/vale/typing/CompilerOutputs.scala b/Frontend/TypingPass/src/dev/vale/typing/CompilerOutputs.scala index 932621add..b972283bb 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/CompilerOutputs.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/CompilerOutputs.scala @@ -354,21 +354,21 @@ case class CompilerOutputs() { superInterfaceTemplateToImpls.getOrElse(superInterfaceTemplate, Vector[ImplT]()) } - def addKindExport(range: RangeS, kind: KindT, packageCoord: PackageCoordinate, exportedName: StrI): Unit = { - kindExports += KindExportT(range, kind, packageCoord, exportedName) + def addKindExport(range: RangeS, kind: KindT, id: IdT[ExportNameT], exportedName: StrI): Unit = { + kindExports += KindExportT(range, kind, id, exportedName) } - def addFunctionExport(range: RangeS, function: PrototypeT, packageCoord: PackageCoordinate, exportedName: StrI): Unit = { + def addFunctionExport(range: RangeS, function: PrototypeT, exportId: IdT[ExportNameT], exportedName: StrI): Unit = { vassert(getInstantiationBounds(function.id).nonEmpty) - functionExports += FunctionExportT(range, function, packageCoord, exportedName) + functionExports += FunctionExportT(range, function, exportId, exportedName) } def addKindExtern(kind: KindT, packageCoord: PackageCoordinate, exportedName: StrI): Unit = { kindExterns += KindExternT(kind, packageCoord, exportedName) } - def addFunctionExtern(range: RangeS, function: PrototypeT, packageCoord: PackageCoordinate, exportedName: StrI): Unit = { - functionExterns += FunctionExternT(range, function, packageCoord, exportedName) + def addFunctionExtern(range: RangeS, externPlaceholderedId: IdT[ExternNameT], function: PrototypeT, exportedName: StrI): Unit = { + functionExterns += FunctionExternT(range, externPlaceholderedId, function, exportedName) } def deferEvaluatingFunctionBody(devf: DeferredEvaluatingFunctionBody): Unit = { diff --git a/Frontend/TypingPass/src/dev/vale/typing/ConvertHelper.scala b/Frontend/TypingPass/src/dev/vale/typing/ConvertHelper.scala index e43e251de..f84d120b7 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/ConvertHelper.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/ConvertHelper.scala @@ -7,7 +7,7 @@ import dev.vale.typing.types._ import dev.vale._ import dev.vale.typing.ast._ import dev.vale.typing.citizen.{IsParent, IsParentResult, IsntParent} -import dev.vale.typing.function.FunctionCompiler.EvaluateFunctionSuccess +import dev.vale.typing.function._ //import dev.vale.astronomer.IRulexSR import dev.vale.typing.citizen.ImplCompiler import dev.vale.typing.env.IDenizenEnvironmentBoxT diff --git a/Frontend/TypingPass/src/dev/vale/typing/EdgeCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/EdgeCompiler.scala index 858300fc7..91b969b8f 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/EdgeCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/EdgeCompiler.scala @@ -11,7 +11,7 @@ import dev.vale.typing.types._ import dev.vale.typing.ast._ import dev.vale.typing.citizen.ImplCompiler import dev.vale.typing.function.FunctionCompiler -import dev.vale.typing.function.FunctionCompiler.{EvaluateFunctionFailure, EvaluateFunctionSuccess} +import dev.vale.typing.function._ import dev.vale.typing.names._ import dev.vale.typing.templata.ITemplataT.{expectCoord, expectCoordTemplata, expectKindTemplata} import dev.vale.typing.templata.{CoordTemplataT, FunctionTemplataT, ITemplataT, KindTemplataT, MutabilityTemplataT, PlaceholderTemplataT} diff --git a/Frontend/TypingPass/src/dev/vale/typing/InferCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/InferCompiler.scala index fd9b27061..46ab924b2 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/InferCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/InferCompiler.scala @@ -10,7 +10,7 @@ import dev.vale.typing.OverloadResolver.FindFunctionFailure import dev.vale.typing.ast.PrototypeT import dev.vale.typing.citizen.{IResolveOutcome, IsParent, IsParentResult, IsntParent, ResolveFailure, ResolveSuccess} import dev.vale.typing.env.{CitizenEnvironmentT, EnvironmentHelper, GeneralEnvironmentT, GlobalEnvironment, IEnvEntry, IEnvironmentT, IInDenizenEnvironmentT, ILookupContext, IVariableT, TemplataEnvEntry, TemplataLookupContext, TemplatasStore} -import dev.vale.typing.function.FunctionCompiler.EvaluateFunctionSuccess +import dev.vale.typing.function._ import dev.vale.typing.infer.{CompilerSolver, CouldntFindFunction, CouldntFindImpl, CouldntResolveKind, IInfererDelegate, ITypingPassSolverError, ReturnTypeConflict} import dev.vale.typing.names.{BuildingFunctionNameWithClosuredsT, IImplNameT, INameT, ITemplateNameT, IdT, ImplNameT, NameTranslator, ReachablePrototypeNameT, ResolvingEnvNameT, RuneNameT} import dev.vale.typing.templata.{CoordListTemplataT, CoordTemplataT, ITemplataT, InterfaceDefinitionTemplataT, KindTemplataT, PrototypeTemplataT, RuntimeSizedArrayTemplateTemplataT, StaticSizedArrayTemplateTemplataT, StructDefinitionTemplataT} diff --git a/Frontend/TypingPass/src/dev/vale/typing/OverloadResolver.scala b/Frontend/TypingPass/src/dev/vale/typing/OverloadResolver.scala index fbb46359a..3e37e795a 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/OverloadResolver.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/OverloadResolver.scala @@ -5,7 +5,7 @@ import dev.vale.postparsing._ import dev.vale.postparsing.rules.{DefinitionFuncSR, IRulexSR, RuneParentEnvLookupSR} import dev.vale.solver.IIncompleteOrFailedSolve import dev.vale.typing.expression.CallCompiler -import dev.vale.typing.function.FunctionCompiler +import dev.vale.typing.function._ import dev.vale.typing.infer.ITypingPassSolverError import dev.vale.typing.types._ import dev.vale.highertyping._ @@ -14,7 +14,7 @@ import dev.vale.solver.FailedSolve import OverloadResolver.{Outscored, RuleTypeSolveFailure, SpecificParamDoesntMatchExactly, SpecificParamDoesntSend} import dev.vale.highertyping.HigherTypingPass.explicifyLookups import dev.vale.typing.ast.{AbstractT, FunctionBannerT, FunctionCalleeCandidate, HeaderCalleeCandidate, ICalleeCandidate, IValidCalleeCandidate, ParameterT, PrototypeT, ReferenceExpressionTE, ValidCalleeCandidate, ValidHeaderCalleeCandidate} -import dev.vale.typing.env.{ExpressionLookupContext, FunctionEnvironmentBoxT, IInDenizenEnvironmentT, IDenizenEnvironmentBoxT, TemplataLookupContext} +import dev.vale.typing.env.{ExpressionLookupContext, FunctionEnvironmentBoxT, IDenizenEnvironmentBoxT, IInDenizenEnvironmentT, TemplataLookupContext} import dev.vale.typing.templata._ import dev.vale.typing.ast._ import dev.vale.typing.names.{CallEnvNameT, CodeVarNameT, FunctionBoundNameT, FunctionBoundTemplateNameT, FunctionNameT, FunctionTemplateNameT, IdT} @@ -29,7 +29,6 @@ import dev.vale.typing.templata._ import dev.vale.postparsing.ExplicitTemplateArgRuneS import OverloadResolver.{IFindFunctionFailureReason, InferFailure, FindFunctionFailure, SpecificParamVirtualityDoesntMatch, WrongNumberOfArguments, WrongNumberOfTemplateArguments} import dev.vale.typing.env._ -import FunctionCompiler.{EvaluateFunctionFailure, EvaluateFunctionSuccess, IEvaluateFunctionResult} //import dev.vale.typingpass.infer.infer.{InferSolveFailure, InferSolveSuccess} import dev.vale.Profiler diff --git a/Frontend/TypingPass/src/dev/vale/typing/ast/ast.scala b/Frontend/TypingPass/src/dev/vale/typing/ast/ast.scala index 526c7f5fc..735609262 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/ast/ast.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/ast/ast.scala @@ -62,7 +62,9 @@ case class ImplT( case class KindExportT( range: RangeS, tyype: KindT, - packageCoordinate: PackageCoordinate, + // Good for knowing the package of this export for later prefixing the exportedName, also good + // for getting its region. + id: IdT[ExportNameT], exportedName: StrI ) { override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() @@ -72,7 +74,7 @@ case class KindExportT( case class FunctionExportT( range: RangeS, prototype: PrototypeT, - packageCoordinate: PackageCoordinate, + exportId: IdT[ExportNameT], exportedName: StrI ) { override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() @@ -90,8 +92,8 @@ case class KindExternT( case class FunctionExternT( range: RangeS, + externPlaceholderedId: IdT[ExternNameT], prototype: PrototypeT, - packageCoordinate: PackageCoordinate, externName: StrI ) { override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() @@ -196,6 +198,8 @@ case class FunctionDefinitionT( // We always end a function with a ret, whose result is a Never. vassert(body.result.kind == NeverT(false)) + + def isPure: Boolean = header.isPure } object getFunctionLastName { @@ -218,6 +222,7 @@ case class AbstractT() case class ParameterT( name: IVarNameT, virtuality: Option[AbstractT], + preChecked: Boolean, tyype: CoordT) { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; @@ -421,7 +426,7 @@ case class FunctionHeaderT( def getAbstractInterface: Option[InterfaceTT] = { val abstractInterfaces = params.collect({ - case ParameterT(_, Some(AbstractT()), CoordT(_, _, ir @ InterfaceTT(_))) => ir + case ParameterT(_, Some(AbstractT()), _, CoordT(_, _, ir @ InterfaceTT(_))) => ir }) vassert(abstractInterfaces.size <= 1) abstractInterfaces.headOption @@ -430,7 +435,7 @@ case class FunctionHeaderT( def getVirtualIndex: Option[Int] = { val indices = params.zipWithIndex.collect({ - case (ParameterT(_, Some(AbstractT()), _), index) => index + case (ParameterT(_, Some(AbstractT()), _, _), index) => index }) vassert(indices.size <= 1) indices.headOption @@ -459,6 +464,10 @@ case class FunctionHeaderT( def unapply(arg: FunctionHeaderT): Option[(IdT[IFunctionNameT], Vector[ParameterT], CoordT)] = { Some(id, params, returnType) } + + def isPure: Boolean = { + attributes.collectFirst({ case PureT => }).nonEmpty + } } case class PrototypeT( diff --git a/Frontend/TypingPass/src/dev/vale/typing/ast/citizens.scala b/Frontend/TypingPass/src/dev/vale/typing/ast/citizens.scala index a7c17f38a..956b764c9 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/ast/citizens.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/ast/citizens.scala @@ -28,6 +28,8 @@ case class StructDefinitionT( runeToFunctionBound: Map[IRuneS, IdT[FunctionBoundNameT]], runeToImplBound: Map[IRuneS, IdT[ImplBoundNameT]], ) extends CitizenDefinitionT { + vpass() + override def genericParamTypes: Vector[ITemplataType] = { instantiatedCitizen.id.localName.templateArgs.map(_.tyype) } diff --git a/Frontend/TypingPass/src/dev/vale/typing/citizen/ImplCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/citizen/ImplCompiler.scala index c010b2b52..712fa6508 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/citizen/ImplCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/citizen/ImplCompiler.scala @@ -16,7 +16,7 @@ import dev.vale.typing.templata._ import dev.vale.typing._ import dev.vale.typing.ast.{CitizenDefinitionT, ImplT, InterfaceDefinitionT} import dev.vale.typing.env._ -import dev.vale.typing.function.FunctionCompiler.EvaluateFunctionFailure +import dev.vale.typing.function._ import dev.vale.typing.infer.ITypingPassSolverError import scala.collection.immutable.Set diff --git a/Frontend/TypingPass/src/dev/vale/typing/citizen/StructCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/citizen/StructCompiler.scala index 7b236b8d6..d3f78f018 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/citizen/StructCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/citizen/StructCompiler.scala @@ -19,7 +19,7 @@ import dev.vale.postparsing.rules._ import dev.vale.typing.env._ import dev.vale.typing.function.FunctionCompiler import dev.vale.typing.ast._ -import dev.vale.typing.function.FunctionCompiler.{EvaluateFunctionSuccess, IEvaluateFunctionResult} +import dev.vale.typing.function._ import dev.vale.typing.templata.ITemplataT.expectMutability import scala.collection.immutable.List diff --git a/Frontend/TypingPass/src/dev/vale/typing/citizen/StructCompilerCore.scala b/Frontend/TypingPass/src/dev/vale/typing/citizen/StructCompilerCore.scala index 8af9ca15d..ef2eff0f2 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/citizen/StructCompilerCore.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/citizen/StructCompilerCore.scala @@ -160,22 +160,6 @@ class StructCompilerCore( runeToImplBound) coutputs.addStruct(structDefT); - - maybeExport match { - case None => - case Some(exportPackageCoord) => { - val exportedName = - placeholderedIdT.localName match { - case StructNameT(StructTemplateNameT(humanName), _) => humanName - case _ => vfail("Can't export something that doesn't have a human readable name!") - } - coutputs.addKindExport( - structA.range, - placeholderedStructTT, - exportPackageCoord.packageCoordinate, - exportedName) - } - } } def translateCitizenAttributes(attrs: Vector[ICitizenAttributeS]): Vector[ICitizenAttributeT] = { @@ -299,22 +283,6 @@ class StructCompilerCore( internalMethods) coutputs.addInterface(interfaceDef2) - maybeExport match { - case None => - case Some(exportPackageCoord) => { - val exportedName = - placeholderedIdT.localName match { - case InterfaceNameT(InterfaceTemplateNameT(humanName), _) => humanName - case _ => vfail("Can't export something that doesn't have a human readable name!") - } - coutputs.addKindExport( - interfaceA.range, - placeholderedInterfaceTT, - exportPackageCoord.packageCoordinate, - exportedName) - } - } - (interfaceDef2) } diff --git a/Frontend/TypingPass/src/dev/vale/typing/expression/ExpressionCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/expression/ExpressionCompiler.scala index 46ddb189b..bf79a8a3f 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/expression/ExpressionCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/expression/ExpressionCompiler.scala @@ -21,7 +21,7 @@ import dev.vale.typing.OverloadResolver.FindFunctionFailure import dev.vale.typing.{ast, _} import dev.vale.typing.ast._ import dev.vale.typing.env._ -import dev.vale.typing.function.FunctionCompiler.{EvaluateFunctionFailure, EvaluateFunctionSuccess, IEvaluateFunctionResult} +import dev.vale.typing.function._ import dev.vale.typing.names.{ArbitraryNameT, CitizenTemplateNameT, ClosureParamNameT, CodeVarNameT, IImplNameT, IVarNameT, IdT, LambdaCitizenNameT, LambdaCitizenTemplateNameT, NameTranslator, RuneNameT, TypingPassBlockResultVarNameT, TypingPassFunctionResultVarNameT} import dev.vale.typing.templata._ import dev.vale.typing.types._ diff --git a/Frontend/TypingPass/src/dev/vale/typing/function/DestructorCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/function/DestructorCompiler.scala index 945473d7e..ab37a7a3e 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/function/DestructorCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/function/DestructorCompiler.scala @@ -20,7 +20,7 @@ import dev.vale.typing.types._ import dev.vale.typing.{ast, _} import dev.vale.typing.ast._ import dev.vale.typing.env._ -import dev.vale.typing.function.FunctionCompiler.EvaluateFunctionSuccess +import dev.vale.typing.function._ import dev.vale.typing.names.PackageTopLevelNameT import scala.collection.immutable.List diff --git a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompiler.scala index 2e92a9083..11cfd5596 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompiler.scala @@ -14,7 +14,6 @@ import dev.vale.typing.OverloadResolver.IFindFunctionFailureReason import dev.vale.typing._ import dev.vale.typing.ast._ import dev.vale.typing.env._ -import FunctionCompiler.IEvaluateFunctionResult import dev.vale.highertyping.FunctionA import dev.vale.typing.{CompilerOutputs, ConvertHelper, IFunctionGenerator, InferCompiler, TemplataCompiler, TypingPassOptions} import dev.vale.typing.ast.{FunctionBannerT, FunctionHeaderT, LocationInFunctionEnvironmentT, ParameterT, PrototypeT, ReferenceExpressionTE} @@ -67,18 +66,18 @@ trait IFunctionCompilerDelegate { FunctionHeaderT } -object FunctionCompiler { - trait IEvaluateFunctionResult +object FunctionCompiler - case class EvaluateFunctionSuccess( +trait IEvaluateFunctionResult + +case class EvaluateFunctionSuccess( prototype: PrototypeTemplataT, inferences: Map[IRuneS, ITemplataT[ITemplataType]] - ) extends IEvaluateFunctionResult +) extends IEvaluateFunctionResult - case class EvaluateFunctionFailure( +case class EvaluateFunctionFailure( reason: IFindFunctionFailureReason - ) extends IEvaluateFunctionResult -} +) extends IEvaluateFunctionResult // When typingpassing a function, these things need to happen: // - Spawn a local environment for the function diff --git a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerClosureOrLightLayer.scala b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerClosureOrLightLayer.scala index faea1698f..4d3fc5626 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerClosureOrLightLayer.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerClosureOrLightLayer.scala @@ -10,7 +10,7 @@ import dev.vale.postparsing.IFunctionDeclarationNameS import dev.vale.typing._ import dev.vale.typing.ast._ import dev.vale.typing.env._ -import FunctionCompiler.IEvaluateFunctionResult +import dev.vale.typing.function._ import dev.vale.typing.ast.{FunctionBannerT, FunctionHeaderT, PrototypeT} import dev.vale.typing.env.{AddressibleClosureVariableT, BuildingFunctionEnvironmentWithClosuredsT, IEnvEntry, IInDenizenEnvironmentT, IVariableT, ReferenceClosureVariableT, TemplataEnvEntry, TemplatasStore} import dev.vale.typing.{CompilerOutputs, ConvertHelper, InferCompiler, TemplataCompiler, TypingPassOptions, env} diff --git a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerCore.scala b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerCore.scala index 3879fe04c..b261ac0b4 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerCore.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerCore.scala @@ -142,7 +142,7 @@ class FunctionCompilerCore( val header = makeExternFunction( coutputs, - fullEnv.id, + fullEnv, fullEnv.function.range, translateFunctionAttributes(fullEnv.function.attributes), params2, @@ -212,22 +212,22 @@ class FunctionCompilerCore( } } - maybeExport match { - case None => - case Some(exportPackageCoord) => { - val exportedName = - fullEnv.id.localName match { - case FunctionNameT(FunctionTemplateNameT(humanName, _), _, _) => humanName - case _ => vfail("Can't export something that doesn't have a human readable name!") - } - coutputs.addInstantiationBounds(header.toPrototype.id, InstantiationBoundArgumentsT(Map(), Map())) - coutputs.addFunctionExport( - fullEnv.function.range, - header.toPrototype, - exportPackageCoord.packageCoordinate, - exportedName) - } - } + // maybeExport match { + // case None => + // case Some(exportPackageCoord) => { + // val exportedName = + // fullEnv.id.localName match { + // case FunctionNameT(FunctionTemplateNameT(humanName, _), _, _) => humanName + // case _ => vfail("Can't export something that doesn't have a human readable name!") + // } + // coutputs.addInstantiationBounds(header.toPrototype.id, InstantiationBoundArgumentsT(Map(), Map())) + // coutputs.addFunctionExport( + // fullEnv.function.range, + // header.toPrototype, + // exportPackageCoord.packageCoordinate, + // exportedName) + // } + // } if (header.attributes.contains(PureT)) { // header.params.foreach(param => { @@ -338,26 +338,27 @@ class FunctionCompilerCore( def makeExternFunction( coutputs: CompilerOutputs, - id: IdT[IFunctionNameT], + env: FunctionEnvironmentT, range: RangeS, attributes: Vector[IFunctionAttributeT], params2: Vector[ParameterT], returnType2: CoordT, maybeOrigin: Option[FunctionTemplataT]): (FunctionHeaderT) = { - id.localName match { + env.id.localName match { case FunctionNameT(FunctionTemplateNameT(humanName, _), Vector(), params) => { val header = ast.FunctionHeaderT( - id, - Vector(ExternT(range.file.packageCoordinate)) ++ attributes, + env.id, + attributes, +// Vector(RegionT(env.defaultRegion.localName, true)), params2, returnType2, maybeOrigin) - val externId = IdT(id.packageCoord, Vector.empty, interner.intern(ExternFunctionNameT(humanName, params))) - val externPrototype = PrototypeT(externId, header.returnType) - coutputs.addFunctionExtern(range, externPrototype, id.packageCoord, humanName) + val externFunctionId = IdT(env.id.packageCoord, Vector.empty, interner.intern(ExternFunctionNameT(humanName, params))) + val externPrototype = PrototypeT(externFunctionId, header.returnType) + coutputs.addInstantiationBounds(externPrototype.id, InstantiationBoundArgumentsT(Map(), Map())) val argLookups = @@ -373,7 +374,9 @@ class FunctionCompilerCore( coutputs.addFunction(function2) (header) } - case _ => throw CompileErrorExceptionT(RangedInternalErrorT(List(range), "Only human-named function can be extern!")) + case _ => { + throw CompileErrorExceptionT(RangedInternalErrorT(List(range), "Only human-named function can be extern!")) + } } } diff --git a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerMiddleLayer.scala b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerMiddleLayer.scala index c90b05d81..73fdef5c5 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerMiddleLayer.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerMiddleLayer.scala @@ -306,7 +306,7 @@ class FunctionCompilerMiddleLayer( case None => interner.intern(TypingIgnoredParamNameT(index)) case Some(x) => nameTranslator.translateVarNameStep(x.name) } - ParameterT(nameT, maybeVirtuality, coord) + ParameterT(nameT, maybeVirtuality, param1.preChecked, coord) }) } // diff --git a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerSolvingLayer.scala b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerSolvingLayer.scala index 771d0d13e..27b1f563b 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerSolvingLayer.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerSolvingLayer.scala @@ -4,7 +4,6 @@ import dev.vale.{Err, Interner, Keywords, Ok, Profiler, RangeS, StrI, typing, va import dev.vale.highertyping.FunctionA import dev.vale.postparsing.rules.{IRulexSR, RuneUsage} import dev.vale.typing.citizen.StructCompiler -import dev.vale.typing.function.FunctionCompiler.IEvaluateFunctionResult import dev.vale.postparsing.patterns._ import dev.vale.typing.types._ import dev.vale.typing.templata._ @@ -13,7 +12,7 @@ import dev.vale.typing.OverloadResolver.InferFailure import dev.vale.typing._ import dev.vale.typing.ast._ import dev.vale.typing.env._ -import FunctionCompiler.{EvaluateFunctionFailure, EvaluateFunctionSuccess, IEvaluateFunctionResult} +import dev.vale.typing.function._ import dev.vale.solver.{CompleteSolve, FailedSolve, IncompleteSolve, Solver} import dev.vale.typing.ast.{FunctionBannerT, FunctionHeaderT, PrototypeT} import dev.vale.typing.env.{BuildingFunctionEnvironmentWithClosuredsT, BuildingFunctionEnvironmentWithClosuredsAndTemplateArgsT, TemplataEnvEntry, TemplataLookupContext} diff --git a/Frontend/TypingPass/src/dev/vale/typing/macros/AbstractBodyMacro.scala b/Frontend/TypingPass/src/dev/vale/typing/macros/AbstractBodyMacro.scala index ba17f4699..88bb73988 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/macros/AbstractBodyMacro.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/macros/AbstractBodyMacro.scala @@ -9,7 +9,7 @@ import dev.vale.typing.ast.{AbstractT, ArgLookupTE, BlockTE, FunctionDefinitionT import dev.vale.typing.env.{FunctionEnvironmentT, TemplatasStore} import dev.vale.typing.types.CoordT import dev.vale.typing.ast._ -import dev.vale.typing.function.FunctionCompiler.EvaluateFunctionSuccess +import dev.vale.typing.function._ import dev.vale.typing.templata.{FunctionTemplataT, PrototypeTemplataT} class AbstractBodyMacro(interner: Interner, keywords: Keywords, overloadResolver: OverloadResolver) extends IFunctionBodyMacro { diff --git a/Frontend/TypingPass/src/dev/vale/typing/macros/FunctorHelper.scala b/Frontend/TypingPass/src/dev/vale/typing/macros/FunctorHelper.scala index 1a3df953c..47c12993d 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/macros/FunctorHelper.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/macros/FunctorHelper.scala @@ -12,7 +12,7 @@ import dev.vale.typing.types._ import dev.vale.typing.ast._ import dev.vale.typing.expression.CallCompiler import dev.vale.typing.function.FunctionCompiler -import dev.vale.typing.function.FunctionCompiler.{EvaluateFunctionFailure, EvaluateFunctionSuccess} +import dev.vale.typing.function._ import dev.vale.typing.names.RuneNameT import dev.vale.typing.templata.PrototypeTemplataT import dev.vale.typing.types.CoordT diff --git a/Frontend/TypingPass/src/dev/vale/typing/macros/StructConstructorMacro.scala b/Frontend/TypingPass/src/dev/vale/typing/macros/StructConstructorMacro.scala index 1e24fd81a..09938cfcd 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/macros/StructConstructorMacro.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/macros/StructConstructorMacro.scala @@ -18,7 +18,6 @@ import dev.vale.typing.OverloadResolver.FindFunctionFailure import dev.vale.typing.ast._ import dev.vale.typing.env.PackageEnvironmentT import dev.vale.typing.expression.CallCompiler -import dev.vale.typing.function.FunctionCompiler.EvaluateFunctionSuccess import dev.vale.typing.function.{DestructorCompiler, FunctionCompilerCore} import dev.vale.typing.infer.CouldntFindFunction import dev.vale.typing.templata.ITemplataT.expectMutability @@ -138,7 +137,7 @@ class StructConstructorMacro( val constructorId = env.id vassert(constructorId.localName.parameters.size == members.size) val constructorParams = - members.map({ case (name, coord) => ParameterT(name, None, coord) }) + members.map({ case (name, coord) => ParameterT(name, None, false, coord) }) val mutability = StructCompiler.getMutability( interner, keywords, coutputs, structTT, diff --git a/Frontend/TypingPass/src/dev/vale/typing/names/names.scala b/Frontend/TypingPass/src/dev/vale/typing/names/names.scala index aeb7c1fce..5651eb4ff 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/names/names.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/names/names.scala @@ -311,6 +311,16 @@ case class BuildingFunctionNameWithClosuredsT( +} + +case class ExternTemplateNameT( + codeLoc: CodeLocationS, +) extends ITemplateNameT + +case class ExternNameT( + template: ExternTemplateNameT +) extends IInstantiationNameT { + override def templateArgs: Vector[ITemplataT[ITemplataType]] = Vector() } case class ExternFunctionNameT( diff --git a/Frontend/TypingPass/test/dev/vale/typing/CompilerLambdaTests.scala b/Frontend/TypingPass/test/dev/vale/typing/CompilerLambdaTests.scala index f246d35d3..fae5bfb9e 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/CompilerLambdaTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/CompilerLambdaTests.scala @@ -49,7 +49,7 @@ class CompilerLambdaTests extends FunSuite with Matchers { // Make sure it inferred the param type and return type correctly Collector.only(coutputs.lookupLambdaIn("main"), - { case ParameterT(_, None, CoordT(ShareT, _, IntT.i32)) => }) + { case ParameterT(_, None, _, CoordT(ShareT, _, IntT.i32)) => }) coutputs.lookupLambdaIn("main").header.returnType shouldEqual CoordT(ShareT, GlobalRegionT(), IntT.i32) @@ -128,7 +128,7 @@ class CompilerLambdaTests extends FunSuite with Matchers { val lambda = coutputs.lookupLambdaIn("main"); // Check that the param type is right - Collector.only(lambda, { case ParameterT(CodeVarNameT(StrI("a")), None, CoordT(ShareT, _, IntT.i32)) => {} }) + Collector.only(lambda, { case ParameterT(CodeVarNameT(StrI("a")), None, _, CoordT(ShareT, _, IntT.i32)) => {} }) // Check the name is right vassert(coutputs.nameIsLambdaIn(lambda.header.id, "main")) diff --git a/Frontend/TypingPass/test/dev/vale/typing/CompilerSolverTests.scala b/Frontend/TypingPass/test/dev/vale/typing/CompilerSolverTests.scala index 586618f55..c617ac811 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/CompilerSolverTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/CompilerSolverTests.scala @@ -14,7 +14,7 @@ import dev.vale.postparsing._ import dev.vale.solver.{FailedSolve, IncompleteSolve, RuleError, SolverConflict, Step} import dev.vale.typing.ast.{ConstantIntTE, FunctionCallTE, KindExportT, PrototypeT, SignatureT} import dev.vale.typing.infer.{CallResultWasntExpectedType, ITypingPassSolverError, KindIsNotConcrete, SendingNonCitizen} -import dev.vale.typing.names.{BuildingFunctionNameWithClosuredsT, CitizenNameT, CitizenTemplateNameT, FunctionBoundNameT, FunctionBoundTemplateNameT, FunctionNameT, FunctionTemplateNameT, IdT, InterfaceNameT, InterfaceTemplateNameT, KindPlaceholderNameT, KindPlaceholderTemplateNameT, StructNameT, StructTemplateNameT} +import dev.vale.typing.names._ import dev.vale.typing.templata._ import dev.vale.typing.ast._ import dev.vale.typing.templata._ @@ -200,18 +200,27 @@ class CompilerSolverTests extends FunSuite with Matchers { val keywords = new Keywords(interner) val tz = List(RangeS.testZero(interner)) val testPackageCoord = PackageCoordinate.TEST_TLD(interner, keywords) + val tzCodeLoc = CodeLocationS.testZero(interner) + val funcTemplateName = FunctionTemplateNameT(interner.intern(StrI("main")), tzCodeLoc) + val funcTemplateId = IdT(testPackageCoord, Vector(), funcTemplateName) + val funcName = IdT(testPackageCoord, Vector(), FunctionNameT(FunctionTemplateNameT(interner.intern(StrI("main")), tzCodeLoc), Vector(), Vector())) + val regionName = funcTemplateId.addStep(interner.intern(KindPlaceholderNameT(interner.intern(KindPlaceholderTemplateNameT(0, DenizenDefaultRegionRuneS(FunctionNameS(funcTemplateName.humanName, funcTemplateName.codeLocation))))))) + val region = GlobalRegionT() + val fireflyKind = StructTT(IdT(testPackageCoord, Vector(), StructNameT(StructTemplateNameT(StrI("Firefly")), Vector()))) - val fireflyCoord = CoordT(OwnT,GlobalRegionT(), fireflyKind) + val fireflyCoord = CoordT(OwnT,region,fireflyKind) val serenityKind = StructTT(IdT(testPackageCoord, Vector(), StructNameT(StructTemplateNameT(StrI("Serenity")), Vector()))) - val serenityCoord = CoordT(OwnT,GlobalRegionT(), serenityKind) + val serenityCoord = CoordT(OwnT,region,serenityKind) val ispaceshipKind = InterfaceTT(IdT(testPackageCoord, Vector(), InterfaceNameT(InterfaceTemplateNameT(StrI("ISpaceship")), Vector()))) - val ispaceshipCoord = CoordT(OwnT,GlobalRegionT(), ispaceshipKind) + val ispaceshipCoord = CoordT(OwnT,region,ispaceshipKind) val unrelatedKind = StructTT(IdT(testPackageCoord, Vector(), StructNameT(StructTemplateNameT(StrI("Spoon")), Vector()))) - val unrelatedCoord = CoordT(OwnT,GlobalRegionT(), unrelatedKind) + val unrelatedCoord = CoordT(OwnT,region,unrelatedKind) val fireflySignature = SignatureT(IdT(testPackageCoord, Vector(), interner.intern(FunctionNameT(interner.intern(FunctionTemplateNameT(interner.intern(StrI("myFunc")), tz.head.begin)), Vector(), Vector(fireflyCoord))))) - val fireflyExport = KindExportT(tz.head, fireflyKind, testPackageCoord, interner.intern(StrI("Firefly"))); - val serenityExport = KindExportT(tz.head, fireflyKind, testPackageCoord, interner.intern(StrI("Serenity"))); + val fireflyExportId = IdT(testPackageCoord, Vector(), interner.intern(ExportNameT(ExportTemplateNameT(tz.head.begin)))) + val fireflyExport = KindExportT(tz.head, fireflyKind, fireflyExportId, interner.intern(StrI("Firefly"))); + val serenityExportId = IdT(testPackageCoord, Vector(), interner.intern(ExportNameT(ExportTemplateNameT(tz.head.begin)))) + val serenityExport = KindExportT(tz.head, fireflyKind, serenityExportId, interner.intern(StrI("Serenity"))); val codeStr = "Hello I am A large piece Of code [that has An error]" val filenamesAndSources = FileCoordinateMap.test(interner, codeStr) diff --git a/Frontend/TypingPass/test/dev/vale/typing/CompilerTests.scala b/Frontend/TypingPass/test/dev/vale/typing/CompilerTests.scala index 2866e81d9..cdf7467e7 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/CompilerTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/CompilerTests.scala @@ -15,8 +15,8 @@ import dev.vale.Collector.ProgramWithExpect import dev.vale.postparsing._ import dev.vale.postparsing.rules.IRulexSR import dev.vale.solver.{FailedSolve, RuleError, Step} -import dev.vale.typing.ast.{ConstantIntTE, DestroyTE, DiscardTE, FunctionCallTE, FunctionHeaderT, FunctionDefinitionT, KindExportT, LetAndLendTE, LetNormalTE, LocalLookupTE, ParameterT, PrototypeT, ReferenceMemberLookupTE, ReturnTE, SignatureT, SoftLoadTE, UserFunctionT, referenceExprResultKind, referenceExprResultStructName} -import dev.vale.typing.names.{BuildingFunctionNameWithClosuredsT, CitizenNameT, CitizenTemplateNameT, CodeVarNameT, IdT, FunctionNameT, FunctionTemplateNameT, InterfaceNameT, InterfaceTemplateNameT, KindPlaceholderNameT, KindPlaceholderTemplateNameT, StructNameT, StructTemplateNameT} +import dev.vale.typing.ast.{ConstantIntTE, DestroyTE, DiscardTE, FunctionCallTE, FunctionDefinitionT, FunctionHeaderT, KindExportT, LetAndLendTE, LetNormalTE, LocalLookupTE, ParameterT, PrototypeT, ReferenceMemberLookupTE, ReturnTE, SignatureT, SoftLoadTE, UserFunctionT, referenceExprResultKind, referenceExprResultStructName} +import dev.vale.typing.names.{BuildingFunctionNameWithClosuredsT, CitizenNameT, CitizenTemplateNameT, CodeVarNameT, ExportNameT, ExportTemplateNameT, FunctionNameT, FunctionTemplateNameT, IdT, InterfaceNameT, InterfaceTemplateNameT, KindPlaceholderNameT, KindPlaceholderTemplateNameT, StructNameT, StructTemplateNameT} import dev.vale.typing.templata._ import dev.vale.typing.types._ import dev.vale.typing.ast._ @@ -292,7 +292,7 @@ class CompilerTests extends FunSuite with Matchers { case FunctionHeaderT( simpleName("MyStruct"), _, - Vector(ParameterT(CodeVarNameT(StrI("a")), None, CoordT(ShareT, _,IntT.i32))), + Vector(ParameterT(CodeVarNameT(StrI("a")), None, _, CoordT(ShareT, _,IntT.i32))), CoordT(OwnT, _,StructTT(simpleName("MyStruct"))), _) => }) @@ -586,6 +586,7 @@ class CompilerTests extends FunSuite with Matchers { ParameterT( CodeVarNameT(StrI("value")), None, + _, CoordT(OwnT,_,KindPlaceholderT(IdT(_,_,KindPlaceholderNameT(KindPlaceholderTemplateNameT(0, _))))))), CoordT( OwnT, @@ -1197,20 +1198,29 @@ class CompilerTests extends FunSuite with Matchers { test("Humanize errors") { val interner = new Interner() val keywords = new Keywords(interner) + val testPackageCoord = PackageCoordinate.TEST_TLD(interner, keywords) val tz = List(RangeS.testZero(interner)) - - val fireflyKind = StructTT(IdT(PackageCoordinate.TEST_TLD(interner, keywords), Vector(), StructNameT(StructTemplateNameT(StrI("Firefly")), Vector()))) - val fireflyCoord = CoordT(OwnT,GlobalRegionT(), fireflyKind) - val serenityKind = StructTT(IdT(PackageCoordinate.TEST_TLD(interner, keywords), Vector(), StructNameT(StructTemplateNameT(StrI("Serenity")), Vector()))) - val serenityCoord = CoordT(OwnT,GlobalRegionT(), serenityKind) - val ispaceshipKind = InterfaceTT(IdT(PackageCoordinate.TEST_TLD(interner, keywords), Vector(), InterfaceNameT(InterfaceTemplateNameT(StrI("ISpaceship")), Vector()))) - val ispaceshipCoord = CoordT(OwnT,GlobalRegionT(), ispaceshipKind) - val unrelatedKind = StructTT(IdT(PackageCoordinate.TEST_TLD(interner, keywords), Vector(), StructNameT(StructTemplateNameT(StrI("Spoon")), Vector()))) - val unrelatedCoord = CoordT(OwnT,GlobalRegionT(), unrelatedKind) - val fireflyTemplateName = IdT(PackageCoordinate.TEST_TLD(interner, keywords), Vector(), interner.intern(FunctionTemplateNameT(interner.intern(StrI("myFunc")), tz.head.begin))) - val fireflySignature = ast.SignatureT(IdT(PackageCoordinate.TEST_TLD(interner, keywords), Vector(), interner.intern(FunctionNameT(interner.intern(FunctionTemplateNameT(interner.intern(StrI("myFunc")), tz.head.begin)), Vector(), Vector(fireflyCoord))))) - val fireflyExport = KindExportT(tz.head, fireflyKind, PackageCoordinate.TEST_TLD(interner, keywords), interner.intern(StrI("Firefly"))); - val serenityExport = KindExportT(tz.head, fireflyKind, PackageCoordinate.TEST_TLD(interner, keywords), interner.intern(StrI("Serenity"))); + val tzCodeLoc = CodeLocationS.testZero(interner) + val funcTemplateName = FunctionTemplateNameT(interner.intern(StrI("main")), tzCodeLoc) + val funcTemplateId = IdT(testPackageCoord, Vector(), funcTemplateName) + val funcName = IdT(testPackageCoord, Vector(), FunctionNameT(FunctionTemplateNameT(interner.intern(StrI("main")), tzCodeLoc), Vector(), Vector())) + val regionName = funcTemplateId.addStep(interner.intern(KindPlaceholderNameT(interner.intern(KindPlaceholderTemplateNameT(0, DenizenDefaultRegionRuneS(FunctionNameS(funcTemplateName.humanName, funcTemplateName.codeLocation))))))) + val region = GlobalRegionT() + + val fireflyKind = StructTT(IdT(testPackageCoord, Vector(), StructNameT(StructTemplateNameT(StrI("Firefly")), Vector()))) + val fireflyCoord = CoordT(OwnT,region,fireflyKind) + val serenityKind = StructTT(IdT(testPackageCoord, Vector(), StructNameT(StructTemplateNameT(StrI("Serenity")), Vector()))) + val serenityCoord = CoordT(OwnT,region,serenityKind) + val ispaceshipKind = InterfaceTT(IdT(testPackageCoord, Vector(), InterfaceNameT(InterfaceTemplateNameT(StrI("ISpaceship")), Vector()))) + val ispaceshipCoord = CoordT(OwnT,region,ispaceshipKind) + val unrelatedKind = StructTT(IdT(testPackageCoord, Vector(), StructNameT(StructTemplateNameT(StrI("Spoon")), Vector()))) + val unrelatedCoord = CoordT(OwnT,region,unrelatedKind) + val fireflyTemplateName = IdT(testPackageCoord, Vector(), interner.intern(FunctionTemplateNameT(interner.intern(StrI("myFunc")), tz.head.begin))) + val fireflySignature = ast.SignatureT(IdT(testPackageCoord, Vector(), interner.intern(FunctionNameT(interner.intern(FunctionTemplateNameT(interner.intern(StrI("myFunc")), tz.head.begin)), Vector(), Vector(fireflyCoord))))) + val fireflyExportId = IdT(testPackageCoord, Vector(), interner.intern(ExportNameT(ExportTemplateNameT(tz.head.begin)))) + val fireflyExport = KindExportT(tz.head, fireflyKind, fireflyExportId, interner.intern(StrI("Firefly"))); + val serenityExportId = IdT(testPackageCoord, Vector(), interner.intern(ExportNameT(ExportTemplateNameT(tz.head.begin)))) + val serenityExport = KindExportT(tz.head, fireflyKind, serenityExportId, interner.intern(StrI("Serenity"))); val filenamesAndSources = FileCoordinateMap.test(interner, "blah blah blah\nblah blah blah") From f78060ec3d13811e9f7d4afbfd90b7a8ffe1dbff Mon Sep 17 00:00:00 2001 From: Evan Ovadia <> Date: Sun, 9 Jul 2023 15:03:10 -0400 Subject: [PATCH 2/5] Regions merge: bringing in Instantiator phase from regions branch --- Frontend/Builtins/src/dev/vale/Builtins.scala | 6 + .../src/dev/vale/resources/arith.vale | 3 + .../src/dev/vale/resources/arrays.vale | 18 +- .../Builtins/src/dev/vale/resources/opt.vale | 2 +- .../src/dev/vale/resources/panic.vale | 13 - .../src/dev/vale/resources/panicutils.vale | 13 + .../src/dev/vale/resources/result.vale | 2 +- .../resources/runtime_sized_array_len.vale | 2 + .../runtime_sized_array_mut_new.vale | 3 + .../resources/runtime_sized_array_pop.vale | 2 + .../resources/runtime_sized_array_push.vale | 2 + .../Builtins/src/dev/vale/resources/str.vale | 9 - .../src/dev/vale/resources/streq.vale | 9 + .../src/dev/vale/finalast/MetalPrinter.scala | 37 - .../FinalAST/src/dev/vale/finalast/ast.scala | 41 +- .../src/dev/vale/finalast/instructions.scala | 113 +- .../src/dev/vale/finalast/types.scala | 30 +- .../InstantiatedCompilation.scala | 11 +- .../instantiating/InstantiatedHumanizer.scala | 213 + .../dev/vale/instantiating/Instantiator.scala | 4016 ++++++++++++----- .../RegionCollapserConsistent.scala | 411 ++ .../RegionCollapserIndividual.scala | 383 ++ .../vale/instantiating/RegionCounter.scala | 470 ++ .../dev/vale/instantiating/ast/HinputsI.scala | 211 + .../instantiating/ast/TemplataUtils.scala | 41 + .../src/dev/vale/instantiating/ast/ast.scala | 359 ++ .../dev/vale/instantiating/ast/citizens.scala | 110 + .../vale/instantiating/ast/expressions.scala | 906 ++++ .../dev/vale/instantiating/ast/names.scala | 625 +++ .../dev/vale/instantiating/ast/templata.scala | 243 + .../dev/vale/instantiating/ast/types.scala | 240 + .../IntegrationTests/IntegrationTests.iml | 1 + .../vale/AfterRegionsIntegrationTests.scala | 2 +- .../test/dev/vale/ArrayTests.scala | 12 +- .../test/dev/vale/HammerTests.scala | 13 +- .../test/dev/vale/IntegrationTestsA.scala | 20 +- .../test/dev/vale/PatternTests.scala | 8 +- .../test/dev/vale/ResultTests.scala | 12 +- .../test/dev/vale/VirtualTests.scala | 11 +- Frontend/PassManager/PassManager.iml | 1 + .../vale/passmanager/FullCompilation.scala | 9 +- Frontend/SimplifyingPass/SimplifyingPass.iml | 2 +- .../dev/vale/simplifying/BlockHammer.scala | 75 +- .../dev/vale/simplifying/Conversions.scala | 63 +- .../vale/simplifying/ExpressionHammer.scala | 321 +- .../dev/vale/simplifying/FunctionHammer.scala | 41 +- .../src/dev/vale/simplifying/Hammer.scala | 63 +- .../vale/simplifying/HammerCompilation.scala | 10 +- .../src/dev/vale/simplifying/Hamuts.scala | 185 +- .../src/dev/vale/simplifying/LetHammer.scala | 189 +- .../src/dev/vale/simplifying/LoadHammer.scala | 341 +- .../dev/vale/simplifying/MutateHammer.scala | 152 +- .../src/dev/vale/simplifying/NameHammer.scala | 70 +- .../dev/vale/simplifying/StructHammer.scala | 148 +- .../src/dev/vale/simplifying/TypeHammer.scala | 147 +- .../src/dev/vale/simplifying/VonHammer.scala | 58 +- .../src/dev/vale/testvm/ExpressionVivem.scala | 148 +- .../src/dev/vale/testvm/FunctionVivem.scala | 92 +- .../TestVM/src/dev/vale/testvm/Heap.scala | 40 +- .../TestVM/src/dev/vale/testvm/Values.scala | 4 +- .../TestVM/src/dev/vale/testvm/Vivem.scala | 4 +- .../src/dev/vale/testvm/VivemExterns.scala | 93 +- .../test/dev/vale/testvm/VivemTests.scala | 16 +- .../main/resources/panicutils/panicutils.vale | 1 + .../src/dev/vale/typing/ArrayCompiler.scala | 2 +- .../src/dev/vale/typing/Compilation.scala | 6 +- .../src/dev/vale/typing/Compiler.scala | 4 +- .../typing/{Hinputs.scala => HinputsT.scala} | 2 +- .../dev/vale/typing/TemplataCompiler.scala | 12 +- .../src/dev/vale/typing/ast/expressions.scala | 15 +- .../expression/ExpressionCompiler.scala | 2 +- .../vale/typing/expression/LocalHelper.scala | 2 +- .../function/FunctionCompilerCore.scala | 10 +- .../vale/typing/AfterRegionsErrorTests.scala | 2 +- .../dev/vale/typing/CompilerMutateTests.scala | 2 - .../dev/vale/typing/CompilerSolverTests.scala | 4 +- .../test/dev/vale/typing/CompilerTests.scala | 11 +- docs/Generics.md | 3 +- 78 files changed, 8582 insertions(+), 2391 deletions(-) create mode 100644 Frontend/Builtins/src/dev/vale/resources/panicutils.vale create mode 100644 Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_len.vale create mode 100644 Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_mut_new.vale create mode 100644 Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_pop.vale create mode 100644 Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_push.vale create mode 100644 Frontend/Builtins/src/dev/vale/resources/streq.vale create mode 100644 Frontend/InstantiatingPass/src/dev/vale/instantiating/InstantiatedHumanizer.scala create mode 100644 Frontend/InstantiatingPass/src/dev/vale/instantiating/RegionCollapserConsistent.scala create mode 100644 Frontend/InstantiatingPass/src/dev/vale/instantiating/RegionCollapserIndividual.scala create mode 100644 Frontend/InstantiatingPass/src/dev/vale/instantiating/RegionCounter.scala create mode 100644 Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/HinputsI.scala create mode 100644 Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/TemplataUtils.scala create mode 100644 Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/ast.scala create mode 100644 Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/citizens.scala create mode 100644 Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/expressions.scala create mode 100644 Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/names.scala create mode 100644 Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/templata.scala create mode 100644 Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/types.scala rename Frontend/TypingPass/src/dev/vale/typing/{Hinputs.scala => HinputsT.scala} (99%) diff --git a/Frontend/Builtins/src/dev/vale/Builtins.scala b/Frontend/Builtins/src/dev/vale/Builtins.scala index d7c2af7ae..2b9d35dd7 100644 --- a/Frontend/Builtins/src/dev/vale/Builtins.scala +++ b/Frontend/Builtins/src/dev/vale/Builtins.scala @@ -16,11 +16,17 @@ object Builtins { "drop" -> "drop.vale", "clone" -> "clone.vale", "arrays" -> "arrays.vale", + "runtime_sized_array_mut_new" -> "runtime_sized_array_mut_new.vale", + "runtime_sized_array_push" -> "runtime_sized_array_push.vale", + "runtime_sized_array_pop" -> "runtime_sized_array_pop.vale", + "runtime_sized_array_len" -> "runtime_sized_array_len.vale", "mainargs" -> "mainargs.vale", "as" -> "as.vale", "print" -> "print.vale", "tup" -> "tup.vale", + "streq" -> "streq.vale", "panic" -> "panic.vale", + "panicutils" -> "panicutils.vale", "opt" -> "opt.vale", "result" -> "result.vale", "sameinstance" -> "sameinstance.vale", diff --git a/Frontend/Builtins/src/dev/vale/resources/arith.vale b/Frontend/Builtins/src/dev/vale/resources/arith.vale index 2c79e753e..7864a62f1 100644 --- a/Frontend/Builtins/src/dev/vale/resources/arith.vale +++ b/Frontend/Builtins/src/dev/vale/resources/arith.vale @@ -7,6 +7,9 @@ extern func castFloatI32(x float) int; extern func TruncateI64ToI32(x i64) int; +func i64(x int) i64 { __vbi_ExtendI32ToI64(x) } +extern func __vbi_ExtendI32ToI64(x int) i64; + func -(x int) int { return __vbi_negateI32(x); } extern func __vbi_negateI32(x int) int; diff --git a/Frontend/Builtins/src/dev/vale/resources/arrays.vale b/Frontend/Builtins/src/dev/vale/resources/arrays.vale index ba8ce136b..c1ce1b6ee 100644 --- a/Frontend/Builtins/src/dev/vale/resources/arrays.vale +++ b/Frontend/Builtins/src/dev/vale/resources/arrays.vale @@ -1,6 +1,10 @@ import v.builtins.arith.*; import v.builtins.drop.*; import v.builtins.panic.*; +import v.builtins.runtime_sized_array_mut_new.*; +import v.builtins.runtime_sized_array_push.*; +import v.builtins.runtime_sized_array_pop.*; +import v.builtins.runtime_sized_array_len.*; func drop_into(arr [#S]E, consumer &F) void where func(&F, E)void @@ -47,23 +51,9 @@ where func drop(E)void { extern("vale_static_sized_array_len") func len(arr &[#S]E) int; -extern("vale_runtime_sized_array_len") -func len(arr &[]E) int; - - extern("vale_runtime_sized_array_capacity") func capacity(arr &[]E) int; -extern("vale_runtime_sized_array_push") -func push(arr &[]E, newElement E) void; - -extern("vale_runtime_sized_array_pop") -func pop(arr &[]E) E; - -extern("vale_runtime_sized_array_mut_new") -func Array(size int) []E -where M = mut; - func Array(n int, generator G) []E where M Mutability = mut, diff --git a/Frontend/Builtins/src/dev/vale/resources/opt.vale b/Frontend/Builtins/src/dev/vale/resources/opt.vale index 9340a661e..1399aa9ea 100644 --- a/Frontend/Builtins/src/dev/vale/resources/opt.vale +++ b/Frontend/Builtins/src/dev/vale/resources/opt.vale @@ -1,4 +1,4 @@ -import v.builtins.panic.*; +import v.builtins.panicutils.*; import v.builtins.drop.*; #!DeriveInterfaceDrop diff --git a/Frontend/Builtins/src/dev/vale/resources/panic.vale b/Frontend/Builtins/src/dev/vale/resources/panic.vale index d8f480d20..331e89f92 100644 --- a/Frontend/Builtins/src/dev/vale/resources/panic.vale +++ b/Frontend/Builtins/src/dev/vale/resources/panic.vale @@ -1,14 +1 @@ -import v.builtins.print.*; -import v.builtins.str.*; - -func panic() __Never { - return __vbi_panic(); -} - -func panic(msg str) __Never { - print(msg); - print("\n"); - return __vbi_panic(); -} - extern func __vbi_panic() __Never; diff --git a/Frontend/Builtins/src/dev/vale/resources/panicutils.vale b/Frontend/Builtins/src/dev/vale/resources/panicutils.vale new file mode 100644 index 000000000..f7c25182a --- /dev/null +++ b/Frontend/Builtins/src/dev/vale/resources/panicutils.vale @@ -0,0 +1,13 @@ +import v.builtins.print.*; +import v.builtins.str.*; +import v.builtins.panic.*; + +func panic() __Never { + return __vbi_panic(); +} + +func panic(msg str) __Never { + print(msg); + print("\n"); + return __vbi_panic(); +} diff --git a/Frontend/Builtins/src/dev/vale/resources/result.vale b/Frontend/Builtins/src/dev/vale/resources/result.vale index f1d2dd5bd..c86fc8be5 100644 --- a/Frontend/Builtins/src/dev/vale/resources/result.vale +++ b/Frontend/Builtins/src/dev/vale/resources/result.vale @@ -1,4 +1,4 @@ -import v.builtins.panic.*; +import v.builtins.panicutils.*; import v.builtins.logic.*; #!DeriveInterfaceDrop diff --git a/Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_len.vale b/Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_len.vale new file mode 100644 index 000000000..e544f456a --- /dev/null +++ b/Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_len.vale @@ -0,0 +1,2 @@ +extern("vale_runtime_sized_array_len") +func len(arr &[]E) int; diff --git a/Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_mut_new.vale b/Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_mut_new.vale new file mode 100644 index 000000000..6eb004eef --- /dev/null +++ b/Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_mut_new.vale @@ -0,0 +1,3 @@ +extern("vale_runtime_sized_array_mut_new") +func Array(size int) []E +where M = mut; diff --git a/Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_pop.vale b/Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_pop.vale new file mode 100644 index 000000000..dc254b448 --- /dev/null +++ b/Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_pop.vale @@ -0,0 +1,2 @@ +extern("vale_runtime_sized_array_pop") +func pop(arr &[]E) E; diff --git a/Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_push.vale b/Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_push.vale new file mode 100644 index 000000000..ce08be652 --- /dev/null +++ b/Frontend/Builtins/src/dev/vale/resources/runtime_sized_array_push.vale @@ -0,0 +1,2 @@ +extern("vale_runtime_sized_array_push") +func push(arr &[]E, newElement E) void; diff --git a/Frontend/Builtins/src/dev/vale/resources/str.vale b/Frontend/Builtins/src/dev/vale/resources/str.vale index dfcc0ad30..4511248bf 100644 --- a/Frontend/Builtins/src/dev/vale/resources/str.vale +++ b/Frontend/Builtins/src/dev/vale/resources/str.vale @@ -32,15 +32,6 @@ extern func substring( end int) str; -extern func streq( - aContainerStr str, - aBegin int, - aEnd int, - bContainerStr str, - bBegin int, - bEnd int) -bool; - extern func strcmp( aContainerStr str, aBegin int, diff --git a/Frontend/Builtins/src/dev/vale/resources/streq.vale b/Frontend/Builtins/src/dev/vale/resources/streq.vale new file mode 100644 index 000000000..0b21d9781 --- /dev/null +++ b/Frontend/Builtins/src/dev/vale/resources/streq.vale @@ -0,0 +1,9 @@ + +extern func streq( + aContainerStr str, + aBegin int, + aEnd int, + bContainerStr str, + bBegin int, + bEnd int) +bool; diff --git a/Frontend/FinalAST/src/dev/vale/finalast/MetalPrinter.scala b/Frontend/FinalAST/src/dev/vale/finalast/MetalPrinter.scala index 421f1f2d1..2c06f76c3 100644 --- a/Frontend/FinalAST/src/dev/vale/finalast/MetalPrinter.scala +++ b/Frontend/FinalAST/src/dev/vale/finalast/MetalPrinter.scala @@ -2,40 +2,3 @@ package dev.vale.finalast import dev.vale.von.{IVonData, VonPrinter, VonSyntax} -//object MetalPrinter { -// def print(data: IVonData): String = { -// val nameMap = -// Map( -// "Str" -> "s", -// "Int" -> "i", -// "Float" -> "f", -//// "Void" -> "v", -// "Bool" -> "b", -// "Function" -> "F", -// "Ref" -> "R", -// "Share" -> "@", -// "Pointer" -> "*", -// "Weak" -> "&&", -// "Own" -> "^", -// "Readonly" -> "#", -// "Readwrite" -> "!", -// "Inline" -> "<", -// "Yonder" -> ">", -// "CoordTemplata" -> "TR", -// "KindTemplata" -> "TK", -// "CitizenName" -> "C", -// "CoordListTemplata" -> "TRL", -// "CitizenTemplateName" -> "CT", -// "InterfaceTemplateName" -> "CT", -// "StructTemplateName" -> "CT", -// "Immutable" -> "imm", -// "MutabilityTemplata" -> "TM", -// "StructId" -> "SId", -// "InterfaceId" -> "IId", -// "AnonymousSubstructName" -> "AS", -// "LambdaCitizenName" -> "LC", -// ) -// val printer = new VonPrinter(VonSyntax(false, true, false, false), Int.MaxValue, nameMap, false); -// printer.print(data) -// } -//} diff --git a/Frontend/FinalAST/src/dev/vale/finalast/ast.scala b/Frontend/FinalAST/src/dev/vale/finalast/ast.scala index 9a3a5c457..e16e2066e 100644 --- a/Frontend/FinalAST/src/dev/vale/finalast/ast.scala +++ b/Frontend/FinalAST/src/dev/vale/finalast/ast.scala @@ -16,9 +16,7 @@ object ProgramH { val externRegionName = "host" } -case class RegionH( - name: String, - kinds: Vector[KindHT]) { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); } +case class RegionH() { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); } case class Export( nameH: IdH, @@ -64,7 +62,7 @@ case class PackageH( val matches = (Vector.empty ++ exportNameToFunction.find(_._1.str == readableName).map(_._2).toVector ++ - functions.filter(_.prototype.fullName.localName == readableName).map(_.prototype)) + functions.filter(_.prototype.id.localName == readableName).map(_.prototype)) .distinct vassert(matches.nonEmpty) vassert(matches.size <= 1) @@ -74,7 +72,7 @@ case class PackageH( // Convenience function for the tests to look up a struct. // Struct must be at the top level of the program. def lookupStruct(humanName: String) = { - val matches = structs.filter(_.fullName.localName == humanName) + val matches = structs.filter(_.id.localName == humanName) vassert(matches.size == 1) matches.head } @@ -82,7 +80,7 @@ case class PackageH( // Convenience function for the tests to look up an interface. // Interface must be at the top level of the program. def lookupInterface(humanName: String) = { - val matches = interfaces.filter(_.fullName.shortenedName == humanName) + val matches = interfaces.filter(_.id.shortenedName == humanName) vassert(matches.size == 1) matches.head } @@ -97,22 +95,22 @@ case class ProgramH( vassertSome(packages.get(packageCoordinate)) } def lookupFunction(prototype: PrototypeH): FunctionH = { - val paackage = lookupPackage(prototype.fullName.packageCoordinate) - val result = vassertSome(paackage.functions.find(_.fullName == prototype.fullName)) + val paackage = lookupPackage(prototype.id.packageCoordinate) + val result = vassertSome(paackage.functions.find(_.fullName == prototype.id)) vassert(prototype == result.prototype) result } def lookupStruct(structRefH: StructHT): StructDefinitionH = { - val paackage = lookupPackage(structRefH.fullName.packageCoordinate) + val paackage = lookupPackage(structRefH.id.packageCoordinate) vassertSome(paackage.structs.find(_.getRef == structRefH)) } def lookupInterface(interfaceRefH: InterfaceHT): InterfaceDefinitionH = { - val paackage = lookupPackage(interfaceRefH.fullName.packageCoordinate) + val paackage = lookupPackage(interfaceRefH.id.packageCoordinate) vassertSome(paackage.interfaces.find(_.getRef == interfaceRefH)) } def lookupStaticSizedArray(ssaTH: StaticSizedArrayHT): StaticSizedArrayDefinitionHT = { - val paackage = lookupPackage(ssaTH.name.packageCoordinate) - vassertSome(paackage.staticSizedArrays.find(_.name == ssaTH.name)) + val paackage = lookupPackage(ssaTH.id.packageCoordinate) + vassertSome(paackage.staticSizedArrays.find(_.name == ssaTH.id)) } def lookupRuntimeSizedArray(rsaTH: RuntimeSizedArrayHT): RuntimeSizedArrayDefinitionHT = { val paackage = lookupPackage(rsaTH.name.packageCoordinate) @@ -124,7 +122,7 @@ case class ProgramH( // There is only one of these per type of struct in the program. case class StructDefinitionH( // Name of the struct. Guaranteed to be unique in the entire program. - fullName: IdH, + id: IdH, // Whether we can take weak references to this object. // On native, this means an extra "weak ref count" will be included for the object. // On JVM/CLR/JS, this means the object will have an extra tiny object pointing @@ -143,7 +141,7 @@ case class StructDefinitionH( // The members of the struct, in order. members: Vector[StructMemberH]) { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - def getRef: StructHT = StructHT(fullName) + def getRef: StructHT = StructHT(id) } // A member of a struct. @@ -164,7 +162,7 @@ case class StructMemberH( // An interface definition containing name, methods, etc. case class InterfaceDefinitionH( - fullName: IdH, + id: IdH, // Whether we can take weak references to this interface. // On native, this means an extra "weak ref count" will be included for the object. // On JVM/CLR/JS, this means the object should extend the IWeakable interface, @@ -182,7 +180,7 @@ case class InterfaceDefinitionH( // All the methods that we can call on this interface. methods: Vector[InterfaceMethodH]) { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - def getRef = InterfaceHT(fullName) + def getRef = InterfaceHT(id) } // A method in an interface. @@ -218,7 +216,7 @@ case class FunctionH( // Whether this has a body. If true, the body will simply contain an InterfaceCallH instruction. isAbstract: Boolean, - // Whether this has a body. If true, the body will simply contain an ExternCallH instruction to the same + // Whether this is an extern. If true, the body will simply contain an ExternCallH instruction to the same // prototype describing this function. isExtern: Boolean, @@ -226,14 +224,17 @@ case class FunctionH( // The body of the function that contains the actual instructions. body: ExpressionH[KindHT]) { + + vpass() + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - def fullName = prototype.fullName + def fullName = prototype.id def isUserFunction = attributes.contains(UserFunctionH) } // A wrapper around a function's name, which also has its params and return type. case class PrototypeH( - fullName: IdH, + id: IdH, params: Vector[CoordH[KindHT]], returnType: CoordH[KindHT] ) { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; } @@ -247,6 +248,8 @@ case class IdH( shortenedName: String, // Most precise name, without shortening. fullyQualifiedName: String) { + vpass() + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = { diff --git a/Frontend/FinalAST/src/dev/vale/finalast/instructions.scala b/Frontend/FinalAST/src/dev/vale/finalast/instructions.scala index f536976d8..eddce18ec 100644 --- a/Frontend/FinalAST/src/dev/vale/finalast/instructions.scala +++ b/Frontend/FinalAST/src/dev/vale/finalast/instructions.scala @@ -1,7 +1,6 @@ package dev.vale.finalast -import dev.vale.{vassert, vcurious, vfail, vwat} -import dev.vale.vimpl +import dev.vale.{vassert, vcurious, vfail, vimpl, vpass, vwat} // Common trait for all instructions. sealed trait ExpressionH[+T <: KindHT] { @@ -64,7 +63,7 @@ sealed trait ExpressionH[+T <: KindHT] { // Produces a void. case class ConstantVoidH() extends ExpressionH[VoidHT] { override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = 1337 - override def resultType: CoordH[VoidHT] = CoordH(ShareH, InlineH, VoidHT()) + override def resultType: CoordH[VoidHT] = CoordH(MutableShareH, InlineH, VoidHT()) } // Produces an integer. @@ -74,7 +73,7 @@ case class ConstantIntH( bits: Int ) extends ExpressionH[IntHT] { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[IntHT] = CoordH(ShareH, InlineH, IntHT(bits)) + override def resultType: CoordH[IntHT] = CoordH(MutableShareH, InlineH, IntHT(bits)) } // Produces a boolean. @@ -83,7 +82,7 @@ case class ConstantBoolH( value: Boolean ) extends ExpressionH[BoolHT] { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[BoolHT] = CoordH(ShareH, InlineH, BoolHT()) + override def resultType: CoordH[BoolHT] = CoordH(MutableShareH, InlineH, BoolHT()) } // Produces a string. @@ -92,7 +91,7 @@ case class ConstantStrH( value: String ) extends ExpressionH[StrHT] { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[StrHT] = CoordH(ShareH, YonderH, StrHT()) + override def resultType: CoordH[StrHT] = CoordH(MutableShareH, YonderH, StrHT()) } // Produces a float. @@ -101,7 +100,7 @@ case class ConstantF64H( value: Double ) extends ExpressionH[FloatHT] { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[FloatHT] = CoordH(ShareH, InlineH, FloatHT()) + override def resultType: CoordH[FloatHT] = CoordH(MutableShareH, InlineH, FloatHT()) } // Produces the value from an argument. @@ -129,7 +128,7 @@ case class StackifyH( sourceExpr.resultType.kind match { case NeverHT(_) => vwat() case _ => } vassert(sourceExpr.resultType == local.typeH) - override def resultType: CoordH[VoidHT] = CoordH(ShareH, InlineH, VoidHT()) + override def resultType: CoordH[VoidHT] = CoordH(MutableShareH, InlineH, VoidHT()) } // Takes a value from the source expression and puts it into a local @@ -148,7 +147,7 @@ case class RestackifyH( sourceExpr.resultType.kind match { case NeverHT(_) => vwat() case _ => } vassert(sourceExpr.resultType == local.typeH) - override def resultType: CoordH[VoidHT] = CoordH(ShareH, InlineH, VoidHT()) + override def resultType: CoordH[VoidHT] = CoordH(MutableShareH, InlineH, VoidHT()) } // Takes a value from a local variable on the stack, and produces it. @@ -188,7 +187,7 @@ case class DestroyH( // Nevermind, type system guarantees it // structExpression.resultType.kind match { case NeverH(_) => vwat() case _ => } - override def resultType: CoordH[VoidHT] = CoordH(ShareH, InlineH, VoidHT()) + override def resultType: CoordH[VoidHT] = CoordH(MutableShareH, InlineH, VoidHT()) } // Takes a struct from the given expressions, and destroys it. @@ -213,7 +212,7 @@ case class DestroyStaticSizedArrayIntoLocalsH( // Nevermind, type system guarantees it // structExpression.resultType.kind match { case NeverH(_) => vwat() case _ => } - override def resultType: CoordH[VoidHT] = CoordH(ShareH, InlineH, VoidHT()) + override def resultType: CoordH[VoidHT] = CoordH(MutableShareH, InlineH, VoidHT()) } // Takes a struct reference from the "source" expressions, and makes an interface reference @@ -289,10 +288,10 @@ case class LocalLoadH( override def resultType: CoordH[KindHT] = { val location = (targetOwnership, local.typeH.location) match { - case (BorrowH, _) => YonderH + case (ImmutableBorrowH | MutableBorrowH, _) => YonderH case (WeakH, _) => YonderH case (OwnH, location) => location - case (ShareH, location) => location + case (MutableShareH | ImmutableShareH, location) => location } CoordH(targetOwnership, location, local.typeH.kind) } @@ -487,6 +486,8 @@ case class ExternCallH( // Expressions containing the arguments to pass to the function. argsExpressions: Vector[ExpressionH[KindHT]] ) extends ExpressionH[KindHT] { + vpass() + // See BRCOBS, no arguments should be Never. argsExpressions.foreach(expr => { expr.resultType.kind match { case NeverHT(_) => vwat() case _ => } @@ -560,9 +561,9 @@ case class WhileH( val resultCoord = bodyBlock.resultType.kind match { - case VoidHT() => CoordH(ShareH, InlineH, VoidHT()) - case NeverHT(true) => CoordH(ShareH, InlineH, VoidHT()) - case NeverHT(false) => CoordH(ShareH, InlineH, NeverHT(false)) + case VoidHT() => CoordH(MutableShareH, InlineH, VoidHT()) + case NeverHT(true) => CoordH(MutableShareH, InlineH, VoidHT()) + case NeverHT(false) => CoordH(MutableShareH, InlineH, NeverHT(false)) case _ => vwat() } @@ -589,7 +590,7 @@ case class ConsecutorH( // The init ones should always return void structs. // If there's a never somewhere in there, then there should be nothing afterward. // Use Hammer.consecutive to conform to this. - vassert(nonLastResultLine.resultType == CoordH(ShareH, InlineH, VoidHT())) + vassert(nonLastResultLine.resultType == CoordH(MutableShareH, InlineH, VoidHT())) }) val indexOfFirstNever = @@ -655,6 +656,44 @@ case class BlockH( override def resultType: CoordH[KindHT] = inner.resultType } +// Casts an immutable reference to a mutable one. +case class MutabilifyH( + inner: ExpressionH[KindHT], +) extends ExpressionH[KindHT] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); + override def resultType: CoordH[KindHT] = { + val CoordH(ownership, location, kind) = inner.resultType + CoordH( + ownership match { + case OwnH => OwnH + case ImmutableBorrowH | MutableBorrowH => MutableBorrowH + case ImmutableShareH | MutableShareH => MutableShareH + case WeakH => vimpl() + }, + location, + kind) + } +} + +// Casts a mutable reference to an immutable one. +case class ImmutabilifyH( + inner: ExpressionH[KindHT], +) extends ExpressionH[KindHT] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); + override def resultType: CoordH[KindHT] = { + val CoordH(ownership, location, kind) = inner.resultType + CoordH( + ownership match { + case OwnH => OwnH + case ImmutableBorrowH | MutableBorrowH => ImmutableBorrowH + case ImmutableShareH | MutableShareH => ImmutableShareH + case WeakH => vimpl() + }, + location, + kind) + } +} + // Ends the current function and returns a reference. A function will always end // with a return statement. case class ReturnH( @@ -665,7 +704,7 @@ case class ReturnH( sourceExpression.resultType.kind match { case NeverHT(_) => vwat() case _ => } val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[NeverHT] = CoordH(ShareH, InlineH, NeverHT(false)) + override def resultType: CoordH[NeverHT] = CoordH(MutableShareH, InlineH, NeverHT(false)) } // Constructs an immutable unknown-size array, whose length is the integer from sizeExpression, @@ -696,7 +735,7 @@ case class NewImmRuntimeSizedArrayH( val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); generatorExpression.resultType.ownership match { - case ShareH | BorrowH => + case MutableShareH | ImmutableShareH | MutableBorrowH | ImmutableBorrowH => case other => vwat(other) } vassert(sizeExpression.resultType.kind == IntHT.i32) @@ -735,7 +774,7 @@ case class PushRuntimeSizedArrayH( val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[KindHT] = CoordH(ShareH, InlineH, VoidHT()) + override def resultType: CoordH[KindHT] = CoordH(MutableShareH, InlineH, VoidHT()) } // Adds a new element to the end of a mutable unknown-size array. @@ -778,8 +817,10 @@ case class StaticArrayFromCallableH( val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); vassert( - generatorExpression.resultType.ownership == BorrowH || - generatorExpression.resultType.ownership == ShareH) + generatorExpression.resultType.ownership == MutableBorrowH || + generatorExpression.resultType.ownership == ImmutableBorrowH || + generatorExpression.resultType.ownership == MutableShareH || + generatorExpression.resultType.ownership == ImmutableShareH) } // Destroys an array previously created with NewArrayFromValuesH. @@ -800,7 +841,7 @@ case class DestroyStaticSizedArrayIntoFunctionH( consumerExpression.resultType.kind match { case NeverHT(_) => vwat() case _ => } val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[VoidHT] = CoordH(ShareH, InlineH, VoidHT()) + override def resultType: CoordH[VoidHT] = CoordH(MutableShareH, InlineH, VoidHT()) } // Destroys an array previously created with ConstructRuntimeSizedArrayH. @@ -820,7 +861,7 @@ case class DestroyImmRuntimeSizedArrayH( consumerExpression.resultType.kind match { case NeverHT(_) => vwat() case _ => } val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[VoidHT] = CoordH(ShareH, InlineH, VoidHT()) + override def resultType: CoordH[VoidHT] = CoordH(MutableShareH, InlineH, VoidHT()) } // Destroys an array previously created with ConstructRuntimeSizedArrayH. @@ -834,13 +875,13 @@ case class DestroyMutRuntimeSizedArrayH( // arrayExpression.resultType.kind match { case NeverH(_) => vwat() case _ => } val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[VoidHT] = CoordH(ShareH, InlineH, VoidHT()) + override def resultType: CoordH[VoidHT] = CoordH(MutableShareH, InlineH, VoidHT()) } // Jumps to after the closest containing loop. case class BreakH() extends ExpressionH[NeverHT] { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[NeverHT] = CoordH(ShareH, InlineH, NeverHT(true)) + override def resultType: CoordH[NeverHT] = CoordH(MutableShareH, InlineH, NeverHT(true)) } // Creates a new struct instance. @@ -867,7 +908,7 @@ case class ArrayLengthH( sourceExpression.resultType.kind match { case NeverHT(_) => vwat() case _ => } val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[IntHT] = CoordH(ShareH, InlineH, IntHT.i32) + override def resultType: CoordH[IntHT] = CoordH(MutableShareH, InlineH, IntHT.i32) } // Gets the capacity of an unknown-sized array. @@ -879,7 +920,7 @@ case class ArrayCapacityH( sourceExpression.resultType.kind match { case NeverHT(_) => vwat() case _ => } val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[IntHT] = CoordH(ShareH, InlineH, IntHT.i32) + override def resultType: CoordH[IntHT] = CoordH(MutableShareH, InlineH, IntHT.i32) } // Turns a borrow ref into a weak ref. @@ -890,7 +931,7 @@ case class BorrowToWeakH( // See BRCOBS, no arguments should be Never. refExpression.resultType.kind match { case NeverHT(_) => vwat() case _ => } - vassert(refExpression.resultType.ownership == BorrowH) + vassert(refExpression.resultType.ownership == ImmutableBorrowH || refExpression.resultType.ownership == MutableBorrowH) val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); override def resultType: CoordH[KindHT] = CoordH(WeakH, YonderH, refExpression.resultType.kind) @@ -906,7 +947,7 @@ case class IsSameInstanceH( rightExpression.resultType.kind match { case NeverHT(_) => vwat() case _ => } val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); - override def resultType: CoordH[KindHT] = CoordH(ShareH, InlineH, BoolHT()) + override def resultType: CoordH[KindHT] = CoordH(MutableShareH, InlineH, BoolHT()) } // Tries to downcast to the specified subtype and wrap in a Some. @@ -951,9 +992,17 @@ case class DiscardH(sourceExpression: ExpressionH[KindHT]) extends ExpressionH[V val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); sourceExpression.resultType.ownership match { - case BorrowH | ShareH | WeakH => + case MutableBorrowH | ImmutableBorrowH | MutableShareH | ImmutableShareH | WeakH => + } + override def resultType: CoordH[VoidHT] = CoordH(MutableShareH, InlineH, VoidHT()) +} + +case class PreCheckBorrowH(innerExpression: ExpressionH[KindHT]) extends ExpressionH[KindHT] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); + innerExpression.resultType.ownership match { + case MutableBorrowH => } - override def resultType: CoordH[VoidHT] = CoordH(ShareH, InlineH, VoidHT()) + override def resultType: CoordH[KindHT] = innerExpression.resultType } trait IExpressionH { diff --git a/Frontend/FinalAST/src/dev/vale/finalast/types.scala b/Frontend/FinalAST/src/dev/vale/finalast/types.scala index 1fd7fad5e..b5310e7d6 100644 --- a/Frontend/FinalAST/src/dev/vale/finalast/types.scala +++ b/Frontend/FinalAST/src/dev/vale/finalast/types.scala @@ -33,8 +33,8 @@ case class CoordH[+T <: KindHT]( (ownership, location) match { case (OwnH, YonderH) => - case (ShareH, _) => - case (BorrowH, YonderH) => + case (ImmutableShareH | MutableShareH, _) => + case (MutableBorrowH | ImmutableBorrowH, YonderH) => case (WeakH, YonderH) => case _ => vfail() } @@ -42,19 +42,21 @@ case class CoordH[+T <: KindHT]( kind match { case IntHT(_) | BoolHT() | FloatHT() | NeverHT(_) => { // Make sure that if we're pointing at a primitives, it's via a Share reference. - vassert(ownership == ShareH) + // We don't want any ImmutableShareH, it's better to only ever have one ownership for + // primitives. + vassert(ownership == MutableShareH) vassert(location == InlineH) } case StrHT() => { // Strings need to be yonder because Midas needs to do refcounting for them. - vassert(ownership == ShareH) + vassert(ownership == ImmutableShareH || ownership == MutableShareH) vassert(location == YonderH) } case StructHT(name) => { val isBox = name.fullyQualifiedName.startsWith("__Box") if (isBox) { - vassert(ownership == OwnH || ownership == BorrowH) + vassert(ownership == OwnH || ownership == ImmutableBorrowH || ownership == MutableBorrowH) } } case _ => @@ -130,28 +132,28 @@ case class NeverHT(fromBreak: Boolean) extends KindHT { case class InterfaceHT( // Unique identifier for the interface. - fullName: IdH + id: IdH ) extends KindHT { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; - override def packageCoord(interner: Interner, keywords: Keywords): PackageCoordinate = fullName.packageCoordinate + override def packageCoord(interner: Interner, keywords: Keywords): PackageCoordinate = id.packageCoordinate } case class StructHT( // Unique identifier for the interface. - fullName: IdH + id: IdH ) extends KindHT { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; - override def packageCoord(interner: Interner, keywords: Keywords): PackageCoordinate = fullName.packageCoordinate + override def packageCoord(interner: Interner, keywords: Keywords): PackageCoordinate = id.packageCoordinate } // An array whose size is known at compile time, and therefore doesn't need to // carry around its size at runtime. case class StaticSizedArrayHT( // This is useful for naming the Midas struct that wraps this array and its ref count. - name: IdH, + id: IdH, ) extends KindHT { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; - override def packageCoord(interner: Interner, keywords: Keywords): PackageCoordinate = name.packageCoordinate + override def packageCoord(interner: Interner, keywords: Keywords): PackageCoordinate = id.packageCoordinate } // An array whose size is known at compile time, and therefore doesn't need to @@ -197,9 +199,11 @@ case class CodeLocation( // ReferenceH for explanation. sealed trait OwnershipH case object OwnH extends OwnershipH -case object BorrowH extends OwnershipH +case object MutableBorrowH extends OwnershipH +case object ImmutableBorrowH extends OwnershipH +case object MutableShareH extends OwnershipH +case object ImmutableShareH extends OwnershipH case object WeakH extends OwnershipH -case object ShareH extends OwnershipH // Location says whether a reference contains the kind's location (yonder) or // contains the kind itself (inline). diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/InstantiatedCompilation.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/InstantiatedCompilation.scala index feb092079..ed07b421b 100644 --- a/Frontend/InstantiatingPass/src/dev/vale/instantiating/InstantiatedCompilation.scala +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/InstantiatedCompilation.scala @@ -1,12 +1,13 @@ package dev.vale.instantiating import dev.vale.highertyping.{ICompileErrorA, ProgramA} +import dev.vale.instantiating.ast.HinputsI import dev.vale.lexing.{FailedParse, RangeL} import dev.vale.options.GlobalOptions import dev.vale.parsing.ast.FileP import dev.vale.postparsing.{ICompileErrorS, ProgramS} import dev.vale.{FileCoordinateMap, IPackageResolver, Interner, Keywords, PackageCoordinate, PackageCoordinateMap, Result, vassertSome, vcurious} -import dev.vale.typing.{Hinputs, ICompileErrorT, TypingPassCompilation, TypingPassOptions} +import dev.vale.typing.{HinputsT, ICompileErrorT, TypingPassCompilation, TypingPassOptions} case class InstantiatorCompilationOptions( globalOptions: GlobalOptions = GlobalOptions(), @@ -30,17 +31,17 @@ class InstantiatedCompilation( TypingPassOptions( options.globalOptions, options.debugOut)) - var monoutsCache: Option[Hinputs] = None + var monoutsCache: Option[HinputsI] = None def getCodeMap(): Result[FileCoordinateMap[String], FailedParse] = typingPassCompilation.getCodeMap() def getParseds(): Result[FileCoordinateMap[(FileP, Vector[RangeL])], FailedParse] = typingPassCompilation.getParseds() def getVpstMap(): Result[FileCoordinateMap[String], FailedParse] = typingPassCompilation.getVpstMap() def getScoutput(): Result[FileCoordinateMap[ProgramS], ICompileErrorS] = typingPassCompilation.getScoutput() def getAstrouts(): Result[PackageCoordinateMap[ProgramA], ICompileErrorA] = typingPassCompilation.getAstrouts() - def getCompilerOutputs(): Result[Hinputs, ICompileErrorT] = typingPassCompilation.getCompilerOutputs() - def expectCompilerOutputs(): Hinputs = typingPassCompilation.expectCompilerOutputs() + def getCompilerOutputs(): Result[HinputsT, ICompileErrorT] = typingPassCompilation.getCompilerOutputs() + def expectCompilerOutputs(): HinputsT = typingPassCompilation.expectCompilerOutputs() - def getMonouts(): Hinputs = { + def getMonouts(): HinputsI = { monoutsCache match { case Some(monouts) => monouts case None => { diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/InstantiatedHumanizer.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/InstantiatedHumanizer.scala new file mode 100644 index 000000000..d175f819f --- /dev/null +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/InstantiatedHumanizer.scala @@ -0,0 +1,213 @@ +package dev.vale.instantiating + +import dev.vale._ +import dev.vale.instantiating.ast._ + +object InstantiatedHumanizer { + def humanizeTemplata[R <: IRegionsModeI]( + codeMap: CodeLocationS => String, + templata: ITemplataI[R]): + String = { + templata match { + case RuntimeSizedArrayTemplateTemplataI() => "Array" + case StaticSizedArrayTemplateTemplataI() => "StaticArray" + case InterfaceDefinitionTemplataI(envId, tyype) => humanizeId(codeMap, envId, None) + case StructDefinitionTemplataI(envId, tyype) => humanizeId(codeMap, envId, None) + case VariabilityTemplataI(variability) => { + variability match { + case FinalI => "final" + case VaryingI => "vary" + } + } + case IntegerTemplataI(value) => value.toString + case MutabilityTemplataI(mutability) => { + mutability match { + case MutableI => "mut" + case ImmutableI => "imm" + } + } + case OwnershipTemplataI(ownership) => { + ownership match { + case OwnI => "own" + case ImmutableBorrowI => "i&" + case MutableBorrowI => "&" + case ImmutableShareI => "i*" + case MutableShareI => "*" + case WeakI => "weak" + } + } + case PrototypeTemplataI(range, prototype) => { + humanizeId(codeMap, prototype.id) + } + case CoordTemplataI(region, coord) => { + humanizeCoord(codeMap, coord) + } + case KindTemplataI(kind) => { + humanizeKind(codeMap, kind) + } + case CoordListTemplataI(coords) => { + "(" + coords.map(humanizeCoord(codeMap, _)).mkString(",") + ")" + } + case StringTemplataI(value) => "\"" + value + "\"" + case RegionTemplataI(pureHeight) => pureHeight.toString + case other => vimpl(other) + } + } + + private def humanizeCoord[R <: IRegionsModeI]( + codeMap: CodeLocationS => String, + coord: CoordI[R] + ): String = { + val CoordI(ownership, kind) = coord + + val ownershipStr = + ownership match { + case OwnI => "" + case MutableShareI => "" + case MutableBorrowI => "&" + case ImmutableShareI => "#" + case ImmutableBorrowI => "&#" + case WeakI => "weak&" + } + val kindStr = humanizeKind(codeMap, kind) + ownershipStr + kindStr + } + + private def humanizeKind[R <: IRegionsModeI]( + codeMap: CodeLocationS => String, + kind: KindIT[R] + ) = { + kind match { + case IntIT(bits) => "i" + bits + case BoolIT() => "bool" + case StrIT() => "str" + case NeverIT(_) => "never" + case VoidIT() => "void" + case FloatIT() => "float" + case InterfaceIT(name) => humanizeId(codeMap, name) + case StructIT(name) => humanizeId(codeMap, name) + case RuntimeSizedArrayIT(name) => humanizeId(codeMap, name) + case StaticSizedArrayIT(name) => humanizeId(codeMap, name) + } + } + + def humanizeId[R <: IRegionsModeI, I <: INameI[R]]( + codeMap: CodeLocationS => String, + name: IdI[R, I], + containingRegion: Option[ITemplataI[R]] = None): + String = { + (if (name.initSteps.nonEmpty) { + name.initSteps.map(n => humanizeName(codeMap, n)).mkString(".") + "." + } else { + "" + }) + + humanizeName(codeMap, name.localName, containingRegion) + } + + def humanizeName[R <: IRegionsModeI, I <: INameI[R]]( + codeMap: CodeLocationS => String, + name: INameI[R], + containingRegion: Option[ITemplataI[R]] = None): + String = { + name match { + case AnonymousSubstructConstructorNameI(template, templateArgs, parameters) => { + humanizeName(codeMap, template) + + "<" + templateArgs.map(humanizeTemplata(codeMap, _)).mkString(",") + ">" + + "(" + parameters.map(humanizeCoord(codeMap, _)).mkString(",") + ")" + } + case AnonymousSubstructConstructorTemplateNameI(substruct) => { + "asc:" + humanizeName(codeMap, substruct) + } + case SelfNameI() => "self" + case IteratorNameI(range) => "it:" + codeMap(range.begin) + case IterableNameI(range) => "ib:" + codeMap(range.begin) + case IterationOptionNameI(range) => "io:" + codeMap(range.begin) + case ForwarderFunctionNameI(_, inner) => humanizeName(codeMap, inner) + case ForwarderFunctionTemplateNameI(inner, index) => "fwd" + index + ":" + humanizeName(codeMap, inner) + case MagicParamNameI(codeLoc) => "mp:" + codeMap(codeLoc) + case ClosureParamNameI(codeLocation) => "λP:" + codeMap(codeLocation) + case ConstructingMemberNameI(name) => "cm:" + name + case TypingPassBlockResultVarNameI(life) => "b:" + life + case TypingPassFunctionResultVarNameI() => "(result)" + case TypingPassTemporaryVarNameI(life) => "t:" + life + case FunctionBoundTemplateNameI(humanName, codeLocation) => humanName.str + case LambdaCallFunctionTemplateNameI(codeLocation, _) => "λF:" + codeMap(codeLocation) + case LambdaCitizenTemplateNameI(codeLocation) => "λC:" + codeMap(codeLocation) + case LambdaCallFunctionNameI(template, templateArgs, parameters) => { + humanizeName(codeMap, template) + + humanizeGenericArgs(codeMap, templateArgs, None) + + "(" + parameters.map(humanizeCoord(codeMap, _)).mkString(",") + ")" + } + case FunctionBoundNameI(template, templateArgs, parameters) => { + humanizeName(codeMap, template) + + humanizeGenericArgs(codeMap, templateArgs, None) + + "(" + parameters.map(humanizeCoord(codeMap, _)).mkString(",") + ")" + } + case CodeVarNameI(name) => name.str + case LambdaCitizenNameI(template) => humanizeName(codeMap, template) + "<>" + case FunctionTemplateNameI(humanName, codeLoc) => humanName.str + case ExternFunctionNameI(humanName, parameters) => humanName.str + case FunctionNameIX(templateName, templateArgs, parameters) => { + humanizeName(codeMap, templateName) + + humanizeGenericArgs(codeMap, templateArgs, containingRegion) + + (if (parameters.nonEmpty) { + "(" + parameters.map(humanizeCoord(codeMap, _)).mkString(",") + ")" + } else { + "" + }) + } + case CitizenNameI(humanName, templateArgs) => { + humanizeName(codeMap, humanName) + + humanizeGenericArgs(codeMap, templateArgs, containingRegion) + } + case RuntimeSizedArrayNameI(RuntimeSizedArrayTemplateNameI(), RawArrayNameI(mutability, elementType, region)) => { + ("[]<" + + (mutability match { case ImmutableI => "i" case MutableI => "m" }) + "," + + humanizeTemplata(codeMap, region) + ">" + + humanizeTemplata(codeMap, elementType)) + } + case StaticSizedArrayNameI(StaticSizedArrayTemplateNameI(), size, variability, RawArrayNameI(mutability, elementType, region)) => { + ("[]<" + + humanizeTemplata(codeMap, IntegerTemplataI(size)) + "," + + humanizeTemplata(codeMap, MutabilityTemplataI(mutability)) + "," + + humanizeTemplata(codeMap, VariabilityTemplataI(variability)) + "," + + humanizeTemplata(codeMap, region) + ">" + + humanizeTemplata(codeMap, elementType)) + } + case AnonymousSubstructNameI(interface, templateArgs) => { + humanizeName(codeMap, interface) + + "<" + templateArgs.map(humanizeTemplata(codeMap, _)).mkString(",") + ">" + } + case AnonymousSubstructTemplateNameI(interface) => { + humanizeName(codeMap, interface) + ".anonymous" + } + case StructTemplateNameI(humanName) => humanName.str + case InterfaceTemplateNameI(humanName) => humanName.str + } + } + + private def humanizeGenericArgs[R <: IRegionsModeI]( + codeMap: CodeLocationS => String, + templateArgs: Vector[ITemplataI[R]], + containingRegion: Option[ITemplataI[R]] + ) = { + ( + if (templateArgs.nonEmpty) { + "<" + + (templateArgs.init.map(humanizeTemplata(codeMap, _)) ++ + templateArgs.lastOption.map(region => { + containingRegion match { + case None => humanizeTemplata(codeMap, region) + case Some(r) => vassert(r == region); "_" + } + })).mkString(",") + + ">" + } else { + "" + }) + } + + def humanizeSignature[R <: IRegionsModeI](codeMap: CodeLocationS => String, signature: SignatureI[R]): String = { + humanizeId(codeMap, signature.id) + } +} diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala index 695ddbf1e..5cba5b623 100644 --- a/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala @@ -1,84 +1,129 @@ package dev.vale.instantiating +import dev.vale.instantiating.ast._ import dev.vale.options.GlobalOptions -import dev.vale.{Accumulator, Collector, Interner, Keywords, StrI, vassert, vassertOne, vassertSome, vcurious, vfail, vimpl, vpass, vwat} -import dev.vale.postparsing.{IRuneS, ITemplataType, IntegerTemplataType} -import dev.vale.typing.TemplataCompiler.{getTopLevelDenizenId, substituteTemplatasInKind} -import dev.vale.typing.{Hinputs, InstantiationBoundArgumentsT, TemplataCompiler} +import dev.vale._ +import dev.vale.instantiating.ast.ITemplataI.expectRegionTemplata +import dev.vale.postparsing._ +import dev.vale.typing.TemplataCompiler._ +import dev.vale.typing._ import dev.vale.typing.ast._ import dev.vale.typing.env._ import dev.vale.typing.names._ -import dev.vale.typing.templata.ITemplataT.{expectIntegerTemplata, expectKind, expectKindTemplata, expectMutabilityTemplata, expectVariabilityTemplata} +import dev.vale.typing.templata.ITemplataT._ import dev.vale.typing.templata._ import dev.vale.typing.types._ import scala.collection.immutable.Map import scala.collection.mutable -case class DenizenBoundToDenizenCallerBoundArg( - funcBoundToCallerSuppliedBoundArgFunc: Map[IdT[FunctionBoundNameT], PrototypeT], - implBoundToCallerSuppliedBoundArgImpl: Map[IdT[ImplBoundNameT], IdT[IImplNameT]]) - +// DO NOT SUBMIT straighten out all the C and I and S suffixes and whatnot in this whole file + +case class DenizenBoundToDenizenCallerBoundArgI( + funcBoundToCallerSuppliedBoundArgFunc: Map[IdT[FunctionBoundNameT], PrototypeI[sI]], + implBoundToCallerSuppliedBoundArgImpl: Map[IdT[ImplBoundNameT], IdI[sI, IImplNameI[sI]]]) + +// Note this has mutable stuff in it. +case class NodeEnvironment( + maybeParent: Option[NodeEnvironment], +// // We track these because we need to know the original type of the local, see CTOTFIPB. +// nameToLocal: mutable.HashMap[IVarNameT, ILocalVariableT] +) { + +// def addTranslatedVariable(idT: IVarNameT, translatedLocalVar: ILocalVariableT): Unit = { +// nameToLocal += (idT -> translatedLocalVar) +// } +// +// def lookupOriginalTranslatedVariable(idT: IVarNameT): ILocalVariableT = { +// vassertSome(nameToLocal.get(idT)) +// } +} class InstantiatedOutputs() { - val functions: mutable.HashMap[IdT[IFunctionNameT], FunctionDefinitionT] = - mutable.HashMap[IdT[IFunctionNameT], FunctionDefinitionT]() - val structs: mutable.HashMap[IdT[IStructNameT], StructDefinitionT] = mutable.HashMap() - val interfacesWithoutMethods: mutable.HashMap[IdT[IInterfaceNameT], InterfaceDefinitionT] = mutable.HashMap() + val functions: mutable.HashMap[IdI[cI, IFunctionNameI[cI]], FunctionDefinitionI] = + mutable.HashMap() + val structs: mutable.HashMap[IdI[cI, IStructNameI[cI]], StructDefinitionI] = mutable.HashMap() + val interfacesWithoutMethods: mutable.HashMap[IdI[cI, IInterfaceNameI[cI]], InterfaceDefinitionI] = mutable.HashMap() // We can get some recursion if we have a self-referential struct like: // struct Node { value T; next Opt>; } // So we need these to short-circuit that nonsense. - val startedStructs: mutable.HashMap[IdT[IStructNameT], (MutabilityT, DenizenBoundToDenizenCallerBoundArg)] = mutable.HashMap() - val startedInterfaces: mutable.HashMap[IdT[IInterfaceNameT], (MutabilityT, DenizenBoundToDenizenCallerBoundArg)] = mutable.HashMap() + val structToMutability: mutable.HashMap[IdI[cI, IStructNameI[cI]], MutabilityI] = mutable.HashMap() + val structToBounds: mutable.HashMap[IdI[sI, IStructNameI[sI]], DenizenBoundToDenizenCallerBoundArgI] = mutable.HashMap() + val interfaceToMutability: mutable.HashMap[IdI[cI, IInterfaceNameI[cI]], MutabilityI] = mutable.HashMap() + val interfaceToBounds: mutable.HashMap[IdI[sI, IInterfaceNameI[sI]], DenizenBoundToDenizenCallerBoundArgI] = mutable.HashMap() + val implToMutability: mutable.HashMap[IdI[cI, IImplNameI[cI]], MutabilityI] = mutable.HashMap() + val implToBounds: mutable.HashMap[IdI[sI, IImplNameI[sI]], DenizenBoundToDenizenCallerBoundArgI] = mutable.HashMap() // val immKindToDestructor: mutable.HashMap[KindT, PrototypeT] = // mutable.HashMap[KindT, PrototypeT]() // We already know from the hinputs that Some implements Opt. // In this map, we'll know that Some implements Opt, Some implements Opt, etc. - val interfaceToImpls: mutable.HashMap[IdT[IInterfaceNameT], mutable.HashSet[IdT[IImplNameT]]] = + val interfaceToImpls: mutable.HashMap[IdI[cI, IInterfaceNameI[cI]], mutable.HashSet[(IdT[IImplNameT], IdI[cI, IImplNameI[cI]])]] = mutable.HashMap() - val interfaceToAbstractFuncToVirtualIndex: mutable.HashMap[IdT[IInterfaceNameT], mutable.HashMap[PrototypeT, Int]] = + val interfaceToAbstractFuncToVirtualIndex: mutable.HashMap[IdI[cI, IInterfaceNameI[cI]], mutable.HashMap[PrototypeI[cI], Int]] = mutable.HashMap() val impls: mutable.HashMap[ - IdT[IImplNameT], - (ICitizenTT, IdT[IInterfaceNameT], DenizenBoundToDenizenCallerBoundArg, Instantiator)] = + IdI[cI, IImplNameI[cI]], + (ICitizenIT[cI], IdI[cI, IInterfaceNameI[cI]], DenizenBoundToDenizenCallerBoundArgI)] = mutable.HashMap() // We already know from the hinputs that Opt has func drop(T). // In this map, we'll know that Opt has func drop(int). - val abstractFuncToInstantiatorAndSuppliedPrototypes: mutable.HashMap[IdT[IFunctionNameT], (Instantiator, InstantiationBoundArgumentsT)] = - mutable.HashMap() + // DO NOT SUBMIT rename + val abstractFuncToInstantiatorAndSuppliedPrototypes: mutable.HashMap[IdI[cI, IFunctionNameI[cI]], (DenizenBoundToDenizenCallerBoundArgI, InstantiationBoundArgumentsI)] = + mutable.HashMap() // This map collects all overrides for every impl. We'll use it to assemble vtables soon. val interfaceToImplToAbstractPrototypeToOverride: - mutable.HashMap[IdT[IInterfaceNameT], mutable.HashMap[IdT[IImplNameT], mutable.HashMap[PrototypeT, OverrideT]]] = + mutable.HashMap[IdI[cI, IInterfaceNameI[cI]], mutable.HashMap[IdI[cI, IImplNameI[cI]], mutable.HashMap[PrototypeI[cI], PrototypeI[cI]]]] = mutable.HashMap() // These are new impls and abstract funcs we discover for interfaces. // As we discover a new impl or a new abstract func, we'll later need to stamp a lot more overrides either way. - val newImpls: mutable.Queue[(IdT[IImplNameT], InstantiationBoundArgumentsT)] = mutable.Queue() + val newImpls: mutable.Queue[(IdT[IImplNameT], IdI[nI, IImplNameI[nI]], InstantiationBoundArgumentsI)] = mutable.Queue() // The int is a virtual index - val newAbstractFuncs: mutable.Queue[(PrototypeT, Int, IdT[IInterfaceNameT], InstantiationBoundArgumentsT)] = mutable.Queue() - val newFunctions: mutable.Queue[(PrototypeT, InstantiationBoundArgumentsT, Option[DenizenBoundToDenizenCallerBoundArg])] = mutable.Queue() + val newAbstractFuncs: mutable.Queue[(PrototypeT, PrototypeI[nI], Int, IdI[cI, IInterfaceNameI[cI]], InstantiationBoundArgumentsI)] = mutable.Queue() + val newFunctions: mutable.Queue[(PrototypeT, PrototypeI[nI], InstantiationBoundArgumentsI, Option[DenizenBoundToDenizenCallerBoundArgI])] = mutable.Queue() def addMethodToVTable( - implFullName: IdT[IImplNameT], - superInterfaceFullName: IdT[IInterfaceNameT], - abstractFuncPrototype: PrototypeT, - overrride: OverrideT + implId: IdI[cI, IImplNameI[cI]], + superInterfaceId: IdI[cI, IInterfaceNameI[cI]], + abstractFuncPrototype: PrototypeI[cI], + overrride: PrototypeI[cI] ) = { val map = interfaceToImplToAbstractPrototypeToOverride - .getOrElseUpdate(superInterfaceFullName, mutable.HashMap()) - .getOrElseUpdate(implFullName, mutable.HashMap()) + .getOrElseUpdate(superInterfaceId, mutable.HashMap()) + .getOrElseUpdate(implId, mutable.HashMap()) vassert(!map.contains(abstractFuncPrototype)) map.put(abstractFuncPrototype, overrride) } } object Instantiator { - def translate(opts: GlobalOptions, interner: Interner, keywords: Keywords, hinputs: Hinputs): Hinputs = { - val Hinputs( + def translate( + opts: GlobalOptions, + interner: Interner, + keywords: Keywords, + hinputs: HinputsT): + HinputsI = { + val monouts = new InstantiatedOutputs() + val instantiator = new Instantiator(opts, interner, keywords, hinputs, monouts) + instantiator.translate() + } +} + +class Instantiator( + opts: GlobalOptions, + interner: Interner, + keywords: Keywords, + hinputs: HinputsT, + monouts: InstantiatedOutputs) { + + def translate(): + HinputsI = { + + val HinputsT( interfacesT, structsT, functionsT, @@ -88,118 +133,171 @@ object Instantiator { instantiationNameToFunctionBoundToRuneT, kindExportsT, functionExportsT, - kindExternsT, + kindExterns, functionExternsT) = hinputs - val monouts = new InstantiatedOutputs() + // DO NOT SUBMIT we do nothing with kindExterns - kindExportsT.foreach({ case KindExportT(range, tyype, packageId, exportedName) => - val packageName = IdT(packageId.packageCoord, Vector(), interner.intern(PackageTopLevelNameT())) - val exportName = - packageName.addStep(interner.intern(ExportNameT(interner.intern(ExportTemplateNameT(range.begin))))) - val exportTemplateName = TemplataCompiler.getExportTemplate(exportName) - val instantiator = - new Instantiator( - opts, - interner, - keywords, - hinputs, - monouts, - exportTemplateName, - exportName, - Map(), - DenizenBoundToDenizenCallerBoundArg(Map(), Map())) - KindExportT( - range, - instantiator.translateKind(tyype), - packageId, - exportedName) - }) + val kindExportsI = + kindExportsT.map({ case KindExportT(range, tyype, exportPlaceholderedIdT, exportedName) => - functionExportsT.foreach({ case FunctionExportT(range, prototype, packageId, exportedName) => - val packageName = IdT(packageId.packageCoord, Vector(), interner.intern(PackageTopLevelNameT())) - val exportName = - packageName.addStep( - interner.intern(ExportNameT(interner.intern(ExportTemplateNameT(range.begin))))) - val exportTemplateName = TemplataCompiler.getExportTemplate(exportName) - val instantiator = - new Instantiator( - opts, - interner, - keywords, - hinputs, - monouts, - exportTemplateName, - exportName, - Map(), - DenizenBoundToDenizenCallerBoundArg(Map(), Map())) - FunctionExportT( - range, - instantiator.translatePrototype(prototype), - packageId, - exportedName) - }) + val exportIdI = + translateId[ExportNameT, ExportNameI[sI]]( + exportPlaceholderedIdT, + { case ExportNameT(ExportTemplateNameT(codeLoc)) => + ExportNameI(ExportTemplateNameI(codeLoc), RegionTemplataI(0)) + }) + val exportIdC = + RegionCollapserIndividual.collapseExportId(RegionCounter.countExportId(exportIdI), exportIdI) + + val exportTemplateIdT = TemplataCompiler.getExportTemplate(exportPlaceholderedIdT) + + + val substitutions = + Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( + exportTemplateIdT -> assemblePlaceholderMap(exportPlaceholderedIdT, exportIdI)) + + val denizenBoundToDenizenCallerSuppliedThing = DenizenBoundToDenizenCallerBoundArgI(Map(), Map()) + val kindIT = + translateKind( + exportPlaceholderedIdT, denizenBoundToDenizenCallerSuppliedThing, substitutions, GlobalRegionT(), tyype) + val kindCT = RegionCollapserIndividual.collapseKind(kindIT) + + KindExportI(range, kindCT, exportIdC, exportedName) + }) + + val functionExportsI = + functionExportsT.map({ case FunctionExportT(range, prototypeT, exportPlaceholderedIdT, exportedName) => + val perspectiveRegionT = GlobalRegionT() + // exportPlaceholderedIdT.localName.templateArgs.last match { + // case PlaceholderTemplataT(IdT(packageCoord, initSteps, r @ RegionPlaceholderNameT(_, _, _, _)), RegionTemplataType()) => { + // IdT(packageCoord, initSteps, r) + // } + // case _ => vwat() + // } + + val exportIdI = + translateId[ExportNameT, ExportNameI[sI]]( + exportPlaceholderedIdT, + { case ExportNameT(ExportTemplateNameT(codeLoc)) => + ExportNameI(ExportTemplateNameI(codeLoc), RegionTemplataI(0)) + }) + val exportIdC = + RegionCollapserIndividual.collapseExportId(RegionCounter.countExportId(exportIdI), exportIdI) + + val exportTemplateIdT = TemplataCompiler.getExportTemplate(exportPlaceholderedIdT) + + val substitutions = + Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( + exportTemplateIdT -> assemblePlaceholderMap(exportPlaceholderedIdT, exportIdI)) + + val (_, prototypeC) = + translatePrototype( + exportPlaceholderedIdT, + DenizenBoundToDenizenCallerBoundArgI(Map(), Map()), + substitutions, + perspectiveRegionT, + prototypeT) + Collector.all(prototypeC, { case PlaceholderTemplataT(_, _) => vwat() }) + FunctionExportI(range, prototypeC, exportIdC, exportedName) + }) + + val funcExternsI = + functionExternsT.map({ case FunctionExternT(range, externPlaceholderedIdT, prototypeT, externedName) => + val perspectiveRegionT = GlobalRegionT() + // externPlaceholderedIdT.localName.templateArgs.last match { + // case PlaceholderTemplataT(IdT(packageCoord, initSteps, r @ RegionPlaceholderNameT(_, _, _, _)), RegionTemplataType()) => { + // IdT(packageCoord, initSteps, r) + // } + // case _ => vwat() + // } + + val externIdI = + translateId[ExternNameT, ExternNameI[sI]]( + externPlaceholderedIdT, + { case ExternNameT(ExternTemplateNameT(codeLoc)) => + ExternNameI(ExternTemplateNameI(codeLoc), RegionTemplataI(0)) + }) + val externIdC = + RegionCollapserIndividual.collapseExternId(RegionCounter.countExternId(externIdI), externIdI) + + val externTemplateIdT = TemplataCompiler.getExternTemplate(externPlaceholderedIdT) + + val substitutions = + Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( + externTemplateIdT -> assemblePlaceholderMap(externPlaceholderedIdT, externIdI)) + + val (_, prototypeC) = + translatePrototype( + externPlaceholderedIdT, + DenizenBoundToDenizenCallerBoundArgI(Map(), Map()), + substitutions, + perspectiveRegionT, + prototypeT) + Collector.all(prototypeC, { case PlaceholderTemplataT(_, _) => vwat() }) + FunctionExternI(prototypeC, externedName) + }) while ({ // We make structs and interfaces eagerly as we come across them // if (monouts.newStructs.nonEmpty) { // val newStructName = monouts.newStructs.dequeue() - // DenizenInstantiator.translateStructDefinition(opts, interner, keywords, hinputs, monouts, newStructName) + // DenizentranslateStructDefinition(opts, interner, keywords, hinputs, monouts, newStructName) // true // } else if (monouts.newInterfaces.nonEmpty) { // val (newInterfaceName, calleeRuneToSuppliedPrototype) = monouts.newInterfaces.dequeue() - // DenizenInstantiator.translateInterfaceDefinition( + // DenizentranslateInterfaceDefinition( // opts, interner, keywords, hinputs, monouts, newInterfaceName, calleeRuneToSuppliedPrototype) // true // } else if (monouts.newFunctions.nonEmpty) { - val (newFuncName, instantiationBoundArgs, maybeDenizenBoundToDenizenCallerSuppliedThing) = + val (newFuncIdT, newFuncIdN, instantiationBoundArgs, maybeDenizenBoundToDenizenCallerSuppliedThing) = monouts.newFunctions.dequeue() - Instantiator.translateFunction( - opts, interner, keywords, hinputs, monouts, newFuncName, instantiationBoundArgs, + translateFunction1( + opts, interner, keywords, hinputs, monouts, newFuncIdT, newFuncIdN, instantiationBoundArgs, maybeDenizenBoundToDenizenCallerSuppliedThing) true } else if (monouts.newImpls.nonEmpty) { - val (implFullName, instantiationBoundsForUnsubstitutedImpl) = monouts.newImpls.dequeue() - Instantiator.translateImpl( - opts, interner, keywords, hinputs, monouts, implFullName, instantiationBoundsForUnsubstitutedImpl) + val (implIdT, implIdN, instantiationBoundsForUnsubstitutedImpl) = + monouts.newImpls.dequeue() + translateImpl( + opts, interner, keywords, hinputs, monouts, implIdT, implIdN, instantiationBoundsForUnsubstitutedImpl) true } else if (monouts.newAbstractFuncs.nonEmpty) { - val (abstractFunc, virtualIndex, interfaceFullName, instantiationBoundArgs) = monouts.newAbstractFuncs.dequeue() - Instantiator.translateAbstractFunc( - opts, interner, keywords, hinputs, monouts, interfaceFullName, abstractFunc, virtualIndex, instantiationBoundArgs) + val (abstractFuncT, abstractFunc, virtualIndex, interfaceId, instantiationBoundArgs) = + monouts.newAbstractFuncs.dequeue() + translateAbstractFunc( + opts, interner, keywords, hinputs, monouts, interfaceId, abstractFuncT, abstractFunc, virtualIndex, instantiationBoundArgs) true } else { false } }) {} - // interfaceToEdgeBlueprints.foreach({ case (interfacePlaceholderedFullName, edge) => - // val instantiator = new DenizenInstantiator(interner, monouts, interfacePlaceholderedFullName) + // interfaceToEdgeBlueprints.foreach({ case (interfacePlaceholderedId, edge) => + // val instantiator = new DenizenInstantiator(interner, monouts, interfacePlaceholderedId) // // }) val interfaceEdgeBlueprints = monouts.interfaceToAbstractFuncToVirtualIndex.map({ case (interface, abstractFuncPrototypes) => - interface -> - InterfaceEdgeBlueprintT( - interface, - abstractFuncPrototypes.toVector) + interface -> InterfaceEdgeBlueprintI(interface, abstractFuncPrototypes.toVector) }).toMap val interfaces = monouts.interfacesWithoutMethods.values.map(interface => { - val InterfaceDefinitionT(templateName, instantiatedInterface, ref, attributes, weakable, mutability, _, _, _) = interface - InterfaceDefinitionT( - templateName, instantiatedInterface, ref, attributes, weakable, mutability, Map(), Map(), - vassertSome(monouts.interfaceToAbstractFuncToVirtualIndex.get(interface.ref.id)).toVector) + val InterfaceDefinitionI(ref, attributes, weakable, mutability, _, _, _) = interface + InterfaceDefinitionI( + ref, attributes, weakable, mutability, Map(), Map(), + vassertSome( + monouts.interfaceToAbstractFuncToVirtualIndex.get(ref.id)).toVector) }) val interfaceToSubCitizenToEdge = monouts.interfaceToImpls.map({ case (interface, impls) => interface -> - impls.map(implFullName => { - val (subCitizen, parentInterface, _, implInstantiator) = vassertSome(monouts.impls.get(implFullName)) + impls.map({ case (implIdT, implIdI) => + val (subCitizen, parentInterface, _) = vassertSome(monouts.impls.get(implIdI)) vassert(parentInterface == interface) val abstractFuncToVirtualIndex = vassertSome(monouts.interfaceToAbstractFuncToVirtualIndex.get(interface)) @@ -209,18 +307,19 @@ object Instantiator { vassertSome( vassertSome( vassertSome(monouts.interfaceToImplToAbstractPrototypeToOverride.get(interface)) - .get(implFullName)) + .get(implIdI)) .get(abstractFuncPrototype)) vassert( abstractFuncPrototype.id.localName.parameters(virtualIndex).kind != - overrride.overridePrototype.id.localName.parameters(virtualIndex).kind) + overrride.id.localName.parameters(virtualIndex).kind) abstractFuncPrototype.id -> overrride }) + val edge = - EdgeT( - implFullName, + EdgeI( + implIdI, subCitizen, interface, Map(), @@ -230,60 +329,118 @@ object Instantiator { }).toMap }).toMap - Hinputs( - interfaces.toVector, - monouts.structs.values.toVector, - monouts.functions.values.toVector, - // monouts.immKindToDestructor.toMap, - interfaceEdgeBlueprints, - interfaceToSubCitizenToEdge, - Map(), - kindExportsT, - functionExportsT, - kindExternsT, - functionExternsT) - } - - def translateInterfaceDefinition( + val resultHinputs = + HinputsI( + interfaces.toVector, + monouts.structs.values.toVector, + monouts.functions.values.toVector, + // monouts.immKindToDestructor.toMap, + interfaceEdgeBlueprints, + interfaceToSubCitizenToEdge, +// Map(), + kindExportsI, + functionExportsI, + funcExternsI) + + resultHinputs + } + + def translateId[T <: INameT, Y <: INameI[sI]](idT: IdT[T], func: T => Y): IdI[sI, Y] = { + val IdT(packageCoord, initStepsT, localNameT) = idT + IdI[sI, Y](packageCoord, initStepsT.map(translateName(_)), func(localNameT)) + } + + def translateExportName( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + exportNameT: ExportNameT): + ExportNameI[sI] = { + val ExportNameT(ExportTemplateNameT(codeLoc)) = exportNameT + ExportNameI( + ExportTemplateNameI(codeLoc), + RegionTemplataI(0)) + } + + def translateExportTemplateName(exportTemplateNameT: ExportTemplateNameT): ExportTemplateNameI[sI] = { + val ExportTemplateNameT(codeLoc) = exportTemplateNameT + ExportTemplateNameI(codeLoc) + } + + def translateName(t: INameT): INameI[sI] = { + vimpl() + } + + def collapseAndTranslateInterfaceDefinition( opts: GlobalOptions, interner: Interner, keywords: Keywords, - hinputs: Hinputs, + hinputs: HinputsT, monouts: InstantiatedOutputs, - interfaceFullName: IdT[IInterfaceNameT], - instantiationBoundArgs: InstantiationBoundArgumentsT): + interfaceIdT: IdT[IInterfaceNameT], + interfaceIdI: IdI[sI, IInterfaceNameI[sI]], + instantiationBoundArgs: InstantiationBoundArgumentsI): Unit = { - val interfaceTemplate = TemplataCompiler.getInterfaceTemplate(interfaceFullName) - - val interfaceDefT = - vassertOne(hinputs.interfaces.filter(_.templateName == interfaceTemplate)) - - val instantiator = - new Instantiator( - opts, - interner, - keywords, - hinputs, - monouts, - interfaceTemplate, - interfaceFullName, - Map(interfaceTemplate -> assemblePlaceholderMap(hinputs, interfaceFullName)), - DenizenBoundToDenizenCallerBoundArg( - assembleCalleeDenizenFunctionBounds( - interfaceDefT.runeToFunctionBound, - instantiationBoundArgs.runeToFunctionBoundArg), - assembleCalleeDenizenImplBounds( - interfaceDefT.runeToImplBound, - instantiationBoundArgs.runeToImplBoundArg))) - instantiator.translateInterfaceDefinition(interfaceFullName, interfaceDefT) + + if (opts.sanityCheck) { + vassert(Collector.all(interfaceIdI, { case KindPlaceholderNameT(_) => }).isEmpty) + } + + val interfaceTemplateIdT = TemplataCompiler.getInterfaceTemplate(interfaceIdT) + + val interfaceDefT = findInterface(hinputs, interfaceIdT) + + val denizenBoundToDenizenCallerSuppliedThing = + DenizenBoundToDenizenCallerBoundArgI( + assembleCalleeDenizenFunctionBounds( + interfaceDefT.runeToFunctionBound, instantiationBoundArgs.runeToFunctionBoundArg), + assembleCalleeDenizenImplBounds( + interfaceDefT.runeToImplBound, instantiationBoundArgs.runeToImplBoundArg)) + monouts.interfaceToBounds.get(interfaceIdI) match { + case Some(x) => vcurious(x == denizenBoundToDenizenCallerSuppliedThing) // DO NOT SUBMIT should we early return here? + case None => + } + monouts.interfaceToBounds.put(interfaceIdI, denizenBoundToDenizenCallerSuppliedThing) + + val topLevelDenizenId = + getTopLevelDenizenId(interfaceIdT) + val topLevelDenizenTemplateId = + TemplataCompiler.getTemplate(topLevelDenizenId) + + val substitutions = + Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( + topLevelDenizenTemplateId -> + assemblePlaceholderMap( + // One would imagine we'd get interfaceId.last.templateArgs here, because that's the interface + // we're about to monomorphize. However, only the top level denizen has placeholders, see LHPCTLD. + // This interface might not be the top level denizen, such as if it's a lambda. + // DO NOT SUBMIT might be obsolete + interfaceDefT.instantiatedCitizen.id, + interfaceIdI)) + // val instantiator = + // new Instantiator( + // opts, + // interner, + // keywords, + // hinputs, + // monouts, + // interfaceTemplate, + // interfaceIdT, + // denizenBoundToDenizenCallerSuppliedThing) + val interfaceIdC = + RegionCollapserIndividual.collapseInterfaceId(interfaceIdI) + + translateCollapsedInterfaceDefinition( + interfaceIdT, denizenBoundToDenizenCallerSuppliedThing, substitutions, interfaceIdC, interfaceDefT) } def assembleCalleeDenizenFunctionBounds( // This is from the receiver's perspective, they have some runes for their required functions. calleeRuneToReceiverBoundT: Map[IRuneS, IdT[FunctionBoundNameT]], // This is a map from the receiver's rune to the bound that the caller is supplying. - calleeRuneToSuppliedPrototype: Map[IRuneS, PrototypeT] - ): Map[IdT[FunctionBoundNameT], PrototypeT] = { + calleeRuneToSuppliedPrototype: Map[IRuneS, PrototypeI[sI]] + ): Map[IdT[FunctionBoundNameT], PrototypeI[sI]] = { calleeRuneToSuppliedPrototype.map({ case (calleeRune, suppliedFunctionT) => vassertSome(calleeRuneToReceiverBoundT.get(calleeRune)) -> suppliedFunctionT }) @@ -293,251 +450,355 @@ object Instantiator { // This is from the receiver's perspective, they have some runes for their required functions. calleeRuneToReceiverBoundT: Map[IRuneS, IdT[ImplBoundNameT]], // This is a map from the receiver's rune to the bound that the caller is supplying. - calleeRuneToSuppliedImpl: Map[IRuneS, IdT[IImplNameT]] - ): Map[IdT[ImplBoundNameT], IdT[IImplNameT]] = { + calleeRuneToSuppliedImpl: Map[IRuneS, IdI[sI, IImplNameI[sI]]] + ): Map[IdT[ImplBoundNameT], IdI[sI, IImplNameI[sI]]] = { calleeRuneToSuppliedImpl.map({ case (calleeRune, suppliedFunctionT) => vassertSome(calleeRuneToReceiverBoundT.get(calleeRune)) -> suppliedFunctionT }) } - def translateStructDefinition( + def collapseAndTranslateStructDefinition( opts: GlobalOptions, interner: Interner, keywords: Keywords, - hinputs: Hinputs, + hinputs: HinputsT, monouts: InstantiatedOutputs, - structFullName: IdT[IStructNameT], - instantiationBoundArgs: InstantiationBoundArgumentsT): + structIdT: IdT[IStructNameT], + structIdI: IdI[sI, IStructNameI[sI]], + instantiationBoundArgs: InstantiationBoundArgumentsI): Unit = { if (opts.sanityCheck) { - vassert(Collector.all(structFullName, { case KindPlaceholderNameT(_) => }).isEmpty) + vassert(Collector.all(structIdI, { case KindPlaceholderNameT(_) => }).isEmpty) } - val structTemplate = TemplataCompiler.getStructTemplate(structFullName) + val structTemplate = TemplataCompiler.getStructTemplate(structIdT) - val structDefT = findStruct(hinputs, structFullName) - - val topLevelDenizenFullName = - getTopLevelDenizenId(structFullName) - val topLevelDenizenTemplateFullName = - TemplataCompiler.getTemplate(topLevelDenizenFullName) + val structDefT = findStruct(hinputs, structIdT) val denizenBoundToDenizenCallerSuppliedThing = - DenizenBoundToDenizenCallerBoundArg( + DenizenBoundToDenizenCallerBoundArgI( assembleCalleeDenizenFunctionBounds( structDefT.runeToFunctionBound, instantiationBoundArgs.runeToFunctionBoundArg), assembleCalleeDenizenImplBounds( structDefT.runeToImplBound, instantiationBoundArgs.runeToImplBoundArg)) - val instantiator = - new Instantiator( - opts, - interner, - keywords, - hinputs, - monouts, - structTemplate, - structFullName, - Map( - topLevelDenizenTemplateFullName -> - assemblePlaceholderMap( - hinputs, - // One would imagine we'd get structFullName.last.templateArgs here, because that's the struct - // we're about to monomorphize. However, only the top level denizen has placeholders, see LHPCTLD. - // This struct might not be the top level denizen, such as if it's a lambda. - topLevelDenizenFullName)), - denizenBoundToDenizenCallerSuppliedThing) - - instantiator.translateStructDefinition(structFullName, structDefT) + monouts.structToBounds.get(structIdI) match { + case Some(x) => vcurious(x == denizenBoundToDenizenCallerSuppliedThing) // DO NOT SUBMIT should we early return here? + case None => + } + monouts.structToBounds.put(structIdI, denizenBoundToDenizenCallerSuppliedThing) + + val topLevelDenizenId = + getTopLevelDenizenId(structIdT) + val topLevelDenizenTemplateId = + TemplataCompiler.getTemplate(topLevelDenizenId) + + val substitutions = + Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( + topLevelDenizenTemplateId -> + assemblePlaceholderMap( + // One would imagine we'd get structId.last.templateArgs here, because that's the struct + // we're about to monomorphize. However, only the top level denizen has placeholders, see LHPCTLD. + // This struct might not be the top level denizen, such as if it's a lambda. + // DO NOT SUBMIT might be obsolete + structDefT.instantiatedCitizen.id, + structIdI)) +// val instantiator = +// new Instantiator( +// opts, +// interner, +// keywords, +// hinputs, +// monouts, +// structTemplate, +// structIdT, +// denizenBoundToDenizenCallerSuppliedThing) + val structIdC = + RegionCollapserIndividual.collapseStructId(structIdI) + translateCollapsedStructDefinition( + structIdT, denizenBoundToDenizenCallerSuppliedThing, substitutions, structIdT, structIdC, structDefT) } - - private def findStruct(hinputs: Hinputs, structFullName: IdT[IStructNameT]) = { + // + // def collapseAndTranslateImplDefinition( + // opts: GlobalOptions, + // interner: Interner, + // keywords: Keywords, + // hinputs: HinputsT, + // monouts: InstantiatedOutputs, + // implIdT: IdT[IImplNameT], + // implIdI: IdI[sI, IImplNameI[sI]], + // instantiationBoundArgs: InstantiationBoundArgumentsI): + // Unit = { + // if (opts.sanityCheck) { + // vassert(Collector.all(implIdI, { case KindPlaceholderNameT(_) => }).isEmpty) + // } + // + // val implTemplate = TemplataCompiler.getImplTemplate(implIdT) + // + // val implDefT = findImpl(hinputs, implIdT) + // + // val denizenBoundToDenizenCallerSuppliedThing = + // DenizenBoundToDenizenCallerBoundArgI( + // assembleCalleeDenizenFunctionBounds( + // implDefT.runeToFuncBound, instantiationBoundArgs.runeToFunctionBoundArg), + // assembleCalleeDenizenImplBounds( + // implDefT.runeToImplBound, instantiationBoundArgs.runeToImplBoundArg)) + // monouts.implToBounds.get(implIdI) match { + // case Some(x) => vcurious(x == denizenBoundToDenizenCallerSuppliedThing) // DO NOT SUBMIT should we early return here? + // case None => + // } + // monouts.implToBounds.put(implIdI, denizenBoundToDenizenCallerSuppliedThing) + // + // val topLevelDenizenId = + // getTopLevelDenizenId(implIdT) + // val topLevelDenizenTemplateId = + // TemplataCompiler.getTemplate(topLevelDenizenId) + // + // val substitutions = + // Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( + // topLevelDenizenTemplateId -> + // assemblePlaceholderMap( + // // One would imagine we'd get implId.last.templateArgs here, because that's the impl + // // we're about to monomorphize. However, only the top level denizen has placeholders, see LHPCTLD. + // // This impl might not be the top level denizen, such as if it's a lambda. + // // DO NOT SUBMIT might be obsolete + // implDefT.edgeId, + // implIdI)) + // // val instantiator = + // // new Instantiator( + // // opts, + // // interner, + // // keywords, + // // hinputs, + // // monouts, + // // implTemplate, + // // implIdT, + // // denizenBoundToDenizenCallerSuppliedThing) + // val implIdC = + // RegionCollapserIndividual.collapseImplId(implIdI) + // + // translateCollapsedImplDefinition( + // implIdT, denizenBoundToDenizenCallerSuppliedThing, substitutions, implIdT, implIdI, implIdC, implDefT) + // } + + private def findStruct(hinputs: HinputsT, structId: IdT[IStructNameT]) = { vassertOne( hinputs.structs .filter(structT => { TemplataCompiler.getSuperTemplate(structT.instantiatedCitizen.id) == - TemplataCompiler.getSuperTemplate(structFullName) + TemplataCompiler.getSuperTemplate(structId) })) } - private def findInterface(hinputs: Hinputs, interfaceFullName: IdT[IInterfaceNameT]) = { + private def findInterface(hinputs: HinputsT, interfaceId: IdT[IInterfaceNameT]) = { vassertOne( hinputs.interfaces .filter(interfaceT => { TemplataCompiler.getSuperTemplate(interfaceT.instantiatedCitizen.id) == - TemplataCompiler.getSuperTemplate(interfaceFullName) + TemplataCompiler.getSuperTemplate(interfaceId) })) } - def translateAbstractFunc( - opts: GlobalOptions, - interner: Interner, - keywords: Keywords, - hinputs: Hinputs, - monouts: InstantiatedOutputs, - interfaceFullName: IdT[IInterfaceNameT], - abstractFunc: PrototypeT, - virtualIndex: Int, - instantiationBoundArgs: InstantiationBoundArgumentsT): - Unit = { - val funcTemplateNameT = TemplataCompiler.getFunctionTemplate(abstractFunc.id) - - val funcT = - vassertOne( - hinputs.functions.filter(func => { - TemplataCompiler.getFunctionTemplate(func.header.id) == funcTemplateNameT - })) - - val abstractFuncInstantiator = - new Instantiator( - opts, - interner, - keywords, - hinputs, - monouts, - funcTemplateNameT, - abstractFunc.id, - Map( - funcTemplateNameT -> - assemblePlaceholderMap(hinputs, abstractFunc.id)), - DenizenBoundToDenizenCallerBoundArg( - assembleCalleeDenizenFunctionBounds( - funcT.runeToFuncBound, instantiationBoundArgs.runeToFunctionBoundArg), - assembleCalleeDenizenImplBounds( - funcT.runeToImplBound, instantiationBoundArgs.runeToImplBoundArg))) - - vassert(!monouts.abstractFuncToInstantiatorAndSuppliedPrototypes.contains(abstractFunc.id)) - monouts.abstractFuncToInstantiatorAndSuppliedPrototypes.put(abstractFunc.id, (abstractFuncInstantiator, instantiationBoundArgs)) - - val abstractFuncs = vassertSome(monouts.interfaceToAbstractFuncToVirtualIndex.get(interfaceFullName)) - vassert(!abstractFuncs.contains(abstractFunc)) - abstractFuncs.put(abstractFunc, virtualIndex) - - vassertSome(monouts.interfaceToImpls.get(interfaceFullName)).foreach(impl => { - translateOverride(opts, interner, keywords, hinputs, monouts, impl, abstractFunc) - }) + private def findImpl(hinputs: HinputsT, implId: IdT[IImplNameT]): EdgeT = { + vassertOne( + hinputs.interfaceToSubCitizenToEdge.values.flatMap(subCitizenToEdge => { + subCitizenToEdge.values.filter(edge => { + TemplataCompiler.getSuperTemplate(edge.edgeId) == + TemplataCompiler.getSuperTemplate(implId) + }) + })) } def translateOverride( opts: GlobalOptions, interner: Interner, keywords: Keywords, - hinputs: Hinputs, + hinputs: HinputsT, monouts: InstantiatedOutputs, - implFullName: IdT[IImplNameT], - abstractFuncPrototype: PrototypeT): + implIdT: IdT[IImplNameT], + implIdC: IdI[cI, IImplNameI[cI]], + abstractFuncPrototypeT: PrototypeT, + abstractFuncPrototypeC: PrototypeI[cI]): Unit = { - // val superInterfaceFullName: FullNameT[IInterfaceNameT], + // Our ultimate goal in here is to make a PrototypeI[cI] for the override. + // To do that, we're going to compile a dispatcher function given an impl, see CDFGI. + // + // For example: + // + // abstract func launch(self &ISpaceship, bork X) where exists drop(Y)void; // Known as "abst" + // struct Raza { ... } + // impl ISpaceship for Raza; // This impl known as "ri" + // func launch(self &Raza, bork int) where exists drop(Y)void { ... } // Known as "over" + // + // we're going to pretend that there's instead a "dispatcher" function that's just forwarding calls based on the + // type of self: + // + // func dispatcher(self &ISpaceship, bork int) where exists drop(str)void { + // match self { + // raza &Raza => launch(raza, bork) + // ... + // } + // } + // + // this dispatcher function is also known as "dis". Note how we know the concrete types right now (int, str, bool), + // that's because we're in the instantiator and we know those. + // Our ultimate goal is to find (and instantiate) the prototype for that launch(raza, bork) in there. - val implTemplateFullName = TemplataCompiler.getImplTemplate(implFullName) + // First step: gather a bunch of details about the given impl, super interface (ISpaceship), sub citizen (Raza) + // and the abstract function (virtual func launch). + val implTemplateId = TemplataCompiler.getImplTemplate(implIdT) val implDefinitionT = vassertOne( hinputs.interfaceToSubCitizenToEdge .flatMap(_._2.values) - .filter(edge => TemplataCompiler.getImplTemplate(edge.edgeId) == implTemplateFullName)) - - val superInterfaceTemplateFullName = TemplataCompiler.getInterfaceTemplate(implDefinitionT.superInterface) - val superInterfaceDefinitionT = hinputs.lookupInterfaceByTemplateId(superInterfaceTemplateFullName) + .filter(edge => TemplataCompiler.getImplTemplate(edge.edgeId) == implTemplateId)) + val superInterfaceTemplateId = TemplataCompiler.getInterfaceTemplate(implDefinitionT.superInterface) + val superInterfaceDefinitionT = hinputs.lookupInterfaceByTemplateId(superInterfaceTemplateId) val superInterfacePlaceholderedName = superInterfaceDefinitionT.instantiatedInterface - val subCitizenTemplateFullName = TemplataCompiler.getCitizenTemplate(implDefinitionT.subCitizen.id) - val subCitizenDefinitionT = hinputs.lookupCitizenByTemplateId(subCitizenTemplateFullName) + val subCitizenTemplateId = TemplataCompiler.getCitizenTemplate(implDefinitionT.subCitizen.id) + val subCitizenDefinitionT = hinputs.lookupCitizenByTemplateId(subCitizenTemplateId) val subCitizenPlaceholderedName = subCitizenDefinitionT.instantiatedCitizen - - val abstractFuncTemplateName = TemplataCompiler.getFunctionTemplate(abstractFuncPrototype.id) + val abstractFuncTemplateName = TemplataCompiler.getFunctionTemplate(abstractFuncPrototypeT.id) val abstractFuncPlaceholderedNameT = vassertSome( hinputs.functions .find(func => TemplataCompiler.getFunctionTemplate(func.header.id) == abstractFuncTemplateName)) .header.id - val edgeT = vassertSome( vassertSome(hinputs.interfaceToSubCitizenToEdge.get(superInterfacePlaceholderedName.id)) .get(subCitizenPlaceholderedName.id)) + vcurious(edgeT == implDefinitionT) // DO NOT SUBMIT remove all this? they're the same. + + // Luckily, the typing phase knows what the override is. + // In this example, it's func launch(self &Raza, bork int) + // We just have to instantiate it, given that someone called the abstract function with certain known types. + // If they called launch(&ISpaceship, int) then we know: + // - abst$A = int + // - abst$B = str + // - abst$C = bool + // But we need to know over$Y and over$Z. val OverrideT( - dispatcherFullNameT, - implPlaceholderToDispatcherPlaceholder, - implPlaceholderToCasePlaceholder, - implSubCitizenReachableBoundsToCaseSubCitizenReachableBounds, - dispatcherRuneToFunctionBound, - dispatcherRuneToImplBound, - dispatcherCaseFullNameT, - overridePrototypeT) = + dispatcherIdT, + implPlaceholderToDispatcherPlaceholder, + implPlaceholderToCasePlaceholder, + implSubCitizenReachableBoundsToCaseSubCitizenReachableBounds, + // This is a map of the dispatcher's rune to the dispatcher's function bound, here: + // $1114 -> func abst/bound:drop(int) + dispatcherRuneToFunctionBound, + dispatcherRuneToImplBound, + dispatcherCaseIdT, + overridePrototypeT) = vassertSome(edgeT.abstractFuncToOverrideFunc.get(abstractFuncPlaceholderedNameT)) - val (abstractFunctionInstantiator, abstractFunctionRuneToCallerSuppliedInstantiationBoundArgs) = - vassertSome(monouts.abstractFuncToInstantiatorAndSuppliedPrototypes.get(abstractFuncPrototype.id)) - // The dispatcher was originally made from the abstract function, they have the same runes. + val ( + // This is a map of, from the original abstract function's caller's perspective, what the actual instantiated + // functions are to use for the bounds. + // In this example, the original abstract function: + // abstract func launch(self &ISpaceship, bork X) where exists drop(Y)void; + // had that bound: + // where exists drop(Y)void + // so this map here will be: + // abst/bound:drop(^abst:bound:drop$X) -> func v/builtins/drop(int)void + abstractFunctionDenizenBoundToDenizenCallerThing, + // This is similar, a map of rune to the bound to use: + // $1114 -> func v/builtins/drop(int)void + abstractFunctionRuneToCallerSuppliedInstantiationBoundArgs) = + vassertSome(monouts.abstractFuncToInstantiatorAndSuppliedPrototypes.get(abstractFuncPrototypeC.id)) + // The dispatcher was originally made from the abstract function, so they have the same runes. + // This will be: + // $1114 -> func v/builtins/drop(int)void val dispatcherRuneToCallerSuppliedPrototype = abstractFunctionRuneToCallerSuppliedInstantiationBoundArgs.runeToFunctionBoundArg + // (this will be empty in this example) TODO: make an example that shows stuff here val dispatcherRuneToCallerSuppliedImpl = abstractFunctionRuneToCallerSuppliedInstantiationBoundArgs.runeToImplBoundArg - val edgeInstantiator = - vassertSome(monouts.impls.get(implFullName))._4 - - val dispatcherPlaceholderFullNameToSuppliedTemplata = - dispatcherFullNameT.localName.templateArgs - .map(dispatcherPlaceholderTemplata => {// FullNameT(_, _, PlaceholderNameT(PlaceholderTemplateNameT(index))) => - val dispatcherPlaceholderFullName = + // (this will be empty in this example) TODO: make an example that shows stuff here + val edgeDenizenBoundToDenizenCallerBoundArgI = + vassertSome(monouts.impls.get(implIdC))._3 + + // We currently know the abstract function's caller's runes and how they map to the instantiated values, + // - abst$A = int + // - abst$B = str + // - abst$C = bool + // ...but this dispatcher function is different than the abstract function. The dispatcher function has its own + // runes, here: + // - dis$I + // - dis$J + // So we'll map the abstract function's caller's runes to the dispatcher's runes. + val dispatcherPlaceholderIdToSuppliedTemplata = + dispatcherIdT.localName.templateArgs + .map(dispatcherPlaceholderTemplata => { + val dispatcherPlaceholderId = TemplataCompiler.getPlaceholderTemplataId(dispatcherPlaceholderTemplata) val implPlaceholder = vassertSome( - implPlaceholderToDispatcherPlaceholder.find(_._2 == dispatcherPlaceholderTemplata))._1 + // This implPlaceholderToDispatcherPlaceholder has a map of the impl runes to the dispatcher runes, like: + // - ri$I -> dis$I + // - ri$J -> dis$J + implPlaceholderToDispatcherPlaceholder + .find(_._2 == dispatcherPlaceholderTemplata))._1 val IdT(_, _, KindPlaceholderNameT(KindPlaceholderTemplateNameT(index, rune))) = implPlaceholder - val templata = implFullName.localName.templateArgs(index) - dispatcherPlaceholderFullName -> templata - }) + // Here we're grabbing it from the instantiated impl that we're overriding, here ri. + val templataC = implIdC.localName.templateArgs(index) + // This is a collapsed, but it needs to be subjective from this dispatcher's perspective. + // TODO(regions): Figure out how to turn this into an sI. + dispatcherPlaceholderId -> vregionmut(templataC.asInstanceOf[ITemplataI[sI]]) + }) + // In this case we'll end up with: + // dis/dis$I -> bool + // dis/dis$J -> str + + // Now that we have the values for the dispatcher placeholders, let's get the values for the function/impl bounds. + + // This turns the above: + // $1114 -> func abst/bound:drop(int) + // and + // $1114 -> func v/builtins/drop(int)void + // into this: + // launch/bound:drop(int) -> func v/builtins/drop(int)void + // so it's really just a rearrangement of the typing phase's data, not quite useful yet. val dispatcherFunctionBoundToIncomingPrototype = assembleCalleeDenizenFunctionBounds( dispatcherRuneToFunctionBound, dispatcherRuneToCallerSuppliedPrototype) + // (this is empty in this example) val dispatcherImplBoundToIncomingImpl = assembleCalleeDenizenImplBounds( dispatcherRuneToImplBound, dispatcherRuneToCallerSuppliedImpl) - val dispatcherTemplateId = TemplataCompiler.getTemplate(dispatcherFullNameT) - dispatcherPlaceholderFullNameToSuppliedTemplata.map(_._1).foreach(x => vassert(x.initId(interner) == dispatcherTemplateId)) - - val dispatcherInstantiator = - new Instantiator( - opts, - interner, - keywords, - hinputs, - monouts, - TemplataCompiler.getFunctionTemplate(dispatcherFullNameT), - dispatcherFullNameT, - Map(dispatcherTemplateId -> dispatcherPlaceholderFullNameToSuppliedTemplata.toMap), - DenizenBoundToDenizenCallerBoundArg( - dispatcherFunctionBoundToIncomingPrototype, - dispatcherImplBoundToIncomingImpl)) - - // These are the placeholders' templatas that should be visible from inside the dispatcher case. + val dispatcherTemplateId = TemplataCompiler.getTemplate(dispatcherIdT) + dispatcherPlaceholderIdToSuppliedTemplata.map(_._1).foreach(x => vassert(x.initId(interner) == dispatcherTemplateId)) + + // These are the instantiated values that should be visible from inside the dispatcher case. // These will be used to call the override properly. - val dispatcherCasePlaceholderFullNameToSuppliedTemplata = - dispatcherCaseFullNameT.localName.independentImplTemplateArgs.zipWithIndex.map({ + // Sometimes (such as in the Milano case, see OMCNAGP) we have independent runes that need to be filled. + // DO NOT SUBMIT talk about this more. + val dispatcherCasePlaceholderIdToSuppliedTemplata = + dispatcherCaseIdT.localName.independentImplTemplateArgs.zipWithIndex.map({ case (casePlaceholderTemplata, index) => { - val casePlaceholderFullName = + val casePlaceholderId = TemplataCompiler.getPlaceholderTemplataId(casePlaceholderTemplata) val implPlaceholder = vassertSome( implPlaceholderToCasePlaceholder.find(_._2 == casePlaceholderTemplata))._1 val IdT(_, _, KindPlaceholderNameT(KindPlaceholderTemplateNameT(index, rune))) = implPlaceholder - val templata = implFullName.localName.templateArgs(index) - casePlaceholderFullName -> templata + val templata = implIdC.localName.templateArgs(index) + // TODO(regions): Figure out how to turn this into an sI. + casePlaceholderId -> vregionmut(templata.asInstanceOf[ITemplataI[sI]]) // // templata is the value from the edge that's doing the overriding. It comes from the impl. - // val dispatcherCasePlaceholderFullName = - // dispatcherCaseFullNameT.addStep(interner.intern(PlaceholderNameT(interner.intern(PlaceholderTemplateNameT(index))))) + // val dispatcherCasePlaceholderId = + // dispatcherCaseIdT.addStep(interner.intern(PlaceholderNameT(interner.intern(PlaceholderTemplateNameT(index))))) // val templataGivenToCaseFromImpl = - // edgeInstantiator.translateTemplata(templataGivenToCaseFromImplT) - // dispatcherCasePlaceholderFullName -> templataGivenToCaseFromImpl + // edgetranslateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, templataGivenToCaseFromImplT) + // dispatcherCasePlaceholderId -> templataGivenToCaseFromImpl } }) val edgeDenizenBoundToDenizenCallerSuppliedThing = - edgeInstantiator.denizenBoundToDenizenCallerSuppliedThing + edgeDenizenBoundToDenizenCallerBoundArgI // See TIBANFC, we need this map to bring in the impl bound args for the override dispatcher @@ -559,7 +820,7 @@ object Instantiator { }}) val caseDenizenBoundToDenizenCallerSuppliedThing = - DenizenBoundToDenizenCallerBoundArg( + DenizenBoundToDenizenCallerBoundArgI( caseFunctionBoundToIncomingPrototype, caseImplBoundToIncomingImpl) @@ -588,29 +849,30 @@ object Instantiator { // .map(_.implBoundToCallerSuppliedImpl) // .reduceOption(_ ++ _).getOrElse(Map())) - dispatcherPlaceholderFullNameToSuppliedTemplata.map(_._1).foreach(x => vassert(x.initId(interner) == dispatcherTemplateId)) - dispatcherCasePlaceholderFullNameToSuppliedTemplata.map(_._1).foreach(x => vassert(x.initId(interner) == dispatcherFullNameT)) + dispatcherPlaceholderIdToSuppliedTemplata.map(_._1).foreach(x => vassert(x.initId(interner) == dispatcherTemplateId)) + dispatcherCasePlaceholderIdToSuppliedTemplata.map(_._1).foreach(x => vassert(x.initId(interner) == dispatcherIdT)) - val dispatcherPlaceholderFullNameToSuppliedTemplataMap = dispatcherPlaceholderFullNameToSuppliedTemplata.toMap - val dispatcherCasePlaceholderFullNameToSuppliedTemplataMap = dispatcherCasePlaceholderFullNameToSuppliedTemplata.toMap + val dispatcherPlaceholderIdToSuppliedTemplataMap = dispatcherPlaceholderIdToSuppliedTemplata.toMap + val dispatcherCasePlaceholderIdToSuppliedTemplataMap = dispatcherCasePlaceholderIdToSuppliedTemplata.toMap // Sanity check there's no overlap vassert( - (dispatcherPlaceholderFullNameToSuppliedTemplataMap ++ dispatcherCasePlaceholderFullNameToSuppliedTemplataMap).size == - dispatcherPlaceholderFullNameToSuppliedTemplataMap.size + dispatcherCasePlaceholderFullNameToSuppliedTemplataMap.size) - - val caseInstantiator = - new Instantiator( - opts, - interner, - keywords, - hinputs, - monouts, - dispatcherCaseFullNameT, - dispatcherCaseFullNameT, - Map( - dispatcherTemplateId -> dispatcherPlaceholderFullNameToSuppliedTemplataMap, - dispatcherFullNameT -> dispatcherCasePlaceholderFullNameToSuppliedTemplataMap), - caseDenizenBoundToDenizenCallerSuppliedThing) + (dispatcherPlaceholderIdToSuppliedTemplataMap ++ dispatcherCasePlaceholderIdToSuppliedTemplataMap).size == + dispatcherPlaceholderIdToSuppliedTemplataMap.size + dispatcherCasePlaceholderIdToSuppliedTemplataMap.size) + + val caseSubstitutions = + Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( + dispatcherTemplateId -> dispatcherPlaceholderIdToSuppliedTemplataMap, + dispatcherIdT -> dispatcherCasePlaceholderIdToSuppliedTemplataMap) +// val caseInstantiator = +// new Instantiator( +// opts, +// interner, +// keywords, +// hinputs, +// monouts, +// dispatcherCaseIdT, +// dispatcherCaseIdT, +// caseDenizenBoundToDenizenCallerSuppliedThing) // right here we're calling it from the perspective of the abstract function @@ -619,45 +881,55 @@ object Instantiator { // we need to make a instantiator that thinks in terms of impl overrides. - val overridePrototype = caseInstantiator.translatePrototype(overridePrototypeT) + val (overridePrototypeS, overridePrototypeC) = + translatePrototype( + dispatcherCaseIdT, + caseDenizenBoundToDenizenCallerSuppliedThing, + caseSubstitutions, + GlobalRegionT(), + overridePrototypeT) - val superInterfaceFullName = vassertSome(monouts.impls.get(implFullName))._2 + val superInterfaceId = vassertSome(monouts.impls.get(implIdC))._2 - val overrride = - OverrideT( - dispatcherFullNameT, Vector(), Vector(), Map(), Map(), Map(), dispatcherCaseFullNameT, overridePrototype) - monouts.addMethodToVTable(implFullName, superInterfaceFullName, abstractFuncPrototype, overrride) + monouts.addMethodToVTable(implIdC, superInterfaceId, abstractFuncPrototypeC, overridePrototypeC) } def translateImpl( opts: GlobalOptions, interner: Interner, keywords: Keywords, - hinputs: Hinputs, + hinputs: HinputsT, monouts: InstantiatedOutputs, - implFullName: IdT[IImplNameT], - instantiationBoundsForUnsubstitutedImpl: InstantiationBoundArgumentsT): + implIdT: IdT[IImplNameT], + implIdN: IdI[nI, IImplNameI[nI]], + instantiationBoundsForUnsubstitutedImpl: InstantiationBoundArgumentsI): Unit = { - val implTemplateFullName = TemplataCompiler.getImplTemplate(implFullName) + // This works because the sI/cI are never actually used in these instances, they are just a + // compile-time type-system bit of tracking, see CCFCTS. + val implIdS: IdI[sI, IImplNameI[sI]] = implIdN + val implIdC = RegionCollapserIndividual.collapseImplId(implIdS) + + val implTemplateId = TemplataCompiler.getImplTemplate(implIdT) val implDefinition = vassertOne( hinputs.interfaceToSubCitizenToEdge .flatMap(_._2.values) .filter(edge => { - TemplataCompiler.getImplTemplate(edge.edgeId) == implTemplateFullName + //TemplataCompiler.getSuperTemplate(edge.edgeId) == TemplataCompiler.getSuperTemplate(implTemplateId), doesnt fix it + TemplataCompiler.getImplTemplate(edge.edgeId) == implTemplateId })) val subCitizenT = implDefinition.subCitizen val subCitizenM = - implFullName.localName match { - case ImplNameT(template, templateArgs, subCitizen) => subCitizen - case AnonymousSubstructImplNameT(template, templateArgs, subCitizen) => subCitizen + implIdS.localName match { + case ImplNameI(template, templateArgs, subCitizen) => subCitizen + case AnonymousSubstructImplNameI(template, templateArgs, subCitizen) => subCitizen case other => vimpl(other) } val denizenBoundToDenizenCallerSuppliedThingFromDenizenItself = - DenizenBoundToDenizenCallerBoundArg( + DenizenBoundToDenizenCallerBoundArgI( assembleCalleeDenizenFunctionBounds( implDefinition.runeToFuncBound, instantiationBoundsForUnsubstitutedImpl.runeToFunctionBoundArg), assembleCalleeDenizenImplBounds( @@ -667,7 +939,7 @@ object Instantiator { hoistBoundsFromParameter(hinputs, monouts, subCitizenT, subCitizenM) val denizenBoundToDenizenCallerSuppliedThing = - DenizenBoundToDenizenCallerBoundArg( + DenizenBoundToDenizenCallerBoundArgI( denizenBoundToDenizenCallerSuppliedThingFromDenizenItselfAndParams .map(_.funcBoundToCallerSuppliedBoundArgFunc) .reduceOption(_ ++ _).getOrElse(Map()), @@ -675,29 +947,39 @@ object Instantiator { .map(_.implBoundToCallerSuppliedBoundArgImpl) .reduceOption(_ ++ _).getOrElse(Map())) - val instantiator = - new Instantiator( - opts, - interner, - keywords, - hinputs, - monouts, - implTemplateFullName, - implFullName, - Map(implTemplateFullName -> assemblePlaceholderMap(hinputs, implFullName)), - denizenBoundToDenizenCallerSuppliedThing) - instantiator.translateImplDefinition(implFullName, implDefinition) - - - // val (subCitizenFullName, superInterfaceFullName, implBoundToImplCallerSuppliedPrototype) = vassertSome(monouts.impls.get(implFullName)) - // val subCitizenTemplateFullName = TemplataCompiler.getCitizenTemplate(subCitizenFullName) - // val subCitizenDefinition = hinputs.lookupCitizenByTemplateFullName(subCitizenTemplateFullName) + val substitutions = + Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( + implTemplateId -> assemblePlaceholderMap(implDefinition.edgeId, implIdS)) +// val instantiator = +// new Instantiator( +// opts, +// interner, +// keywords, +// hinputs, +// monouts, +// implTemplateId, +// implIdT, +// denizenBoundToDenizenCallerSuppliedThing) +// instantiator.translateImplDefinition(substitutions, implIdT, implIdI, implDefinition) + translateCollapsedImplDefinition( + implIdT, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + implIdT, + implIdS, + implIdC, + implDefinition) + + + // val (subCitizenId, superInterfaceId, implBoundToImplCallerSuppliedPrototype) = vassertSome(monouts.impls.get(implId)) + // val subCitizenTemplateId = TemplataCompiler.getCitizenTemplate(subCitizenId) + // val subCitizenDefinition = hinputs.lookupCitizenByTemplateId(subCitizenTemplateId) // val subCitizenPlaceholderedName = subCitizenDefinition.instantiatedCitizen - // val superInterfaceTemplateFullName = TemplataCompiler.getInterfaceTemplate(superInterfaceFullName) - // val superInterfaceDefinition = hinputs.lookupInterfaceByTemplateFullName(superInterfaceTemplateFullName) + // val superInterfaceTemplateId = TemplataCompiler.getInterfaceTemplate(superInterfaceId) + // val superInterfaceDefinition = hinputs.lookupInterfaceByTemplateId(superInterfaceTemplateId) // val superInterfacePlaceholderedName = superInterfaceDefinition.instantiatedInterface - // val abstractFuncToBounds = vassertSome(monouts.interfaceToAbstractFuncToBounds.get(superInterfaceFullName)) + // val abstractFuncToBounds = vassertSome(monouts.interfaceToAbstractFuncToBounds.get(superInterfaceId)) // abstractFuncToBounds.foreach({ case (abstractFunc, _) => // val edge = // vassertSome( @@ -709,31 +991,37 @@ object Instantiator { // vassertSome(edge.abstractFuncTemplateToOverrideFunc.get(abstractFuncTemplateName)) // // val funcT = - // DenizenInstantiator.translateFunction( + // DenizentranslateFunction( // opts, interner, keywords, hinputs, monouts, overridePrototype.fullName, - // translateBoundArgsForCallee( + // translateBoundArgsForCallee(denizenName, denizenBoundToDenizenCallerSuppliedThing, // hinputs.getInstantiationBounds(overridePrototype.fullName))) // - // monouts.addMethodToVTable(implFullName, superInterfaceFullName, abstractFunc, funcT) + // monouts.addMethodToVTable(implId, superInterfaceId, abstractFunc, funcT) // }) } - def translateFunction( + // DO NOT SUBMIT figure out better name + def translateFunction1( opts: GlobalOptions, interner: Interner, keywords: Keywords, - hinputs: Hinputs, + hinputs: HinputsT, monouts: InstantiatedOutputs, - desiredPrototype: PrototypeT, - suppliedBoundArgs: InstantiationBoundArgumentsT, - // This is only Some if this is a lambda. This will contain the prototypes supplied to the top level denizen by its - // own caller, see LCNBAFA. - maybeDenizenBoundToDenizenCallerSuppliedThing: Option[DenizenBoundToDenizenCallerBoundArg]): - FunctionDefinitionT = { - val funcTemplateNameT = TemplataCompiler.getFunctionTemplate(desiredPrototype.id) - - val desiredFuncSuperTemplateName = TemplataCompiler.getSuperTemplate(desiredPrototype.id) + desiredPrototypeT: PrototypeT, + desiredPrototypeN: PrototypeI[nI], + suppliedBoundArgs: InstantiationBoundArgumentsI, + // This is only Some if this is a lambda. This will contain the prototypes supplied to the top + // level denizen by its own caller, see LCNBAFA. + maybeDenizenBoundToDenizenCallerSuppliedThing: Option[DenizenBoundToDenizenCallerBoundArgI]): + FunctionDefinitionI = { + // This works because the sI/cI are never actually used in these instances, they are just a + // compile-time type-system bit of tracking, see CCFCTS. + val desiredPrototypeI: PrototypeI[sI] = desiredPrototypeN + val desiredPrototypeC = + RegionCollapserIndividual.collapsePrototype(desiredPrototypeI) + + val desiredFuncSuperTemplateName = TemplataCompiler.getSuperTemplate(desiredPrototypeT.id) val funcT = vassertOne( hinputs.functions @@ -742,13 +1030,13 @@ object Instantiator { val denizenBoundToDenizenCallerSuppliedThingFromDenizenItself = maybeDenizenBoundToDenizenCallerSuppliedThing.getOrElse({ - DenizenBoundToDenizenCallerBoundArg( + DenizenBoundToDenizenCallerBoundArgI( // This is a top level denizen, and someone's calling it. Assemble the bounds! assembleCalleeDenizenFunctionBounds(funcT.runeToFuncBound, suppliedBoundArgs.runeToFunctionBoundArg), // This is a top level denizen, and someone's calling it. Assemble the bounds! assembleCalleeDenizenImplBounds(funcT.runeToImplBound, suppliedBoundArgs.runeToImplBoundArg)) }) - val argsM = desiredPrototype.id.localName.parameters.map(_.kind) + val argsM = desiredPrototypeI.id.localName.parameters.map(_.kind) val paramsT = funcT.header.params.map(_.tyype.kind) val denizenBoundToDenizenCallerSuppliedThingFromParams = paramsT.zip(argsM).flatMap({ case (a, x) => @@ -760,7 +1048,7 @@ object Instantiator { denizenBoundToDenizenCallerSuppliedThingFromParams val denizenBoundToDenizenCallerSuppliedThing = - DenizenBoundToDenizenCallerBoundArg( + DenizenBoundToDenizenCallerBoundArgI( denizenBoundToDenizenCallerSuppliedThingFromDenizenItselfAndParams .map(_.funcBoundToCallerSuppliedBoundArgFunc) .reduceOption(_ ++ _).getOrElse(Map()), @@ -769,69 +1057,247 @@ object Instantiator { .reduceOption(_ ++ _).getOrElse(Map())) - val topLevelDenizenFullName = - getTopLevelDenizenId(desiredPrototype.id) - val topLevelDenizenTemplateFullName = - TemplataCompiler.getTemplate(topLevelDenizenFullName) - // One would imagine we'd get structFullName.last.templateArgs here, because that's the struct + val topLevelDenizenId = + getTopLevelDenizenId(desiredPrototypeT.id) + val topLevelDenizenTemplateId = + TemplataCompiler.getTemplate(topLevelDenizenId) + // One would imagine we'd get structId.last.templateArgs here, because that's the struct // we're about to monomorphize. However, only the top level denizen has placeholders, see LHPCTLD. val topLevelDenizenPlaceholderIndexToTemplata = - topLevelDenizenFullName.localName.templateArgs - - - val instantiator = - new Instantiator( - opts, - interner, - keywords, - hinputs, - monouts, - funcTemplateNameT, - desiredPrototype.id, - Map( - topLevelDenizenTemplateFullName -> - assemblePlaceholderMap(hinputs, topLevelDenizenFullName)), - denizenBoundToDenizenCallerSuppliedThing) - - desiredPrototype.id match { - case IdT(_,Vector(),FunctionNameT(FunctionTemplateNameT(StrI("as"),_),_, _)) => { - vpass() - } - case _ => false - } + topLevelDenizenId.localName.templateArgs + + val substitutions = + Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( + topLevelDenizenTemplateId -> + assemblePlaceholderMap(funcT.header.id, desiredPrototypeI.id)) +// val instantiator = +// new Instantiator( +// opts, +// interner, +// keywords, +// hinputs, +// monouts, +// funcTemplateNameT, +// desiredPrototypeT.id, +// denizenBoundToDenizenCallerSuppliedThing) + + val monomorphizedFuncT = + translateCollapsedFunction( + desiredPrototypeT.id, denizenBoundToDenizenCallerSuppliedThing, substitutions, desiredPrototypeC, funcT) + + vassert(desiredPrototypeC.returnType == monomorphizedFuncT.header.returnType) - val monomorphizedFuncT = instantiator.translateFunction(funcT) + monomorphizedFuncT + } - vassert(desiredPrototype.returnType == monomorphizedFuncT.header.returnType) + def translateAbstractFunc( + opts: GlobalOptions, + interner: Interner, + keywords: Keywords, + hinputs: HinputsT, + monouts: InstantiatedOutputs, + interfaceIdC: IdI[cI, IInterfaceNameI[cI]], + desiredAbstractPrototypeT: PrototypeT, + desiredAbstractPrototypeN: PrototypeI[nI], + virtualIndex: Int, + suppliedBoundArgs: InstantiationBoundArgumentsI): + Unit = { + // This works because the sI/cI are never actually used in these instances, they are just a + // compile-time type-system bit of tracking, see CCFCTS. + val desiredAbstractPrototypeI: PrototypeI[sI] = desiredAbstractPrototypeN + val desiredAbstractPrototypeC = + RegionCollapserIndividual.collapsePrototype(desiredAbstractPrototypeI) - monomorphizedFuncT + val desiredSuperTemplateId = TemplataCompiler.getSuperTemplate(desiredAbstractPrototypeT.id) + val funcT = + vassertOne( + hinputs.functions + .filter(funcT => TemplataCompiler.getSuperTemplate(funcT.header.id) == desiredSuperTemplateId)) + + + val denizenBoundToDenizenCallerSuppliedThingFromDenizenItself = + DenizenBoundToDenizenCallerBoundArgI( + // This is a top level denizen, and someone's calling it. Assemble the bounds! + assembleCalleeDenizenFunctionBounds(funcT.runeToFuncBound, suppliedBoundArgs.runeToFunctionBoundArg), + // This is a top level denizen, and someone's calling it. Assemble the bounds! + assembleCalleeDenizenImplBounds(funcT.runeToImplBound, suppliedBoundArgs.runeToImplBoundArg)) + val argsM = desiredAbstractPrototypeI.id.localName.parameters.map(_.kind) + val paramsT = funcT.header.params.map(_.tyype.kind) + val denizenBoundToDenizenCallerSuppliedThingFromParams = + paramsT.zip(argsM).flatMap({ case (a, x) => + hoistBoundsFromParameter(hinputs, monouts, a, x) + }) + + val denizenBoundToDenizenCallerSuppliedThingFromDenizenItselfAndParams = + Vector(denizenBoundToDenizenCallerSuppliedThingFromDenizenItself) ++ + denizenBoundToDenizenCallerSuppliedThingFromParams + + val denizenBoundToDenizenCallerSuppliedThing = + DenizenBoundToDenizenCallerBoundArgI( + denizenBoundToDenizenCallerSuppliedThingFromDenizenItselfAndParams + .map(_.funcBoundToCallerSuppliedBoundArgFunc) + .reduceOption(_ ++ _).getOrElse(Map()), + denizenBoundToDenizenCallerSuppliedThingFromDenizenItselfAndParams + .map(_.implBoundToCallerSuppliedBoundArgImpl) + .reduceOption(_ ++ _).getOrElse(Map())) + + + vassert(!monouts.abstractFuncToInstantiatorAndSuppliedPrototypes.contains(desiredAbstractPrototypeC.id)) + monouts.abstractFuncToInstantiatorAndSuppliedPrototypes.put(desiredAbstractPrototypeC.id, (denizenBoundToDenizenCallerSuppliedThing, suppliedBoundArgs)) + + val abstractFuncs = vassertSome(monouts.interfaceToAbstractFuncToVirtualIndex.get(interfaceIdC)) + vassert(!abstractFuncs.contains(desiredAbstractPrototypeC)) + abstractFuncs.put(desiredAbstractPrototypeC, virtualIndex) + + vassertSome(monouts.interfaceToImpls.get(interfaceIdC)).foreach({ case (implT, impl) => + translateOverride(opts, interner, keywords, hinputs, monouts, implT, impl, desiredAbstractPrototypeT, desiredAbstractPrototypeC) + }) + } + + def assemblePlaceholderMap( + idT: IdT[INameT], + idI: IdI[sI, INameI[sI]]): + Map[IdT[IPlaceholderNameT], ITemplataI[sI]] = { + (idT.initNonPackageId() match { + case None => Map() + case Some(initNonPackageIdT) => { + assemblePlaceholderMap(initNonPackageIdT, vassertSome(idI.initNonPackageFullName())) + } + }) ++ + (idT match { + case IdT(packageCoordT, initStepsT, localNameT: IInstantiationNameT) => { + val instantiationIdT = IdT(packageCoordT, initStepsT, localNameT) + val instantiationIdI = + idI match { + case IdI(packageCoordI, initStepsI, localNameUncastedI) => { + if (localNameUncastedI.isInstanceOf[IInstantiationNameI[sI]]) { + IdI(packageCoordI, initStepsI, localNameUncastedI.asInstanceOf[IInstantiationNameI[sI]]) + } else { + vwat() + } + } + case _ => vwat() + } + assemblePlaceholderMapInner(instantiationIdT, instantiationIdI) + } + case _ => Map() + }) + } + + def assemblePlaceholderMapInner( + idT: IdT[IInstantiationNameT], + idI: IdI[sI, IInstantiationNameI[sI]]): + Map[IdT[IPlaceholderNameT], ITemplataI[sI]] = { + val placeholderedName = idT +// val placeholderedName = +// idT match { +// case IdT(_, _, localName : IStructNameT) => { +// hinputs.lookupStructByTemplate(localName.template).instantiatedCitizen.id +// } +// case IdT(_, _, localName : IInterfaceNameT) => { +// hinputs.lookupInterfaceByTemplate(localName.template).instantiatedInterface.id +// } +// case IdT(_, _, localName : IFunctionNameT) => { +// vassertSome(hinputs.lookupFunction(localName.template)).header.id +// } +// case IdT(_, _, localName : IImplNameT) => { +// hinputs.lookupImplByTemplate(localName.template).edgeId +// } +// case IdT(_, _, localName : ExportNameT) => { +// vassertOne( +// hinputs.kindExports.filter(_.id.localName.template == localName.template).map(_.id) ++ +// hinputs.functionExports.filter(_.exportId.localName.template == localName.template).map(_.exportId)) +// } +// } + + placeholderedName.localName.templateArgs + .zip(idI.localName.templateArgs) + .flatMap({ + case ( + CoordTemplataT(CoordT(placeholderOwnership, GlobalRegionT(), kindT)), + c @ CoordTemplataI(regionI, _)) => { + kindT match { + case KindPlaceholderT(kindPlaceholderId) => { + vregionmut() + // vassert(placeholderOwnership == OwnT || placeholderOwnership == ShareT) + // In "Array has" test, we actually have a placeholder thats a borrow. + + // // We might need to do something with placeholderRegion here, but I think we can just + // // assume it correctly matches up with the coord's region. The typing phase should have + // // made sure it matches up nicely. + // // If we hit this vimpl, then we might need to find some way to hand in the region, + // // even though we lost that in the translation to IdI which has no regions. We might be + // // able to scavenge it from the name, though it might be tricky to get the region of + // // region-less primitives. Perhaps we can assume theyre the same region as their + // // parent template? + // val regionTemplata = + // maybeRegionHeight.map(x => RegionTemplataI[sI](x)).getOrElse(vimpl()) + vcurious(regionI.pureHeight <= 0) // These are subjective, but they should be negative + List( + (kindPlaceholderId -> c)) + } + // This could be e.g. *i32 and *!i32, in other words the template arg is already populated. This can + // happen if we're processing a lambda's name. + // placeholderedName *doesn't* contain a placeholder like one might normally expect: + // test/main.lam:0:34.__call{lam:0:34, *i32}<__call$0> (doesn't have this) + // Instead placeholderedName might be: + // test/main.lam:0:34.__call{lam:0:34, *i32}<*i32> + // ...because the typing phase already filled it in. + // Theoretically the typing phase could have stripped that out before now, maybe. Don't know. + // Either way, it is there. + // Just ignore it, we don't need a mapping for it. + case _ => { + List() + } + } + } + case (KindTemplataT(KindPlaceholderT(placeholderId)), kindTemplataI) => { + List((placeholderId -> kindTemplataI)) + } + case (PlaceholderTemplataT(placeholderId, tyype), templataI) => { + List((placeholderId -> templataI)) + } + case (MutabilityTemplataT(MutableT),MutabilityTemplataI(MutableI)) | + (MutabilityTemplataT(ImmutableT),MutabilityTemplataI(ImmutableI)) => { + // We once got a `mut` for the placeholdered name's templata. + // That's because we do some specialization for arrays still. + // They don't come with a placeholder, so ignore them. + List() + } + case other => vimpl(other) + }) + .toMap } // This isn't just for parameters, it's for impl subcitizens, and someday for cases too. // See NBIFP private def hoistBoundsFromParameter( - hinputs: Hinputs, + hinputs: HinputsT, monouts: InstantiatedOutputs, paramT: KindT, - paramM: KindT): - Option[DenizenBoundToDenizenCallerBoundArg] = { - (paramT, paramM) match { - case (StructTT(structFullNameT), StructTT(structFullNameM)) => { - val calleeRuneToBoundArgT = hinputs.getInstantiationBoundArgs(structFullNameT) - val (_, structDenizenBoundToDenizenCallerSuppliedThing) = vassertSome(monouts.startedStructs.get(structFullNameM)) - val structT = findStruct(hinputs, structFullNameT) + paramI: KindIT[sI]): + Option[DenizenBoundToDenizenCallerBoundArgI] = { + (paramT, paramI) match { + case (StructTT(structIdT), StructIT(structIdI)) => { + val calleeRuneToBoundArgT = hinputs.getInstantiationBoundArgs(structIdT) + val structDenizenBoundToDenizenCallerSuppliedThing = + vassertSome(monouts.structToBounds.get(structIdI)) + val structT = findStruct(hinputs, structIdT) val denizenBoundToDenizenCallerSuppliedThing = hoistBoundsFromParameterInner( structDenizenBoundToDenizenCallerSuppliedThing, calleeRuneToBoundArgT, structT.runeToFunctionBound, structT.runeToImplBound) Some(denizenBoundToDenizenCallerSuppliedThing) } - case (InterfaceTT(interfaceFullNameT), InterfaceTT(interfaceFullNameM)) => { - val calleeRuneToBoundArgT = hinputs.getInstantiationBoundArgs(interfaceFullNameT) - val (_, interfaceDenizenBoundToDenizenCallerSuppliedThing) = vassertSome(monouts.startedInterfaces.get(interfaceFullNameM)) - val interfaceT = findInterface(hinputs, interfaceFullNameT) + case (InterfaceTT(interfaceIdT), InterfaceIT(interfaceIdM)) => { + val calleeRuneToBoundArgT = hinputs.getInstantiationBoundArgs(interfaceIdT) + val interfaceDenizenBoundToDenizenCallerSuppliedThing = vassertSome(monouts.interfaceToBounds.get(interfaceIdM)) + val interfaceT = findInterface(hinputs, interfaceIdT) val denizenBoundToDenizenCallerSuppliedThing = hoistBoundsFromParameterInner( - interfaceDenizenBoundToDenizenCallerSuppliedThing, calleeRuneToBoundArgT, interfaceT.runeToFunctionBound, interfaceT.runeToImplBound) + interfaceDenizenBoundToDenizenCallerSuppliedThing, + calleeRuneToBoundArgT, + interfaceT.runeToFunctionBound, + interfaceT.runeToImplBound) Some(denizenBoundToDenizenCallerSuppliedThing) } case _ => None @@ -840,11 +1306,11 @@ object Instantiator { // See NBIFP private def hoistBoundsFromParameterInner( - parameterDenizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArg, + parameterDenizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, calleeRuneToBoundArgT: InstantiationBoundArgumentsT, calleeRuneToCalleeFunctionBoundT: Map[IRuneS, IdT[FunctionBoundNameT]], calleeRuneToCalleeImplBoundT: Map[IRuneS, IdT[ImplBoundNameT]]): - DenizenBoundToDenizenCallerBoundArg = { + DenizenBoundToDenizenCallerBoundArgI = { val calleeFunctionBoundTToBoundArgM = parameterDenizenBoundToDenizenCallerSuppliedThing.funcBoundToCallerSuppliedBoundArgFunc val implBoundTToBoundArgM = parameterDenizenBoundToDenizenCallerSuppliedThing.implBoundToCallerSuppliedBoundArgImpl @@ -898,85 +1364,19 @@ object Instantiator { }).flatten.toMap val denizenBoundToDenizenCallerSuppliedThing = - DenizenBoundToDenizenCallerBoundArg( + DenizenBoundToDenizenCallerBoundArgI( callerSuppliedBoundToInstantiatedFunction, callerSuppliedBoundToInstantiatedImpl) denizenBoundToDenizenCallerSuppliedThing } - def assemblePlaceholderMap(hinputs: Hinputs, id: IdT[IInstantiationNameT]): - Map[IdT[IPlaceholderNameT], ITemplataT[ITemplataType]] = { - val containersPlaceholderMap = - // This might be a lambda's name. If it is, its name has an init step that's the parent - // function's name, and we want its mappings too. - (id.initNonPackageId() match { - case Some(IdT(packageCoord, initSteps, parentLocalName : IInstantiationNameT)) => { - assemblePlaceholderMap(hinputs, IdT(packageCoord, initSteps, parentLocalName)) - } - case _ => Map[IdT[KindPlaceholderNameT], ITemplataT[ITemplataType]]() - }) - - val placeholderedName = - id match { - case IdT(_, _, localName : IStructNameT) => { - hinputs.lookupStructByTemplate(localName.template).instantiatedCitizen.id - } - case IdT(_, _, localName : IInterfaceNameT) => { - hinputs.lookupInterfaceByTemplate(localName.template).instantiatedInterface.id - } - case IdT(_, _, localName : IFunctionNameT) => { - vassertSome(hinputs.lookupFunction(localName.template)).header.id - } - case IdT(_, _, localName : IImplNameT) => { - hinputs.lookupImplByTemplate(localName.template).edgeId - } - } - - containersPlaceholderMap ++ - placeholderedName.localName.templateArgs - .zip(id.localName.templateArgs) - .flatMap({ - case (CoordTemplataT(CoordT(placeholderOwnership, _, KindPlaceholderT(placeholderId))), c @ CoordTemplataT(_)) => { - vassert(placeholderOwnership == OwnT || placeholderOwnership == ShareT) - List((placeholderId -> c)) - } - case (KindTemplataT(KindPlaceholderT(placeholderId)), kindTemplata) => { - List((placeholderId -> kindTemplata)) - } - case (PlaceholderTemplataT(placeholderId, tyype), templata) => { - List((placeholderId -> templata)) - } - case (a, b) => { - // We once got a `mut` for the placeholdered name's templata. - // That's because we do some specialization for arrays still. - // They don't come with a placeholder, so ignore them. - vassert(a == b) - List() - } - }) - .toMap - } -} +// def translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, templata: ITemplataT[ITemplataType]): ITemplataI = { +// vimpl() +// } -class Instantiator( - opts: GlobalOptions, - interner: Interner, - keywords: Keywords, - hinputs: Hinputs, - monouts: InstantiatedOutputs, - denizenTemplateName: IdT[ITemplateNameT], - denizenName: IdT[IInstantiationNameT], - - // This IdT might be the top level denizen and not necessarily *this* denizen, see LHPCTLD. - substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataT[ITemplataType]]], - - val denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArg) { // selfFunctionBoundToRuneUnsubstituted: Map[PrototypeT, IRuneS], // denizenRuneToDenizenCallerPrototype: Map[IRuneS, PrototypeT]) { - // This is just here to get scala to include these fields so i can see them in the debugger - vassert(TemplataCompiler.getTemplate(denizenName) == denizenTemplateName) - // if (opts.sanityCheck) { // denizenFunctionBoundToDenizenCallerSuppliedPrototype.foreach({ // case (denizenFunctionBound, denizenCallerSuppliedPrototype) => { @@ -985,20 +1385,41 @@ class Instantiator( // }) // } - def translateStructMember(member: IStructMemberT): IStructMemberT = { + def translateStructMember( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + member: IStructMemberT): + (CoordI[sI], StructMemberI) = { member match { case NormalStructMemberT(name, variability, tyype) => { - NormalStructMemberT( - translateVarName(name), - variability, + val (memberSubjectiveIT, memberTypeI) = tyype match { - case ReferenceMemberTypeT((unsubstitutedCoord)) => { - ReferenceMemberTypeT(translateCoord(unsubstitutedCoord)) + case ReferenceMemberTypeT(unsubstitutedCoord) => { + val typeI = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, unsubstitutedCoord) + val result = + ReferenceMemberTypeI( + RegionCollapserIndividual.collapseCoord(typeI.coord)) + (typeI, result) } - case AddressMemberTypeT((unsubstitutedCoord)) => { - AddressMemberTypeT(translateCoord(unsubstitutedCoord)) + case AddressMemberTypeT(unsubstitutedCoord) => { + val typeI = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, unsubstitutedCoord) + val result = AddressMemberTypeI(RegionCollapserIndividual.collapseCoord(typeI.coord)) + (typeI, result) } - }) + } + val nameI = translateVarName(name) + val memberI = + StructMemberI( + RegionCollapserIndividual.collapseVarName(nameI), + translateVariability(variability), + memberTypeI) + (memberSubjectiveIT.coord, memberI) } case VariadicStructMemberT(name, tyype) => { vimpl() @@ -1006,68 +1427,149 @@ class Instantiator( } } + def translateVariability(x: VariabilityT): VariabilityI = { + x match { + case VaryingT => VaryingI + case FinalT => FinalI + } + } + + def translateMutability(m: MutabilityT): MutabilityI = { + m match { + case MutableT => MutableI + case ImmutableT => ImmutableI + } + } + // This is run at the call site, from the caller's perspective def translatePrototype( - desiredPrototypeUnsubstituted: PrototypeT): - PrototypeT = { - val PrototypeT(desiredPrototypeFullNameUnsubstituted, desiredPrototypeReturnTypeUnsubstituted) = desiredPrototypeUnsubstituted + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + desiredPrototypeT: PrototypeT): + (PrototypeI[sI], PrototypeI[cI]) = { + val PrototypeT(desiredPrototypeIdUnsubstituted, desiredPrototypeReturnTypeUnsubstituted) = desiredPrototypeT val runeToBoundArgsForCall = translateBoundArgsForCallee( - hinputs.getInstantiationBoundArgs(desiredPrototypeUnsubstituted.id)) - - val desiredPrototype = - PrototypeT( - translateFunctionFullName(desiredPrototypeFullNameUnsubstituted), - translateCoord(desiredPrototypeReturnTypeUnsubstituted)) - - desiredPrototypeUnsubstituted.id match { + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + hinputs.getInstantiationBoundArgs(desiredPrototypeT.id)) + + val returnSubjectiveIT = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, desiredPrototypeReturnTypeUnsubstituted) + + val desiredPrototypeS = + PrototypeI[sI]( + translateFunctionId(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, desiredPrototypeIdUnsubstituted), + returnSubjectiveIT.coord) + + desiredPrototypeT.id match { case IdT(packageCoord, initSteps, name @ FunctionBoundNameT(_, _, _)) => { val funcBoundName = IdT(packageCoord, initSteps, name) - val result = vassertSome(denizenBoundToDenizenCallerSuppliedThing.funcBoundToCallerSuppliedBoundArgFunc.get(funcBoundName)) + val prototypeS = vassertSome(denizenBoundToDenizenCallerSuppliedThing.funcBoundToCallerSuppliedBoundArgFunc.get(funcBoundName)) // if (opts.sanityCheck) { // vassert(Collector.all(result, { case PlaceholderTemplateNameT(_) => }).isEmpty) // } - result + + val prototypeC = + RegionCollapserIndividual.collapsePrototype(prototypeS) + + (prototypeS, prototypeC) } case IdT(_, _, ExternFunctionNameT(_, _)) => { if (opts.sanityCheck) { - vassert(Collector.all(desiredPrototype, { case KindPlaceholderTemplateNameT(_, _) => }).isEmpty) + vassert(Collector.all(desiredPrototypeS, { case KindPlaceholderTemplateNameT(_, _) => }).isEmpty) } - desiredPrototype + val desiredPrototypeC = + RegionCollapserIndividual.collapsePrototype(desiredPrototypeS) + (desiredPrototypeS, desiredPrototypeC) } case IdT(_, _, last) => { last match { case LambdaCallFunctionNameT(_, _, _) => { - vassert( - desiredPrototype.id.steps.slice(0, desiredPrototype.id.steps.length - 2) == - denizenName.steps) - vcurious(desiredPrototype.id.steps.startsWith(denizenName.steps)) + (denizenName.steps.last, desiredPrototypeS.id.steps.init.init.last) match { + case ( + FunctionNameT(FunctionTemplateNameT(nameA,codeLocA),templateArgsA,parametersA), + FunctionNameIX(FunctionTemplateNameI(nameB,codeLocB),templateArgsB,parametersB)) => { + // Make sure we're talking about roughly the same function + vassert(nameA == nameB) + vassert(codeLocA == codeLocB) + vassert(templateArgsA.length == templateArgsB.length) + vassert(parametersA.length == parametersB.length) + // TODO: Could we have a false positive here if we're doing things on different templates? + // I don't think so. DO NOT SUBMIT + } + case ( + LambdaCallFunctionNameT(LambdaCallFunctionTemplateNameT(codeLocA,paramsTTA),templateArgsA,parametersA), + LambdaCallFunctionNameI(LambdaCallFunctionTemplateNameI(codeLocB,paramsTTB),templateArgsB,parametersB)) => { + // Make sure we're talking about roughly the same function + vassert(codeLocA == codeLocB) + vassert(paramsTTA == paramsTTB) + vassert(templateArgsA.length == templateArgsB.length) + vassert(parametersA.length == parametersB.length) + } + case other => vwat(other) + } } case _ => } +// // Let's say we want to call 1'myPureDisplay(0'board). +// // We want that to become 0'myPureDisplay(-1'board). +// // The default region we send should always be zero, and all incoming imms should be negative. +// // DO NOT SUBMIT centralize docs +// // TODO use an array instead of a map here +// val oldRegionPureHeights = +// Collector.all(uncollapsedDesiredPrototypeI, { +// case RegionTemplataI(pureHeight) => pureHeight +// }).toVector.distinct.sorted +// val oldToNewRegionPureHeight = +// oldRegionPureHeights.zipWithIndex.map({ case (oldRegionPureHeight, index) => +// (oldRegionPureHeight, index - (oldRegionPureHeights.length - 1)) +// }).toMap + + val desiredPrototypeC = + RegionCollapserIndividual.collapsePrototype(desiredPrototypeS) + + val desiredPrototypeN = + RegionCollapserConsistent.collapsePrototype( + RegionCounter.countPrototype(desiredPrototypeS), + desiredPrototypeS) + + vassert(RegionCollapserIndividual.collapsePrototype(desiredPrototypeN) == desiredPrototypeC) + monouts.newFunctions.enqueue( ( - desiredPrototype, + desiredPrototypeT, + desiredPrototypeN, runeToBoundArgsForCall, - // We need to supply our bounds to our lambdas, see LCCPGB and LCNBAFA. - if (desiredPrototype.id.steps.startsWith(denizenName.steps)) { + // If we're instantiating something whose name starts with our name, then we're instantiating our lambda. + if (TemplataCompiler.getSuperTemplate(desiredPrototypeT.id).steps.startsWith(TemplataCompiler.getSuperTemplate(denizenName).steps)) { + // We need to supply our bounds to our lambdas, see LCCPGB and LCNBAFA. Some(denizenBoundToDenizenCallerSuppliedThing) } else { None })) - desiredPrototype + (desiredPrototypeS, desiredPrototypeC) } } } private def translateBoundArgsForCallee( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, // This contains a map from rune to a prototype, specifically the prototype that we // (the *template* caller) is supplying to the *template* callee. This prototype might // be a placeholder, phrased in terms of our (the *template* caller's) placeholders instantiationBoundArgsForCallUnsubstituted: InstantiationBoundArgumentsT): - InstantiationBoundArgumentsT = { + InstantiationBoundArgumentsI = { val runeToSuppliedPrototypeForCallUnsubstituted = instantiationBoundArgsForCallUnsubstituted.runeToFunctionBoundArg val runeToSuppliedPrototypeForCall = @@ -1081,7 +1583,10 @@ class Instantiator( IdT(packageCoord, initSteps, name))) } case _ => { - translatePrototype(suppliedPrototypeUnsubstituted) + val (prototypeI, prototypeC) = + translatePrototype( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, suppliedPrototypeUnsubstituted) + prototypeI } }) }) @@ -1103,46 +1608,69 @@ class Instantiator( // Not sure about these three lines, but they seem to work. val runeToBoundArgsForCall = translateBoundArgsForCallee( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, hinputs.getInstantiationBoundArgs(suppliedImplUnsubstituted)) - translateImplFullName(suppliedImplUnsubstituted, runeToBoundArgsForCall) + val implNameI = + translateImplId( + denizenName, denizenBoundToDenizenCallerSuppliedThing,substitutions, perspectiveRegionT, suppliedImplUnsubstituted, runeToBoundArgsForCall) + implNameI } }) }) // And now we have a map from the callee's rune to the *instantiated* callee's impls. - InstantiationBoundArgumentsT(runeToSuppliedPrototypeForCall, runeToSuppliedImplForCall) + InstantiationBoundArgumentsI(runeToSuppliedPrototypeForCall, runeToSuppliedImplForCall) } - def translateStructDefinition( - newFullName: IdT[IStructNameT], + def translateCollapsedStructDefinition( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + newIdT: IdT[IStructNameT], + newId: IdI[cI, IStructNameI[cI]], structDefT: StructDefinitionT): Unit = { val StructDefinitionT(templateName, instantiatedCitizen, attributes, weakable, mutabilityT, members, isClosure, _, _) = structDefT if (opts.sanityCheck) { - vassert(Collector.all(newFullName, { case KindPlaceholderNameT(_) => }).isEmpty) + vassert(Collector.all(newId, { case KindPlaceholderNameT(_) => }).isEmpty) } - val mutability = expectMutabilityTemplata(translateTemplata(mutabilityT)).mutability + val perspectiveRegionT = GlobalRegionT() + // structDefT.instantiatedCitizen.id.localName.templateArgs.last match { + // case PlaceholderTemplataT(IdT(packageCoord, initSteps, r @ RegionPlaceholderNameT(_, _, _, _)), RegionTemplataType()) => { + // IdT(packageCoord, initSteps, r) + // } + // case _ => vwat() + // } - if (monouts.startedStructs.contains(newFullName)) { + val mutability = ITemplataI.expectMutabilityTemplata(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, mutabilityT)).mutability + + if (monouts.structToMutability.contains(newId)) { return } - monouts.startedStructs.put(newFullName, (mutability, this.denizenBoundToDenizenCallerSuppliedThing)) + monouts.structToMutability.put(newId, mutability) + +// val currentPureHeight = vimpl() val result = - StructDefinitionT( - templateName, - interner.intern(StructTT(newFullName)), - attributes, + StructDefinitionI( +// templateName, + StructIT(newId), + attributes.map(vimpl(_)), weakable, - MutabilityTemplataT(mutability), - members.map(translateStructMember), + mutability, + members.map(memberT => { + translateStructMember(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, memberT)._2 + }), isClosure, Map(), Map()) - vassert(result.instantiatedCitizen.id == newFullName) + vassert(result.instantiatedCitizen.id == newId) monouts.structs.put(result.instantiatedCitizen.id, result) @@ -1153,246 +1681,672 @@ class Instantiator( result } - def translateInterfaceDefinition( - newFullName: IdT[IInterfaceNameT], + // This inner function is conceptually from the interface's own perspective. That's why it's + // taking in a collapsed id. + def translateCollapsedInterfaceDefinition( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + newIdC: IdI[cI, IInterfaceNameI[cI]], interfaceDefT: InterfaceDefinitionT): Unit = { + if (monouts.interfaceToMutability.contains(newIdC)) { + return + } + val InterfaceDefinitionT(templateName, instantiatedCitizen, ref, attributes, weakable, mutabilityT, _, _, internalMethods) = interfaceDefT - val mutability = expectMutabilityTemplata(translateTemplata(mutabilityT)).mutability + vassert(!monouts.interfaceToImplToAbstractPrototypeToOverride.contains(newIdC)) + monouts.interfaceToImplToAbstractPrototypeToOverride.put(newIdC, mutable.HashMap()) - if (monouts.startedInterfaces.contains(newFullName)) { - return + vassert(!monouts.interfaceToAbstractFuncToVirtualIndex.contains(newIdC)) + monouts.interfaceToAbstractFuncToVirtualIndex.put(newIdC, mutable.HashMap()) + + vassert(!monouts.interfaceToImpls.contains(newIdC)) + monouts.interfaceToImpls.put(newIdC, mutable.HashSet()) + + if (opts.sanityCheck) { + vassert(Collector.all(newIdC, { case KindPlaceholderNameT(_) => }).isEmpty) } - monouts.startedInterfaces.put(newFullName, (mutability, this.denizenBoundToDenizenCallerSuppliedThing)) - val newInterfaceTT = interner.intern(InterfaceTT(newFullName)) + val perspectiveRegionT = GlobalRegionT() + // interfaceDefT.instantiatedCitizen.id.localName.templateArgs.last match { + // case PlaceholderTemplataT(IdT(packageCoord, initSteps, r @ RegionPlaceholderNameT(_, _, _, _)), RegionTemplataType()) => { + // IdT(packageCoord, initSteps, r) + // } + // case _ => vwat() + // } + + val mutability = ITemplataI.expectMutabilityTemplata(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, mutabilityT)).mutability + + vassert(!monouts.interfaceToMutability.contains(newIdC)) + monouts.interfaceToMutability.put(newIdC, mutability) + + // val currentPureHeight = vimpl() + + val newInterfaceIT = InterfaceIT(newIdC) val result = - InterfaceDefinitionT( - templateName, - newInterfaceTT, - newInterfaceTT, - attributes, + InterfaceDefinitionI( + newInterfaceIT, + attributes.map({ + case SealedT => SealedI + case other => vimpl(other) + }), weakable, - MutabilityTemplataT(mutability), + mutability, Map(), Map(), Vector()) - if (opts.sanityCheck) { - vassert(Collector.all(result, { case KindPlaceholderNameT(_) => }).isEmpty) - } - - vassert(!monouts.interfaceToImplToAbstractPrototypeToOverride.contains(newFullName)) - monouts.interfaceToImplToAbstractPrototypeToOverride.put(newFullName, mutable.HashMap()) - - monouts.interfacesWithoutMethods.put(newFullName, result) + monouts.interfacesWithoutMethods.put(newIdC, result) - vassert(!monouts.interfaceToAbstractFuncToVirtualIndex.contains(newFullName)) - monouts.interfaceToAbstractFuncToVirtualIndex.put(newFullName, mutable.HashMap()) + vassert(result.instantiatedCitizen.id == newIdC) - vassert(!monouts.interfaceToImpls.contains(newFullName)) - monouts.interfaceToImpls.put(newFullName, mutable.HashSet()) + if (opts.sanityCheck) { + vassert(Collector.all(result.instantiatedInterface, { case KindPlaceholderNameT(_) => }).isEmpty) + } - vassert(result.instantiatedCitizen.id == newFullName) + result } - def translateFunctionHeader(header: FunctionHeaderT): FunctionHeaderT = { + def translateFunctionHeader( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + header: FunctionHeaderT): + FunctionHeaderI = { val FunctionHeaderT(fullName, attributes, params, returnType, maybeOriginFunctionTemplata) = header - val newFullName = translateFunctionFullName(fullName) + val newIdI = + translateFunctionId( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, fullName) + val newIdC = + RegionCollapserIndividual.collapseId[IFunctionNameI[sI], IFunctionNameI[cI]]( + newIdI, + x => RegionCollapserIndividual.collapseFunctionName( x)) - val result = - FunctionHeaderT( - newFullName, - attributes, - params.map(translateParameter), - translateCoord(returnType), - maybeOriginFunctionTemplata) + val returnIT = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, returnType) + val returnIC = RegionCollapserIndividual.collapseCoord(returnIT.coord) - // if (opts.sanityCheck) { - // vassert(Collector.all(result.fullName, { case PlaceholderNameT(_) => }).isEmpty) - // vassert(Collector.all(result.attributes, { case PlaceholderNameT(_) => }).isEmpty) - // vassert(Collector.all(result.params, { case PlaceholderNameT(_) => }).isEmpty) - // vassert(Collector.all(result.returnType, { case PlaceholderNameT(_) => }).isEmpty) - // } + val result = + FunctionHeaderI( + newIdC, + attributes.map(translateFunctionAttribute), + params.map(translateParameter(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), + returnIC) result } - def translateFunction( + def translateFunctionAttribute(x: IFunctionAttributeT): IFunctionAttributeI = { + x match { + case UserFunctionT => UserFunctionI + case PureT => PureI + case ExternT(packageCoord) => ExternI(packageCoord) + case other => vimpl(other) + } + } + + // DO NOT SUBMIT why does this one not take in the collapsed id like the struct and interface things + def translateCollapsedFunction( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + // For doublechecking we're getting the actual function we requested + desiredPrototypeC: PrototypeI[cI], functionT: FunctionDefinitionT): - FunctionDefinitionT = { + FunctionDefinitionI = { val FunctionDefinitionT(headerT, _, _, bodyT) = functionT val FunctionHeaderT(fullName, attributes, params, returnType, maybeOriginFunctionTemplata) = headerT - val newFullName = translateFunctionFullName(fullName) + if (opts.sanityCheck) { + Collector.all(substitutions.toVector, { + case RegionTemplataI(x) if x > 0 => vwat() + }) + } - monouts.functions.get(newFullName) match { + val perspectiveRegionT = GlobalRegionT() + // functionT.header.id.localName.templateArgs.last match { + // case PlaceholderTemplataT(IdT(packageCoord, initSteps, r @ RegionPlaceholderNameT(_, _, _, _)), RegionTemplataType()) => { + // IdT(packageCoord, initSteps, r) + // } + // case _ => vwat() + // } + + val functionIdI = + translateFunctionId( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, fullName) + val functionIdC = + RegionCollapserIndividual.collapseFunctionId(functionIdI) + + monouts.functions.get(functionIdC) match { case Some(func) => return func case None => } - val newHeader = translateFunctionHeader(headerT) + val newHeader = translateFunctionHeader(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, headerT) + + if (newHeader.toPrototype != desiredPrototypeC) { + translateFunctionHeader(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, headerT) + vfail() + } + + val startingEnv = NodeEnvironment(None) + val (bodySubjectiveIT, bodyIE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, startingEnv, substitutions, perspectiveRegionT, bodyT) + + val result = FunctionDefinitionI(newHeader, Map(), Map(), bodyIE) - val result = FunctionDefinitionT(newHeader, Map(), Map(), translateRefExpr(bodyT)) monouts.functions.put(result.header.id, result) result } def translateLocalVariable( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, variable: ILocalVariableT): - ILocalVariableT = { + // Returns subjective coord and the local var + (CoordI[sI], ILocalVariableI) = { variable match { - case r @ ReferenceLocalVariableT(_, _, _) => translateReferenceLocalVariable(r) - case AddressibleLocalVariableT(id, variability, coord) => { - AddressibleLocalVariableT( - translateVarName(id), - variability, - translateCoord(coord)) + case r @ ReferenceLocalVariableT(_, _, _) => { + translateReferenceLocalVariable( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, r) + } + case a @ AddressibleLocalVariableT(_, _, _) => { + translateAddressibleLocalVariable( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, a) } } } def translateReferenceLocalVariable( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, variable: ReferenceLocalVariableT): - ReferenceLocalVariableT = { - val ReferenceLocalVariableT(id, variability, reference) = variable - ReferenceLocalVariableT( - translateVarName(id), - variability, - translateCoord(reference)) + // Returns subjective coord and the local var + (CoordI[sI], ReferenceLocalVariableI) = { + val ReferenceLocalVariableT(id, variability, coord) = variable + val coordI = + translateCoord( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + coord) + val varNameI = translateVarName(id) + val localI = + ReferenceLocalVariableI( + RegionCollapserIndividual.collapseVarName(varNameI), + translateVariability(variability), + RegionCollapserIndividual.collapseCoord(coordI.coord)) + (coordI.coord, localI) + } + + def translateAddressibleLocalVariable( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + variable: AddressibleLocalVariableT): + // Returns subjective coord and the local var + (CoordI[sI], AddressibleLocalVariableI) = { + val AddressibleLocalVariableT(id, variability, coord) = variable + val coordI = + translateCoord( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + GlobalRegionT(), + coord) + val varI = translateVarName(id) + val localI = + AddressibleLocalVariableI( + RegionCollapserIndividual.collapseVarName(varI), + translateVariability(variability), + RegionCollapserIndividual.collapseCoord(coordI.coord)) + (coordI.coord, localI) } def translateAddrExpr( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + env: NodeEnvironment, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, expr: AddressExpressionTE): - AddressExpressionTE = { + // Returns the subjective coord (see HCCSCS) and the expression. + (CoordI[sI], AddressExpressionIE) = { expr match { - case LocalLookupTE(range, localVariable) => { - LocalLookupTE(range, translateLocalVariable(localVariable)) + case LocalLookupTE(range, localVariableT) => { +// // We specifically don't *translate* LocalLookupTE.localVariable because we can't translate +// // it properly from here with our current understandings of the regions' mutabilities, we +// // need its original type. See CTOTFIPB. +// val localVariable = env.lookupOriginalTranslatedVariable(localVariableT.name) + val (localSubjectiveIT, localVariableI) = + translateLocalVariable( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, localVariableT) +// +// val sourceRegion = +// ITemplataI.expectRegionTemplata( +// translateTemplata( +// denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, vimpl())) + +// val subjectiveResultIT = +// CoordI( +// (localVariableI.coord.ownership, coordRegionIsMutable(substitutions, perspectiveRegionT, localVariableT.coord)) match { +// case (OwnT, _) => OwnI +// case other => vimpl(other) +// }, +// localVariableI.coord.kind) + + val resultSubjectiveIT = localSubjectiveIT + val resultIE = + LocalLookupIE( + localVariableI, + RegionCollapserIndividual.collapseCoord(resultSubjectiveIT)) + (resultSubjectiveIT, resultIE) } - case ReferenceMemberLookupTE(range, structExpr, memberName, memberCoord, variability) => { - ReferenceMemberLookupTE( - range, - translateRefExpr(structExpr), - translateVarName(memberName), - translateCoord(memberCoord), - variability) + case ReferenceMemberLookupTE(range, structExprT, memberNameT, memberCoordT, variability) => { + val (structSubjectiveIT, structIE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, structExprT) + val structSubjectiveStructIT = structSubjectiveIT.kind.expectStruct() + val memberName = translateVarName(memberNameT) + +// // We can't translate ReferenceMemberLookupTE.memberCoord's kind here because we'll +// // translate its template args' regions incorrectly according to their current mutabilities. +// // They need to be the mutabilities at the time they were introduced, see CTOTFIPB. So +// // instead, we look it up from the struct definition. +// val structDef = vassertSome(monouts.structs.get(structSubjectiveStructIT.id)) +// val defMemberCoord: CoordT = vimpl() +//// vassertSome(structDef.members.find(_.name == memberName)) match { +//// case NormalStructMemberT(name, variability, tyype) => tyype.reference +//// case VariadicStructMemberT(name, tyype) => vimpl() +// } +// // However, the resulting coord's region *should* have the current mutability. + + val memberCoordI = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, memberCoordT) + +// val resultOwnership = +// (memberCoordI.ownership, resultRegion) match { +// case (OwnI, RegionTemplataI(_)) => OwnI +//// case (MutableShareI, RegionTemplataI(true)) => MutableShareI +//// case (MutableShareI, RegionTemplataI(false)) => ImmutableShareI +// case (ImmutableShareI, _) => ImmutableShareI +// case other => vimpl(other) +// } + + val resultSubjectiveIT = memberCoordI + val resultIE = + ReferenceMemberLookupIE( + range, + structIE, + RegionCollapserIndividual.collapseVarName(memberName), + RegionCollapserIndividual.collapseCoord(resultSubjectiveIT.coord), + translateVariability(variability)) + (resultSubjectiveIT.coord, resultIE) } - case StaticSizedArrayLookupTE(range, arrayExpr, arrayType, indexExpr, variability) => { - StaticSizedArrayLookupTE( - range, - translateRefExpr(arrayExpr), - translateStaticSizedArray(arrayType), - translateRefExpr(indexExpr), - variability) + case StaticSizedArrayLookupTE(range, arrayExprT, arrayType, indexExprT, elementTypeT, variability) => { + // DO NOT SUBMIT combine a lot of this with the ReferenceMemberLookupTE case + val (arraySubjectiveIT, arrayIE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExprT) +// // We can't translate StaticSizedArrayLookupTE.elementTypeT's kind here because we'll +// // translate its template args' regions incorrectly according to their current mutabilities. +// // They need to be the mutabilities at the time they were introduced, see CTOTFIPB. So +// // instead, we look it up from the struct definition. +// val elementType = +// arraySubjectiveIT.kind match { +// case StaticSizedArrayIT(IdI(_, _, StaticSizedArrayNameI(_, _, _, RawArrayNameI(_, elementType, _)))) => { +// elementType +// } +// } + val elementTypeI = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, elementTypeT).coord + + val (indexIT, indexCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, indexExprT) + +// // However, the resulting coord's region *should* have the current mutability. +// val resultRegion = +// ITemplataI.expectRegionTemplata( +// translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, elementTypeT.region)) + + val resultCoord = CoordI(elementTypeI.ownership, elementTypeI.kind) + + val resultIE = + StaticSizedArrayLookupIE( + range, + arrayIE, + indexCE, + RegionCollapserIndividual.collapseCoord(resultCoord), + translateVariability(variability)) + (resultCoord, resultIE) } case AddressMemberLookupTE(range, structExpr, memberName, resultType2, variability) => { - AddressMemberLookupTE( - range, - translateRefExpr(structExpr), - translateVarName(memberName), - translateCoord(resultType2), - variability) + val (structIT, structCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, structExpr) + val varNameI = translateVarName(memberName) + val resultIT = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, resultType2) + val variabilityI = translateVariability(variability) + + val resultCE = + AddressMemberLookupIE( + structCE, + RegionCollapserIndividual.collapseVarName(varNameI), + RegionCollapserIndividual.collapseCoord(resultIT.coord), + variabilityI) + (resultIT.coord, resultCE) } - case RuntimeSizedArrayLookupTE(range, arrayExpr, arrayType, indexExpr, variability) => { - RuntimeSizedArrayLookupTE( - range, - translateRefExpr(arrayExpr), - translateRuntimeSizedArray(arrayType), - translateRefExpr(indexExpr), - variability) + case RuntimeSizedArrayLookupTE(range, arrayExpr, rsaTT, indexExpr, variability) => { + val (arrayIT, arrayCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + val rsaIT = + translateRuntimeSizedArray( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, rsaTT) + val (indexIT, indexCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, indexExpr) + val variabilityI = translateVariability(variability) + + // We can't just say rsaIT.elementType here because that's the element from the array's own + // perspective. + val elementIT = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, rsaTT.elementType) + + val resultIT = elementIT + val resultCE = + RuntimeSizedArrayLookupIE( + arrayCE, indexCE, RegionCollapserIndividual.collapseCoord(elementIT.coord), variabilityI) + (resultIT.coord, resultCE) } case other => vimpl(other) } } def translateExpr( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + env: NodeEnvironment, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, expr: ExpressionT): - ExpressionT = { + // Returns the subjective coord (see HCCSCS) and the expression. + (CoordI[sI], ExpressionI) = { expr match { - case r : ReferenceExpressionTE => translateRefExpr(r) - case a : AddressExpressionTE => translateAddrExpr(a) + case r : ReferenceExpressionTE => { + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, r) + } + case a : AddressExpressionTE => { + translateAddrExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, a) + } } } def translateRefExpr( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + env: NodeEnvironment, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, expr: ReferenceExpressionTE): - ReferenceExpressionTE = { - val resultRefExpr = + // Returns the subjective coord (see HCCSCS) and the expression. + (CoordI[sI], ReferenceExpressionIE) = { + val denizenTemplateName = TemplataCompiler.getTemplate(denizenName) + val (resultIT, resultCE) = expr match { - case LetNormalTE(variable, inner) => LetNormalTE(translateLocalVariable(variable), translateRefExpr(inner)) - case RestackifyTE(variable, inner) => RestackifyTE(translateLocalVariable(variable), translateRefExpr(inner)) - case BlockTE(inner) => BlockTE(translateRefExpr(inner)) - case ReturnTE(inner) => ReturnTE(translateRefExpr(inner)) - case ConsecutorTE(inners) => ConsecutorTE(inners.map(translateRefExpr)) + case RestackifyTE(variable, inner) => { + val (innerIT, innerIE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, inner) + val (localIT, localI) = + translateLocalVariable( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, variable) + // env.addTranslatedVariable(variableT.name, vimpl(translatedVariable)) + val subjectiveResultIT = CoordI[sI](MutableShareI, VoidIT()) + val exprIE = + RestackifyIE( + localI, innerIE, RegionCollapserIndividual.collapseCoord(subjectiveResultIT)) + (subjectiveResultIT, exprIE) + } + + case LetNormalTE(variableT, innerTE) => { + val (innerIT, innerIE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerTE) + val (localIT, localI) = + translateLocalVariable( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, variableT) +// env.addTranslatedVariable(variableT.name, vimpl(translatedVariable)) + val subjectiveResultIT = CoordI[sI](MutableShareI, VoidIT()) + val exprIE = + LetNormalIE( + localI, innerIE, RegionCollapserIndividual.collapseCoord(subjectiveResultIT)) + (subjectiveResultIT, exprIE) + } + case BlockTE(inner) => { + val (innerIT, innerIE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, inner) + val resultIT = innerIT + val resultIE = BlockIE(innerIE, RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultIE) + } + case ReturnTE(inner) => { + val (innerIT, innerIE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, inner) + val resultIE = ReturnIE(innerIE) + (CoordI[sI](MutableShareI, NeverIT(false)), resultIE) + } + case c @ ConsecutorTE(inners) => { + val resultTT = c.result.coord + val resultIT = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, resultTT) + .coord + val innersIE = + inners.map(innerTE => { + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerTE)._2 + }) + val resultIE = ConsecutorIE(innersIE, RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultIE) + } case ConstantIntTE(value, bits) => { - ConstantIntTE(ITemplataT.expectIntegerTemplata(translateTemplata(value)), bits) + val resultCE = + ConstantIntIE( + ITemplataI.expectIntegerTemplata( + translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, value)).value, + bits) + (CoordI[sI](MutableShareI, IntIT(bits)), resultCE) + } + case ConstantStrTE(value) => { + val resultCE = ConstantStrIE(value) + (CoordI[sI](MutableShareI, StrIT()), resultCE) + } + case ConstantBoolTE(value) => { + val resultCE = ConstantBoolIE(value) + (CoordI[sI](MutableShareI, BoolIT()), resultCE) + } + case ConstantFloatTE(value) => { + val resultCE = ConstantFloatIE(value) + (CoordI[sI](MutableShareI, BoolIT()), resultCE) + } + case UnletTE(variable) => { + val (localIT, localIE) = + translateLocalVariable( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, variable) + val resultIT = localIT +// val local = env.lookupOriginalTranslatedVariable(variable.name) + val resultIE = UnletIE(localIE, RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultIE) + } + case DiscardTE(innerTE) => { + val (innerIT, innerIE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerTE) + val resultIE = DiscardIE(innerIE) + (CoordI[sI](MutableShareI, VoidIT()), resultIE) + } + case VoidLiteralTE() => { + (CoordI[sI](MutableShareI, VoidIT()), VoidLiteralIE()) } - case ConstantStrTE(value) => ConstantStrTE(value) - case ConstantBoolTE(value) => ConstantBoolTE(value) - case ConstantFloatTE(value) => ConstantFloatTE(value) - case UnletTE(variable) => UnletTE(translateLocalVariable(variable)) - case DiscardTE(expr) => DiscardTE(translateRefExpr(expr)) - case VoidLiteralTE() => VoidLiteralTE() case FunctionCallTE(prototypeT, args) => { - val prototype = translatePrototype(prototypeT) - FunctionCallTE( - prototype, - args.map(translateRefExpr)) + val innersIE = + args.map(argTE => { + val (argIT, argCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, argTE) + // if (pure && argIT.ownership == MutableBorrowI) { + // PreCheckBorrowIE(argCE) + // } else { + argCE + // } + }) + + val (prototypeI, prototypeC) = + translatePrototype( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + prototypeT) + val returnCoordIT = prototypeI.returnType + // translateCoord( + // denizenName, + // denizenBoundToDenizenCallerSuppliedThing, + // substitutions, + // perspectiveRegionT, + // returnCoordT) + // .coord + val returnCoordCT = + RegionCollapserIndividual.collapseCoord(returnCoordIT) + val resultIE = FunctionCallIE(prototypeC, innersIE, returnCoordCT) + (returnCoordIT, resultIE) } case InterfaceFunctionCallTE(superFunctionPrototypeT, virtualParamIndex, resultReference, args) => { - val superFunctionPrototype = translatePrototype(superFunctionPrototypeT) - val result = - InterfaceFunctionCallTE( - superFunctionPrototype, + val (superFunctionPrototypeI, superFunctionPrototypeC) = + translatePrototype( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, superFunctionPrototypeT) + val resultIT = superFunctionPrototypeI.returnType + val resultCE = + InterfaceFunctionCallIE( + superFunctionPrototypeC, virtualParamIndex, - translateCoord(resultReference), - args.map(translateRefExpr)) - val interfaceFullName = - superFunctionPrototype.paramTypes(virtualParamIndex).kind.expectInterface().id - // val interfaceFullName = - // translateInterfaceFullName( - // interfaceFullNameT, - // translateBoundArgsForCallee( + args.map(arg => { + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arg)._2 + }), + RegionCollapserIndividual.collapseCoord(resultIT)) + val interfaceIdC = + superFunctionPrototypeC.paramTypes(virtualParamIndex).kind.expectInterface().id + // val interfaceId = + // translateInterfaceId( + // interfaceIdT, + // translateBoundArgsForCallee(denizenName, denizenBoundToDenizenCallerSuppliedThing, // hinputs.getInstantiationBounds(callee.toPrototype.fullName))) val instantiationBoundArgs = - translateBoundArgsForCallee( + translateBoundArgsForCallee(denizenName, denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, // but this is literally calling itself from where its defined // perhaps we want the thing that originally called hinputs.getInstantiationBoundArgs(superFunctionPrototypeT.id)) + val superFunctionPrototypeN = + RegionCollapserConsistent.collapsePrototype( + RegionCounter.countPrototype(superFunctionPrototypeI), + superFunctionPrototypeI) + + vassert(RegionCollapserIndividual.collapsePrototype(superFunctionPrototypeN) == superFunctionPrototypeC) + monouts.newAbstractFuncs.enqueue( - (superFunctionPrototype, virtualParamIndex, interfaceFullName, instantiationBoundArgs)) + (superFunctionPrototypeT, superFunctionPrototypeN, virtualParamIndex, interfaceIdC, instantiationBoundArgs)) - result + (resultIT, resultCE) + } + case ArgLookupTE(paramIndex, reference) => { + val typeI = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, reference) + .coord + val resultCE = ArgLookupIE(paramIndex, RegionCollapserIndividual.collapseCoord(typeI)) + (typeI, resultCE) } - case ArgLookupTE(paramIndex, reference) => ArgLookupTE(paramIndex, translateCoord(reference)) case SoftLoadTE(originalInner, originalTargetOwnership) => { - val inner = translateAddrExpr(originalInner) + val (innerIT, innerIE) = + translateAddrExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, originalInner) val targetOwnership = - (originalTargetOwnership, inner.result.coord.ownership) match { - case (a, b) if a == b => a - case (BorrowT, ShareT) => ShareT - case (BorrowT, WeakT) => WeakT - case (BorrowT, OwnT) => BorrowT - case (WeakT, ShareT) => ShareT - case (WeakT, OwnT) => WeakT - case (WeakT, BorrowT) => WeakT + // First, figure out what ownership it is after substitution. + // if we have an owned T but T is a &Ship, then own + borrow = borrow + (originalTargetOwnership, innerIT.ownership) match { +// case (a, b) if a == b => a + case (ShareT, ImmutableShareI) => ImmutableShareI + case (ShareT, MutableShareI) => MutableShareI + case (BorrowT, ImmutableShareI) => ImmutableShareI + case (BorrowT, MutableShareI) => MutableShareI + case (BorrowT, ImmutableBorrowI) => ImmutableBorrowI + case (BorrowT, MutableBorrowI | OwnI) => { + // if (coordRegionIsMutable(substitutions, perspectiveRegionT, originalInner.result.coord)) { + MutableBorrowI + // } else { + // ImmutableBorrowI + // } + } + case (WeakT, ImmutableShareI) => vregionmut(ImmutableShareI) + case (WeakT, MutableShareI) => vregionmut(MutableShareI) + case (WeakT, OwnI) => vregionmut(WeakI) + case (WeakT, ImmutableBorrowI) => vregionmut(WeakI) + case (WeakT, MutableBorrowI) => vregionmut(WeakI) + case (WeakT, WeakI) => vregionmut(WeakI) case other => vwat(other) } - SoftLoadTE(inner, targetOwnership) + val resultIT = CoordI[sI](targetOwnership, innerIT.kind) + val resultIE = + SoftLoadIE(innerIE, targetOwnership, RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultIE) } case ExternFunctionCallTE(prototype2, args) => { - ExternFunctionCallTE( - translatePrototype(prototype2), - args.map(translateRefExpr)) + val (prototypeI, prototypeC) = + translatePrototype( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, prototype2) + val argsIE = + args.map(argTE => { + translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, argTE)._2 + }) + val resultIT = prototypeI.returnType + val resultIE = ExternFunctionCallIE(prototypeC, argsIE, prototypeC.returnType) + (resultIT, resultIE) } case ConstructTE(structTT, resultReference, args) => { - val coord = translateCoord(resultReference) + val resultIT = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, resultReference) + .coord // val freePrototype = translatePrototype(freePrototypeT) // // They might disagree on the ownership, and thats fine. @@ -1403,36 +2357,119 @@ class Instantiator( // monouts.immKindToDestructor.put(coord.kind, freePrototype) // } - ConstructTE( + val argsIE = + args.map(argTE => { + translateExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, argTE)._2 + }) + + val structIT = translateStruct( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, structTT, translateBoundArgsForCallee( - hinputs.getInstantiationBoundArgs(structTT.id))), - coord, - args.map(translateExpr)) + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + hinputs.getInstantiationBoundArgs(structTT.id))) + + val resultIE = + ConstructIE( + StructIT(RegionCollapserIndividual.collapseStructId(structIT.id)), + RegionCollapserIndividual.collapseCoord(resultIT), + argsIE) + (resultIT, resultIE) } - case DestroyTE(expr, structTT, destinationReferenceVariables) => { - DestroyTE( - translateRefExpr(expr), - translateStruct( - structTT, + case DestroyTE(exprT, structTT, destinationReferenceVariables) => { + val (sourceIT, sourceIE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, exprT) + + val structIT = + translateStructId( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + structTT.id, translateBoundArgsForCallee( - hinputs.getInstantiationBoundArgs(structTT.id))), - destinationReferenceVariables.map(translateReferenceLocalVariable)) + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + hinputs.getInstantiationBoundArgs(structTT.id))) + +// val resultT = +// expr.result.coord.kind match { +// case s @ StructIT(_) => s +// case other => vwat(other) +// } + +// val structDef = vassertSome(monouts.structs.get(resultT.id)) +// vassert(structDef.members.size == destinationReferenceVariables.size) + + val resultIE = + DestroyIE( + sourceIE, + StructIT(RegionCollapserIndividual.collapseStructId(structIT)), + destinationReferenceVariables.map(destRefVarT => { + translateReferenceLocalVariable( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, + perspectiveRegionT, destRefVarT)._2 + })) + (CoordI[sI](MutableShareI, VoidIT()), resultIE) + } + case DestroyStaticSizedArrayIntoLocalsTE(exprT, ssaTT, destinationReferenceVariables) => { + val (sourceIT, sourceIE) = translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, exprT) + val (ssaIT, size) = + sourceIT.kind match { + case s @ StaticSizedArrayIT(IdI(_, _, StaticSizedArrayNameI(_, size, _, _))) => (s, size) + case other => vwat(other) + } + + vassert(size == destinationReferenceVariables.size) + val resultCE = + DestroyStaticSizedArrayIntoLocalsIE( + sourceIE, + RegionCollapserIndividual.collapseStaticSizedArray(ssaIT), + destinationReferenceVariables.map(destRefVarT => { + translateReferenceLocalVariable( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, destRefVarT)._2 + })) + (CoordI[sI](MutableShareI, VoidIT()), resultCE) } - case MutateTE(destinationExpr, sourceExpr) => { - MutateTE( - translateAddrExpr(destinationExpr), - translateRefExpr(sourceExpr)) + case MutateTE(destinationTT, sourceExpr) => { + // DO NOT SUBMIT change all IE to CE like this one + val (destinationIT, destinationCE) = + translateAddrExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, destinationTT) + val (sourceIT, sourceCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, sourceExpr) + val resultIT = destinationIT + val resultCE = MutateIE(destinationCE, sourceCE, RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultCE) } - case u @ UpcastTE(innerExprUnsubstituted, targetSuperKind, untranslatedImplFullName) => { - val implFullName = - translateImplFullName( - untranslatedImplFullName, - translateBoundArgsForCallee( - hinputs.getInstantiationBoundArgs(untranslatedImplFullName))) + case u @ UpcastTE(innerExprUnsubstituted, targetSuperKind, untranslatedImplId) => { + val implId = + translateImplId(denizenName, denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + + untranslatedImplId, + translateBoundArgsForCallee(denizenName, denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + + hinputs.getInstantiationBoundArgs(untranslatedImplId))) // val freePrototype = translatePrototype(freePrototypeT) - val coord = translateCoord(u.result.coord) + val resultIT = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, u.result.coord) // They might disagree on the ownership, and thats fine. // That free prototype is only going to take an owning or a share reference, and we'll only // use it if we have a shared reference so it's all good. @@ -1441,27 +2478,60 @@ class Instantiator( // monouts.immKindToDestructor.put(coord.kind, freePrototypeT) // } - UpcastTE( - translateRefExpr(innerExprUnsubstituted), - translateSuperKind(targetSuperKind), - implFullName)//, - // freePrototype) + val (innerIT, innerCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerExprUnsubstituted) + + val superKindI = + translateSuperKind( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, targetSuperKind) + + val resultCE = + UpcastIE( + innerCE, + InterfaceIT(RegionCollapserIndividual.collapseInterfaceId(superKindI.id)), + RegionCollapserIndividual.collapseImplId(implId), + RegionCollapserIndividual.collapseCoord(resultIT.coord)) + (resultIT.coord, resultCE) } case IfTE(condition, thenCall, elseCall) => { - IfTE( - translateRefExpr(condition), - translateRefExpr(thenCall), - translateRefExpr(elseCall)) + val (conditionIT, conditionCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, condition) + val (thenIT, thenCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, thenCall) + val (elseIT, elseCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, elseCall) + val resultIT = + (thenIT, elseIT) match { + case (a, b) if a == b => a + case (a, CoordI(_, NeverIT(_))) => a + case (CoordI(_, NeverIT(_)), b) => b + case other => vwat(other) + } + + val resultCE = IfIE(conditionCE, thenCE, elseCE, RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultCE) } case IsSameInstanceTE(left, right) => { - IsSameInstanceTE( - translateRefExpr(left), - translateRefExpr(right)) + val (leftIT, leftCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, left) + val (rightIT, rightCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, right) + val resultCE = IsSameInstanceIE(leftCE, rightCE) + (CoordI[sI](MutableShareI, BoolIT()), resultCE) } case StaticArrayFromValuesTE(elements, resultReference, arrayType) => { // val freePrototype = translatePrototype(freePrototypeT) - val coord = translateCoord(resultReference) + val resultIT = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, resultReference) + .coord // They might disagree on the ownership, and thats fine. // That free prototype is only going to take an owning or a share reference, and we'll only // use it if we have a shared reference so it's all good. @@ -1470,81 +2540,192 @@ class Instantiator( // monouts.immKindToDestructor.put(coord.kind, freePrototypeT) // } - StaticArrayFromValuesTE( - elements.map(translateRefExpr), - translateCoord(resultReference), - arrayType) + val elementsCE = + elements.map(elementTE => { + translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, elementTE)._2 + }) + + val ssaTT = + translateStaticSizedArray( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + arrayType) + + val resultCE = + StaticArrayFromValuesIE( + elementsCE, + RegionCollapserIndividual.collapseCoord(resultIT), + RegionCollapserIndividual.collapseStaticSizedArray(ssaTT)) + (resultIT, resultCE) } case DeferTE(innerExpr, deferredExpr) => { - DeferTE( - translateRefExpr(innerExpr), - translateRefExpr(deferredExpr)) + val (innerIT, innerCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerExpr) + val (deferredIT, deferredCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, deferredExpr) + val resultIT = innerIT + val resultCE = + DeferIE(innerCE, deferredCE, RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultCE) } - case LetAndLendTE(variable, sourceExprT, targetOwnership) => { - val sourceExpr = translateRefExpr(sourceExprT) - - val resultOwnership = - (targetOwnership, sourceExpr.result.coord.ownership) match { - case (OwnT, OwnT) => OwnT - case (OwnT, BorrowT) => BorrowT - case (BorrowT, OwnT) => BorrowT - case (BorrowT, BorrowT) => BorrowT - case (BorrowT, WeakT) => WeakT - case (BorrowT, ShareT) => ShareT - case (WeakT, OwnT) => WeakT - case (WeakT, BorrowT) => WeakT - case (WeakT, WeakT) => WeakT - case (WeakT, ShareT) => ShareT - case (ShareT, ShareT) => ShareT - case (OwnT, ShareT) => ShareT - case other => vwat(other) - } - - LetAndLendTE( - translateLocalVariable(variable), - sourceExpr, - resultOwnership) + case LetAndLendTE(variable, sourceExprT, outerOwnershipT) => { + val (sourceSubjectiveIT, sourceIE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, sourceExprT) + + val resultOwnershipI = + translateOwnership( + substitutions, + perspectiveRegionT, + composeOwnerships(outerOwnershipT, sourceSubjectiveIT.ownership), + sourceExprT.result.coord.region) + + val resultIT = CoordI(resultOwnershipI, sourceSubjectiveIT.kind) + + val (localIT, localI) = + translateLocalVariable( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, variable) + + val resultIE = + LetAndLendIE( + localI, + sourceIE, + resultOwnershipI, + RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultIE) } case BorrowToWeakTE(innerExpr) => { - BorrowToWeakTE(translateRefExpr(innerExpr)) + val (innerIT, innerCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerExpr) + + + val resultIT = innerIT.copy(ownership = WeakI) + val resultCT = RegionCollapserIndividual.collapseCoord(resultIT) + + (resultIT, BorrowToWeakIE(innerCE, resultCT)) } case WhileTE(BlockTE(inner)) => { - WhileTE(BlockTE(translateRefExpr(inner))) + val (innerIT, innerCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, inner) + + // While loops must always produce void. + // If we want a foreach/map/whatever construct, the loop should instead + // add things to a list inside; WhileIE shouldnt do it for it. + val resultIT = + innerIT match { + case CoordI(_, VoidIT()) => innerIT + case CoordI(_, NeverIT(true)) => CoordI[sI](MutableShareI, VoidIT()) + case CoordI(_, NeverIT(false)) => innerIT + case _ => vwat() + } + + val resultCE = + WhileIE( + BlockIE(innerCE, RegionCollapserIndividual.collapseCoord(innerIT)), + RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultCE) } - case BreakTE() => BreakTE() - case LockWeakTE(innerExpr, resultOptBorrowType, someConstructor, noneConstructor, someImplUntranslatedFullName, noneImplUntranslatedFullName) => { - LockWeakTE( - translateRefExpr(innerExpr), - translateCoord(resultOptBorrowType), - translatePrototype(someConstructor), - translatePrototype(noneConstructor), - translateImplFullName( - someImplUntranslatedFullName, - translateBoundArgsForCallee( - hinputs.getInstantiationBoundArgs(someImplUntranslatedFullName))), - translateImplFullName( - noneImplUntranslatedFullName, - translateBoundArgsForCallee( - hinputs.getInstantiationBoundArgs(noneImplUntranslatedFullName)))) + case BreakTE() => { + val resultCE = BreakIE() + (CoordI[sI](MutableShareI, NeverIT(true)), resultCE) + } + case LockWeakTE(innerExpr, resultOptBorrowType, someConstructor, noneConstructor, someImplUntranslatedId, noneImplUntranslatedId) => { + val resultIT = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, resultOptBorrowType).coord + val resultCT = RegionCollapserIndividual.collapseCoord(resultIT) + val resultCE = + LockWeakIE( + translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerExpr)._2, + resultCT, + translatePrototype(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, someConstructor)._2, + translatePrototype(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, noneConstructor)._2, + RegionCollapserIndividual.collapseImplId( + translateImplId( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + someImplUntranslatedId, + translateBoundArgsForCallee( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + hinputs.getInstantiationBoundArgs(someImplUntranslatedId)))), + RegionCollapserIndividual.collapseImplId( + translateImplId( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + noneImplUntranslatedId, + translateBoundArgsForCallee( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + hinputs.getInstantiationBoundArgs(noneImplUntranslatedId)))), + resultCT) + (resultIT, resultCE) } case DestroyStaticSizedArrayIntoFunctionTE(arrayExpr, arrayType, consumer, consumerMethod) => { - DestroyStaticSizedArrayIntoFunctionTE( - translateRefExpr(arrayExpr), - translateStaticSizedArray(arrayType), - translateRefExpr(consumer), - translatePrototype(consumerMethod)) + val (arrayIT, arrayCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + val ssaIT = + translateStaticSizedArray( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayType) + val (consumerIT, consumerCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, consumer) + val (consumerPrototypeI, consumerPrototypeC) = + translatePrototype( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, consumerMethod) + val resultCE = + DestroyStaticSizedArrayIntoFunctionIE( + arrayCE, RegionCollapserIndividual.collapseStaticSizedArray(ssaIT), consumerCE, consumerPrototypeC) + (CoordI[sI](MutableShareI, VoidIT()), resultCE) } case NewImmRuntimeSizedArrayTE(arrayType, sizeExpr, generator, generatorMethod) => { // val freePrototype = translatePrototype(freePrototypeT) - val result = - NewImmRuntimeSizedArrayTE( - translateRuntimeSizedArray(arrayType), - translateRefExpr(sizeExpr), - translateRefExpr(generator), - translatePrototype(generatorMethod)) + val rsaIT = + translateRuntimeSizedArray( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayType) + val (sizeIT, sizeCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, sizeExpr) + val (generatorIT, generatorCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, generator) + val (generatorPrototypeI, generatorPrototypeC) = + translatePrototype( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, generatorMethod) + + val resultIT = + CoordI[sI]( + rsaIT.mutability match { + case MutableI => OwnI + case ImmutableI => MutableShareI + }, + rsaIT) + + val resultCE = + NewImmRuntimeSizedArrayIE( + RegionCollapserIndividual.collapseRuntimeSizedArray(rsaIT), + sizeCE, + generatorCE, + generatorPrototypeC, + RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultCE) - val coord = result.result.coord // They might disagree on the ownership, and thats fine. // That free prototype is only going to take an owning or a share reference, and we'll only // use it if we have a shared reference so it's all good. @@ -1553,18 +2734,35 @@ class Instantiator( // monouts.immKindToDestructor.put(coord.kind, freePrototype) // } - result } case StaticArrayFromCallableTE(arrayType, generator, generatorMethod) => { // val freePrototype = translatePrototype(freePrototypeT) - val result = - StaticArrayFromCallableTE( - translateStaticSizedArray(arrayType), - translateRefExpr(generator), - translatePrototype(generatorMethod)) + val ssaIT = + translateStaticSizedArray( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayType) + val (generatorIT, generatorCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, generator) + val (generatorPrototypeI, generatorPrototypeC) = + translatePrototype( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, generatorMethod) + + val resultIT = + CoordI[sI]( + ssaIT.mutability match { + case MutableI => OwnI + case ImmutableI => MutableShareI + }, + ssaIT) + + val resultCE = + StaticArrayFromCallableIE( + RegionCollapserIndividual.collapseStaticSizedArray(ssaIT), + generatorCE, + generatorPrototypeC, + RegionCollapserIndividual.collapseCoord(resultIT)) - val coord = result.result.coord // They might disagree on the ownership, and thats fine. // That free prototype is only going to take an owning or a share reference, and we'll only // use it if we have a shared reference so it's all good. @@ -1573,217 +2771,542 @@ class Instantiator( // monouts.immKindToDestructor.put(coord.kind, freePrototype) // } - result + (resultIT, resultCE) } case RuntimeSizedArrayCapacityTE(arrayExpr) => { - RuntimeSizedArrayCapacityTE(translateRefExpr(arrayExpr)) + val (arrayIT, arrayCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + val resultCE = RuntimeSizedArrayCapacityIE(arrayCE) + (CoordI[sI](MutableShareI, IntIT(32)), resultCE) } case PushRuntimeSizedArrayTE(arrayExpr, newElementExpr) => { - PushRuntimeSizedArrayTE( - translateRefExpr(arrayExpr), - translateRefExpr(newElementExpr)) + val (arrayIT, arrayCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + val (elementIT, elementCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, newElementExpr) + val resultCE = PushRuntimeSizedArrayIE(arrayCE, elementCE) + (CoordI[sI](MutableShareI, VoidIT()), resultCE) } case PopRuntimeSizedArrayTE(arrayExpr) => { - PopRuntimeSizedArrayTE(translateRefExpr(arrayExpr)) + val (arrayIT, arrayCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + val elementIT = + arrayIT.kind match { + case RuntimeSizedArrayIT(IdI(_, _, RuntimeSizedArrayNameI(_, RawArrayNameI(_, elementType, _)))) => { + elementType.coord + } + case other => vwat(other) + } + val resultCE = PopRuntimeSizedArrayIE(arrayCE, RegionCollapserIndividual.collapseCoord(elementIT)) + (elementIT, resultCE) } case ArrayLengthTE(arrayExpr) => { - ArrayLengthTE(translateRefExpr(arrayExpr)) + val (arrayIT, arrayCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + val resultIT = CoordI[sI](MutableShareI, IntIT(32)) + val resultCE = ArrayLengthIE(arrayCE) + (resultIT, resultCE) } case DestroyImmRuntimeSizedArrayTE(arrayExpr, arrayType, consumer, consumerMethod) => { - DestroyImmRuntimeSizedArrayTE( - translateRefExpr(arrayExpr), - translateRuntimeSizedArray(arrayType), - translateRefExpr(consumer), - translatePrototype(consumerMethod)) - // translatePrototype(freePrototype)) + val (arrayIT, arrayCE) = translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + val rsaIT = translateRuntimeSizedArray(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayType) + val (consumerIT, consumerCE) = translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, consumer) + val (prototypeI, prototypeC) = + translatePrototype( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, consumerMethod) + + val resultCE = + DestroyImmRuntimeSizedArrayIE( + arrayCE, + RegionCollapserIndividual.collapseRuntimeSizedArray(rsaIT), + consumerCE, + prototypeC) + (CoordI[sI](MutableShareI, VoidIT()), resultCE) } case DestroyMutRuntimeSizedArrayTE(arrayExpr) => { - DestroyMutRuntimeSizedArrayTE(translateRefExpr(arrayExpr)) + val (arrayIT, arrayIE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + val resultIE = DestroyMutRuntimeSizedArrayIE(arrayIE) + (CoordI.void[sI], resultIE) } - case NewMutRuntimeSizedArrayTE(arrayType, capacityExpr) => { - NewMutRuntimeSizedArrayTE( - translateRuntimeSizedArray(arrayType), - translateRefExpr(capacityExpr)) + case NewMutRuntimeSizedArrayTE(arrayTT, capacityExpr) => { + val arrayIT = + translateRuntimeSizedArray( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayTT) + val resultIT = + CoordI[sI]( + arrayIT.mutability match { + case MutableI => OwnI + case ImmutableI => MutableShareI + }, + arrayIT) + + val (capacityIT, capacityIE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, capacityExpr) + + val resultCE = + NewMutRuntimeSizedArrayIE( + RegionCollapserIndividual.collapseRuntimeSizedArray(arrayIT), + capacityIE, + RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultCE) } case TupleTE(elements, resultReference) => { - TupleTE( - elements.map(translateRefExpr), - translateCoord(resultReference)) + val elementsCE = + elements.map(elementTE => { + translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, elementTE)._2 + }) + + val resultIT = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, resultReference) + .coord + + (resultIT, TupleIE(elementsCE, RegionCollapserIndividual.collapseCoord(resultIT))) } - case AsSubtypeTE(sourceExpr, targetSubtype, resultResultType, okConstructor, errConstructor, implFullNameT, okResultImplFullNameT, errResultImplFullNameT) => { - AsSubtypeTE( - translateRefExpr(sourceExpr), - translateCoord(targetSubtype), - translateCoord(resultResultType), - translatePrototype(okConstructor), - translatePrototype(errConstructor), - translateImplFullName( - implFullNameT, - translateBoundArgsForCallee( - hinputs.getInstantiationBoundArgs(implFullNameT))), - translateImplFullName( - okResultImplFullNameT, - translateBoundArgsForCallee( - hinputs.getInstantiationBoundArgs(okResultImplFullNameT))), - translateImplFullName( - errResultImplFullNameT, - translateBoundArgsForCallee( - hinputs.getInstantiationBoundArgs(errResultImplFullNameT)))) + case AsSubtypeTE(sourceExpr, targetSubtype, resultResultType, okConstructor, errConstructor, implIdT, okResultImplIdT, errResultImplIdT) => { + val (sourceIT, sourceCE) = + translateRefExpr( + denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, sourceExpr) + val resultIT = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + resultResultType).coord + val resultCE = + AsSubtypeIE( + sourceCE, + RegionCollapserIndividual.collapseCoord(translateCoord(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, targetSubtype).coord), + RegionCollapserIndividual.collapseCoord(translateCoord(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, resultResultType).coord), + translatePrototype(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, okConstructor)._2, + translatePrototype(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, errConstructor)._2, + RegionCollapserIndividual.collapseImplId( + translateImplId( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + implIdT, + translateBoundArgsForCallee( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + hinputs.getInstantiationBoundArgs(implIdT)))), + RegionCollapserIndividual.collapseImplId( + translateImplId( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + okResultImplIdT, + translateBoundArgsForCallee( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + hinputs.getInstantiationBoundArgs(okResultImplIdT)))), + RegionCollapserIndividual.collapseImplId( + translateImplId( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + errResultImplIdT, + translateBoundArgsForCallee( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + hinputs.getInstantiationBoundArgs(errResultImplIdT)))), + RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultCE) } case other => vimpl(other) } // if (opts.sanityCheck) { // vassert(Collector.all(resultRefExpr, { case PlaceholderNameT(_) => }).isEmpty) // } - resultRefExpr + (resultIT, resultCE) + } + + private def maybeImmutabilify(innerIE: ReferenceExpressionIE): ReferenceExpressionIE = { + innerIE.result.kind match { + case x if x.isPrimitive => { + return innerIE // These are conceptually moved into the receiver's region + } + case _ => // continue + } + innerIE match { + case SoftLoadIE(expr, MutableBorrowI, result) => { + return SoftLoadIE(expr, ImmutableBorrowI, result.copy(ownership = ImmutableBorrowI)) + } + case SoftLoadIE(expr, MutableShareI, result) => { + return SoftLoadIE(expr, ImmutableShareI, result.copy(ownership = ImmutableShareI)) + } + case _ => //continue + } + innerIE.result.ownership match { + case OwnI => innerIE // These are being moved into the receiver's region + case ImmutableBorrowI | ImmutableShareI => innerIE + case MutableBorrowI => { + ImmutabilifyIE(innerIE, innerIE.result.copy(ownership = ImmutableBorrowI)) + } + case MutableShareI => { + ImmutabilifyIE(innerIE, innerIE.result.copy(ownership = ImmutableShareI)) + } + } + } + + private def runInNewPureRegion[T]( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + env: NodeEnvironment, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + denizenTemplateName: IdT[ITemplateNameT], + newDefaultRegionT: ITemplataT[RegionTemplataType], + run: (Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], GlobalRegionT) => T): + T = { + val newDefaultRegionNameT = GlobalRegionT() + val newPerspectiveRegionT = newDefaultRegionNameT + + val newDefaultRegion = GlobalRegionT() + val oldSubstitutionsForThisDenizenTemplate = + substitutions.getOrElse(denizenTemplateName, Map()) + val newSubstitutionsForThisDenizenTemplate = + oldSubstitutionsForThisDenizenTemplate + val newSubstitutions = + substitutions + (denizenTemplateName -> newSubstitutionsForThisDenizenTemplate) + + run(newSubstitutions, newPerspectiveRegionT) + } + + def translateOwnership( + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + ownershipT: OwnershipT, + regionT: GlobalRegionT): + OwnershipI = { + ownershipT match { // Now if it's a borrow, figure out whether it's mutable or immutable + case OwnT => OwnI + case BorrowT => { + // if (regionIsMutable(substitutions, perspectiveRegionT, expectRegionPlaceholder(regionT))) { + MutableBorrowI + // } else { + // ImmutableBorrowI + // } + } + case ShareT => { + // if (regionIsMutable(substitutions, perspectiveRegionT, expectRegionPlaceholder(regionT))) { + MutableShareI + // } else { + // ImmutableShareI + // } + } + case WeakT => vimpl() + } + } + + def composeOwnerships( + outerOwnership: OwnershipT, + innerOwnership: OwnershipI): + OwnershipT = { + (outerOwnership, innerOwnership) match { + case (OwnT, OwnI) => OwnT + case (OwnT, MutableBorrowI) => BorrowT + case (BorrowT, OwnI) => BorrowT + case (BorrowT, MutableBorrowI) => BorrowT + case (BorrowT, WeakI) => WeakT + case (BorrowT, MutableShareI) => ShareT + case (WeakT, OwnI) => WeakT + case (WeakT, MutableBorrowI) => WeakT + case (WeakT, WeakI) => WeakT + case (WeakT, MutableShareI) => ShareT + case (ShareT, MutableShareI) => ShareT + case (OwnT, MutableShareI) => ShareT + case other => vwat(other) + } } - def translateFunctionFullName( + def translateFunctionId( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, fullNameT: IdT[IFunctionNameT]): - IdT[IFunctionNameT] = { + IdI[sI, IFunctionNameI[sI]] = { val IdT(module, steps, last) = fullNameT val fullName = - IdT( + IdI( module, - steps.map(translateName), - translateFunctionName(last)) + steps.map(translateName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), + translateFunctionName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, last)) // if (opts.sanityCheck) { // vassert(Collector.all(fullName, { case PlaceholderNameT(_) => }).isEmpty) // } fullName } - def translateStructFullName( +// def translateRegionId( +// substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplata[ITemplataType]]], +// perspectiveRegionT: GlobalRegionT, +// fullNameT: IdT[IRegionNameT]//, +// //instantiationBoundArgs: InstantiationBoundArguments +// ): +// IdT[IRegionNameT] = { +// fullNameT match { +// case IdT(packageCoord, initSteps, r @ RegionPlaceholderNameT(_, _, _, _)) => { +// IdT( +// packageCoord, +// initSteps.map(translateName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), +// translateRegionName(substitutions, perspectiveRegionT, r)) +// } +// } +// } + + def translateStructId( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, fullNameT: IdT[IStructNameT], - instantiationBoundArgs: InstantiationBoundArgumentsT): - IdT[IStructNameT] = { + instantiationBoundArgs: InstantiationBoundArgumentsI): + IdI[sI, IStructNameI[sI]] = { val IdT(module, steps, lastT) = fullNameT - val fullName = - IdT( + val fullNameI = + IdI( module, - steps.map(translateName), - translateStructName(lastT)) + steps.map(translateName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), + translateStructName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, lastT)) - Instantiator.translateStructDefinition( - opts, interner, keywords, hinputs, monouts, fullName, instantiationBoundArgs) + collapseAndTranslateStructDefinition( + opts, interner, keywords, hinputs, monouts, fullNameT, fullNameI, instantiationBoundArgs) - return fullName + fullNameI } - def translateInterfaceFullName( + def translateInterfaceId( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, fullNameT: IdT[IInterfaceNameT], - instantiationBoundArgs: InstantiationBoundArgumentsT): - IdT[IInterfaceNameT] = { + instantiationBoundArgs: InstantiationBoundArgumentsI): + IdI[sI, IInterfaceNameI[sI]] = { val IdT(module, steps, last) = fullNameT - val newFullName = - IdT( + val newIdI = + IdI( module, - steps.map(translateName), - translateInterfaceName(last)) + steps.map(translateName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), + translateInterfaceName(denizenName, denizenBoundToDenizenCallerSuppliedThing,substitutions, perspectiveRegionT, last)) - Instantiator.translateInterfaceDefinition( - opts, interner, keywords, hinputs, monouts, newFullName, instantiationBoundArgs) + collapseAndTranslateInterfaceDefinition( + opts, interner, keywords, hinputs, monouts, fullNameT, newIdI, instantiationBoundArgs) - newFullName + newIdI } - def translateCitizenName(t: ICitizenNameT): ICitizenNameT = { - t match { - case s : IStructNameT => translateStructName(s) - case i : IInterfaceNameT => translateInterfaceName(i) - } - } + def translateImplId( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + implIdT: IdT[IImplNameT], + // DO NOT SUBMIT this seems to be redundant with what we do below + instantiationBoundArgs: InstantiationBoundArgumentsI): + IdI[sI, IImplNameI[sI]] = { + val IdT(module, steps, lastT) = implIdT + + // collapseAndTranslateImplDefinition( + // opts, interner, keywords, hinputs, monouts, implIdT, implIdT, instantiationBoundArgs) + + implIdT match { + case IdT(packageCoord, initSteps, name @ ImplBoundNameT(_, _)) => { + val implBoundName = IdT(packageCoord, initSteps, name) + val implIdS = vassertSome(denizenBoundToDenizenCallerSuppliedThing.implBoundToCallerSuppliedBoundArgImpl.get(implBoundName)) - def translateCitizenFullName( - fullName: IdT[ICitizenNameT], - instantiationBoundArgs: InstantiationBoundArgumentsT): - IdT[ICitizenNameT] = { - fullName match { - case IdT(module, steps, last : IStructNameT) => { - translateStructFullName(IdT(module, steps, last), instantiationBoundArgs) + // val implIdC = + // RegionCollapserIndividual.collapseImplId(implIdS) + implIdS } - case IdT(module, steps, last : IInterfaceNameT) => { - translateInterfaceFullName(IdT(module, steps, last), instantiationBoundArgs) + case _ => { + val implIdS = + IdI( + module, + steps.map(translateName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), + translateImplName( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, lastT)) + + val implIdN = + RegionCollapserConsistent.collapseImplId( + RegionCounter.countImplId(implIdS), + implIdS) + + val runeToBoundArgsForNewImpl = + translateBoundArgsForCallee( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + hinputs.getInstantiationBoundArgs(implIdT)) + + monouts.newImpls.enqueue((implIdT, implIdN, runeToBoundArgsForNewImpl)) + + implIdS } - case other => vimpl(other) } } - def translateImplFullName( - fullNameT: IdT[IImplNameT], - instantiationBoundArgs: InstantiationBoundArgumentsT): - IdT[IImplNameT] = { - val IdT(module, steps, last) = fullNameT - val fullName = - IdT( - module, - steps.map(translateName), - translateImplName(last, instantiationBoundArgs)) + def translateCitizenName( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + t: ICitizenNameT): + ICitizenNameI[sI] = { + t match { + case s : IStructNameT => translateStructName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, s) + case i : IInterfaceNameT => translateInterfaceName(denizenName, denizenBoundToDenizenCallerSuppliedThing,substitutions, perspectiveRegionT, i) + } + } + def translateId( + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + id: IdT[INameT]): + IdI[sI, INameI[sI]] = { + id match { + case other => vimpl(other) + } + } - fullNameT match { - case IdT(packageCoord, initSteps, name@ImplBoundNameT(_, _)) => { - val implBoundName = IdT(packageCoord, initSteps, name) - val result = vassertSome(denizenBoundToDenizenCallerSuppliedThing.implBoundToCallerSuppliedBoundArgImpl.get(implBoundName)) - // if (opts.sanityCheck) { - // vassert(Collector.all(result, { case PlaceholderTemplateNameT(_) => }).isEmpty) - // } - result + def translateCitizenId( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + id: IdT[ICitizenNameT], + instantiationBoundArgs: InstantiationBoundArgumentsI): + IdI[sI, ICitizenNameI[sI]] = { + id match { + case IdT(module, steps, last : IStructNameT) => { + translateStructId( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, IdT(module, steps, last), instantiationBoundArgs) } - case IdT(_, _, _) => { - monouts.newImpls.enqueue((fullName, instantiationBoundArgs)) - fullName + case IdT(module, steps, last : IInterfaceNameT) => { + translateInterfaceId( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, IdT(module, steps, last), instantiationBoundArgs) } + case other => vimpl(other) } } - def translateFullName( - fullName: IdT[INameT]): - IdT[INameT] = { - vimpl() - } - def translateCoord( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, coord: CoordT): - CoordT = { - val CoordT(ownership, _, kind) = coord + CoordTemplataI[sI] = { + val CoordT(outerOwnership, outerRegion, kind) = coord + val outerRegionI = GlobalRegionT() + // translateTemplata( + // denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, outerRegion) + // .expectRegionTemplata() + + // strt here, somethings weird. + // // its possible the ownership from the substitution is messing with us. + // // the ownership should + kind match { - case KindPlaceholderT(placeholderFullName) => { + case KindPlaceholderT(placeholderId) => { // Let's get the index'th placeholder from the top level denizen. // If we're compiling a function or a struct, it might actually be a lambda function or lambda struct. // In these cases, the topLevelDenizenPlaceholderIndexToTemplata actually came from the containing function, // see LHPCTLD. - vassertSome(vassertSome(substitutions.get(placeholderFullName.initId(interner))).get(placeholderFullName)) match { - case CoordTemplataT(CoordT(innerOwnership, _, kind)) => { + vassertSome(vassertSome(substitutions.get(placeholderId.initId(interner))).get(placeholderId)) match { + case CoordTemplataI(region, CoordI(innerOwnership, kind)) => { val combinedOwnership = - (ownership, innerOwnership) match { - case (OwnT, OwnT) => OwnT - case (OwnT, BorrowT) => BorrowT - case (BorrowT, OwnT) => BorrowT - case (BorrowT, BorrowT) => BorrowT - case (BorrowT, WeakT) => WeakT - case (BorrowT, ShareT) => ShareT - case (WeakT, OwnT) => WeakT - case (WeakT, BorrowT) => WeakT - case (WeakT, WeakT) => WeakT - case (WeakT, ShareT) => ShareT - case (ShareT, ShareT) => ShareT - case (OwnT, ShareT) => ShareT - case other => vwat(other) + kind match { + case IntIT(_) | BoolIT() | VoidIT() => { + // We don't want any ImmutableShareH for primitives, it's better to only ever have one + // ownership for primitives. + MutableShareI + } + case _ => { + ((outerOwnership, innerOwnership) match { + case (OwnT, OwnI) => OwnI + // case (OwnT, ImmutableShareI) => ImmutableShareI + case (OwnT | BorrowT, MutableShareI | ImmutableShareI) => { + // We disregard whether it's a MutableShareI or ImmutableShareI because + // that was likely calculated under different circumstances from a + // different perspective region. + // We'll recalculate it now with out own perspective region. + // See IPOMFIC. + //if (regionIsMutable(substitutions, perspectiveRegionT, expectRegionPlaceholder(outerRegion))) { + MutableShareI + // } else { + // ImmutableShareI + // } + } + // case (OwnT, BorrowT) => BorrowT + case (OwnT, MutableBorrowI) => { + vregionmut() // here too maybe? + MutableBorrowI + } + // case (BorrowT, OwnT) => BorrowT + case (BorrowT, OwnI) => { + vregionmut() // we'll probably want a regionIsMutable call like above + MutableBorrowI + } + // case (BorrowT, BorrowT) => BorrowT + case (BorrowT, MutableBorrowI) => { + vregionmut() // we'll probably want a regionIsMutable call like above + MutableBorrowI + } + // case (BorrowT, WeakT) => WeakT + // case (BorrowT, ShareT) => ShareT + // case (WeakT, OwnT) => WeakT + case (WeakT, OwnI) => { + vregionmut() // here too maybe? + WeakI + } + // case (WeakT, BorrowT) => WeakT + // case (WeakT, WeakT) => WeakT + // case (WeakT, ShareT) => ShareT + // case (ShareT, ShareT) => ShareT + case (ShareT, MutableShareI) => { + vregionmut() // here too maybe? + MutableShareI + } + // case (OwnT, ShareT) => ShareT + case other => vwat(other) + // DO NOT SUBMIT combine this with what's elsewhere in this file + }) + } } - CoordT(combinedOwnership, GlobalRegionT(), kind) +// vassert(innerRegion == translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, outerRegion)) + CoordTemplataI(RegionTemplataI(0), CoordI(combinedOwnership, kind)) } - case KindTemplataT(kind) => { - val newOwnership = - getMutability(kind) match { - case ImmutableT => ShareT - case MutableT => ownership - } - CoordT(newOwnership, GlobalRegionT(), kind) + case KindTemplataI(kind) => { +// val newOwnership = +// getMutability(kind) match { +// case ImmutableT => ShareT +// case MutableT => outerOwnership +// } + CoordTemplataI(RegionTemplataI(0), CoordI(vimpl(/*newOwnership*/), vimpl(kind))) } } } @@ -1791,172 +3314,343 @@ class Instantiator( // We could, for example, be translating an Vector (which is temporarily regarded mutable) // to an Vector (which is immutable). // So, we have to check for that here and possibly make the ownership share. - val kind = translateKind(other) - val mutability = getMutability(kind) + val kind = translateKind(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, other) val newOwnership = - (ownership, mutability) match { - case (_, ImmutableT) => ShareT - case (other, MutableT) => other + kind match { + case IntIT(_) | BoolIT() | VoidIT() => { + // We don't want any ImmutableShareH for primitives, it's better to only ever have one + // ownership for primitives. + MutableShareI + } + case _ => { + val mutability = getMutability(RegionCollapserIndividual.collapseKind(kind)) + ((outerOwnership, mutability) match { + case (_, ImmutableI) => ShareT + case (other, MutableI) => other + }) match { // Now if it's a borrow, figure out whether it's mutable or immutable + case BorrowT => { + // if (regionIsMutable(substitutions, perspectiveRegionT, expectRegionPlaceholder(outerRegion))) { + MutableBorrowI + // } else { + // ImmutableBorrowI + // } + } + case ShareT => { + // if (regionIsMutable(substitutions, perspectiveRegionT, expectRegionPlaceholder(outerRegion))) { + MutableShareI + // } else { + // ImmutableShareI + // } + } + case OwnT => { + // We don't have this assert because we sometimes can see owning references even + // though we dont hold them, see RMLRMO. + // vassert(regionIsMutable(substitutions, perspectiveRegionT, expectRegionPlaceholder(outerRegion))) + OwnI + } + case WeakT => { + vregionmut(WeakI) + } + } + } } - CoordT(newOwnership, GlobalRegionT(), translateKind(other)) +// val newRegion = expectRegionTemplata(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, outerRegion)) + CoordTemplataI(RegionTemplataI(0), CoordI(newOwnership, kind)) } } } - def getMutability(t: KindT): MutabilityT = { + def getMutability(t: KindIT[cI]): MutabilityI = { t match { - case IntT(_) | BoolT() | StrT() | NeverT(_) | FloatT() | VoidT() => ImmutableT - case StructTT(name) => { - vassertSome(monouts.startedStructs.get(name))._1 + case IntIT(_) | BoolIT() | StrIT() | NeverIT(_) | FloatIT() | VoidIT() => ImmutableI + case StructIT(name) => { + vassertSome(monouts.structToMutability.get(name)) } - case InterfaceTT(name) => { - vassertSome(monouts.startedInterfaces.get(name))._1 + case InterfaceIT(name) => { + vassertSome(monouts.interfaceToMutability.get(name)) } - case RuntimeSizedArrayTT(IdT(_, _, RuntimeSizedArrayNameT(_, RawArrayNameT(mutability, _)))) => { - expectMutabilityTemplata(mutability).mutability + case RuntimeSizedArrayIT(IdI(_, _, RuntimeSizedArrayNameI(_, RawArrayNameI(mutability, _, region)))) => { + mutability } - case StaticSizedArrayTT(IdT(_, _, StaticSizedArrayNameT(_, _, _, RawArrayNameT(mutability, _)))) => { - expectMutabilityTemplata(mutability).mutability + case StaticSizedArrayIT(IdI(_, _, StaticSizedArrayNameI(_, _, _, RawArrayNameI(mutability, _, region)))) => { + mutability } case other => vimpl(other) } } - def translateCitizen(citizen: ICitizenTT, instantiationBoundArgs: InstantiationBoundArgumentsT): ICitizenTT = { + def translateCitizen( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + citizen: ICitizenTT, + instantiationBoundArgs: InstantiationBoundArgumentsI): + ICitizenIT[sI] = { citizen match { - case s @ StructTT(_) => translateStruct(s, instantiationBoundArgs) - case s @ InterfaceTT(_) => translateInterface(s, instantiationBoundArgs) + case s @ StructTT(_) => translateStruct(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, s, instantiationBoundArgs) + case s @ InterfaceTT(_) => translateInterface(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, s, instantiationBoundArgs) } } - def translateStruct(struct: StructTT, instantiationBoundArgs: InstantiationBoundArgumentsT): StructTT = { + def translateStruct( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + struct: StructTT, + instantiationBoundArgs: InstantiationBoundArgumentsI): + StructIT[sI] = { val StructTT(fullName) = struct - val desiredStruct = interner.intern(StructTT(translateStructFullName(fullName, instantiationBoundArgs))) + val desiredStruct = + StructIT( + translateStructId( + denizenName, denizenBoundToDenizenCallerSuppliedThing, + substitutions, perspectiveRegionT, fullName, instantiationBoundArgs)) desiredStruct } - def translateInterface(interface: InterfaceTT, instantiationBoundArgs: InstantiationBoundArgumentsT): InterfaceTT = { + def translateInterface( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + interface: InterfaceTT, + instantiationBoundArgs: InstantiationBoundArgumentsI): + InterfaceIT[sI] = { val InterfaceTT(fullName) = interface - val desiredInterface = interner.intern(InterfaceTT(translateInterfaceFullName(fullName, instantiationBoundArgs))) + val desiredInterface = + InterfaceIT( + translateInterfaceId( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, fullName, instantiationBoundArgs)) desiredInterface } - def translateSuperKind(kind: ISuperKindTT): ISuperKindTT = { + def translateSuperKind( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + kind: ISuperKindTT): + InterfaceIT[sI] = { kind match { case i @ InterfaceTT(_) => { translateInterface( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, i, translateBoundArgsForCallee( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, hinputs.getInstantiationBoundArgs(i.id))) } case p @ KindPlaceholderT(_) => { - translatePlaceholder(p) match { - case s : ISuperKindTT => s + translatePlaceholder(substitutions, p) match { + case s : InterfaceIT[_] => { + vassert(s.isInstanceOf[InterfaceIT[sI]]) + s.asInstanceOf[InterfaceIT[sI]] + } case other => vwat(other) } } } } - def translatePlaceholder(t: KindPlaceholderT): KindT = { + def translatePlaceholder( + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + t: KindPlaceholderT): + KindIT[sI] = { val newSubstitutingTemplata = vassertSome( vassertSome(substitutions.get(t.id.initId(interner))) .get(t.id)) - ITemplataT.expectKindTemplata(newSubstitutingTemplata).kind + ITemplataI.expectKindTemplata(newSubstitutingTemplata).kind } - def translateStaticSizedArray(ssaTT: StaticSizedArrayTT): StaticSizedArrayTT = { + def translateStaticSizedArray( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + ssaTT: StaticSizedArrayTT): + StaticSizedArrayIT[sI] = { val StaticSizedArrayTT( IdT( packageCoord, initSteps, - StaticSizedArrayNameT(template, size, variability, RawArrayNameT(mutability, elementType)))) = ssaTT - - interner.intern(StaticSizedArrayTT( - IdT( + StaticSizedArrayNameT(StaticSizedArrayTemplateNameT(), sizeT, variabilityT, RawArrayNameT(mutabilityT, elementTypeT)))) = ssaTT + + val newPerspectiveRegionT = GlobalRegionT() + // ssaRegionT match { + // case PlaceholderTemplataT(IdT(packageCoord, initSteps, r @ RegionPlaceholderNameT(_, _, _, _)), RegionTemplataType()) => { + // IdT(packageCoord, initSteps, r) + // } + // case _ => vwat() + // } + + // We use newPerspectiveRegionT for these because of TTTDRM. + val ssaRegion = GlobalRegionT() + // We dont have this assert because this might be a templata deep in a struct or function's + // name, so the heights might actually be negative. + // vassert(Some(ssaRegion.pureHeight) == newPerspectiveRegionT.localName.pureHeight) + val intTemplata = ITemplataI.expectIntegerTemplata(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, newPerspectiveRegionT, sizeT)).value + val variabilityTemplata = ITemplataI.expectVariabilityTemplata(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, newPerspectiveRegionT, variabilityT)).variability + val mutabilityTemplata = + ITemplataI.expectMutabilityTemplata( + translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, newPerspectiveRegionT, mutabilityT)).mutability + val elementType = + translateCoord(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, newPerspectiveRegionT, elementTypeT) + + StaticSizedArrayIT( + IdI( packageCoord, - initSteps, - interner.intern(StaticSizedArrayNameT( - template, - expectIntegerTemplata(translateTemplata(size)), - expectVariabilityTemplata(translateTemplata(variability)), - interner.intern(RawArrayNameT( - expectMutabilityTemplata(translateTemplata(mutability)), - translateCoord(elementType)))))))) + initSteps.map(translateName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), + StaticSizedArrayNameI( + StaticSizedArrayTemplateNameI(), + intTemplata, + variabilityTemplata, + RawArrayNameI( + mutabilityTemplata, + elementType, + RegionTemplataI(0))))) } - def translateRuntimeSizedArray(ssaTT: RuntimeSizedArrayTT): RuntimeSizedArrayTT = { + def translateRuntimeSizedArray( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + rsaTT: RuntimeSizedArrayTT): + RuntimeSizedArrayIT[sI] = { val RuntimeSizedArrayTT( - IdT( - packageCoord, - initSteps, - RuntimeSizedArrayNameT(template, RawArrayNameT(mutability, elementType)))) = ssaTT - - interner.intern(RuntimeSizedArrayTT( IdT( + packageCoord, + initSteps, + RuntimeSizedArrayNameT(RuntimeSizedArrayTemplateNameT(), RawArrayNameT(mutabilityT, elementTypeT)))) = rsaTT + + val newPerspectiveRegionT = GlobalRegionT() + // rsaRegionT match { + // case PlaceholderTemplataT(IdT(packageCoord, initSteps, r @ RegionPlaceholderNameT(_, _, _, _)), RegionTemplataType()) => { + // IdT(packageCoord, initSteps, r) + // } + // case _ => vwat() + // } + + // We use newPerspectiveRegionT for these because of TTTDRM. + val rsaRegion = GlobalRegionT() + // We dont have this assert because this might be a templata deep in a struct or function's + // name, so the heights might actually be negative. + // vassert(Some(ssaRegion.pureHeight) == newPerspectiveRegionT.localName.pureHeight) + val mutabilityTemplata = + ITemplataI.expectMutabilityTemplata( + translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, newPerspectiveRegionT, mutabilityT)).mutability + val elementType = translateCoord(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, newPerspectiveRegionT, elementTypeT) + + RuntimeSizedArrayIT( + IdI( packageCoord, - initSteps, - interner.intern(RuntimeSizedArrayNameT( - template, - interner.intern(RawArrayNameT( - expectMutabilityTemplata(translateTemplata(mutability)), - translateCoord(elementType)))))))) + initSteps.map(translateName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), + RuntimeSizedArrayNameI( + RuntimeSizedArrayTemplateNameI(), + RawArrayNameI( + mutabilityTemplata, + elementType, + RegionTemplataI(0))))) } - def translateKind(kind: KindT): KindT = { + def translateKind( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + kind: KindT): + KindIT[sI] = { kind match { - case IntT(bits) => IntT(bits) - case BoolT() => BoolT() - case FloatT() => FloatT() - case VoidT() => VoidT() - case StrT() => StrT() - case NeverT(fromBreak) => NeverT(fromBreak) - case p @ KindPlaceholderT(_) => translatePlaceholder(p) + case IntT(bits) => IntIT(bits) + case BoolT() => BoolIT() + case FloatT() => FloatIT() + case VoidT() => VoidIT() + case StrT() => StrIT() + case NeverT(fromBreak) => NeverIT(fromBreak) + case p @ KindPlaceholderT(_) => translatePlaceholder(substitutions, p) case s @ StructTT(_) => { translateStruct( - s, translateBoundArgsForCallee(hinputs.getInstantiationBoundArgs(s.id))) + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + s, + translateBoundArgsForCallee(denizenName, denizenBoundToDenizenCallerSuppliedThing, + substitutions, perspectiveRegionT, hinputs.getInstantiationBoundArgs(s.id))) } case s @ InterfaceTT(_) => { translateInterface( - s, translateBoundArgsForCallee(hinputs.getInstantiationBoundArgs(s.id))) + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + s, + translateBoundArgsForCallee( + denizenName, denizenBoundToDenizenCallerSuppliedThing, + substitutions, perspectiveRegionT, hinputs.getInstantiationBoundArgs(s.id))) } - case a @ contentsStaticSizedArrayTT(_, _, _, _) => translateStaticSizedArray(a) - case a @ contentsRuntimeSizedArrayTT(_, _) => translateRuntimeSizedArray(a) + case a @ contentsStaticSizedArrayTT(_, _, _, _) => translateStaticSizedArray(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, a) + case a @ contentsRuntimeSizedArrayTT(_, _) => translateRuntimeSizedArray(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, a) case other => vimpl(other) } } def translateParameter( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, param: ParameterT): - ParameterT = { + ParameterI = { val ParameterT(name, virtuality, preChecked, tyype) = param - ParameterT( - translateVarName(name), - virtuality, + val typeIT = + translateCoord( + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, tyype) + .coord + val nameI = translateVarName(name) + ParameterI( + RegionCollapserIndividual.collapseVarName(nameI), + virtuality.map({ case AbstractT() => AbstractI() }), preChecked, - translateCoord(tyype)) + RegionCollapserIndividual.collapseCoord(typeIT)) } def translateTemplata( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, templata: ITemplataT[ITemplataType]): - ITemplataT[ITemplataType] = { + ITemplataI[sI] = { val result = templata match { - case PlaceholderTemplataT(n, _) => { - vassertSome(vassertSome(substitutions.get(n.initId(interner))).get(n)) + case PlaceholderTemplataT(n, tyype) => { + val substitution = + vassertSome(vassertSome(substitutions.get(n.initId(interner))).get(n)) + substitution + } + case IntegerTemplataT(value) => IntegerTemplataI[sI](value) + case BooleanTemplataT(value) => BooleanTemplataI[sI](value) + case StringTemplataT(value) => StringTemplataI[sI](value) + case CoordTemplataT(coord) => { + translateCoord(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, coord) } - case IntegerTemplataT(value) => IntegerTemplataT(value) - case BooleanTemplataT(value) => BooleanTemplataT(value) - case StringTemplataT(value) => StringTemplataT(value) - case CoordTemplataT(coord) => CoordTemplataT(translateCoord(coord)) - case MutabilityTemplataT(mutability) => MutabilityTemplataT(mutability) - case VariabilityTemplataT(variability) => VariabilityTemplataT(variability) - case KindTemplataT(kind) => KindTemplataT(translateKind(kind)) + case MutabilityTemplataT(mutability) => MutabilityTemplataI[sI](translateMutability(mutability)) + case VariabilityTemplataT(variability) => VariabilityTemplataI[sI](translateVariability(variability)) + case KindTemplataT(kind) => KindTemplataI[sI](translateKind(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, kind)) case other => vimpl(other) } if (opts.sanityCheck) { @@ -1967,137 +3661,194 @@ class Instantiator( def translateVarName( name: IVarNameT): - IVarNameT = { + IVarNameI[sI] = { name match { - case TypingPassFunctionResultVarNameT() => name - case CodeVarNameT(_) => name - case ClosureParamNameT(_) => name - case TypingPassBlockResultVarNameT(life) => name - case TypingPassTemporaryVarNameT(life) => name - case ConstructingMemberNameT(_) => name - case IterableNameT(range) => name - case IteratorNameT(range) => name - case IterationOptionNameT(range) => name - case MagicParamNameT(codeLocation2) => name - case SelfNameT() => name + case TypingPassFunctionResultVarNameT() => TypingPassFunctionResultVarNameI() + case CodeVarNameT(x) => CodeVarNameI(x) + case ClosureParamNameT(x) => ClosureParamNameI(x) + case TypingPassBlockResultVarNameT(LocationInFunctionEnvironmentT(path)) => TypingPassBlockResultVarNameI(LocationInFunctionEnvironmentI(path)) + case TypingPassTemporaryVarNameT(LocationInFunctionEnvironmentT(path)) => TypingPassTemporaryVarNameI(LocationInFunctionEnvironmentI(path)) + case ConstructingMemberNameT(x) => ConstructingMemberNameI(x) + case IterableNameT(range) => IterableNameI(range) + case IteratorNameT(range) => IteratorNameI(range) + case IterationOptionNameT(range) => IterationOptionNameI(range) + case MagicParamNameT(codeLocation2) => MagicParamNameI(codeLocation2) + case SelfNameT() => SelfNameI() + case other => vimpl(other) + } + } + + def translateFunctionTemplateName(name: IFunctionTemplateNameT): IFunctionTemplateNameI[sI] = { + name match { + case FunctionTemplateNameT(humanName, codeLocation) => FunctionTemplateNameI(humanName, codeLocation) case other => vimpl(other) } } def translateFunctionName( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, name: IFunctionNameT): - IFunctionNameT = { + IFunctionNameI[sI] = { name match { case FunctionNameT(FunctionTemplateNameT(humanName, codeLoc), templateArgs, params) => { - interner.intern(FunctionNameT( - interner.intern(FunctionTemplateNameT(humanName, codeLoc)), - templateArgs.map(translateTemplata), - params.map(translateCoord))) + FunctionNameIX( + FunctionTemplateNameI(humanName, codeLoc), + templateArgs.map(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), + params.map(translateCoord(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _).coord)) } case ForwarderFunctionNameT(ForwarderFunctionTemplateNameT(innerTemplate, index), inner) => { - interner.intern(ForwarderFunctionNameT( - interner.intern(ForwarderFunctionTemplateNameT( - // We dont translate these, as these are what uniquely identify generics, and we need that - // information later to map this back to its originating generic. - // See DMPOGN for a more detailed explanation. This oddity is really tricky. - innerTemplate, - index)), - translateFunctionName(inner))) + ForwarderFunctionNameI( + ForwarderFunctionTemplateNameI( + translateFunctionTemplateName(innerTemplate), + index), + translateFunctionName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, inner)) } case ExternFunctionNameT(humanName, parameters) => { - interner.intern(ExternFunctionNameT(humanName, parameters.map(translateCoord))) + ExternFunctionNameI( + humanName, parameters.map(translateCoord(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _).coord)) } case FunctionBoundNameT(FunctionBoundTemplateNameT(humanName, codeLocation), templateArgs, params) => { - interner.intern(FunctionBoundNameT( - interner.intern(FunctionBoundTemplateNameT(humanName, codeLocation)), - templateArgs.map(translateTemplata), - params.map(translateCoord))) + FunctionBoundNameI( + FunctionBoundTemplateNameI(humanName, codeLocation), + templateArgs.map(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), + params.map(translateCoord(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _).coord)) } case AnonymousSubstructConstructorNameT(template, templateArgs, params) => { - interner.intern(AnonymousSubstructConstructorNameT( - translateName(template) match { - case x @ AnonymousSubstructConstructorTemplateNameT(_) => x + AnonymousSubstructConstructorNameI( + translateName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, template) match { + case x @ AnonymousSubstructConstructorTemplateNameI(_) => x case other => vwat(other) }, - templateArgs.map(translateTemplata), - params.map(translateCoord))) + templateArgs.map(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), + params.map(translateCoord(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _).coord)) } case LambdaCallFunctionNameT(LambdaCallFunctionTemplateNameT(codeLocation, paramTypesForGeneric), templateArgs, paramTypes) => { - interner.intern(LambdaCallFunctionNameT( - interner.intern(LambdaCallFunctionTemplateNameT( + LambdaCallFunctionNameI( + LambdaCallFunctionTemplateNameI( codeLocation, // We dont translate these, as these are what uniquely identify generics, and we need that // information later to map this back to its originating generic. // See DMPOGN for a more detailed explanation. This oddity is really tricky. - paramTypesForGeneric)), - templateArgs.map(translateTemplata), - paramTypes.map(translateCoord))) + paramTypesForGeneric), + templateArgs.map(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), + paramTypes.map(translateCoord(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _).coord)) } case other => vimpl(other) } } def translateImplName( - name: IImplNameT, - instantiationBoundArgs: InstantiationBoundArgumentsT): - IImplNameT = { + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, + name: IImplNameT): + IImplNameI[sI] = { name match { case ImplNameT(ImplTemplateNameT(codeLocationS), templateArgs, subCitizen) => { - interner.intern(ImplNameT( - interner.intern(ImplTemplateNameT(codeLocationS)), - templateArgs.map(translateTemplata), - translateCitizen( + ImplNameI( + ImplTemplateNameI(codeLocationS), + templateArgs.map(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), + translateCitizen(denizenName, denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, subCitizen, - hinputs.getInstantiationBoundArgs(subCitizen.id)))) + translateBoundArgsForCallee( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + hinputs.getInstantiationBoundArgs(subCitizen.id)))) } case ImplBoundNameT(ImplBoundTemplateNameT(codeLocationS), templateArgs) => { - interner.intern(ImplBoundNameT( - interner.intern(ImplBoundTemplateNameT(codeLocationS)), - templateArgs.map(translateTemplata))) + ImplBoundNameI( + ImplBoundTemplateNameI(codeLocationS), + templateArgs.map(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _))) } case AnonymousSubstructImplNameT(AnonymousSubstructImplTemplateNameT(interface), templateArgs, subCitizen) => { - interner.intern(AnonymousSubstructImplNameT( - interner.intern(AnonymousSubstructImplTemplateNameT( - // We dont translate these, as these are what uniquely identify generics, and we need that - // information later to map this back to its originating generic. - // See DMPOGN for a more detailed explanation. This oddity is really tricky. - interface)), - templateArgs.map(translateTemplata), + AnonymousSubstructImplNameI( + AnonymousSubstructImplTemplateNameI( + translateInterfaceTemplateName(interface)), + templateArgs.map(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), translateCitizen( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, subCitizen, - hinputs.getInstantiationBoundArgs(subCitizen.id)))) + translateBoundArgsForCallee( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, + substitutions, + perspectiveRegionT, + hinputs.getInstantiationBoundArgs(subCitizen.id)))) } } } +// def translateRegionName( +// substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplata[ITemplataType]]], +// perspectiveRegionT: GlobalRegionT, +// name: IRegionNameT): +// IRegionNameT = { +// name match { +// case RegionPlaceholderNameT(index, rune, originallyIntroducedLocation, originallyMutable) => { +// +// } +// } +// } + def translateStructName( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + // See TTTDRM, this is the region from which we're determining other regions' mutabilities. + perspectiveRegionT: GlobalRegionT, name: IStructNameT): - IStructNameT = { + IStructNameI[sI] = { + val newPerspectiveRegionT = GlobalRegionT() + // vassertSome(name.templateArgs.lastOption) match { + // case PlaceholderTemplataT(IdT(packageCoord, initSteps, r @ RegionPlaceholderNameT(_, _, _, _)), RegionTemplataType()) => { + // IdT(packageCoord, initSteps, r) + // } + // case _ => vwat() + // } name match { case StructNameT(StructTemplateNameT(humanName), templateArgs) => { - interner.intern(StructNameT( - interner.intern(StructTemplateNameT(humanName)), - templateArgs.map(translateTemplata))) + StructNameI( + StructTemplateNameI(humanName), + // We use newPerspectiveRegionT here because of TTTDRM. + templateArgs.map(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, newPerspectiveRegionT, _))) } case AnonymousSubstructNameT(AnonymousSubstructTemplateNameT(interface), templateArgs) => { - interner.intern(AnonymousSubstructNameT( - interner.intern(AnonymousSubstructTemplateNameT( - translateInterfaceTemplateName(interface))), - templateArgs.map(translateTemplata))) + AnonymousSubstructNameI( + AnonymousSubstructTemplateNameI( + translateInterfaceTemplateName(interface)), + // We use newPerspectiveRegionT here because of TTTDRM. + templateArgs.map(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, newPerspectiveRegionT, _))) + } + case LambdaCitizenNameT(LambdaCitizenTemplateNameT(codeLocation)) => { + LambdaCitizenNameI(LambdaCitizenTemplateNameI(codeLocation)) } - case LambdaCitizenNameT(LambdaCitizenTemplateNameT(codeLocation)) => name case other => vimpl(other) } } def translateInterfaceName( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, name: IInterfaceNameT): - IInterfaceNameT = { + IInterfaceNameI[sI] = { name match { case InterfaceNameT(InterfaceTemplateNameT(humanName), templateArgs) => { - interner.intern(InterfaceNameT( - interner.intern(InterfaceTemplateNameT(humanName)), - templateArgs.map(translateTemplata))) + InterfaceNameI( + InterfaceTemplateNameI(humanName), + templateArgs.map(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _))) } case other => vimpl(other) } @@ -2105,82 +3856,119 @@ class Instantiator( def translateInterfaceTemplateName( name: IInterfaceTemplateNameT): - IInterfaceTemplateNameT = { + IInterfaceTemplateNameI[sI] = { name match { - case InterfaceTemplateNameT(humanName) => name + case InterfaceTemplateNameT(humanName) => InterfaceTemplateNameI(humanName) case other => vimpl(other) } } def translateName( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + perspectiveRegionT: GlobalRegionT, name: INameT): - INameT = { + INameI[sI] = { name match { case v : IVarNameT => translateVarName(v) case KindPlaceholderTemplateNameT(index, _) => vwat() case KindPlaceholderNameT(inner) => vwat() case StructNameT(StructTemplateNameT(humanName), templateArgs) => { - interner.intern(StructNameT( - interner.intern(StructTemplateNameT(humanName)), - templateArgs.map(translateTemplata))) + StructNameI( + StructTemplateNameI(humanName), + templateArgs.map(translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _))) } case ForwarderFunctionTemplateNameT(inner, index) => { - interner.intern(ForwarderFunctionTemplateNameT( - // We dont translate these, as these are what uniquely identify generics, and we need that - // information later to map this back to its originating generic. - // See DMPOGN for a more detailed explanation. This oddity is really tricky. - inner, - index)) + ForwarderFunctionTemplateNameI( + translateFunctionTemplateName(inner), + index) } case AnonymousSubstructConstructorTemplateNameT(substructTemplateName) => { - interner.intern(AnonymousSubstructConstructorTemplateNameT( - translateName(substructTemplateName) match { - case x : ICitizenTemplateNameT => x + AnonymousSubstructConstructorTemplateNameI( + translateName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, substructTemplateName) match { + case x : ICitizenTemplateNameI[sI] => x case other => vwat(other) - })) + }) } - case FunctionTemplateNameT(humanName, codeLoc) => name - case StructTemplateNameT(humanName) => name - case LambdaCitizenTemplateNameT(codeLoc) => name + case FunctionTemplateNameT(humanName, codeLoc) => FunctionTemplateNameI(humanName, codeLoc) + case StructTemplateNameT(humanName) => StructTemplateNameI(humanName) + case LambdaCitizenTemplateNameT(codeLoc) => LambdaCitizenTemplateNameI(codeLoc) case AnonymousSubstructTemplateNameT(interface) => { - interner.intern(AnonymousSubstructTemplateNameT( - translateInterfaceTemplateName(interface))) + AnonymousSubstructTemplateNameI( + translateInterfaceTemplateName(interface)) + } + case LambdaCitizenNameT(LambdaCitizenTemplateNameT(codeLocation)) => { + LambdaCitizenNameI(LambdaCitizenTemplateNameI(codeLocation)) } - case LambdaCitizenNameT(LambdaCitizenTemplateNameT(codeLocation)) => name - case InterfaceTemplateNameT(humanNamee) => name + case InterfaceTemplateNameT(humanNamee) => InterfaceTemplateNameI(humanNamee) // case FreeTemplateNameT(codeLoc) => name - case f : IFunctionNameT => translateFunctionName(f) + case f : IFunctionNameT => translateFunctionName(denizenName, denizenBoundToDenizenCallerSuppliedThing,substitutions, perspectiveRegionT, f) case other => vimpl(other) } } - def translateImplDefinition( - implFullName: IdT[IImplNameT], + def translateCollapsedImplDefinition( + denizenName: IdT[IInstantiationNameT], + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], + implIdT: IdT[IImplNameT], + implIdS: IdI[sI, IImplNameI[sI]], + implIdC: IdI[cI, IImplNameI[cI]], implDefinition: EdgeT): Unit = { - if (monouts.impls.contains(implFullName)) { - return + val EdgeT(_, subCitizen, superInterface, runeToFuncBound, runeToImplBound, abstractFuncToOverrideFunc) = implDefinition + + if (opts.sanityCheck) { + vassert(Collector.all(implIdS, { case KindPlaceholderNameT(_) => }).isEmpty) } - val citizen = + val perspectiveRegionT = GlobalRegionT() + // structDefT.instantiatedCitizen.id.localName.templateArgs.last match { + // case PlaceholderTemplataT(IdT(packageCoord, initSteps, r @ RegionPlaceholderNameT(_, _, _, _)), RegionTemplataType()) => { + // IdT(packageCoord, initSteps, r) + // } + // case _ => vwat() + // } + + val subCitizenI = translateCitizen( + denizenName, denizenBoundToDenizenCallerSuppliedThing, + substitutions, + GlobalRegionT(), implDefinition.subCitizen, - translateBoundArgsForCallee(hinputs.getInstantiationBoundArgs(implDefinition.subCitizen.id))) - val superInterface = - translateInterfaceFullName( + translateBoundArgsForCallee(denizenName, denizenBoundToDenizenCallerSuppliedThing, + substitutions, + GlobalRegionT(), + hinputs.getInstantiationBoundArgs(implDefinition.subCitizen.id))) + val subCitizenC = + RegionCollapserIndividual.collapseCitizen(subCitizenI) + val superInterfaceI = + translateInterfaceId( + denizenName, denizenBoundToDenizenCallerSuppliedThing, + substitutions, + GlobalRegionT(), implDefinition.superInterface, - translateBoundArgsForCallee(hinputs.getInstantiationBoundArgs(implDefinition.superInterface))) - monouts.impls.put(implFullName, (citizen, superInterface, denizenBoundToDenizenCallerSuppliedThing, this)) + translateBoundArgsForCallee(denizenName, denizenBoundToDenizenCallerSuppliedThing, + substitutions, + GlobalRegionT(), + hinputs.getInstantiationBoundArgs(implDefinition.superInterface))) + val superInterfaceC = + RegionCollapserIndividual.collapseInterfaceId(superInterfaceI) + + val mutability = vassertSome(monouts.interfaceToMutability.get(superInterfaceC)) + if (monouts.implToMutability.contains(implIdC)) { + return + } + monouts.implToMutability.put(implIdC, mutability) - vassertSome(monouts.interfaceToImplToAbstractPrototypeToOverride.get(superInterface)) - .put(implFullName, mutable.HashMap()) - vassertSome(monouts.interfaceToImpls.get(superInterface)).add(implFullName) + // We assemble the EdgeI at the very end of the instantiating stage. - vassertSome(monouts.interfaceToAbstractFuncToVirtualIndex.get(superInterface)) - .foreach({ case (abstractFuncPrototype, virtualIndex) => - Instantiator.translateOverride( - opts, interner, keywords, hinputs, monouts, implFullName, abstractFuncPrototype) - }) + monouts.impls.put(implIdC, (subCitizenC, superInterfaceC, denizenBoundToDenizenCallerSuppliedThing)) + + vassertSome(monouts.interfaceToImplToAbstractPrototypeToOverride.get(superInterfaceC)) + .put(implIdC, mutable.HashMap()) + vassertSome(monouts.interfaceToImpls.get(superInterfaceC)).add((implIdT, implIdC)) } } diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/RegionCollapserConsistent.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/RegionCollapserConsistent.scala new file mode 100644 index 000000000..1c37b573d --- /dev/null +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/RegionCollapserConsistent.scala @@ -0,0 +1,411 @@ +package dev.vale.instantiating + +import dev.vale.instantiating.ast._ +import dev.vale.{vassertSome, vimpl} + +// See ICRHRC for why/when we count the regions. +// This one will use one map for the entire deep collapse, rather than making a new map for everything. +object RegionCollapserConsistent { + + def collapsePrototype(map: Map[Int, Int], prototype: PrototypeI[sI]): PrototypeI[nI] = { + val PrototypeI(id, returnType) = prototype + PrototypeI( + collapseFunctionId(map, id), + collapseCoord(map, returnType)) + } + + def collapseId[T <: INameI[sI], Y <: INameI[nI]]( + map: Map[Int, Int], + id: IdI[sI, T], + func: T => Y): + IdI[nI, Y] = { + val IdI(packageCoord, initSteps, localName) = id + IdI( + packageCoord, + initSteps.map(x => collapseName(map, x)), + func(localName)) + } + + def collapseFunctionId( + map: Map[Int, Int], + id: IdI[sI, IFunctionNameI[sI]]): + IdI[nI, IFunctionNameI[nI]] = { + collapseId[IFunctionNameI[sI], IFunctionNameI[nI]]( + map, + id, + x => collapseFunctionName(map, x)) + } + + def collapseFunctionName( + map: Map[Int, Int], + name: IFunctionNameI[sI]): + IFunctionNameI[nI] = { + name match { + case n @ FunctionNameIX(FunctionTemplateNameI(humanName, codeLocation), templateArgs, parameters) => { + val templateC = FunctionTemplateNameI[nI](humanName, codeLocation) + val templateArgsC = templateArgs.map(collapseTemplata(map, _)) + val paramsC = + parameters.map(param => { + collapseCoord(map, param) + }) + FunctionNameIX[nI](templateC, templateArgsC, paramsC) + } + case ExternFunctionNameI(humanName, parameters) => { + val paramsC = + parameters.map(param => { + collapseCoord(map, param) + }) + ExternFunctionNameI[nI](humanName, paramsC) + } + case LambdaCallFunctionNameI(LambdaCallFunctionTemplateNameI(codeLocation, paramsTT), templateArgs, parameters) => { + val templateC = LambdaCallFunctionTemplateNameI[nI](codeLocation, paramsTT) + val templateArgsC = templateArgs.map(collapseTemplata(map, _)) + val paramsC = + parameters.map(param => { + collapseCoord(map, param) + }) + LambdaCallFunctionNameI[nI](templateC, templateArgsC, paramsC) + } + case AnonymousSubstructConstructorNameI(AnonymousSubstructConstructorTemplateNameI(substruct), templateArgs, parameters) => { + val templateC = AnonymousSubstructConstructorTemplateNameI[nI](collapseCitizenTemplateName(substruct)) + val templateArgsC = templateArgs.map(collapseTemplata(map, _)) + val paramsC = + parameters.map(param => { + collapseCoord(map, param) + }) + AnonymousSubstructConstructorNameI[nI](templateC, templateArgsC, paramsC) + } + case ForwarderFunctionNameI(ForwarderFunctionTemplateNameI(funcTemplateName, index), funcName) => { + ForwarderFunctionNameI( + ForwarderFunctionTemplateNameI(collapseFunctionTemplateName(funcTemplateName), index), + collapseFunctionName(map, funcName)) + } + } + } + + def collapseVarName( + name: IVarNameI[sI]): + IVarNameI[sI] = { + name match { + case TypingPassBlockResultVarNameI(life) => TypingPassBlockResultVarNameI(life) + case CodeVarNameI(name) => CodeVarNameI(name) + case TypingPassTemporaryVarNameI(life) => TypingPassTemporaryVarNameI(life) + case TypingPassFunctionResultVarNameI() => TypingPassFunctionResultVarNameI() + } + } + + def collapseName( + map: Map[Int, Int], + name: INameI[sI]): + INameI[nI] = { + name match { + case s: IStructTemplateNameI[_] => { + collapseStructTemplateName(s.asInstanceOf[IStructTemplateNameI[sI]]) + } + case s: IInterfaceTemplateNameI[_] => { + collapseInterfaceTemplateName(s.asInstanceOf[IInterfaceTemplateNameI[sI]]) + } + case s: IFunctionTemplateNameI[_] => { + collapseFunctionTemplateName(s.asInstanceOf[IFunctionTemplateNameI[sI]]) + } + case n @ FunctionNameIX(_, _, _) => { + collapseFunctionName(map, n) + } + case n @ LambdaCallFunctionNameI(_, _, _) => collapseFunctionName(map, n) + case other => vimpl(other) + } + } + + def collapseCoordTemplata( + map: Map[Int, Int], + templata: CoordTemplataI[sI]): + CoordTemplataI[nI] = { + val CoordTemplataI(region, coord) = templata + CoordTemplataI(collapseRegionTemplata(map, region), collapseCoord(map, coord)) + } + + def collapseTemplata( + map: Map[Int, Int], + templata: ITemplataI[sI]): + ITemplataI[nI] = { + templata match { + case c @ CoordTemplataI(_, _) => collapseCoordTemplata(map, c) + case KindTemplataI(kind) => KindTemplataI(collapseKind(map, kind)) + case r @ RegionTemplataI(_) => collapseRegionTemplata(map, r) + case MutabilityTemplataI(mutability) => MutabilityTemplataI(mutability) + case IntegerTemplataI(x) => IntegerTemplataI(x) + case VariabilityTemplataI(variability) => VariabilityTemplataI(variability) + case other => vimpl(other) + } + } + + def collapseRegionTemplata( + map: Map[Int, Int], + templata: RegionTemplataI[sI]): + RegionTemplataI[nI] = { + val RegionTemplataI(oldPureHeight) = templata + RegionTemplataI[nI](vassertSome(map.get(oldPureHeight))) + } + + def collapseCoord( + map: Map[Int, Int], + coord: CoordI[sI]): + CoordI[nI] = { + val CoordI(ownership, kind) = coord + CoordI(ownership, collapseKind(map, kind)) + } + + def collapseKind( + map: Map[Int, Int], + kind: KindIT[sI]): + KindIT[nI] = { + kind match { + case NeverIT(fromBreak) => NeverIT(fromBreak) + case VoidIT() => VoidIT() + case IntIT(x) => IntIT(x) + case BoolIT() => BoolIT() + case FloatIT() => FloatIT() + case StrIT() => StrIT() + case StructIT(id) => StructIT(collapseStructId(map, id)) + case InterfaceIT(id) => InterfaceIT(collapseInterfaceId(map, id)) + case ssa @ StaticSizedArrayIT(_) => collapseStaticSizedArray(map, ssa) + case rsa @ RuntimeSizedArrayIT(_) => collapseRuntimeSizedArray(map, rsa) + } + } + + def collapseRuntimeSizedArray( + map: Map[Int, Int], + rsa: RuntimeSizedArrayIT[sI]): + RuntimeSizedArrayIT[nI] = { + val RuntimeSizedArrayIT(ssaId) = rsa + RuntimeSizedArrayIT( + collapseId[RuntimeSizedArrayNameI[sI], RuntimeSizedArrayNameI[nI]]( + map, + ssaId, + { case RuntimeSizedArrayNameI(RuntimeSizedArrayTemplateNameI(), RawArrayNameI(mutability, elementType, selfRegion)) => + RuntimeSizedArrayNameI( + RuntimeSizedArrayTemplateNameI(), + RawArrayNameI( + mutability, + collapseTemplata(map, elementType).expectCoordTemplata(), + collapseRegionTemplata(map, selfRegion))) + })) + } + + def collapseStaticSizedArray( + map: Map[Int, Int], + ssa: StaticSizedArrayIT[sI]): + StaticSizedArrayIT[nI] = { + val StaticSizedArrayIT(ssaId) = ssa + StaticSizedArrayIT( + collapseId[StaticSizedArrayNameI[sI], StaticSizedArrayNameI[nI]]( + map, + ssaId, + { case StaticSizedArrayNameI(StaticSizedArrayTemplateNameI(), size, variability, RawArrayNameI(mutability, elementType, selfRegion)) => + StaticSizedArrayNameI( + StaticSizedArrayTemplateNameI(), + size, + variability, + RawArrayNameI( + mutability, + collapseTemplata(map, elementType).expectCoordTemplata(), + collapseRegionTemplata(map, selfRegion))) + })) + } + + def collapseCitizen( + map: Map[Int, Int], + citizen: ICitizenIT[sI]): + ICitizenIT[nI] = { + citizen match { + case StructIT(structId) => StructIT(collapseStructId(map, structId)) + case InterfaceIT(structId) => InterfaceIT(collapseInterfaceId(map, structId)) + } + } + + def collapseCitizenId( + map: Map[Int, Int], + implId: IdI[sI, ICitizenNameI[sI]]): + IdI[nI, ICitizenNameI[nI]] = { + collapseId[ICitizenNameI[sI], ICitizenNameI[nI]]( + map, + implId, + collapseCitizenName(map, _)) + } + + def collapseCitizenName( + map: Map[Int, Int], + citizenName: ICitizenNameI[sI]): + ICitizenNameI[nI] = { + citizenName match { + case s: IStructNameI[_] => collapseStructName(map, s.asInstanceOf[IStructNameI[sI]]) + case i: IInterfaceNameI[_] => collapseInterfaceName(map, i.asInstanceOf[IInterfaceNameI[sI]]) + } + } + + def collapseStructName( + map: Map[Int, Int], + structName: IStructNameI[sI]): + IStructNameI[nI] = { + structName match { + case StructNameI(template, templateArgs) => { + StructNameI( + collapseStructTemplateName(template), + templateArgs.map(collapseTemplata(map, _))) + } + case LambdaCitizenNameI(LambdaCitizenTemplateNameI(codeLocation)) => { + LambdaCitizenNameI(LambdaCitizenTemplateNameI(codeLocation)) + } + case AnonymousSubstructNameI(AnonymousSubstructTemplateNameI(interface), templateArgs) => { + AnonymousSubstructNameI( + AnonymousSubstructTemplateNameI(collapseInterfaceTemplateName(interface)), + templateArgs.map(collapseTemplata(map, _))) + } + } + } + + def collapseStructId( + map: Map[Int, Int], + structId: IdI[sI, IStructNameI[sI]]): + IdI[nI, IStructNameI[nI]] = { + collapseId[IStructNameI[sI], IStructNameI[nI]]( + map, + structId, + collapseStructName(map, _)) + } + + def collapseInterfaceName( + map: Map[Int, Int], + interfaceName: IInterfaceNameI[sI]): + IInterfaceNameI[nI] = { + interfaceName match { + case InterfaceNameI(template, templateArgs) => { + InterfaceNameI( + collapseInterfaceTemplateName(template), + templateArgs.map(collapseTemplata(map, _))) + } + } + } + + def collapseInterfaceId( + map: Map[Int, Int], + interfaceId: IdI[sI, IInterfaceNameI[sI]]): + IdI[nI, IInterfaceNameI[nI]] = { + collapseId[IInterfaceNameI[sI], IInterfaceNameI[nI]]( + map, + interfaceId, + collapseInterfaceName(map, _)) + } + + def collapseExportId( + map: Map[Int, Int], + structId: IdI[sI, ExportNameI[sI]]): + IdI[nI, ExportNameI[nI]] = { + collapseId[ExportNameI[sI], ExportNameI[nI]]( + map, + structId, + { case ExportNameI(ExportTemplateNameI(codeLoc), templateArg) => + ExportNameI( + ExportTemplateNameI(codeLoc), + collapseRegionTemplata(map, templateArg)) + }) + } + + def collapseExternId( + map: Map[Int, Int], + structId: IdI[sI, ExternNameI[sI]]): + IdI[nI, ExternNameI[nI]] = { + collapseId[ExternNameI[sI], ExternNameI[nI]]( + map, + structId, + { case ExternNameI(ExternTemplateNameI(codeLoc), templateArg) => + ExternNameI( + ExternTemplateNameI(codeLoc), + collapseRegionTemplata(map, templateArg)) + }) + } + + def collapseCitizenTemplateName( + citizenName: ICitizenTemplateNameI[sI]): + ICitizenTemplateNameI[nI] = { + citizenName match { + case s : IStructTemplateNameI[_] => { + collapseStructTemplateName(s.asInstanceOf[IStructTemplateNameI[nI]]) + } + case s: IInterfaceTemplateNameI[_] => { + collapseInterfaceTemplateName(s.asInstanceOf[IInterfaceTemplateNameI[nI]]) + } + } + } + + def collapseStructTemplateName( + structName: IStructTemplateNameI[sI]): + IStructTemplateNameI[nI] = { + structName match { + case StructTemplateNameI(humanName) => StructTemplateNameI(humanName) + case AnonymousSubstructTemplateNameI(interface) => AnonymousSubstructTemplateNameI(collapseInterfaceTemplateName(interface)) + case LambdaCitizenTemplateNameI(codeLocation) => LambdaCitizenTemplateNameI(codeLocation) + } + } + + def collapseFunctionTemplateName( + structName: IFunctionTemplateNameI[sI]): + IFunctionTemplateNameI[nI] = { + structName match { + case FunctionTemplateNameI(humanName, codeLocation) => FunctionTemplateNameI(humanName, codeLocation) + } + } + + def collapseInterfaceTemplateName( + structName: IInterfaceTemplateNameI[sI]): + IInterfaceTemplateNameI[nI] = { + structName match { + case InterfaceTemplateNameI(humanName) => InterfaceTemplateNameI(humanName) + } + } + + def collapseImplName( + map: Map[Int, Int], + name: IImplNameI[sI]): + IImplNameI[nI] = { + name match { + case ImplNameI(template, templateArgs, subCitizen) => { + ImplNameI( + collapseImplTemplateName(map, template), + templateArgs.map(collapseTemplata(map, _)), + collapseCitizen(map, subCitizen)) + } + case AnonymousSubstructImplNameI(AnonymousSubstructImplTemplateNameI(interface), templateArgs, subCitizen) => { + AnonymousSubstructImplNameI( + AnonymousSubstructImplTemplateNameI(collapseInterfaceTemplateName(interface)), + templateArgs.map(collapseTemplata(map, _)), + collapseCitizen(map, subCitizen)) + } + case ImplBoundNameI(ImplBoundTemplateNameI(codeLocationS), templateArgs) => { + ImplBoundNameI( + ImplBoundTemplateNameI(codeLocationS), + templateArgs.map(collapseTemplata(map, _))) + } + } + } + + def collapseImplId( + map: Map[Int, Int], + structId: IdI[sI, IImplNameI[sI]]): + IdI[nI, IImplNameI[nI]] = { + collapseId[IImplNameI[sI], IImplNameI[nI]]( + map, + structId, + collapseImplName(map, _)) + } + + def collapseImplTemplateName( + map: Map[Int, Int], + structName: IImplTemplateNameI[sI]): + IImplTemplateNameI[nI] = { + structName match { + case ImplTemplateNameI(humanName) => ImplTemplateNameI(humanName) + } + } + +} diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/RegionCollapserIndividual.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/RegionCollapserIndividual.scala new file mode 100644 index 000000000..236b655e2 --- /dev/null +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/RegionCollapserIndividual.scala @@ -0,0 +1,383 @@ +package dev.vale.instantiating + +import dev.vale.instantiating.ast._ +import dev.vale.{vassertSome, vimpl, vwat} + +import scala.collection.immutable.Map + +// See ICRHRC for why/when we count the regions. +// This one will collapse every node based on only the things it contains. +// It creates a new collapsing map for each one. +object RegionCollapserIndividual { + def collapsePrototype(prototype: PrototypeI[sI]): PrototypeI[cI] = { + val PrototypeI(id, returnType) = prototype + PrototypeI( + collapseFunctionId(id), + collapseCoord(returnType)) + } + + def collapseId[T <: INameI[sI], Y <: INameI[cI]]( + id: IdI[sI, T], + func: T => Y): + IdI[cI, Y] = { + val IdI(packageCoord, initSteps, localName) = id + IdI( + packageCoord, + initSteps.map(x => collapseName(x)), + func(localName)) + } + + def collapseFunctionId( + id: IdI[sI, IFunctionNameI[sI]]): + IdI[cI, IFunctionNameI[cI]] = { + collapseId[IFunctionNameI[sI], IFunctionNameI[cI]]( + id, + x => collapseFunctionName(x)) + } + + def collapseFunctionName( + name: IFunctionNameI[sI]): + IFunctionNameI[cI] = { + name match { + case n @ FunctionNameIX(FunctionTemplateNameI(humanName, codeLocation), templateArgs, parameters) => { + val map = RegionCounter.countFunctionName(n) + val templateC = FunctionTemplateNameI[cI](humanName, codeLocation) + val templateArgsC = templateArgs.map(collapseTemplata(map, _)) + val paramsC = + parameters.map(param => { + collapseCoord(param) + }) + FunctionNameIX[cI](templateC, templateArgsC, paramsC) + } + case ExternFunctionNameI(humanName, parameters) => { + val paramsC = + parameters.map(param => { + collapseCoord(param) + }) + ExternFunctionNameI[cI](humanName, paramsC) + } + case n @ LambdaCallFunctionNameI(LambdaCallFunctionTemplateNameI(codeLocation, paramsTT), templateArgs, parameters) => { + val map = RegionCounter.countFunctionName(n) + val templateC = LambdaCallFunctionTemplateNameI[cI](codeLocation, paramsTT) + val templateArgsC = templateArgs.map(collapseTemplata(map, _)) + val paramsC = + parameters.map(param => { + collapseCoord(param) + }) + LambdaCallFunctionNameI[cI](templateC, templateArgsC, paramsC) + } + case n @ AnonymousSubstructConstructorNameI(AnonymousSubstructConstructorTemplateNameI(substruct), templateArgs, parameters) => { + val map = RegionCounter.countFunctionName(n) + val templateC = AnonymousSubstructConstructorTemplateNameI[cI](collapseCitizenTemplateName(substruct)) + val templateArgsC = templateArgs.map(collapseTemplata(map, _)) + val paramsC = + parameters.map(param => { + collapseCoord(param) + }) + AnonymousSubstructConstructorNameI[cI](templateC, templateArgsC, paramsC) + } + case ForwarderFunctionNameI(ForwarderFunctionTemplateNameI(innerTemplate, index), funcName) => { + ForwarderFunctionNameI( + ForwarderFunctionTemplateNameI(collapseFunctionTemplateName(innerTemplate), index), + collapseFunctionName(funcName)) + } + case other => vimpl(other) + } + } + + def collapseCitizenTemplateName(citizen: ICitizenTemplateNameI[sI]): ICitizenTemplateNameI[cI] = { + citizen match { + case s : IStructTemplateNameI[_] => { + collapseStructTemplateName(s.asInstanceOf[IStructTemplateNameI[sI]]) + } + case i : IInterfaceTemplateNameI[_] => { + collapseInterfaceTemplateName(i.asInstanceOf[IInterfaceTemplateNameI[sI]]) + } + case other => vimpl(other) + } + } + + def collapseVarName( + name: IVarNameI[sI]): + IVarNameI[cI] = { + name match { + case TypingPassBlockResultVarNameI(life) => TypingPassBlockResultVarNameI(life) + case CodeVarNameI(name) => CodeVarNameI(name) + case TypingPassTemporaryVarNameI(life) => TypingPassTemporaryVarNameI(life) + case TypingPassFunctionResultVarNameI() => TypingPassFunctionResultVarNameI() + case ClosureParamNameI(codeLocation) => ClosureParamNameI(codeLocation) + case MagicParamNameI(codeLocation2) => MagicParamNameI(codeLocation2) + case IterableNameI(range) => IterableNameI(range) + case ConstructingMemberNameI(name) => ConstructingMemberNameI(name) + case IteratorNameI(range) => IteratorNameI(range) + case IterationOptionNameI(range) => IterationOptionNameI(range) + case SelfNameI() => SelfNameI() + } + } + + def collapseFunctionTemplateName( + functionName: IFunctionTemplateNameI[sI]): + IFunctionTemplateNameI[cI] = { + functionName match { + case FunctionTemplateNameI(humanName, codeLocation) => FunctionTemplateNameI(humanName, codeLocation) + } + } + + def collapseName( + name: INameI[sI]): + INameI[cI] = { + name match { + case n @ FunctionNameIX(_, _, _) => collapseFunctionName(n) + case x : IFunctionTemplateNameI[_] => collapseFunctionTemplateName(x.asInstanceOf[IFunctionTemplateNameI[sI]]) + case StructTemplateNameI(humanName) => StructTemplateNameI(humanName) + case x @ LambdaCitizenNameI(_) => collapseStructName(x) + case LambdaCitizenTemplateNameI(codeLocation) => LambdaCitizenTemplateNameI(codeLocation) + case n @ LambdaCallFunctionNameI(LambdaCallFunctionTemplateNameI(codeLocation, paramTypes), templateArgs, parameters) => collapseFunctionName(n) + case InterfaceTemplateNameI(humanName) => InterfaceTemplateNameI(humanName) + case AnonymousSubstructTemplateNameI(interface) => AnonymousSubstructTemplateNameI(collapseInterfaceTemplateName(interface)) + case other => vimpl(other) + } + } + + def collapseCoordTemplata( + map: Map[Int, Int], + templata: CoordTemplataI[sI]): + CoordTemplataI[cI] = { + val CoordTemplataI(region, coord) = templata + CoordTemplataI(collapseRegionTemplata(map, region), collapseCoord(coord)) + } + + def collapseTemplata( + map: Map[Int, Int], + templata: ITemplataI[sI]): + ITemplataI[cI] = { + templata match { + case c @ CoordTemplataI(_, _) => collapseCoordTemplata(map, c) + case KindTemplataI(kind) => KindTemplataI(collapseKind(kind)) + case r @ RegionTemplataI(_) => collapseRegionTemplata(map, r) + case MutabilityTemplataI(mutability) => MutabilityTemplataI(mutability) + case IntegerTemplataI(x) => IntegerTemplataI(x) + case VariabilityTemplataI(variability) => VariabilityTemplataI(variability) + case other => vimpl(other) + } + } + + def collapseRegionTemplata( + map: Map[Int, Int], + templata: RegionTemplataI[sI]): + RegionTemplataI[cI] = { + val RegionTemplataI(oldPureHeight) = templata + RegionTemplataI[cI](vassertSome(map.get(oldPureHeight))) + } + + def collapseCoord( + coord: CoordI[sI]): + CoordI[cI] = { + val CoordI(ownership, kind) = coord + CoordI(ownership, collapseKind(kind)) + } + + def collapseKind( + kind: KindIT[sI]): + KindIT[cI] = { + kind match { + case NeverIT(fromBreak) => NeverIT(fromBreak) + case VoidIT() => VoidIT() + case IntIT(x) => IntIT(x) + case BoolIT() => BoolIT() + case FloatIT() => FloatIT() + case StrIT() => StrIT() + case StructIT(id) => StructIT(collapseStructId(id)) + case InterfaceIT(id) => InterfaceIT(collapseInterfaceId(id)) + case ssa @ StaticSizedArrayIT(_) => collapseStaticSizedArray(ssa) + case rsa @ RuntimeSizedArrayIT(_) => collapseRuntimeSizedArray(rsa) + } + } + + def collapseRuntimeSizedArray( + rsa: RuntimeSizedArrayIT[sI]): + RuntimeSizedArrayIT[cI] = { + val RuntimeSizedArrayIT(rsaId) = rsa + val map = RegionCounter.countRuntimeSizedArray(rsa) + RuntimeSizedArrayIT( + collapseId[RuntimeSizedArrayNameI[sI], RuntimeSizedArrayNameI[cI]]( + rsaId, + { case RuntimeSizedArrayNameI(RuntimeSizedArrayTemplateNameI(), RawArrayNameI(mutability, elementType, selfRegion)) => + RuntimeSizedArrayNameI( + RuntimeSizedArrayTemplateNameI(), + RawArrayNameI( + mutability, + collapseTemplata(map, elementType).expectCoordTemplata(), + collapseRegionTemplata(map, selfRegion))) + })) + } + + def collapseStaticSizedArray( + ssa: StaticSizedArrayIT[sI]): + StaticSizedArrayIT[cI] = { + val StaticSizedArrayIT(ssaId) = ssa + val map = RegionCounter.countStaticSizedArray(ssa) + StaticSizedArrayIT( + collapseId[StaticSizedArrayNameI[sI], StaticSizedArrayNameI[cI]]( + ssaId, + { case StaticSizedArrayNameI(StaticSizedArrayTemplateNameI(), size, variability, RawArrayNameI(mutability, elementType, selfRegion)) => + StaticSizedArrayNameI( + StaticSizedArrayTemplateNameI(), + size, + variability, + RawArrayNameI( + mutability, + collapseTemplata(map, elementType).expectCoordTemplata(), + collapseRegionTemplata(map, selfRegion))) + })) + } + + def collapseInterfaceId( + interfaceId: IdI[sI, IInterfaceNameI[sI]]): + IdI[cI, IInterfaceNameI[cI]] = { + collapseId[IInterfaceNameI[sI], IInterfaceNameI[cI]]( + interfaceId, + x => collapseInterfaceName(x)) + } + + def collapseStructId( + structId: IdI[sI, IStructNameI[sI]]): + IdI[cI, IStructNameI[cI]] = { + collapseId[IStructNameI[sI], IStructNameI[cI]]( + structId, + x => collapseStructName(x)) + } + + def collapseStructName( + structName: IStructNameI[sI]): + IStructNameI[cI] = { + structName match { + case StructNameI(template, templateArgs) => { + val map = RegionCounter.countCitizenName(structName) + StructNameI( + collapseStructTemplateName(template), + templateArgs.map(collapseTemplata(map, _))) + } + case LambdaCitizenNameI(LambdaCitizenTemplateNameI(codeLocation)) => { + LambdaCitizenNameI(LambdaCitizenTemplateNameI(codeLocation)) + } + case AnonymousSubstructNameI(AnonymousSubstructTemplateNameI(interface), templateArgs) => { + val map = RegionCounter.countCitizenName(structName) + AnonymousSubstructNameI( + AnonymousSubstructTemplateNameI(collapseInterfaceTemplateName(interface)), + templateArgs.map(collapseTemplata(map, _))) + } + } + } + + def collapseImplName( + implName: IImplNameI[sI]): + IImplNameI[cI] = { + implName match { + case ImplNameI(template, templateArgs, subCitizen) => { + val map = RegionCounter.countImplName(implName) + ImplNameI[cI]( + collapseImplTemplateName(map, template), + templateArgs.map(collapseTemplata(map, _)), + collapseCitizen(subCitizen)) + } + case ImplBoundNameI(ImplBoundTemplateNameI(codeLocationS), templateArgs) => { + val map = RegionCounter.countImplName(implName) + ImplBoundNameI( + ImplBoundTemplateNameI(codeLocationS), + templateArgs.map(collapseTemplata(map, _))) + } + case AnonymousSubstructImplNameI(AnonymousSubstructImplTemplateNameI(interface), templateArgs, subCitizen) => { + val map = RegionCounter.countImplName(implName) + AnonymousSubstructImplNameI[cI]( + AnonymousSubstructImplTemplateNameI(collapseInterfaceTemplateName(interface)), + templateArgs.map(collapseTemplata(map, _)), + collapseCitizen(subCitizen)) + } + } + } + + def collapseInterfaceName( + interfaceName: IInterfaceNameI[sI]): + IInterfaceNameI[cI] = { + interfaceName match { + case InterfaceNameI(InterfaceTemplateNameI(humanNamee), templateArgs) => { + val map = RegionCounter.countCitizenName(interfaceName) + InterfaceNameI( + InterfaceTemplateNameI(humanNamee), + templateArgs.map(collapseTemplata(map, _))) + } + case other => vimpl(other) + } + } + + def collapseExportId( + map: Map[Int, Int], + structId: IdI[sI, ExportNameI[sI]]): + IdI[cI, ExportNameI[cI]] = { + collapseId[ExportNameI[sI], ExportNameI[cI]]( + structId, + { case ExportNameI(ExportTemplateNameI(codeLoc), templateArg) => + ExportNameI( + ExportTemplateNameI(codeLoc), + collapseRegionTemplata(map, templateArg)) + }) + } + + def collapseExternId( + map: Map[Int, Int], + structId: IdI[sI, ExternNameI[sI]]): + IdI[cI, ExternNameI[cI]] = { + collapseId[ExternNameI[sI], ExternNameI[cI]]( + structId, + { case ExternNameI(ExternTemplateNameI(codeLoc), templateArg) => + ExternNameI( + ExternTemplateNameI(codeLoc), + collapseRegionTemplata(map, templateArg)) + }) + } + + def collapseStructTemplateName( + structName: IStructTemplateNameI[sI]): + IStructTemplateNameI[cI] = { + structName match { + case StructTemplateNameI(humanName) => StructTemplateNameI(humanName) + case AnonymousSubstructTemplateNameI(interface) => AnonymousSubstructTemplateNameI(collapseInterfaceTemplateName(interface)) + } + } + + def collapseInterfaceTemplateName( + structName: IInterfaceTemplateNameI[sI]): + IInterfaceTemplateNameI[cI] = { + structName match { + case InterfaceTemplateNameI(humanName) => InterfaceTemplateNameI(humanName) + } + } + + def collapseImplId( + implId: IdI[sI, IImplNameI[sI]]): + IdI[cI, IImplNameI[cI]] = { + collapseId[IImplNameI[sI], IImplNameI[cI]]( + implId, + x => collapseImplName(x)) + } + + def collapseImplTemplateName( + map: Map[Int, Int], + structName: IImplTemplateNameI[sI]): + IImplTemplateNameI[cI] = { + structName match { + case ImplTemplateNameI(humanName) => ImplTemplateNameI(humanName) + } + } + + def collapseCitizen( + citizen: ICitizenIT[sI]): + ICitizenIT[cI] = { + citizen match { + case StructIT(structIdT) => StructIT(collapseStructId(structIdT)) + case InterfaceIT(interfaceIdT) => InterfaceIT(collapseInterfaceId(interfaceIdT)) + } + } + +} diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/RegionCounter.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/RegionCounter.scala new file mode 100644 index 000000000..13acc0b1b --- /dev/null +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/RegionCounter.scala @@ -0,0 +1,470 @@ +package dev.vale.instantiating + +import dev.vale.instantiating.RegionCounter._ +import dev.vale.instantiating.ast._ +import dev.vale.{U, vassert, vimpl, vwat} + +import scala.collection.mutable + +object RegionCounter { + class Counter { + // TODO(optimize): Use an array for this, with a minimum index and maximum index (similar to + // what a circular queue uses) + val set: mutable.HashSet[Int] = mutable.HashSet[Int]() + + def count(region: RegionTemplataI[sI]): Unit = { + set.add(region.pureHeight) + } + + def assembleMap(): Map[Int, Int] = { + val numRegions = set.size + // Let's say we have a set that contains 3, 5, -2, 0, 4, it becomes... + set.toVector + .sorted // -2, 0, 3, 4, 5 + .zipWithIndex // (-2, 0), (0, 1), (3, 2), (4, 3), (5, 4) + .map({ case (subjectiveRegion, i) => + // If we have 4 regions, then they should go from -3 to 0 + subjectiveRegion -> (i - numRegions + 1) + }) // (-2, -4), (0, -3), (3, -2), (4, -1), (5, 0) + .toMap + } + +// def assembleMap(counter: Counter): Vector[Int] = { +// var numRegions = 0 +// U.foreach(counts.toVector, (hasRegion: Boolean) => { +// if (hasRegion) { +// numRegions = numRegions + 1 +// } +// }) +// // If we have 4 regions, then they should go from -3 to 0 +// var nextRegion = -numRegions + 1 +// U.mapWithIndex(counts.toVector, (i, hasRegion: Boolean) => { +// if (hasRegion) { +// val region = nextRegion +// nextRegion = nextRegion + 1 +// region +// } else { +// Int.MaxValue +// } +// }) +// } + + // private def count(counter: Counter, region: RegionTemplataI[sI]): Unit = { +// while (region.pureHeight >= counts.size) { +// counts += false +// } +// counts(region.pureHeight) = true +// } + + } + + def countPrototype(counter: Counter, prototype: PrototypeI[sI]): Unit = { + val PrototypeI(id, returnType) = prototype + countFunctionId(counter, id) + countCoord(counter, returnType) + } + + def countId[T <: INameI[sI]]( + counter: Counter, + id: IdI[sI, T], + func: T => Unit): + Unit = { + val IdI(packageCoord, initSteps, localName) = id + initSteps.foreach(x => countName(counter, x)) + func(localName) + } + + def countFunctionId( + counter: Counter, + id: IdI[sI, IFunctionNameI[sI]]): + Unit = { + countId[IFunctionNameI[sI]]( + counter: Counter, + id, + x => countFunctionName(counter, x)) + } + + def countFunctionName( + counter: Counter, + name: IFunctionNameI[sI]): + Unit = { + name match { + case FunctionNameIX(FunctionTemplateNameI(humanName, codeLocation), templateArgs, parameters) => { + templateArgs.foreach(countTemplata(counter, _)) + parameters.foreach(countCoord(counter, _)) + } + case ExternFunctionNameI(humanName, parameters) => { + parameters.foreach(countCoord(counter, _)) + } + case LambdaCallFunctionNameI(LambdaCallFunctionTemplateNameI(codeLoc, paramsTT), templateArgs, parameters) => { + templateArgs.foreach(countTemplata(counter, _)) + parameters.foreach(countCoord(counter, _)) + } + case AnonymousSubstructConstructorNameI(AnonymousSubstructConstructorTemplateNameI(substruct), templateArgs, parameters) => { + countName(counter, substruct) + templateArgs.foreach(countTemplata(counter, _)) + parameters.foreach(countCoord(counter, _)) + } + case ForwarderFunctionNameI(ForwarderFunctionTemplateNameI(funcTemplateName, index), funcName) => { + countName(counter, funcTemplateName) + countFunctionName(counter, funcName) + } + } + } + + def countCitizenName( + counter: Counter, + name: ICitizenNameI[sI]): + Unit = { + name match { + case StructNameI(StructTemplateNameI(humanName), templateArgs) => { + templateArgs.foreach(countTemplata(counter, _)) + } + case LambdaCitizenNameI(template) => { + } + case InterfaceNameI(InterfaceTemplateNameI(humanName), templateArgs) => { + templateArgs.foreach(countTemplata(counter, _)) + } + case AnonymousSubstructNameI(AnonymousSubstructTemplateNameI(interface), templateArgs) => { + countName(counter, interface) + templateArgs.foreach(countTemplata(counter, _)) + } + } + } + + def countVarName( + counter: Counter, + name: IVarNameI[sI]): + Unit = { + name match { + case CodeVarNameI(name) => + case TypingPassBlockResultVarNameI(life) => + case TypingPassTemporaryVarNameI(life) => + case TypingPassFunctionResultVarNameI() => + } + } + + def countName( + counter: Counter, + name: INameI[sI]): + Unit = { + name match { + case z : IFunctionNameI[_] => { + // Scala can't seem to match generics. + val x = z.asInstanceOf[IFunctionNameI[sI]] + countFunctionName(counter, x) + } + case ExportNameI(template, region) => { + counter.count(region) + } + case ExternNameI(template, region) => { + counter.count(region) + } + case c : ICitizenNameI[_] => { + // Scala can't seem to match generics. + val x = c.asInstanceOf[ICitizenNameI[sI]] + countCitizenName(counter, x) + } + case StructNameI(template, templateArgs) => { + templateArgs.foreach(arg => countTemplata(counter, arg)) + } + case StructTemplateNameI(_) => + case LambdaCitizenTemplateNameI(_) => + case InterfaceTemplateNameI(humanNamee) => + case AnonymousSubstructTemplateNameI(interface) => { + countName(counter, interface) + } + case FunctionTemplateNameI(humanName, codeLocation) => + case other => vimpl(other) + } + } + + def countTemplata( + counter: Counter, + templata: ITemplataI[sI]): + Unit = { + templata match { + case CoordTemplataI(region, coord) => { + countTemplata(counter, region) + countCoord(counter, coord) + } + case KindTemplataI(kind) => countKind(counter, kind) + case r @ RegionTemplataI(_) => counter.count(r) + case MutabilityTemplataI(mutability) => + case IntegerTemplataI(_) => + case VariabilityTemplataI(variability) => + case other => vimpl(other) + } + } + + def countCoord( + counter: Counter, + coord: CoordI[sI]): + Unit = { + val CoordI(ownership, kind) = coord + countKind(counter, kind) + } + + def countKind(kind: KindIT[sI]): Map[Int, Int] = { + val map = new RegionCounter.Counter() + RegionCounter.countKind(map, kind) + map.assembleMap() + } + + def countKind( + counter: Counter, + kind: KindIT[sI]): + Unit = { + kind match { + case NeverIT(_) => + case VoidIT() => + case IntIT(_) => + case BoolIT() => + case FloatIT() => + case StrIT() => + case StructIT(id) => countStructId(counter, id) + case InterfaceIT(id) => countInterfaceId(counter, id) + case StaticSizedArrayIT(ssaId) => { + countId[StaticSizedArrayNameI[sI]]( + counter, + ssaId, + { case StaticSizedArrayNameI(template, size, variability, RawArrayNameI(mutability, elementType, selfRegion)) => + countTemplata(elementType) + counter.count(selfRegion) + }) + } + case RuntimeSizedArrayIT(ssaId) => { + countId[RuntimeSizedArrayNameI[sI]]( + counter, + ssaId, + { case RuntimeSizedArrayNameI(template, RawArrayNameI(mutability, elementType, selfRegion)) => + countTemplata(elementType) + counter.count(selfRegion) + }) + } + } + } + + def countRuntimeSizedArray( + counter: Counter, + rsa: RuntimeSizedArrayIT[sI]): + Unit = { + val RuntimeSizedArrayIT(rsaId) = rsa + countId[RuntimeSizedArrayNameI[sI]]( + counter, + rsaId, + { case RuntimeSizedArrayNameI(template, RawArrayNameI(mutability, elementType, selfRegion)) => + countTemplata(counter, elementType) + counter.count(selfRegion) + }) + } + + def countStaticSizedArray( + counter: Counter, + ssa: StaticSizedArrayIT[sI]): + Unit = { + val StaticSizedArrayIT(ssaId) = ssa + countId[StaticSizedArrayNameI[sI]]( + counter, + ssaId, + { case StaticSizedArrayNameI(template, size, variability, RawArrayNameI(mutability, elementType, selfRegion)) => + countTemplata(elementType) + counter.count(selfRegion) + }) + } + + def countCitizenId( + counter: Counter, + citizenId: IdI[sI, ICitizenNameI[sI]]): + Unit = { + citizenId match { + case IdI(packageCoord, initSteps, localName: IStructNameI[_]) => { + countStructId(IdI(packageCoord, initSteps, localName.asInstanceOf[IStructNameI[sI]])) + } + case IdI(packageCoord, initSteps, localName: IInterfaceNameI[_]) => { + countInterfaceId(IdI(packageCoord, initSteps, localName.asInstanceOf[IInterfaceNameI[sI]])) + } + } + } + + def countStructId( + counter: Counter, + structId: IdI[sI, IStructNameI[sI]]): + Unit = { + countId[IStructNameI[sI]]( + counter, + structId, + { + case StructNameI(template, templateArgs) => { + templateArgs.foreach(countTemplata(counter, _)) + } + case LambdaCitizenNameI(template) => { + } + case AnonymousSubstructNameI(template, templateArgs) => { + templateArgs.foreach(countTemplata(counter, _)) + } + }) + } + + def countImplId( + counter: Counter, + structId: IdI[sI, IImplNameI[sI]]): + Unit = { + countId[IImplNameI[sI]]( + counter, + structId, + x => countImplName(counter, x)) + } + + def countImplName( + counter: Counter, + implId: IImplNameI[sI]): + Unit = { + implId match { + case ImplNameI(template, templateArgs, subCitizen) => { + countImplTemplateName(counter, template) + templateArgs.foreach(countTemplata(counter, _)) + countCitizenId(subCitizen.id) + } + case AnonymousSubstructImplNameI(AnonymousSubstructImplTemplateNameI(interface), templateArgs, subCitizen) => { + countName(counter, interface) + templateArgs.foreach(countTemplata(counter, _)) + countCitizenId(subCitizen.id) + } + case ImplBoundNameI(ImplBoundTemplateNameI(codeLocationS), templateArgs) => { + templateArgs.foreach(countTemplata(counter, _)) + } + } + } + + def countImplTemplateName( + counter: Counter, + structName: IImplTemplateNameI[sI]): + Unit = { + structName match { + case ImplTemplateNameI(humanName) => ImplTemplateNameI(humanName) + } + } + + def countExportId(idI: IdI[sI, ExportNameI[sI]]): Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countId(counter, idI, (x: ExportNameI[sI]) => RegionCounter.countName(counter, x)) + counter.assembleMap() + } + + def countExternId(idI: IdI[sI, ExternNameI[sI]]): Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countId(counter, idI, (x: ExternNameI[sI]) => RegionCounter.countName(counter, x)) + counter.assembleMap() + } + + def countStructId(idI: IdI[sI, IStructNameI[sI]]): Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countId(counter, idI, (x: IStructNameI[sI]) => RegionCounter.countName(counter, x)) + counter.assembleMap() + } + + def countInterfaceId(idI: IdI[sI, IInterfaceNameI[sI]]): Map[Int, Int] = { + val counter = new RegionCounter.Counter() + countInterfaceId(counter, idI) + counter.assembleMap() + } + + def countInterfaceId( + counter: Counter, + interfaceId: IdI[sI, IInterfaceNameI[sI]]): + Unit = { + RegionCounter.countId(counter, interfaceId, (x: IInterfaceNameI[sI]) => RegionCounter.countName(counter, x)) + } + + def countFunctionId(idI: IdI[sI, IFunctionNameI[sI]]): Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countId(counter, idI, (x: IFunctionNameI[sI]) => RegionCounter.countName(counter, x)) + counter.assembleMap() + } + + def countImplId( + implId: IdI[sI, IImplNameI[sI]]): + Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countId( + counter, implId, (x: IImplNameI[sI]) => RegionCounter.countImplName(counter, x)) + counter.assembleMap() + } + + def countCoord(coord: CoordI[sI]): Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countCoord(counter, coord) + counter.assembleMap() + } + + def countVarName( + name: IVarNameI[sI]): + Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countVarName(counter, name) + counter.assembleMap() + } + + def countStaticSizedArray( + ssa: StaticSizedArrayIT[sI]): + Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countStaticSizedArray(counter, ssa) + counter.assembleMap() + } + + def countRuntimeSizedArray( + rsa: RuntimeSizedArrayIT[sI]): + Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countRuntimeSizedArray(counter, rsa) + counter.assembleMap() + } + + def countPrototype(prototype: PrototypeI[sI]): Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countPrototype(counter, prototype) + counter.assembleMap() + } + + def countFunctionName( + name: IFunctionNameI[sI]): + Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countFunctionName(counter, name) + counter.assembleMap() + } + + def countImplName( + name: IImplNameI[sI]): + Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countImplName(counter, name) + counter.assembleMap() + } + + def countCitizenName( + name: ICitizenNameI[sI]): + Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countCitizenName(counter, name) + counter.assembleMap() + } + + def countCitizenId( + name: IdI[sI, ICitizenNameI[sI]]): + Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countCitizenId(counter, name) + counter.assembleMap() + } + + def countTemplata( + name: ITemplataI[sI]): + Map[Int, Int] = { + val counter = new RegionCounter.Counter() + RegionCounter.countTemplata(counter, name) + counter.assembleMap() + } +} diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/HinputsI.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/HinputsI.scala new file mode 100644 index 000000000..b25eeb7ac --- /dev/null +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/HinputsI.scala @@ -0,0 +1,211 @@ +package dev.vale.instantiating.ast + +import dev.vale.postparsing.IRuneS +import dev.vale.typing.ast._ +import dev.vale.typing.names.{CitizenNameT, CitizenTemplateNameT, IdT, FunctionNameT, IFunctionNameT, LambdaCitizenNameT} +import dev.vale.typing.templata._ +import dev.vale.typing.types._ +import dev.vale.{StrI, vassertOne, vassertSome, vcurious, vfail, vimpl} +import dev.vale.typing.ast._ +import dev.vale.typing.names._ +import dev.vale.typing.types._ + +import scala.collection.mutable + +case class InstantiationBoundArgumentsI( + runeToFunctionBoundArg: Map[IRuneS, PrototypeI[sI]], + runeToImplBoundArg: Map[IRuneS, IdI[sI, IImplNameI[sI]]]) + +case class HinputsI( + interfaces: Vector[InterfaceDefinitionI], + structs: Vector[StructDefinitionI], +// emptyPackStructRef: StructTT, + functions: Vector[FunctionDefinitionI], +// immKindToDestructor: Map[KindT, PrototypeI], + + // The typing pass keys this by placeholdered name, and the instantiator keys this by non-placeholdered names + interfaceToEdgeBlueprints: Map[IdI[cI, IInterfaceNameI[cI]], InterfaceEdgeBlueprintI], + // The typing pass keys this by placeholdered name, and the instantiator keys this by non-placeholdered names + interfaceToSubCitizenToEdge: Map[IdI[cI, IInterfaceNameI[cI]], Map[IdI[cI, ICitizenNameI[cI]], EdgeI]], + +// instantiationNameToInstantiationBounds: Map[IdI[cI, IInstantiationNameI[cI]], InstantiationBoundArgumentsI], + + kindExports: Vector[KindExportI], + functionExports: Vector[FunctionExportI], +// kindExterns: Vector[KindExternI], + functionExterns: Vector[FunctionExternI], +) { + + private val subCitizenToInterfaceToEdgeMutable = mutable.HashMap[IdI[cI, ICitizenNameI[cI]], mutable.HashMap[IdI[cI, IInterfaceNameI[cI]], EdgeI]]() + interfaceToSubCitizenToEdge.foreach({ case (interface, subCitizenToEdge) => + subCitizenToEdge.foreach({ case (subCitizen, edge) => + subCitizenToInterfaceToEdgeMutable + .getOrElseUpdate(subCitizen, mutable.HashMap[IdI[cI, IInterfaceNameI[cI]], EdgeI]()) + .put(interface, edge) + }) + }) + val subCitizenToInterfaceToEdge: Map[IdI[cI, ICitizenNameI[cI]], Map[IdI[cI, IInterfaceNameI[cI]], EdgeI]] = + subCitizenToInterfaceToEdgeMutable.mapValues(_.toMap).toMap + + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vfail() // Would need a really good reason to hash something this big + + def lookupStruct(structId: IdI[cI, IStructNameI[cI]]): StructDefinitionI = { + vassertSome(structs.find(_.instantiatedCitizen.id == structId)) + } + + def lookupInterface(interfaceId: IdI[cI, IInterfaceNameI[cI]]): InterfaceDefinitionI = { + vassertSome(interfaces.find(_.instantiatedCitizen.id == interfaceId)) + } + + def lookupStructByTemplate(structTemplateName: IStructTemplateNameI[cI]): StructDefinitionI = { + vassertSome(structs.find(_.instantiatedCitizen.id.localName.template == structTemplateName)) + } + + def lookupInterfaceByTemplate(interfaceTemplateName: IInterfaceTemplateNameI[cI]): InterfaceDefinitionI = { + vassertSome(interfaces.find(_.instantiatedCitizen.id.localName.template == interfaceTemplateName)) + } + + def lookupImplByTemplate(implTemplateName: IImplTemplateNameI[cI]): EdgeI = { + vassertSome(interfaceToSubCitizenToEdge.flatMap(_._2.values).find(_.edgeId.localName.template == implTemplateName)) + } + + def lookupEdge(implId: IdI[cI, IImplNameI[cI]]): EdgeI = { + vassertOne(interfaceToSubCitizenToEdge.flatMap(_._2.values).find(_.edgeId == implId)) + } + +// def getInstantiationBoundArgs(instantiationName: IdI[cI, IInstantiationNameI[cI]]): InstantiationBoundArgumentsI = { +// vassertSome(instantiationNameToInstantiationBounds.get(instantiationName)) +// } + +// def lookupStructByTemplateFullName(structTemplateId: IdI[IStructTemplateNameI]): StructDefinitionI = { +// vassertSome(structs.find(_.templateName == structTemplateId)) +// } +// +// def lookupInterfaceByTemplateFullName(interfaceTemplateId: IdI[IInterfaceTemplateNameI]): InterfaceDefinitionI = { +// vassertSome(interfaces.find(_.templateName == interfaceTemplateId)) +// } +// +// def lookupCitizenByTemplateFullName(interfaceTemplateId: IdI[ICitizenTemplateNameI]): CitizenDefinitionI = { +// interfaceTemplateId match { +// case IdI(packageCoord, initSteps, t: IStructTemplateNameI) => { +// lookupStructByTemplateFullName(IdI(packageCoord, initSteps, t)) +// } +// case IdI(packageCoord, initSteps, t: IInterfaceTemplateNameI) => { +// lookupInterfaceByTemplateFullName(IdI(packageCoord, initSteps, t)) +// } +// } +// } +// +// def lookupStructByTemplateName(structTemplateName: StructTemplateNameI): StructDefinitionI = { +// vassertOne(structs.filter(_.templateName.localName == structTemplateName)) +// } +// +// def lookupInterfaceByTemplateName(interfaceTemplateName: InterfaceTemplateNameI): InterfaceDefinitionI = { +// vassertSome(interfaces.find(_.templateName.localName == interfaceTemplateName)) +// } + + // def lookupFunction(signature2: SignatureI[cI]): Option[FunctionDefinitionI] = { + // functions.find(_.header.toSignature == signature2).headOption + // } + + def lookupFunction(funcTemplateName: IFunctionTemplateNameI[cI]): Option[FunctionDefinitionI] = { + functions.find(_.header.id.localName.template == funcTemplateName).headOption + } + + def lookupFunction(humanName: String): FunctionDefinitionI = { + val matches = functions.filter(f => { + f.header.id.localName match { + case FunctionNameIX(n, _, _) if n.humanName.str == humanName => true + case _ => false + } + }) + if (matches.size == 0) { + vfail("Function \"" + humanName + "\" not found!") + } else if (matches.size > 1) { + vfail("Multiple found!") + } + matches.head + } + + def lookupStruct(humanName: String): StructDefinitionI = { + val matches = structs.filter(s => { + s.instantiatedCitizen.id.localName match { + case StructNameI(StructTemplateNameI(n), _) if n.str == humanName => true + case _ => false + } + }) + if (matches.size == 0) { + vfail("Struct \"" + humanName + "\" not found!") + } else if (matches.size > 1) { + vfail("Multiple found!") + } + matches.head + } + + def lookupImpl( + subCitizenIT: IdI[cI, ICitizenNameI[cI]], + interfaceIT: IdI[cI, IInterfaceNameI[cI]]): + EdgeI = { + vassertSome( + vassertSome(interfaceToSubCitizenToEdge.get(interfaceIT)) + .get(subCitizenIT)) + } + + def lookupInterface(humanName: String): InterfaceDefinitionI = { + val matches = interfaces.filter(s => { + s.instantiatedCitizen.id.localName match { + case InterfaceNameI(InterfaceTemplateNameI(n), _) if n.str == humanName => true + case _ => false + } + }) + if (matches.size == 0) { + vfail("Interface \"" + humanName + "\" not found!") + } else if (matches.size > 1) { + vfail("Multiple found!") + } + matches.head + } + + def lookupUserFunction(humanName: String): FunctionDefinitionI = { + val matches = + functions + .filter(function => simpleNameI.unapply(function.header.id).contains(humanName)) + .filter(_.header.isUserFunction) + if (matches.size == 0) { + vfail("Not found!") + } else if (matches.size > 1) { + vfail("Multiple found!") + } + matches.head + } + +// def nameIsLambdaIn(name: IdI[cI, IFunctionNameI[cI]], needleFunctionHumanName: String): Boolean = { +// val first = name.steps.head +// val lastTwo = name.steps.slice(name.steps.size - 2, name.steps.size) +// (first, lastTwo) match { +// case ( +// FunctionNameIX(FunctionTemplateNameI(StrI(hayFunctionHumanName), _), _, _), +// Vector( +// LambdaCitizenTemplateNameI(_), +// LambdaCallFunctionNameI(LambdaCallFunctionTemplateNameI(_, _), _, _))) +// if hayFunctionHumanName == needleFunctionHumanName => true +// case _ => false +// } +// } + +// def lookupLambdasIn(needleFunctionHumanName: String): Vector[FunctionDefinitionI] = { +// functions.filter(f => nameIsLambdaIn(f.header.id, needleFunctionHumanName)).toVector +// } + +// def lookupLambdaIn(needleFunctionHumanName: String): FunctionDefinitionI = { +// vassertOne(lookupLambdasIn(needleFunctionHumanName)) +// } + + def getAllNonExternFunctions: Iterable[FunctionDefinitionI] = { + functions.filter(!_.header.isExtern) + } + + def getAllUserFunctions: Iterable[FunctionDefinitionI] = { + functions.filter(_.header.isUserFunction) + } +} diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/TemplataUtils.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/TemplataUtils.scala new file mode 100644 index 000000000..1bf318240 --- /dev/null +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/TemplataUtils.scala @@ -0,0 +1,41 @@ +package dev.vale.instantiating.ast + +import dev.vale.typing.ast.{FunctionHeaderT, FunctionDefinitionT, PrototypeT} +import dev.vale.typing.names._ +import dev.vale.typing.ast._ +import dev.vale.typing.names._ + +object simpleNameI { + def unapply[R <: IRegionsModeI](id: IdI[R, INameI[R]]): Option[String] = { + id.localName match { +// case ImplDeclareNameI(_) => None + case LambdaCallFunctionNameI(_, _, _) => Some("__call") + case LetNameI(_) => None + case UnnamedLocalNameI(_) => None + case FunctionBoundNameI(FunctionBoundTemplateNameI(humanName, _), _, _) => Some(humanName.str) + case ClosureParamNameI(_) => None + case MagicParamNameI(_) => None + case CodeVarNameI(name) => Some(name.str) + case FunctionNameIX(FunctionTemplateNameI(humanName, _), _, _) => Some(humanName.str) + case LambdaCitizenNameI(_) => None + case StructNameI(StructTemplateNameI(humanName), _) => Some(humanName.str) + case StructTemplateNameI(humanName) => Some(humanName.str) + case InterfaceNameI(InterfaceTemplateNameI(humanName), _) => Some(humanName.str) + case InterfaceTemplateNameI(humanName) => Some(humanName.str) + case AnonymousSubstructTemplateNameI(InterfaceTemplateNameI(humanNamee)) => Some(humanNamee.str) + } + } +} + +object functionNameI { + def unapply(function2: FunctionDefinitionI): Option[String] = { + unapply(function2.header) + } + def unapply(header: FunctionHeaderI): Option[String] = { + simpleNameI.unapply(header.id) + } + def unapply[R <: IRegionsModeI](prototype: PrototypeI[R]): Option[String] = { + simpleNameI.unapply(prototype.id) + } +} + diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/ast.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/ast.scala new file mode 100644 index 000000000..5aacea292 --- /dev/null +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/ast.scala @@ -0,0 +1,359 @@ +package dev.vale.instantiating.ast + +import dev.vale._ +import dev.vale.postparsing._ + +import scala.collection.immutable._ + +// We won't always have a return type for a banner... it might have not specified its return +// type, so we're currently evaluating the entire body for it right now. +// If we ever find ourselves wanting the return type for a banner, we need to: +// - Check if it's in the returnTypesByBanner map. If so, good. +// - If not, then check if the banner is in declaredBanners. If so, then we're currently in +// the process of evaluating the entire body. In this case, throw an error because we're +// about to infinite loop. Hopefully this is a user error, they need to specify a return +// type to avoid a cyclical definition. +// - If not in declared banners, then tell FunctionCompiler to start evaluating it. + +// case class ImplI( +// // These are ICitizenTI and InterfaceIT which likely have placeholder templatas in them. +// // We do this because a struct might implement an interface in multiple ways, see SCIIMT. +// // We have the template names as well as the placeholders for better searching, see MLUIBTN. +// +// templata: ImplDefinitionTemplataI[cI], +// +// instantiatedId: IdI[cI, IImplNameI[cI]], +// templateId: IdI[cI, IImplTemplateNameI[cI]], +// +// subCitizenTemplateId: IdI[cI, ICitizenTemplateNameI[cI]], +// subCitizen: ICitizenIT[cI], +// +// superInterface: InterfaceIT[cI], +// superInterfaceTemplateId: IdI[cI, IInterfaceTemplateNameI[cI]], +// +// // This is similar to FunctionT.runeToFuncBound +// runeToFuncBound: Map[IRuneS, IdI[cI, FunctionBoundNameI[cI]]], +// runeToImplBound: Map[IRuneS, IdI[cI, ImplBoundNameI[cI]]], +// +// runeIndexToIndependence: Vector[Boolean], +// +// // A function will inherit bounds from its parameters' kinds. Same with an impl from its sub +// // citizen, and a case block from its receiving kind. +// // We'll need to remember those, so the instantiator can do its thing. +// // See TIBANFC for more. +// reachableBoundsFromSubCitizen: Vector[PrototypeI[cI]] +// +// // // Starting from a placeholdered super interface, this is the interface that would result. +// // // We get this by solving the impl, given a placeholdered sub citizen. +// // subCitizenFromPlaceholderedParentInterface: ICitizenIT, +// ) + +case class KindExportI( + range: RangeS, + tyype: KindIT[cI], + // Good for knowing the package of this export for later prefixing the exportedName, also good + // for getting its region. + id: IdI[cI, ExportNameI[cI]], + exportedName: StrI +) { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + +} + +case class FunctionExportI( + range: RangeS, + prototype: PrototypeI[cI], + exportId: IdI[cI, ExportNameI[cI]], + exportedName: StrI +) { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + vpass() +} + +//case class KindExternI( +// tyype: KindIT, +// packageCoordinate: PackageCoordinate, +// externName: StrI +//) { +// override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// +//} + +case class FunctionExternI( +// range: RangeS, + prototype: PrototypeI[cI], +// packageCoordinate: PackageCoordinate, + externName: StrI +) { + vpass() + + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + +} + +case class InterfaceEdgeBlueprintI( + // The typing pass keys this by placeholdered name, and the instantiator keys this by non-placeholdered names + interface: IdI[cI, IInterfaceNameI[cI]], + superFamilyRootHeaders: Vector[(PrototypeI[cI], Int)]) { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); } + +case class EdgeI( + // The typing pass keys this by placeholdered name, and the instantiator keys this by non-placeholdered names + edgeId: IdI[cI, IImplNameI[cI]], + // The typing pass keys this by placeholdered name, and the instantiator keys this by non-placeholdered names + subCitizen: ICitizenIT[cI], + // The typing pass keys this by placeholdered name, and the instantiator keys this by non-placeholdered names + superInterface: IdI[cI, IInterfaceNameI[cI]], + // This is similar to FunctionT.runeToFuncBound + runeToFuncBound: Map[IRuneS, IdI[cI, FunctionBoundNameI[cI]]], + runeToImplBound: Map[IRuneS, IdI[cI, ImplBoundNameI[cI]]], + // The typing pass keys this by placeholdered name, and the instantiator keys this by non-placeholdered names + abstractFuncToOverrideFunc: Map[IdI[cI, IFunctionNameI[cI]], PrototypeI[cI]] +) { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + + override def equals(obj: Any): Boolean = { + obj match { + case EdgeI(thatEdgeFullName, thatStruct, thatInterface, _, _, _) => { + val isSame = subCitizen == thatStruct && superInterface == thatInterface + if (isSame) { + vassert(edgeId == thatEdgeFullName) + } + isSame + } + } + } +} + +case class FunctionDefinitionI( + header: FunctionHeaderI, + runeToFuncBound: Map[IRuneS, IdI[cI, FunctionBoundNameI[cI]]], + runeToImplBound: Map[IRuneS, IdI[cI, ImplBoundNameI[cI]]], + body: ReferenceExpressionIE) { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + + // We always end a function with a ret, whose result is a Never. + vassert(body.result.kind == NeverIT[cI](false)) + + def isPure: Boolean = header.isPure +} + +object getFunctionLastName { + def unapply(f: FunctionDefinitionI): Option[IFunctionNameI[cI]] = Some(f.header.id.localName) +} + +// A unique location in a function. Environment is in the name so it spells LIFE! +case class LocationInFunctionEnvironmentI(path: Vector[Int]) { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + + def +(subLocation: Int): LocationInFunctionEnvironmentI = { + LocationInFunctionEnvironmentI(path :+ subLocation) + } + + override def toString: String = path.mkString(".") +} + +case class AbstractI() + +case class ParameterI( + name: IVarNameI[cI], + virtuality: Option[AbstractI], + preChecked: Boolean, + tyype: CoordI[cI]) { + + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + + // Use same instead, see EHCFBD for why we dont like equals. + override def equals(obj: Any): Boolean = vcurious(); + + def same(that: ParameterI): Boolean = { + name == that.name && + virtuality == that.virtuality && + tyype == that.tyype + } +} + +// A "signature" is just the things required for overload resolution, IOW function name and arg types. + +// An autograph could be a super signature; a signature plus attributes like virtual and mutable. +// If we ever need it, a "schema" could be something. + +// A FunctionBanner2 is everything in a FunctionHeader2 minus the return type. +// These are only made by the FunctionCompiler, to signal that it's currently being +// evaluated or it's already been evaluated. +// It's easy to see all possible function banners, but not easy to see all possible +// function headers, because functions don't have to specify their return types and +// it takes a complete typingpass evaluate to deduce a function's return type. + +case class SignatureI[+R <: IRegionsModeI](id: IdI[R, IFunctionNameI[R]]) { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + def paramTypes: Vector[CoordI[R]] = id.localName.parameters +} + +sealed trait IFunctionAttributeI +sealed trait ICitizenAttributeI +case class ExternI(packageCoord: PackageCoordinate) extends IFunctionAttributeI with ICitizenAttributeI { // For optimization later + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; +} +// There's no Export2 here, we use separate KindExport and FunctionExport constructs. +//case class Export2(packageCoord: PackageCoordinate) extends IFunctionAttribute2 with ICitizenAttribute2 +case object PureI extends IFunctionAttributeI +case object SealedI extends ICitizenAttributeI +case object UserFunctionI extends IFunctionAttributeI // Whether it was written by a human. Mostly for tests right now. + +case class RegionI( + name: IRegionNameI[cI], + mutable: Boolean) + +case class FunctionHeaderI( + // This one little name field can illuminate much of how the compiler works, see UINIT. + id: IdI[cI, IFunctionNameI[cI]], + attributes: Vector[IFunctionAttributeI], +// regions: Vector[cIegionI], + params: Vector[ParameterI], + returnType: CoordI[cI]) { + + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +// val perspectiveRegion = +// id.localName.templateArgs.last match { +// case PlaceholderTemplata(IdI(packageCoord, initSteps, r @ RegionPlaceholderNameI(_, _, _, _, _)), RegionTemplataType()) => { +// IdI(packageCoord, initSteps, r) +// } +// case _ => vwat() +// } +// if (attributes.contains(PureI)) { +// // Instantiator relies on this assumption so that it knows when certain things are pure. +// vassert(perspectiveRegion.localName.originalMaybeNearestPureLocation == Some(LocationInDenizen(Vector()))) +// } + + override def equals(obj: Any): Boolean = { + obj match { + case FunctionHeaderI(thatName, _, _, _) => { + id == thatName + } + case _ => false + } + } + + // Make sure there's no duplicate names + vassert(params.map(_.name).toSet.size == params.size); + + vassert(id.localName.parameters == paramTypes) + + def isExtern = attributes.exists({ case ExternI(_) => true case _ => false }) + // def isExport = attributes.exists({ case Export2(_) => true case _ => false }) + def isUserFunction = attributes.contains(UserFunctionI) +// def getAbstractInterface: Option[InterfaceIT] = toBanner.getAbstractInterface +//// def getOverride: Option[(StructIT, InterfaceIT)] = toBanner.getOverride +// def getVirtualIndex: Option[Int] = toBanner.getVirtualIndex + +// def toSignature(interner: Interner, keywords: Keywords): SignatureI = { +// val newLastStep = templateName.last.makeFunctionName(interner, keywords, templateArgs, params) +// val fullName = FullNameI(templateName.packageCoord, name.initSteps, newLastStep) +// +// SignatureI(fullName) +// +// } +// def paramTypes: Vector[CoordI[cI]] = params.map(_.tyype) + + def getAbstractInterface: Option[InterfaceIT[cI]] = { + val abstractInterfaces = + params.collect({ + case ParameterI(_, Some(AbstractI()), _, CoordI(_, ir @ InterfaceIT(_))) => ir + }) + vassert(abstractInterfaces.size <= 1) + abstractInterfaces.headOption + } + + def getVirtualIndex: Option[Int] = { + val indices = + params.zipWithIndex.collect({ + case (ParameterI(_, Some(AbstractI()), _, _), index) => index + }) + vassert(indices.size <= 1) + indices.headOption + } + +// maybeOriginFunction.foreach(originFunction => { +// if (originFunction.genericParameters.size != fullName.last.templateArgs.size) { +// vfail("wtf m8") +// } +// }) + + def toPrototype: PrototypeI[cI] = { +// val substituter = TemplataCompiler.getPlaceholderSubstituter(interner, fullName, templateArgs) +// val paramTypes = params.map(_.tyype).map(substituter.substituteForCoord) +// val newLastStep = fullName.last.makeFunctionName(interner, keywords, templateArgs, paramTypes) +// val newName = FullNameI(fullName.packageCoord, fullName.initSteps, newLastStep) + PrototypeI(id, returnType) + } + def toSignature: SignatureI[cI] = { + toPrototype.toSignature + } + + def paramTypes: Vector[CoordI[cI]] = id.localName.parameters + + def unapply(arg: FunctionHeaderI): Option[(IdI[cI, IFunctionNameI[cI]], Vector[ParameterI], CoordI[cI])] = { + Some(id, params, returnType) + } + + def isPure: Boolean = { + attributes.collectFirst({ case PureI => }).nonEmpty + } +} + +case class PrototypeI[+R <: IRegionsModeI]( + id: IdI[R, IFunctionNameI[R]], + returnType: CoordI[R]) { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + def paramTypes: Vector[CoordI[R]] = id.localName.parameters + def toSignature: SignatureI[R] = SignatureI[R](id) +} + +sealed trait IVariableI { + def name: IVarNameI[cI] + def variability: VariabilityI + def collapsedCoord: CoordI[cI] +} +sealed trait ILocalVariableI extends IVariableI { + def name: IVarNameI[cI] + def collapsedCoord: CoordI[cI] +} +// Why the difference between reference and addressible: +// If we mutate/move a variable from inside a closure, we need to put +// the local's address into the struct. But, if the closures don't +// mutate/move, then we could just put a regular reference in the struct. +// Lucky for us, the parser figured out if any of our child closures did +// any mutates/moves/borrows. +case class AddressibleLocalVariableI( + name: IVarNameI[cI], + variability: VariabilityI, + collapsedCoord: CoordI[cI] +) extends ILocalVariableI { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); +} +case class ReferenceLocalVariableI( + name: IVarNameI[cI], + variability: VariabilityI, + collapsedCoord: CoordI[cI] +) extends ILocalVariableI { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); + vpass() +} +case class AddressibleClosureVariableI( + name: IVarNameI[cI], + closuredVarsStructType: StructIT[cI], + variability: VariabilityI, + collapsedCoord: CoordI[cI] +) extends IVariableI { + vpass() +} +case class ReferenceClosureVariableI( + name: IVarNameI[cI], + closuredVarsStructType: StructIT[cI], + variability: VariabilityI, + collapsedCoord: CoordI[cI] +) extends IVariableI { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); + +} diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/citizens.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/citizens.scala new file mode 100644 index 000000000..db5672944 --- /dev/null +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/citizens.scala @@ -0,0 +1,110 @@ +package dev.vale.instantiating.ast + +import dev.vale.postparsing._ +import dev.vale._ + +import scala.collection.immutable.Map + +// A "citizen" is a struct or an interface. +trait CitizenDefinitionI { +// def genericParamTypes: Vector[ITemplataType] + def instantiatedCitizen: ICitizenIT[cI] +} + +case class StructDefinitionI( +// templateName: IdI[cI, IStructTemplateNameI], + // In typing pass, this will have placeholders. Monomorphizing will give it a real name. + instantiatedCitizen: StructIT[cI], + attributes: Vector[ICitizenAttributeI], + weakable: Boolean, + mutability: MutabilityI, + members: Vector[StructMemberI], + isClosure: Boolean, + runeToFunctionBound: Map[IRuneS, IdI[cI, FunctionBoundNameI[cI]]], + runeToImplBound: Map[IRuneS, IdI[cI, ImplBoundNameI[cI]]], +) extends CitizenDefinitionI { +// override def genericParamTypes: Vector[ITemplataType] = { +// instantiatedCitizen.id.localName.templateArgs.map(_.tyype) +// } + + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + +// override def getRef: StructIT = ref +// +// def getMember(memberName: StrI): StructMemberI = { +// members.find(p => p.name.equals(CodeVarNameI(memberName))) match { +// case None => vfail("Couldn't find member " + memberName) +// case Some(member) => member +// } +// } +// +// private def getIndex(memberName: IVarNameI): Int = { +// members.zipWithIndex.find(p => p._1.name.equals(memberName)) match { +// case None => vfail("wat") +// case Some((member, index)) => index +// } +// } + + def getMemberAndIndex(needleName: IVarNameI[cI]): Option[(StructMemberI, Int)] = { + members.zipWithIndex + .foreach({ + case (m @ StructMemberI(hayName, _, _), index) if hayName == needleName => { + return Some((m, index)) + } + case _ => + }) + None + } +} + +case class StructMemberI( + name: IVarNameI[cI], + // In the case of address members, this refers to the variability of the pointee variable. + variability: VariabilityI, + tyype: IMemberTypeI +) { + vpass() +} + +sealed trait IMemberTypeI { + def reference: CoordI[cI] + + def expectReferenceMember(): ReferenceMemberTypeI = { + this match { + case r @ ReferenceMemberTypeI(_) => r + case a @ AddressMemberTypeI(_) => vfail("Expected reference member, was address member!") + } + } + def expectAddressMember(): AddressMemberTypeI = { + this match { + case r @ ReferenceMemberTypeI(_) => vfail("Expected reference member, was address member!") + case a @ AddressMemberTypeI(_) => a + } + } +} + +case class AddressMemberTypeI(reference: CoordI[cI]) extends IMemberTypeI +case class ReferenceMemberTypeI(reference: CoordI[cI]) extends IMemberTypeI + +case class InterfaceDefinitionI( +// templateName: IdI[cI, IInterfaceTemplateNameI], + instantiatedInterface: InterfaceIT[cI], +// ref: InterfaceIT, + attributes: Vector[ICitizenAttributeI], + weakable: Boolean, + mutability: MutabilityI, + runeToFunctionBound: Map[IRuneS, IdI[cI, FunctionBoundNameI[cI]]], + runeToImplBound: Map[IRuneS, IdI[cI, ImplBoundNameI[cI]]], + // This does not include abstract functions declared outside the interface. + // Note from later: Though, sometimes macros add functions into the inside. + // See IMRFDI for why we need to remember only the internal methods here. + internalMethods: Vector[(PrototypeI[cI], Int)] +) extends CitizenDefinitionI { +// override def genericParamTypes: Vector[ITemplataType] = { +// instantiatedCitizen.id.localName.templateArgs.map(_.tyype) +// } + + override def instantiatedCitizen: ICitizenIT[cI] = instantiatedInterface + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def getRef = ref +} diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/expressions.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/expressions.scala new file mode 100644 index 000000000..828154276 --- /dev/null +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/expressions.scala @@ -0,0 +1,906 @@ +package dev.vale.instantiating.ast + +import dev.vale._ +import dev.vale.postparsing._ + +//trait IExpressionResultI { +// def expectReference(): ReferenceResultI = { +// this match { +// case r @ ReferenceResultI(_) => r +// case AddressResultI(_) => vfail("Expected a reference as a result, but got an address!") +// } +// } +// def expectAddress(): AddressResultI = { +// this match { +// case a @ AddressResultI(_) => a +// case ReferenceResultI(_) => vfail("Expected an address as a result, but got a reference!") +// } +// } +// // DO NOT SUBMIT rename back to coord +// def collapsedCoord: CoordI[cI] +//} +//// This is only the collapsed coord, see HCCSCS. +//case class ReferenceResultI(collapsedCoord: CoordI[cI]) extends IExpressionResultI { +// override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +//} +//case class AddressResultI(collapsedCoord: CoordI[cI]) extends IExpressionResultI { +// override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +//} + +trait ExpressionI { + def result: CoordI[cI] +} +trait ReferenceExpressionIE extends ExpressionI { } +// This is an Expression2 because we sometimes take an address and throw it +// directly into a struct (closures!), which can have addressible members. +trait AddressExpressionIE extends ExpressionI { +// def range: RangeS + +// // Whether or not we can change where this address points to +// def variability: VariabilityI +} + +case class LetAndLendIE( + variable: ILocalVariableI, + expr: ReferenceExpressionIE, + targetOwnership: OwnershipI, + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + vassert(variable.collapsedCoord == expr.result) + + (expr.result.ownership, targetOwnership) match { + case (MutableShareI, MutableShareI) => + case (ImmutableShareI, ImmutableShareI) => + case (OwnI | MutableBorrowI | WeakI | MutableShareI, MutableBorrowI) => + case (ImmutableBorrowI, ImmutableBorrowI) => + } + + expr match { + case BreakIE() | ReturnIE(_) => vwat() // See BRCOBS + case _ => + } +} + +case class LockWeakIE( + innerExpr: ReferenceExpressionIE, + // We could just calculaIE this, but it feels better to let the StructCompiler + // make it, so we're sure it's created. + resultOptBorrowType: CoordI[cI], + + // Function to give a borrow ref to to make a Some(borrow ref) + someConstructor: PrototypeI[cI], + // Function to make a None of the right type + noneConstructor: PrototypeI[cI], + + // This is the impl we use to allow/permit the upcast from the some to the none. + // It'll be useful for monomorphization and later on for locating the itable ptr to put in fat pointers. + someImplName: IdI[cI, IImplNameI[cI]], + // This is the impl we use to allow/permit the upcast from the some to the none. + // It'll be useful for monomorphization and later on for locating the itable ptr to put in fat pointers. + noneImplName: IdI[cI, IImplNameI[cI]], + + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe: CoordI[cI] = resultOptBorrowType +} + +// Turns a borrow ref into a weak ref +// NoIE that we can also get a weak ref from LocalLoad2'ing a +// borrow ref local into a weak ref. +case class BorrowToWeakIE( + innerExpr: ReferenceExpressionIE, + result: CoordI[cI] +) extends ReferenceExpressionIE { + vassert( + innerExpr.result.ownership == ImmutableBorrowI || + innerExpr.result.ownership == MutableBorrowI) + + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + innerExpr.result.ownership match { + case MutableBorrowI | ImmutableBorrowI => + } + vassert(result.ownership == vregionmut(WeakI)) + +// override def resultRemoveMe: CoordI[cI] = { +// vimpl()//ReferenceResultI(CoordI[cI](WeakI, innerExpr.kind)) +// } +} + +case class LetNormalIE( + variable: ILocalVariableI, + expr: ReferenceExpressionIE, + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + + expr.result.kind match { + case NeverIT(_) => // then we can put it into whatever type we want + case _ => { + variable.collapsedCoord.kind match { + case NeverIT(_) => vfail() // can't receive into a never + case _ => vassert(variable.collapsedCoord == expr.result) + } + } + } + + expr match { + case BreakIE() | ReturnIE(_) => vwat() // See BRCOBS + case _ => + } +} + +case class RestackifyIE( + variable: ILocalVariableI, + expr: ReferenceExpressionIE, + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + + expr.result.kind match { + case NeverIT(_) => // then we can put it into whatever type we want + case _ => { + variable.collapsedCoord.kind match { + case NeverIT(_) => vfail() // can't receive into a never + case _ => vassert(variable.collapsedCoord == expr.result) + } + } + } + + expr match { + case BreakIE() | ReturnIE(_) => vwat() // See BRCOBS + case _ => + } +} + +// Only ExpressionCompiler.unletLocal should make these +case class UnletIE( + variable: ILocalVariableI, + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe = variable.collapsedCoord + + vpass() +} + +// Throws away a reference. +// Unless given to an instruction which consumes it, all borrow and share +// references must eventually hit a Discard2, just like all owning +// references must eventually hit a Destructure2. +// Depending on the backend, it will either be a no-op (like for GC'd backends) +// or a decrement+maybedestruct (like for RC'd backends) +// See DINSIE for why this isnt three instructions, and why we dont have the +// destructor in here for shareds. +case class DiscardIE( + expr: ReferenceExpressionIE +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + override def result: CoordI[cI] = CoordI[cI](MutableShareI, VoidIT()) + + expr.result.ownership match { + case MutableBorrowI => + case ImmutableBorrowI => + case MutableShareI | ImmutableShareI => + case WeakI => + } + + expr match { + case ConsecutorIE(exprs, _) => { + exprs.last match { + case DiscardIE(_) => vwat() + case _ => + } + } + case _ => + } +} + +case class DeferIE( + innerExpr: ReferenceExpressionIE, + // Every deferred expression should discard its result, IOW, return Void. + deferredExpr: ReferenceExpressionIE, + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + +// override def resultRemoveMe = ReferenceResultI(innerExpr.result) + + vassert(deferredExpr.result == CoordI[cI](MutableShareI, VoidIT())) +} + + +// Eventually, when we want to do if-let, we'll have a different construct +// entirely. See comment below If2. +// These are blocks because we don't want inner locals to escape. +case class IfIE( + condition: ReferenceExpressionIE, + thenCall: ReferenceExpressionIE, + elseCall: ReferenceExpressionIE, + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + private val conditionResultCoord = condition.result + private val thenResultCoord = thenCall.result + private val elseResultCoord = elseCall.result + + conditionResultCoord match { + case CoordI(MutableShareI | ImmutableShareI, BoolIT()) => + case other => vfail(other) + } + + (thenResultCoord.kind, thenResultCoord.kind) match { + case (NeverIT(_), _) => + case (_, NeverIT(_)) => + case (a, b) if a == b => + case _ => vwat() + } + + private val commonSupertype = + thenResultCoord.kind match { + case NeverIT(_) => elseResultCoord + case _ => thenResultCoord + } + +// override def resultRemoveMe = ReferenceResultI(commonSupertype) +} + +// The block is expected to return a boolean (false = stop, true = keep going). +// The block will probably contain an If2(the condition, the body, false) +case class WhileIE( + block: BlockIE, + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe = ReferenceResultI(resultCoord) + vpass() +} + +case class MutateIE( + destinationExpr: AddressExpressionIE, + sourceExpr: ReferenceExpressionIE, + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe = ReferenceResultI(destinationExpr.result) +} + + +case class ReturnIE( + sourceExpr: ReferenceExpressionIE +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + + override def result: CoordI[cI] = CoordI[cI](MutableShareI, NeverIT(false)) +} + +case class BreakIE() extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + override def result: CoordI[cI] = CoordI[cI](MutableShareI, NeverIT(true)) +} + +// when we make a closure, we make a struct full of pointers to all our variables +// and the first element is our parent closure +// this can live on the stack, since blocks are additive to this expression +// later we can optimize it to only have the things we use + +// Block2 is required to unlet all the variables it introduces. +case class BlockIE( + inner: ReferenceExpressionIE, + result: CoordI[cI] +) extends ReferenceExpressionIE { + vpass() + + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe = inner.result +} + +// A pure block will: +// 1. Create a new region (someday possibly with an allocator) +// 2. Freeze the existing region +// 3. Run the inner code +// 4. Un-freeze the existing region +// 5. Merge (transmigrate) any results from the new region into the existing region +// 6. Destroy the new region +case class MutabilifyIE( + inner: ReferenceExpressionIE, + result: CoordI[cI] // See HCCSCS +) extends ReferenceExpressionIE { + vpass() + vassert(inner.result.kind == result.kind) + + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +} + +// See NPFCASTN +case class ImmutabilifyIE( + inner: ReferenceExpressionIE, + result: CoordI[cI] +) extends ReferenceExpressionIE { + vpass() + vassert(inner.result.kind == result.kind) + vassert(inner.result.ownership == MutableBorrowI || inner.result.ownership == MutableShareI) + vassert(result.ownership == ImmutableBorrowI || result.ownership == ImmutableShareI) + inner match { + case SoftLoadIE(_, _, _) => { + // The SoftLoadIE should be immutabilifying on its own. + // We should have code that looks for this and simplifies it away. + vwat() + } + case _ => + } + + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +} + +case class PreCheckBorrowIE( + inner: ReferenceExpressionIE +) extends ReferenceExpressionIE { + vpass() + vassert(inner.result.ownership == MutableBorrowI) + + override def result: CoordI[cI] = inner.result + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +} + +case class ConsecutorIE( + exprs: Vector[ReferenceExpressionIE], + result: CoordI[cI] + ) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + // There shouldn't be a 0-element consecutor. + // If we want a consecutor that returns nothing, put a VoidLiteralIE in it. + vassert(exprs.nonEmpty) +} + +case class TupleIE( + elements: Vector[ReferenceExpressionIE], + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe = ReferenceResultI(resultReference) +} + +//// Discards a reference, whether it be owned or borrow or whatever. +//// This is used after panics or other never-returning things, to signal that a certain +//// variable should be considered gone. See AUMAP. +//// This can also be used if theres anything after a panic in a block, like +//// exported func main() int { +//// __panic(); +//// println("hi"); +//// } +//case class UnreachableMootIE(innerExpr: ReferenceExpressionIE) extends ReferenceExpressionIE { +// override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe = ReferenceResulIT(CoordI[cI](MutableShareI, NeverI())) +//} + +case class StaticArrayFromValuesIE( + elements: Vector[ReferenceExpressionIE], + resultReference: CoordI[cI], + arrayType: StaticSizedArrayIT[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + + override def result: CoordI[cI] = resultReference +} + +case class ArraySizeIE( + array: ReferenceExpressionIE, + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe = ReferenceResultI(CoordI[cI](MutableShareI, IntIT.i32)) +} + +// Can we do an === of objects in two regions? It could be pretty useful. +case class IsSameInstanceIE( + left: ReferenceExpressionIE, + right: ReferenceExpressionIE +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + vassert(left.result == right.result) + + override def result: CoordI[cI] = CoordI[cI](MutableShareI, BoolIT()) +} + +case class AsSubtypeIE( + sourceExpr: ReferenceExpressionIE, + targetType: CoordI[cI], + + // We could just calculaIE this, but it feels better to let the StructCompiler + // make it, so we're sure it's created. + resultResultType: CoordI[cI], + // Function to give a borrow ref to to make a Some(borrow ref) + okConstructor: PrototypeI[cI], + // Function to make a None of the right type + errConstructor: PrototypeI[cI], + + // This is the impl we use to allow/permit the downcast. It'll be useful for monomorphization. + implName: IdI[cI, IImplNameI[cI]], + + // These are the impls that we conceptually use to upcast the created Ok/Err to Result. + // Really they're here so the instantiator can know what impls it needs to instantiaIE. + okImplName: IdI[cI, IImplNameI[cI]], + errImplName: IdI[cI, IImplNameI[cI]], + + result: CoordI[cI] +) extends ReferenceExpressionIE { + vpass() + + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe = ReferenceResultI(resultResultType) +} + +case class VoidLiteralIE() extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + override def result: CoordI[cI] = CoordI[cI](MutableShareI, VoidIT()) +} + +case class ConstantIntIE(value: Long, bits: Int) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + override def result = CoordI[cI](MutableShareI, IntIT(bits)) +} + +case class ConstantBoolIE(value: Boolean) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + override def result = CoordI[cI](MutableShareI, BoolIT()) +} + +case class ConstantStrIE(value: String) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + override def result = CoordI[cI](MutableShareI, StrIT()) +} + +case class ConstantFloatIE(value: Double) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + override def result = CoordI[cI](MutableShareI, FloatIT()) +} + +case class LocalLookupIE( + // This is the local variable at the time it was created + localVariable: ILocalVariableI, +// // The instantiator might want to load this as a different region mutability than the mutability +// // when originally created, so tihs field will be able to hold that. +// // Conceptually, it's the current mutability of the source region at the time of the local lookup. +// pureHeight: Int, + // nevermind, we leave it to SoftLoad to figure out the target ownership/immutability + + // reference: CoordI[cI], + // variability: VariabilityI + result: CoordI[cI] +) extends AddressExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def variability: VariabilityI = localVariable.variability +} + +case class ArgLookupIE( + paramIndex: Int, + coord: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + override def result: CoordI[cI] = coord +} + +case class StaticSizedArrayLookupIE( + range: RangeS, + arrayExpr: ReferenceExpressionIE, + indexExpr: ReferenceExpressionIE, + // See RMLRMO for why this is the same ownership as the original field. + elementType: CoordI[cI], + // See RMLRMO for why we dont have a targetOwnership field here. + variability: VariabilityI +) extends AddressExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + + // See RMLRMO why we just return the element type. + override def result: CoordI[cI] = elementType +} + +case class RuntimeSizedArrayLookupIE( + arrayExpr: ReferenceExpressionIE, +// arrayType: RuntimeSizedArrayIT[cI], + indexExpr: ReferenceExpressionIE, + // See RMLRMO for why this is the same ownership as the original field. + elementType: CoordI[cI], + // See RMLRMO for why we dont have a targetOwnership field here. + variability: VariabilityI +) extends AddressExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// vassert(arrayExpr.result.kind == arrayType) + + // See RMLRMO why we just return the element type. + override def result: CoordI[cI] = elementType +} + +case class ArrayLengthIE(arrayExpr: ReferenceExpressionIE) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + override def result: CoordI[cI] = CoordI[cI](MutableShareI, IntIT(32)) +} + +case class ReferenceMemberLookupIE( + range: RangeS, + structExpr: ReferenceExpressionIE, + memberName: IVarNameI[cI], + // See RMLRMO for why this is the same ownership as the original field. + memberReference: CoordI[cI], + // See RMLRMO for why we dont have a targetOwnership field here. + variability: VariabilityI +) extends AddressExpressionIE { + vpass() + + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + + // See RMLRMO why we just return the member type. + override def result: CoordI[cI] = memberReference +} +case class AddressMemberLookupIE( + structExpr: ReferenceExpressionIE, + memberName: IVarNameI[cI], + // See RMLRMO for why this is the same ownership as the original field. + memberReference: CoordI[cI], + variability: VariabilityI +) extends AddressExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + + // See RMLRMO why we just return the member type. + override def result: CoordI[cI] = memberReference +} + +case class InterfaceFunctionCallIE( + superFunctionPrototype: PrototypeI[cI], + virtualParamIndex: Int, + args: Vector[ReferenceExpressionIE], + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe: CoordI[cI] = ReferenceResultI(resultReference) +} + +case class ExternFunctionCallIE( + prototype2: PrototypeI[cI], + args: Vector[ReferenceExpressionIE], + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + // We dont: + // vassert(prototype2.fullName.last.templateArgs.isEmpty) + // because we totally can have extern templates. + // Will one day be useful for plugins, and we already use it for + // lock, which is generated by the backend. + + prototype2.id.localName match { + case ExternFunctionNameI(_, _) => + case _ => vwat() + } + + + +// override def resultRemoveMe = ReferenceResultI(prototype2.returnType) +} + +case class FunctionCallIE( + callable: PrototypeI[cI], + args: Vector[ReferenceExpressionIE], + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + + vassert(callable.paramTypes.size == args.size) + args.map(_.result).zip(callable.paramTypes).foreach({ + case (CoordI(_, NeverIT(_)), _) => + case (a, b) => vassert(a == b) + }) + +// override def resultRemoveMe: CoordI[cI] = { +// ReferenceResultI(callable.returnType) +// } +} + +// A typingpass reinterpret is interpreting a type as a different one which is hammer-equivalent. +// For example, a pack and a struct are the same thing to hammer. +// Also, a closure and a struct are the same thing to hammer. +// But, Compiler attaches different meanings to these things. The typingpass is free to reinterpret +// between hammer-equivalent things as it wants. +case class ReinterpretIE( + expr: ReferenceExpressionIE, + resultReference: CoordI[cI], + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + vassert(expr.result != resultReference) + +// override def resultRemoveMe = ReferenceResultI(resultReference) + + expr.result.kind match { + // Unless it's a Never... + case NeverIT(_) => + case _ => { + if (resultReference.ownership != expr.result.ownership) { + // Cant reinterpret to a different ownership! + vfail("wat"); + } + } + } +} + +case class ConstructIE( + structTT: StructIT[cI], + result: CoordI[cI], + args: Vector[ExpressionI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + vpass() + +// override def resultRemoveMe = ReferenceResultI(resultReference) +} + +// NoIE: the functionpointercall's last argument is a Placeholder2, +// it's up to later stages to replace that with an actual index +case class NewMutRuntimeSizedArrayIE( + arrayType: RuntimeSizedArrayIT[cI], + capacityExpr: ReferenceExpressionIE, + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe: CoordI[cI] = { +// ReferenceResultI( +// CoordI[cI]( +// arrayType.mutability match { +// case MutableI => OwnI +// case ImmutableI => MutableShareI +// }, +// arrayType)) +// } +} + +case class StaticArrayFromCallableIE( + arrayType: StaticSizedArrayIT[cI], + generator: ReferenceExpressionIE, + generatorMethod: PrototypeI[cI], + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe: CoordI[cI] = { +// ReferenceResultI( +// CoordI[cI]( +// arrayType.mutability match { +// case MutableI => OwnI +// case ImmutableI => MutableShareI +// }, +// arrayType)) +// } +} + +// NoIE: the functionpointercall's last argument is a Placeholder2, +// it's up to later stages to replace that with an actual index +// This returns nothing, as opposed to DrainStaticSizedArray2 which returns a +// sequence of results from the call. +case class DestroyStaticSizedArrayIntoFunctionIE( + arrayExpr: ReferenceExpressionIE, + arrayType: StaticSizedArrayIT[cI], + consumer: ReferenceExpressionIE, + consumerMethod: PrototypeI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + vassert(consumerMethod.paramTypes.size == 2) +// vassert(consumerMethod.paramTypes(0) == consumer.result) + vassert(consumerMethod.paramTypes(1) == arrayType.elementType.coord) + + // See https://github.com/ValeLang/Vale/issues/375 + consumerMethod.returnType.kind match { + case StructIT(IdI(_, _, StructNameI(StructTemplateNameI(name), _))) => { + vassert(name.str == "Tup") + } + case VoidIT() => + case _ => vwat() + } + + override def result: CoordI[cI] = CoordI[cI](MutableShareI, VoidIT()) +} + +// We destroy both Share and Own things +// If the struct contains any addressibles, those die immediately and aren't stored +// in the destination variables, which is why it's a list of ReferenceLocalVariable2. +case class DestroyStaticSizedArrayIntoLocalsIE( + expr: ReferenceExpressionIE, + staticSizedArray: StaticSizedArrayIT[cI], + destinationReferenceVariables: Vector[ReferenceLocalVariableI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + override def result: CoordI[cI] = CoordI[cI](MutableShareI, VoidIT()) + + vassert(expr.result.kind == staticSizedArray) +} + +case class DestroyMutRuntimeSizedArrayIE( + arrayExpr: ReferenceExpressionIE +) extends ReferenceExpressionIE { + override def result: CoordI[cI] = CoordI[cI](MutableShareI, VoidIT()) +} + +case class RuntimeSizedArrayCapacityIE( + arrayExpr: ReferenceExpressionIE +) extends ReferenceExpressionIE { + override def result: CoordI[cI] = CoordI[cI](MutableShareI, IntIT(32)) +// override def resultRemoveMe: CoordI[cI] = ReferenceResultI(CoordI[cI](MutableShareI, IntIT(32))) +} + +case class PushRuntimeSizedArrayIE( + arrayExpr: ReferenceExpressionIE, + // arrayType: RuntimeSizedArrayIT[cI], + newElementExpr: ReferenceExpressionIE, + // newElementType: CoordI[cI] +) extends ReferenceExpressionIE { + override def result: CoordI[cI] = CoordI[cI](MutableShareI, VoidIT()) +} + +case class PopRuntimeSizedArrayIE( + arrayExpr: ReferenceExpressionIE, + result: CoordI[cI] +) extends ReferenceExpressionIE { + private val elementType = + arrayExpr.result.kind match { + case contentsRuntimeSizedArrayIT(_, e, _) => e + case other => vwat(other) + } +// override def resultRemoveMe: CoordI[cI] = ReferenceResultI(elementType) +} + +case class InterfaceToInterfaceUpcastIE( + innerExpr: ReferenceExpressionIE, + targetInterface: InterfaceIT[cI], + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// def result: ReferenceResultI = { +// ReferenceResultI( +// CoordI[cI]( +// innerExpr.result.ownership, +// targetInterface)) +// } +} + +// This used to be StructToInterfaceUpcastIE, and then we added generics. +// Now, it could be that we're upcasting a placeholder to an interface, or a +// placeholder to another placeholder. For all we know, this'll eventually be +// upcasting an int to an int. +// So, the target kind can be anything, not just an interface. +case class UpcastIE( + innerExpr: ReferenceExpressionIE, + targetSuperKind: InterfaceIT[cI], + // This is the impl we use to allow/permit the upcast. It'll be useful for monomorphization + // and later on for locating the itable ptr to put in fat pointers. + implName: IdI[cI, IImplNameI[cI]], + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// def result: ReferenceResultI = { +// ReferenceResultI( +// CoordI[cI]( +// innerExpr.result.ownership, +// targetSuperKind)) +// } +} + +// A soft load is one that turns an int&& into an int*. a hard load turns an int* into an int. +// Turns an Addressible(Pointer) into an OwningPointer. Makes the source owning pointer into null + +// If the source was an own and target is borrow, that's a point + +case class SoftLoadIE( + expr: AddressExpressionIE, + targetOwnership: OwnershipI, + result: CoordI[cI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + + vassert(targetOwnership == result.ownership) + + if (targetOwnership == MutableShareI) { + vassert(expr.result.ownership != ImmutableShareI) + } + vassert(targetOwnership != OwnI) // need to unstackify or destroy to get an owning reference + // This is just here to try the asserts inside Coord's constructor + CoordI[cI](targetOwnership, expr.result.kind) + + result.kind match { + case IntIT(_) | BoolIT() | FloatIT() => { + vassert(targetOwnership == MutableShareI) + } + case _ => + } + +// override def resultRemoveMe: CoordI[cI] = { +// ReferenceResultI(CoordI[cI](targetOwnership, expr.result.kind)) +// } +} + +// Destroy an object. +// If the struct contains any addressibles, those die immediately and aren't stored +// in the destination variables, which is why it's a list of ReferenceLocalVariable2. +// +// We also destroy shared things with this, see DDSOT. +case class DestroyIE( + expr: ReferenceExpressionIE, + structTT: StructIT[cI], + destinationReferenceVariables: Vector[ReferenceLocalVariableI] +) extends ReferenceExpressionIE { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + override def result: CoordI[cI] = CoordI[cI](MutableShareI, VoidIT()) +} + +case class DestroyImmRuntimeSizedArrayIE( + arrayExpr: ReferenceExpressionIE, + arrayType: RuntimeSizedArrayIT[cI], + consumer: ReferenceExpressionIE, + consumerMethod: PrototypeI[cI] +) extends ReferenceExpressionIE { + arrayType.mutability match { + case ImmutableI => + case _ => vwat() + } + + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + vassert(consumerMethod.paramTypes.size == 2) + vassert(consumerMethod.paramTypes(0) == consumer.result) + // vassert(consumerMethod.paramTypes(1) == Program2.intType) + vassert(consumerMethod.paramTypes(1) == arrayType.elementType.coord) + + // See https://github.com/ValeLang/Vale/issues/375 + consumerMethod.returnType.kind match { + case VoidIT() => + } + + override def result: CoordI[cI] = CoordI[cI](MutableShareI, VoidIT()) +} + +// NoIE: the functionpointercall's last argument is a Placeholder2, +// it's up to later stages to replace that with an actual index +case class NewImmRuntimeSizedArrayIE( + arrayType: RuntimeSizedArrayIT[cI], + sizeExpr: ReferenceExpressionIE, + generator: ReferenceExpressionIE, + generatorMethod: PrototypeI[cI], + result: CoordI[cI] +) extends ReferenceExpressionIE { + arrayType.mutability match { + case ImmutableI => + case _ => vwat() + } + // We dont want to own the generator + generator.result.ownership match { + case MutableBorrowI | ImmutableBorrowI | ImmutableShareI | MutableShareI => + case other => vwat(other) + } + generatorMethod.returnType.ownership match { + case ImmutableShareI | MutableShareI => + case other => vwat(other) + } + + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() +// override def resultRemoveMe: CoordI[cI] = { +// ReferenceResultI( +// CoordI[cI]( +// arrayType.mutability match { +// case MutableI => OwnI +// case ImmutableI => MutableShareI +// }, +// arrayType)) +// } +} + +object referenceExprResultStructName { + def unapply(expr: ReferenceExpressionIE): Option[StrI] = { + expr.result.kind match { + case StructIT(IdI(_, _, StructNameI(StructTemplateNameI(name), _))) => Some(name) + case _ => None + } + } +} + +object referenceExprResultKind { + def unapply(expr: ReferenceExpressionIE): Option[KindIT[cI]] = { + Some(expr.result.kind) + } +} diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/names.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/names.scala new file mode 100644 index 000000000..cb2dd97b5 --- /dev/null +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/names.scala @@ -0,0 +1,625 @@ +package dev.vale.instantiating.ast + +import dev.vale._ +import dev.vale.instantiating.ast.ITemplataI._ +import dev.vale.postparsing._ +import dev.vale.typing.types.CoordT + +// Scout's/Astronomer's name parts correspond to where they are in the source code, +// but Compiler's correspond more to what packages and stamped functions / structs +// they're in. See TNAD. + +case class IdI[+R <: IRegionsModeI, +I <: INameI[R]]( + packageCoord: PackageCoordinate, + initSteps: Vector[INameI[R]], + localName: I +) { + // PackageTopLevelName2 is just here because names have to have a last step. + vassert(initSteps.collectFirst({ case PackageTopLevelNameI() => }).isEmpty) + + vcurious(initSteps.distinct == initSteps) + + override def equals(obj: Any): Boolean = { + obj match { + case IdI(thatPackageCoord, thatInitSteps, thatLast) => { + packageCoord == thatPackageCoord && initSteps == thatInitSteps && localName == thatLast + } + case _ => false + } + } + + def packageFullName: IdI[R, PackageTopLevelNameI[R]] = { + IdI(packageCoord, Vector(), PackageTopLevelNameI()) + } + + def initFullName: IdI[R, INameI[R]] = { + if (initSteps.isEmpty) { + IdI(packageCoord, Vector(), PackageTopLevelNameI()) + } else { + IdI(packageCoord, initSteps.init, initSteps.last) + } + } + + def initNonPackageFullName(): Option[IdI[R, INameI[R]]] = { + if (initSteps.isEmpty) { + None + } else { + Some(IdI(packageCoord, initSteps.init, initSteps.last)) + } + } + + def steps: Vector[INameI[R]] = { + localName match { + case PackageTopLevelNameI() => initSteps + case _ => initSteps :+ localName + } + } +} + +object INameI { + def addStep[R <: IRegionsModeI, I <: INameI[R], Y <: INameI[R]](old: IdI[R, I], newLast: Y): IdI[R, Y] = { + IdI[R, Y](old.packageCoord, old.steps, newLast) + } +} + +sealed trait INameI[+R <: IRegionsModeI] +sealed trait ITemplateNameI[+R <: IRegionsModeI] extends INameI[R] +sealed trait IFunctionTemplateNameI[+R <: IRegionsModeI] extends ITemplateNameI[R] { +// def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplataI[R]], params: Vector[CoordI]): IFunctionNameI +} +sealed trait IInstantiationNameI[+R <: IRegionsModeI] extends INameI[R] { + def template: ITemplateNameI[R] + def templateArgs: Vector[ITemplataI[R]] +} +sealed trait IFunctionNameI[+R <: IRegionsModeI] extends IInstantiationNameI[R] { + def template: IFunctionTemplateNameI[R] + def templateArgs: Vector[ITemplataI[R]] + def parameters: Vector[CoordI[R]] +} +sealed trait ISuperKindTemplateNameI[+R <: IRegionsModeI] extends ITemplateNameI[R] +sealed trait ISubKindTemplateNameI[+R <: IRegionsModeI] extends ITemplateNameI[R] +sealed trait ICitizenTemplateNameI[+R <: IRegionsModeI] extends ISubKindTemplateNameI[R] { +// def makeCitizenName(templateArgs: Vector[ITemplataI[R]]): ICitizenNameI +} +sealed trait IStructTemplateNameI[+R <: IRegionsModeI] extends ICitizenTemplateNameI[R] { +// def makeStructName(templateArgs: Vector[ITemplataI[R]]): IStructNameI +// override def makeCitizenName(templateArgs: Vector[ITemplataI[R]]): +// ICitizenNameI = { +// makeStructName(templateArgs) +// } +} +sealed trait IInterfaceTemplateNameI[+R <: IRegionsModeI] extends ICitizenTemplateNameI[R] with ISuperKindTemplateNameI[R] { +// def makeInterfaceName(templateArgs: Vector[ITemplataI[R]]): IInterfaceNameI +} +sealed trait ISuperKindNameI[+R <: IRegionsModeI] extends IInstantiationNameI[R] { + def template: ISuperKindTemplateNameI[R] + def templateArgs: Vector[ITemplataI[R]] +} +sealed trait ISubKindNameI[+R <: IRegionsModeI] extends IInstantiationNameI[R] { + def template: ISubKindTemplateNameI[R] + def templateArgs: Vector[ITemplataI[R]] +} +sealed trait ICitizenNameI[+R <: IRegionsModeI] extends ISubKindNameI[R] { + def template: ICitizenTemplateNameI[R] + def templateArgs: Vector[ITemplataI[R]] +} +sealed trait IStructNameI[+R <: IRegionsModeI] extends ICitizenNameI[R] with ISubKindNameI[R] { + override def template: IStructTemplateNameI[R] + override def templateArgs: Vector[ITemplataI[R]] +} +sealed trait IInterfaceNameI[+R <: IRegionsModeI] extends ICitizenNameI[R] with ISubKindNameI[R] with ISuperKindNameI[R] { + override def template: IInterfaceTemplateNameI[R] + override def templateArgs: Vector[ITemplataI[R]] +} +sealed trait IImplTemplateNameI[+R <: IRegionsModeI] extends ITemplateNameI[R] { +// def makeImplName(templateArgs: Vector[ITemplataI[R]], subCitizen: ICitizenIT): IImplNameI +} +sealed trait IImplNameI[+R <: IRegionsModeI] extends IInstantiationNameI[R] { + def template: IImplTemplateNameI[R] +} + +sealed trait IRegionNameI[+R <: IRegionsModeI] extends INameI[R] + +case class RegionNameI[+R <: IRegionsModeI](rune: IRuneS) extends IRegionNameI[R] +case class DenizenDefaultRegionNameI[+R <: IRegionsModeI]() extends IRegionNameI[R] + +case class ExportTemplateNameI[+R <: IRegionsModeI](codeLoc: CodeLocationS) extends ITemplateNameI[R] +case class ExportNameI[+R <: IRegionsModeI]( + template: ExportTemplateNameI[R], + region: RegionTemplataI[R] +) extends IInstantiationNameI[R] { + override def templateArgs: Vector[ITemplataI[R]] = Vector(region) +} + +case class ExternTemplateNameI[+R <: IRegionsModeI](codeLoc: CodeLocationS) extends ITemplateNameI[R] +case class ExternNameI[+R <: IRegionsModeI]( + template: ExternTemplateNameI[R], + region: RegionTemplataI[R] +) extends IInstantiationNameI[R] { + override def templateArgs: Vector[ITemplataI[R]] = Vector(region) +} + +case class ImplTemplateNameI[+R <: IRegionsModeI](codeLocationS: CodeLocationS) extends IImplTemplateNameI[R] { + vpass() +// override def makeImplName(templateArgs: Vector[ITemplataI[R]], subCitizen: ICitizenIT): ImplNameI = { +// ImplNameI(this, templateArgs, subCitizen) +// } +} +case class ImplNameI[+R <: IRegionsModeI]( + template: IImplTemplateNameI[R], + templateArgs: Vector[ITemplataI[R]], + // The instantiator wants this so it can know the struct type up-front before monomorphizing the + // whole impl, so it can hoist some bounds out of the struct, like NBIFP. + subCitizen: ICitizenIT[R] +) extends IImplNameI[R] { + vpass() +} + +case class ImplBoundTemplateNameI[+R <: IRegionsModeI](codeLocationS: CodeLocationS) extends IImplTemplateNameI[R] { +// override def makeImplName(templateArgs: Vector[ITemplataI[R]], subCitizen: ICitizenIT): ImplBoundNameI = { +// ImplBoundNameI(this, templateArgs) +// } +} +case class ImplBoundNameI[+R <: IRegionsModeI]( + template: ImplBoundTemplateNameI[R], + templateArgs: Vector[ITemplataI[R]] +) extends IImplNameI[R] { + +} + +//// The name of an impl that is subclassing some interface. To find all impls subclassing an interface, +//// look for this name. +//case class ImplImplementingSuperInterfaceNameI[+R <: IRegionsModeI](superInterface: FullNameI[IInterfaceTemplateNameI]) extends IImplTemplateNameI +//// The name of an impl that is augmenting some sub citizen. To find all impls subclassing an interface, +//// look for this name. +//case class ImplAugmentingSubCitizenNameI[+R <: IRegionsModeI](subCitizen: FullNameI[ICitizenTemplateNameI]) extends IImplTemplateNameI + +case class LetNameI[+R <: IRegionsModeI](codeLocation: CodeLocationS) extends INameI[R] +case class ExportAsNameI[+R <: IRegionsModeI](codeLocation: CodeLocationS) extends INameI[R] + +case class RawArrayNameI[+R <: IRegionsModeI]( + mutability: MutabilityI, + elementType: CoordTemplataI[R], + selfRegion: RegionTemplataI[R] +) extends INameI[R] { +} + +case class ReachablePrototypeNameI[+R <: IRegionsModeI](num: Int) extends INameI[R] + +case class StaticSizedArrayTemplateNameI[+R <: IRegionsModeI]() extends ICitizenTemplateNameI[R] { +// override def makeCitizenName(templateArgs: Vector[ITemplataI[R]]): ICitizenNameI = { +// vassert(templateArgs.size == 5) +// val size = expectIntegerTemplata(templateArgs(0)).value +// val mutability = expectMutabilityTemplata(templateArgs(1)).mutability +// val variability = expectVariabilityTemplata(templateArgs(2)).variability +// val elementType = expectCoordTemplata(templateArgs(3)).coord +// val selfRegion = expectRegionTemplata(templateArgs(4)) +// StaticSizedArrayNameI(this, size, variability, RawArrayNameI(mutability, elementType, selfRegion)) +// } +} + +case class StaticSizedArrayNameI[+R <: IRegionsModeI]( + template: StaticSizedArrayTemplateNameI[R], + size: Long, + variability: VariabilityI, + arr: RawArrayNameI[R] +) extends ICitizenNameI[R] { + + override def templateArgs: Vector[ITemplataI[R]] = { + Vector( + IntegerTemplataI(size), + MutabilityTemplataI(arr.mutability), + VariabilityTemplataI(variability), + arr.elementType) + } +} + +case class RuntimeSizedArrayTemplateNameI[+R <: IRegionsModeI]() extends ICitizenTemplateNameI[R] { +// override def makeCitizenName(templateArgs: Vector[ITemplataI[R]]): ICitizenNameI = { +// vassert(templateArgs.size == 3) +// val mutability = expectMutabilityTemplata(templateArgs(0)).mutability +// val elementType = expectCoordTemplata(templateArgs(1)).coord +// val region = expectRegionTemplata(templateArgs(2)) +// RuntimeSizedArrayNameI(this, RawArrayNameI(mutability, elementType, region)) +// } +} + +case class RuntimeSizedArrayNameI[+R <: IRegionsModeI]( + template: RuntimeSizedArrayTemplateNameI[R], + arr: RawArrayNameI[R] +) extends ICitizenNameI[R] { + override def templateArgs: Vector[ITemplataI[R]] = { + Vector( + MutabilityTemplataI(arr.mutability), + arr.elementType) + } +} + +// See NNSPAFOC. +case class OverrideDispatcherTemplateNameI[+R <: IRegionsModeI]( + implId: IdI[R, IImplTemplateNameI[R]] +) extends IFunctionTemplateNameI[R] { +// override def makeFunctionName( +// interner: Interner, +// keywords: Keywords, +// templateArgs: Vector[ITemplataI[R]], +// params: Vector[CoordI]): +// OverrideDispatcherNameI = { +// interner.intern(OverrideDispatcherNameI(this, templateArgs, params)) +// } +} + +case class OverrideDispatcherNameI[+R <: IRegionsModeI]( + template: OverrideDispatcherTemplateNameI[R], + // This will have placeholders in it after the typing pass. + templateArgs: Vector[ITemplataI[R]], + parameters: Vector[CoordI[R]] +) extends IFunctionNameI[R] { + vpass() +} + +case class OverrideDispatcherCaseNameI[+R <: IRegionsModeI]( + // These are the templatas for the independent runes from the impl, like the for Milano, see + // OMCNAGP. + independentImplTemplateArgs: Vector[ITemplataI[R]] +) extends ITemplateNameI[R] with IInstantiationNameI[R] { + override def template: ITemplateNameI[R] = this + override def templateArgs: Vector[ITemplataI[R]] = independentImplTemplateArgs +} + +sealed trait IVarNameI[+R <: IRegionsModeI] extends INameI[R] +case class TypingPassBlockResultVarNameI[+R <: IRegionsModeI](life: LocationInFunctionEnvironmentI) extends IVarNameI[R] +case class TypingPassFunctionResultVarNameI[+R <: IRegionsModeI]() extends IVarNameI[R] +case class TypingPassTemporaryVarNameI[+R <: IRegionsModeI](life: LocationInFunctionEnvironmentI) extends IVarNameI[R] +case class TypingPassPatternMemberNameI[+R <: IRegionsModeI](life: LocationInFunctionEnvironmentI) extends IVarNameI[R] +case class TypingIgnoredParamNameI[+R <: IRegionsModeI](num: Int) extends IVarNameI[R] +case class TypingPassPatternDestructureeNameI[+R <: IRegionsModeI](life: LocationInFunctionEnvironmentI) extends IVarNameI[R] +case class UnnamedLocalNameI[+R <: IRegionsModeI](codeLocation: CodeLocationS) extends IVarNameI[R] +case class ClosureParamNameI[+R <: IRegionsModeI](codeLocation: CodeLocationS) extends IVarNameI[R] +case class ConstructingMemberNameI[+R <: IRegionsModeI](name: StrI) extends IVarNameI[R] +case class WhileCondResultNameI[+R <: IRegionsModeI](range: RangeS) extends IVarNameI[R] +case class IterableNameI[+R <: IRegionsModeI](range: RangeS) extends IVarNameI[R] { } +case class IteratorNameI[+R <: IRegionsModeI](range: RangeS) extends IVarNameI[R] { } +case class IterationOptionNameI[+R <: IRegionsModeI](range: RangeS) extends IVarNameI[R] { } +case class MagicParamNameI[+R <: IRegionsModeI](codeLocation2: CodeLocationS) extends IVarNameI[R] +case class CodeVarNameI[+R <: IRegionsModeI](name: StrI) extends IVarNameI[R] +// We dont use CodeVarName2(0), CodeVarName2(1) etc because we dont want the user to address these members directly. +case class AnonymousSubstructMemberNameI[+R <: IRegionsModeI](index: Int) extends IVarNameI[R] +case class PrimitiveNameI[+R <: IRegionsModeI](humanName: StrI) extends INameI[R] +// Only made in typingpass +case class PackageTopLevelNameI[+R <: IRegionsModeI]() extends INameI[R] +case class ProjectNameI[+R <: IRegionsModeI](name: StrI) extends INameI[R] +case class PackageNameI[+R <: IRegionsModeI](name: StrI) extends INameI[R] +case class RuneNameI[+R <: IRegionsModeI](rune: IRuneS) extends INameI[R] + +// This is the name of a function that we're still figuring out in the function typingpass. +// We have its closured variables, but are still figuring out its template args and params. +case class BuildingFunctionNameWithClosuredsI[+R <: IRegionsModeI]( + templateName: IFunctionTemplateNameI[R], +) extends INameI[R] { + + + +} + +case class ExternFunctionNameI[+R <: IRegionsModeI]( + humanName: StrI, + parameters: Vector[CoordI[R]] +) extends IFunctionNameI[R] with IFunctionTemplateNameI[R] { + override def template: IFunctionTemplateNameI[R] = this + +// override def makeFunctionName( +// interner: Interner, +// keywords: Keywords, +// templateArgs: Vector[ITemplataI[R]], +// params: Vector[CoordI]): +// IFunctionNameI = this + + override def templateArgs: Vector[ITemplataI[R]] = Vector.empty +} + +case class FunctionNameIX[+R <: IRegionsModeI]( + template: FunctionTemplateNameI[R], + templateArgs: Vector[ITemplataI[R]], + parameters: Vector[CoordI[R]] +) extends IFunctionNameI[R] + +case class ForwarderFunctionNameI[+R <: IRegionsModeI]( + template: ForwarderFunctionTemplateNameI[R], + inner: IFunctionNameI[R] +) extends IFunctionNameI[R] { + override def templateArgs: Vector[ITemplataI[R]] = inner.templateArgs + override def parameters: Vector[CoordI[R]] = inner.parameters +} + +case class FunctionBoundTemplateNameI[+R <: IRegionsModeI]( + humanName: StrI, + codeLocation: CodeLocationS +) extends INameI[R] with IFunctionTemplateNameI[R] { +// override def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplataI[R]], params: Vector[CoordI]): FunctionBoundNameI = { +// interner.intern(FunctionBoundNameI(this, templateArgs, params)) +// } +} + +case class FunctionBoundNameI[+R <: IRegionsModeI]( + template: FunctionBoundTemplateNameI[R], + templateArgs: Vector[ITemplataI[R]], + parameters: Vector[CoordI[R]] +) extends IFunctionNameI[R] + +case class FunctionTemplateNameI[+R <: IRegionsModeI]( + humanName: StrI, + codeLocation: CodeLocationS +) extends INameI[R] with IFunctionTemplateNameI[R] { + vpass() +// override def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplataI[R]], params: Vector[CoordI]): IFunctionNameI = { +// interner.intern(FunctionNameI(this, templateArgs, params)) +// } +} + +case class LambdaCallFunctionTemplateNameI[+R <: IRegionsModeI]( + codeLocation: CodeLocationS, + paramTypes: Vector[CoordT] +) extends INameI[R] with IFunctionTemplateNameI[R] { +// override def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplataI[R]], params: Vector[CoordI]): IFunctionNameI = { +// // Post instantiator, the params will be real, but our template paramTypes will still be placeholders +// // vassert(params == paramTypes) +// interner.intern(LambdaCallFunctionNameI(this, templateArgs, params)) +// } +} + +case class LambdaCallFunctionNameI[+R <: IRegionsModeI]( + template: LambdaCallFunctionTemplateNameI[R], + templateArgs: Vector[ITemplataI[R]], + parameters: Vector[CoordI[R]] +) extends IFunctionNameI[R] + +case class ForwarderFunctionTemplateNameI[+R <: IRegionsModeI]( + inner: IFunctionTemplateNameI[R], + index: Int +) extends INameI[R] with IFunctionTemplateNameI[R] { +// override def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplataI[R]], params: Vector[CoordI]): IFunctionNameI = { +// interner.intern(ForwarderFunctionNameI(this, inner.makeFunctionName(keywords, templateArgs, params)))//, index)) +// } +} + + +//case class AbstractVirtualDropFunctionTemplateNameI[+R <: IRegionsModeI]( +// implName: INameI[R] +//) extends INameI[R] with IFunctionTemplateNameI { +// override def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplata[ITemplataType]], params: Vector[CoordI]): IFunctionNameI = { +// interner.intern( +// AbstractVirtualDropFunctionNameI(implName, templateArgs, params)) +// } +//} + +//case class AbstractVirtualDropFunctionNameI[+R <: IRegionsModeI]( +// implName: INameI[R], +// templateArgs: Vector[ITemplata[ITemplataType]], +// parameters: Vector[CoordI] +//) extends INameI[R] with IFunctionNameI + +//case class OverrideVirtualDropFunctionTemplateNameI[+R <: IRegionsModeI]( +// implName: INameI[R] +//) extends INameI[R] with IFunctionTemplateNameI { +// override def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplata[ITemplataType]], params: Vector[CoordI]): IFunctionNameI = { +// interner.intern( +// OverrideVirtualDropFunctionNameI(implName, templateArgs, params)) +// } +//} + +//case class OverrideVirtualDropFunctionNameI[+R <: IRegionsModeI]( +// implName: INameI[R], +// templateArgs: Vector[ITemplata[ITemplataType]], +// parameters: Vector[CoordI] +//) extends INameI[R] with IFunctionNameI + +//case class LambdaTemplateNameI[+R <: IRegionsModeI]( +// codeLocation: CodeLocationS +//) extends INameI[R] with IFunctionTemplateNameI { +// override def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplata[ITemplataType]], params: Vector[CoordI]): IFunctionNameI = { +// interner.intern(FunctionNameI(interner.intern(FunctionTemplateNameI(keywords.underscoresCall, codeLocation)), templateArgs, params)) +// } +//} +case class ConstructorTemplateNameI[+R <: IRegionsModeI]( + codeLocation: CodeLocationS +) extends INameI[R] with IFunctionTemplateNameI[R] { +// override def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplataI[R]], params: Vector[CoordI]): IFunctionNameI = vimpl() +} + +//case class FreeTemplateNameI[+R <: IRegionsModeI](codeLoc: CodeLocationS) extends INameI[R] with IFunctionTemplateNameI { +// vpass() +// override def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplata[ITemplataType]], params: Vector[CoordI]): IFunctionNameI = { +// params match { +// case Vector(coord) => { +// interner.intern(FreeNameI(this, templateArgs, coord)) +// } +// case other => vwat(other) +// } +// } +//} +//case class FreeNameI[+R <: IRegionsModeI]( +// template: FreeTemplateNameI, +// templateArgs: Vector[ITemplata[ITemplataType]], +// coordT: CoordI +//) extends IFunctionNameI { +// override def parameters: Vector[CoordI] = Vector(coordI) +//} + +//// See NSIDN for why we have these virtual names +//case class AbstractVirtualFreeTemplateNameI[+R <: IRegionsModeI](codeLoc: CodeLocationS) extends INameI[R] with IFunctionTemplateNameI { +// override def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplata[ITemplataType]], params: Vector[CoordI]): IFunctionNameI = { +// val Vector(CoordI(ShareI, kind)) = params +// interner.intern(AbstractVirtualFreeNameI(templateArgs, kind)) +// } +//} +//// See NSIDN for why we have these virtual names +//case class AbstractVirtualFreeNameI[+R <: IRegionsModeI](templateArgs: Vector[ITemplata[ITemplataType]], param: KindI) extends IFunctionNameI { +// override def parameters: Vector[CoordI] = Vector(CoordI(ShareI, param)) +//} +// +//// See NSIDN for why we have these virtual names +//case class OverrideVirtualFreeTemplateNameI[+R <: IRegionsModeI](codeLoc: CodeLocationS) extends INameI[R] with IFunctionTemplateNameI { +// override def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplata[ITemplataType]], params: Vector[CoordI]): IFunctionNameI = { +// val Vector(CoordI(ShareI, kind)) = params +// interner.intern(OverrideVirtualFreeNameI(templateArgs, kind)) +// } +//} +//// See NSIDN for why we have these virtual names +//case class OverrideVirtualFreeNameI[+R <: IRegionsModeI](templateArgs: Vector[ITemplata[ITemplataType]], param: KindI) extends IFunctionNameI { +// override def parameters: Vector[CoordI] = Vector(CoordI(ShareI, param)) +//} + +// Vale has no Self, its just a convenient first name parameter. +// See also SelfNameS. +case class SelfNameI[+R <: IRegionsModeI]() extends IVarNameI[R] +case class ArbitraryNameI[+R <: IRegionsModeI]() extends INameI[R] + +sealed trait CitizenNameI[+R <: IRegionsModeI] extends ICitizenNameI[R] { + def template: ICitizenTemplateNameI[R] + def templateArgs: Vector[ITemplataI[R]] +} + +object CitizenNameI { + def unapply[R <: IRegionsModeI](c: CitizenNameI[R]): Option[(ICitizenTemplateNameI[R], Vector[ITemplataI[R]])] = { + c match { + case StructNameI(template, templateArgs) => Some((template, templateArgs)) + case InterfaceNameI(template, templateArgs) => Some((template, templateArgs)) + } + } +} + +case class StructNameI[+R <: IRegionsModeI]( + template: IStructTemplateNameI[R], + templateArgs: Vector[ITemplataI[R]] +) extends IStructNameI[R] with CitizenNameI[R] { + vpass() +} + +case class InterfaceNameI[+R <: IRegionsModeI]( + template: IInterfaceTemplateNameI[R], + templateArgs: Vector[ITemplataI[R]] +) extends IInterfaceNameI[R] with CitizenNameI[R] { + vpass() +} + +case class LambdaCitizenTemplateNameI[+R <: IRegionsModeI]( + codeLocation: CodeLocationS +) extends IStructTemplateNameI[R] { +// override def makeStructName(templateArgs: Vector[ITemplataI[R]]): IStructNameI = { +// vassert(templateArgs.isEmpty) +// interner.intern(LambdaCitizenNameI(this)) +// } +} + +case class LambdaCitizenNameI[+R <: IRegionsModeI]( + template: LambdaCitizenTemplateNameI[R] +) extends IStructNameI[R] { + def templateArgs: Vector[ITemplataI[R]] = Vector.empty + vpass() +} + +sealed trait CitizenTemplateNameI[+R <: IRegionsModeI] extends ICitizenTemplateNameI[R] { + def humanName: StrI + // We don't include a CodeLocation here because: + // - There's no struct overloading, so there should only ever be one, we don't have to disambiguate + // with code locations + // - It makes it easier to determine the CitizenTemplateNameI from a CitizenNameI which doesn't + // remember its code location. + //codeLocation: CodeLocationS + +// override def makeCitizenName(templateArgs: Vector[ITemplata[ITemplataType]]): ICitizenNameI = { +// interner.intern(CitizenNameI(this, templateArgs)) +// } +} + +case class StructTemplateNameI[+R <: IRegionsModeI]( + humanName: StrI, + // We don't include a CodeLocation here because: + // - There's no struct overloading, so there should only ever be one, we don't have to disambiguate + // with code locations + // - It makes it easier to determine the StructTemplateNameI from a StructNameI which doesn't + // remember its code location. + // (note from later: not sure this is true anymore, since StructNameI contains a StructTemplateNameI) + //codeLocation: CodeLocationS +) extends IStructTemplateNameI[R] with CitizenTemplateNameI[R] { + vpass() + +// override def makeStructName(templateArgs: Vector[ITemplataI[R]]): IStructNameI = { +// interner.intern(StructNameI(this, templateArgs)) +// } +} +case class InterfaceTemplateNameI[+R <: IRegionsModeI]( + humanNamee: StrI, + // We don't include a CodeLocation here because: + // - There's no struct overloading, so there should only ever be one, we don't have to disambiguate + // with code locations + // - It makes it easier to determine the InterfaceTemplateNameI from a InterfaceNameI which doesn't + // remember its code location. + //codeLocation: CodeLocationS +) extends IInterfaceTemplateNameI[R] with CitizenTemplateNameI[R] with ICitizenTemplateNameI[R] { + override def humanName = humanNamee +// override def makeInterfaceName(templateArgs: Vector[ITemplataI[R]]): IInterfaceNameI = { +// interner.intern(InterfaceNameI(this, templateArgs)) +// } +// override def makeCitizenName(templateArgs: Vector[ITemplataI[R]]): ICitizenNameI = { +// makeInterfaceName(templateArgs) +// } +} + +case class AnonymousSubstructImplTemplateNameI[+R <: IRegionsModeI]( + interface: IInterfaceTemplateNameI[R] +) extends IImplTemplateNameI[R] { +// override def makeImplName(templateArgs: Vector[ITemplataI[R]], subCitizen: ICitizenIT): IImplNameI = { +// AnonymousSubstructImplNameI(this, templateArgs, subCitizen) +// } +} +case class AnonymousSubstructImplNameI[+R <: IRegionsModeI]( + template: AnonymousSubstructImplTemplateNameI[R], + templateArgs: Vector[ITemplataI[R]], + subCitizen: ICitizenIT[R] +) extends IImplNameI[R] + + +case class AnonymousSubstructTemplateNameI[+R <: IRegionsModeI]( + // This happens to be the same thing that appears before this AnonymousSubstructNameI in a FullNameT. + // This is really only here to help us calculate the imprecise name for this thing. + interface: IInterfaceTemplateNameI[R] +) extends IStructTemplateNameI[R] { +// override def makeStructName(templateArgs: Vector[ITemplataI[R]]): IStructNameI = { +// interner.intern(AnonymousSubstructNameI(this, templateArgs)) +// } +} +case class AnonymousSubstructConstructorTemplateNameI[+R <: IRegionsModeI]( + substruct: ICitizenTemplateNameI[R] +) extends IFunctionTemplateNameI[R] { +// override def makeFunctionName(keywords: Keywords, templateArgs: Vector[ITemplataI[R]], params: Vector[CoordI]): IFunctionNameI = { +// interner.intern(AnonymousSubstructConstructorNameI(this, templateArgs, params)) +// } +} + +case class AnonymousSubstructConstructorNameI[+R <: IRegionsModeI]( + template: AnonymousSubstructConstructorTemplateNameI[R], + templateArgs: Vector[ITemplataI[R]], + parameters: Vector[CoordI[R]] +) extends IFunctionNameI[R] + +case class AnonymousSubstructNameI[+R <: IRegionsModeI]( + // This happens to be the same thing that appears before this AnonymousSubstructNameI in a FullNameT. + // This is really only here to help us calculate the imprecise name for this thing. + template: AnonymousSubstructTemplateNameI[R], + templateArgs: Vector[ITemplataI[R]] +) extends IStructNameI[R] { + +} +//case class AnonymousSubstructImplNameI[+R <: IRegionsModeI]() extends INameI[R] { +// +//} + +case class ResolvingEnvNameI[+R <: IRegionsModeI]() extends INameI[R] { + vpass() +} + +case class CallEnvNameI[+R <: IRegionsModeI]() extends INameI[R] { + vpass() +} diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/templata.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/templata.scala new file mode 100644 index 000000000..e021b6b59 --- /dev/null +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/templata.scala @@ -0,0 +1,243 @@ +package dev.vale.instantiating.ast + +import dev.vale.postparsing._ +import dev.vale.typing.env._ +import dev.vale.typing.names._ +import dev.vale.typing.types._ +import dev.vale.{RangeS, StrI, vassert, vfail, vimpl, vpass, vwat} +import dev.vale.highertyping._ +import dev.vale.typing.ast._ +import dev.vale.typing.env._ +import dev.vale.typing.types._ + +import scala.collection.immutable.List + + +object ITemplataI { + def expectCoord[R <: IRegionsModeI](templata: ITemplataI[R]): ITemplataI[R] = { + templata match { + case t @ CoordTemplataI(_, _) => t + case other => vfail(other) + } + } + + def expectCoordTemplata[R <: IRegionsModeI](templata: ITemplataI[R]): CoordTemplataI[R] = { + templata match { + case t @ CoordTemplataI(_, _) => t + case other => vfail(other) + } + } + + def expectIntegerTemplata[R <: IRegionsModeI](templata: ITemplataI[R]): IntegerTemplataI[R] = { + templata match { + case t @ IntegerTemplataI(_) => t + case _ => vfail() + } + } + + def expectMutabilityTemplata[R <: IRegionsModeI](templata: ITemplataI[R]): MutabilityTemplataI[R] = { + templata match { + case t @ MutabilityTemplataI(_) => t + case _ => vfail() + } + } + + def expectVariabilityTemplata[R <: IRegionsModeI](templata: ITemplataI[R]): VariabilityTemplataI[R] = { + templata match { + case t @ VariabilityTemplataI(_) => t + case _ => vfail() + } + } + + def expectKind[R <: IRegionsModeI](templata: ITemplataI[R]): ITemplataI[R] = { + templata match { + case t @ KindTemplataI(_) => t + case _ => vfail() + } + } + + def expectKindTemplata[R <: IRegionsModeI](templata: ITemplataI[R]): KindTemplataI[R] = { + templata match { + case t @ KindTemplataI(_) => t + case _ => vfail() + } + } + + def expectRegionTemplata[R <: IRegionsModeI](templata: ITemplataI[R]): RegionTemplataI[R] = { + templata match { + case t @ RegionTemplataI(_) => t + case _ => vfail() + } + } + +} + +sealed trait ITemplataI[+R <: IRegionsModeI] { + def expectCoordTemplata(): CoordTemplataI[R] = { + this match { + case c@CoordTemplataI(_, _) => c + case other => vwat(other) + } + } + + def expectRegionTemplata(): RegionTemplataI[R] = { + this match { + case c@RegionTemplataI(_) => c + case other => vwat(other) + } + } +} + +//// The typing phase never makes one of these, they're purely abstract and conceptual in the +//// typing phase. The monomorphizer is the one that actually makes these templatas. +//case class RegionTemplataI[+R <: IRegionsModeI](pureHeight: Int) extends ITemplataI[R] { +// vpass() +// val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; +// +//} + +case class CoordTemplataI[+R <: IRegionsModeI]( + region: RegionTemplataI[R], + coord: CoordI[R] +) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + + this match { + case CoordTemplataI(RegionTemplataI(-1), CoordI(ImmutableShareI, StrIT())) => { + vpass() + } + case _ => + } + + vpass() +} +//case class PlaceholderTemplataI[+T <: ITemplataType]( +// fullNameT: IdI[R, IPlaceholderNameI], +// tyype: T +//) extends ITemplataI[R] { +// tyype match { +// case CoordTemplataType() => vwat() +// case KindTemplataType() => vwat() +// case _ => +// } +// val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; +//} +case class KindTemplataI[+R <: IRegionsModeI](kind: KindIT[R]) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} +case class RuntimeSizedArrayTemplateTemplataI[+R <: IRegionsModeI]() extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} +case class StaticSizedArrayTemplateTemplataI[+R <: IRegionsModeI]() extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} + + + +case class FunctionTemplataI[+R <: IRegionsModeI]( + envId: IdI[R, FunctionTemplateNameI[R]] +) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + + + + def getTemplateName(): IdI[R, INameI[R]] = vimpl() +} + +case class StructDefinitionTemplataI[+R <: IRegionsModeI]( + envId: IdI[R, StructTemplateNameI[R]], + tyype: TemplateTemplataType +) extends CitizenDefinitionTemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; +} + +sealed trait CitizenDefinitionTemplataI[+R <: IRegionsModeI] extends ITemplataI[R] + +case class InterfaceDefinitionTemplataI[+R <: IRegionsModeI]( + envId: IdI[R, InterfaceTemplateNameI[R]], + tyype: TemplateTemplataType +) extends CitizenDefinitionTemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; +} + +case class ImplDefinitionTemplataI[+R <: IRegionsModeI]( + envId: IdI[R, INameI[R]] +// // The paackage this interface was declared in. +// // See TMRE for more on these environments. +// env: IEnvironment, +//// +//// // The containers are the structs/interfaces/impls/functions that this thing is inside. +//// // E.g. if LinkedList has a Node substruct, then the Node's templata will have one +//// // container, the LinkedList. +//// // See NTKPRR for why we have these parents. +//// containers: Vector[IContainer], +// +// // This is the impl that the interface came from originally. It has all the parent +// // structs and interfaces. See NTKPRR for more. +// impl: ImplA +) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} + +case class OwnershipTemplataI[+R <: IRegionsModeI](ownership: OwnershipI) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} +case class VariabilityTemplataI[+R <: IRegionsModeI](variability: VariabilityI) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} +case class MutabilityTemplataI[+R <: IRegionsModeI](mutability: MutabilityI) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} +case class LocationTemplataI[+R <: IRegionsModeI](location: LocationI) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} + +case class BooleanTemplataI[+R <: IRegionsModeI](value: Boolean) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} +case class IntegerTemplataI[+R <: IRegionsModeI](value: Long) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} +case class StringTemplataI[+R <: IRegionsModeI](value: String) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} +case class PrototypeTemplataI[+R <: IRegionsModeI](declarationRange: RangeS, prototype: PrototypeI[R]) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} +case class IsaTemplataI[+R <: IRegionsModeI](declarationRange: RangeS, implName: IdI[R, IImplNameI[R]], subKind: KindT, superKind: KindIT[R]) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} +case class CoordListTemplataI[+R <: IRegionsModeI](coords: Vector[CoordI[R]]) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + + vpass() +} +case class RegionTemplataI[+R <: IRegionsModeI](pureHeight: Int) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} + +// ExternFunction/ImplTemplata are here because for example when we create an anonymous interface +// substruct, we want to add its forwarding functions and its impl to the environment, but it's +// very difficult to add the ImplA and FunctionA for those. So, we allow having coutputs like +// these directly in the environment. +// These should probably be renamed from Extern to something else... they could be supplied +// by plugins, but theyre also used internally. + +case class ExternFunctionTemplataI[+R <: IRegionsModeI](header: FunctionHeaderI) extends ITemplataI[R] { + val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; + +} diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/types.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/types.scala new file mode 100644 index 000000000..e1e7e6bba --- /dev/null +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/types.scala @@ -0,0 +1,240 @@ +package dev.vale.instantiating.ast + +import dev.vale._ +import dev.vale.postparsing.IImpreciseNameS +import dev.vale.typing.ast._ +import dev.vale.typing.env._ +import dev.vale.typing.names._ +import dev.vale.highertyping._ +import dev.vale.postparsing._ +import dev.vale.typing._ +import dev.vale.typing.ast._ +import dev.vale.typing.templata._ +import dev.vale.typing.types._ + +import scala.collection.immutable.List + +sealed trait OwnershipI { +} +// Instantiator turns BorrowI into MutableBorrowI and ImmutableBorrowI, see HRALII +case object ImmutableShareI extends OwnershipI { + override def toString: String = "immshare" +} +// Instantiator turns ShareI into MutableShareI and ImmutableShareI, see HRALII +// Ironic because shared things are immutable, this is rather referring to the refcount. +case object MutableShareI extends OwnershipI { + override def toString: String = "mutshare" +} +case object OwnI extends OwnershipI { + override def toString: String = "own" +} +case object WeakI extends OwnershipI { + override def toString: String = "weak" +} +// Instantiator turns BorrowI into MutableBorrowI and ImmutableBorrowI, see HRALII +case object ImmutableBorrowI extends OwnershipI { + override def toString: String = "immborrow" +} +// Instantiator turns BorrowI into MutableBorrowI and ImmutableBorrowI, see HRALII +case object MutableBorrowI extends OwnershipI { + override def toString: String = "mutborrow" +} + +sealed trait MutabilityI { +} +case object MutableI extends MutabilityI { + override def toString: String = "mut" +} +case object ImmutableI extends MutabilityI { + override def toString: String = "imm" +} + +sealed trait VariabilityI { +} +case object FinalI extends VariabilityI { + override def toString: String = "final" +} +case object VaryingI extends VariabilityI { + override def toString: String = "vary" +} + +sealed trait LocationI { +} +case object InlineI extends LocationI { + override def toString: String = "inl" +} +case object YonderI extends LocationI { + override def toString: String = "heap" +} + +sealed trait IRegionsModeI +// See CCFCTS, these need to have zero members. If we need to have members, we'll need to stop +// casting from collapsed to subjective ASTs. +class sI() extends IRegionsModeI +class nI() extends sI // Stands for new. Serves as a starting point for a new instantiation. +class cI() extends IRegionsModeI + +object CoordI { + def void[R <: IRegionsModeI]: CoordI[R] = CoordI[R](MutableShareI, VoidIT()) +} + +case class CoordI[+R <: IRegionsModeI]( + ownership: OwnershipI, + kind: KindIT[R]) { + + vpass() + + kind match { + case IntIT(_) | BoolIT() | StrIT() | FloatIT() | VoidIT() | NeverIT(_) => { +// // We don't want any ImmutableShareH, it's better to only ever have one ownership for +// // primitives. +// vassert(ownership == MutableShareI) + } + case RuntimeSizedArrayIT(IdI(_, _, RuntimeSizedArrayNameI(_, RawArrayNameI(_, _, arrRegion)))) => + case StaticSizedArrayIT(IdI(_, _, StaticSizedArrayNameI(_, _, _, RawArrayNameI(_, _, arrRegion)))) => + case StructIT(IdI(_, _, localName)) => + case InterfaceIT(IdI(_, _, localName)) => + case _ => + } + if (ownership == OwnI) { + // See CSHROOR for why we don't assert this. + // vassert(permission == Readwrite) + } + (ownership, kind) match { + case (MutableBorrowI, StrIT()) => vwat() + case (MutableBorrowI, IntIT(_)) => vwat() + case _ => + } +} + +sealed trait KindIT[+R <: IRegionsModeI] { + // Note, we don't have a mutability: Mutability in here because this Kind + // should be enough to uniquely identify a type, and no more. + // We can always get the mutability for a struct from the coutputs. + + def isPrimitive: Boolean + + def expectCitizen(): ICitizenIT[R] = { + this match { + case c : ICitizenIT[R] => c + case _ => vfail() + } + } + + def expectInterface(): InterfaceIT[R] = { + this match { + case c @ InterfaceIT(_) => c + case _ => vfail() + } + } + + def expectStruct(): StructIT[R] = { + this match { + case c @ StructIT(_) => c + case _ => vfail() + } + } +} + +// like Scala's Nothing. No instance of this can ever happen. +case class NeverIT[+R <: IRegionsModeI]( + // True if this Never came from a break. + // While will have to know about this; if IT's a Never from a ret, IT should + // propagate IT, but if its body is a break never, the while produces a void. + // See BRCOBS. + fromBreak: Boolean +) extends KindIT[R] { + override def isPrimitive: Boolean = true +} + +// Mostly for interoperability with extern functions +case class VoidIT[+R <: IRegionsModeI]() extends KindIT[R] { + override def isPrimitive: Boolean = true +} + +case class IntIT[+R <: IRegionsModeI](bits: Int) extends KindIT[R] { + override def isPrimitive: Boolean = true +} + +case class BoolIT[+R <: IRegionsModeI]() extends KindIT[R] { + override def isPrimitive: Boolean = true +} + +case class StrIT[+R <: IRegionsModeI]() extends KindIT[R] { + override def isPrimitive: Boolean = false +} + +case class FloatIT[+R <: IRegionsModeI]() extends KindIT[R] { + override def isPrimitive: Boolean = true +} + +object contentsStaticSizedArrayIT { + def unapply[R <: IRegionsModeI](ssa: StaticSizedArrayIT[R]): + Option[(Long, MutabilityI, VariabilityI, CoordTemplataI[R], RegionTemplataI[R])] = { + val IdI(_, _, StaticSizedArrayNameI(_, size, variability, RawArrayNameI(mutability, coord, selfRegion))) = ssa.name + Some((size, mutability, variability, coord, selfRegion)) + } +} + +case class StaticSizedArrayIT[+R <: IRegionsModeI]( + name: IdI[R, StaticSizedArrayNameI[R]] +) extends KindIT[R] { + vassert(name.initSteps.isEmpty) + override def isPrimitive: Boolean = false + def mutability: MutabilityI = name.localName.arr.mutability + def elementType = name.localName.arr.elementType + def size = name.localName.size + def variability = name.localName.variability +} + +object contentsRuntimeSizedArrayIT { + def unapply[R <: IRegionsModeI](rsa: RuntimeSizedArrayIT[R]): + Option[(MutabilityI, CoordTemplataI[R], RegionTemplataI[R])] = { + val IdI(_, _, RuntimeSizedArrayNameI(_, RawArrayNameI(mutability, coord, selfRegion))) = rsa.name + Some((mutability, coord, selfRegion)) + } +} +case class RuntimeSizedArrayIT[+R <: IRegionsModeI]( + name: IdI[R, RuntimeSizedArrayNameI[R]] +) extends KindIT[R] { + override def isPrimitive: Boolean = false + def mutability = name.localName.arr.mutability + def elementType = name.localName.arr.elementType + +// name.localName.arr.selfRegion match { +// case RegionTemplata(false) => vwat() +// case _ => +// } +} + +object ICitizenIT { + def unapply[R <: IRegionsModeI](self: ICitizenIT[R]): Option[IdI[R, ICitizenNameI[R]]] = { + Some(self.id) + } +} + +// Structs, interfaces, and placeholders +sealed trait ISubKindIT[+R <: IRegionsModeI] extends KindIT[R] { + def id: IdI[R, ISubKindNameI[R]] +} + +sealed trait ICitizenIT[+R <: IRegionsModeI] extends ISubKindIT[R] { + def id: IdI[R, ICitizenNameI[R]] +} + +// These should only be made by StructCompiler, which puts the definition and bounds into coutputs at the same time +case class StructIT[+R <: IRegionsModeI](id: IdI[R, IStructNameI[R]]) extends ICitizenIT[R] { + override def isPrimitive: Boolean = false + (id.initSteps.lastOption, id.localName) match { + case (Some(StructTemplateNameI(_)), StructNameI(_, _)) => vfail() + case _ => + } +} + +case class InterfaceIT[+R <: IRegionsModeI](id: IdI[R, IInterfaceNameI[R]]) extends ICitizenIT[R] { + override def isPrimitive: Boolean = false + (id.initSteps.lastOption, id.localName) match { + case (Some(InterfaceTemplateNameI(_)), InterfaceNameI(_, _)) => vfail() + case _ => + } +} diff --git a/Frontend/IntegrationTests/IntegrationTests.iml b/Frontend/IntegrationTests/IntegrationTests.iml index d5c590e12..19938d6ff 100644 --- a/Frontend/IntegrationTests/IntegrationTests.iml +++ b/Frontend/IntegrationTests/IntegrationTests.iml @@ -26,5 +26,6 @@ + \ No newline at end of file diff --git a/Frontend/IntegrationTests/test/dev/vale/AfterRegionsIntegrationTests.scala b/Frontend/IntegrationTests/test/dev/vale/AfterRegionsIntegrationTests.scala index 72f6f5a6e..5c117b149 100644 --- a/Frontend/IntegrationTests/test/dev/vale/AfterRegionsIntegrationTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/AfterRegionsIntegrationTests.scala @@ -14,7 +14,7 @@ import dev.vale.typing.expression.TookWeakRefOfNonWeakableError import dev.vale.typing.names.{FunctionNameT, FunctionTemplateNameT} import dev.vale.typing.templata.MutabilityTemplataT import dev.vale.typing.types._ -import dev.vale.typing.{Hinputs, ICompileErrorT} +import dev.vale.typing.{HinputsT, ICompileErrorT} import dev.vale.von.{IVonData, VonBool, VonFloat, VonInt} import org.scalatest.{FunSuite, Matchers} diff --git a/Frontend/IntegrationTests/test/dev/vale/ArrayTests.scala b/Frontend/IntegrationTests/test/dev/vale/ArrayTests.scala index acfa324d5..8c5bd21d1 100644 --- a/Frontend/IntegrationTests/test/dev/vale/ArrayTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/ArrayTests.scala @@ -40,7 +40,7 @@ class ArrayTests extends FunSuite with Matchers { val coutputs = compile.expectCompilerOutputs() Collector.only(coutputs.lookupFunction("main"), { - case StaticSizedArrayLookupTE(_,_,_,_, _) => { + case StaticSizedArrayLookupTE(_,_,_,_,_, _) => { } }) @@ -150,7 +150,7 @@ class ArrayTests extends FunSuite with Matchers { val coutputs = compile.expectCompilerOutputs() Collector.only(coutputs.lookupFunction("main"), { - case StaticSizedArrayLookupTE(_,_,arrayType, _, _) => { + case StaticSizedArrayLookupTE(_,_,arrayType, _,_, _) => { arrayType.mutability shouldEqual MutabilityTemplataT(MutableT) } }) @@ -163,7 +163,7 @@ class ArrayTests extends FunSuite with Matchers { val coutputs = compile.expectCompilerOutputs() Collector.only(coutputs.lookupFunction("main"), { - case StaticSizedArrayLookupTE(_,_,arrayType, _, _) => { + case StaticSizedArrayLookupTE(_,_,arrayType, _,_, _) => { arrayType.mutability shouldEqual MutabilityTemplataT(ImmutableT) } }) @@ -176,7 +176,7 @@ class ArrayTests extends FunSuite with Matchers { val coutputs = compile.expectCompilerOutputs() Collector.only(coutputs.lookupFunction("main"), { - case StaticSizedArrayLookupTE(_,_,arrayType, _, _) => { + case StaticSizedArrayLookupTE(_,_,arrayType, _,_, _) => { arrayType.mutability shouldEqual MutabilityTemplataT(MutableT) } }) @@ -189,7 +189,7 @@ class ArrayTests extends FunSuite with Matchers { val coutputs = compile.expectCompilerOutputs() Collector.only(coutputs.lookupFunction("main"), { - case StaticSizedArrayLookupTE(_,_,arrayType, _, _) => { + case StaticSizedArrayLookupTE(_,_,arrayType, _,_, _) => { arrayType.mutability shouldEqual MutabilityTemplataT(ImmutableT) } }) @@ -202,7 +202,7 @@ class ArrayTests extends FunSuite with Matchers { val coutputs = compile.expectCompilerOutputs() Collector.only(coutputs.lookupFunction("main"), { - case StaticSizedArrayLookupTE(_,_,arrayType, _, _) => { + case StaticSizedArrayLookupTE(_,_,arrayType, _,_, _) => { arrayType.mutability shouldEqual MutabilityTemplataT(MutableT) } }) diff --git a/Frontend/IntegrationTests/test/dev/vale/HammerTests.scala b/Frontend/IntegrationTests/test/dev/vale/HammerTests.scala index a8e6f6134..20fd91b7a 100644 --- a/Frontend/IntegrationTests/test/dev/vale/HammerTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/HammerTests.scala @@ -1,11 +1,10 @@ package dev.vale import dev.vale.passmanager.FullCompilationOptions -import dev.vale.finalast.{BlockH, CallH, ConsecutorH, ConstantIntH, InlineH, IntHT, NeverHT, PrototypeH, CoordH, ShareH} +import dev.vale.finalast._ import dev.vale.typing.types.ShareT import dev.vale.testvm.PanicException import dev.vale.simplifying._ -import dev.vale.finalast.VariableIdH import dev.vale.von.VonInt import dev.vale.{finalast => m} import org.scalatest.{FunSuite, Matchers} @@ -23,7 +22,7 @@ class HammerTests extends FunSuite with Matchers { val testPackage = hamuts.lookupPackage(PackageCoordinate.TEST_TLD(compile.interner, compile.keywords)) vassert(testPackage.getAllUserFunctions.size == 1) - testPackage.getAllUserFunctions.head.prototype.fullName.fullyQualifiedName shouldEqual """main""" + testPackage.getAllUserFunctions.head.prototype.id.fullyQualifiedName shouldEqual """main""" } // // Make sure a ListNode struct made it out @@ -59,14 +58,14 @@ class HammerTests extends FunSuite with Matchers { val packageH = compile.getHamuts().lookupPackage(PackageCoordinate.TEST_TLD(compile.interner, compile.keywords)) vassertSome( packageH.interfaces.find(interface => { - interface.fullName.fullyQualifiedName == """MyOption""" + interface.id.fullyQualifiedName == """MyOption""" })) - val mySome = packageH.structs.find(_.fullName.fullyQualifiedName == """MySome""").get; + val mySome = packageH.structs.find(_.id.fullyQualifiedName == """MySome""").get; vassert(mySome.members.size == 1); - vassert(mySome.members.head.tyype == CoordH[IntHT](ShareH, InlineH, IntHT.i32)) + vassert(mySome.members.head.tyype == CoordH[IntHT](MutableShareH, InlineH, IntHT.i32)) - val myNone = packageH.structs.find(_.fullName.fullyQualifiedName == """MyNone""").get; + val myNone = packageH.structs.find(_.id.fullyQualifiedName == """MyNone""").get; vassert(myNone.members.isEmpty); } diff --git a/Frontend/IntegrationTests/test/dev/vale/IntegrationTestsA.scala b/Frontend/IntegrationTests/test/dev/vale/IntegrationTestsA.scala index baf1481a0..0b2a0a0a3 100644 --- a/Frontend/IntegrationTests/test/dev/vale/IntegrationTestsA.scala +++ b/Frontend/IntegrationTests/test/dev/vale/IntegrationTestsA.scala @@ -7,8 +7,9 @@ import dev.vale.options.GlobalOptions import dev.vale.parsing.ast.FileP import dev.vale.postparsing._ import dev.vale.typing.ast._ -import dev.vale.typing.names.{IdT, FunctionNameT, FunctionTemplateNameT} -import dev.vale.typing.{Hinputs, ICompileErrorT, ast} +import dev.vale.instantiating.ast._ +import dev.vale.typing.names.{FunctionNameT, FunctionTemplateNameT, IdT} +import dev.vale.typing.{HinputsT, ICompileErrorT, ast} import dev.vale.typing.types._ import dev.vale.testvm.{ConstraintViolatedException, Heap, IntV, PrimitiveKindV, ReferenceV, StructInstanceV, Vivem} import dev.vale.highertyping.ICompileErrorA @@ -20,6 +21,7 @@ import dev.vale.testvm.ReferenceV import org.scalatest.{FunSuite, Matchers} import dev.vale.passmanager.FullCompilation import dev.vale.finalast.IdH +import dev.vale.instantiating.ast.HinputsI import dev.vale.lexing.{FailedParse, RangeL} import dev.vale.postparsing.ICompileErrorS import dev.vale.typing.ast._ @@ -67,9 +69,9 @@ class RunCompilation( def getVpstMap(): Result[FileCoordinateMap[String], FailedParse] = fullCompilation.getVpstMap() def getScoutput(): Result[FileCoordinateMap[ProgramS], ICompileErrorS] = fullCompilation.getScoutput() def getAstrouts(): Result[PackageCoordinateMap[ProgramA], ICompileErrorA] = fullCompilation.getAstrouts() - def getCompilerOutputs(): Result[Hinputs, ICompileErrorT] = fullCompilation.getCompilerOutputs() - def expectCompilerOutputs(): Hinputs = fullCompilation.expectCompilerOutputs() - def getMonouts(): Hinputs = fullCompilation.getMonouts() + def getCompilerOutputs(): Result[HinputsT, ICompileErrorT] = fullCompilation.getCompilerOutputs() + def expectCompilerOutputs(): HinputsT = fullCompilation.expectCompilerOutputs() + def getMonouts(): HinputsI = fullCompilation.getMonouts() def getHamuts(): ProgramH = { val hamuts = fullCompilation.getHamuts() fullCompilation.getVonHammer().vonifyProgram(hamuts) @@ -776,14 +778,14 @@ class IntegrationTestsA extends FunSuite with Matchers { val keywords = compile.keywords vassert( - hinputs.functions.filter(func => func.header.id.localName match { - case FunctionNameT(FunctionTemplateNameT(StrI("bork"), _), _, _) => true + !hinputs.functions.exists(func => func.header.id.localName match { + case FunctionNameIX(FunctionTemplateNameI(StrI("bork"), _), _, _) => true case _ => false - }).isEmpty) + })) vassert( hinputs.functions.find(func => func.header.id.localName match { - case FunctionNameT(FunctionTemplateNameT(StrI("helperFunc"), _), _, _) => true + case FunctionNameIX(FunctionTemplateNameI(StrI("helperFunc"), _), _, _) => true case _ => false }).size == 1) } diff --git a/Frontend/IntegrationTests/test/dev/vale/PatternTests.scala b/Frontend/IntegrationTests/test/dev/vale/PatternTests.scala index 115943d40..2ab9227b8 100644 --- a/Frontend/IntegrationTests/test/dev/vale/PatternTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/PatternTests.scala @@ -5,6 +5,7 @@ import dev.vale.postparsing.CodeRuneS import dev.vale.typing.env.ReferenceLocalVariableT import dev.vale.typing.types._ import dev.vale.typing._ +import dev.vale.instantiating.ast._ import dev.vale.typing.ast.{NormalStructMemberT, ReferenceMemberTypeT} import dev.vale.typing.names.{IdT, KindPlaceholderNameT, KindPlaceholderTemplateNameT, StructNameT, StructTemplateNameT} import dev.vale.typing.types.IntT @@ -72,11 +73,11 @@ class PatternTests extends FunSuite with Matchers { val monouts = compile.getMonouts() val tupDef = monouts.lookupStruct("Tup") val tupDefMemberTypes = - tupDef.members.collect({ case NormalStructMemberT(_, _, tyype) => tyype.reference }) + tupDef.members.collect({ case StructMemberI(_, _, tyype) => tyype.reference }) tupDefMemberTypes match { case Vector( - CoordT(ShareT,_,IntT(32)), - CoordT(BorrowT,_,StructTT(IdT(_,Vector(),StructNameT(StructTemplateNameT(StrI("Marine")),Vector()))))) => + CoordI(MutableShareI,IntIT(32)), + CoordI(MutableBorrowI,StructIT(IdI(_,Vector(),StructNameI(StructTemplateNameI(StrI("Marine")),Vector()))))) => case null => // case Vector( // ReferenceMemberTypeT(CoordT(own,PlaceholderT(IdT(_,Vector(StructTemplateNameT(StrI("Tup"))),PlaceholderNameT(PlaceholderTemplateNameT(0,CodeRuneS(StrI("T1")))))))), @@ -98,7 +99,6 @@ class PatternTests extends FunSuite with Matchers { |} """.stripMargin) val coutputs = compile.expectCompilerOutputs() - coutputs.functions.head.header.returnType == CoordT(ShareT, GlobalRegionT(), IntT.i32) compile.evalForKind(Vector()) match { case VonInt(42) => } } diff --git a/Frontend/IntegrationTests/test/dev/vale/ResultTests.scala b/Frontend/IntegrationTests/test/dev/vale/ResultTests.scala index 5c31b83af..c75304006 100644 --- a/Frontend/IntegrationTests/test/dev/vale/ResultTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/ResultTests.scala @@ -8,7 +8,7 @@ class ResultTests extends FunSuite with Matchers { test("Test borrow is_ok and expect for Ok") { val compile = RunCompilation.test( """ - |import v.builtins.panic.*; + |import v.builtins.panicutils.*; |import v.builtins.result.*; | |exported func main() int { @@ -24,7 +24,7 @@ class ResultTests extends FunSuite with Matchers { test("Test is_err and borrow expect_err for Err") { val compile = RunCompilation.test( """ - |import v.builtins.panic.*; + |import v.builtins.panicutils.*; |import v.builtins.result.*; | |exported func main() str { @@ -40,7 +40,7 @@ class ResultTests extends FunSuite with Matchers { test("Test owning expect") { val compile = RunCompilation.test( """ - |import v.builtins.panic.*; + |import v.builtins.panicutils.*; |import v.builtins.result.*; | |exported func main() int { @@ -55,7 +55,7 @@ class ResultTests extends FunSuite with Matchers { test("Test owning expect_err") { val compile = RunCompilation.test( """ - |import v.builtins.panic.*; + |import v.builtins.panicutils.*; |import v.builtins.result.*; | |exported func main() str { @@ -70,7 +70,7 @@ class ResultTests extends FunSuite with Matchers { test("Test expect() panics for Err") { val compile = RunCompilation.test( """ - |import v.builtins.panic.*; + |import v.builtins.panicutils.*; |import v.builtins.result.*; | |exported func main() int { @@ -90,7 +90,7 @@ class ResultTests extends FunSuite with Matchers { test("Test expect_err() panics for Ok") { val compile = RunCompilation.test( """ - |import v.builtins.panic.*; + |import v.builtins.panicutils.*; |import v.builtins.result.*; | |exported func main() str { diff --git a/Frontend/IntegrationTests/test/dev/vale/VirtualTests.scala b/Frontend/IntegrationTests/test/dev/vale/VirtualTests.scala index 9239d26ea..6af17c51d 100644 --- a/Frontend/IntegrationTests/test/dev/vale/VirtualTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/VirtualTests.scala @@ -1,8 +1,9 @@ package dev.vale +import dev.vale.instantiating.ast._ import dev.vale.typing.{ast, types} import dev.vale.typing.ast.{AbstractT, SignatureT} -import dev.vale.typing.names.{CitizenNameT, CitizenTemplateNameT, IdT, FunctionNameT, FunctionTemplateNameT, InterfaceNameT, InterfaceTemplateNameT} +import dev.vale.typing.names._ import dev.vale.typing.types._ import dev.vale.testvm.IntV import dev.vale.typing.ast._ @@ -355,14 +356,14 @@ class VirtualTests extends FunSuite with Matchers { val moo = compile.getMonouts().lookupFunction("moo") val (destVar, returnType) = Collector.only(moo, { - case LetNormalTE(destVar, FunctionCallTE(PrototypeT(IdT(_, _, FunctionNameT(FunctionTemplateNameT(StrI("as"), _), _, _)), returnType), _)) => { + case LetNormalIE(destVar, FunctionCallIE(PrototypeI(IdI(_, _, FunctionNameIX(FunctionTemplateNameI(StrI("as"), _), _, _)), returnType), _, _), _) => { (destVar, returnType) } }) - vassert(destVar.coord == returnType) + vassert(destVar.collapsedCoord == returnType) val Vector(successType, failType) = returnType.kind.expectInterface().id.localName.templateArgs - vassert(expectCoordTemplata(successType).coord.ownership == BorrowT) - vassert(expectCoordTemplata(failType).coord.ownership == BorrowT) + vassert(successType.expectCoordTemplata().coord.ownership == MutableBorrowI) + vassert(failType.expectCoordTemplata().coord.ownership == MutableBorrowI) } compile.evalForKind(Vector()) match { case VonInt(42) => } diff --git a/Frontend/PassManager/PassManager.iml b/Frontend/PassManager/PassManager.iml index bffa96174..73e92adbc 100644 --- a/Frontend/PassManager/PassManager.iml +++ b/Frontend/PassManager/PassManager.iml @@ -23,5 +23,6 @@ + \ No newline at end of file diff --git a/Frontend/PassManager/src/dev/vale/passmanager/FullCompilation.scala b/Frontend/PassManager/src/dev/vale/passmanager/FullCompilation.scala index d6bdf2ba3..8b2fc70bb 100644 --- a/Frontend/PassManager/src/dev/vale/passmanager/FullCompilation.scala +++ b/Frontend/PassManager/src/dev/vale/passmanager/FullCompilation.scala @@ -8,8 +8,9 @@ import dev.vale.{Builtins, Err, FileCoordinate, FileCoordinateMap, IPackageResol import dev.vale.highertyping.ICompileErrorA import PassManager.SourceInput import dev.vale.highertyping.{ICompileErrorA, ProgramA} +import dev.vale.instantiating.ast.HinputsI import dev.vale.lexing.{FailedParse, RangeL} -import dev.vale.typing.{Hinputs, ICompileErrorT} +import dev.vale.typing.{HinputsT, ICompileErrorT} import dev.vale.postparsing.PostParser import dev.vale.simplifying._ import dev.vale.typing.ICompileErrorT @@ -47,8 +48,8 @@ class FullCompilation( def getVpstMap(): Result[FileCoordinateMap[String], FailedParse] = hammerCompilation.getVpstMap() def getScoutput(): Result[FileCoordinateMap[ProgramS], ICompileErrorS] = hammerCompilation.getScoutput() def getAstrouts(): Result[PackageCoordinateMap[ProgramA], ICompileErrorA] = hammerCompilation.getAstrouts() - def getCompilerOutputs(): Result[Hinputs, ICompileErrorT] = hammerCompilation.getCompilerOutputs() - def expectCompilerOutputs(): Hinputs = hammerCompilation.expectCompilerOutputs() + def getCompilerOutputs(): Result[HinputsT, ICompileErrorT] = hammerCompilation.getCompilerOutputs() + def expectCompilerOutputs(): HinputsT = hammerCompilation.expectCompilerOutputs() def getHamuts(): ProgramH = hammerCompilation.getHamuts() - def getMonouts(): Hinputs = hammerCompilation.getMonouts() + def getMonouts(): HinputsI = hammerCompilation.getMonouts() } diff --git a/Frontend/SimplifyingPass/SimplifyingPass.iml b/Frontend/SimplifyingPass/SimplifyingPass.iml index 68fb3da01..fa26fee27 100644 --- a/Frontend/SimplifyingPass/SimplifyingPass.iml +++ b/Frontend/SimplifyingPass/SimplifyingPass.iml @@ -15,13 +15,13 @@ - + \ No newline at end of file diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/BlockHammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/BlockHammer.scala index 575148504..f2094d983 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/BlockHammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/BlockHammer.scala @@ -1,21 +1,16 @@ package dev.vale.simplifying -import dev.vale.finalast.{BlockH, NeverHT} -import dev.vale.typing.Hinputs -import dev.vale.typing.ast.{BlockTE, FunctionHeaderT} -import dev.vale.vfail -import dev.vale.{finalast => m} -import dev.vale.finalast._ -import dev.vale.typing.ast._ -import dev.vale.vfail - -class BlockHammer(expressionHammer: ExpressionHammer) { +import dev.vale.finalast.{BlockH, ImmutabilifyH, ImmutableBorrowH, ImmutableShareH, MutabilifyH, MutableBorrowH, MutableShareH, NeverHT} +import dev.vale.instantiating.ast._ +import dev.vale.{vassert, vcurious, vfail, vimpl, vwat, finalast => m} + +class BlockHammer(expressionHammer: ExpressionHammer, typeHammer: TypeHammer) { def translateBlock( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, parentLocals: LocalsBox, - block2: BlockTE): + block2: BlockIE): (BlockH) = { val blockLocals = LocalsBox(parentLocals.snapshot) @@ -54,4 +49,58 @@ class BlockHammer(expressionHammer: ExpressionHammer) { // start here, we're returning locals and thats not optimal BlockH(exprH) } + + def translateMutabilify( + hinputs: HinputsI, + hamuts: HamutsBox, + currentFunctionHeader: FunctionHeaderI, + locals: LocalsBox, + node: MutabilifyIE): + MutabilifyH = { + val MutabilifyIE(innerIE, resultCoordI) = node + + val innerHE = + expressionHammer.translateExpressionsAndDeferreds( + hinputs, hamuts, currentFunctionHeader, locals, Vector(innerIE)) + + val resultCoordH = + typeHammer.translateCoord(hinputs, hamuts, resultCoordI) + + vassert( + resultCoordH.ownership == + (innerHE.resultType.ownership match { + case ImmutableShareH => MutableShareH + case ImmutableBorrowH => MutableBorrowH + case other => other + })) + + MutabilifyH(innerHE) + } + + def translateImmutabilify( + hinputs: HinputsI, + hamuts: HamutsBox, + currentFunctionHeader: FunctionHeaderI, + locals: LocalsBox, + node: ImmutabilifyIE): + ImmutabilifyH = { + val ImmutabilifyIE(innerIE, resultCoordI) = node + + val innerHE = + expressionHammer.translateExpressionsAndDeferreds( + hinputs, hamuts, currentFunctionHeader, locals, Vector(innerIE)) + + val resultCoordH = + typeHammer.translateCoord(hinputs, hamuts, resultCoordI) + + vassert( + resultCoordH.ownership == + (innerHE.resultType.ownership match { + case MutableShareH => ImmutableShareH + case MutableBorrowH => ImmutableBorrowH + case other => other + })) + + ImmutabilifyH(innerHE) + } } diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/Conversions.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/Conversions.scala index a1f4a82ed..233150bdf 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/Conversions.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/Conversions.scala @@ -1,15 +1,12 @@ package dev.vale.simplifying import dev.vale.{CodeLocationS, finalast, vimpl} -import dev.vale.finalast.{BorrowH, CodeLocation, Final, Immutable, InlineH, LocationH, Mutability, Mutable, OwnH, OwnershipH, ShareH, Variability, Varying, WeakH, YonderH} +import dev.vale.finalast._ import dev.vale.postparsing._ -import dev.vale.typing.types._ import dev.vale.highertyping._ import dev.vale.finalast._ +import dev.vale.instantiating.ast._ import dev.vale.postparsing.rules._ -import dev.vale.typing.templata.{ITemplataT, IntegerTemplataT, MutabilityTemplataT, VariabilityTemplataT} -import dev.vale.typing.types._ -import dev.vale.typing.{types => t} import dev.vale.{finalast => m, postparsing => s} object Conversions { @@ -18,61 +15,49 @@ object Conversions { finalast.CodeLocation(line, col) } - def evaluateMutability(mutability: MutabilityT): Mutability = { + def evaluateMutability(mutability: MutabilityI): Mutability = { mutability match { - case MutableT => Mutable - case ImmutableT => Immutable + case MutableI => Mutable + case ImmutableI => Immutable } } - def evaluateMutabilityTemplata(mutability: ITemplataT[MutabilityTemplataType]): Mutability = { + def evaluateMutabilityTemplata(mutability: MutabilityI): Mutability = { mutability match { - case MutabilityTemplataT(MutableT) => Mutable - case MutabilityTemplataT(ImmutableT) => Immutable + case MutableI => Mutable + case ImmutableI => Immutable } } - def evaluateVariabilityTemplata(mutability: ITemplataT[VariabilityTemplataType]): Variability = { + def evaluateVariabilityTemplata(mutability: VariabilityI): Variability = { mutability match { - case VariabilityTemplataT(VaryingT) => Varying - case VariabilityTemplataT(FinalT) => Final - } - } - - def evaluateIntegerTemplata(templata: ITemplataT[IntegerTemplataType]): Long = { - templata match { - case IntegerTemplataT(n) => n + case VaryingI => Varying + case FinalI => Final } } - def evaluateLocation(location: LocationT): LocationH = { + def evaluateLocation(location: LocationI): LocationH = { location match { - case InlineT => InlineH - case YonderT => YonderH + case InlineI => InlineH + case YonderI => YonderH } } - def evaluateVariability(variability: VariabilityT): Variability = { + def evaluateVariability(variability: VariabilityI): Variability = { variability match { - case FinalT => Final - case VaryingT => Varying - } - } - - def evaluateOwnership(ownership: OwnershipT): OwnershipH = { - ownership match { - case OwnT => OwnH - case BorrowT => BorrowH - case ShareT => ShareH - case WeakT => WeakH + case FinalI => Final + case VaryingI => Varying } } - def unevaluateOwnership(ownership: OwnershipH): OwnershipH = { + def evaluateOwnership(ownership: OwnershipI): OwnershipH = { ownership match { - case OwnH => finalast.OwnH - case BorrowH => finalast.BorrowH - case ShareH => finalast.ShareH + case OwnI => OwnH + case ImmutableBorrowI => ImmutableBorrowH + case MutableBorrowI => MutableBorrowH + case ImmutableShareI => ImmutableShareH + case MutableShareI => MutableShareH + case WeakI => WeakH } } diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/ExpressionHammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/ExpressionHammer.scala index b0d0ae52b..d4cc84936 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/ExpressionHammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/ExpressionHammer.scala @@ -1,15 +1,9 @@ package dev.vale.simplifying import dev.vale.finalast._ -import dev.vale.typing.Hinputs -import dev.vale.typing.ast._ -import dev.vale.typing.env.AddressibleLocalVariableT -import dev.vale.typing.types._ -import dev.vale.{Keywords, vassert, vcurious, vfail, vimpl, finalast => m} +import dev.vale.{Keywords, vassert, vcurious, vfail, vimpl, vregionmut, finalast => m} import dev.vale.finalast._ -import dev.vale.typing._ -import dev.vale.typing.ast._ -import dev.vale.typing.types._ +import dev.vale.instantiating.ast._ import scala.collection.immutable.Map @@ -19,7 +13,7 @@ class ExpressionHammer( nameHammer: NameHammer, structHammer: StructHammer, functionHammer: FunctionHammer) { - val blockHammer = new BlockHammer(this) + val blockHammer = new BlockHammer(this, typeHammer) val loadHammer = new LoadHammer(keywords, typeHammer, nameHammer, structHammer, this) val letHammer = new LetHammer(typeHammer, nameHammer, structHammer, this, loadHammer) val mutateHammer = new MutateHammer(keywords, typeHammer, nameHammer, structHammer, this) @@ -31,46 +25,46 @@ class ExpressionHammer( // - result register id // - deferred expressions, to move to after the enclosing call. head is put first after call. def translate( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - expr2: ExpressionT - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { + expr2: ExpressionI + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { expr2 match { - case ConstantIntTE(numTemplata, bits) => { - val num = Conversions.evaluateIntegerTemplata(numTemplata) + case ConstantIntIE(numTemplata, bits) => { + val num = numTemplata (ConstantIntH(num, bits), Vector.empty) } - case VoidLiteralTE() => { + case VoidLiteralIE() => { val constructH = ConstantVoidH() (constructH, Vector.empty) } - case ConstantStrTE(value) => { + case ConstantStrIE(value) => { (ConstantStrH(value), Vector.empty) } - case ConstantFloatTE(value) => { + case ConstantFloatIE(value) => { (ConstantF64H(value), Vector.empty) } - case ConstantBoolTE(value) => { + case ConstantBoolIE(value) => { (ConstantBoolH(value), Vector.empty) } - case let2 @ LetNormalTE(_, _) => { + case let2 @ LetNormalIE(_, _, _) => { val letH = letHammer.translateLet(hinputs, hamuts, currentFunctionHeader, locals, let2) (letH, Vector.empty) } - case let2 @ RestackifyTE(_, _) => { + case let2 @ RestackifyIE(_, _, _) => { val letH = letHammer.translateRestackify(hinputs, hamuts, currentFunctionHeader, locals, let2) (letH, Vector.empty) } - case let2 @ LetAndLendTE(_, _, _) => { + case let2 @ LetAndLendIE(_, _, _, _) => { val borrowAccess = letHammer.translateLetAndPoint(hinputs, hamuts, currentFunctionHeader, locals, let2) (borrowAccess, Vector.empty) } - case des2 @ DestroyTE(_, _, _) => { + case des2 @ DestroyIE(_, _, _) => { val destroyH = letHammer.translateDestroy(hinputs, hamuts, currentFunctionHeader, locals, des2) // Compiler destructures put things in local variables (even though hammer itself @@ -79,7 +73,7 @@ class ExpressionHammer( // return a void. (destroyH, Vector.empty) } - case des2 @ DestroyStaticSizedArrayIntoLocalsTE(_, _, _) => { + case des2 @ DestroyStaticSizedArrayIntoLocalsIE(_, _, _) => { val destructureH = letHammer.translateDestructureStaticSizedArray(hinputs, hamuts, currentFunctionHeader, locals, des2) // Compiler destructures put things in local variables (even though hammer itself @@ -88,47 +82,61 @@ class ExpressionHammer( // return a void. (destructureH, Vector.empty) } - case unlet2 @ UnletTE(_) => { + case unlet2 @ UnletIE(_, _) => { val valueAccess = letHammer.translateUnlet( hinputs, hamuts, currentFunctionHeader, locals, unlet2) (valueAccess, Vector.empty) } - case mutate2 @ MutateTE(_, _) => { + case mutate2 @ MutateIE(_, _, _) => { val newEmptyPackStructNodeHE = mutateHammer.translateMutate(hinputs, hamuts, currentFunctionHeader, locals, mutate2) (newEmptyPackStructNodeHE, Vector.empty) } - case b @ BlockTE(_) => { + case b @ MutabilifyIE(_, _) => { + val pureH = + blockHammer.translateMutabilify(hinputs, hamuts, currentFunctionHeader, locals, b) + (pureH, Vector.empty) + } + case b@ImmutabilifyIE(_, _) => { + val pureH = + blockHammer.translateImmutabilify(hinputs, hamuts, currentFunctionHeader, locals, b) + (pureH, Vector.empty) + } + case b @ BlockIE(_, _) => { val blockH = blockHammer.translateBlock(hinputs, hamuts, currentFunctionHeader, locals, b) (blockH, Vector.empty) } - case call2 @ FunctionCallTE(callableExpr, args) => { + case call2 @ FunctionCallIE(callableExpr, args, _) => { val access = translateFunctionPointerCall( - hinputs, hamuts, currentFunctionHeader, locals, callableExpr, args, call2.result.coord) + hinputs, hamuts, currentFunctionHeader, locals, callableExpr, args, call2.result) (access, Vector.empty) } - - case InterfaceFunctionCallTE(superFunctionPrototype, virtualParamIndex, resultType2, argsExprs2) => { + case PreCheckBorrowIE(inner) => { + val (innerHE, deferreds) = + translate(hinputs, hamuts, currentFunctionHeader, locals, inner) + (PreCheckBorrowH(innerHE), deferreds) + } + case InterfaceFunctionCallIE(superFunctionPrototype, virtualParamIndex, argsExprs2, resultType2) => { val access = translateInterfaceFunctionCall( hinputs, hamuts, currentFunctionHeader, locals, superFunctionPrototype, virtualParamIndex, resultType2, argsExprs2) (access, Vector.empty) } - case ConsecutorTE(exprsTE) => { + case ConsecutorIE(exprsIE, _) => { // If there's an expression returning a Never, then remove all the expressions after that. // See BRCOBS. val exprsHE = - exprsTE.foldLeft(Vector[ExpressionH[KindHT]]())({ - case (previousHE, nextTE) => { + exprsIE.foldLeft(Vector[ExpressionH[KindHT]]())({ + case (previousHE, nextIE) => { previousHE.lastOption.map(_.resultType.kind) match { case Some(NeverHT(_)) => previousHE case _ => { val (nextHE, nextDeferreds) = - translate(hinputs, hamuts, currentFunctionHeader, locals, nextTE); + translate(hinputs, hamuts, currentFunctionHeader, locals, nextIE); val nextExprWithDeferredsHE = translateDeferreds( hinputs, hamuts, currentFunctionHeader, locals, nextHE, nextDeferreds) @@ -147,7 +155,7 @@ class ExpressionHammer( (Hammer.consecutive(exprsHE), Vector.empty) } - case ArrayLengthTE(arrayExpr2) => { + case ArrayLengthIE(arrayExpr2) => { val (resultHE, deferreds) = translate(hinputs, hamuts, currentFunctionHeader, locals, arrayExpr2); @@ -159,7 +167,7 @@ class ExpressionHammer( (arrayLengthAndDeferredsExprH, Vector.empty) } - case RuntimeSizedArrayCapacityTE(arrayExpr2) => { + case RuntimeSizedArrayCapacityIE(arrayExpr2) => { val (resultHE, deferreds) = translate(hinputs, hamuts, currentFunctionHeader, locals, arrayExpr2); @@ -171,7 +179,7 @@ class ExpressionHammer( (arrayLengthAndDeferredsExprH, Vector.empty) } - case LockWeakTE(innerExpr2, resultOptBorrowType2, someConstructor, noneConstructor, _, _) => { + case LockWeakIE(innerExpr2, resultOptBorrowType2, someConstructor, noneConstructor, _, _, _) => { val (resultHE, deferreds) = translate(hinputs, hamuts, currentFunctionHeader, locals, innerExpr2); val (resultOptBorrowTypeH) = @@ -191,7 +199,7 @@ class ExpressionHammer( (resultNode, deferreds) } - case TupleTE(exprs, resultType) => { + case TupleIE(exprs, resultType) => { val (resultsHE, deferreds) = translateExpressionsUntilNever( hinputs, hamuts, currentFunctionHeader, locals, exprs); @@ -203,14 +211,14 @@ class ExpressionHammer( case _ => } - val resultStructT = resultType.kind match { case s @ StructTT(_) => s } + val resultStructI = resultType.kind match { case s @ StructIT(_) => s } val (underlyingStructRefH) = - structHammer.translateStructT(hinputs, hamuts, resultStructT); + structHammer.translateStructI(hinputs, hamuts, resultStructI); val (resultReference) = typeHammer.translateCoord(hinputs, hamuts, resultType) vassert(resultReference.kind == underlyingStructRefH) - val structDefH = hamuts.structTToStructDefH(resultStructT) + val structDefH = hamuts.structTToStructDefH(resultStructI) vassert(resultsHE.size == structDefH.members.size) val newStructNode = NewStructH( @@ -225,7 +233,7 @@ class ExpressionHammer( (newStructAndDeferredsExprH, Vector.empty) } - case StaticArrayFromValuesTE(exprs, arrayReference2, arrayType2) => { + case StaticArrayFromValuesIE(exprs, arrayReference2, arrayType2) => { val (resultsHE, deferreds) = translateExpressionsUntilNever(hinputs, hamuts, currentFunctionHeader, locals, exprs); // Don't evaluate anything that can't ever be run, see BRCOBS @@ -253,7 +261,7 @@ class ExpressionHammer( (newStructAndDeferredsExprH, Vector.empty) } - case ConstructTE(structTT, resultType2, memberExprs) => { + case ConstructIE(structIT, resultType2, memberExprs) => { val (membersHE, deferreds) = translateExpressionsUntilNever(hinputs, hamuts, currentFunctionHeader, locals, memberExprs); // Don't evaluate anything that can't ever be run, see BRCOBS @@ -268,7 +276,7 @@ class ExpressionHammer( typeHammer.translateCoord(hinputs, hamuts, resultType2) - val structDefH = hamuts.structTToStructDefH(structTT) + val structDefH = hamuts.structTToStructDefH(structIT) vassert(membersHE.size == structDefH.members.size) membersHE.zip(structDefH.members).foreach({ case (memberHE, memberH ) => vassert(memberHE.resultType == memberH.tyype) @@ -285,43 +293,44 @@ class ExpressionHammer( (newStructAndDeferredsExprH, Vector.empty) } - case load2 @ SoftLoadTE(_, _) => { + case load2 @ SoftLoadIE(_, _, _) => { val (loadedAccessH, deferreds) = loadHammer.translateLoad(hinputs, hamuts, currentFunctionHeader, locals, load2) (loadedAccessH, deferreds) } - case lookup2 @ LocalLookupTE(_,AddressibleLocalVariableT(_, _, _)) => { + case lookup2 @ LocalLookupIE(AddressibleLocalVariableI(_, _, _), _) => { + vregionmut() val loadBoxAccess = loadHammer.translateLocalAddress(hinputs, hamuts, currentFunctionHeader, locals, lookup2) (loadBoxAccess, Vector.empty) } - case lookup2 @ AddressMemberLookupTE(_,_, _, _, _) => { + case lookup2 @ AddressMemberLookupIE(_, _, _, _) => { val (loadBoxAccess, deferreds) = loadHammer.translateMemberAddress(hinputs, hamuts, currentFunctionHeader, locals, lookup2) (loadBoxAccess, deferreds) } - case if2 @ IfTE(_, _, _) => { + case if2 @ IfIE(_, _, _, _) => { val maybeAccess = translateIf(hinputs, hamuts, currentFunctionHeader, locals, if2) (maybeAccess, Vector.empty) } - case prsaTE @ PushRuntimeSizedArrayTE(_, _) => { + case prsaIE @ PushRuntimeSizedArrayIE(_, _) => { - val PushRuntimeSizedArrayTE(arrayTE, newcomerTE) = prsaTE; + val PushRuntimeSizedArrayIE(arrayIE, newcomerIE) = prsaIE; val (arrayHE, arrayDeferreds) = translate( - hinputs, hamuts, currentFunctionHeader, locals, arrayTE); + hinputs, hamuts, currentFunctionHeader, locals, arrayIE); val rsaHE = arrayHE.expectRuntimeSizedArrayAccess() val rsaDefH = hamuts.getRuntimeSizedArray(rsaHE.resultType.kind) val (newcomerHE, newcomerDeferreds) = translate( - hinputs, hamuts, currentFunctionHeader, locals, newcomerTE); + hinputs, hamuts, currentFunctionHeader, locals, newcomerIE); vassert(newcomerHE.resultType == rsaDefH.elementType) @@ -334,12 +343,12 @@ class ExpressionHammer( (access, Vector.empty) } - case prsaTE @ PopRuntimeSizedArrayTE(_) => { - val PopRuntimeSizedArrayTE(arrayTE) = prsaTE; + case prsaIE @ PopRuntimeSizedArrayIE(_, _) => { + val PopRuntimeSizedArrayIE(arrayIE, _) = prsaIE; val (arrayHE, arrayDeferreds) = translate( - hinputs, hamuts, currentFunctionHeader, locals, arrayTE); + hinputs, hamuts, currentFunctionHeader, locals, arrayIE); val rsaHE = arrayHE.expectRuntimeSizedArrayAccess() val rsaDefH = hamuts.getRuntimeSizedArray(rsaHE.resultType.kind) @@ -352,30 +361,30 @@ class ExpressionHammer( (access, Vector.empty) } - case nmrsaTE @ NewMutRuntimeSizedArrayTE(_, _) => { + case nmrsaIE @ NewMutRuntimeSizedArrayIE(_, _, _) => { val access = translateNewMutRuntimeSizedArray( - hinputs, hamuts, currentFunctionHeader, locals, nmrsaTE) + hinputs, hamuts, currentFunctionHeader, locals, nmrsaIE) (access, Vector.empty) } - case nirsaTE @ NewImmRuntimeSizedArrayTE(_, _, _, _) => { + case nirsaIE @ NewImmRuntimeSizedArrayIE(_, _, _, _, _) => { val access = translateNewImmRuntimeSizedArray( - hinputs, hamuts, currentFunctionHeader, locals, nirsaTE) + hinputs, hamuts, currentFunctionHeader, locals, nirsaIE) (access, Vector.empty) } - case ca2 @ StaticArrayFromCallableTE(_, _, _) => { + case ca2 @ StaticArrayFromCallableIE(_, _, _, _) => { val access = translateStaticArrayFromCallable( hinputs, hamuts, currentFunctionHeader, locals, ca2) (access, Vector.empty) } - case ReinterpretTE(innerExpr, resultType2) => { + case ReinterpretIE(innerExpr, resultType2, _) => { // Check types; it's overkill because reinterprets are rather scary. - val innerExprResultType2 = innerExpr.result.coord + val innerExprResultType2 = innerExpr.result val (innerExprResultTypeH) = typeHammer.translateCoord(hinputs, hamuts, innerExprResultType2); val (resultTypeH) = typeHammer.translateCoord(hinputs, hamuts, resultType2); innerExprResultTypeH.kind match { @@ -413,9 +422,9 @@ class ExpressionHammer( (innerExprHE, deferreds) } - case up @ InterfaceToInterfaceUpcastTE(innerExpr, targetInterfaceRef2) => { - val targetPointerType2 = up.result.coord; - val sourcePointerType2 = innerExpr.result.coord + case up @ InterfaceToInterfaceUpcastIE(innerExpr, targetInterfaceRef2, _) => { + val targetPointerType2 = up.result; + val sourcePointerType2 = innerExpr.result val (sourcePointerTypeH) = typeHammer.translateCoord(hinputs, hamuts, sourcePointerType2); @@ -436,9 +445,9 @@ class ExpressionHammer( (upcastNode, innerDeferreds) } - case up @ UpcastTE(innerExpr, targetInterfaceRef2, _) => { - val targetPointerType2 = up.result.coord; - val sourcePointerType2 = innerExpr.result.coord + case up @ UpcastIE(innerExpr, targetInterfaceRef2, _, _) => { + val targetPointerType2 = up.result; + val sourcePointerType2 = innerExpr.result val (sourcePointerTypeH) = typeHammer.translateCoord(hinputs, hamuts, sourcePointerType2); @@ -460,25 +469,25 @@ class ExpressionHammer( (upcastNode, innerDeferreds) } - case ExternFunctionCallTE(prototype2, argsExprs2) => { + case ExternFunctionCallIE(prototype2, argsExprs2, _) => { val access = translateExternFunctionCall(hinputs, hamuts, currentFunctionHeader, locals, prototype2, argsExprs2) (access, Vector.empty) } - case while2 @ WhileTE(_) => { + case while2 @ WhileIE(_, _) => { val whileH = translateWhile(hinputs, hamuts, currentFunctionHeader, locals, while2) (whileH, Vector.empty) } - case DeferTE(innerExpr, deferredExpr) => { + case DeferIE(innerExpr, deferredExpr, _) => { val (innerExprHE, innerDeferreds) = translate(hinputs, hamuts, currentFunctionHeader, locals, innerExpr); (innerExprHE, Vector(deferredExpr) ++ innerDeferreds) } - case DiscardTE(innerExpr) => { + case DiscardIE(innerExpr) => { val (undiscardedInnerExprH, innerDeferreds) = translate(hinputs, hamuts, currentFunctionHeader, locals, innerExpr); vassert(innerDeferreds.isEmpty) // BMHD, probably need to translate them here. @@ -487,10 +496,10 @@ class ExpressionHammer( translateDeferreds(hinputs, hamuts, currentFunctionHeader, locals, innerExprH, innerDeferreds) (innerWithDeferredsExprH, Vector.empty) } - case ReturnTE(innerExpr) => { + case ReturnIE(innerExpr) => { vassert( - innerExpr.result.coord.kind == NeverT(false) || - innerExpr.result.coord == currentFunctionHeader.returnType) + innerExpr.result.kind == NeverIT[cI](false) || + innerExpr.result == currentFunctionHeader.returnType) val (innerExprHE, innerDeferreds) = translate(hinputs, hamuts, currentFunctionHeader, locals, innerExpr); @@ -509,10 +518,10 @@ class ExpressionHammer( case _ => } - vassert(innerExpr.result.coord == currentFunctionHeader.returnType) + vassert(innerExpr.result == currentFunctionHeader.returnType) (ReturnH(innerWithDeferreds), Vector.empty) } - case ArgLookupTE(paramIndex, type2) => { + case ArgLookupIE(paramIndex, type2) => { val typeH = typeHammer.translateCoord(hinputs, hamuts, type2) vassert(currentFunctionHeader.paramTypes(paramIndex) == type2) vassert(typeHammer.translateCoord(hinputs, hamuts, currentFunctionHeader.paramTypes(paramIndex)) == typeH) @@ -520,21 +529,21 @@ class ExpressionHammer( (argNode, Vector.empty) } - case das2 @ DestroyStaticSizedArrayIntoFunctionTE(_, _, _, _) => { + case das2 @ DestroyStaticSizedArrayIntoFunctionIE(_, _, _, _) => { val dasH = translateDestroyStaticSizedArray( hinputs, hamuts, currentFunctionHeader, locals, das2) (dasH, Vector.empty) } - case das2 @ DestroyImmRuntimeSizedArrayTE(_, _, _, _) => { + case das2 @ DestroyImmRuntimeSizedArrayIE(_, _, _, _) => { val drsaH = translateDestroyImmRuntimeSizedArray( hinputs, hamuts, currentFunctionHeader, locals, das2) (drsaH, Vector.empty) } -// case UnreachableMootTE(innerExpr) => { +// case UnreachableMootIE(innerExpr) => { // val (innerExprHE, innerDeferreds) = // translate(hinputs, hamuts, currentFunctionHeader, locals, innerExpr); // val innerWithDeferredsH = @@ -549,26 +558,26 @@ class ExpressionHammer( // (void, Vector.empty) // } - case BorrowToWeakTE(innerExpr) => { + case BorrowToWeakIE(innerExpr, _) => { val (innerExprHE, innerDeferreds) = translate(hinputs, hamuts, currentFunctionHeader, locals, innerExpr); (BorrowToWeakH(innerExprHE), innerDeferreds) } - case IsSameInstanceTE(leftExprT, rightExprT) => { + case IsSameInstanceIE(leftExprI, rightExprI) => { val (leftExprHE, leftDeferreds) = - translate(hinputs, hamuts, currentFunctionHeader, locals, leftExprT); + translate(hinputs, hamuts, currentFunctionHeader, locals, leftExprI); val (rightExprHE, rightDeferreds) = - translate(hinputs, hamuts, currentFunctionHeader, locals, rightExprT); + translate(hinputs, hamuts, currentFunctionHeader, locals, rightExprI); val resultHE = IsSameInstanceH(leftExprHE, rightExprHE) val expr = translateDeferreds(hinputs, hamuts, currentFunctionHeader, locals, resultHE, leftDeferreds ++ rightDeferreds) (expr, Vector.empty) } - case AsSubtypeTE(leftExprT, targetSubtype, resultOptType, someConstructor, noneConstructor, _, _, _) => { + case AsSubtypeIE(leftExprI, targetSubtype, resultOptType, someConstructor, noneConstructor, _, _, _, _) => { val (resultHE, deferreds) = - translate(hinputs, hamuts, currentFunctionHeader, locals, leftExprT); + translate(hinputs, hamuts, currentFunctionHeader, locals, leftExprI); val (targetSubtypeH) = typeHammer.translateCoord(hinputs, hamuts, targetSubtype).kind val (resultOptTypeH) = @@ -589,9 +598,9 @@ class ExpressionHammer( (resultNode, deferreds) } - case DestroyMutRuntimeSizedArrayTE(rsaTE) => { + case DestroyMutRuntimeSizedArrayIE(rsaIE) => { val (rsaHE, rsaDeferreds) = - translate(hinputs, hamuts, currentFunctionHeader, locals, rsaTE); + translate(hinputs, hamuts, currentFunctionHeader, locals, rsaIE); val destroyHE = DestroyMutRuntimeSizedArrayH(rsaHE.expectRuntimeSizedArrayAccess()) @@ -600,7 +609,7 @@ class ExpressionHammer( (expr, Vector.empty) } - case BreakTE() => { + case BreakIE() => { (BreakH(), Vector.empty) } @@ -611,12 +620,12 @@ class ExpressionHammer( } def translateDeferreds( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, originalExpr: ExpressionH[KindHT], - deferreds: Vector[ExpressionT]): + deferreds: Vector[ExpressionI]): ExpressionH[KindHT] = { if (deferreds.isEmpty) { return originalExpr @@ -663,13 +672,13 @@ class ExpressionHammer( } def translateExpressionsUntilNever( - hinputs: Hinputs, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + hinputs: HinputsI, hamuts: HamutsBox, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - exprsTE: Vector[ExpressionT]): - (Vector[ExpressionH[KindHT]], Vector[ExpressionT]) = { + exprsIE: Vector[ExpressionI]): + (Vector[ExpressionH[KindHT]], Vector[ExpressionI]) = { val (exprsHE, deferreds) = - exprsTE.foldLeft((Vector[ExpressionH[KindHT]](), Vector[ExpressionT]()))({ + exprsIE.foldLeft((Vector[ExpressionH[KindHT]](), Vector[ExpressionI]()))({ // If we previously saw a Never, stop there, don't proceed, don't even waste // time compiling the rest. case ((prevExprsHE, _), _) @@ -678,9 +687,9 @@ class ExpressionHammer( }) => { (prevExprsHE, Vector()) } - case ((prevExprsHE, prevDeferreds), nextTE) => { + case ((prevExprsHE, prevDeferreds), nextIE) => { val (nextHE, nextDeferreds) = - translate(hinputs, hamuts, currentFunctionHeader, locals, nextTE); + translate(hinputs, hamuts, currentFunctionHeader, locals, nextIE); (prevExprsHE :+ nextHE, prevDeferreds ++ nextDeferreds) } }) @@ -693,11 +702,11 @@ class ExpressionHammer( } def translateExpressionsAndDeferreds( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - exprs2: Vector[ExpressionT]): + exprs2: Vector[ExpressionI]): ExpressionH[KindHT] = { val exprs = exprs2.map({ case expr2 => @@ -711,12 +720,12 @@ class ExpressionHammer( } def translateExternFunctionCall( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - prototype2: PrototypeT, - argsExprs2: Vector[ReferenceExpressionTE]): + prototype2: PrototypeI[cI], + argsExprs2: Vector[ReferenceExpressionIE]): (ExpressionH[KindHT]) = { val (argsHE, argsDeferreds) = translateExpressionsUntilNever( @@ -741,13 +750,13 @@ class ExpressionHammer( } def translateFunctionPointerCall( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - function: PrototypeT, - args: Vector[ExpressionT], - resultType2: CoordT): + function: PrototypeI[cI], + args: Vector[ExpressionI], + resultType2: CoordI[cI]): ExpressionH[KindHT] = { val returnType2 = function.returnType val paramTypes = function.paramTypes @@ -782,12 +791,12 @@ class ExpressionHammer( } def translateNewMutRuntimeSizedArray( - hinputs: Hinputs, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + hinputs: HinputsI, hamuts: HamutsBox, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - constructArray2: NewMutRuntimeSizedArrayTE): + constructArray2: NewMutRuntimeSizedArrayIE): (ExpressionH[KindHT]) = { - val NewMutRuntimeSizedArrayTE(arrayType2, capacityExpr2) = constructArray2; + val NewMutRuntimeSizedArrayIE(arrayType2, capacityExpr2, _) = constructArray2; val (capacityRegisterId, capacityDeferreds) = translate( @@ -795,7 +804,7 @@ class ExpressionHammer( val (arrayRefTypeH) = typeHammer.translateCoord( - hinputs, hamuts, constructArray2.result.coord) + hinputs, hamuts, constructArray2.result) val (arrayTypeH) = typeHammer.translateRuntimeSizedArray(hinputs, hamuts, arrayType2) @@ -814,12 +823,12 @@ class ExpressionHammer( } def translateNewImmRuntimeSizedArray( - hinputs: Hinputs, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + hinputs: HinputsI, hamuts: HamutsBox, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - constructArray2: NewImmRuntimeSizedArrayTE): + constructArray2: NewImmRuntimeSizedArrayIE): (ExpressionH[KindHT]) = { - val NewImmRuntimeSizedArrayTE(arrayType2, sizeExpr2, generatorExpr2, generatorMethod) = constructArray2; + val NewImmRuntimeSizedArrayIE(arrayType2, sizeExpr2, generatorExpr2, generatorMethod, _) = constructArray2; val (sizeRegisterId, sizeDeferreds) = translate( @@ -831,7 +840,7 @@ class ExpressionHammer( val (arrayRefTypeH) = typeHammer.translateCoord( - hinputs, hamuts, constructArray2.result.coord) + hinputs, hamuts, constructArray2.result) val (arrayTypeH) = typeHammer.translateRuntimeSizedArray(hinputs, hamuts, arrayType2) @@ -855,13 +864,13 @@ class ExpressionHammer( } def translateStaticArrayFromCallable( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - exprTE: StaticArrayFromCallableTE): + exprIE: StaticArrayFromCallableIE): (ExpressionH[KindHT]) = { - val StaticArrayFromCallableTE(arrayType2, generatorExpr2, generatorMethod) = exprTE; + val StaticArrayFromCallableIE(arrayType2, generatorExpr2, generatorMethod, _) = exprIE; val (generatorRegisterId, generatorDeferreds) = translate( @@ -869,7 +878,7 @@ class ExpressionHammer( val (arrayRefTypeH) = typeHammer.translateCoord( - hinputs, hamuts, exprTE.result.coord) + hinputs, hamuts, exprIE.result) val (arrayTypeH) = typeHammer.translateStaticSizedArray(hinputs, hamuts, arrayType2) @@ -892,18 +901,18 @@ class ExpressionHammer( } def translateDestroyStaticSizedArray( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - das2: DestroyStaticSizedArrayIntoFunctionTE): + das2: DestroyStaticSizedArrayIntoFunctionIE): ExpressionH[KindHT] = { - val DestroyStaticSizedArrayIntoFunctionTE(arrayExpr2, staticSizedArrayType, consumerExpr2, consumerMethod2) = das2; + val DestroyStaticSizedArrayIntoFunctionIE(arrayExpr2, staticSizedArrayType, consumerExpr2, consumerMethod2) = das2; val (arrayTypeH) = typeHammer.translateStaticSizedArray(hinputs, hamuts, staticSizedArrayType) val (arrayRefTypeH) = - typeHammer.translateCoord(hinputs, hamuts, arrayExpr2.result.coord) + typeHammer.translateCoord(hinputs, hamuts, arrayExpr2.result) vassert(arrayRefTypeH.expectStaticSizedArrayCoord().kind == arrayTypeH) val (arrayExprResultHE, arrayExprDeferreds) = @@ -932,20 +941,20 @@ class ExpressionHammer( } def translateDestroyImmRuntimeSizedArray( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - das2: DestroyImmRuntimeSizedArrayTE): + das2: DestroyImmRuntimeSizedArrayIE): ExpressionH[KindHT] = { - val DestroyImmRuntimeSizedArrayTE(arrayExpr2, runtimeSizedArrayType2, consumerExpr2, consumerMethod2) = das2; + val DestroyImmRuntimeSizedArrayIE(arrayExpr2, runtimeSizedArrayType2, consumerExpr2, consumerMethod2) = das2; // val RuntimeSizedArrayT2(RawArrayT2(memberType2, mutability)) = runtimeSizedArrayType2 val (arrayTypeH) = typeHammer.translateRuntimeSizedArray(hinputs, hamuts, runtimeSizedArrayType2) val (arrayRefTypeH) = - typeHammer.translateCoord(hinputs, hamuts, arrayExpr2.result.coord) + typeHammer.translateCoord(hinputs, hamuts, arrayExpr2.result) vassert(arrayRefTypeH.expectRuntimeSizedArrayCoord().kind == arrayTypeH) val (arrayExprResultHE, arrayExprDeferreds) = @@ -976,17 +985,17 @@ class ExpressionHammer( } def translateIf( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, parentLocals: LocalsBox, - if2: IfTE): + if2: IfIE): ExpressionH[KindHT] = { - val IfTE(condition2, thenBlock2, elseBlock2) = if2 + val IfIE(condition2, thenBlock2, elseBlock2, _) = if2 val (conditionBlockH, Vector()) = translate(hinputs, hamuts, currentFunctionHeader, parentLocals, condition2); - vassert(conditionBlockH.resultType == CoordH(ShareH, InlineH, BoolHT())) + vassert(conditionBlockH.resultType == CoordH(MutableShareH, InlineH, BoolHT())) val thenLocals = LocalsBox(parentLocals.snapshot) val (thenBlockH, Vector()) = @@ -1001,7 +1010,7 @@ class ExpressionHammer( parentLocals.setNextLocalIdNumber(elseLocals.nextLocalIdNumber) val commonSupertypeH = - typeHammer.translateCoord(hinputs, hamuts, if2.result.coord) + typeHammer.translateCoord(hinputs, hamuts, if2.result) val ifCallNode = IfH(conditionBlockH.expectBoolAccess(), thenBlockH, elseBlockH, commonSupertypeH) @@ -1045,13 +1054,13 @@ class ExpressionHammer( } def translateWhile( - hinputs: Hinputs, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + hinputs: HinputsI, hamuts: HamutsBox, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - while2: WhileTE): + while2: WhileIE): WhileH = { - val WhileTE(bodyExpr2) = while2 + val WhileIE(bodyExpr2, _) = while2 val (exprWithoutDeferreds, deferreds) = translate(hinputs, hamuts, currentFunctionHeader, locals, bodyExpr2); @@ -1063,14 +1072,14 @@ class ExpressionHammer( } def translateInterfaceFunctionCall( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - superFunctionPrototype: PrototypeT, + superFunctionPrototype: PrototypeI[cI], virtualParamIndex: Int, - resultType2: CoordT, - argsExprs2: Vector[ExpressionT]): + resultType2: CoordI[cI], + argsExprs2: Vector[ExpressionI]): ExpressionH[KindHT] = { val (argsHE, argsDeferreds) = translateExpressionsUntilNever( @@ -1081,12 +1090,12 @@ class ExpressionHammer( } // val virtualParamIndex = superFunctionHeader.getVirtualIndex.get - val CoordT(_, _,interfaceTT @ InterfaceTT(_)) = + val CoordI(_, interfaceIT @ InterfaceIT(_)) = superFunctionPrototype.paramTypes(virtualParamIndex) val (interfaceRefH) = - structHammer.translateInterface(hinputs, hamuts, interfaceTT) - val edge = hinputs.interfaceToEdgeBlueprints(interfaceTT.id) - vassert(edge.interface == interfaceTT.id) + structHammer.translateInterface(hinputs, hamuts, interfaceIT) + val edge = hinputs.interfaceToEdgeBlueprints(interfaceIT.id) + vassert(edge.interface == interfaceIT.id) val indexInEdge = edge.superFamilyRootHeaders.indexWhere(x => superFunctionPrototype.toSignature == x._1.toSignature) vassert(indexInEdge >= 0) diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/FunctionHammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/FunctionHammer.scala index 86bb2ae3b..c3ec91f5d 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/FunctionHammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/FunctionHammer.scala @@ -1,14 +1,9 @@ package dev.vale.simplifying -import dev.vale.finalast.{FunctionH, Local, NeverHT, PureH, UserFunctionH, VariableIdH} -import dev.vale.typing.Hinputs -import dev.vale.typing.ast.{ExternT, FunctionHeaderT, FunctionDefinitionT, IFunctionAttributeT, PrototypeT, PureT, UserFunctionT} -import dev.vale.typing.names.{IdT, IVarNameT} +import dev.vale.finalast.{FunctionH, Local, PureH, UserFunctionH, VariableIdH} import dev.vale.{Keywords, vassert, vfail, vimpl, vwat, finalast => m} import dev.vale.finalast._ -import dev.vale.typing._ -import dev.vale.typing.ast._ -import dev.vale.typing.names.IVarNameT +import dev.vale.instantiating.ast._ class FunctionHammer( keywords: Keywords, @@ -19,9 +14,9 @@ class FunctionHammer( new ExpressionHammer(keywords, typeHammer, nameHammer, structHammer, this) def translateFunctions( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - functions2: Vector[FunctionDefinitionT]): + functions2: Vector[FunctionDefinitionI]): (Vector[FunctionRefH]) = { functions2.foldLeft((Vector[FunctionRefH]()))({ case ((previousFunctionsH), function2) => { @@ -32,16 +27,16 @@ class FunctionHammer( } def translateFunction( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - function2: FunctionDefinitionT): + function2: FunctionDefinitionI): (FunctionRefH) = { // opts.debugOut("Translating function " + function2.header.fullName) hamuts.functionRefs.get(function2.header.toPrototype) match { case Some(functionRefH) => functionRefH case None => { - val FunctionDefinitionT( - header @ FunctionHeaderT(humanName, attrs2, params2, returnType2, _), + val FunctionDefinitionI( + header @ FunctionHeaderI(humanName, attrs2, params2, returnType2), _, _, body) = function2; @@ -53,7 +48,7 @@ class FunctionHammer( val locals = LocalsBox( Locals( - Map[IVarNameT, VariableIdH](), + Map[IVarNameI[cI], VariableIdH](), Set[VariableIdH](), Map[VariableIdH,Local](), 1)); @@ -74,8 +69,8 @@ class FunctionHammer( } val isAbstract = header.getAbstractInterface.nonEmpty - val isExtern = header.attributes.exists({ case ExternT(packageCoord) => true case _ => false }) - val attrsH = translateFunctionAttributes(attrs2.filter(a => !a.isInstanceOf[ExternT])) + val isExtern = header.attributes.exists({ case ExternI(packageCoord) => true case _ => false }) + val attrsH = translateFunctionAttributes(attrs2.filter(a => !a.isInstanceOf[ExternI])) val functionH = FunctionH(prototypeH, isAbstract, isExtern, attrsH, bodyH); hamuts.addFunction(header.toPrototype, functionH) @@ -84,20 +79,20 @@ class FunctionHammer( } } - def translateFunctionAttributes(attributes: Vector[IFunctionAttributeT]) = { + def translateFunctionAttributes(attributes: Vector[IFunctionAttributeI]) = { attributes.map({ - case UserFunctionT => UserFunctionH - case PureT => PureH - case ExternT(_) => vwat() // Should have been filtered out, hammer cares about extern directly + case UserFunctionI => UserFunctionH + case PureI => PureH + case ExternI(_) => vwat() // Should have been filtered out, hammer cares about extern directly case x => vimpl(x.toString) }) } def translateFunctionRef( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, - prototype2: PrototypeT): + currentFunctionHeader: FunctionHeaderI, + prototype2: PrototypeI[cI]): (FunctionRefH) = { val (prototypeH) = typeHammer.translatePrototype(hinputs, hamuts, prototype2); val functionRefH = FunctionRefH(prototypeH); diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hammer.scala index 319573587..3bd6b0c22 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hammer.scala @@ -1,23 +1,18 @@ package dev.vale.simplifying import dev.vale.{Builtins, FileCoordinateMap, IPackageResolver, Interner, Keywords, PackageCoordinate, PackageCoordinateMap, Profiler, Result, finalast, vassert, vcurious, vfail, vwat} -import dev.vale.finalast.{ConsecutorH, ConstantVoidH, ExpressionH, Final, IdH, KindHT, Local, NeverHT, PackageH, ProgramH, PrototypeH, CoordH, StackifyH, Variability, VariableIdH, VoidHT} -import dev.vale.typing.Hinputs -import dev.vale.typing.ast.{FunctionExportT, FunctionExternT, KindExportT, KindExternT} -import dev.vale.typing.names.{IdT, IVarNameT} +import dev.vale.finalast.{ConsecutorH, ConstantVoidH, CoordH, ExpressionH, Final, IdH, KindHT, Local, NeverHT, PackageH, ProgramH, PrototypeH, StackifyH, Variability, VariableIdH, VoidHT} import dev.vale.highertyping.ICompileErrorA import dev.vale.finalast._ +import dev.vale.instantiating.ast._ import dev.vale.postparsing.ICompileErrorS -import dev.vale.typing.ast._ -import dev.vale.typing.names.IVarNameT -import dev.vale.typing.{types => t} import scala.collection.immutable.List case class FunctionRefH(prototype: PrototypeH) { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; override def equals(obj: Any): Boolean = vcurious(); // def functionType = prototype.functionType - def fullName = prototype.fullName + def fullName = prototype.id } case class LocalsBox(var inner: Locals) { @@ -25,18 +20,18 @@ case class LocalsBox(var inner: Locals) { def snapshot = inner - def typingPassLocals: Map[IVarNameT, VariableIdH] = inner.typingPassLocals + def typingPassLocals: Map[IVarNameI[cI], VariableIdH] = inner.typingPassLocals def unstackifiedVars: Set[VariableIdH] = inner.unstackifiedVars def locals: Map[VariableIdH, Local] = inner.locals def nextLocalIdNumber: Int = inner.nextLocalIdNumber - def get(id: IVarNameT) = inner.get(id) + def get(id: IVarNameI[cI]) = inner.get(id) def get(id: VariableIdH) = inner.get(id) - def markUnstackified(varId2: IVarNameT): Unit = { + def markUnstackified(varId2: IVarNameI[cI]): Unit = { inner = inner.markUnstackified(varId2) } - def markRestackified(varId2: IVarNameT): Unit = { + def markRestackified(varId2: IVarNameI[cI]): Unit = { inner = inner.markRestackified(varId2) } @@ -57,7 +52,7 @@ case class LocalsBox(var inner: Locals) { } def addTypingPassLocal( - varId2: IVarNameT, + varId2: IVarNameI[cI], varIdNameH: IdH, variability: Variability, tyype: CoordH[KindHT]): @@ -75,7 +70,7 @@ case class LocalsBox(var inner: Locals) { case class Locals( // This doesn't have all the locals that are in the locals list, this just // has any locals added by typingpass. - typingPassLocals: Map[IVarNameT, VariableIdH], + typingPassLocals: Map[IVarNameI[cI], VariableIdH], unstackifiedVars: Set[VariableIdH], @@ -86,7 +81,7 @@ case class Locals( override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() def addCompilerLocal( - varId2: IVarNameT, + varId2: IVarNameI[cI], varIdNameH: IdH, variability: Variability, tyype: CoordH[KindHT]): @@ -126,11 +121,11 @@ case class Locals( (newLocals, newLocal) } - def markUnstackified(varId2: IVarNameT): Locals = { + def markUnstackified(varId2: IVarNameI[cI]): Locals = { markUnstackified(typingPassLocals(varId2)) } - def markRestackified(varId2: IVarNameT): Locals = { + def markRestackified(varId2: IVarNameI[cI]): Locals = { markRestackified(typingPassLocals(varId2)) } @@ -152,7 +147,7 @@ case class Locals( Locals(typingPassLocals, unstackifiedVars - varIdH, locals, nextLocalIdNumber) } - def get(varId: IVarNameT): Option[Local] = { + def get(varId: IVarNameI[cI]): Option[Local] = { typingPassLocals.get(varId) match { case None => None case Some(index) => Some(locals(index)) @@ -171,24 +166,22 @@ class Hammer(interner: Interner, keywords: Keywords) { interner, keywords, nameHammer, - (hinputs, hamuts, prototypeT) => typeHammer.translatePrototype(hinputs, hamuts, prototypeT), - (hinputs, hamuts, referenceT) => typeHammer.translateCoord(hinputs, hamuts, referenceT)) + (hinputs, hamuts, prototypeI) => typeHammer.translatePrototype(hinputs, hamuts, prototypeI), + (hinputs, hamuts, referenceI) => typeHammer.translateCoord(hinputs, hamuts, referenceI)) val typeHammer: TypeHammer = new TypeHammer(interner, keywords, nameHammer, structHammer) val functionHammer = new FunctionHammer(keywords, typeHammer, nameHammer, structHammer) val vonHammer = new VonHammer(nameHammer, typeHammer) - def translate(hinputs: Hinputs): ProgramH = { - val Hinputs( + def translate(hinputs: HinputsI): ProgramH = { + val HinputsI( interfaces, structs, functions, // kindToDestructor, interfaceToEdgeBlueprints, edges, - _, kindExports, functionExports, - kindExterns, functionExterns) = hinputs @@ -196,24 +189,24 @@ class Hammer(interner: Interner, keywords: Keywords) { // val emptyPackStructRefH = structHammer.translateStructRef(hinputs, hamuts, emptyPackStructRef) // vassert(emptyPackStructRefH == ProgramH.emptyTupleStructRef) - kindExports.foreach({ case KindExportT(_, tyype, packageId, exportName) => + kindExports.foreach({ case KindExportI(_, tyype, exportId, exportName) => val kindH = typeHammer.translateKind(hinputs, hamuts, tyype) - hamuts.addKindExport(kindH, packageId.packageCoord, exportName) + hamuts.addKindExport(kindH, exportId.packageCoord, exportName) }) - functionExports.foreach({ case FunctionExportT(_, prototype, packageId, exportName) => + functionExports.foreach({ case FunctionExportI(_, prototype, exportId, exportName) => val prototypeH = typeHammer.translatePrototype(hinputs, hamuts, prototype) - hamuts.addFunctionExport(prototypeH, packageId.packageCoord, exportName) + hamuts.addFunctionExport(prototypeH, exportId.packageCoord, exportName) }) - kindExterns.foreach({ case KindExternT(tyype, packageCoordinate, exportName) => - val kindH = typeHammer.translateKind(hinputs, hamuts, tyype) - hamuts.addKindExtern(kindH, packageCoordinate, exportName) - }) +// kindExterns.foreach({ case KindExternI(tyype, packageCoordinate, exportName) => +// val kindH = typeHammer.translateKind(hinputs, hamuts, tyype) +// hamuts.addKindExtern(kindH, packageCoordinate, exportName) +// }) - functionExterns.foreach({ case FunctionExternT(_, externPlaceholderedId, prototype, exportName) => + functionExterns.foreach({ case FunctionExternI(prototype, exportName) => val prototypeH = typeHammer.translatePrototype(hinputs, hamuts, prototype) - hamuts.addFunctionExtern(prototypeH, externPlaceholderedId.packageCoord, exportName) + hamuts.addFunctionExtern(prototypeH, exportName) }) // We generate the names here first, so that externs get the first chance at having @@ -255,7 +248,7 @@ class Hammer(interner: Interner, keywords: Keywords) { // }) val packageToInterfaceDefs = hamuts.interfaceTToInterfaceDefH.groupBy(_._1.id.packageCoord) - val packageToStructDefs = hamuts.structDefs.groupBy(_.fullName.packageCoordinate) + val packageToStructDefs = hamuts.structDefs.groupBy(_.id.packageCoordinate) val packageToFunctionDefs = hamuts.functionDefs.groupBy(_._1.id.packageCoord).mapValues(_.values.toVector) val packageToStaticSizedArrays = hamuts.staticSizedArrays.values.toVector.groupBy(_.name.packageCoordinate) val packageToRuntimeSizedArrays = hamuts.runtimeSizedArrays.values.toVector.groupBy(_.name.packageCoordinate) diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/HammerCompilation.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/HammerCompilation.scala index b43630837..d7d1c1eff 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/HammerCompilation.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/HammerCompilation.scala @@ -5,13 +5,13 @@ import dev.vale.finalast.ProgramH import dev.vale.options.GlobalOptions import dev.vale.parsing.ast.FileP import dev.vale.postparsing._ -import dev.vale.typing.{Hinputs, ICompileErrorT} import dev.vale.{FileCoordinateMap, IPackageResolver, Interner, Keywords, PackageCoordinate, PackageCoordinateMap, Profiler, Result, vassertSome, vcurious, vimpl} import dev.vale.highertyping.ICompileErrorA +import dev.vale.instantiating.ast.HinputsI import dev.vale.lexing.{FailedParse, RangeL} import dev.vale.instantiating.{InstantiatedCompilation, InstantiatorCompilationOptions} import dev.vale.postparsing.ICompileErrorS -import dev.vale.typing.ICompileErrorT +import dev.vale.typing.{HinputsT, ICompileErrorT} import scala.collection.immutable.List @@ -47,9 +47,9 @@ class HammerCompilation( def getVpstMap(): Result[FileCoordinateMap[String], FailedParse] = instantiatedCompilation.getVpstMap() def getScoutput(): Result[FileCoordinateMap[ProgramS], ICompileErrorS] = instantiatedCompilation.getScoutput() def getAstrouts(): Result[PackageCoordinateMap[ProgramA], ICompileErrorA] = instantiatedCompilation.getAstrouts() - def getCompilerOutputs(): Result[Hinputs, ICompileErrorT] = instantiatedCompilation.getCompilerOutputs() - def getMonouts(): Hinputs = instantiatedCompilation.getMonouts() - def expectCompilerOutputs(): Hinputs = instantiatedCompilation.expectCompilerOutputs() + def getCompilerOutputs(): Result[HinputsT, ICompileErrorT] = instantiatedCompilation.getCompilerOutputs() + def getMonouts(): HinputsI = instantiatedCompilation.getMonouts() + def expectCompilerOutputs(): HinputsT = instantiatedCompilation.expectCompilerOutputs() def getHamuts(): ProgramH = { hamutsCache match { diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hamuts.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hamuts.scala index f95cc864d..cc74ad16c 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hamuts.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hamuts.scala @@ -1,11 +1,8 @@ package dev.vale.simplifying import dev.vale.{PackageCoordinate, StrI, vassert, vcurious, vfail, vimpl} -import dev.vale.finalast.{IdH, FunctionH, InterfaceDefinitionH, InterfaceHT, KindHT, PrototypeH, RuntimeSizedArrayDefinitionHT, RuntimeSizedArrayHT, StaticSizedArrayDefinitionHT, StaticSizedArrayHT, StructDefinitionH, StructHT} -import dev.vale.typing.ast.PrototypeT -import dev.vale.typing.types._ import dev.vale.finalast._ -import dev.vale.typing.types.InterfaceTT +import dev.vale.instantiating.ast._ import dev.vale.von.IVonData @@ -16,49 +13,49 @@ case class HamutsBox(var inner: Hamuts) { def packageCoordToExportNameToKind: Map[PackageCoordinate, Map[StrI, KindHT]] = inner.packageCoordToExportNameToKind def packageCoordToExternNameToFunction: Map[PackageCoordinate, Map[StrI, PrototypeH]] = inner.packageCoordToExternNameToFunction def packageCoordToExternNameToKind: Map[PackageCoordinate, Map[StrI, KindHT]] = inner.packageCoordToExternNameToKind - def structTToStructH: Map[StructTT, StructHT] = inner.structTToStructH - def structTToStructDefH: Map[StructTT, StructDefinitionH] = inner.structTToStructDefH + def structTToStructH: Map[StructIT[cI], StructHT] = inner.structTToStructH + def structTToStructDefH: Map[StructIT[cI], StructDefinitionH] = inner.structTToStructDefH def structDefs: Vector[StructDefinitionH] = inner.structDefs - def interfaceTToInterfaceH: Map[InterfaceTT, InterfaceHT] = inner.interfaceTToInterfaceH - def interfaceTToInterfaceDefH: Map[InterfaceTT, InterfaceDefinitionH] = inner.interfaceTToInterfaceDefH - def functionRefs: Map[PrototypeT, FunctionRefH] = inner.functionRefs - def functionDefs: Map[PrototypeT, FunctionH] = inner.functionDefs - def staticSizedArrays: Map[StaticSizedArrayTT, StaticSizedArrayDefinitionHT] = inner.staticSizedArrays - def runtimeSizedArrays: Map[RuntimeSizedArrayTT, RuntimeSizedArrayDefinitionHT] = inner.runtimeSizedArrays - - def forwardDeclareStruct(structTT: StructTT, structRefH: StructHT): Unit = { - inner = inner.forwardDeclareStruct(structTT, structRefH) + def interfaceTToInterfaceH: Map[InterfaceIT[cI], InterfaceHT] = inner.interfaceTToInterfaceH + def interfaceTToInterfaceDefH: Map[InterfaceIT[cI], InterfaceDefinitionH] = inner.interfaceTToInterfaceDefH + def functionRefs: Map[PrototypeI[cI], FunctionRefH] = inner.functionRefs + def functionDefs: Map[PrototypeI[cI], FunctionH] = inner.functionDefs + def staticSizedArrays: Map[StaticSizedArrayIT[cI], StaticSizedArrayDefinitionHT] = inner.staticSizedArrays + def runtimeSizedArrays: Map[RuntimeSizedArrayIT[cI], RuntimeSizedArrayDefinitionHT] = inner.runtimeSizedArrays + + def forwardDeclareStruct(structIT: StructIT[cI], structRefH: StructHT): Unit = { + inner = inner.forwardDeclareStruct(structIT, structRefH) } - def addStructOriginatingFromTypingPass(structTT: StructTT, structDefH: StructDefinitionH): Unit = { - inner = inner.addStructOriginatingFromTypingPass(structTT, structDefH) + def addStructOriginatingFromTypingPass(structIT: StructIT[cI], structDefH: StructDefinitionH): Unit = { + inner = inner.addStructOriginatingFromTypingPass(structIT, structDefH) } def addStructOriginatingFromHammer(structDefH: StructDefinitionH): Unit = { inner = inner.addStructOriginatingFromHammer(structDefH) } - def forwardDeclareInterface(interfaceTT: InterfaceTT, interfaceRefH: InterfaceHT): Unit = { - inner = inner.forwardDeclareInterface(interfaceTT, interfaceRefH) + def forwardDeclareInterface(interfaceIT: InterfaceIT[cI], interfaceRefH: InterfaceHT): Unit = { + inner = inner.forwardDeclareInterface(interfaceIT, interfaceRefH) } - def addInterface(interfaceTT: InterfaceTT, interfaceDefH: InterfaceDefinitionH): Unit = { - inner = inner.addInterface(interfaceTT, interfaceDefH) + def addInterface(interfaceIT: InterfaceIT[cI], interfaceDefH: InterfaceDefinitionH): Unit = { + inner = inner.addInterface(interfaceIT, interfaceDefH) } - def addStaticSizedArray(ssaTT: StaticSizedArrayTT, staticSizedArrayDefinitionTH: StaticSizedArrayDefinitionHT): Unit = { - inner = inner.addStaticSizedArray(ssaTT, staticSizedArrayDefinitionTH) + def addStaticSizedArray(ssaIT: StaticSizedArrayIT[cI], staticSizedArrayDefinitionTH: StaticSizedArrayDefinitionHT): Unit = { + inner = inner.addStaticSizedArray(ssaIT, staticSizedArrayDefinitionTH) } - def addRuntimeSizedArray(rsaTT: RuntimeSizedArrayTT, runtimeSizedArrayDefinitionTH: RuntimeSizedArrayDefinitionHT): Unit = { - inner = inner.addRuntimeSizedArray(rsaTT, runtimeSizedArrayDefinitionTH) + def addRuntimeSizedArray(rsaIT: RuntimeSizedArrayIT[cI], runtimeSizedArrayDefinitionTH: RuntimeSizedArrayDefinitionHT): Unit = { + inner = inner.addRuntimeSizedArray(rsaIT, runtimeSizedArrayDefinitionTH) } - def forwardDeclareFunction(functionRef2: PrototypeT, functionRefH: FunctionRefH): Unit = { + def forwardDeclareFunction(functionRef2: PrototypeI[cI], functionRefH: FunctionRefH): Unit = { inner = inner.forwardDeclareFunction(functionRef2, functionRefH) } - def addFunction(functionRef2: PrototypeT, functionDefH: FunctionH): Unit = { + def addFunction(functionRef2: PrototypeI[cI], functionDefH: FunctionH): Unit = { inner = inner.addFunction(functionRef2, functionDefH) } @@ -66,16 +63,16 @@ case class HamutsBox(var inner: Hamuts) { inner = inner.addKindExport(kind, packageCoordinate, exportedName) } - def addKindExtern(kind: KindHT, packageCoordinate: PackageCoordinate, exportedName: StrI): Unit = { - inner = inner.addKindExtern(kind, packageCoordinate, exportedName) - } +// def addKindExtern(kind: KindHT, packageCoordinate: PackageCoordinate, exportedName: StrI): Unit = { +// inner = inner.addKindExtern(kind, packageCoordinate, exportedName) +// } def addFunctionExport(prototype: PrototypeH, packageCoordinate: PackageCoordinate, exportedName: StrI): Unit = { inner = inner.addFunctionExport(prototype, packageCoordinate, exportedName) } - def addFunctionExtern(prototype: PrototypeH, packageCoordinate: PackageCoordinate, exportedName: StrI): Unit = { - inner = inner.addFunctionExtern(prototype, packageCoordinate, exportedName) + def addFunctionExtern(prototype: PrototypeH, exportedName: StrI): Unit = { + inner = inner.addFunctionExtern(prototype, exportedName) } // def getNameId(readableName: String, packageCoordinate: PackageCoordinate, parts: Vector[IVonData]): Int = { @@ -94,15 +91,15 @@ case class HamutsBox(var inner: Hamuts) { case class Hamuts( humanNameToFullNameToId: Map[String, Map[String, Int]], - structTToStructH: Map[StructTT, StructHT], - structTToStructDefH: Map[StructTT, StructDefinitionH], + structTToStructH: Map[StructIT[cI], StructHT], + structTToStructDefH: Map[StructIT[cI], StructDefinitionH], structDefs: Vector[StructDefinitionH], - staticSizedArrays: Map[StaticSizedArrayTT, StaticSizedArrayDefinitionHT], - runtimeSizedArrays: Map[RuntimeSizedArrayTT, RuntimeSizedArrayDefinitionHT], - interfaceTToInterfaceH: Map[InterfaceTT, InterfaceHT], - interfaceTToInterfaceDefH: Map[InterfaceTT, InterfaceDefinitionH], - functionRefs: Map[PrototypeT, FunctionRefH], - functionDefs: Map[PrototypeT, FunctionH], + staticSizedArrays: Map[StaticSizedArrayIT[cI], StaticSizedArrayDefinitionHT], + runtimeSizedArrays: Map[RuntimeSizedArrayIT[cI], RuntimeSizedArrayDefinitionHT], + interfaceTToInterfaceH: Map[InterfaceIT[cI], InterfaceHT], + interfaceTToInterfaceDefH: Map[InterfaceIT[cI], InterfaceDefinitionH], + functionRefs: Map[PrototypeI[cI], FunctionRefH], + functionDefs: Map[PrototypeI[cI], FunctionH], packageCoordToExportNameToFunction: Map[PackageCoordinate, Map[StrI, PrototypeH]], packageCoordToExportNameToKind: Map[PackageCoordinate, Map[StrI, KindHT]], packageCoordToExternNameToFunction: Map[PackageCoordinate, Map[StrI, PrototypeH]], @@ -110,13 +107,13 @@ case class Hamuts( override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vfail() // Would need a really good reason to hash something this big vassert(functionDefs.values.map(_.fullName).toVector.distinct.size == functionDefs.values.size) - vassert(structDefs.map(_.fullName).distinct.size == structDefs.size) + vassert(structDefs.map(_.id).distinct.size == structDefs.size) vassert(runtimeSizedArrays.values.map(_.name).toVector.distinct.size == runtimeSizedArrays.size) - def forwardDeclareStruct(structTT: StructTT, structRefH: StructHT): Hamuts = { + def forwardDeclareStruct(structIT: StructIT[cI], structRefH: StructHT): Hamuts = { Hamuts( humanNameToFullNameToId, - structTToStructH + (structTT -> structRefH), + structTToStructH + (structIT -> structRefH), structTToStructDefH, structDefs, staticSizedArrays, @@ -131,15 +128,16 @@ case class Hamuts( packageCoordToExternNameToKind) } - def addStructOriginatingFromTypingPass(structTT: StructTT, structDefH: StructDefinitionH): Hamuts = { + def addStructOriginatingFromTypingPass(structTT: StructIT[cI], structDefH: StructDefinitionH): Hamuts = { vassert(structTToStructH.contains(structTT)) structTToStructDefH.get(structTT) match { case Some(existingDef) => { + // DO NOT SUBMIT // Added all this to help VmdSiteGen. Apparently it calls this method twice with the same structs sometimes? - vassert(existingDef.fullName == structDefH.fullName) + vassert(existingDef.id == structDefH.id) vassert(existingDef.members.map(_.name) == structDefH.members.map(_.name)) vassert(existingDef.members.map(_.tyype) == structDefH.members.map(_.tyype)) - vassert(structDefs.exists(_.fullName == structDefH.fullName)) + vassert(structDefs.exists(_.id == structDefH.id)) this } case None => { @@ -163,7 +161,7 @@ case class Hamuts( } def addStructOriginatingFromHammer(structDefH: StructDefinitionH): Hamuts = { - vassert(!structDefs.exists(_.fullName == structDefH.fullName)) + vassert(!structDefs.exists(_.id == structDefH.id)) Hamuts( humanNameToFullNameToId, @@ -182,7 +180,7 @@ case class Hamuts( packageCoordToExternNameToKind) } - def forwardDeclareInterface(interfaceTT: InterfaceTT, interfaceRefH: InterfaceHT): Hamuts = { + def forwardDeclareInterface(interfaceIT: InterfaceIT[cI], interfaceRefH: InterfaceHT): Hamuts = { Hamuts( humanNameToFullNameToId, structTToStructH, @@ -190,7 +188,7 @@ case class Hamuts( structDefs, staticSizedArrays, runtimeSizedArrays, - interfaceTToInterfaceH + (interfaceTT -> interfaceRefH), + interfaceTToInterfaceH + (interfaceIT -> interfaceRefH), interfaceTToInterfaceDefH, functionRefs, functionDefs, @@ -200,8 +198,8 @@ case class Hamuts( packageCoordToExternNameToKind) } - def addInterface(interfaceTT: InterfaceTT, interfaceDefH: InterfaceDefinitionH): Hamuts = { - vassert(interfaceTToInterfaceH.contains(interfaceTT)) + def addInterface(interfaceIT: InterfaceIT[cI], interfaceDefH: InterfaceDefinitionH): Hamuts = { + vassert(interfaceTToInterfaceH.contains(interfaceIT)) Hamuts( humanNameToFullNameToId, structTToStructH, @@ -210,7 +208,7 @@ case class Hamuts( staticSizedArrays, runtimeSizedArrays, interfaceTToInterfaceH, - interfaceTToInterfaceDefH + (interfaceTT -> interfaceDefH), + interfaceTToInterfaceDefH + (interfaceIT -> interfaceDefH), functionRefs, functionDefs, packageCoordToExportNameToFunction, @@ -219,7 +217,7 @@ case class Hamuts( packageCoordToExternNameToKind) } - def forwardDeclareFunction(functionRef2: PrototypeT, functionRefH: FunctionRefH): Hamuts = { + def forwardDeclareFunction(functionRef2: PrototypeI[cI], functionRefH: FunctionRefH): Hamuts = { vassert(!functionRefs.contains(functionRef2)) Hamuts( @@ -239,7 +237,7 @@ case class Hamuts( packageCoordToExternNameToKind) } - def addFunction(functionRef2: PrototypeT, functionDefH: FunctionH): Hamuts = { + def addFunction(functionRef2: PrototypeI[cI], functionDefH: FunctionH): Hamuts = { vassert(functionRefs.contains(functionRef2)) functionDefs.find(_._2.fullName == functionDefH.fullName) match { case None => @@ -335,42 +333,43 @@ case class Hamuts( packageCoordToExternNameToKind) } - def addKindExtern(kind: KindHT, packageCoordinate: PackageCoordinate, exportedName: StrI): Hamuts = { - val newPackageCoordToExternNameToKind = - packageCoordToExternNameToKind.get(packageCoordinate) match { - case None => { - packageCoordToExternNameToKind + (packageCoordinate -> Map(exportedName -> kind)) - } - case Some(exportNameToFullName) => { - exportNameToFullName.get(exportedName) match { - case None => { - packageCoordToExternNameToKind + (packageCoordinate -> (exportNameToFullName + (exportedName -> kind))) - } - case Some(existingFullName) => { - vfail("Already exported a `" + exportedName + "` from package `" + packageCoordinate + " : " + existingFullName) - } - } - } - } - - Hamuts( - humanNameToFullNameToId, - structTToStructH, - structTToStructDefH, - structDefs, - staticSizedArrays, - runtimeSizedArrays, - interfaceTToInterfaceH, - interfaceTToInterfaceDefH, - functionRefs, - functionDefs, - packageCoordToExportNameToFunction, - packageCoordToExportNameToKind, - packageCoordToExternNameToFunction, - newPackageCoordToExternNameToKind) - } +// def addKindExtern(kind: KindHT, packageCoordinate: PackageCoordinate, exportedName: StrI): Hamuts = { +// val newPackageCoordToExternNameToKind = +// packageCoordToExternNameToKind.get(packageCoordinate) match { +// case None => { +// packageCoordToExternNameToKind + (packageCoordinate -> Map(exportedName -> kind)) +// } +// case Some(exportNameToFullName) => { +// exportNameToFullName.get(exportedName) match { +// case None => { +// packageCoordToExternNameToKind + (packageCoordinate -> (exportNameToFullName + (exportedName -> kind))) +// } +// case Some(existingFullName) => { +// vfail("Already exported a `" + exportedName + "` from package `" + packageCoordinate + " : " + existingFullName) +// } +// } +// } +// } +// +// Hamuts( +// humanNameToFullNameToId, +// structTToStructH, +// structTToStructDefH, +// structDefs, +// staticSizedArrays, +// runtimeSizedArrays, +// interfaceTToInterfaceH, +// interfaceTToInterfaceDefH, +// functionRefs, +// functionDefs, +// packageCoordToExportNameToFunction, +// packageCoordToExportNameToKind, +// packageCoordToExternNameToFunction, +// newPackageCoordToExternNameToKind) +// } - def addFunctionExtern(function: PrototypeH, packageCoordinate: PackageCoordinate, exportedName: StrI): Hamuts = { + def addFunctionExtern(function: PrototypeH, exportedName: StrI): Hamuts = { + val packageCoordinate = function.id.packageCoordinate val newPackageCoordToExternNameToFunction = packageCoordToExternNameToFunction.get(packageCoordinate) match { case None => { @@ -406,7 +405,7 @@ case class Hamuts( } def addStaticSizedArray( - ssaTT: StaticSizedArrayTT, + ssaIT: StaticSizedArrayIT[cI], staticSizedArrayDefinitionHT: StaticSizedArrayDefinitionHT ): Hamuts = { Hamuts( @@ -414,7 +413,7 @@ case class Hamuts( structTToStructH, structTToStructDefH, structDefs, - staticSizedArrays + (ssaTT -> staticSizedArrayDefinitionHT), + staticSizedArrays + (ssaIT -> staticSizedArrayDefinitionHT), runtimeSizedArrays, interfaceTToInterfaceH, interfaceTToInterfaceDefH, @@ -427,7 +426,7 @@ case class Hamuts( } def addRuntimeSizedArray( - rsaTT: RuntimeSizedArrayTT, + rsaIT: RuntimeSizedArrayIT[cI], runtimeSizedArrayDefinitionHT: RuntimeSizedArrayDefinitionHT ): Hamuts = { Hamuts( @@ -436,7 +435,7 @@ case class Hamuts( structTToStructDefH, structDefs, staticSizedArrays, - runtimeSizedArrays + (rsaTT -> runtimeSizedArrayDefinitionHT), + runtimeSizedArrays + (rsaIT -> runtimeSizedArrayDefinitionHT), interfaceTToInterfaceH, interfaceTToInterfaceDefH, functionRefs, diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/LetHammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/LetHammer.scala index c78cd88c6..627391bf6 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/LetHammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/LetHammer.scala @@ -1,19 +1,9 @@ package dev.vale.simplifying -import dev.vale.finalast.{BorrowH, ConsecutorH, CoordH, DestroyH, DestroyStaticSizedArrayIntoLocalsH, DiscardH, ExpressionH, Final, KindHT, Local, NeverHT, NewStructH, OwnH, StackifyH, UnstackifyH, YonderH} -import dev.vale.typing.Hinputs -import dev.vale.typing.ast.{DestroyStaticSizedArrayIntoLocalsTE, DestroyTE, FunctionHeaderT, LetAndLendTE, LetNormalTE, ReferenceExpressionTE, UnletTE} -import dev.vale.typing.env.{AddressibleLocalVariableT, ReferenceLocalVariableT} -import dev.vale.typing.names.{IVarNameT, IdT} -import dev.vale.typing.types._ -import dev.vale.{vassert, vassertSome, vfail, vimpl, vwat, finalast => m} import dev.vale.finalast._ -import dev.vale.typing._ -import dev.vale.typing.ast._ -import dev.vale.typing.env.ReferenceLocalVariableT -import dev.vale.typing.names.IVarNameT -import dev.vale.typing.templata.ITemplataT.expectIntegerTemplata -import dev.vale.typing.types._ +import dev.vale.{vassert, vassertSome, vfail, vimpl, vregionmut, vwat, finalast => m} +import dev.vale.finalast._ +import dev.vale.instantiating.ast._ object LetHammer { val BOX_MEMBER_INDEX: Int = 0 @@ -27,18 +17,18 @@ class LetHammer( loadHammer: LoadHammer) { def translateLet( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - let2: LetNormalTE): + let2: LetNormalIE): ExpressionH[KindHT] = { - val LetNormalTE(localVariable, sourceExpr2) = let2 + val LetNormalIE(localVariable, sourceExpr2, _) = let2 val (sourceExprHE, deferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, sourceExpr2); val (sourceResultPointerTypeH) = - typeHammer.translateCoord(hinputs, hamuts, sourceExpr2.result.coord) + typeHammer.translateCoord(hinputs, hamuts, sourceExpr2.result) sourceExprHE.resultType.kind match { // We'll never get to this let, so strip it out. See BRCOBS. @@ -48,11 +38,11 @@ class LetHammer( val stackifyNode = localVariable match { - case ReferenceLocalVariableT(varId, variability, type2) => { + case ReferenceLocalVariableI(varId, variability, type2) => { translateMundaneLet( hinputs, hamuts, currentFunctionHeader, locals, sourceExprHE, sourceResultPointerTypeH, varId, variability) } - case AddressibleLocalVariableT(varId, variability, reference) => { + case AddressibleLocalVariableI(varId, variability, reference) => { translateAddressibleLet( hinputs, hamuts, currentFunctionHeader, locals, sourceExprHE, sourceResultPointerTypeH, varId, variability, reference) } @@ -63,18 +53,18 @@ class LetHammer( } def translateRestackify( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - let2: RestackifyTE): + let2: RestackifyIE): ExpressionH[KindHT] = { - val RestackifyTE(localVariable, sourceExpr2) = let2 + val RestackifyIE(localVariable, sourceExpr2, _) = let2 val (sourceExprHE, deferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, sourceExpr2); val (sourceResultPointerTypeH) = - typeHammer.translateCoord(hinputs, hamuts, sourceExpr2.result.coord) + typeHammer.translateCoord(hinputs, hamuts, sourceExpr2.result) sourceExprHE.resultType.kind match { // We'll never get to this let, so strip it out. See BRCOBS. @@ -84,11 +74,11 @@ class LetHammer( val stackifyNode = localVariable match { - case ReferenceLocalVariableT(varId, variability, type2) => { + case ReferenceLocalVariableI(varId, variability, type2) => { translateMundaneRestackify( hinputs, hamuts, currentFunctionHeader, locals, sourceExprHE, varId) } - case AddressibleLocalVariableT(varId, variability, reference) => { + case AddressibleLocalVariableI(varId, variability, reference) => { translateAddressibleRestackify( hinputs, hamuts, currentFunctionHeader, locals, sourceExprHE, sourceResultPointerTypeH, varId, variability, reference) } @@ -99,28 +89,28 @@ class LetHammer( } def translateLetAndPoint( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - letTE: LetAndLendTE): + letIE: LetAndLendIE): (ExpressionH[KindHT]) = { - val LetAndLendTE(localVariable, sourceExpr2, targetOwnership) = letTE + val LetAndLendIE(localVariable, sourceExpr2, targetOwnership, _) = letIE val (sourceExprHE, deferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, sourceExpr2); val (sourceResultPointerTypeH) = - typeHammer.translateCoord(hinputs, hamuts, sourceExpr2.result.coord) + typeHammer.translateCoord(hinputs, hamuts, sourceExpr2.result) val borrowAccess = localVariable match { - case ReferenceLocalVariableT(varId, variability, type2) => { + case ReferenceLocalVariableI(varId, variability, type2) => { translateMundaneLetAndPoint( - hinputs, hamuts, currentFunctionHeader, locals, sourceExpr2, sourceExprHE, sourceResultPointerTypeH, letTE, varId, variability) + hinputs, hamuts, currentFunctionHeader, locals, sourceExpr2, sourceExprHE, sourceResultPointerTypeH, letIE, varId, variability) } - case AddressibleLocalVariableT(varId, variability, reference) => { + case AddressibleLocalVariableI(varId, variability, reference) => { translateAddressibleLetAndPoint( - hinputs, hamuts, currentFunctionHeader, locals, sourceExpr2, sourceExprHE, sourceResultPointerTypeH, letTE, varId, variability, reference) + hinputs, hamuts, currentFunctionHeader, locals, sourceExpr2, sourceExprHE, sourceResultPointerTypeH, letIE, varId, variability, reference) } } @@ -129,21 +119,21 @@ class LetHammer( } private def translateAddressibleLet( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, sourceExprHE: ExpressionH[KindHT], sourceResultPointerTypeH: CoordH[KindHT], - varId: IVarNameT, - variability: VariabilityT, - reference: CoordT): + varId: IVarNameI[cI], + variability: VariabilityI, + reference: CoordI[cI]): ExpressionH[KindHT] = { val (boxStructRefH) = structHammer.makeBox(hinputs, hamuts, variability, reference, sourceResultPointerTypeH) val expectedLocalBoxType = CoordH(OwnH, YonderH, boxStructRefH) - val varIdNameH = nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(varId)) + val varIdNameH = nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, varId)) val local = locals.addTypingPassLocal( varId, varIdNameH, Conversions.evaluateVariability(variability), expectedLocalBoxType) @@ -154,19 +144,19 @@ class LetHammer( hamuts.structDefs.find(_.getRef == boxStructRefH).get.members.map(_.name), expectedLocalBoxType), local, - Some(nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(varId)))) + Some(nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, varId)))) } private def translateAddressibleRestackify( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, sourceExprHE: ExpressionH[KindHT], sourceResultPointerTypeH: CoordH[KindHT], - varId: IVarNameT, - variability: VariabilityT, - reference: CoordT): + varId: IVarNameI[cI], + variability: VariabilityI, + reference: CoordI[cI]): ExpressionH[KindHT] = { val (boxStructRefH) = structHammer.makeBox(hinputs, hamuts, variability, reference, sourceResultPointerTypeH) @@ -182,21 +172,21 @@ class LetHammer( hamuts.structDefs.find(_.getRef == boxStructRefH).get.members.map(_.name), expectedLocalBoxType), local, - Some(nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(varId)))) + Some(nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, varId)))) } private def translateAddressibleLetAndPoint( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - sourceExpr2: ReferenceExpressionTE, + sourceExpr2: ReferenceExpressionIE, sourceExprHE: ExpressionH[KindHT], sourceResultPointerTypeH: CoordH[KindHT], - letTE: LetAndLendTE, - varId: IVarNameT, - variability: VariabilityT, - reference: CoordT): + letIE: LetAndLendIE, + varId: IVarNameI[cI], + variability: VariabilityI, + reference: CoordI[cI]): (ExpressionH[KindHT]) = { val stackifyH = translateAddressibleLet( @@ -209,43 +199,43 @@ class LetHammer( locals, varId, variability, - sourceExpr2.result.coord, - letTE.result.coord.ownership) + sourceExpr2.result, + letIE.result.ownership) ConsecutorH(Vector(stackifyH, borrowAccess)) } private def translateMundaneLet( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, sourceExprHE: ExpressionH[KindHT], sourceResultPointerTypeH: CoordH[KindHT], - varId: IVarNameT, - variability: VariabilityT): + varId: IVarNameI[cI], + variability: VariabilityI): StackifyH = { sourceExprHE.resultType.kind match { case NeverHT(_) => vwat() case _ => } - val varIdNameH = nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(varId)) + val varIdNameH = nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, varId)) val localIndex = locals.addTypingPassLocal(varId, varIdNameH, Conversions.evaluateVariability(variability), sourceResultPointerTypeH) val stackNode = StackifyH( sourceExprHE, localIndex, - Some(nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(varId)))) + Some(nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, varId)))) stackNode } private def translateMundaneRestackify( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, sourceExprHE: ExpressionH[KindHT], - varId: IVarNameT): + varId: IVarNameI[cI]): RestackifyH = { locals.markRestackified(varId) @@ -258,21 +248,21 @@ class LetHammer( RestackifyH( sourceExprHE, local, - Some(nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(varId)))) + Some(nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, varId)))) stackNode } private def translateMundaneLetAndPoint( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - sourceExpr2: ReferenceExpressionTE, + sourceExpr2: ReferenceExpressionIE, sourceExprHE: ExpressionH[KindHT], sourceResultPointerTypeH: CoordH[KindHT], - letTE: LetAndLendTE, - varId: IVarNameT, - variability: VariabilityT): + letIE: LetAndLendIE, + varId: IVarNameI[cI], + variability: VariabilityI): ExpressionH[KindHT] = { val stackifyH = translateMundaneLet( @@ -292,18 +282,18 @@ class LetHammer( currentFunctionHeader, locals, varId, - sourceExpr2.result.coord, - letTE.result.coord.ownership) + sourceExpr2.result, + letIE.result.ownership) ConsecutorH(Vector(stackifyH, borrowAccess)) } def translateUnlet( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - unlet2: UnletTE): + unlet2: UnletIE): (ExpressionH[KindHT]) = { val local = locals.get(unlet2.variable.name) match { @@ -314,13 +304,13 @@ class LetHammer( } unlet2.variable match { - case ReferenceLocalVariableT(varId, _, localType2) => { + case ReferenceLocalVariableI(varId, _, localType2) => { val localTypeH = typeHammer.translateCoord(hinputs, hamuts, localType2) val unstackifyNode = UnstackifyH(local) locals.markUnstackified(varId) unstackifyNode } - case AddressibleLocalVariableT(varId, variability, innerType2) => { + case AddressibleLocalVariableI(varId, variability, innerType2) => { val innerTypeH = typeHammer.translateCoord(hinputs, hamuts, innerType2) val structRefH = structHammer.makeBox(hinputs, hamuts, variability, innerType2, innerTypeH) @@ -345,18 +335,18 @@ class LetHammer( } def translateDestructureStaticSizedArray( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - des2: DestroyStaticSizedArrayIntoLocalsTE + des2: DestroyStaticSizedArrayIntoLocalsIE ): ExpressionH[KindHT] = { - val DestroyStaticSizedArrayIntoLocalsTE(sourceExpr2, arrSeqT, destinationReferenceLocalVariables) = des2 + val DestroyStaticSizedArrayIntoLocalsIE(sourceExpr2, arrSeqI, destinationReferenceLocalVariables) = des2 val (sourceExprHE, sourceExprDeferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, sourceExpr2); - vassert(destinationReferenceLocalVariables.size == expectIntegerTemplata(arrSeqT.size).value) + vassert(destinationReferenceLocalVariables.size == arrSeqI.size) // Destructure2 will immediately destroy any addressible references inside it // (see Destructure2 comments). @@ -371,10 +361,10 @@ class LetHammer( destinationReferenceLocalVariables .map(destinationReferenceLocalVariable => { val (memberRefTypeH) = - typeHammer.translateCoord(hinputs, hamuts, arrSeqT.elementType) + typeHammer.translateCoord(hinputs, hamuts, arrSeqI.elementType.coord) val varIdNameH = nameHammer.translateFullName( - hinputs, hamuts, currentFunctionHeader.id.addStep(destinationReferenceLocalVariable.name)) + hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, destinationReferenceLocalVariable.name)) val localIndex = locals.addTypingPassLocal( destinationReferenceLocalVariable.name, @@ -396,19 +386,19 @@ class LetHammer( } def translateDestroy( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - des2: DestroyTE): + des2: DestroyIE): ExpressionH[KindHT] = { - val DestroyTE(sourceExpr2, structTT, destinationReferenceLocalVariables) = des2 + val DestroyIE(sourceExpr2, structTI, destinationReferenceLocalVariables) = des2 val (sourceExprHE, sourceExprDeferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, sourceExpr2); // val structDefT = hinputs.lookupStruct(TemplataCompiler.getStructTemplate(structTT.fullName)) - val structDefT = structHammer.lookupStruct(hinputs, hamuts, structTT) + val structDefT = structHammer.lookupStruct(hinputs, hamuts, structTI) // Destructure2 will immediately destroy any addressible references inside it // (see Destructure2 comments). @@ -425,12 +415,12 @@ class LetHammer( structDefT.members.foldLeft((destinationReferenceLocalVariables, Vector[CoordH[KindHT]](), Vector[Local]()))({ case ((remainingDestinationReferenceLocalVariables, previousLocalTypes, previousLocalIndices), member2) => { member2 match { - case NormalStructMemberT(name, variability, ReferenceMemberTypeT(memberRefType2)) => { + case StructMemberI(name, variability, ReferenceMemberTypeI(memberRefType2)) => { val destinationReferenceLocalVariable = remainingDestinationReferenceLocalVariables.head val (memberRefTypeH) = typeHammer.translateCoord(hinputs, hamuts, memberRefType2) - val varIdNameH = nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(destinationReferenceLocalVariable.name)) + val varIdNameH = nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, destinationReferenceLocalVariable.name)) val localIndex = locals.addTypingPassLocal( destinationReferenceLocalVariable.name, @@ -443,7 +433,7 @@ class LetHammer( // borrow refs of boxes which contain things. We're moving that borrow // ref into a local variable. We'll then unlet the local variable, and // unborrow it. - case NormalStructMemberT(name, variability, AddressMemberTypeT(memberRefType2)) => { + case StructMemberI(name, variability, AddressMemberTypeI(memberRefType2)) => { val (memberRefTypeH) = typeHammer.translateCoord(hinputs, hamuts, memberRefType2); // In the case of an addressible struct member, its variability refers to the @@ -451,7 +441,7 @@ class LetHammer( val (boxStructRefH) = structHammer.makeBox(hinputs, hamuts, variability, memberRefType2, memberRefTypeH) // Structs only ever borrow boxes, boxes are only ever owned by the stack. - val localBoxType = CoordH(BorrowH, YonderH, boxStructRefH) + val localBoxType = CoordH(vregionmut(MutableBorrowH), YonderH, boxStructRefH) val localIndex = locals.addHammerLocal(localBoxType, Final) (remainingDestinationReferenceLocalVariables, previousLocalTypes :+ localBoxType, previousLocalIndices :+ localIndex) @@ -468,9 +458,8 @@ class LetHammer( val unboxingsH = structDefT.members.zip(localTypes.zip(localIndices)).flatMap({ - case (VariadicStructMemberT(_, _), (localType, local)) => vimpl() - case (NormalStructMemberT(_, _, ReferenceMemberTypeT(_)), (localType, local)) => Vector.empty - case (NormalStructMemberT(_, _, AddressMemberTypeT(_)), (localType, local)) => { + case (StructMemberI(_, _, ReferenceMemberTypeI(_)), (localType, local)) => Vector.empty + case (StructMemberI(_, _, AddressMemberTypeI(_)), (localType, local)) => { // localType is the box type. // First, unlet it, then discard the contents. // We discard instead of putting it into a local because address members diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/LoadHammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/LoadHammer.scala index 3f141e795..a5392a3d0 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/LoadHammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/LoadHammer.scala @@ -1,18 +1,10 @@ package dev.vale.simplifying -import dev.vale.{Keywords, finalast, vassert, vfail, vimpl} -import dev.vale.finalast.{BorrowH, ExpressionH, KindHT, LocalLoadH, MemberLoadH, OwnH, CoordH, RuntimeSizedArrayLoadH, ShareH, StaticSizedArrayLoadH, YonderH} -import dev.vale.typing.Hinputs -import dev.vale.typing.ast.{AddressMemberLookupTE, ExpressionT, FunctionHeaderT, LocalLookupTE, ReferenceExpressionTE, ReferenceMemberLookupTE, RuntimeSizedArrayLookupTE, SoftLoadTE, StaticSizedArrayLookupTE} -import dev.vale.typing.env.{AddressibleLocalVariableT, ReferenceLocalVariableT} -import dev.vale.typing.names.{IdT, IVarNameT} -import dev.vale.typing.types._ +import dev.vale.{Keywords, finalast, vassert, vfail, vimpl, vregionmut} import dev.vale.finalast._ -import dev.vale.typing.{types => t, _} -import dev.vale.typing.ast._ -import dev.vale.typing.env.ReferenceLocalVariableT -import dev.vale.typing.names.IVarNameT -import dev.vale.typing.types._ +import dev.vale.finalast._ +import dev.vale.instantiating.ast._ +import dev.vale.postparsing.RegionTemplataType class LoadHammer( keywords: Keywords, @@ -22,33 +14,99 @@ class LoadHammer( expressionHammer: ExpressionHammer) { def translateLoad( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - load2: SoftLoadTE): - (ExpressionH[KindHT], Vector[ExpressionT]) = { - val SoftLoadTE(sourceExpr2, targetOwnership) = load2 + load2: SoftLoadIE): + (ExpressionH[KindHT], Vector[ExpressionI]) = { + val SoftLoadIE(sourceExpr2, targetOwnership, _) = load2 val (loadedAccessH, sourceDeferreds) = sourceExpr2 match { - case LocalLookupTE(_,ReferenceLocalVariableT(varId, variability, reference)) => { - translateMundaneLocalLoad(hinputs, hamuts, currentFunctionHeader, locals, varId, reference, targetOwnership) + case LocalLookupIE(ReferenceLocalVariableI(varId, variability, reference), _) => { + // DO NOI SUBMIT combine this with below + val combinedTargetOwnership = targetOwnership +// (targetOwnership, sourceRegion) match { +// case (OwnI, _) => OwnI +// case (BorrowI, RegionTemplata(true)) => MutableBorrowI +// case (BorrowI, RegionTemplata(false)) => ImmutableBorrowI +// case (ShareI, RegionTemplata(true)) => MutableShareI +// case (ShareI, RegionTemplata(false)) => ImmutableShareI +// case (WeakI, _) => vimpl() +// } + translateMundaneLocalLoad(hinputs, hamuts, currentFunctionHeader, locals, varId, reference, combinedTargetOwnership) } - case LocalLookupTE(_,AddressibleLocalVariableT(varId, variability, localReference2)) => { - translateAddressibleLocalLoad(hinputs, hamuts, currentFunctionHeader, locals, varId, variability, localReference2, targetOwnership) + case LocalLookupIE(AddressibleLocalVariableI(varId, variability, localReference2), _) => { + // DO NOI SUBMIT combine this with below + val combinedTargetOwnership = vregionmut() +// (targetOwnership, sourceRegion) match { +// case (OwnI, _) => OwnI +// case (BorrowI, RegionTemplata(true)) => MutableBorrowI +// case (BorrowI, RegionTemplata(false)) => ImmutableBorrowI +// case (ShareI, RegionTemplata(true)) => MutableShareI +// case (ShareI, RegionTemplata(false)) => ImmutableShareI +// case (WeakI, _) => vimpl() +// } + translateAddressibleLocalLoad(hinputs, hamuts, currentFunctionHeader, locals, varId, variability, localReference2, vregionmut(targetOwnership)) } - case ReferenceMemberLookupTE(_,structExpr2, memberName, memberType2, _) => { + case ReferenceMemberLookupIE(_,structExpr2, memberName, memberType2, _) => { +// val sourceRegion: ITemplata[RegionTemplataType] = vimpl() + // DO NOI SUBMIT combine this with below +// val combinedTargetOwnership = +// (targetOwnership, sourceRegion) match { +// case (OwnI, _) => OwnI +// case (BorrowI, RegionTemplata(true)) => MutableBorrowI +// case (BorrowI, RegionTemplata(false)) => ImmutableBorrowI +// case (ShareI, RegionTemplata(true)) => MutableShareI +// case (ShareI, RegionTemplata(false)) => ImmutableShareI +// case (WeakI, _) => vimpl() +// } translateMundaneMemberLoad(hinputs, hamuts, currentFunctionHeader, locals, structExpr2, memberType2, memberName, targetOwnership) } - case AddressMemberLookupTE(_,structExpr2, memberName, memberType2, _) => { - translateAddressibleMemberLoad(hinputs, hamuts, currentFunctionHeader, locals, structExpr2, memberName, memberType2, targetOwnership) + case AddressMemberLookupIE(structExpr2, memberName, memberType2, _) => { +// val sourceRegion: ITemplataI[RegionTemplataType] = vimpl() + // DO NOI SUBMIT combine this with below + vregionmut() +// val combinedTargetOwnership = +// (targetOwnership, sourceRegion) match { +// case (OwnI, _) => OwnI +// case (BorrowI, RegionTemplata(true)) => MutableBorrowI +// case (BorrowI, RegionTemplata(false)) => ImmutableBorrowI +// case (ShareI, RegionTemplata(true)) => MutableShareI +// case (ShareI, RegionTemplata(false)) => ImmutableShareI +// case (WeakI, _) => vimpl() +// } + translateAddressibleMemberLoad(hinputs, hamuts, currentFunctionHeader, locals, structExpr2, memberName, memberType2, vregionmut(targetOwnership)) } - case RuntimeSizedArrayLookupTE(_, arrayExpr2, _, indexExpr2, _) => { - translateMundaneRuntimeSizedArrayLoad(hinputs, hamuts, currentFunctionHeader, locals, arrayExpr2, indexExpr2, targetOwnership) + case RuntimeSizedArrayLookupIE(arrayExpr2, indexExpr2, _, _) => { +// val sourceRegion: ITemplataI[RegionTemplataType] = vimpl() + // DO NOI SUBMIT combine this with below + val combinedTargetOwnership = targetOwnership +// (targetOwnership, sourceRegion) match { +// case (OwnI, _) => OwnI +// case (BorrowI, RegionTemplata(true)) => MutableBorrowI +// case (BorrowI, RegionTemplata(false)) => ImmutableBorrowI +// case (ShareI, RegionTemplata(true)) => MutableShareI +// case (ShareI, RegionTemplata(false)) => ImmutableShareI +// case (WeakI, _) => vimpl() +// } + translateMundaneRuntimeSizedArrayLoad(hinputs, hamuts, currentFunctionHeader, locals, arrayExpr2, indexExpr2, combinedTargetOwnership) } - case StaticSizedArrayLookupTE(_, arrayExpr2, _, indexExpr2, _) => { - translateMundaneStaticSizedArrayLoad(hinputs, hamuts, currentFunctionHeader, locals, arrayExpr2, indexExpr2, targetOwnership) + case StaticSizedArrayLookupIE(_, arrayExpr2, indexExpr2, _, _) => { +// val sourceRegion: ITemplataI[RegionTemplataType] = vimpl() + // DO NOI SUBMIT combine this with below +// val combinedTargetOwnership = +// (targetOwnership, sourceRegion) match { +// case (OwnI, _) => OwnI +// case (BorrowI, RegionTemplata(true)) => MutableBorrowI +// case (BorrowI, RegionTemplata(false)) => ImmutableBorrowI +// case (ShareI, RegionTemplata(true)) => MutableShareI +// case (ShareI, RegionTemplata(false)) => ImmutableShareI +// case (WeakI, _) => vimpl() +// } + translateMundaneStaticSizedArrayLoad( + hinputs, hamuts, currentFunctionHeader, locals, arrayExpr2, indexExpr2, targetOwnership) } } @@ -58,15 +116,15 @@ class LoadHammer( } private def translateMundaneRuntimeSizedArrayLoad( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - arrayExpr2: ReferenceExpressionTE, - indexExpr2: ReferenceExpressionTE, - targetOwnershipT: OwnershipT, - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { - val targetOwnership = Conversions.evaluateOwnership(targetOwnershipT) + arrayExpr2: ReferenceExpressionIE, + indexExpr2: ReferenceExpressionIE, + targetOwnershipI: OwnershipI, + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { + val targetOwnership = Conversions.evaluateOwnership(targetOwnershipI) val (arrayResultLine, arrayDeferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, arrayExpr2); @@ -77,17 +135,21 @@ class LoadHammer( val indexAccess = indexExprResultLine.expectIntAccess() vassert( - targetOwnership == BorrowH || - targetOwnership == ShareH) + targetOwnership == MutableBorrowH || + targetOwnership == ImmutableBorrowH || + targetOwnership == ImmutableShareH || + targetOwnership == MutableShareH) val rsa = hamuts.getRuntimeSizedArray(arrayAccess.resultType.kind) val expectedElementType = rsa.elementType val resultType = { val location = (targetOwnership, expectedElementType.location) match { - case (BorrowH, _) => YonderH + case (ImmutableBorrowH, _) => YonderH + case (MutableBorrowH, _) => YonderH case (OwnH, location) => location - case (ShareH, location) => location + case (MutableShareH, location) => location + case (ImmutableShareH, location) => location } CoordH(targetOwnership, location, expectedElementType.kind) } @@ -105,15 +167,15 @@ class LoadHammer( } private def translateMundaneStaticSizedArrayLoad( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - arrayExpr2: ReferenceExpressionTE, - indexExpr2: ReferenceExpressionTE, - targetOwnershipT: OwnershipT, - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { - val targetOwnership = Conversions.evaluateOwnership(targetOwnershipT) + arrayExpr2: ReferenceExpressionIE, + indexExpr2: ReferenceExpressionIE, + targetOwnershipI: OwnershipI, + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { + val targetOwnership = Conversions.evaluateOwnership(targetOwnershipI) val (arrayResultLine, arrayDeferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, arrayExpr2); @@ -123,16 +185,20 @@ class LoadHammer( expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, indexExpr2); val indexAccess = indexExprResultLine.expectIntAccess() - vassert(targetOwnership == finalast.BorrowH || targetOwnership == finalast.ShareH) + vassert( + targetOwnership == finalast.MutableBorrowH || + targetOwnership == finalast.ImmutableBorrowH || + targetOwnership == finalast.MutableShareH || + targetOwnership == finalast.ImmutableShareH) val ssa = hamuts.getStaticSizedArray(arrayAccess.resultType.kind) val expectedElementType = ssa.elementType val resultType = { val location = (targetOwnership, expectedElementType.location) match { - case (BorrowH, _) => YonderH + case (MutableBorrowH | ImmutableBorrowH, _) => YonderH case (OwnH, location) => location - case (ShareH, location) => location + case (ImmutableShareH | MutableShareH, location) => location } CoordH(targetOwnership, location, expectedElementType.kind) } @@ -151,31 +217,30 @@ class LoadHammer( } private def translateAddressibleMemberLoad( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - structExpr2: ReferenceExpressionTE, - memberName: IVarNameT, - expectedType2: CoordT, - targetOwnershipT: OwnershipT, - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { + structExpr2: ReferenceExpressionIE, + memberName: IVarNameI[cI], + expectedType2: CoordI[cI], + targetOwnershipI: OwnershipI, + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { val (structResultLine, structDeferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, structExpr2); - val structTT = - structExpr2.result.coord.kind match { - case sr @ StructTT(_) => sr -// case TupleTT(_, sr) => sr -// case PackTT(_, sr) => sr + val structIT = + structExpr2.result.kind match { + case sr @ StructIT(_) => sr +// case TupleIT(_, sr) => sr +// case PackIT(_, sr) => sr } - val structDefT = structHammer.lookupStruct(hinputs, hamuts, structTT) - val memberIndex = structDefT.members.indexWhere(_.name == memberName) + val structDefI = structHammer.lookupStruct(hinputs, hamuts, structIT) + val memberIndex = structDefI.members.indexWhere(_.name == memberName) vassert(memberIndex >= 0) val member2 = - structDefT.members(memberIndex) match { - case n @ NormalStructMemberT(name, variability, tyype) => n - case VariadicStructMemberT(name, tyype) => vimpl() + structDefI.members(memberIndex) match { + case n @ StructMemberI(name, variability, tyype) => n } val variability = member2.variability @@ -188,13 +253,13 @@ class LoadHammer( val (boxStructRefH) = structHammer.makeBox(hinputs, hamuts, variability, boxedType2, boxedTypeH) - val boxInStructCoord = CoordH(BorrowH, YonderH, boxStructRefH) + val boxInStructCoord = CoordH(vregionmut(MutableBorrowH), YonderH, boxStructRefH) // We're storing into a struct's member that is a box. The stack is also // pointing at this box. First, get the box, then mutate what's inside. var varFullNameH = nameHammer.translateFullName( - hinputs, hamuts, currentFunctionHeader.id.addStep(memberName)) + hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, memberName)) val loadBoxNode = MemberLoadH( structResultLine.expectStructAccess(), @@ -203,7 +268,7 @@ class LoadHammer( boxInStructCoord, varFullNameH) - val targetOwnership = Conversions.evaluateOwnership(targetOwnershipT) + val targetOwnership = Conversions.evaluateOwnership(targetOwnershipI) val loadResultType = CoordH( targetOwnership, @@ -215,21 +280,21 @@ class LoadHammer( LetHammer.BOX_MEMBER_INDEX, boxedTypeH, loadResultType, - nameHammer.addStep(hamuts, boxStructRefH.fullName, keywords.BOX_MEMBER_NAME.str)) + nameHammer.addStep(hamuts, boxStructRefH.id, keywords.BOX_MEMBER_NAME.str)) (loadedNodeH, structDeferreds) } private def translateMundaneMemberLoad( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - structExpr2: ReferenceExpressionTE, - expectedMemberCoord: CoordT, - memberName: IVarNameT, + structExpr2: ReferenceExpressionIE, + expectedMemberCoord: CoordI[cI], + memberName: IVarNameI[cI], // resultCoord: Coord, - targetOwnershipT: OwnershipT, - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { + targetOwnershipI: OwnershipI, + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { val (structResultLine, structDeferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, structExpr2); @@ -238,17 +303,17 @@ class LoadHammer( // val (resultTypeH) = // typeHammer.translateReference(hinputs, hamuts, resultCoord); - val structTT = - structExpr2.result.coord.kind match { - case sr @ StructTT(_) => sr -// case TupleTT(_, sr) => sr -// case PackTT(_, sr) => sr + val structIT = + structExpr2.result.kind match { + case sr @ StructIT(_) => sr +// case TupleIT(_, sr) => sr +// case PackIT(_, sr) => sr } - val structDefT = structHammer.lookupStruct(hinputs, hamuts, structTT) - val memberIndex = structDefT.members.indexWhere(_.name == memberName) + val structDefI = structHammer.lookupStruct(hinputs, hamuts, structIT) + val memberIndex = structDefI.members.indexWhere(_.name == memberName) vassert(memberIndex >= 0) - val targetOwnership = Conversions.evaluateOwnership(targetOwnershipT) + val targetOwnership = Conversions.evaluateOwnership(targetOwnershipI) val loadResultType = CoordH(targetOwnership, expectedMemberTypeH.location, expectedMemberTypeH.kind) // We're loading from a regular reference member of a struct. @@ -258,20 +323,20 @@ class LoadHammer( memberIndex, expectedMemberTypeH, loadResultType, - nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(memberName))) + nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, memberName))) (loadedNode, structDeferreds) } def translateAddressibleLocalLoad( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - varId: IVarNameT, - variability: VariabilityT, - localReference2: CoordT, - targetOwnershipT: OwnershipT, - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { + varId: IVarNameI[cI], + variability: VariabilityI, + localReference2: CoordI[cI], + targetOwnershipI: OwnershipI, + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { val local = locals.get(varId).get vassert(!locals.unstackifiedVars.contains(local.id)) @@ -285,14 +350,14 @@ class LoadHammer( // We need to load the box, then mutate its contents. val varNameH = nameHammer.translateFullName( - hinputs, hamuts, currentFunctionHeader.id.addStep(varId)) + hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, varId)) val loadBoxNode = LocalLoadH( local, - finalast.BorrowH, + vregionmut(MutableBorrowH), varNameH) - val targetOwnership = Conversions.evaluateOwnership(targetOwnershipT) + val targetOwnership = Conversions.evaluateOwnership(targetOwnershipI) val loadResultType = CoordH(targetOwnership, localTypeH.location, localTypeH.kind) val loadedNode = @@ -301,20 +366,20 @@ class LoadHammer( LetHammer.BOX_MEMBER_INDEX, localTypeH, loadResultType, - nameHammer.addStep(hamuts, boxStructRefH.fullName, keywords.BOX_MEMBER_NAME.str)) + nameHammer.addStep(hamuts, boxStructRefH.id, keywords.BOX_MEMBER_NAME.str)) (loadedNode, Vector.empty) } def translateMundaneLocalLoad( - hinputs: Hinputs, - hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, - locals: LocalsBox, - varId: IVarNameT, - expectedType2: CoordT, - targetOwnershipT: OwnershipT, - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { - val targetOwnership = Conversions.evaluateOwnership(targetOwnershipT) + hinputs: HinputsI, + hamuts: HamutsBox, + currentFunctionHeader: FunctionHeaderI, + locals: LocalsBox, + varId: IVarNameI[cI], + localType: CoordI[cI], + targetOwnershipI: OwnershipI, + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { + val targetOwnership = Conversions.evaluateOwnership(targetOwnershipI) val local = locals.get(varId) match { case Some(x) => x @@ -324,74 +389,74 @@ class LoadHammer( } vassert(!locals.unstackifiedVars.contains(local.id)) - val (expectedTypeH) = - typeHammer.translateCoord(hinputs, hamuts, expectedType2); - vassert(expectedTypeH == local.typeH) +// val (expectedTypeH) = +// typeHammer.translateCoord(hinputs, hamuts, expectedType2); +// vassert(localType == local.typeH) val loadedNode = LocalLoadH( local, targetOwnership, nameHammer.translateFullName( - hinputs, hamuts, currentFunctionHeader.id.addStep(varId))) + hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, varId))) (loadedNode, Vector.empty) } def translateLocalAddress( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - lookup2: LocalLookupTE): + lookup2: LocalLookupIE): (ExpressionH[KindHT]) = { - val LocalLookupTE(_,localVar) = lookup2; + val LocalLookupIE(localVar, _) = lookup2; + vregionmut() val local = locals.get(localVar.name).get vassert(!locals.unstackifiedVars.contains(local.id)) val (boxStructRefH) = - structHammer.makeBox(hinputs, hamuts, localVar.variability, localVar.coord, local.typeH) + structHammer.makeBox(hinputs, hamuts, localVar.variability, localVar.collapsedCoord, local.typeH) // This means we're trying to load from a local variable that holds a box. // We need to load the box, then mutate its contents. val loadBoxNode = LocalLoadH( local, - finalast.BorrowH, - nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(localVar.name))) + vregionmut(MutableBorrowH), + nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, localVar.name))) loadBoxNode } // In this, we're basically taking an addressible lookup, in other words, // a reference to a box. def translateMemberAddress( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - lookup2: AddressMemberLookupTE): - (ExpressionH[KindHT], Vector[ExpressionT]) = { - val AddressMemberLookupTE(_,structExpr2, memberName, resultType2, _) = lookup2; + lookup2: AddressMemberLookupIE): + (ExpressionH[KindHT], Vector[ExpressionI]) = { + val AddressMemberLookupIE(structExpr2, memberName, resultType2, _) = lookup2; val (structResultLine, structDeferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, structExpr2); - val structTT = - structExpr2.result.coord.kind match { - case sr @ StructTT(_) => sr -// case TupleTT(_, sr) => sr -// case PackTT(_, sr) => sr + val structIT = + structExpr2.result.kind match { + case sr @ StructIT(_) => sr +// case TupleIT(_, sr) => sr +// case PackIT(_, sr) => sr } - val structDefT = structHammer.lookupStruct(hinputs, hamuts, structTT) - val memberIndex = structDefT.members.indexWhere(_.name == memberName) + val structDefI = structHammer.lookupStruct(hinputs, hamuts, structIT) + val memberIndex = structDefI.members.indexWhere(_.name == memberName) vassert(memberIndex >= 0) val member2 = - structDefT.members(memberIndex) match { - case n @ NormalStructMemberT(name, variability, tyype) => n - case VariadicStructMemberT(name, tyype) => vimpl() + structDefI.members(memberIndex) match { + case n @ StructMemberI(name, variability, tyype) => n } val variability = member2.variability - vassert(variability == VaryingT, "Expected varying for member " + memberName) // curious + vassert(variability == VaryingI, "Expected varying for member " + memberName) // curious val boxedType2 = member2.tyype.expectAddressMember().reference @@ -402,14 +467,14 @@ class LoadHammer( structHammer.makeBox(hinputs, hamuts, variability, boxedType2, boxedTypeH) // We expect a borrow because structs never own boxes, they only borrow them - val expectedStructBoxMemberType = CoordH(finalast.BorrowH, YonderH, boxStructRefH) + val expectedStructBoxMemberType = CoordH(vregionmut(MutableBorrowH), YonderH, boxStructRefH) val loadResultType = CoordH( // Boxes are either owned or borrowed. We only own boxes from locals, // and we're loading from a struct here, so we're getting a borrow to the // box from the struct. - BorrowH, + vregionmut(MutableBorrowH), YonderH, boxStructRefH) @@ -421,7 +486,7 @@ class LoadHammer( memberIndex, expectedStructBoxMemberType, loadResultType, - nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(memberName))) + nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, memberName))) (loadBoxNode, structDeferreds) } @@ -429,8 +494,8 @@ class LoadHammer( def getBorrowedLocation(memberType: CoordH[KindHT]) = { (memberType.ownership, memberType.location) match { case (OwnH, _) => YonderH - case (BorrowH, _) => YonderH - case (ShareH, location) => location + case (ImmutableBorrowH | MutableBorrowH, _) => YonderH + case (MutableShareH | ImmutableShareH, location) => location } } } diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/MutateHammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/MutateHammer.scala index 39cbc6872..d7cb55d3c 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/MutateHammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/MutateHammer.scala @@ -1,18 +1,8 @@ package dev.vale.simplifying -import dev.vale.{Keywords, finalast, vassert, vimpl} -import dev.vale.finalast.{BorrowH, ExpressionH, KindHT, LocalLoadH, LocalStoreH, MemberLoadH, MemberStoreH, CoordH, RuntimeSizedArrayStoreH, StaticSizedArrayStoreH, YonderH} -import dev.vale.typing.Hinputs -import dev.vale.typing.ast.{AddressMemberLookupTE, ExpressionT, FunctionHeaderT, LocalLookupTE, MutateTE, ReferenceExpressionTE, ReferenceMemberLookupTE, RuntimeSizedArrayLookupTE, StaticSizedArrayLookupTE} -import dev.vale.typing.env.{AddressibleLocalVariableT, ReferenceLocalVariableT} -import dev.vale.typing.names.{IdT, IVarNameT} -import dev.vale.typing.types._ +import dev.vale.{Keywords, finalast, vassert, vimpl, vregionmut} import dev.vale.finalast._ -import dev.vale.typing._ -import dev.vale.typing.ast._ -import dev.vale.typing.env.ReferenceLocalVariableT -import dev.vale.typing.names.IVarNameT -import dev.vale.typing.types._ +import dev.vale.instantiating.ast._ class MutateHammer( keywords: Keywords, @@ -22,37 +12,38 @@ class MutateHammer( expressionHammer: ExpressionHammer) { def translateMutate( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, - mutate2: MutateTE): + mutate2: MutateIE): (ExpressionH[KindHT]) = { - val MutateTE(destinationExpr2, sourceExpr2) = mutate2 + val MutateIE(destinationExpr2, sourceExpr2, _) = mutate2 val (sourceExprResultLine, sourceDeferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, sourceExpr2); val (sourceResultPointerTypeH) = - typeHammer.translateCoord(hinputs, hamuts, sourceExpr2.result.coord) + typeHammer.translateCoord(hinputs, hamuts, sourceExpr2.result) val (oldValueAccess, destinationDeferreds) = destinationExpr2 match { - case LocalLookupTE(_,ReferenceLocalVariableT(varId, variability, reference)) => { + case LocalLookupIE(ReferenceLocalVariableI(varId, variability, reference), _) => { translateMundaneLocalMutate(hinputs, hamuts, currentFunctionHeader, locals, sourceExprResultLine, varId) } - case LocalLookupTE(_,AddressibleLocalVariableT(varId, variability, reference)) => { + case LocalLookupIE(AddressibleLocalVariableI(varId, variability, reference), _) => { + vimpl() translateAddressibleLocalMutate(hinputs, hamuts, currentFunctionHeader, locals, sourceExprResultLine, sourceResultPointerTypeH, varId, variability, reference) } - case ReferenceMemberLookupTE(_,structExpr2, memberName, _, _) => { + case ReferenceMemberLookupIE(_,structExpr2, memberName, _, _) => { translateMundaneMemberMutate(hinputs, hamuts, currentFunctionHeader, locals, sourceExprResultLine, structExpr2, memberName) } - case AddressMemberLookupTE(_,structExpr2, memberName, memberType2, _) => { + case AddressMemberLookupIE(structExpr2, memberName, memberType2, _) => { translateAddressibleMemberMutate(hinputs, hamuts, currentFunctionHeader, locals, sourceExprResultLine, structExpr2, memberName) } - case StaticSizedArrayLookupTE(_, arrayExpr2, _, indexExpr2, _) => { + case StaticSizedArrayLookupIE(_, arrayExpr2, indexExpr2, _, _) => { translateMundaneStaticSizedArrayMutate(hinputs, hamuts, currentFunctionHeader, locals, sourceExprResultLine, arrayExpr2, indexExpr2) } - case RuntimeSizedArrayLookupTE(_, arrayExpr2, _, indexExpr2, _) => { + case RuntimeSizedArrayLookupIE(arrayExpr2, indexExpr2, _, _) => { translateMundaneRuntimeSizedArrayMutate(hinputs, hamuts, currentFunctionHeader, locals, sourceExprResultLine, arrayExpr2, indexExpr2) } } @@ -61,14 +52,14 @@ class MutateHammer( } private def translateMundaneRuntimeSizedArrayMutate( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, sourceExprResultLine: ExpressionH[KindHT], - arrayExpr2: ReferenceExpressionTE, - indexExpr2: ReferenceExpressionTE - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { + arrayExpr2: ReferenceExpressionIE, + indexExpr2: ReferenceExpressionIE + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { val (destinationResultLine, destinationDeferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, arrayExpr2); val (indexExprResultLine, indexDeferreds) = @@ -89,14 +80,14 @@ class MutateHammer( } private def translateMundaneStaticSizedArrayMutate( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, sourceExprResultLine: ExpressionH[KindHT], - arrayExpr2: ReferenceExpressionTE, - indexExpr2: ReferenceExpressionTE - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { + arrayExpr2: ReferenceExpressionIE, + indexExpr2: ReferenceExpressionIE + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { val (destinationResultLine, destinationDeferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, arrayExpr2); val (indexExprResultLine, indexDeferreds) = @@ -117,30 +108,29 @@ class MutateHammer( } private def translateAddressibleMemberMutate( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, sourceExprResultLine: ExpressionH[KindHT], - structExpr2: ReferenceExpressionTE, - memberName: IVarNameT - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { + structExpr2: ReferenceExpressionIE, + memberName: IVarNameI[cI] + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { val (destinationResultLine, destinationDeferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, structExpr2); - val structTT = - structExpr2.result.coord.kind match { - case sr @ StructTT(_) => sr -// case TupleTT(_, sr) => sr -// case PackTT(_, sr) => sr + val structIT = + structExpr2.result.kind match { + case sr @ StructIT(_) => sr +// case TupleIT(_, sr) => sr +// case PackIT(_, sr) => sr } - val structDefT = hinputs.lookupStruct(structTT.id) - val memberIndex = structDefT.members.indexWhere(_.name == memberName) + val structDefI = hinputs.lookupStruct(structIT.id) + val memberIndex = structDefI.members.indexWhere(_.name == memberName) vassert(memberIndex >= 0) val member2 = - structDefT.members(memberIndex) match { - case n @ NormalStructMemberT(name, variability, tyype) => n - case VariadicStructMemberT(name, tyype) => vimpl() + structDefI.members(memberIndex) match { + case n @ StructMemberI(name, variability, tyype) => n } val variability = member2.variability @@ -154,14 +144,14 @@ class MutateHammer( structHammer.makeBox(hinputs, hamuts, variability, boxedType2, boxedTypeH) // Remember, structs can never own boxes, they only borrow them - val expectedStructBoxMemberType = CoordH(BorrowH, YonderH, boxStructRefH) + val expectedStructBoxMemberType = CoordH(vregionmut(MutableBorrowH), YonderH, boxStructRefH) // We're storing into a struct's member that is a box. The stack is also // pointing at this box. First, get the box, then mutate what's inside. - val nameH = nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(memberName)) + val nameH = nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, memberName)) val loadResultType = CoordH( - finalast.BorrowH, + vregionmut(MutableBorrowH), YonderH, boxStructRefH) val loadBoxNode = @@ -177,33 +167,33 @@ class MutateHammer( loadBoxNode.expectStructAccess(), LetHammer.BOX_MEMBER_INDEX, sourceExprResultLine, - nameHammer.addStep(hamuts, boxStructRefH.fullName, keywords.BOX_MEMBER_NAME.str)) + nameHammer.addStep(hamuts, boxStructRefH.id, keywords.BOX_MEMBER_NAME.str)) (storeNode, destinationDeferreds) } private def translateMundaneMemberMutate( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, sourceExprResultLine: ExpressionH[KindHT], - structExpr2: ReferenceExpressionTE, - memberName: IVarNameT - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { + structExpr2: ReferenceExpressionIE, + memberName: IVarNameI[cI], + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { val (destinationResultLine, destinationDeferreds) = expressionHammer.translate(hinputs, hamuts, currentFunctionHeader, locals, structExpr2); - val structTT = - structExpr2.result.coord.kind match { - case sr @ StructTT(_) => sr + val structIT = + structExpr2.result.kind match { + case sr @ StructIT(_) => sr } - val structDefT = hinputs.lookupStruct(structTT.id) + val structDefI = hinputs.lookupStruct(structIT.id) val memberIndex = - structDefT.members + structDefI.members .indexWhere(_.name == memberName) vassert(memberIndex >= 0) - val structDefH = hamuts.structTToStructDefH(structTT) + val structDefH = hamuts.structTToStructDefH(structIT) // We're storing into a regular reference member of a struct. val storeNode = @@ -212,21 +202,21 @@ class MutateHammer( destinationResultLine.expectStructAccess(), memberIndex, sourceExprResultLine, - nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(memberName))) + nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, memberName))) (storeNode, destinationDeferreds) } private def translateAddressibleLocalMutate( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, + currentFunctionHeader: FunctionHeaderI, locals: LocalsBox, sourceExprResultLine: ExpressionH[KindHT], sourceResultPointerTypeH: CoordH[KindHT], - varId: IVarNameT, - variability: VariabilityT, - reference: CoordT - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { + varId: IVarNameI[cI], + variability: VariabilityI, + reference: CoordI[cI] + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { val local = locals.get(varId).get val (boxStructRefH) = structHammer.makeBox(hinputs, hamuts, variability, reference, sourceResultPointerTypeH) @@ -235,11 +225,11 @@ class MutateHammer( // This means we're trying to mutate a local variable that holds a box. // We need to load the box, then mutate its contents. - val nameH = nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(varId)) + val nameH = nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, varId)) val loadBoxNode = LocalLoadH( local, - finalast.BorrowH, + vimpl(/*BorrowH*/), nameH) val storeNode = MemberStoreH( @@ -247,25 +237,25 @@ class MutateHammer( loadBoxNode.expectStructAccess(), LetHammer.BOX_MEMBER_INDEX, sourceExprResultLine, - nameHammer.addStep(hamuts, boxStructRefH.fullName, keywords.BOX_MEMBER_NAME.str)) + nameHammer.addStep(hamuts, boxStructRefH.id, keywords.BOX_MEMBER_NAME.str)) (storeNode, Vector.empty) } private def translateMundaneLocalMutate( - hinputs: Hinputs, - hamuts: HamutsBox, - currentFunctionHeader: FunctionHeaderT, - locals: LocalsBox, - sourceExprResultLine: ExpressionH[KindHT], - varId: IVarNameT - ): (ExpressionH[KindHT], Vector[ExpressionT]) = { + hinputs: HinputsI, + hamuts: HamutsBox, + currentFunctionHeader: FunctionHeaderI, + locals: LocalsBox, + sourceExprResultLine: ExpressionH[KindHT], + varId: IVarNameI[cI] + ): (ExpressionH[KindHT], Vector[ExpressionI]) = { val local = locals.get(varId).get vassert(!locals.unstackifiedVars.contains(local.id)) val newStoreNode = LocalStoreH( local, sourceExprResultLine, - nameHammer.translateFullName(hinputs, hamuts, currentFunctionHeader.id.addStep(varId))) + nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(currentFunctionHeader.id, varId))) (newStoreNode, Vector.empty) } } diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/NameHammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/NameHammer.scala index 3ec4a5e8e..ff74368b1 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/NameHammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/NameHammer.scala @@ -1,78 +1,24 @@ package dev.vale.simplifying -import dev.vale.{CodeLocationS, FileCoordinate, PackageCoordinate, SourceCodeUtils, finalast, vwat} +import dev.vale._ import dev.vale.finalast.IdH -import dev.vale.typing.Hinputs -import dev.vale.typing.names._ import dev.vale.finalast._ import dev.vale.postparsing.AnonymousSubstructParentInterfaceTemplateRuneS -import dev.vale.typing._ -import dev.vale.typing.env.PackageEnvironmentT -import dev.vale.typing.names._ -import dev.vale.typing.templata._ -import dev.vale.typing.types._ +import dev.vale.instantiating._ +import dev.vale.instantiating.ast._ import dev.vale.von.{IVonData, VonArray, VonInt, VonMember, VonObject, VonStr} import scala.collection.immutable.List class NameHammer() { - def getReadableName(namePart: INameT): String = { - namePart match { - case SelfNameT() => "self" - case AnonymousSubstructImplNameT(_, _, _) => "AnonSubstructImpl" -// case AbstractVirtualFreeNameT(_, _) => "(abstract vfree)" -// case OverrideVirtualFreeNameT(_, _) => "(override vfree)" -// case AbstractVirtualDropFunctionNameT(_, _, _) => "vdrop" -// case OverrideVirtualDropFunctionNameT(_, _, _) => "vdrop" -// case FreeNameT(FreeTemplateNameT(codeLoc), templateArgs, kind) => "Free" - case AnonymousSubstructMemberNameT(index) => "anonSubstructMember" + index - case AnonymousSubstructConstructorNameT(AnonymousSubstructConstructorTemplateNameT(substruct), templateArgs, params) => "anonSubstructConstructor" - case AnonymousSubstructNameT(_, _) => "AnonSubstruct" - case BuildingFunctionNameWithClosuredsT(_) => vwat() // Shouldnt see this in hammer - case CitizenNameT(templateName, templateArgs) => getReadableName(templateName) - case StructTemplateNameT(humanName) => humanName.str - case InterfaceTemplateNameT(humanName) => humanName.str - case ClosureParamNameT(_) => "closure" - case CodeVarNameT(name) => name.str - case ConstructingMemberNameT(name) => name.str -// case ConstructorNameT(params) => "constructor" - case ConstructorTemplateNameT(codeLoc) => "constructorTemplate" - case ExternFunctionNameT(humanName, params) => humanName.str - case FunctionNameT(FunctionTemplateNameT(humanName, codeLocation), templateArgs, params) => humanName.str - case FunctionTemplateNameT(humanName, codeLoc) => humanName.str - case PackageTopLevelNameT() => vwat() // Does this ever make it to hammer? -// case ImplDeclareNameT(codeLoc) => "impl" + codeLoc - case StaticSizedArrayNameT(_, size, variability, arr) => "ssa" + size + "," + variability - case LambdaCitizenNameT(codeLoc) => "lam" - case LambdaCallFunctionNameT(_, _, _) => "lamCall" - case LambdaCallFunctionTemplateNameT(_, _) => "lamTemplate" - case LetNameT(codeLoc) => "let" - case IterableNameT(range) => "iterable" - case IteratorNameT(range) => "iterator" - case IterationOptionNameT(range) => "iterationOption" - case MagicParamNameT(codeLoc) => "magicParam" - case PrimitiveNameT(humanName) => humanName.str - case RawArrayNameT(mutability, elementType) => "rawArr" - case TypingPassBlockResultVarNameT(num) => "blockResult" + num - case TypingPassFunctionResultVarNameT() => "funcResult" - case TypingPassPatternDestructureeNameT(num) => "patDestr" + num - case TypingPassPatternMemberNameT(life) => "patMem" + life - case TypingPassTemporaryVarNameT(num) => "tempVar" + num - case RuntimeSizedArrayNameT(_, _) => "rsa" - case UnnamedLocalNameT(codeLoc) => "unnamedLocal" - case ForwarderFunctionTemplateNameT(inner, index) => "fwdt_" + index + "_" + getReadableName(inner) - case ForwarderFunctionNameT(ForwarderFunctionTemplateNameT(innerFuncName, index), inner) => "fwd_" + index + "_" + getReadableName(inner) - } - } - def translateFullName( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - fullName2: IdT[INameT] + fullName2: IdI[cI, INameI[cI]] ): IdH = { - val IdT(packageCoord, _, localNameT) = fullName2 - val longName = CompilerErrorHumanizer.humanizeName(_.toString, fullName2) - val localName = CompilerErrorHumanizer.humanizeName(_.toString, localNameT) + val IdI(packageCoord, _, localNameT) = fullName2 + val longName = InstantiatedHumanizer.humanizeId(_.toString, fullName2) + val localName = InstantiatedHumanizer.humanizeName(_.toString, localNameT) finalast.IdH(localName, packageCoord, longName, longName) } diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/StructHammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/StructHammer.scala index 6814b3946..204d52470 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/StructHammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/StructHammer.scala @@ -1,16 +1,8 @@ package dev.vale.simplifying -import dev.vale.{Interner, Keywords, PackageCoordinate, vassert, vassertSome, vimpl, finalast => m} -import dev.vale.finalast.{BorrowH, EdgeH, InterfaceDefinitionH, InterfaceMethodH, InterfaceHT, KindHT, Mutable, PrototypeH, CoordH, StructDefinitionH, StructMemberH, StructHT, YonderH} -import dev.vale.typing.Hinputs -import dev.vale.typing.ast.{EdgeT, PrototypeT} -import dev.vale.typing.names._ -import dev.vale.typing.templata.{CoordTemplataT, MutabilityTemplataT} -import dev.vale.typing.types._ +import dev.vale.{Interner, Keywords, PackageCoordinate, vassert, vassertSome, vimpl, vregionmut, finalast => m} import dev.vale.finalast._ -import dev.vale.typing._ -import dev.vale.typing.ast._ -import dev.vale.typing.types._ +import dev.vale.instantiating.ast._ import scala.collection.immutable.ListMap @@ -19,16 +11,16 @@ class StructHammer( interner: Interner, keywords: Keywords, nameHammer: NameHammer, - translatePrototype: (Hinputs, HamutsBox, PrototypeT) => PrototypeH, - translateReference: (Hinputs, HamutsBox, CoordT) => CoordH[KindHT]) { - def translateInterfaces(hinputs: Hinputs, hamuts: HamutsBox): Unit = { + translatePrototype: (HinputsI, HamutsBox, PrototypeI[cI]) => PrototypeH, + translateReference: (HinputsI, HamutsBox, CoordI[cI]) => CoordH[KindHT]) { + def translateInterfaces(hinputs: HinputsI, hamuts: HamutsBox): Unit = { hinputs.interfaces.foreach(interface => translateInterface(hinputs, hamuts, interface.instantiatedInterface)) } def translateInterfaceMethods( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - interfaceTT: InterfaceTT): + interfaceTT: InterfaceIT[cI]): Vector[InterfaceMethodH] = { val edgeBlueprint = vassertSome(hinputs.interfaceToEdgeBlueprints.get(interfaceTT.id)) @@ -44,40 +36,40 @@ class StructHammer( } def translateInterface( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - interfaceTT: InterfaceTT): + interfaceIT: InterfaceIT[cI]): InterfaceHT = { - hamuts.interfaceTToInterfaceH.get(interfaceTT) match { + hamuts.interfaceTToInterfaceH.get(interfaceIT) match { case Some(structRefH) => structRefH case None => { - val fullNameH = nameHammer.translateFullName(hinputs, hamuts, interfaceTT.id) + val fullNameH = nameHammer.translateFullName(hinputs, hamuts, interfaceIT.id) // This is the only place besides InterfaceDefinitionH that can make a InterfaceRefH val temporaryInterfaceRefH = InterfaceHT(fullNameH); - hamuts.forwardDeclareInterface(interfaceTT, temporaryInterfaceRefH) - val interfaceDefT = hinputs.lookupInterface(interfaceTT.id); + hamuts.forwardDeclareInterface(interfaceIT, temporaryInterfaceRefH) + val interfaceDefI = hinputs.lookupInterface(interfaceIT.id); - val methodsH = translateInterfaceMethods(hinputs, hamuts, interfaceTT) + val methodsH = translateInterfaceMethods(hinputs, hamuts, interfaceIT) val interfaceDefH = InterfaceDefinitionH( fullNameH, - interfaceDefT.weakable, - Conversions.evaluateMutabilityTemplata(interfaceDefT.mutability), + interfaceDefI.weakable, + Conversions.evaluateMutabilityTemplata(interfaceDefI.mutability), Vector.empty /* super interfaces */, methodsH) - hamuts.addInterface(interfaceTT, interfaceDefH) + hamuts.addInterface(interfaceIT, interfaceDefH) vassert(interfaceDefH.getRef == temporaryInterfaceRefH) // Make sure there's a destructor for this shared interface. - interfaceDefT.mutability match { - case MutabilityTemplataT(MutableT) => None - case MutabilityTemplataT(ImmutableT) => { + interfaceDefI.mutability match { + case MutableI => None + case ImmutableI => { // vassert( // hinputs.functions.exists(function => { // function.header.fullName match { -// case FullNameT(_, _, FreeNameT(_, _, k)) if k.kind == interfaceDefT.instantiatedInterface => true +// case FullNameI(_, _, FreeNameI(_, _, k)) if k.kind == interfaceDefI.instantiatedInterface => true // case _ => false // } // })) @@ -89,46 +81,46 @@ class StructHammer( } } - def translateStructs(hinputs: Hinputs, hamuts: HamutsBox): Unit = { - hinputs.structs.foreach(structDefT => translateStructT(hinputs, hamuts, structDefT.instantiatedCitizen)) + def translateStructs(hinputs: HinputsI, hamuts: HamutsBox): Unit = { + hinputs.structs.foreach(structDefI => translateStructI(hinputs, hamuts, structDefI.instantiatedCitizen)) } - def translateStructT( - hinputs: Hinputs, + def translateStructI( + hinputs: HinputsI, hamuts: HamutsBox, - structTT: StructTT): + structIT: StructIT[cI]): (StructHT) = { - hamuts.structTToStructH.get(structTT) match { + hamuts.structTToStructH.get(structIT) match { case Some(structRefH) => structRefH case None => { - val (fullNameH) = nameHammer.translateFullName(hinputs, hamuts, structTT.id) + val (fullNameH) = nameHammer.translateFullName(hinputs, hamuts, structIT.id) // This is the only place besides StructDefinitionH that can make a StructRefH val temporaryStructRefH = StructHT(fullNameH); - hamuts.forwardDeclareStruct(structTT, temporaryStructRefH) - val structDefT = hinputs.lookupStruct(structTT.id); + hamuts.forwardDeclareStruct(structIT, temporaryStructRefH) + val structDefI = hinputs.lookupStruct(structIT.id); val (membersH) = - translateMembers(hinputs, hamuts, structDefT.instantiatedCitizen.id, structDefT.members) + translateMembers(hinputs, hamuts, structDefI.instantiatedCitizen.id, structDefI.members) - val (edgesH) = translateEdgesForStruct(hinputs, hamuts, temporaryStructRefH, structTT) + val (edgesH) = translateEdgesForStruct(hinputs, hamuts, temporaryStructRefH, structIT) val structDefH = StructDefinitionH( fullNameH, - structDefT.weakable, - Conversions.evaluateMutabilityTemplata(structDefT.mutability), + structDefI.weakable, + Conversions.evaluateMutabilityTemplata(structDefI.mutability), edgesH, membersH); - hamuts.addStructOriginatingFromTypingPass(structTT, structDefH) + hamuts.addStructOriginatingFromTypingPass(structIT, structDefH) vassert(structDefH.getRef == temporaryStructRefH) // Make sure there's a destructor for this shared struct. - structDefT.mutability match { - case MutabilityTemplataT(MutableT) => None - case MutabilityTemplataT(ImmutableT) => { + structDefI.mutability match { + case MutableI => None + case ImmutableI => { // vassert( // hinputs.functions.exists(function => { // function.header.fullName match { -// case FullNameT(_, _, FreeNameT(_, _, k)) if k.kind == structDefT.instantiatedCitizen => true +// case FullNameI(_, _, FreeNameI(_, _, k)) if k.kind == structDefI.instantiatedCitizen => true // case _ => false // } // })) @@ -141,50 +133,50 @@ class StructHammer( } } - def translateMembers(hinputs: Hinputs, hamuts: HamutsBox, structName: IdT[INameT], members: Vector[IStructMemberT]): + def translateMembers(hinputs: HinputsI, hamuts: HamutsBox, structName: IdI[cI, INameI[cI]], members: Vector[StructMemberI]): (Vector[StructMemberH]) = { members.map(translateMember(hinputs, hamuts, structName, _)) } - def translateMember(hinputs: Hinputs, hamuts: HamutsBox, structName: IdT[INameT], member2: IStructMemberT): + def translateMember(hinputs: HinputsI, hamuts: HamutsBox, structName: IdI[cI, INameI[cI]], member2: StructMemberI): (StructMemberH) = { val (variability, memberType) = member2 match { - case VariadicStructMemberT(name, tyype) => vimpl() - case NormalStructMemberT(_, variability, ReferenceMemberTypeT(coord)) => { +// case VariadicStructMemberI(name, tyype) => vimpl() + case StructMemberI(_, variability, ReferenceMemberTypeI(coord)) => { (variability, translateReference(hinputs, hamuts, coord)) } - case NormalStructMemberT(_, variability, AddressMemberTypeT(coord)) => { + case StructMemberI(_, variability, AddressMemberTypeI(coord)) => { val (referenceH) = translateReference(hinputs, hamuts, coord) val (boxStructRefH) = makeBox(hinputs, hamuts, variability, coord, referenceH) // The stack owns the box, closure structs just borrow it. - (variability, CoordH(BorrowH, YonderH, boxStructRefH)) + (variability, CoordH(vregionmut(MutableBorrowH), YonderH, boxStructRefH)) } } StructMemberH( - nameHammer.translateFullName(hinputs, hamuts, structName.addStep(member2.name)), + nameHammer.translateFullName(hinputs, hamuts, INameI.addStep(structName, member2.name)), Conversions.evaluateVariability(variability), memberType) } def makeBox( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - conceptualVariability: VariabilityT, - type2: CoordT, + conceptualVariability: VariabilityI, + type2: CoordI[cI], typeH: CoordH[KindHT]): (StructHT) = { val boxFullName2 = - IdT( + IdI( PackageCoordinate.BUILTIN(interner, keywords), - Vector.empty, - interner.intern(StructNameT( - interner.intern(StructTemplateNameT(keywords.BOX_HUMAN_NAME)), - Vector(CoordTemplataT(type2))))) + Vector[INameI[cI]](), + StructNameI[cI]( + StructTemplateNameI[cI](keywords.BOX_HUMAN_NAME), + Vector(CoordTemplataI[cI](RegionTemplataI(0), type2)))) val boxFullNameH = nameHammer.translateFullName(hinputs, hamuts, boxFullName2) - hamuts.structDefs.find(_.fullName == boxFullNameH) match { + hamuts.structDefs.find(_.id == boxFullNameH) match { case Some(structDefH) => (structDefH.getRef) case None => { val temporaryStructRefH = StructHT(boxFullNameH); @@ -192,11 +184,11 @@ class StructHammer( // We don't actually care about the given variability, because even if it's final, we still need // the box to contain a varying reference, see VCBAAF. val _ = conceptualVariability - val actualVariability = VaryingT + val actualVariability = VaryingI val memberH = StructMemberH( - nameHammer.addStep(hamuts, temporaryStructRefH.fullName, keywords.BOX_MEMBER_NAME.str), + nameHammer.addStep(hamuts, temporaryStructRefH.id, keywords.BOX_MEMBER_NAME.str), Conversions.evaluateVariability(actualVariability), typeH) val structDefH = @@ -214,36 +206,36 @@ class StructHammer( } private def translateEdgesForStruct( - hinputs: Hinputs, hamuts: HamutsBox, + hinputs: HinputsI, hamuts: HamutsBox, structRefH: StructHT, - structTT: StructTT): + structTT: StructIT[cI]): (Vector[EdgeH]) = { val edges2 = hinputs.interfaceToSubCitizenToEdge.values.flatMap(_.values).filter(_.subCitizen.id == structTT.id) translateEdgesForStruct(hinputs, hamuts, structRefH, edges2.toVector) } private def translateEdgesForStruct( - hinputs: Hinputs, hamuts: HamutsBox, + hinputs: HinputsI, hamuts: HamutsBox, structRefH: StructHT, - edges2: Vector[EdgeT]): + edges2: Vector[EdgeI]): (Vector[EdgeH]) = { - edges2.map(e => translateEdge(hinputs, hamuts, structRefH, interner.intern(InterfaceTT(e.superInterface)), e)) + edges2.map(e => translateEdge(hinputs, hamuts, structRefH, InterfaceIT(e.superInterface), e)) } - private def translateEdge(hinputs: Hinputs, hamuts: HamutsBox, structRefH: StructHT, interfaceTT: InterfaceTT, edge2: EdgeT): + private def translateEdge(hinputs: HinputsI, hamuts: HamutsBox, structRefH: StructHT, interfaceIT: InterfaceIT[cI], edge2: EdgeI): (EdgeH) = { // Purposefully not trying to translate the entire struct here, because we might hit a circular dependency - val interfaceRefH = translateInterface(hinputs, hamuts, interfaceTT) - val interfacePrototypesH = translateInterfaceMethods(hinputs, hamuts, interfaceTT) + val interfaceRefH = translateInterface(hinputs, hamuts, interfaceIT) + val interfacePrototypesH = translateInterfaceMethods(hinputs, hamuts, interfaceIT) val prototypesH = - vassertSome(hinputs.interfaceToEdgeBlueprints.get(interfaceTT.id)) + vassertSome(hinputs.interfaceToEdgeBlueprints.get(interfaceIT.id)) .superFamilyRootHeaders.map({ case (superFamilyPrototype, virtualParamIndex) => - val overridePrototypeT = + val overridePrototypeI = vassertSome(edge2.abstractFuncToOverrideFunc.get(superFamilyPrototype.id)) - val overridePrototypeH = translatePrototype(hinputs, hamuts, overridePrototypeT.overridePrototype) + val overridePrototypeH = translatePrototype(hinputs, hamuts, overridePrototypeI) overridePrototypeH }) @@ -251,11 +243,11 @@ class StructHammer( (EdgeH(structRefH, interfaceRefH, structPrototypesByInterfacePrototype)) } - def lookupStruct(hinputs: Hinputs, hamuts: HamutsBox, structTT: StructTT): StructDefinitionT = { + def lookupStruct(hinputs: HinputsI, hamuts: HamutsBox, structTT: StructIT[cI]): StructDefinitionI = { hinputs.lookupStruct(structTT.id) } - def lookupInterface(hinputs: Hinputs, hamuts: HamutsBox, interfaceTT: InterfaceTT): InterfaceDefinitionT = { + def lookupInterface(hinputs: HinputsI, hamuts: HamutsBox, interfaceTT: InterfaceIT[cI]): InterfaceDefinitionI = { hinputs.lookupInterface(interfaceTT.id) } } diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/TypeHammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/TypeHammer.scala index f86574f56..0b1d1f13c 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/TypeHammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/TypeHammer.scala @@ -1,69 +1,71 @@ package dev.vale.simplifying -import dev.vale.finalast.{BoolHT, FloatHT, InlineH, IntHT, KindHT, NeverHT, PrototypeH, CoordH, RuntimeSizedArrayDefinitionHT, RuntimeSizedArrayHT, StaticSizedArrayDefinitionHT, StaticSizedArrayHT, StrHT, VoidHT, YonderH} -import dev.vale.typing.Hinputs -import dev.vale.typing.ast.PrototypeT -import dev.vale.typing.types._ -import dev.vale.{Interner, Keywords, vfail, vwat, finalast => m} +import dev.vale.finalast.{BoolHT, CoordH, FloatHT, InlineH, IntHT, KindHT, NeverHT, PrototypeH, RuntimeSizedArrayDefinitionHT, RuntimeSizedArrayHT, StaticSizedArrayDefinitionHT, StaticSizedArrayHT, StrHT, VoidHT, YonderH} +import dev.vale.{Interner, Keywords, vassert, vfail, vimpl, vregionmut, vwat, finalast => m} import dev.vale.finalast._ -import dev.vale.typing._ -import dev.vale.typing.names.CitizenTemplateNameT -//import dev.vale.typingpass.templata.FunctionHeaderT -import dev.vale.typing.types._ +import dev.vale.instantiating.ast._ class TypeHammer( interner: Interner, keywords: Keywords, nameHammer: NameHammer, structHammer: StructHammer) { - def translateKind(hinputs: Hinputs, hamuts: HamutsBox, tyype: KindT): + def translateKind(hinputs: HinputsI, hamuts: HamutsBox, tyype: KindIT[cI]): (KindHT) = { tyype match { - case NeverT(fromBreak) => NeverHT(fromBreak) - case IntT(bits) => IntHT(bits) - case BoolT() => BoolHT() - case FloatT() => FloatHT() - case StrT() => StrHT() - case VoidT() => VoidHT() - case s @ StructTT(_) => structHammer.translateStructT(hinputs, hamuts, s) + case NeverIT(fromBreak) => NeverHT(fromBreak) + case IntIT(bits) => IntHT(bits) + case BoolIT() => BoolHT() + case FloatIT() => FloatHT() + case StrIT() => StrHT() + case VoidIT() => VoidHT() + case s @ StructIT(_) => structHammer.translateStructI(hinputs, hamuts, s) - case i @ InterfaceTT(_) => structHammer.translateInterface(hinputs, hamuts, i) + case i @ InterfaceIT(_) => structHammer.translateInterface(hinputs, hamuts, i) - case OverloadSetT(_, _) => VoidHT() +// case OverloadSetI(_, _) => VoidHT() - case a @ contentsStaticSizedArrayTT(_, _, _, _) => translateStaticSizedArray(hinputs, hamuts, a) - case a @ contentsRuntimeSizedArrayTT(_, _) => translateRuntimeSizedArray(hinputs, hamuts, a) - case KindPlaceholderT(fullName) => { - // this is a bit of a hack. sometimes lambda templates like to remember their original - // defining generics, and we dont translate those in the instantiator, so it can later - // use them to find those original templates. - // because of that, they make their way into the hammer, right here. - // long term, we should probably find a way to tostring templatas cleanly rather than - // converting them to hammer first. - // See DMPOGN for why these make it into the hammer. - VoidHT() - } + case a @ contentsStaticSizedArrayIT(_, _, _, _, _) => translateStaticSizedArray(hinputs, hamuts, a) + case a @ contentsRuntimeSizedArrayIT(_, _, _) => translateRuntimeSizedArray(hinputs, hamuts, a) +// case KindPlaceholderI(fullName) => { +// // this is a bit of a hack. sometimes lambda templates like to remember their original +// // defining generics, and we dont translate those in the instantiator, so it can later +// // use them to find those original templates. +// // because of that, they make their way into the hammer, right here. +// // long term, we should probably find a way to tostring templatas cleanly rather than +// // converting them to hammer first. +// // See DMPOGN for why these make it into the hammer. +// VoidHT() +// } } } + def translateRegion( + hinputs: HinputsI, + hamuts: HamutsBox, + region: RegionTemplataI[cI]): + RegionH = { + RegionH() + } + def translateCoord( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - coord: CoordT): + coord: CoordI[cI]): (CoordH[KindHT]) = { - val CoordT(ownership, _, innerType) = coord; + val CoordI(ownership, innerType) = coord; val location = { (ownership, innerType) match { - case (OwnT, _) => YonderH - case (BorrowT, _) => YonderH - case (WeakT, _) => YonderH - case (ShareT, OverloadSetT(_, _)) => InlineH -// case (ShareT, PackTT(_, _)) => InlineH -// case (ShareT, TupleTT(_, _)) => InlineH -// case (ShareT, StructTT(FullNameT(_, Vector(), CitizenNameT(CitizenTemplateNameT("Tup"), _)))) => InlineH - case (ShareT, VoidT() | IntT(_) | BoolT() | FloatT() | NeverT(_)) => InlineH - case (ShareT, StrT()) => YonderH - case (ShareT, _) => YonderH + case (OwnI, _) => YonderH + case (ImmutableBorrowI | MutableBorrowI, _) => YonderH + case (WeakI, _) => YonderH +// case (ImmutableShareI | MutableShareI, OverloadSetI(_, _)) => InlineH +// case (ShareI, PackIT(_, _)) => InlineH +// case (ShareI, TupleIT(_, _)) => InlineH +// case (ShareI, StructIT(FullNameI(_, Vector(), CitizenNameI(CitizenTemplateNameI("Tup"), _)))) => InlineH + case (ImmutableShareI | MutableShareI, VoidIT() | IntIT(_) | BoolIT() | FloatIT() | NeverIT(_)) => InlineH + case (ImmutableShareI | MutableShareI, StrIT()) => YonderH + case (ImmutableShareI | MutableShareI, _) => YonderH } } val (innerH) = translateKind(hinputs, hamuts, innerType); @@ -71,9 +73,9 @@ class TypeHammer( } def translateCoords( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - references2: Vector[CoordT]): + references2: Vector[CoordI[cI]]): (Vector[CoordH[KindHT]]) = { references2.map(translateCoord(hinputs, hamuts, _)) } @@ -85,47 +87,56 @@ class TypeHammer( } def translateStaticSizedArray( - hinputs: Hinputs, + hinputs: HinputsI, hamuts: HamutsBox, - ssaTT: StaticSizedArrayTT): + ssaIT: StaticSizedArrayIT[cI]): StaticSizedArrayHT = { - hamuts.staticSizedArrays.get(ssaTT) match { + hamuts.staticSizedArrays.get(ssaIT) match { case Some(x) => x.kind case None => { - val name = nameHammer.translateFullName(hinputs, hamuts, ssaTT.name) - val contentsStaticSizedArrayTT(_, mutabilityT, variabilityT, memberType) = ssaTT - val memberReferenceH = translateCoord(hinputs, hamuts, memberType) - val mutability = Conversions.evaluateMutabilityTemplata(mutabilityT) - val variability = Conversions.evaluateVariabilityTemplata(variabilityT) - val size = Conversions.evaluateIntegerTemplata(ssaTT.size) + val name = nameHammer.translateFullName(hinputs, hamuts, ssaIT.name) + val contentsStaticSizedArrayIT(_, mutabilityI, variabilityI, memberType, arrRegion) = ssaIT + vregionmut(arrRegion) // what do with arrRegion? + val memberReferenceH = translateCoord(hinputs, hamuts, memberType.coord) + val mutability = Conversions.evaluateMutabilityTemplata(mutabilityI) + val variability = Conversions.evaluateVariabilityTemplata(variabilityI) + val size = ssaIT.size val definition = StaticSizedArrayDefinitionHT(name, size, mutability, variability, memberReferenceH) - hamuts.addStaticSizedArray(ssaTT, definition) + hamuts.addStaticSizedArray(ssaIT, definition) StaticSizedArrayHT(name) } } } - def translateRuntimeSizedArray(hinputs: Hinputs, hamuts: HamutsBox, rsaTT: RuntimeSizedArrayTT): RuntimeSizedArrayHT = { - hamuts.runtimeSizedArrays.get(rsaTT) match { + def translateRuntimeSizedArray(hinputs: HinputsI, hamuts: HamutsBox, rsaIT: RuntimeSizedArrayIT[cI]): RuntimeSizedArrayHT = { + hamuts.runtimeSizedArrays.get(rsaIT) match { case Some(x) => x.kind case None => { - val nameH = nameHammer.translateFullName(hinputs, hamuts, rsaTT.name) - val contentsRuntimeSizedArrayTT(mutabilityT, memberType) = rsaTT - val memberReferenceH = translateCoord(hinputs, hamuts, memberType) - val mutability = Conversions.evaluateMutabilityTemplata(mutabilityT) - // val variability = Conversions.evaluateVariability(variabilityT) + val nameH = nameHammer.translateFullName(hinputs, hamuts, rsaIT.name) + val contentsRuntimeSizedArrayIT(mutabilityI, memberType, arrRegion) = rsaIT + vregionmut(arrRegion) // what do with arrRegion? + val memberReferenceH = translateCoord(hinputs, hamuts, memberType.coord) + val mutability = Conversions.evaluateMutabilityTemplata(mutabilityI) + // val variability = Conversions.evaluateVariability(variabilityI) val definition = RuntimeSizedArrayDefinitionHT(nameH, mutability, memberReferenceH) - hamuts.addRuntimeSizedArray(rsaTT, definition) - RuntimeSizedArrayHT(nameH) + val result = RuntimeSizedArrayHT(nameH) + // DO NOT SUBMIT a few options: + // - do this for SSAs too + // - nuke the way we were doing names for hamuts, make proper names finally + hamuts.runtimeSizedArrays.values.find(_.kind == result) match { + case Some(x) => + case None => hamuts.addRuntimeSizedArray(rsaIT, definition) + } + result } } } def translatePrototype( - hinputs: Hinputs, hamuts: HamutsBox, - prototype2: PrototypeT): + hinputs: HinputsI, hamuts: HamutsBox, + prototype2: PrototypeI[cI]): (PrototypeH) = { - val PrototypeT(fullName2, returnType2) = prototype2; + val PrototypeI(fullName2, returnType2) = prototype2; val (paramsTypesH) = translateCoords(hinputs, hamuts, prototype2.paramTypes) val (returnTypeH) = translateCoord(hinputs, hamuts, returnType2) val (fullNameH) = nameHammer.translateFullName(hinputs, hamuts, fullName2) diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/VonHammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/VonHammer.scala index aed629bc2..7f5b41275 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/VonHammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/VonHammer.scala @@ -2,16 +2,10 @@ package dev.vale.simplifying import dev.vale.{CodeLocationS, PackageCoordinate, RangeS, vimpl} import dev.vale.finalast._ -import dev.vale.typing.Hinputs -import dev.vale.typing.names._ -import dev.vale.typing.templata._ import dev.vale.finalast._ +import dev.vale.instantiating.ast._ import dev.vale.{finalast => m} import dev.vale.postparsing._ -import dev.vale.typing.templata._ -import dev.vale.typing._ -import dev.vale.typing.names._ -import dev.vale.typing.types._ import dev.vale.von.{IVonData, VonArray, VonBool, VonFloat, VonInt, VonMember, VonObject, VonStr} class VonHammer(nameHammer: NameHammer, typeHammer: TypeHammer) { @@ -124,17 +118,18 @@ class VonHammer(nameHammer: NameHammer, typeHammer: TypeHammer) { } def vonifyRegion(region: RegionH): IVonData = { - val RegionH(name, kinds) = region + val RegionH() = region VonObject( "Region", None, - Vector( - VonMember( - "kinds", - VonArray( - None, - kinds.map(vonifyKind).toVector)))) + Vector()) +// Vector( +// VonMember( +// "kinds", +// VonArray( +// None, +// kinds.map(vonifyKind).toVector)))) } def vonifyStructH(ref: StructHT): IVonData = { @@ -269,8 +264,10 @@ class VonHammer(nameHammer: NameHammer, typeHammer: TypeHammer) { def vonifyOwnership(ownership: OwnershipH): IVonData = { ownership match { case OwnH => VonObject("Own", None, Vector()) - case BorrowH => VonObject("Borrow", None, Vector()) - case ShareH => VonObject("Share", None, Vector()) + case ImmutableBorrowH => VonObject("ImmutableBorrow", None, Vector()) + case MutableBorrowH => VonObject("MutableBorrow", None, Vector()) + case ImmutableShareH => VonObject("ImmutableShare", None, Vector()) + case MutableShareH => VonObject("MutableShare", None, Vector()) case WeakH => VonObject("Weak", None, Vector()) } } @@ -473,6 +470,14 @@ class VonHammer(nameHammer: NameHammer, typeHammer: TypeHammer) { VonMember("sourceExpr", vonifyExpression(sourceExpr)), VonMember("sourceResultType", vonifyCoord(sourceExpr.resultType)))) } + case PreCheckBorrowH(sourceExpr) => { + VonObject( + "PreCheckBorrow", + None, + Vector( + VonMember("sourceExpr", vonifyExpression(sourceExpr)), + VonMember("sourceResultType", vonifyCoord(sourceExpr.resultType)))) + } case ArgumentH(resultReference, argumentIndex) => { VonObject( "Argument", @@ -551,6 +556,7 @@ class VonHammer(nameHammer: NameHammer, typeHammer: TypeHammer) { None, Vector( VonMember("arrayExpr", vonifyExpression(structExpr)), + VonMember("arrayType", vonifyCoord(structExpr.resultType)), VonMember( "localTypes", VonArray(None, localTypes.map(localType => vonifyCoord(localType)).toVector)), @@ -841,6 +847,24 @@ class VonHammer(nameHammer: NameHammer, typeHammer: TypeHammer) { Vector( VonMember("exprs", VonArray(None, nodes.map(node => vonifyExpression(node)).toVector)))) } + case m @ MutabilifyH(inner) => { + VonObject( + "Mutabilify", + None, + Vector( + VonMember("sourceExpr", vonifyExpression(inner)), + VonMember("sourceType", vonifyCoord(inner.resultType)), + VonMember("resultType", vonifyCoord(m.resultType)))) + } + case m @ ImmutabilifyH(inner) => { + VonObject( + "Immutabilify", + None, + Vector( + VonMember("sourceExpr", vonifyExpression(inner)), + VonMember("sourceType", vonifyCoord(inner.resultType)), + VonMember("resultType", vonifyCoord(m.resultType)))) + } case BlockH(inner) => { VonObject( "Block", @@ -898,7 +922,7 @@ class VonHammer(nameHammer: NameHammer, typeHammer: TypeHammer) { vonifyOptional[IdH](maybeName, x => vonifyName(x))))) } - def vonifyOptional[T](opt: Option[T], func: (T) => IVonData): IVonData = { + def vonifyOptional[I](opt: Option[I], func: (I) => IVonData): IVonData = { opt match { case None => VonObject("None", None, Vector()) case Some(value) => VonObject("Some", None, Vector(VonMember("value", func(value)))) diff --git a/Frontend/TestVM/src/dev/vale/testvm/ExpressionVivem.scala b/Frontend/TestVM/src/dev/vale/testvm/ExpressionVivem.scala index 6bc0b492b..813c63cf0 100644 --- a/Frontend/TestVM/src/dev/vale/testvm/ExpressionVivem.scala +++ b/Frontend/TestVM/src/dev/vale/testvm/ExpressionVivem.scala @@ -1,7 +1,7 @@ package dev.vale.testvm -import dev.vale.finalast.{ArgumentH, ArrayCapacityH, ArrayLengthH, AsSubtypeH, BlockH, BoolHT, BorrowH, BorrowToWeakH, BreakH, CallH, ConsecutorH, ConstantBoolH, ConstantF64H, ConstantIntH, ConstantStrH, ConstantVoidH, DestroyH, DestroyImmRuntimeSizedArrayH, DestroyMutRuntimeSizedArrayH, DestroyStaticSizedArrayIntoFunctionH, DestroyStaticSizedArrayIntoLocalsH, DiscardH, ExpressionH, FloatHT, IfH, InlineH, IntHT, InterfaceCallH, InterfaceHT, IsSameInstanceH, KindHT, LocalLoadH, LocalStoreH, LocationH, LockWeakH, MemberLoadH, MemberStoreH, NewArrayFromValuesH, NewImmRuntimeSizedArrayH, NewMutRuntimeSizedArrayH, NewStructH, OwnH, PopRuntimeSizedArrayH, ProgramH, PrototypeH, PushRuntimeSizedArrayH, CoordH, ReturnH, RuntimeSizedArrayHT, RuntimeSizedArrayLoadH, RuntimeSizedArrayStoreH, ShareH, StackifyH, StaticArrayFromCallableH, StaticSizedArrayHT, StaticSizedArrayLoadH, StaticSizedArrayStoreH, StrHT, StructHT, StructToInterfaceUpcastH, UnstackifyH, VoidHT, WeakH, WhileH, YonderH} -import dev.vale.{vassert, vassertOne, vassertSome, vcurious, vfail, vimpl, vwat, finalast => m} +import dev.vale.finalast._ +import dev.vale.{vassert, vassertOne, vassertSome, vcurious, vfail, vimpl, vregionmut, vwat, finalast => m} import dev.vale.finalast._ import scala.collection.mutable @@ -18,8 +18,8 @@ object ExpressionVivem { def makePrimitive(heap: Heap, callId: CallId, location: LocationH, kind: KindV) = { vassert(kind != VoidV) - val ref = heap.allocateTransient(ShareH, location, kind) - heap.incrementReferenceRefCount(RegisterToObjectReferrer(callId, ShareH), ref) + val ref = heap.allocateTransient(MutableShareH, location, kind) + heap.incrementReferenceRefCount(RegisterToObjectReferrer(callId, MutableShareH), ref) ref } @@ -69,10 +69,20 @@ object ExpressionVivem { val callId = expressionId.callId node match { + case PreCheckBorrowH(innerExpr) => { + val innerRef = + executeNode(programH, stdin, stdout, heap, expressionId.addStep(0), innerExpr) match { + case r @ (NodeReturn(_) | NodeBreak()) => return r + case NodeContinue(r) => r + } + return NodeContinue(innerRef) + } case DiscardH(sourceExpr) => { sourceExpr.resultType.ownership match { - case ShareH => - case BorrowH => + case MutableShareH => + case ImmutableShareH => + case ImmutableBorrowH => + case MutableBorrowH => case WeakH => } val sourceRef = @@ -88,6 +98,39 @@ object ExpressionVivem { val ref = heap.void NodeContinue(ref) } + case ExternCallH(prototypeH, argsExprs) => { + val externFunction = FunctionVivem.getExternFunction(programH, prototypeH) + + val argRefs = + argsExprs.zipWithIndex.map({ case (argExpr, i) => + executeNode(programH, stdin, stdout, heap, expressionId.addStep(i), argExpr) match { + case NodeBreak() | NodeReturn(_) => { + // This shouldnt be possible because break and return can only + // be statements, not expressions, see BRCOBS. + vwat() + } + case NodeContinue(r) => r + } + }) + + val resultRef = + externFunction( + new AdapterForExterns( + programH, + heap, + CallId(expressionId.callId.callDepth + 1, prototypeH), + stdin, + stdout), + argRefs.toVector) + heap.incrementReferenceRefCount(RegisterToObjectReferrer(callId, resultRef.ownership), resultRef) + + // Special case for externs; externs arent allowed to change ref counts at all. + // So, we just drop these normally. + argRefs.zip(argsExprs.map(_.resultType)) + .foreach({ case (r, expectedType) => discard(programH, heap, stdout, stdin, callId, expectedType, r) }) + + NodeContinue(resultRef) + } case ConstantIntH(value, bits) => { val ref = makePrimitive(heap, callId, InlineH, IntV(value, bits)) NodeContinue(ref) @@ -151,6 +194,43 @@ object ExpressionVivem { NodeContinue(ref) } + case MutabilifyH(inner) => { + val sourceRef = + executeNode(programH, stdin, stdout, heap, expressionId.addStep(0), inner) match { + case r@(NodeReturn(_) | NodeBreak()) => return r + case NodeContinue(r) => r + } + val resultRef = + sourceRef.copy( + ownership = + sourceRef.ownership match { + case ImmutableShareH => MutableShareH + case ImmutableBorrowH => MutableBorrowH + case other => vwat() + }) + heap.incrementReferenceRefCount(RegisterToObjectReferrer(callId, resultRef.ownership), resultRef) + heap.decrementReferenceRefCount(RegisterToObjectReferrer(callId, sourceRef.ownership), sourceRef) + NodeContinue(resultRef) + } + case ImmutabilifyH(inner) => { + val sourceRef = + executeNode(programH, stdin, stdout, heap, expressionId.addStep(0), inner) match { + case r@(NodeReturn(_) | NodeBreak()) => return r + case NodeContinue(r) => r + } + val resultRef = + sourceRef.copy( + ownership = + sourceRef.ownership match { + case MutableShareH => ImmutableShareH + case MutableBorrowH => ImmutableBorrowH + case other => vwat() + }) + heap.incrementReferenceRefCount(RegisterToObjectReferrer(callId, resultRef.ownership), resultRef) + heap.decrementReferenceRefCount(RegisterToObjectReferrer(callId, sourceRef.ownership), sourceRef) + + NodeContinue(resultRef) + } case BlockH(sourceExpr) => { executeNode(programH, stdin, stdout, heap, expressionId.addStep(0), sourceExpr) } @@ -186,7 +266,7 @@ object ExpressionVivem { structReference) // DDSOT - heap.ensureRefCount(structReference, Some(Set(OwnH, BorrowH)), 0) + heap.ensureRefCount(structReference, Some(Set(OwnH, MutableBorrowH, ImmutableBorrowH)), 0) val oldMemberReferences = heap.destructure(structReference) @@ -264,7 +344,7 @@ object ExpressionVivem { case r @ (NodeReturn(_) | NodeBreak()) => return r case NodeContinue(r) => r } - vassert(constraintRef.ownership == BorrowH) + vassert(constraintRef.ownership == MutableBorrowH || constraintRef.ownership == ImmutableBorrowH) val weakRef = heap.transmute(constraintRef, sourceExpr.resultType, waH.resultType) heap.incrementReferenceRefCount(RegisterToObjectReferrer(callId, weakRef.ownership), weakRef) @@ -325,7 +405,7 @@ object ExpressionVivem { vassert(weakRef.ownership == WeakH) if (heap.containsLiveObject(weakRef)) { - val expectedRef = CoordH(BorrowH, YonderH, sourceExpr.resultType.kind) + val expectedRef = CoordH(vregionmut(MutableBorrowH), YonderH, sourceExpr.resultType.kind) val constraintRef = heap.transmute(weakRef, sourceExpr.resultType, expectedRef) heap.vivemDout.println() @@ -508,27 +588,27 @@ object ExpressionVivem { }) val functionH = programH.lookupFunction(prototypeH) - if (functionH.isExtern) { - val externFunction = FunctionVivem.getExternFunction(programH, prototypeH) - - val resultRef = - externFunction( - new AdapterForExterns( - programH, - heap, - CallId(expressionId.callId.callDepth + 1, prototypeH), - stdin, - stdout), - argRefs.toVector) - heap.incrementReferenceRefCount(RegisterToObjectReferrer(callId, resultRef.ownership), resultRef) - - // Special case for externs; externs arent allowed to change ref counts at all. - // So, we just drop these normally. - argRefs.zip(argsExprs.map(_.resultType)) - .foreach({ case (r, expectedType) => discard(programH, heap, stdout, stdin, callId, expectedType, r) }) - - NodeContinue(resultRef) - } else { +// if (functionH.isExtern) { +// val externFunction = FunctionVivem.getExternFunction(programH, prototypeH) +// +// val resultRef = +// externFunction( +// new AdapterForExterns( +// programH, +// heap, +// CallId(expressionId.callId.callDepth + 1, prototypeH), +// stdin, +// stdout), +// argRefs.toVector) +// heap.incrementReferenceRefCount(RegisterToObjectReferrer(callId, resultRef.ownership), resultRef) +// +// // Special case for externs; externs arent allowed to change ref counts at all. +// // So, we just drop these normally. +// argRefs.zip(argsExprs.map(_.resultType)) +// .foreach({ case (r, expectedType) => discard(programH, heap, stdout, stdin, callId, expectedType, r) }) +// +// NodeContinue(resultRef) +// } else { heap.vivemDout.println() heap.vivemDout.println(" " * expressionId.callId.callDepth + "Making new stack frame (call)") @@ -542,7 +622,7 @@ object ExpressionVivem { val returnRef = possessCalleeReturn(heap, callId, calleeCallId, retuurn) NodeContinue(returnRef) - } +// } } case InterfaceCallH(argsExprs, virtualParamIndex, interfaceRefH, indexInEdge, functionType) => { // undeviewed = not deviewed = the virtual param is still a view and we want it to @@ -1015,7 +1095,7 @@ object ExpressionVivem { heap.vivemDout.println() heap.vivemDout.println(" " * callId.callDepth + "Making new stack frame (generator)") - val indexReference = heap.allocateTransient(ShareH, InlineH, IntV(i, 32)) + val indexReference = heap.allocateTransient(MutableShareH, InlineH, IntV(i, 32)) heap.vivemDout.println() @@ -1130,8 +1210,8 @@ object ExpressionVivem { case WeakH => { heap.deallocateIfNoWeakRefs(actualReference) } - case BorrowH => // Do nothing. - case ShareH => { + case MutableBorrowH | ImmutableBorrowH => // Do nothing. + case MutableShareH | ImmutableShareH => { expectedReference.kind match { case VoidHT() | IntHT(_) | BoolHT() | StrHT() | FloatHT() => { heap.zero(actualReference) diff --git a/Frontend/TestVM/src/dev/vale/testvm/FunctionVivem.scala b/Frontend/TestVM/src/dev/vale/testvm/FunctionVivem.scala index 25068efbf..800f4dec8 100644 --- a/Frontend/TestVM/src/dev/vale/testvm/FunctionVivem.scala +++ b/Frontend/TestVM/src/dev/vale/testvm/FunctionVivem.scala @@ -49,60 +49,58 @@ object FunctionVivem { } def getExternFunction(programH: ProgramH, ref: PrototypeH): (AdapterForExterns, Vector[ReferenceV]) => ReferenceV = { - - ref.fullName.fullyQualifiedName + ref.id.fullyQualifiedName // The tests have a mode where they can interpret the builtins as separate packages, instead // of pulling it all in as one giant namespace. In that case, it prefixes things such as // v::builtins::arith. We can add other prefixes here too as needed. .replaceAllLiterally("v::builtins::arith", "") match { case """__vbi_addI32(i32, i32)""" => VivemExterns.addI32 - case """__vbi_addFloatFloat(float, float)""" => VivemExterns.addFloatFloat + case """__vbi_addFloatFloat""" => VivemExterns.addFloatFloat case """__vbi_panic""" => VivemExterns.panic - case """__vbi_multiplyI32(i32, i32)""" => VivemExterns.multiplyI32 - case """__vbi_subtractFloatFloat(float, float)""" => VivemExterns.subtractFloatFloat - case """__vbi_divideI32(i32, i32)""" => VivemExterns.divideI32 - case """__vbi_multiplyFloatFloat(float, float)""" => VivemExterns.multiplyFloatFloat - case """__vbi_divideFloatFloat(float, float)""" => VivemExterns.divideFloatFloat - case """__vbi_subtractI32(i32, i32)""" => VivemExterns.subtractI32 - case """addStr(str, i32, i32, str, i32, i32)""" => VivemExterns.addStrStr + case """__vbi_multiplyI32""" => VivemExterns.multiplyI32 + case """__vbi_subtractFloatFloat""" => VivemExterns.subtractFloatFloat + case """__vbi_divideI32""" => VivemExterns.divideI32 + case """__vbi_multiplyFloatFloat""" => VivemExterns.multiplyFloatFloat + case """__vbi_divideFloatFloat""" => VivemExterns.divideFloatFloat + case """__vbi_subtractI32""" => VivemExterns.subtractI32 + case """addStr""" => VivemExterns.addStrStr case """__getch""" => VivemExterns.getch - case """__vbi_eqFloatFloat(float, float)""" => VivemExterns.eqFloatFloat - case """sqrt(float)""" => VivemExterns.sqrt - case """__vbi_lessThanI32(i32, i32)""" => VivemExterns.lessThanI32 - case """__vbi_lessThanFloat(float, float)""" => VivemExterns.lessThanFloat - case """__vbi_greaterThanOrEqI32(i32, i32)""" => VivemExterns.greaterThanOrEqI32 - case """__vbi_greaterThanI32(i32, i32)""" => VivemExterns.greaterThanI32 - case """__vbi_eqI32(i32, i32)""" => VivemExterns.eqI32 - case """__vbi_eqBoolBool(bool, bool)""" => VivemExterns.eqBoolBool - case """printstr(str, i32, i32)""" => VivemExterns.print - case """__vbi_not(bool)""" => VivemExterns.not - case """castI32Str(i32)""" => VivemExterns.castI32Str - case """castI64Str(i64)""" => VivemExterns.castI64Str - case """castI32Float(i32)""" => VivemExterns.castI32Float - case """castFloatI32(float)""" => VivemExterns.castFloatI32 - case """__vbi_lessThanOrEqI32(i32, i32)""" => VivemExterns.lessThanOrEqI32 - case """__vbi_and(bool, bool)""" => VivemExterns.and - case """__vbi_or(bool, bool)""" => VivemExterns.or - case """__vbi_modI32(i32, i32)""" => VivemExterns.modI32 - case """__vbi_strLength(str)""" => VivemExterns.strLength - case """castFloatStr(float)""" => VivemExterns.castFloatStr - case """streq(str, i32, i32, str, i32, i32)""" => VivemExterns.eqStrStr - case """__vbi_negateFloat(float)""" => VivemExterns.negateFloat - case """__vbi_addI64(i64, i64)""" => VivemExterns.addI64 - case """__vbi_multiplyI64(i64, i64)""" => VivemExterns.multiplyI64 - case """__vbi_divideI64(i64, i64)""" => VivemExterns.divideI64 - case """__vbi_subtractI64(i64, i64)""" => VivemExterns.subtractI64 - case """__vbi_lessThanI64(i64, i64)""" => VivemExterns.lessThanI64 - case """__vbi_greaterThanOrEqI64(i64, i64)""" => VivemExterns.greaterThanOrEqI64 - case """__vbi_eqI64(i64, i64)""" => VivemExterns.eqI64 - case """__vbi_castI64Str(i64)""" => VivemExterns.castI64Str - case """__vbi_castI64Float(i64)""" => VivemExterns.castI64Float - case """__vbi_castFloatI64(float)""" => VivemExterns.castFloatI64 - case """__vbi_lessThanOrEqI64(i64, i64)""" => VivemExterns.lessThanOrEqI64 - case """__vbi_modI64(i64, i64)""" => VivemExterns.modI64 - case """TruncateI64ToI32(i64)""" => VivemExterns.truncateI64ToI32 - - case _ => vimpl(ref.fullName.fullyQualifiedName) + case """__vbi_eqFloatFloat""" => VivemExterns.eqFloatFloat + case """sqrt""" => VivemExterns.sqrt + case """__vbi_lessThanI32""" => VivemExterns.lessThanI32 + case """__vbi_lessThanFloat""" => VivemExterns.lessThanFloat + case """__vbi_greaterThanOrEqI32""" => VivemExterns.greaterThanOrEqI32 + case """__vbi_greaterThanI32""" => VivemExterns.greaterThanI32 + case """__vbi_eqI32""" => VivemExterns.eqI32 + case """__vbi_eqBoolBool""" => VivemExterns.eqBoolBool + case """printstr""" => VivemExterns.print + case """__vbi_not""" => VivemExterns.not + case """castI32Str""" => VivemExterns.castI32Str + case """castI64Str""" => VivemExterns.castI64Str + case """castI32Float""" => VivemExterns.castI32Float + case """castFloatI32""" => VivemExterns.castFloatI32 + case """__vbi_lessThanOrEqI32""" => VivemExterns.lessThanOrEqI32 + case """__vbi_and""" => VivemExterns.and + case """__vbi_or""" => VivemExterns.or + case """__vbi_modI32""" => VivemExterns.modI32 + case """__vbi_strLength""" => VivemExterns.strLength + case """castFloatStr""" => VivemExterns.castFloatStr + case """streq""" => VivemExterns.eqStrStr + case """__vbi_negateFloat""" => VivemExterns.negateFloat + case """__vbi_addI64""" => VivemExterns.addI64 + case """__vbi_multiplyI64""" => VivemExterns.multiplyI64 + case """__vbi_divideI64""" => VivemExterns.divideI64 + case """__vbi_subtractI64""" => VivemExterns.subtractI64 + case """__vbi_lessThanI64""" => VivemExterns.lessThanI64 + case """__vbi_greaterThanOrEqI64""" => VivemExterns.greaterThanOrEqI64 + case """__vbi_eqI64""" => VivemExterns.eqI64 + case """__vbi_castI64Str""" => VivemExterns.castI64Str + case """__vbi_castI64Float""" => VivemExterns.castI64Float + case """__vbi_castFloatI64""" => VivemExterns.castFloatI64 + case """__vbi_lessThanOrEqI64""" => VivemExterns.lessThanOrEqI64 + case """__vbi_modI64""" => VivemExterns.modI64 + case """TruncateI64ToI32""" => VivemExterns.truncateI64ToI32 + case _ => vimpl(ref.id.fullyQualifiedName) } } } diff --git a/Frontend/TestVM/src/dev/vale/testvm/Heap.scala b/Frontend/TestVM/src/dev/vale/testvm/Heap.scala index d5397f337..2421dfec6 100644 --- a/Frontend/TestVM/src/dev/vale/testvm/Heap.scala +++ b/Frontend/TestVM/src/dev/vale/testvm/Heap.scala @@ -1,6 +1,6 @@ package dev.vale.testvm -import dev.vale.finalast.{BoolHT, BorrowH, FloatHT, InlineH, IntHT, InterfaceHT, KindHT, Local, LocationH, OwnH, OwnershipH, ProgramH, PrototypeH, CoordH, RuntimeSizedArrayDefinitionHT, RuntimeSizedArrayHT, ShareH, StaticSizedArrayDefinitionHT, StaticSizedArrayHT, StrHT, StructDefinitionH, StructMemberH, StructHT, VoidHT, WeakH} +import dev.vale.finalast._ import dev.vale.{vassert, vassertSome, vfail, vimpl, von} import java.io.PrintStream @@ -36,7 +36,7 @@ class AllocationMap(vivemDout: PrintStream) { private val objectsById = mutable.HashMap[AllocationId, Allocation]() private val STARTING_ID = 501 private var nextId = STARTING_ID; - val void: ReferenceV = add(ShareH, InlineH, VoidV) + val void: ReferenceV = add(MutableShareH, InlineH, VoidV) private def newId() = { val id = nextId; @@ -266,8 +266,8 @@ class Heap(in_vivemDout: PrintStream) { } def isSameInstance(callId: CallId, left: ReferenceV, right: ReferenceV): ReferenceV = { - val ref = allocateTransient(ShareH, InlineH, BoolV(left.allocId == right.allocId)) - incrementReferenceRefCount(RegisterToObjectReferrer(callId, ShareH), ref) + val ref = allocateTransient(MutableShareH, InlineH, BoolV(left.allocId == right.allocId)) + incrementReferenceRefCount(RegisterToObjectReferrer(callId, MutableShareH), ref) ref } @@ -327,7 +327,8 @@ class Heap(in_vivemDout: PrintStream) { def zero(reference: ReferenceV) = { val allocation = objectsById.get(reference.allocId) vassert(allocation.getTotalRefCount(Some(OwnH)) == 0) - vassert(allocation.getTotalRefCount(Some(BorrowH)) == 0) + vassert(allocation.getTotalRefCount(Some(ImmutableBorrowH)) == 0) + vassert(allocation.getTotalRefCount(Some(MutableBorrowH)) == 0) allocation.kind match { case si @ StructInstanceV(_, _) => si.zero() case _ => @@ -338,7 +339,8 @@ class Heap(in_vivemDout: PrintStream) { // This happens when the last owning and weak references disappear. def deallocateIfNoWeakRefs(reference: ReferenceV) = { val allocation = objectsById.get(reference.allocId) - if (reference.actualCoord.hamut.ownership == OwnH && allocation.getTotalRefCount(Some(BorrowH)) > 0) { + if (reference.actualCoord.hamut.ownership == OwnH && + (allocation.getTotalRefCount(Some(MutableBorrowH)) + allocation.getTotalRefCount(Some(ImmutableBorrowH))) > 0) { throw ConstraintViolatedException("Constraint violated!") } if (allocation.getTotalRefCount(None) == 0) { @@ -426,7 +428,9 @@ class Heap(in_vivemDout: PrintStream) { } val ReferenceV(actualKind, oldSeenAsType, oldOwnership, oldLocation, objectId) = reference - vassert((oldOwnership == ShareH) == (targetType.ownership == ShareH)) + vassert( + (oldOwnership == MutableShareH || oldOwnership == ImmutableShareH) == + (targetType.ownership == MutableShareH || targetType.ownership == ImmutableShareH)) if (oldSeenAsType.hamut != expectedType.kind) { // not sure if the above .actualType is right @@ -452,7 +456,7 @@ class Heap(in_vivemDout: PrintStream) { } val ReferenceV(actualKind, oldSeenAsType, oldOwnership, oldLocation, objectId) = reference - vassert((oldOwnership == ShareH) == (targetType.ownership == ShareH)) + vassert((oldOwnership == MutableShareH) == (targetType.ownership == MutableShareH)) if (oldSeenAsType.hamut != expectedType.kind) { // not sure if the above .actualType is right @@ -557,7 +561,7 @@ class Heap(in_vivemDout: PrintStream) { case StrV(value) => vivemDout.print(value) case FloatV(value) => vivemDout.print(value) case StructInstanceV(structH, Some(members)) => { - vivemDout.print(structH.fullName + "{" + members.map("o" + _.allocId.num).mkString(", ") + "}") + vivemDout.print(structH.id + "{" + members.map("o" + _.allocId.num).mkString(", ") + "}") } case ArrayInstanceV(typeH, memberTypeH, capacity, elements) => vivemDout.print("array:" + capacity + ":" + memberTypeH + "{" + elements.map("o" + _.allocId.num).mkString(", ") + "}") } @@ -648,7 +652,21 @@ class Heap(in_vivemDout: PrintStream) { } else { vassert(containsLiveObject(actualReference.allocId)) } - if (actualReference.seenAsCoord.hamut != expectedType) { + if ((actualReference.seenAsCoord.hamut.ownership match { + case ImmutableShareH => MutableShareH + case ImmutableBorrowH => MutableBorrowH + case other => other + }) != (expectedType.ownership match { + case ImmutableShareH => MutableShareH + case ImmutableBorrowH => MutableBorrowH + case other => other + })) { + vfail("Expected " + expectedType + " but was " + actualReference.seenAsCoord.hamut) + } + if (actualReference.seenAsCoord.hamut.location != expectedType.location) { + vfail("Expected " + expectedType + " but was " + actualReference.seenAsCoord.hamut) + } + if (actualReference.seenAsCoord.hamut.kind != expectedType.kind) { vfail("Expected " + expectedType + " but was " + actualReference.seenAsCoord.hamut) } val actualKind = dereference(actualReference, actualReference.ownership == WeakH) @@ -769,7 +787,7 @@ class Heap(in_vivemDout: PrintStream) { case StructInstanceV(structH, Some(members)) => { vassert(members.size == structH.members.size) von.VonObject( - structH.fullName.toString, + structH.id.toString, None, structH.members.zip(members).zipWithIndex.map({ case ((memberH, memberV), index) => VonMember(vimpl(memberH.name.toString), toVon(memberV)) diff --git a/Frontend/TestVM/src/dev/vale/testvm/Values.scala b/Frontend/TestVM/src/dev/vale/testvm/Values.scala index 21a90eb0e..27fccd7e3 100644 --- a/Frontend/TestVM/src/dev/vale/testvm/Values.scala +++ b/Frontend/TestVM/src/dev/vale/testvm/Values.scala @@ -257,8 +257,8 @@ case class ElementAddressV(arrayId: AllocationId, elementIndex: Long) { // Used in tracking reference counts/maps. case class CallId(callDepth: Int, function: PrototypeH) { - override def toString: String = "ƒ" + callDepth + "/" + (function.fullName.shortenedName) - override def hashCode(): Int = callDepth + function.fullName.shortenedName.hashCode + override def toString: String = "ƒ" + callDepth + "/" + (function.id.shortenedName) + override def hashCode(): Int = callDepth + function.id.shortenedName.hashCode } //case class RegisterId(blockId: BlockId, lineInBlock: Int) { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; } case class ArgumentId(callId: CallId, index: Int) { val hash = runtime.ScalaRunTime._hashCode(this); override def hashCode(): Int = hash; } diff --git a/Frontend/TestVM/src/dev/vale/testvm/Vivem.scala b/Frontend/TestVM/src/dev/vale/testvm/Vivem.scala index e5e4dc1a9..b838edd68 100644 --- a/Frontend/TestVM/src/dev/vale/testvm/Vivem.scala +++ b/Frontend/TestVM/src/dev/vale/testvm/Vivem.scala @@ -1,6 +1,6 @@ package dev.vale.testvm -import dev.vale.finalast.{InlineH, ProgramH, ShareH} +import dev.vale.finalast._ import dev.vale.{Result, vassert, vassertSome, vcurious, vfail, vpass} import java.io.PrintStream @@ -28,7 +28,7 @@ object Vivem { val heap = new Heap(vivemDout) val argReferences = externalArgumentKinds.map(argKind => { - heap.add(ShareH, InlineH, argKind); + heap.add(MutableShareH, InlineH, argKind); }); innerExecute(programH, argReferences, heap, vivemDout, stdin, stdout) } diff --git a/Frontend/TestVM/src/dev/vale/testvm/VivemExterns.scala b/Frontend/TestVM/src/dev/vale/testvm/VivemExterns.scala index 61dbf16b4..9082a2205 100644 --- a/Frontend/TestVM/src/dev/vale/testvm/VivemExterns.scala +++ b/Frontend/TestVM/src/dev/vale/testvm/VivemExterns.scala @@ -1,10 +1,9 @@ package dev.vale.testvm -import dev.vale.finalast.{InlineH, ShareH, YonderH} +import dev.vale.finalast._ import dev.vale.{vassert, vfail} import java.lang.ArithmeticException -import dev.vale.finalast.YonderH import dev.vale.vfail object VivemExterns { @@ -19,7 +18,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (FloatV(aValue), FloatV(bValue)) => { - memory.addAllocationForReturn(ShareH, InlineH, FloatV(aValue + bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, FloatV(aValue + bValue)) } } } @@ -30,7 +29,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (FloatV(aValue), FloatV(bValue)) => { - memory.addAllocationForReturn(ShareH, InlineH, FloatV(aValue * bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, FloatV(aValue * bValue)) } } } @@ -41,7 +40,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (FloatV(aValue), FloatV(bValue)) => { - memory.addAllocationForReturn(ShareH, InlineH, FloatV(aValue / bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, FloatV(aValue / bValue)) } } } @@ -52,7 +51,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (FloatV(aValue), FloatV(bValue)) => { - memory.addAllocationForReturn(ShareH, InlineH, FloatV(aValue - bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, FloatV(aValue - bValue)) } } } @@ -65,14 +64,14 @@ object VivemExterns { val StrV(bStr) = memory.dereference(args(3)) val IntV(bBegin, 32) = memory.dereference(args(4)) val IntV(bLength, 32) = memory.dereference(args(5)) - memory.addAllocationForReturn(ShareH, YonderH, StrV(aStr.substring(aBegin.toInt, aBegin.toInt + aLength.toInt) + bStr.substring(bBegin.toInt, bBegin.toInt + bLength.toInt))) + memory.addAllocationForReturn(MutableShareH, YonderH, StrV(aStr.substring(aBegin.toInt, aBegin.toInt + aLength.toInt) + bStr.substring(bBegin.toInt, bBegin.toInt + bLength.toInt))) } def getch(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { vassert(args.isEmpty) val next = memory.stdin() val code = if (next.isEmpty) { 0 } else { next.charAt(0).charValue().toInt } - memory.addAllocationForReturn(ShareH, InlineH, IntV(code, 32)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(code, 32)) } def lessThanFloat(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { @@ -81,7 +80,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (FloatV(aValue), FloatV(bValue)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue < bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue < bValue)) } } } @@ -92,7 +91,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (FloatV(aValue), FloatV(bValue)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue > bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue > bValue)) } } } @@ -103,7 +102,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (FloatV(aValue), FloatV(bValue)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue == bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue == bValue)) } } } @@ -117,7 +116,7 @@ object VivemExterns { val IntV(rightStrStart, 32) = memory.dereference(args(4)) val IntV(rightStrLen, 32) = memory.dereference(args(5)) val result = BoolV(leftStr.slice(leftStrStart.toInt, leftStrLen.toInt) == rightStr.slice(rightStrStart.toInt, rightStrLen.toInt)) - memory.addAllocationForReturn(ShareH, InlineH, result) + memory.addAllocationForReturn(MutableShareH, InlineH, result) } def eqBoolBool(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { @@ -126,7 +125,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (BoolV(aValue), BoolV(bValue)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue == bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue == bValue)) } } } @@ -137,7 +136,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (BoolV(aValue), BoolV(bValue)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue && bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue && bValue)) } } } @@ -148,7 +147,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (BoolV(aValue), BoolV(bValue)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue || bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue || bValue)) } } } @@ -156,31 +155,31 @@ object VivemExterns { def not(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { vassert(args.size == 1) val BoolV(value) = memory.dereference(args(0)) - memory.addAllocationForReturn(ShareH, InlineH, BoolV(!value)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(!value)) } def sqrt(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { vassert(args.size == 1) val FloatV(value) = memory.dereference(args(0)) - memory.addAllocationForReturn(ShareH, InlineH, FloatV(Math.sqrt(value).toFloat)) + memory.addAllocationForReturn(MutableShareH, InlineH, FloatV(Math.sqrt(value).toFloat)) } def strLength(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { vassert(args.size == 1) val StrV(value) = memory.dereference(args(0)) - memory.addAllocationForReturn(ShareH, InlineH, IntV(value.length, 32)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(value.length, 32)) } def castFloatStr(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { vassert(args.size == 1) val FloatV(value) = memory.dereference(args(0)) - memory.addAllocationForReturn(ShareH, YonderH, StrV(value.toString)) + memory.addAllocationForReturn(MutableShareH, YonderH, StrV(value.toString)) } def negateFloat(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { vassert(args.size == 1) val FloatV(value) = memory.dereference(args(0)) - memory.addAllocationForReturn(ShareH, InlineH, FloatV(-value)) + memory.addAllocationForReturn(MutableShareH, InlineH, FloatV(-value)) } def print(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { @@ -198,7 +197,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 32), IntV(bValue, 32)) => { - memory.addAllocationForReturn(ShareH, InlineH, IntV(aValue.toInt + bValue.toInt, 32)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(aValue.toInt + bValue.toInt, 32)) } } } @@ -209,7 +208,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 32), IntV(bValue, 32)) => { - memory.addAllocationForReturn(ShareH, InlineH, IntV(aValue.toInt * bValue.toInt, 32)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(aValue.toInt * bValue.toInt, 32)) } } } @@ -220,7 +219,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 32), IntV(bValue, 32)) => { - memory.addAllocationForReturn(ShareH, InlineH, IntV(aValue.toInt / bValue.toInt, 32)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(aValue.toInt / bValue.toInt, 32)) } } } @@ -232,7 +231,7 @@ object VivemExterns { (aKind, bKind) match { case (IntV(aValue, 32), IntV(bValue, 32)) => { try { - memory.addAllocationForReturn(ShareH, InlineH, IntV(aValue.toInt % bValue.toInt, 32)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(aValue.toInt % bValue.toInt, 32)) } catch { case _ : ArithmeticException => vfail() } @@ -246,7 +245,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 32), IntV(bValue, 32)) => { - memory.addAllocationForReturn(ShareH, InlineH, IntV(aValue.toInt - bValue.toInt, 32)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(aValue.toInt - bValue.toInt, 32)) } } } @@ -257,7 +256,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 32), IntV(bValue, 32)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue < bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue < bValue)) } } } @@ -268,7 +267,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 32), IntV(bValue, 32)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue <= bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue <= bValue)) } } } @@ -279,7 +278,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 32), IntV(bValue, 32)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue > bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue > bValue)) } } } @@ -290,7 +289,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 32), IntV(bValue, 32)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue >= bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue >= bValue)) } } } @@ -301,7 +300,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 32), IntV(bValue, 32)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue == bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue == bValue)) } } } @@ -309,19 +308,19 @@ object VivemExterns { def castI32Str(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { vassert(args.size == 1) val IntV(value, 32) = memory.dereference(args(0)) - memory.addAllocationForReturn(ShareH, YonderH, StrV(value.toString)) + memory.addAllocationForReturn(MutableShareH, YonderH, StrV(value.toString)) } def castFloatI32(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { vassert(args.size == 1) val FloatV(value) = memory.dereference(args(0)) - memory.addAllocationForReturn(ShareH, InlineH, IntV(value.toInt, 32)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(value.toInt, 32)) } def castI32Float(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { vassert(args.size == 1) val IntV(value, 32) = memory.dereference(args(0)) - memory.addAllocationForReturn(ShareH, InlineH, FloatV(value.toFloat)) + memory.addAllocationForReturn(MutableShareH, InlineH, FloatV(value.toFloat)) } def addI64(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { @@ -330,7 +329,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 64), IntV(bValue, 64)) => { - memory.addAllocationForReturn(ShareH, InlineH, IntV(aValue + bValue, 64)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(aValue + bValue, 64)) } } } @@ -341,7 +340,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 64), IntV(bValue, 64)) => { - memory.addAllocationForReturn(ShareH, InlineH, IntV(aValue * bValue, 64)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(aValue * bValue, 64)) } } } @@ -352,7 +351,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 64), IntV(bValue, 64)) => { - memory.addAllocationForReturn(ShareH, InlineH, IntV(aValue / bValue, 64)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(aValue / bValue, 64)) } } } @@ -361,7 +360,7 @@ object VivemExterns { vassert(args.size == 1) val IntV(value, 64) = memory.dereference(args(0)) val result = value & 0xFFFFFFFFL - memory.addAllocationForReturn(ShareH, InlineH, IntV(result, 32)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(result, 32)) } def modI64(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { @@ -371,7 +370,7 @@ object VivemExterns { (aKind, bKind) match { case (IntV(aValue, 64), IntV(bValue, 64)) => { try { - memory.addAllocationForReturn(ShareH, InlineH, IntV(aValue % bValue, 64)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(aValue % bValue, 64)) } catch { case _ : ArithmeticException => vfail() } @@ -385,7 +384,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 64), IntV(bValue, 64)) => { - memory.addAllocationForReturn(ShareH, InlineH, IntV(aValue - bValue, 64)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(aValue - bValue, 64)) } } } @@ -396,7 +395,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 64), IntV(bValue, 64)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue < bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue < bValue)) } } } @@ -407,7 +406,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 64), IntV(bValue, 64)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue <= bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue <= bValue)) } } } @@ -418,7 +417,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 64), IntV(bValue, 64)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue > bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue > bValue)) } } } @@ -429,7 +428,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 64), IntV(bValue, 64)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue >= bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue >= bValue)) } } } @@ -440,7 +439,7 @@ object VivemExterns { val bKind = memory.dereference(args(1)) (aKind, bKind) match { case (IntV(aValue, 64), IntV(bValue, 64)) => { - memory.addAllocationForReturn(ShareH, InlineH, BoolV(aValue == bValue)) + memory.addAllocationForReturn(MutableShareH, InlineH, BoolV(aValue == bValue)) } } } @@ -448,18 +447,18 @@ object VivemExterns { def castI64Str(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { vassert(args.size == 1) val IntV(value, 64) = memory.dereference(args(0)) - memory.addAllocationForReturn(ShareH, YonderH, StrV(value.toString)) + memory.addAllocationForReturn(MutableShareH, YonderH, StrV(value.toString)) } def castFloatI64(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { vassert(args.size == 1) val FloatV(value) = memory.dereference(args(0)) - memory.addAllocationForReturn(ShareH, InlineH, IntV(value.toInt, 64)) + memory.addAllocationForReturn(MutableShareH, InlineH, IntV(value.toInt, 64)) } def castI64Float(memory: AdapterForExterns, args: Vector[ReferenceV]): ReferenceV = { vassert(args.size == 1) val IntV(value, 64) = memory.dereference(args(0)) - memory.addAllocationForReturn(ShareH, InlineH, FloatV(value.toFloat)) + memory.addAllocationForReturn(MutableShareH, InlineH, FloatV(value.toFloat)) } } diff --git a/Frontend/TestVM/test/dev/vale/testvm/VivemTests.scala b/Frontend/TestVM/test/dev/vale/testvm/VivemTests.scala index 86321bbbc..79e59428c 100644 --- a/Frontend/TestVM/test/dev/vale/testvm/VivemTests.scala +++ b/Frontend/TestVM/test/dev/vale/testvm/VivemTests.scala @@ -1,7 +1,7 @@ package dev.vale.testvm import dev.vale.{Interner, Keywords, PackageCoordinate, PackageCoordinateMap, StrI, finalast} -import dev.vale.finalast.{BlockH, CallH, ConstantIntH, IdH, FunctionH, InlineH, IntHT, PackageH, ProgramH, PrototypeH, CoordH, ShareH, UserFunctionH} +import dev.vale.finalast._ import dev.vale.finalast._ import dev.vale.von.{VonArray, VonInt, VonMember, VonObject, VonStr} import org.scalatest.{FunSuite, Matchers} @@ -18,7 +18,7 @@ class VivemTests extends FunSuite with Matchers { PackageCoordinate.TEST_TLD(interner, keywords), "main", "main"), - Vector.empty,CoordH(ShareH,InlineH,IntHT.i32)), + Vector.empty,CoordH(MutableShareH,InlineH,IntHT.i32)), true, false, Vector(UserFunctionH), @@ -45,8 +45,8 @@ class VivemTests extends FunSuite with Matchers { PackageCoordinate.BUILTIN(interner, keywords), "__vbi_addI32(i32, i32)", "__vbi_addI32(i32, i32)"), - Vector(CoordH(ShareH,InlineH,IntHT.i32), CoordH(ShareH,InlineH,IntHT.i32)), - CoordH(ShareH,InlineH,IntHT.i32)) + Vector(CoordH(MutableShareH,InlineH,IntHT.i32), CoordH(MutableShareH,InlineH,IntHT.i32)), + CoordH(MutableShareH,InlineH,IntHT.i32)) val main = FunctionH( PrototypeH( @@ -55,7 +55,7 @@ class VivemTests extends FunSuite with Matchers { PackageCoordinate.TEST_TLD(interner, keywords), "main", "main"), - Vector.empty,CoordH(finalast.ShareH,InlineH,IntHT.i32)), + Vector.empty,CoordH(MutableShareH,InlineH,IntHT.i32)), true, false, Vector(UserFunctionH), @@ -75,7 +75,11 @@ class VivemTests extends FunSuite with Matchers { false, true, Vector.empty, - BlockH(ConstantIntH(133337, 32))) + ExternCallH( + addPrototype, + Vector( + ArgumentH(CoordH(MutableShareH,InlineH,IntHT.i32), 0), + ArgumentH(CoordH(MutableShareH,InlineH,IntHT.i32), 1)))) val packages = new PackageCoordinateMap[PackageH]() packages.put(PackageCoordinate.BUILTIN(interner, keywords), PackageH(Vector.empty, Vector.empty, Vector(addExtern), Vector.empty, Vector.empty, Map(), Map(), Map(interner.intern(StrI("__vbi_addI32")) -> addPrototype), Map())) diff --git a/Frontend/Tests/test/main/resources/panicutils/panicutils.vale b/Frontend/Tests/test/main/resources/panicutils/panicutils.vale index d5c746269..090ebfc30 100644 --- a/Frontend/Tests/test/main/resources/panicutils/panicutils.vale +++ b/Frontend/Tests/test/main/resources/panicutils/panicutils.vale @@ -1,4 +1,5 @@ import printutils.*; +import v.builtins.panicutils.*; import v.builtins.logic.*; func __pretend() T { __vbi_panic() } diff --git a/Frontend/TypingPass/src/dev/vale/typing/ArrayCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/ArrayCompiler.scala index ebd98e7a7..0b5f9fc7a 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/ArrayCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/ArrayCompiler.scala @@ -580,7 +580,7 @@ class ArrayCompiler( case PlaceholderTemplataT(_, _) => FinalT case VariabilityTemplataT(variability) => variability } - StaticSizedArrayLookupTE(range, containerExpr2, at, indexExpr2, variability) + StaticSizedArrayLookupTE(range, containerExpr2, at, indexExpr2, memberType, variability) } def lookupInUnknownSizedArray( diff --git a/Frontend/TypingPass/src/dev/vale/typing/Compilation.scala b/Frontend/TypingPass/src/dev/vale/typing/Compilation.scala index 5a6a67a5c..7f6855243 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/Compilation.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/Compilation.scala @@ -28,7 +28,7 @@ class TypingPassCompilation( var higherTypingCompilation = new HigherTypingCompilation( options.globalOptions, interner, keywords, packagesToBuild, packageToContentsResolver) - var hinputsCache: Option[Hinputs] = None + var hinputsCache: Option[HinputsT] = None def getCodeMap(): Result[FileCoordinateMap[String], FailedParse] = higherTypingCompilation.getCodeMap() def getParseds(): Result[FileCoordinateMap[(FileP, Vector[RangeL])], FailedParse] = higherTypingCompilation.getParseds() @@ -37,7 +37,7 @@ class TypingPassCompilation( def getAstrouts(): Result[PackageCoordinateMap[ProgramA], ICompileErrorA] = higherTypingCompilation.getAstrouts() - def getCompilerOutputs(): Result[Hinputs, ICompileErrorT] = { + def getCompilerOutputs(): Result[HinputsT, ICompileErrorT] = { hinputsCache match { case Some(coutputs) => Ok(coutputs) case None => { @@ -57,7 +57,7 @@ class TypingPassCompilation( } } - def expectCompilerOutputs(): Hinputs = { + def expectCompilerOutputs(): HinputsT = { getCompilerOutputs() match { case Err(err) => { diff --git a/Frontend/TypingPass/src/dev/vale/typing/Compiler.scala b/Frontend/TypingPass/src/dev/vale/typing/Compiler.scala index 11f3a6447..1670cca37 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/Compiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/Compiler.scala @@ -704,7 +704,7 @@ class Compiler( opts, interner, keywords, nameTranslator, overloadResolver, structCompiler, structConstructorMacro, structDropMacro) - def evaluate(packageToProgramA: PackageCoordinateMap[ProgramA]): Result[Hinputs, ICompileErrorT] = { + def evaluate(packageToProgramA: PackageCoordinateMap[ProgramA]): Result[HinputsT, ICompileErrorT] = { try { Profiler.frame(() => { val nameToStructDefinedMacro = @@ -1285,7 +1285,7 @@ class Compiler( // val reachableImmKindToDestructor = reachableImmKinds.zip(reachableImmKinds.map(coutputs.findImmDestructor)).toMap val hinputs = - vale.typing.Hinputs( + vale.typing.HinputsT( reachableInterfaces.toVector, reachableStructs.toVector, reachableFunctions.toVector, diff --git a/Frontend/TypingPass/src/dev/vale/typing/Hinputs.scala b/Frontend/TypingPass/src/dev/vale/typing/HinputsT.scala similarity index 99% rename from Frontend/TypingPass/src/dev/vale/typing/Hinputs.scala rename to Frontend/TypingPass/src/dev/vale/typing/HinputsT.scala index b71ad74d1..7807a10b1 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/Hinputs.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/HinputsT.scala @@ -16,7 +16,7 @@ case class InstantiationBoundArgumentsT( runeToFunctionBoundArg: Map[IRuneS, PrototypeT], runeToImplBoundArg: Map[IRuneS, IdT[IImplNameT]]) -case class Hinputs( +case class HinputsT( interfaces: Vector[InterfaceDefinitionT], structs: Vector[StructDefinitionT], // emptyPackStructRef: StructTT, diff --git a/Frontend/TypingPass/src/dev/vale/typing/TemplataCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/TemplataCompiler.scala index 6e3a521c8..12b2c8fd0 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/TemplataCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/TemplataCompiler.scala @@ -4,7 +4,7 @@ import dev.vale.{CodeLocationS, Err, Interner, Keywords, Ok, RangeS, Result, vas import dev.vale.postparsing.rules.{EqualsSR, IRulexSR, RuneUsage} import dev.vale.postparsing._ import dev.vale.typing.env.{FunctionEnvironmentT, GeneralEnvironmentT, IEnvironmentT, IInDenizenEnvironmentT, TemplataEnvEntry, TemplataLookupContext, TemplatasStore} -import dev.vale.typing.names.{AnonymousSubstructNameT, CitizenNameT, ExportNameT, ExportTemplateNameT, FunctionBoundNameT, FunctionNameT, FunctionTemplateNameT, ICitizenNameT, ICitizenTemplateNameT, IFunctionNameT, IFunctionTemplateNameT, IImplNameT, IImplTemplateNameT, IInstantiationNameT, IInterfaceNameT, IInterfaceTemplateNameT, INameT, IStructNameT, IStructTemplateNameT, ISubKindNameT, ISubKindTemplateNameT, ISuperKindNameT, ISuperKindTemplateNameT, ITemplateNameT, IdT, ImplBoundNameT, ImplNameT, InterfaceNameT, InterfaceTemplateNameT, KindPlaceholderNameT, KindPlaceholderTemplateNameT, LambdaCitizenNameT, LambdaCitizenTemplateNameT, NameTranslator, RawArrayNameT, RuneNameT, RuntimeSizedArrayNameT, StaticSizedArrayNameT, StructNameT, StructTemplateNameT} +import dev.vale.typing.names.{AnonymousSubstructNameT, CitizenNameT, ExportNameT, ExportTemplateNameT, ExternNameT, ExternTemplateNameT, FunctionBoundNameT, FunctionNameT, FunctionTemplateNameT, ICitizenNameT, ICitizenTemplateNameT, IFunctionNameT, IFunctionTemplateNameT, IImplNameT, IImplTemplateNameT, IInstantiationNameT, IInterfaceNameT, IInterfaceTemplateNameT, INameT, IPlaceholderNameT, IStructNameT, IStructTemplateNameT, ISubKindNameT, ISubKindTemplateNameT, ISuperKindNameT, ISuperKindTemplateNameT, ITemplateNameT, IdT, ImplBoundNameT, ImplNameT, InterfaceNameT, InterfaceTemplateNameT, KindPlaceholderNameT, KindPlaceholderTemplateNameT, LambdaCitizenNameT, LambdaCitizenTemplateNameT, NameTranslator, RawArrayNameT, RuneNameT, RuntimeSizedArrayNameT, StaticSizedArrayNameT, StructNameT, StructTemplateNameT} import dev.vale.typing.templata._ import dev.vale.typing.types._ import dev.vale.highertyping._ @@ -94,7 +94,7 @@ object TemplataCompiler { IdT(id.packageCoord, initSteps, lastStep) } - def getPlaceholderTemplataId(implPlaceholder: ITemplataT[ITemplataType]) = { + def getPlaceholderTemplataId(implPlaceholder: ITemplataT[ITemplataType]): IdT[IPlaceholderNameT] = { implPlaceholder match { case PlaceholderTemplataT(n, _) => n case KindTemplataT(KindPlaceholderT(n)) => n @@ -213,6 +213,14 @@ object TemplataCompiler { last.template) } + def getExternTemplate(id: IdT[ExternNameT]): IdT[ExternTemplateNameT] = { + val IdT(packageCoord, initSteps, last) = id + IdT( + packageCoord, + initSteps, //.map(getNameTemplate), // See GLIOGN for why we map the initSteps names too + last.template) + } + def getImplTemplate(id: IdT[IImplNameT]): IdT[IImplTemplateNameT] = { val IdT(packageCoord, initSteps, last) = id IdT( diff --git a/Frontend/TypingPass/src/dev/vale/typing/ast/expressions.scala b/Frontend/TypingPass/src/dev/vale/typing/ast/expressions.scala index 6f3bec33d..bb22188eb 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/ast/expressions.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/ast/expressions.scala @@ -466,13 +466,17 @@ case class StaticSizedArrayLookupTE( arrayExpr: ReferenceExpressionTE, arrayType: StaticSizedArrayTT, indexExpr: ReferenceExpressionTE, + // See RMLRMO for why this is the same ownership as the original field. + elementType: CoordT, // See RMLRMO for why we dont have a targetOwnership field here. variability: VariabilityT ) extends AddressExpressionTE { override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() - vassert(arrayExpr.result.coord.kind == arrayType) - override def result = AddressResultT(arrayType.elementType) + override def result = { + // See RMLRMO why we just return the element type. + AddressResultT(elementType) + } } case class RuntimeSizedArrayLookupTE( @@ -487,8 +491,8 @@ case class RuntimeSizedArrayLookupTE( vassert(arrayExpr.result.coord.kind == arrayType) override def result = { - val CoordT(ownership, _, kind) = arrayType.elementType - AddressResultT(CoordT(ownership, GlobalRegionT(), kind)) + // See RMLRMO why we just return the element type. + AddressResultT(arrayType.elementType) } } @@ -501,6 +505,9 @@ case class ReferenceMemberLookupTE( range: RangeS, structExpr: ReferenceExpressionTE, memberName: IVarNameT, + // We include this so the instantiator doesn't have to translate the entire struct definition to + // figure out what type it's pulling out. + // See RMLRMO for why this is the same ownership as the original field. memberReference: CoordT, // See RMLRMO for why we dont have a targetOwnership field here. variability: VariabilityT) extends AddressExpressionTE { diff --git a/Frontend/TypingPass/src/dev/vale/typing/expression/ExpressionCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/expression/ExpressionCompiler.scala index bf79a8a3f..040a21fce 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/expression/ExpressionCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/expression/ExpressionCompiler.scala @@ -666,7 +666,7 @@ class ExpressionCompiler( case RuntimeSizedArrayLookupTE(range, arrayExpr, arrayType, _, _) => { throw CompileErrorExceptionT(CantMutateFinalElement(range :: parentRanges, arrayExpr.result.coord)) } - case StaticSizedArrayLookupTE(range, arrayExpr, arrayType, _, _) => { + case StaticSizedArrayLookupTE(range, arrayExpr, arrayType, _, _, _) => { throw CompileErrorExceptionT(CantMutateFinalElement(range :: parentRanges, arrayExpr.result.coord)) } case x => vimpl(x.toString) diff --git a/Frontend/TypingPass/src/dev/vale/typing/expression/LocalHelper.scala b/Frontend/TypingPass/src/dev/vale/typing/expression/LocalHelper.scala index 9f00b454e..3a9d84f0f 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/expression/LocalHelper.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/expression/LocalHelper.scala @@ -159,7 +159,7 @@ class LocalHelper( } // See CSHROOR for why these aren't just Readwrite. case l @ RuntimeSizedArrayLookupTE(_, _, _, _, _) => SoftLoadTE(l, BorrowT) - case l @ StaticSizedArrayLookupTE(_, _, _, _, _) => SoftLoadTE(l, BorrowT) + case l @ StaticSizedArrayLookupTE(_, _, _, _, _, _) => SoftLoadTE(l, BorrowT) case l @ ReferenceMemberLookupTE(_,_, _, _, _) => SoftLoadTE(l, BorrowT) case l @ AddressMemberLookupTE(_, _, _, _, _) => SoftLoadTE(l, BorrowT) } diff --git a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerCore.scala b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerCore.scala index b261ac0b4..2d4a33d87 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerCore.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerCore.scala @@ -1,14 +1,14 @@ package dev.vale.typing.function import dev.vale.highertyping.FunctionA -import dev.vale.{Err, Interner, Keywords, Ok, Profiler, RangeS, vassert, vassertOne, vassertSome, vcheck, vcurious, vfail, vimpl, vwat} +import dev.vale.{Err, Interner, Keywords, Ok, Profiler, RangeS, U, vassert, vassertOne, vassertSome, vcheck, vcurious, vfail, vimpl, vwat} import dev.vale.postparsing._ import dev.vale.postparsing.patterns.AtomSP import dev.vale.typing.{CompileErrorExceptionT, CompilerOutputs, ConvertHelper, DeferredEvaluatingFunctionBody, RangedInternalErrorT, TemplataCompiler, TypingPassOptions, ast} -import dev.vale.typing.ast.{ArgLookupTE, ExternFunctionCallTE, ExternT, FunctionHeaderT, FunctionDefinitionT, IFunctionAttributeT, LocationInFunctionEnvironmentT, ParameterT, PrototypeT, PureT, ReferenceExpressionTE, ReturnTE, SignatureT, UserFunctionT} +import dev.vale.typing.ast.{ArgLookupTE, ExternFunctionCallTE, ExternT, FunctionDefinitionT, FunctionHeaderT, IFunctionAttributeT, LocationInFunctionEnvironmentT, ParameterT, PrototypeT, PureT, ReferenceExpressionTE, ReturnTE, SignatureT, UserFunctionT} import dev.vale.typing.env._ import dev.vale.typing.expression.CallCompiler -import dev.vale.typing.names.{ExternFunctionNameT, IdT, FunctionNameT, FunctionTemplateNameT, IFunctionNameT, NameTranslator, RuneNameT} +import dev.vale.typing.names.{ExternFunctionNameT, FunctionNameT, FunctionTemplateNameT, IFunctionNameT, IdT, NameTranslator, RuneNameT} import dev.vale.typing.templata.CoordTemplataT import dev.vale.typing.types._ import dev.vale.highertyping._ @@ -381,10 +381,10 @@ class FunctionCompilerCore( } def translateFunctionAttributes(a: Vector[IFunctionAttributeS]): Vector[IFunctionAttributeT] = { - a.map({ + U.map[IFunctionAttributeS, IFunctionAttributeT](a, { case UserFunctionS => UserFunctionT case ExternS(packageCoord) => ExternT(packageCoord) - case x => vimpl(x.toString) + case x => vimpl(x) }) } diff --git a/Frontend/TypingPass/test/dev/vale/typing/AfterRegionsErrorTests.scala b/Frontend/TypingPass/test/dev/vale/typing/AfterRegionsErrorTests.scala index 47aa0de30..8c10ada12 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/AfterRegionsErrorTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/AfterRegionsErrorTests.scala @@ -17,7 +17,7 @@ class AfterRegionsErrorTests extends FunSuite with Matchers { val compile = CompilerTestCompilation.test( """ |import printutils.*; - |import v.builtins.panic.*; + |import v.builtins.panicutils.*; | |#!DeriveInterfaceDrop |sealed interface Opt where T Ref { } diff --git a/Frontend/TypingPass/test/dev/vale/typing/CompilerMutateTests.scala b/Frontend/TypingPass/test/dev/vale/typing/CompilerMutateTests.scala index b671c8b46..603539d9b 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/CompilerMutateTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/CompilerMutateTests.scala @@ -167,7 +167,6 @@ class CompilerMutateTests extends FunSuite with Matchers { """ |import v.builtins.arrays.*; |import v.builtins.drop.*; - |import v.builtins.panic.*; | |exported func main() int { | arr = #[#10]({_}); @@ -220,7 +219,6 @@ class CompilerMutateTests extends FunSuite with Matchers { """ |import v.builtins.arrays.*; |import v.builtins.drop.*; - |import v.builtins.panic.*; | |exported func main() int { | arr = Array(3); diff --git a/Frontend/TypingPass/test/dev/vale/typing/CompilerSolverTests.scala b/Frontend/TypingPass/test/dev/vale/typing/CompilerSolverTests.scala index c617ac811..5aab6bf2c 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/CompilerSolverTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/CompilerSolverTests.scala @@ -217,9 +217,9 @@ class CompilerSolverTests extends FunSuite with Matchers { val unrelatedKind = StructTT(IdT(testPackageCoord, Vector(), StructNameT(StructTemplateNameT(StrI("Spoon")), Vector()))) val unrelatedCoord = CoordT(OwnT,region,unrelatedKind) val fireflySignature = SignatureT(IdT(testPackageCoord, Vector(), interner.intern(FunctionNameT(interner.intern(FunctionTemplateNameT(interner.intern(StrI("myFunc")), tz.head.begin)), Vector(), Vector(fireflyCoord))))) - val fireflyExportId = IdT(testPackageCoord, Vector(), interner.intern(ExportNameT(ExportTemplateNameT(tz.head.begin)))) + val fireflyExportId = IdT(testPackageCoord, Vector(), interner.intern(ExportNameT(interner.intern(ExportTemplateNameT(tz.head.begin))))) val fireflyExport = KindExportT(tz.head, fireflyKind, fireflyExportId, interner.intern(StrI("Firefly"))); - val serenityExportId = IdT(testPackageCoord, Vector(), interner.intern(ExportNameT(ExportTemplateNameT(tz.head.begin)))) + val serenityExportId = IdT(testPackageCoord, Vector(), interner.intern(ExportNameT(interner.intern(ExportTemplateNameT(tz.head.begin))))) val serenityExport = KindExportT(tz.head, fireflyKind, serenityExportId, interner.intern(StrI("Serenity"))); val codeStr = "Hello I am A large piece Of code [that has An error]" diff --git a/Frontend/TypingPass/test/dev/vale/typing/CompilerTests.scala b/Frontend/TypingPass/test/dev/vale/typing/CompilerTests.scala index cdf7467e7..2ffad352f 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/CompilerTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/CompilerTests.scala @@ -913,7 +913,6 @@ class CompilerTests extends FunSuite with Matchers { |import v.builtins.arrays.*; |import v.builtins.functor1.*; |import v.builtins.drop.*; - |import v.builtins.panic.*; | |struct Vec2 imm { | x float; @@ -932,7 +931,7 @@ class CompilerTests extends FunSuite with Matchers { val compile = CompilerTestCompilation.test( """ - |import v.builtins.panic.*; + |import v.builtins.panicutils.*; | |exported struct Moo {} |exported func main() Moo { @@ -1003,7 +1002,6 @@ class CompilerTests extends FunSuite with Matchers { test("Reports when exported function depends on non-exported return") { val compile = CompilerTestCompilation.test( """ - |import v.builtins.panic.*; |import panicutils.*; |struct Firefly { } |exported func moo() &Firefly { __pretend<&Firefly>() } @@ -1217,9 +1215,9 @@ class CompilerTests extends FunSuite with Matchers { val unrelatedCoord = CoordT(OwnT,region,unrelatedKind) val fireflyTemplateName = IdT(testPackageCoord, Vector(), interner.intern(FunctionTemplateNameT(interner.intern(StrI("myFunc")), tz.head.begin))) val fireflySignature = ast.SignatureT(IdT(testPackageCoord, Vector(), interner.intern(FunctionNameT(interner.intern(FunctionTemplateNameT(interner.intern(StrI("myFunc")), tz.head.begin)), Vector(), Vector(fireflyCoord))))) - val fireflyExportId = IdT(testPackageCoord, Vector(), interner.intern(ExportNameT(ExportTemplateNameT(tz.head.begin)))) + val fireflyExportId = IdT(testPackageCoord, Vector(), interner.intern(ExportNameT(interner.intern(ExportTemplateNameT(tz.head.begin))))) val fireflyExport = KindExportT(tz.head, fireflyKind, fireflyExportId, interner.intern(StrI("Firefly"))); - val serenityExportId = IdT(testPackageCoord, Vector(), interner.intern(ExportNameT(ExportTemplateNameT(tz.head.begin)))) + val serenityExportId = IdT(testPackageCoord, Vector(), interner.intern(ExportNameT(interner.intern(ExportTemplateNameT(tz.head.begin))))) val serenityExport = KindExportT(tz.head, fireflyKind, serenityExportId, interner.intern(StrI("Serenity"))); val filenamesAndSources = FileCoordinateMap.test(interner, "blah blah blah\nblah blah blah") @@ -1433,7 +1431,7 @@ class CompilerTests extends FunSuite with Matchers { test("Tests stamping a struct and its implemented interface from a function param") { val compile = CompilerTestCompilation.test( """ - |import v.builtins.panic.*; + |import v.builtins.panicutils.*; |import v.builtins.drop.*; |import panicutils.*; |sealed interface MyOption where func drop(T)void { } @@ -1697,7 +1695,6 @@ class CompilerTests extends FunSuite with Matchers { test("Test MakeArray") { val compile = CompilerTestCompilation.test( """ - |import v.builtins.panic.*; |import v.builtins.arith.*; |import array.make.*; |import v.builtins.arrays.*; diff --git a/docs/Generics.md b/docs/Generics.md index 46437144f..340724d09 100644 --- a/docs/Generics.md +++ b/docs/Generics.md @@ -799,7 +799,7 @@ Note how `{genFunc$0}` is still there, even in an instantiation name. See DMPOGN These all might be completely different functions, depending on what happened inside the body, what kind of metaprogramming it does, etc. -Now the challenge: What is `mvtest/genFunc.lam:2:6.__call{int}`'s original generic's name? We have to be careful because these look very similar: +Now the challenge: What is `mvtest/genFunc.lam:2:6.__call{int}`'s original generic's name? (Note from later: I think this challenge is because we need to know the original generic so we know what to start instantiating.) We have to be careful because these look very similar: * `mvtest/genFunc.lam:2:6.__call{genFunc$0}` * `mvtest/genFunc.lam:2:6.__call{int}` @@ -811,6 +811,7 @@ We can find that second one by comparing all their generic full names. The gener `mvtest/genFunc.lam:2:6.__call{int}` becomes `mvtest/genFunc.lam:2:6.__call{int}`. The two candidates become: + * `mvtest/genFunc.lam:2:6.__call{genFunc$0}` * `mvtest/genFunclam:2:6.__call{int}` From cbfd920291a8e06859596392b56450cce96dd27b Mon Sep 17 00:00:00 2001 From: Evan Ovadia <> Date: Sun, 9 Jul 2023 21:39:38 -0400 Subject: [PATCH 3/5] Regions merge: Cleaned up Instantiator variable names --- .../dev/vale/instantiating/Instantiator.scala | 539 ++++++++---------- .../vale/instantiating/ast/expressions.scala | 24 - 2 files changed, 229 insertions(+), 334 deletions(-) diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala index 5cba5b623..90bd6d21c 100644 --- a/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala @@ -17,27 +17,10 @@ import dev.vale.typing.types._ import scala.collection.immutable.Map import scala.collection.mutable -// DO NOT SUBMIT straighten out all the C and I and S suffixes and whatnot in this whole file - -case class DenizenBoundToDenizenCallerBoundArgI( +case class DenizenBoundToDenizenCallerBoundArgS( funcBoundToCallerSuppliedBoundArgFunc: Map[IdT[FunctionBoundNameT], PrototypeI[sI]], implBoundToCallerSuppliedBoundArgImpl: Map[IdT[ImplBoundNameT], IdI[sI, IImplNameI[sI]]]) -// Note this has mutable stuff in it. -case class NodeEnvironment( - maybeParent: Option[NodeEnvironment], -// // We track these because we need to know the original type of the local, see CTOTFIPB. -// nameToLocal: mutable.HashMap[IVarNameT, ILocalVariableT] -) { - -// def addTranslatedVariable(idT: IVarNameT, translatedLocalVar: ILocalVariableT): Unit = { -// nameToLocal += (idT -> translatedLocalVar) -// } -// -// def lookupOriginalTranslatedVariable(idT: IVarNameT): ILocalVariableT = { -// vassertSome(nameToLocal.get(idT)) -// } -} class InstantiatedOutputs() { val functions: mutable.HashMap[IdI[cI, IFunctionNameI[cI]], FunctionDefinitionI] = mutable.HashMap() @@ -48,11 +31,11 @@ class InstantiatedOutputs() { // struct Node { value T; next Opt>; } // So we need these to short-circuit that nonsense. val structToMutability: mutable.HashMap[IdI[cI, IStructNameI[cI]], MutabilityI] = mutable.HashMap() - val structToBounds: mutable.HashMap[IdI[sI, IStructNameI[sI]], DenizenBoundToDenizenCallerBoundArgI] = mutable.HashMap() + val structToBounds: mutable.HashMap[IdI[sI, IStructNameI[sI]], DenizenBoundToDenizenCallerBoundArgS] = mutable.HashMap() val interfaceToMutability: mutable.HashMap[IdI[cI, IInterfaceNameI[cI]], MutabilityI] = mutable.HashMap() - val interfaceToBounds: mutable.HashMap[IdI[sI, IInterfaceNameI[sI]], DenizenBoundToDenizenCallerBoundArgI] = mutable.HashMap() + val interfaceToBounds: mutable.HashMap[IdI[sI, IInterfaceNameI[sI]], DenizenBoundToDenizenCallerBoundArgS] = mutable.HashMap() val implToMutability: mutable.HashMap[IdI[cI, IImplNameI[cI]], MutabilityI] = mutable.HashMap() - val implToBounds: mutable.HashMap[IdI[sI, IImplNameI[sI]], DenizenBoundToDenizenCallerBoundArgI] = mutable.HashMap() + val implToBounds: mutable.HashMap[IdI[sI, IImplNameI[sI]], DenizenBoundToDenizenCallerBoundArgS] = mutable.HashMap() // val immKindToDestructor: mutable.HashMap[KindT, PrototypeT] = // mutable.HashMap[KindT, PrototypeT]() @@ -66,12 +49,11 @@ class InstantiatedOutputs() { val impls: mutable.HashMap[ IdI[cI, IImplNameI[cI]], - (ICitizenIT[cI], IdI[cI, IInterfaceNameI[cI]], DenizenBoundToDenizenCallerBoundArgI)] = + (ICitizenIT[cI], IdI[cI, IInterfaceNameI[cI]], DenizenBoundToDenizenCallerBoundArgS)] = mutable.HashMap() // We already know from the hinputs that Opt has func drop(T). // In this map, we'll know that Opt has func drop(int). - // DO NOT SUBMIT rename - val abstractFuncToInstantiatorAndSuppliedPrototypes: mutable.HashMap[IdI[cI, IFunctionNameI[cI]], (DenizenBoundToDenizenCallerBoundArgI, InstantiationBoundArgumentsI)] = + val abstractFuncToBounds: mutable.HashMap[IdI[cI, IFunctionNameI[cI]], (DenizenBoundToDenizenCallerBoundArgS, InstantiationBoundArgumentsI)] = mutable.HashMap() // This map collects all overrides for every impl. We'll use it to assemble vtables soon. val interfaceToImplToAbstractPrototypeToOverride: @@ -83,7 +65,7 @@ class InstantiatedOutputs() { val newImpls: mutable.Queue[(IdT[IImplNameT], IdI[nI, IImplNameI[nI]], InstantiationBoundArgumentsI)] = mutable.Queue() // The int is a virtual index val newAbstractFuncs: mutable.Queue[(PrototypeT, PrototypeI[nI], Int, IdI[cI, IInterfaceNameI[cI]], InstantiationBoundArgumentsI)] = mutable.Queue() - val newFunctions: mutable.Queue[(PrototypeT, PrototypeI[nI], InstantiationBoundArgumentsI, Option[DenizenBoundToDenizenCallerBoundArgI])] = mutable.Queue() + val newFunctions: mutable.Queue[(PrototypeT, PrototypeI[nI], InstantiationBoundArgumentsI, Option[DenizenBoundToDenizenCallerBoundArgS])] = mutable.Queue() def addMethodToVTable( implId: IdI[cI, IImplNameI[cI]], @@ -136,28 +118,28 @@ class Instantiator( kindExterns, functionExternsT) = hinputs - // DO NOT SUBMIT we do nothing with kindExterns + // TODO: We do nothing with kindExterns here. - val kindExportsI = + val kindExportsC = kindExportsT.map({ case KindExportT(range, tyype, exportPlaceholderedIdT, exportedName) => - val exportIdI = + val exportIdS = translateId[ExportNameT, ExportNameI[sI]]( exportPlaceholderedIdT, { case ExportNameT(ExportTemplateNameT(codeLoc)) => ExportNameI(ExportTemplateNameI(codeLoc), RegionTemplataI(0)) }) val exportIdC = - RegionCollapserIndividual.collapseExportId(RegionCounter.countExportId(exportIdI), exportIdI) + RegionCollapserIndividual.collapseExportId(RegionCounter.countExportId(exportIdS), exportIdS) val exportTemplateIdT = TemplataCompiler.getExportTemplate(exportPlaceholderedIdT) val substitutions = Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( - exportTemplateIdT -> assemblePlaceholderMap(exportPlaceholderedIdT, exportIdI)) + exportTemplateIdT -> assemblePlaceholderMap(exportPlaceholderedIdT, exportIdS)) - val denizenBoundToDenizenCallerSuppliedThing = DenizenBoundToDenizenCallerBoundArgI(Map(), Map()) + val denizenBoundToDenizenCallerSuppliedThing = DenizenBoundToDenizenCallerBoundArgS(Map(), Map()) val kindIT = translateKind( exportPlaceholderedIdT, denizenBoundToDenizenCallerSuppliedThing, substitutions, GlobalRegionT(), tyype) @@ -166,7 +148,7 @@ class Instantiator( KindExportI(range, kindCT, exportIdC, exportedName) }) - val functionExportsI = + val functionExportsC = functionExportsT.map({ case FunctionExportT(range, prototypeT, exportPlaceholderedIdT, exportedName) => val perspectiveRegionT = GlobalRegionT() // exportPlaceholderedIdT.localName.templateArgs.last match { @@ -176,25 +158,25 @@ class Instantiator( // case _ => vwat() // } - val exportIdI = + val exportIdS = translateId[ExportNameT, ExportNameI[sI]]( exportPlaceholderedIdT, { case ExportNameT(ExportTemplateNameT(codeLoc)) => ExportNameI(ExportTemplateNameI(codeLoc), RegionTemplataI(0)) }) val exportIdC = - RegionCollapserIndividual.collapseExportId(RegionCounter.countExportId(exportIdI), exportIdI) + RegionCollapserIndividual.collapseExportId(RegionCounter.countExportId(exportIdS), exportIdS) val exportTemplateIdT = TemplataCompiler.getExportTemplate(exportPlaceholderedIdT) val substitutions = Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( - exportTemplateIdT -> assemblePlaceholderMap(exportPlaceholderedIdT, exportIdI)) + exportTemplateIdT -> assemblePlaceholderMap(exportPlaceholderedIdT, exportIdS)) val (_, prototypeC) = translatePrototype( exportPlaceholderedIdT, - DenizenBoundToDenizenCallerBoundArgI(Map(), Map()), + DenizenBoundToDenizenCallerBoundArgS(Map(), Map()), substitutions, perspectiveRegionT, prototypeT) @@ -202,7 +184,7 @@ class Instantiator( FunctionExportI(range, prototypeC, exportIdC, exportedName) }) - val funcExternsI = + val funcExternsC = functionExternsT.map({ case FunctionExternT(range, externPlaceholderedIdT, prototypeT, externedName) => val perspectiveRegionT = GlobalRegionT() // externPlaceholderedIdT.localName.templateArgs.last match { @@ -212,25 +194,25 @@ class Instantiator( // case _ => vwat() // } - val externIdI = + val externIdS = translateId[ExternNameT, ExternNameI[sI]]( externPlaceholderedIdT, { case ExternNameT(ExternTemplateNameT(codeLoc)) => ExternNameI(ExternTemplateNameI(codeLoc), RegionTemplataI(0)) }) val externIdC = - RegionCollapserIndividual.collapseExternId(RegionCounter.countExternId(externIdI), externIdI) + RegionCollapserIndividual.collapseExternId(RegionCounter.countExternId(externIdS), externIdS) val externTemplateIdT = TemplataCompiler.getExternTemplate(externPlaceholderedIdT) val substitutions = Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( - externTemplateIdT -> assemblePlaceholderMap(externPlaceholderedIdT, externIdI)) + externTemplateIdT -> assemblePlaceholderMap(externPlaceholderedIdT, externIdS)) val (_, prototypeC) = translatePrototype( externPlaceholderedIdT, - DenizenBoundToDenizenCallerBoundArgI(Map(), Map()), + DenizenBoundToDenizenCallerBoundArgS(Map(), Map()), substitutions, perspectiveRegionT, prototypeT) @@ -338,9 +320,9 @@ class Instantiator( interfaceEdgeBlueprints, interfaceToSubCitizenToEdge, // Map(), - kindExportsI, - functionExportsI, - funcExternsI) + kindExportsC, + functionExportsC, + funcExternsC) resultHinputs } @@ -352,7 +334,7 @@ class Instantiator( def translateExportName( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, exportNameT: ExportNameT): @@ -379,12 +361,12 @@ class Instantiator( hinputs: HinputsT, monouts: InstantiatedOutputs, interfaceIdT: IdT[IInterfaceNameT], - interfaceIdI: IdI[sI, IInterfaceNameI[sI]], + interfaceIdS: IdI[sI, IInterfaceNameI[sI]], instantiationBoundArgs: InstantiationBoundArgumentsI): Unit = { if (opts.sanityCheck) { - vassert(Collector.all(interfaceIdI, { case KindPlaceholderNameT(_) => }).isEmpty) + vassert(Collector.all(interfaceIdS, { case KindPlaceholderNameT(_) => }).isEmpty) } val interfaceTemplateIdT = TemplataCompiler.getInterfaceTemplate(interfaceIdT) @@ -392,16 +374,18 @@ class Instantiator( val interfaceDefT = findInterface(hinputs, interfaceIdT) val denizenBoundToDenizenCallerSuppliedThing = - DenizenBoundToDenizenCallerBoundArgI( + DenizenBoundToDenizenCallerBoundArgS( assembleCalleeDenizenFunctionBounds( interfaceDefT.runeToFunctionBound, instantiationBoundArgs.runeToFunctionBoundArg), assembleCalleeDenizenImplBounds( interfaceDefT.runeToImplBound, instantiationBoundArgs.runeToImplBoundArg)) - monouts.interfaceToBounds.get(interfaceIdI) match { - case Some(x) => vcurious(x == denizenBoundToDenizenCallerSuppliedThing) // DO NOT SUBMIT should we early return here? + monouts.interfaceToBounds.get(interfaceIdS) match { + case Some(x) => { + vcurious(x == denizenBoundToDenizenCallerSuppliedThing) + } case None => } - monouts.interfaceToBounds.put(interfaceIdI, denizenBoundToDenizenCallerSuppliedThing) + monouts.interfaceToBounds.put(interfaceIdS, denizenBoundToDenizenCallerSuppliedThing) val topLevelDenizenId = getTopLevelDenizenId(interfaceIdT) @@ -415,9 +399,9 @@ class Instantiator( // One would imagine we'd get interfaceId.last.templateArgs here, because that's the interface // we're about to monomorphize. However, only the top level denizen has placeholders, see LHPCTLD. // This interface might not be the top level denizen, such as if it's a lambda. - // DO NOT SUBMIT might be obsolete + // TODO(regions): might be obsolete? interfaceDefT.instantiatedCitizen.id, - interfaceIdI)) + interfaceIdS)) // val instantiator = // new Instantiator( // opts, @@ -429,7 +413,7 @@ class Instantiator( // interfaceIdT, // denizenBoundToDenizenCallerSuppliedThing) val interfaceIdC = - RegionCollapserIndividual.collapseInterfaceId(interfaceIdI) + RegionCollapserIndividual.collapseInterfaceId(interfaceIdS) translateCollapsedInterfaceDefinition( interfaceIdT, denizenBoundToDenizenCallerSuppliedThing, substitutions, interfaceIdC, interfaceDefT) @@ -464,11 +448,11 @@ class Instantiator( hinputs: HinputsT, monouts: InstantiatedOutputs, structIdT: IdT[IStructNameT], - structIdI: IdI[sI, IStructNameI[sI]], + structIdS: IdI[sI, IStructNameI[sI]], instantiationBoundArgs: InstantiationBoundArgumentsI): Unit = { if (opts.sanityCheck) { - vassert(Collector.all(structIdI, { case KindPlaceholderNameT(_) => }).isEmpty) + vassert(Collector.all(structIdS, { case KindPlaceholderNameT(_) => }).isEmpty) } val structTemplate = TemplataCompiler.getStructTemplate(structIdT) @@ -476,16 +460,16 @@ class Instantiator( val structDefT = findStruct(hinputs, structIdT) val denizenBoundToDenizenCallerSuppliedThing = - DenizenBoundToDenizenCallerBoundArgI( + DenizenBoundToDenizenCallerBoundArgS( assembleCalleeDenizenFunctionBounds( structDefT.runeToFunctionBound, instantiationBoundArgs.runeToFunctionBoundArg), assembleCalleeDenizenImplBounds( structDefT.runeToImplBound, instantiationBoundArgs.runeToImplBoundArg)) - monouts.structToBounds.get(structIdI) match { + monouts.structToBounds.get(structIdS) match { case Some(x) => vcurious(x == denizenBoundToDenizenCallerSuppliedThing) // DO NOT SUBMIT should we early return here? case None => } - monouts.structToBounds.put(structIdI, denizenBoundToDenizenCallerSuppliedThing) + monouts.structToBounds.put(structIdS, denizenBoundToDenizenCallerSuppliedThing) val topLevelDenizenId = getTopLevelDenizenId(structIdT) @@ -499,9 +483,9 @@ class Instantiator( // One would imagine we'd get structId.last.templateArgs here, because that's the struct // we're about to monomorphize. However, only the top level denizen has placeholders, see LHPCTLD. // This struct might not be the top level denizen, such as if it's a lambda. - // DO NOT SUBMIT might be obsolete + // TODO(regions): might be obsolete? structDefT.instantiatedCitizen.id, - structIdI)) + structIdS)) // val instantiator = // new Instantiator( // opts, @@ -513,72 +497,10 @@ class Instantiator( // structIdT, // denizenBoundToDenizenCallerSuppliedThing) val structIdC = - RegionCollapserIndividual.collapseStructId(structIdI) + RegionCollapserIndividual.collapseStructId(structIdS) translateCollapsedStructDefinition( structIdT, denizenBoundToDenizenCallerSuppliedThing, substitutions, structIdT, structIdC, structDefT) } - // - // def collapseAndTranslateImplDefinition( - // opts: GlobalOptions, - // interner: Interner, - // keywords: Keywords, - // hinputs: HinputsT, - // monouts: InstantiatedOutputs, - // implIdT: IdT[IImplNameT], - // implIdI: IdI[sI, IImplNameI[sI]], - // instantiationBoundArgs: InstantiationBoundArgumentsI): - // Unit = { - // if (opts.sanityCheck) { - // vassert(Collector.all(implIdI, { case KindPlaceholderNameT(_) => }).isEmpty) - // } - // - // val implTemplate = TemplataCompiler.getImplTemplate(implIdT) - // - // val implDefT = findImpl(hinputs, implIdT) - // - // val denizenBoundToDenizenCallerSuppliedThing = - // DenizenBoundToDenizenCallerBoundArgI( - // assembleCalleeDenizenFunctionBounds( - // implDefT.runeToFuncBound, instantiationBoundArgs.runeToFunctionBoundArg), - // assembleCalleeDenizenImplBounds( - // implDefT.runeToImplBound, instantiationBoundArgs.runeToImplBoundArg)) - // monouts.implToBounds.get(implIdI) match { - // case Some(x) => vcurious(x == denizenBoundToDenizenCallerSuppliedThing) // DO NOT SUBMIT should we early return here? - // case None => - // } - // monouts.implToBounds.put(implIdI, denizenBoundToDenizenCallerSuppliedThing) - // - // val topLevelDenizenId = - // getTopLevelDenizenId(implIdT) - // val topLevelDenizenTemplateId = - // TemplataCompiler.getTemplate(topLevelDenizenId) - // - // val substitutions = - // Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( - // topLevelDenizenTemplateId -> - // assemblePlaceholderMap( - // // One would imagine we'd get implId.last.templateArgs here, because that's the impl - // // we're about to monomorphize. However, only the top level denizen has placeholders, see LHPCTLD. - // // This impl might not be the top level denizen, such as if it's a lambda. - // // DO NOT SUBMIT might be obsolete - // implDefT.edgeId, - // implIdI)) - // // val instantiator = - // // new Instantiator( - // // opts, - // // interner, - // // keywords, - // // hinputs, - // // monouts, - // // implTemplate, - // // implIdT, - // // denizenBoundToDenizenCallerSuppliedThing) - // val implIdC = - // RegionCollapserIndividual.collapseImplId(implIdI) - // - // translateCollapsedImplDefinition( - // implIdT, denizenBoundToDenizenCallerSuppliedThing, substitutions, implIdT, implIdI, implIdC, implDefT) - // } private def findStruct(hinputs: HinputsT, structId: IdT[IStructNameT]) = { vassertOne( @@ -704,7 +626,7 @@ class Instantiator( // This is similar, a map of rune to the bound to use: // $1114 -> func v/builtins/drop(int)void abstractFunctionRuneToCallerSuppliedInstantiationBoundArgs) = - vassertSome(monouts.abstractFuncToInstantiatorAndSuppliedPrototypes.get(abstractFuncPrototypeC.id)) + vassertSome(monouts.abstractFuncToBounds.get(abstractFuncPrototypeC.id)) // The dispatcher was originally made from the abstract function, so they have the same runes. // This will be: // $1114 -> func v/builtins/drop(int)void @@ -713,7 +635,7 @@ class Instantiator( val dispatcherRuneToCallerSuppliedImpl = abstractFunctionRuneToCallerSuppliedInstantiationBoundArgs.runeToImplBoundArg // (this will be empty in this example) TODO: make an example that shows stuff here - val edgeDenizenBoundToDenizenCallerBoundArgI = + val edgeDenizenBoundToDenizenCallerBoundArgS = vassertSome(monouts.impls.get(implIdC))._3 // We currently know the abstract function's caller's runes and how they map to the instantiated values, @@ -798,7 +720,7 @@ class Instantiator( }) val edgeDenizenBoundToDenizenCallerSuppliedThing = - edgeDenizenBoundToDenizenCallerBoundArgI + edgeDenizenBoundToDenizenCallerBoundArgS // See TIBANFC, we need this map to bring in the impl bound args for the override dispatcher @@ -820,7 +742,7 @@ class Instantiator( }}) val caseDenizenBoundToDenizenCallerSuppliedThing = - DenizenBoundToDenizenCallerBoundArgI( + DenizenBoundToDenizenCallerBoundArgS( caseFunctionBoundToIncomingPrototype, caseImplBoundToIncomingImpl) @@ -929,7 +851,7 @@ class Instantiator( } val denizenBoundToDenizenCallerSuppliedThingFromDenizenItself = - DenizenBoundToDenizenCallerBoundArgI( + DenizenBoundToDenizenCallerBoundArgS( assembleCalleeDenizenFunctionBounds( implDefinition.runeToFuncBound, instantiationBoundsForUnsubstitutedImpl.runeToFunctionBoundArg), assembleCalleeDenizenImplBounds( @@ -939,7 +861,7 @@ class Instantiator( hoistBoundsFromParameter(hinputs, monouts, subCitizenT, subCitizenM) val denizenBoundToDenizenCallerSuppliedThing = - DenizenBoundToDenizenCallerBoundArgI( + DenizenBoundToDenizenCallerBoundArgS( denizenBoundToDenizenCallerSuppliedThingFromDenizenItselfAndParams .map(_.funcBoundToCallerSuppliedBoundArgFunc) .reduceOption(_ ++ _).getOrElse(Map()), @@ -1013,13 +935,13 @@ class Instantiator( suppliedBoundArgs: InstantiationBoundArgumentsI, // This is only Some if this is a lambda. This will contain the prototypes supplied to the top // level denizen by its own caller, see LCNBAFA. - maybeDenizenBoundToDenizenCallerSuppliedThing: Option[DenizenBoundToDenizenCallerBoundArgI]): + maybeDenizenBoundToDenizenCallerSuppliedThing: Option[DenizenBoundToDenizenCallerBoundArgS]): FunctionDefinitionI = { // This works because the sI/cI are never actually used in these instances, they are just a // compile-time type-system bit of tracking, see CCFCTS. - val desiredPrototypeI: PrototypeI[sI] = desiredPrototypeN + val desiredPrototypeS: PrototypeI[sI] = desiredPrototypeN val desiredPrototypeC = - RegionCollapserIndividual.collapsePrototype(desiredPrototypeI) + RegionCollapserIndividual.collapsePrototype(desiredPrototypeS) val desiredFuncSuperTemplateName = TemplataCompiler.getSuperTemplate(desiredPrototypeT.id) val funcT = @@ -1030,13 +952,13 @@ class Instantiator( val denizenBoundToDenizenCallerSuppliedThingFromDenizenItself = maybeDenizenBoundToDenizenCallerSuppliedThing.getOrElse({ - DenizenBoundToDenizenCallerBoundArgI( + DenizenBoundToDenizenCallerBoundArgS( // This is a top level denizen, and someone's calling it. Assemble the bounds! assembleCalleeDenizenFunctionBounds(funcT.runeToFuncBound, suppliedBoundArgs.runeToFunctionBoundArg), // This is a top level denizen, and someone's calling it. Assemble the bounds! assembleCalleeDenizenImplBounds(funcT.runeToImplBound, suppliedBoundArgs.runeToImplBoundArg)) }) - val argsM = desiredPrototypeI.id.localName.parameters.map(_.kind) + val argsM = desiredPrototypeS.id.localName.parameters.map(_.kind) val paramsT = funcT.header.params.map(_.tyype.kind) val denizenBoundToDenizenCallerSuppliedThingFromParams = paramsT.zip(argsM).flatMap({ case (a, x) => @@ -1048,7 +970,7 @@ class Instantiator( denizenBoundToDenizenCallerSuppliedThingFromParams val denizenBoundToDenizenCallerSuppliedThing = - DenizenBoundToDenizenCallerBoundArgI( + DenizenBoundToDenizenCallerBoundArgS( denizenBoundToDenizenCallerSuppliedThingFromDenizenItselfAndParams .map(_.funcBoundToCallerSuppliedBoundArgFunc) .reduceOption(_ ++ _).getOrElse(Map()), @@ -1069,7 +991,7 @@ class Instantiator( val substitutions = Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]]( topLevelDenizenTemplateId -> - assemblePlaceholderMap(funcT.header.id, desiredPrototypeI.id)) + assemblePlaceholderMap(funcT.header.id, desiredPrototypeS.id)) // val instantiator = // new Instantiator( // opts, @@ -1104,9 +1026,9 @@ class Instantiator( Unit = { // This works because the sI/cI are never actually used in these instances, they are just a // compile-time type-system bit of tracking, see CCFCTS. - val desiredAbstractPrototypeI: PrototypeI[sI] = desiredAbstractPrototypeN + val desiredAbstractPrototypeS: PrototypeI[sI] = desiredAbstractPrototypeN val desiredAbstractPrototypeC = - RegionCollapserIndividual.collapsePrototype(desiredAbstractPrototypeI) + RegionCollapserIndividual.collapsePrototype(desiredAbstractPrototypeS) val desiredSuperTemplateId = TemplataCompiler.getSuperTemplate(desiredAbstractPrototypeT.id) val funcT = @@ -1116,12 +1038,12 @@ class Instantiator( val denizenBoundToDenizenCallerSuppliedThingFromDenizenItself = - DenizenBoundToDenizenCallerBoundArgI( + DenizenBoundToDenizenCallerBoundArgS( // This is a top level denizen, and someone's calling it. Assemble the bounds! assembleCalleeDenizenFunctionBounds(funcT.runeToFuncBound, suppliedBoundArgs.runeToFunctionBoundArg), // This is a top level denizen, and someone's calling it. Assemble the bounds! assembleCalleeDenizenImplBounds(funcT.runeToImplBound, suppliedBoundArgs.runeToImplBoundArg)) - val argsM = desiredAbstractPrototypeI.id.localName.parameters.map(_.kind) + val argsM = desiredAbstractPrototypeS.id.localName.parameters.map(_.kind) val paramsT = funcT.header.params.map(_.tyype.kind) val denizenBoundToDenizenCallerSuppliedThingFromParams = paramsT.zip(argsM).flatMap({ case (a, x) => @@ -1133,7 +1055,7 @@ class Instantiator( denizenBoundToDenizenCallerSuppliedThingFromParams val denizenBoundToDenizenCallerSuppliedThing = - DenizenBoundToDenizenCallerBoundArgI( + DenizenBoundToDenizenCallerBoundArgS( denizenBoundToDenizenCallerSuppliedThingFromDenizenItselfAndParams .map(_.funcBoundToCallerSuppliedBoundArgFunc) .reduceOption(_ ++ _).getOrElse(Map()), @@ -1142,8 +1064,8 @@ class Instantiator( .reduceOption(_ ++ _).getOrElse(Map())) - vassert(!monouts.abstractFuncToInstantiatorAndSuppliedPrototypes.contains(desiredAbstractPrototypeC.id)) - monouts.abstractFuncToInstantiatorAndSuppliedPrototypes.put(desiredAbstractPrototypeC.id, (denizenBoundToDenizenCallerSuppliedThing, suppliedBoundArgs)) + vassert(!monouts.abstractFuncToBounds.contains(desiredAbstractPrototypeC.id)) + monouts.abstractFuncToBounds.put(desiredAbstractPrototypeC.id, (denizenBoundToDenizenCallerSuppliedThing, suppliedBoundArgs)) val abstractFuncs = vassertSome(monouts.interfaceToAbstractFuncToVirtualIndex.get(interfaceIdC)) vassert(!abstractFuncs.contains(desiredAbstractPrototypeC)) @@ -1156,19 +1078,19 @@ class Instantiator( def assemblePlaceholderMap( idT: IdT[INameT], - idI: IdI[sI, INameI[sI]]): + idS: IdI[sI, INameI[sI]]): Map[IdT[IPlaceholderNameT], ITemplataI[sI]] = { (idT.initNonPackageId() match { case None => Map() case Some(initNonPackageIdT) => { - assemblePlaceholderMap(initNonPackageIdT, vassertSome(idI.initNonPackageFullName())) + assemblePlaceholderMap(initNonPackageIdT, vassertSome(idS.initNonPackageFullName())) } }) ++ (idT match { case IdT(packageCoordT, initStepsT, localNameT: IInstantiationNameT) => { val instantiationIdT = IdT(packageCoordT, initStepsT, localNameT) - val instantiationIdI = - idI match { + val instantiationIdS = + idS match { case IdI(packageCoordI, initStepsI, localNameUncastedI) => { if (localNameUncastedI.isInstanceOf[IInstantiationNameI[sI]]) { IdI(packageCoordI, initStepsI, localNameUncastedI.asInstanceOf[IInstantiationNameI[sI]]) @@ -1178,7 +1100,7 @@ class Instantiator( } case _ => vwat() } - assemblePlaceholderMapInner(instantiationIdT, instantiationIdI) + assemblePlaceholderMapInner(instantiationIdT, instantiationIdS) } case _ => Map() }) @@ -1186,7 +1108,7 @@ class Instantiator( def assemblePlaceholderMapInner( idT: IdT[IInstantiationNameT], - idI: IdI[sI, IInstantiationNameI[sI]]): + idS: IdI[sI, IInstantiationNameI[sI]]): Map[IdT[IPlaceholderNameT], ITemplataI[sI]] = { val placeholderedName = idT // val placeholderedName = @@ -1211,7 +1133,7 @@ class Instantiator( // } placeholderedName.localName.templateArgs - .zip(idI.localName.templateArgs) + .zip(idS.localName.templateArgs) .flatMap({ case ( CoordTemplataT(CoordT(placeholderOwnership, GlobalRegionT(), kindT)), @@ -1275,9 +1197,9 @@ class Instantiator( hinputs: HinputsT, monouts: InstantiatedOutputs, paramT: KindT, - paramI: KindIT[sI]): - Option[DenizenBoundToDenizenCallerBoundArgI] = { - (paramT, paramI) match { + paramS: KindIT[sI]): + Option[DenizenBoundToDenizenCallerBoundArgS] = { + (paramT, paramS) match { case (StructTT(structIdT), StructIT(structIdI)) => { val calleeRuneToBoundArgT = hinputs.getInstantiationBoundArgs(structIdT) val structDenizenBoundToDenizenCallerSuppliedThing = @@ -1306,11 +1228,11 @@ class Instantiator( // See NBIFP private def hoistBoundsFromParameterInner( - parameterDenizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + parameterDenizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, calleeRuneToBoundArgT: InstantiationBoundArgumentsT, calleeRuneToCalleeFunctionBoundT: Map[IRuneS, IdT[FunctionBoundNameT]], calleeRuneToCalleeImplBoundT: Map[IRuneS, IdT[ImplBoundNameT]]): - DenizenBoundToDenizenCallerBoundArgI = { + DenizenBoundToDenizenCallerBoundArgS = { val calleeFunctionBoundTToBoundArgM = parameterDenizenBoundToDenizenCallerSuppliedThing.funcBoundToCallerSuppliedBoundArgFunc val implBoundTToBoundArgM = parameterDenizenBoundToDenizenCallerSuppliedThing.implBoundToCallerSuppliedBoundArgImpl @@ -1364,7 +1286,7 @@ class Instantiator( }).flatten.toMap val denizenBoundToDenizenCallerSuppliedThing = - DenizenBoundToDenizenCallerBoundArgI( + DenizenBoundToDenizenCallerBoundArgS( callerSuppliedBoundToInstantiatedFunction, callerSuppliedBoundToInstantiatedImpl) denizenBoundToDenizenCallerSuppliedThing @@ -1387,7 +1309,7 @@ class Instantiator( def translateStructMember( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, member: IStructMemberT): @@ -1397,29 +1319,29 @@ class Instantiator( val (memberSubjectiveIT, memberTypeI) = tyype match { case ReferenceMemberTypeT(unsubstitutedCoord) => { - val typeI = + val typeS = translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, unsubstitutedCoord) val result = ReferenceMemberTypeI( - RegionCollapserIndividual.collapseCoord(typeI.coord)) - (typeI, result) + RegionCollapserIndividual.collapseCoord(typeS.coord)) + (typeS, result) } case AddressMemberTypeT(unsubstitutedCoord) => { - val typeI = + val typeS = translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, unsubstitutedCoord) - val result = AddressMemberTypeI(RegionCollapserIndividual.collapseCoord(typeI.coord)) - (typeI, result) + val result = AddressMemberTypeI(RegionCollapserIndividual.collapseCoord(typeS.coord)) + (typeS, result) } } - val nameI = translateVarName(name) - val memberI = + val nameS = translateVarName(name) + val memberC = StructMemberI( - RegionCollapserIndividual.collapseVarName(nameI), + RegionCollapserIndividual.collapseVarName(nameS), translateVariability(variability), memberTypeI) - (memberSubjectiveIT.coord, memberI) + (memberSubjectiveIT.coord, memberC) } case VariadicStructMemberT(name, tyype) => { vimpl() @@ -1444,7 +1366,7 @@ class Instantiator( // This is run at the call site, from the caller's perspective def translatePrototype( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, desiredPrototypeT: PrototypeT): @@ -1562,7 +1484,7 @@ class Instantiator( private def translateBoundArgsForCallee( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, // This contains a map from rune to a prototype, specifically the prototype that we @@ -1613,10 +1535,10 @@ class Instantiator( substitutions, perspectiveRegionT, hinputs.getInstantiationBoundArgs(suppliedImplUnsubstituted)) - val implNameI = + val implNameS = translateImplId( denizenName, denizenBoundToDenizenCallerSuppliedThing,substitutions, perspectiveRegionT, suppliedImplUnsubstituted, runeToBoundArgsForCall) - implNameI + implNameS } }) }) @@ -1627,7 +1549,7 @@ class Instantiator( def translateCollapsedStructDefinition( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], newIdT: IdT[IStructNameT], newId: IdI[cI, IStructNameI[cI]], @@ -1685,7 +1607,7 @@ class Instantiator( // taking in a collapsed id. def translateCollapsedInterfaceDefinition( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], newIdC: IdI[cI, IInterfaceNameI[cI]], interfaceDefT: InterfaceDefinitionT): @@ -1752,19 +1674,19 @@ class Instantiator( def translateFunctionHeader( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, header: FunctionHeaderT): FunctionHeaderI = { val FunctionHeaderT(fullName, attributes, params, returnType, maybeOriginFunctionTemplata) = header - val newIdI = + val newIdS = translateFunctionId( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, fullName) val newIdC = RegionCollapserIndividual.collapseId[IFunctionNameI[sI], IFunctionNameI[cI]]( - newIdI, + newIdS, x => RegionCollapserIndividual.collapseFunctionName( x)) val returnIT = @@ -1794,7 +1716,7 @@ class Instantiator( // DO NOT SUBMIT why does this one not take in the collapsed id like the struct and interface things def translateCollapsedFunction( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], // For doublechecking we're getting the actual function we requested desiredPrototypeC: PrototypeI[cI], @@ -1818,11 +1740,11 @@ class Instantiator( // case _ => vwat() // } - val functionIdI = + val functionIdS = translateFunctionId( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, fullName) val functionIdC = - RegionCollapserIndividual.collapseFunctionId(functionIdI) + RegionCollapserIndividual.collapseFunctionId(functionIdS) monouts.functions.get(functionIdC) match { case Some(func) => return func @@ -1836,10 +1758,9 @@ class Instantiator( vfail() } - val startingEnv = NodeEnvironment(None) val (bodySubjectiveIT, bodyIE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, startingEnv, substitutions, perspectiveRegionT, bodyT) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, bodyT) val result = FunctionDefinitionI(newHeader, Map(), Map(), bodyIE) @@ -1849,7 +1770,7 @@ class Instantiator( def translateLocalVariable( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, variable: ILocalVariableT): @@ -1869,58 +1790,57 @@ class Instantiator( def translateReferenceLocalVariable( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, variable: ReferenceLocalVariableT): // Returns subjective coord and the local var (CoordI[sI], ReferenceLocalVariableI) = { val ReferenceLocalVariableT(id, variability, coord) = variable - val coordI = + val coordS = translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, coord) - val varNameI = translateVarName(id) - val localI = + val varNameS = translateVarName(id) + val localC = ReferenceLocalVariableI( - RegionCollapserIndividual.collapseVarName(varNameI), + RegionCollapserIndividual.collapseVarName(varNameS), translateVariability(variability), - RegionCollapserIndividual.collapseCoord(coordI.coord)) - (coordI.coord, localI) + RegionCollapserIndividual.collapseCoord(coordS.coord)) + (coordS.coord, localC) } def translateAddressibleLocalVariable( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, variable: AddressibleLocalVariableT): // Returns subjective coord and the local var (CoordI[sI], AddressibleLocalVariableI) = { val AddressibleLocalVariableT(id, variability, coord) = variable - val coordI = + val coordS = translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, GlobalRegionT(), coord) - val varI = translateVarName(id) - val localI = + val varS = translateVarName(id) + val localC = AddressibleLocalVariableI( - RegionCollapserIndividual.collapseVarName(varI), + RegionCollapserIndividual.collapseVarName(varS), translateVariability(variability), - RegionCollapserIndividual.collapseCoord(coordI.coord)) - (coordI.coord, localI) + RegionCollapserIndividual.collapseCoord(coordS.coord)) + (coordS.coord, localC) } def translateAddrExpr( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, - env: NodeEnvironment, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, expr: AddressExpressionTE): @@ -1959,7 +1879,7 @@ class Instantiator( case ReferenceMemberLookupTE(range, structExprT, memberNameT, memberCoordT, variability) => { val (structSubjectiveIT, structIE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, structExprT) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, structExprT) val structSubjectiveStructIT = structSubjectiveIT.kind.expectStruct() val memberName = translateVarName(memberNameT) @@ -1975,7 +1895,7 @@ class Instantiator( // } // // However, the resulting coord's region *should* have the current mutability. - val memberCoordI = + val memberCoordS = translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, memberCoordT) @@ -1988,7 +1908,7 @@ class Instantiator( // case other => vimpl(other) // } - val resultSubjectiveIT = memberCoordI + val resultSubjectiveIT = memberCoordS val resultIE = ReferenceMemberLookupIE( range, @@ -2002,7 +1922,7 @@ class Instantiator( // DO NOT SUBMIT combine a lot of this with the ReferenceMemberLookupTE case val (arraySubjectiveIT, arrayIE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExprT) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayExprT) // // We can't translate StaticSizedArrayLookupTE.elementTypeT's kind here because we'll // // translate its template args' regions incorrectly according to their current mutabilities. // // They need to be the mutabilities at the time they were introduced, see CTOTFIPB. So @@ -2013,20 +1933,20 @@ class Instantiator( // elementType // } // } - val elementTypeI = + val elementTypeS = translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, elementTypeT).coord val (indexIT, indexCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, indexExprT) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, indexExprT) // // However, the resulting coord's region *should* have the current mutability. // val resultRegion = // ITemplataI.expectRegionTemplata( // translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, elementTypeT.region)) - val resultCoord = CoordI(elementTypeI.ownership, elementTypeI.kind) + val resultCoord = CoordI(elementTypeS.ownership, elementTypeS.kind) val resultIE = StaticSizedArrayLookupIE( @@ -2040,32 +1960,32 @@ class Instantiator( case AddressMemberLookupTE(range, structExpr, memberName, resultType2, variability) => { val (structIT, structCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, structExpr) - val varNameI = translateVarName(memberName) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, structExpr) + val varNameS = translateVarName(memberName) val resultIT = translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, resultType2) - val variabilityI = translateVariability(variability) + val variabilityC = translateVariability(variability) val resultCE = AddressMemberLookupIE( structCE, - RegionCollapserIndividual.collapseVarName(varNameI), + RegionCollapserIndividual.collapseVarName(varNameS), RegionCollapserIndividual.collapseCoord(resultIT.coord), - variabilityI) + variabilityC) (resultIT.coord, resultCE) } case RuntimeSizedArrayLookupTE(range, arrayExpr, rsaTT, indexExpr, variability) => { val (arrayIT, arrayCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayExpr) val rsaIT = translateRuntimeSizedArray( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, rsaTT) val (indexIT, indexCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, indexExpr) - val variabilityI = translateVariability(variability) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, indexExpr) + val variabilityC = translateVariability(variability) // We can't just say rsaIT.elementType here because that's the element from the array's own // perspective. @@ -2076,7 +1996,7 @@ class Instantiator( val resultIT = elementIT val resultCE = RuntimeSizedArrayLookupIE( - arrayCE, indexCE, RegionCollapserIndividual.collapseCoord(elementIT.coord), variabilityI) + arrayCE, indexCE, RegionCollapserIndividual.collapseCoord(elementIT.coord), variabilityC) (resultIT.coord, resultCE) } case other => vimpl(other) @@ -2085,8 +2005,8 @@ class Instantiator( def translateExpr( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, - env: NodeEnvironment, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, expr: ExpressionT): @@ -2095,19 +2015,19 @@ class Instantiator( expr match { case r : ReferenceExpressionTE => { translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, r) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, r) } case a : AddressExpressionTE => { translateAddrExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, a) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, a) } } } def translateRefExpr( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, - env: NodeEnvironment, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, expr: ReferenceExpressionTE): @@ -2119,7 +2039,7 @@ class Instantiator( case RestackifyTE(variable, inner) => { val (innerIT, innerIE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, inner) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, inner) val (localIT, localI) = translateLocalVariable( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, variable) @@ -2134,7 +2054,7 @@ class Instantiator( case LetNormalTE(variableT, innerTE) => { val (innerIT, innerIE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerTE) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, innerTE) val (localIT, localI) = translateLocalVariable( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, variableT) @@ -2148,7 +2068,7 @@ class Instantiator( case BlockTE(inner) => { val (innerIT, innerIE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, inner) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, inner) val resultIT = innerIT val resultIE = BlockIE(innerIE, RegionCollapserIndividual.collapseCoord(resultIT)) (resultIT, resultIE) @@ -2156,7 +2076,7 @@ class Instantiator( case ReturnTE(inner) => { val (innerIT, innerIE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, inner) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, inner) val resultIE = ReturnIE(innerIE) (CoordI[sI](MutableShareI, NeverIT(false)), resultIE) } @@ -2169,7 +2089,7 @@ class Instantiator( val innersIE = inners.map(innerTE => { translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerTE)._2 + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, innerTE)._2 }) val resultIE = ConsecutorIE(innersIE, RegionCollapserIndividual.collapseCoord(resultIT)) (resultIT, resultIE) @@ -2206,7 +2126,7 @@ class Instantiator( case DiscardTE(innerTE) => { val (innerIT, innerIE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerTE) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, innerTE) val resultIE = DiscardIE(innerIE) (CoordI[sI](MutableShareI, VoidIT()), resultIE) } @@ -2218,7 +2138,7 @@ class Instantiator( args.map(argTE => { val (argIT, argCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, argTE) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, argTE) // if (pure && argIT.ownership == MutableBorrowI) { // PreCheckBorrowIE(argCE) // } else { @@ -2257,7 +2177,7 @@ class Instantiator( virtualParamIndex, args.map(arg => { translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arg)._2 + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arg)._2 }), RegionCollapserIndividual.collapseCoord(resultIT)) val interfaceIdC = @@ -2289,17 +2209,17 @@ class Instantiator( (resultIT, resultCE) } case ArgLookupTE(paramIndex, reference) => { - val typeI = + val typeS = translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, reference) .coord - val resultCE = ArgLookupIE(paramIndex, RegionCollapserIndividual.collapseCoord(typeI)) - (typeI, resultCE) + val resultCE = ArgLookupIE(paramIndex, RegionCollapserIndividual.collapseCoord(typeS)) + (typeS, resultCE) } case SoftLoadTE(originalInner, originalTargetOwnership) => { val (innerIT, innerIE) = translateAddrExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, originalInner) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, originalInner) val targetOwnership = // First, figure out what ownership it is after substitution. // if we have an owned T but T is a &Ship, then own + borrow = borrow @@ -2336,7 +2256,7 @@ class Instantiator( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, prototype2) val argsIE = args.map(argTE => { - translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, argTE)._2 + translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, argTE)._2 }) val resultIT = prototypeI.returnType val resultIE = ExternFunctionCallIE(prototypeC, argsIE, prototypeC.returnType) @@ -2360,7 +2280,7 @@ class Instantiator( val argsIE = args.map(argTE => { translateExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, argTE)._2 + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, argTE)._2 }) val structIT = @@ -2387,7 +2307,7 @@ class Instantiator( case DestroyTE(exprT, structTT, destinationReferenceVariables) => { val (sourceIT, sourceIE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, exprT) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, exprT) val structIT = translateStructId( @@ -2424,7 +2344,7 @@ class Instantiator( (CoordI[sI](MutableShareI, VoidIT()), resultIE) } case DestroyStaticSizedArrayIntoLocalsTE(exprT, ssaTT, destinationReferenceVariables) => { - val (sourceIT, sourceIE) = translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, exprT) + val (sourceIT, sourceIE) = translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, exprT) val (ssaIT, size) = sourceIT.kind match { case s @ StaticSizedArrayIT(IdI(_, _, StaticSizedArrayNameI(_, size, _, _))) => (s, size) @@ -2446,10 +2366,10 @@ class Instantiator( // DO NOT SUBMIT change all IE to CE like this one val (destinationIT, destinationCE) = translateAddrExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, destinationTT) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, destinationTT) val (sourceIT, sourceCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, sourceExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, sourceExpr) val resultIT = destinationIT val resultCE = MutateIE(destinationCE, sourceCE, RegionCollapserIndividual.collapseCoord(resultIT)) (resultIT, resultCE) @@ -2480,16 +2400,16 @@ class Instantiator( val (innerIT, innerCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerExprUnsubstituted) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, innerExprUnsubstituted) - val superKindI = + val superKindS = translateSuperKind( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, targetSuperKind) val resultCE = UpcastIE( innerCE, - InterfaceIT(RegionCollapserIndividual.collapseInterfaceId(superKindI.id)), + InterfaceIT(RegionCollapserIndividual.collapseInterfaceId(superKindS.id)), RegionCollapserIndividual.collapseImplId(implId), RegionCollapserIndividual.collapseCoord(resultIT.coord)) (resultIT.coord, resultCE) @@ -2497,13 +2417,13 @@ class Instantiator( case IfTE(condition, thenCall, elseCall) => { val (conditionIT, conditionCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, condition) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, condition) val (thenIT, thenCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, thenCall) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, thenCall) val (elseIT, elseCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, elseCall) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, elseCall) val resultIT = (thenIT, elseIT) match { case (a, b) if a == b => a @@ -2518,10 +2438,10 @@ class Instantiator( case IsSameInstanceTE(left, right) => { val (leftIT, leftCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, left) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, left) val (rightIT, rightCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, right) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, right) val resultCE = IsSameInstanceIE(leftCE, rightCE) (CoordI[sI](MutableShareI, BoolIT()), resultCE) } @@ -2542,7 +2462,7 @@ class Instantiator( val elementsCE = elements.map(elementTE => { - translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, elementTE)._2 + translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, elementTE)._2 }) val ssaTT = @@ -2563,10 +2483,10 @@ class Instantiator( case DeferTE(innerExpr, deferredExpr) => { val (innerIT, innerCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, innerExpr) val (deferredIT, deferredCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, deferredExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, deferredExpr) val resultIT = innerIT val resultCE = DeferIE(innerCE, deferredCE, RegionCollapserIndividual.collapseCoord(resultIT)) @@ -2575,16 +2495,16 @@ class Instantiator( case LetAndLendTE(variable, sourceExprT, outerOwnershipT) => { val (sourceSubjectiveIT, sourceIE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, sourceExprT) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, sourceExprT) - val resultOwnershipI = + val resultOwnershipC = translateOwnership( substitutions, perspectiveRegionT, composeOwnerships(outerOwnershipT, sourceSubjectiveIT.ownership), sourceExprT.result.coord.region) - val resultIT = CoordI(resultOwnershipI, sourceSubjectiveIT.kind) + val resultIT = CoordI(resultOwnershipC, sourceSubjectiveIT.kind) val (localIT, localI) = translateLocalVariable( @@ -2594,14 +2514,14 @@ class Instantiator( LetAndLendIE( localI, sourceIE, - resultOwnershipI, + resultOwnershipC, RegionCollapserIndividual.collapseCoord(resultIT)) (resultIT, resultIE) } case BorrowToWeakTE(innerExpr) => { val (innerIT, innerCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, innerExpr) val resultIT = innerIT.copy(ownership = WeakI) @@ -2612,7 +2532,7 @@ class Instantiator( case WhileTE(BlockTE(inner)) => { val (innerIT, innerCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, inner) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, inner) // While loops must always produce void. // If we want a foreach/map/whatever construct, the loop should instead @@ -2642,7 +2562,7 @@ class Instantiator( val resultCT = RegionCollapserIndividual.collapseCoord(resultIT) val resultCE = LockWeakIE( - translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, innerExpr)._2, + translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, innerExpr)._2, resultCT, translatePrototype(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, someConstructor)._2, translatePrototype(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, noneConstructor)._2, @@ -2678,13 +2598,13 @@ class Instantiator( case DestroyStaticSizedArrayIntoFunctionTE(arrayExpr, arrayType, consumer, consumerMethod) => { val (arrayIT, arrayCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayExpr) val ssaIT = translateStaticSizedArray( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayType) val (consumerIT, consumerCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, consumer) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, consumer) val (consumerPrototypeI, consumerPrototypeC) = translatePrototype( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, consumerMethod) @@ -2701,10 +2621,10 @@ class Instantiator( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayType) val (sizeIT, sizeCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, sizeExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, sizeExpr) val (generatorIT, generatorCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, generator) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, generator) val (generatorPrototypeI, generatorPrototypeC) = translatePrototype( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, generatorMethod) @@ -2743,7 +2663,7 @@ class Instantiator( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayType) val (generatorIT, generatorCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, generator) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, generator) val (generatorPrototypeI, generatorPrototypeC) = translatePrototype( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, generatorMethod) @@ -2776,24 +2696,24 @@ class Instantiator( case RuntimeSizedArrayCapacityTE(arrayExpr) => { val (arrayIT, arrayCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayExpr) val resultCE = RuntimeSizedArrayCapacityIE(arrayCE) (CoordI[sI](MutableShareI, IntIT(32)), resultCE) } case PushRuntimeSizedArrayTE(arrayExpr, newElementExpr) => { val (arrayIT, arrayCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayExpr) val (elementIT, elementCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, newElementExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, newElementExpr) val resultCE = PushRuntimeSizedArrayIE(arrayCE, elementCE) (CoordI[sI](MutableShareI, VoidIT()), resultCE) } case PopRuntimeSizedArrayTE(arrayExpr) => { val (arrayIT, arrayCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayExpr) val elementIT = arrayIT.kind match { case RuntimeSizedArrayIT(IdI(_, _, RuntimeSizedArrayNameI(_, RawArrayNameI(_, elementType, _)))) => { @@ -2807,15 +2727,15 @@ class Instantiator( case ArrayLengthTE(arrayExpr) => { val (arrayIT, arrayCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayExpr) val resultIT = CoordI[sI](MutableShareI, IntIT(32)) val resultCE = ArrayLengthIE(arrayCE) (resultIT, resultCE) } case DestroyImmRuntimeSizedArrayTE(arrayExpr, arrayType, consumer, consumerMethod) => { - val (arrayIT, arrayCE) = translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + val (arrayIT, arrayCE) = translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayExpr) val rsaIT = translateRuntimeSizedArray(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayType) - val (consumerIT, consumerCE) = translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, consumer) + val (consumerIT, consumerCE) = translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, consumer) val (prototypeI, prototypeC) = translatePrototype( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, consumerMethod) @@ -2831,7 +2751,7 @@ class Instantiator( case DestroyMutRuntimeSizedArrayTE(arrayExpr) => { val (arrayIT, arrayIE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, arrayExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayExpr) val resultIE = DestroyMutRuntimeSizedArrayIE(arrayIE) (CoordI.void[sI], resultIE) } @@ -2849,7 +2769,7 @@ class Instantiator( val (capacityIT, capacityIE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, capacityExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, capacityExpr) val resultCE = NewMutRuntimeSizedArrayIE( @@ -2861,7 +2781,7 @@ class Instantiator( case TupleTE(elements, resultReference) => { val elementsCE = elements.map(elementTE => { - translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, elementTE)._2 + translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, elementTE)._2 }) val resultIT = @@ -2874,7 +2794,7 @@ class Instantiator( case AsSubtypeTE(sourceExpr, targetSubtype, resultResultType, okConstructor, errConstructor, implIdT, okResultImplIdT, errResultImplIdT) => { val (sourceIT, sourceCE) = translateRefExpr( - denizenName, denizenBoundToDenizenCallerSuppliedThing, env, substitutions, perspectiveRegionT, sourceExpr) + denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, sourceExpr) val resultIT = translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, @@ -2968,8 +2888,8 @@ class Instantiator( private def runInNewPureRegion[T]( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, - env: NodeEnvironment, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, + substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], denizenTemplateName: IdT[ITemplateNameT], newDefaultRegionT: ITemplataT[RegionTemplataType], @@ -3038,7 +2958,7 @@ class Instantiator( def translateFunctionId( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, fullNameT: IdT[IFunctionNameT]): @@ -3074,7 +2994,7 @@ class Instantiator( def translateStructId( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, fullNameT: IdT[IStructNameT], @@ -3082,7 +3002,7 @@ class Instantiator( IdI[sI, IStructNameI[sI]] = { val IdT(module, steps, lastT) = fullNameT - val fullNameI = + val fullNameS = IdI( module, steps.map(translateName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), @@ -3090,36 +3010,35 @@ class Instantiator( collapseAndTranslateStructDefinition( - opts, interner, keywords, hinputs, monouts, fullNameT, fullNameI, instantiationBoundArgs) + opts, interner, keywords, hinputs, monouts, fullNameT, fullNameS, instantiationBoundArgs) - fullNameI + fullNameS } def translateInterfaceId( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, fullNameT: IdT[IInterfaceNameT], instantiationBoundArgs: InstantiationBoundArgumentsI): IdI[sI, IInterfaceNameI[sI]] = { val IdT(module, steps, last) = fullNameT - val newIdI = + val newIdS = IdI( module, steps.map(translateName(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, _)), translateInterfaceName(denizenName, denizenBoundToDenizenCallerSuppliedThing,substitutions, perspectiveRegionT, last)) - collapseAndTranslateInterfaceDefinition( - opts, interner, keywords, hinputs, monouts, fullNameT, newIdI, instantiationBoundArgs) + opts, interner, keywords, hinputs, monouts, fullNameT, newIdS, instantiationBoundArgs) - newIdI + newIdS } def translateImplId( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, implIdT: IdT[IImplNameT], @@ -3170,7 +3089,7 @@ class Instantiator( def translateCitizenName( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, t: ICitizenNameT): @@ -3193,7 +3112,7 @@ class Instantiator( def translateCitizenId( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, id: IdT[ICitizenNameT], @@ -3214,7 +3133,7 @@ class Instantiator( def translateCoord( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, coord: CoordT): @@ -3381,7 +3300,7 @@ class Instantiator( def translateCitizen( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, citizen: ICitizenTT, @@ -3395,7 +3314,7 @@ class Instantiator( def translateStruct( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, struct: StructTT, @@ -3414,7 +3333,7 @@ class Instantiator( def translateInterface( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, interface: InterfaceTT, @@ -3432,7 +3351,7 @@ class Instantiator( def translateSuperKind( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, kind: ISuperKindTT): @@ -3477,7 +3396,7 @@ class Instantiator( def translateStaticSizedArray( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, ssaTT: StaticSizedArrayTT): @@ -3525,7 +3444,7 @@ class Instantiator( def translateRuntimeSizedArray( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, rsaTT: RuntimeSizedArrayTT): @@ -3568,7 +3487,7 @@ class Instantiator( def translateKind( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, kind: KindT): @@ -3610,7 +3529,7 @@ class Instantiator( def translateParameter( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, param: ParameterT): @@ -3620,9 +3539,9 @@ class Instantiator( translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, tyype) .coord - val nameI = translateVarName(name) + val nameS = translateVarName(name) ParameterI( - RegionCollapserIndividual.collapseVarName(nameI), + RegionCollapserIndividual.collapseVarName(nameS), virtuality.map({ case AbstractT() => AbstractI() }), preChecked, RegionCollapserIndividual.collapseCoord(typeIT)) @@ -3630,7 +3549,7 @@ class Instantiator( def translateTemplata( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, templata: ITemplataT[ITemplataType]): @@ -3687,7 +3606,7 @@ class Instantiator( def translateFunctionName( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, name: IFunctionNameT): @@ -3742,7 +3661,7 @@ class Instantiator( def translateImplName( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, name: IImplNameT): @@ -3803,7 +3722,7 @@ class Instantiator( def translateStructName( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], // See TTTDRM, this is the region from which we're determining other regions' mutabilities. perspectiveRegionT: GlobalRegionT, @@ -3839,7 +3758,7 @@ class Instantiator( def translateInterfaceName( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, name: IInterfaceNameT): @@ -3865,7 +3784,7 @@ class Instantiator( def translateName( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, name: INameT): @@ -3910,7 +3829,7 @@ class Instantiator( def translateCollapsedImplDefinition( denizenName: IdT[IInstantiationNameT], - denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgI, + denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], implIdT: IdT[IImplNameT], implIdS: IdI[sI, IImplNameI[sI]], @@ -3931,7 +3850,7 @@ class Instantiator( // case _ => vwat() // } - val subCitizenI = + val subCitizenS = translateCitizen( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, @@ -3942,8 +3861,8 @@ class Instantiator( GlobalRegionT(), hinputs.getInstantiationBoundArgs(implDefinition.subCitizen.id))) val subCitizenC = - RegionCollapserIndividual.collapseCitizen(subCitizenI) - val superInterfaceI = + RegionCollapserIndividual.collapseCitizen(subCitizenS) + val superInterfaceS = translateInterfaceId( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, @@ -3954,7 +3873,7 @@ class Instantiator( GlobalRegionT(), hinputs.getInstantiationBoundArgs(implDefinition.superInterface))) val superInterfaceC = - RegionCollapserIndividual.collapseInterfaceId(superInterfaceI) + RegionCollapserIndividual.collapseInterfaceId(superInterfaceS) val mutability = vassertSome(monouts.interfaceToMutability.get(superInterfaceC)) if (monouts.implToMutability.contains(implIdC)) { diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/expressions.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/expressions.scala index 828154276..86e6a6d25 100644 --- a/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/expressions.scala +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/expressions.scala @@ -3,30 +3,6 @@ package dev.vale.instantiating.ast import dev.vale._ import dev.vale.postparsing._ -//trait IExpressionResultI { -// def expectReference(): ReferenceResultI = { -// this match { -// case r @ ReferenceResultI(_) => r -// case AddressResultI(_) => vfail("Expected a reference as a result, but got an address!") -// } -// } -// def expectAddress(): AddressResultI = { -// this match { -// case a @ AddressResultI(_) => a -// case ReferenceResultI(_) => vfail("Expected an address as a result, but got a reference!") -// } -// } -// // DO NOT SUBMIT rename back to coord -// def collapsedCoord: CoordI[cI] -//} -//// This is only the collapsed coord, see HCCSCS. -//case class ReferenceResultI(collapsedCoord: CoordI[cI]) extends IExpressionResultI { -// override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() -//} -//case class AddressResultI(collapsedCoord: CoordI[cI]) extends IExpressionResultI { -// override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() -//} - trait ExpressionI { def result: CoordI[cI] } From 93bc584fde8f6e0ea1c3f1ba976aadead8663496 Mon Sep 17 00:00:00 2001 From: Evan Ovadia <> Date: Tue, 11 Jul 2023 11:05:30 -0400 Subject: [PATCH 4/5] Fixed the underscore/ignore pattern problem --- .../dev/vale/highertyping/ErrorTests.scala | 2 +- .../highertyping/HigherTypingPassTests.scala | 2 +- .../src/dev/vale/highlighter/Spanner.scala | 3 + .../vale/highlighter/HighlighterTests.scala | 2 +- .../dev/vale/highlighter/SpannerTests.scala | 2 +- .../dev/vale/instantiating/Instantiator.scala | 387 +++++++----------- .../dev/vale/instantiating/ast/names.scala | 4 +- .../instantiating/InstantiatedTests.scala | 2 +- .../vale/AfterRegionsIntegrationTests.scala | 2 +- .../test/dev/vale/ArithmeticTestsA.scala | 2 +- .../test/dev/vale/ArrayListTest.scala | 2 +- .../test/dev/vale/ArrayTests.scala | 9 +- .../test/dev/vale/BlockTests.scala | 2 +- .../test/dev/vale/ClosureTests.scala | 2 +- .../test/dev/vale/ConjunctionTests.scala | 2 +- .../test/dev/vale/FloatTests.scala | 2 +- .../test/dev/vale/HammerTests.scala | 2 +- .../test/dev/vale/HashMapTest.scala | 2 +- .../test/dev/vale/IfTests.scala | 2 +- .../test/dev/vale/ImportTests.scala | 2 +- .../test/dev/vale/InferTemplateTests.scala | 2 +- .../test/dev/vale/IntegrationTestsA.scala | 4 +- .../test/dev/vale/OptTests.scala | 2 +- .../test/dev/vale/OwnershipTests.scala | 2 +- .../test/dev/vale/PackTests.scala | 2 +- .../test/dev/vale/PatternTests.scala | 2 +- .../test/dev/vale/PrintTests.scala | 2 +- .../test/dev/vale/PureFunctionTests.scala | 2 +- .../test/dev/vale/ResultTests.scala | 2 +- .../test/dev/vale/StringTests.scala | 2 +- .../test/dev/vale/StructTests.scala | 20 +- .../test/dev/vale/TupleTests.scala | 2 +- .../test/dev/vale/VirtualTests.scala | 2 +- .../test/dev/vale/WeakTests.scala | 2 +- .../test/dev/vale/WhileTests.scala | 2 +- .../dev/vale/parsing/StringParserTests.scala | 3 +- .../dev/vale/parsing/AfterRegionsTests.scala | 2 +- .../dev/vale/parsing/ExpressionTests.scala | 2 +- .../test/dev/vale/parsing/IfTests.scala | 2 +- .../test/dev/vale/parsing/ImplTests.scala | 2 +- .../test/dev/vale/parsing/LoadTests.scala | 2 +- .../dev/vale/parsing/ParseSamplesTests.scala | 2 +- .../dev/vale/parsing/StatementTests.scala | 2 +- .../test/dev/vale/parsing/StructTests.scala | 2 +- .../test/dev/vale/parsing/TopLevelTests.scala | 2 +- .../test/dev/vale/parsing/WhileTests.scala | 2 +- .../functions/AfterRegionsFunctionTests.scala | 2 +- .../parsing/functions/FunctionTests.scala | 4 +- .../patterns/CaptureAndDestructureTests.scala | 2 +- .../patterns/CaptureAndTypeTests.scala | 2 +- .../patterns/DestructureParserTests.scala | 2 +- .../parsing/patterns/PatternParserTests.scala | 2 +- .../patterns/TypeAndDestructureTests.scala | 2 +- .../dev/vale/parsing/patterns/TypeTests.scala | 2 +- .../vale/parsing/rules/CoordRuleTests.scala | 2 +- .../vale/parsing/rules/KindRuleTests.scala | 2 +- .../dev/vale/parsing/rules/RuleTests.scala | 2 +- .../vale/parsing/rules/RulesEnumsTests.scala | 2 +- .../postparsing/AfterRegionsErrorTests.scala | 2 +- .../PostParserErrorHumanizerTests.scala | 2 +- .../vale/postparsing/PostParserTests.scala | 2 +- .../postparsing/PostParserVariableTests.scala | 2 +- .../PostParsingParametersTests.scala | 2 +- .../postparsing/PostParsingRuleTests.scala | 2 +- .../src/dev/vale/simplifying/Hamuts.scala | 25 +- .../src/dev/vale/simplifying/TypeHammer.scala | 13 +- .../dev/vale/simplifying/HammerTest.scala | 2 +- .../test/dev/vale/solver/SolverTests.scala | 2 +- .../test/dev/vale/solver/TestRuleSolver.scala | 2 +- .../test/dev/vale/solver/TestRules.scala | 2 +- .../src/dev/vale/testvm/FunctionVivem.scala | 2 +- .../test/dev/vale/testvm/VivemTests.scala | 8 +- .../src/dev/vale/typing/Compiler.scala | 7 +- .../vale/typing/CompilerErrorReporter.scala | 8 + .../expression/ExpressionCompiler.scala | 109 ++--- .../typing/expression/PatternCompiler.scala | 72 ++-- .../function/FunctionBodyCompiler.scala | 12 +- .../typing/function/FunctionCompiler.scala | 1 + .../function/FunctionCompilerCore.scala | 3 +- .../src/dev/vale/typing/names/names.scala | 4 +- .../vale/typing/AfterRegionsErrorTests.scala | 2 +- .../dev/vale/typing/AfterRegionsTests.scala | 2 +- .../dev/vale/typing/CompilerLambdaTests.scala | 2 +- .../dev/vale/typing/CompilerMutateTests.scala | 2 +- .../vale/typing/CompilerOwnershipTests.scala | 2 +- .../vale/typing/CompilerProjectTests.scala | 2 +- .../dev/vale/typing/CompilerSolverTests.scala | 2 +- .../vale/typing/CompilerVirtualTests.scala | 2 +- .../dev/vale/typing/InProgressTests.scala | 2 +- .../test/dev/vale/typing/TodoTests.scala | 2 +- Frontend/Von/test/dev/vale/von/VonTest.scala | 2 +- 91 files changed, 414 insertions(+), 426 deletions(-) diff --git a/Frontend/HigherTypingPass/test/dev/vale/highertyping/ErrorTests.scala b/Frontend/HigherTypingPass/test/dev/vale/highertyping/ErrorTests.scala index f173a4df2..4726b47b8 100644 --- a/Frontend/HigherTypingPass/test/dev/vale/highertyping/ErrorTests.scala +++ b/Frontend/HigherTypingPass/test/dev/vale/highertyping/ErrorTests.scala @@ -2,7 +2,7 @@ package dev.vale.highertyping import dev.vale.postparsing.{CodeNameS, PostParser, RuneTypeSolveError, RuneTypingCouldntFindType} import dev.vale.{Err, Ok, SourceCodeUtils, StrI, vassert, vfail} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import dev.vale.solver._ class ErrorTests extends FunSuite with Matchers { diff --git a/Frontend/HigherTypingPass/test/dev/vale/highertyping/HigherTypingPassTests.scala b/Frontend/HigherTypingPass/test/dev/vale/highertyping/HigherTypingPassTests.scala index de17771c1..d72884b27 100644 --- a/Frontend/HigherTypingPass/test/dev/vale/highertyping/HigherTypingPassTests.scala +++ b/Frontend/HigherTypingPass/test/dev/vale/highertyping/HigherTypingPassTests.scala @@ -5,7 +5,7 @@ import dev.vale.postparsing._ import dev.vale.parsing.Parser import dev.vale.postparsing.RuneTypeSolveError import dev.vale._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class HigherTypingPassTests extends FunSuite with Matchers { def compileProgramForError(compilation: HigherTypingCompilation): ICompileErrorA = { diff --git a/Frontend/Highlighter/src/dev/vale/highlighter/Spanner.scala b/Frontend/Highlighter/src/dev/vale/highlighter/Spanner.scala index 7872819f2..0a6e280cd 100644 --- a/Frontend/Highlighter/src/dev/vale/highlighter/Spanner.scala +++ b/Frontend/Highlighter/src/dev/vale/highlighter/Spanner.scala @@ -450,6 +450,9 @@ object Spanner { def forCapture(c: INameDeclarationP): Span = { c match { + case IgnoredLocalNameDeclarationP(nameRange) => { + makeSpan(CaptureName, nameRange, Vector.empty) + } case LocalNameDeclarationP(NameP(nameRange, _)) => { makeSpan(CaptureName, nameRange, Vector.empty) } diff --git a/Frontend/Highlighter/test/dev/vale/highlighter/HighlighterTests.scala b/Frontend/Highlighter/test/dev/vale/highlighter/HighlighterTests.scala index cb47f9696..cf0e48d24 100644 --- a/Frontend/Highlighter/test/dev/vale/highlighter/HighlighterTests.scala +++ b/Frontend/Highlighter/test/dev/vale/highlighter/HighlighterTests.scala @@ -6,7 +6,7 @@ import dev.vale.{Err, FileCoordinateMap, IPackageResolver, Interner, Keywords, O import dev.vale.options.GlobalOptions import dev.vale.parsing.Parser import dev.vale.parsing._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.Map diff --git a/Frontend/Highlighter/test/dev/vale/highlighter/SpannerTests.scala b/Frontend/Highlighter/test/dev/vale/highlighter/SpannerTests.scala index c8fe5a0aa..03540d838 100644 --- a/Frontend/Highlighter/test/dev/vale/highlighter/SpannerTests.scala +++ b/Frontend/Highlighter/test/dev/vale/highlighter/SpannerTests.scala @@ -6,7 +6,7 @@ import dev.vale.parsing.{ParserCompilation, ast} import dev.vale.{Err, FileCoordinateMap, Interner, Keywords, Ok, PackageCoordinate} import dev.vale.parsing.ast.FileP import dev.vale.parsing.{ast, _} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class SpannerTests extends FunSuite with Matchers { private def compile(code: String): FileP = { diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala index 90bd6d21c..471053d40 100644 --- a/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/Instantiator.scala @@ -235,7 +235,7 @@ class Instantiator( if (monouts.newFunctions.nonEmpty) { val (newFuncIdT, newFuncIdN, instantiationBoundArgs, maybeDenizenBoundToDenizenCallerSuppliedThing) = monouts.newFunctions.dequeue() - translateFunction1( + translateFunction( opts, interner, keywords, hinputs, monouts, newFuncIdT, newFuncIdN, instantiationBoundArgs, maybeDenizenBoundToDenizenCallerSuppliedThing) true @@ -466,7 +466,10 @@ class Instantiator( assembleCalleeDenizenImplBounds( structDefT.runeToImplBound, instantiationBoundArgs.runeToImplBoundArg)) monouts.structToBounds.get(structIdS) match { - case Some(x) => vcurious(x == denizenBoundToDenizenCallerSuppliedThing) // DO NOT SUBMIT should we early return here? + case Some(x) => { + vcurious(x == denizenBoundToDenizenCallerSuppliedThing) + return + } case None => } monouts.structToBounds.put(structIdS, denizenBoundToDenizenCallerSuppliedThing) @@ -568,15 +571,15 @@ class Instantiator( // First step: gather a bunch of details about the given impl, super interface (ISpaceship), sub citizen (Raza) // and the abstract function (virtual func launch). val implTemplateId = TemplataCompiler.getImplTemplate(implIdT) - val implDefinitionT = + val edgeT = vassertOne( hinputs.interfaceToSubCitizenToEdge .flatMap(_._2.values) .filter(edge => TemplataCompiler.getImplTemplate(edge.edgeId) == implTemplateId)) - val superInterfaceTemplateId = TemplataCompiler.getInterfaceTemplate(implDefinitionT.superInterface) + val superInterfaceTemplateId = TemplataCompiler.getInterfaceTemplate(edgeT.superInterface) val superInterfaceDefinitionT = hinputs.lookupInterfaceByTemplateId(superInterfaceTemplateId) val superInterfacePlaceholderedName = superInterfaceDefinitionT.instantiatedInterface - val subCitizenTemplateId = TemplataCompiler.getCitizenTemplate(implDefinitionT.subCitizen.id) + val subCitizenTemplateId = TemplataCompiler.getCitizenTemplate(edgeT.subCitizen.id) val subCitizenDefinitionT = hinputs.lookupCitizenByTemplateId(subCitizenTemplateId) val subCitizenPlaceholderedName = subCitizenDefinitionT.instantiatedCitizen val abstractFuncTemplateName = TemplataCompiler.getFunctionTemplate(abstractFuncPrototypeT.id) @@ -585,11 +588,6 @@ class Instantiator( hinputs.functions .find(func => TemplataCompiler.getFunctionTemplate(func.header.id) == abstractFuncTemplateName)) .header.id - val edgeT = - vassertSome( - vassertSome(hinputs.interfaceToSubCitizenToEdge.get(superInterfacePlaceholderedName.id)) - .get(subCitizenPlaceholderedName.id)) - vcurious(edgeT == implDefinitionT) // DO NOT SUBMIT remove all this? they're the same. // Luckily, the typing phase knows what the override is. // In this example, it's func launch(self &Raza, bork int) @@ -697,7 +695,7 @@ class Instantiator( // These will be used to call the override properly. // Sometimes (such as in the Milano case, see OMCNAGP) we have independent runes that need to be filled. - // DO NOT SUBMIT talk about this more. + // Here we grab what their templatas really are, now that we know them because we're instantiating. val dispatcherCasePlaceholderIdToSuppliedTemplata = dispatcherCaseIdT.localName.independentImplTemplateArgs.zipWithIndex.map({ case (casePlaceholderTemplata, index) => { @@ -923,8 +921,7 @@ class Instantiator( } - // DO NOT SUBMIT figure out better name - def translateFunction1( + def translateFunction( opts: GlobalOptions, interner: Interner, keywords: Keywords, @@ -1423,8 +1420,8 @@ class Instantiator( vassert(codeLocA == codeLocB) vassert(templateArgsA.length == templateArgsB.length) vassert(parametersA.length == parametersB.length) - // TODO: Could we have a false positive here if we're doing things on different templates? - // I don't think so. DO NOT SUBMIT + // Could we have a false positive here if we're doing things on different templates? + // I don't think so. } case ( LambdaCallFunctionNameT(LambdaCallFunctionTemplateNameT(codeLocA,paramsTTA),templateArgsA,parametersA), @@ -1444,7 +1441,7 @@ class Instantiator( // // Let's say we want to call 1'myPureDisplay(0'board). // // We want that to become 0'myPureDisplay(-1'board). // // The default region we send should always be zero, and all incoming imms should be negative. -// // DO NOT SUBMIT centralize docs +// // TODO(regions): centralize docs // // TODO use an array instead of a map here // val oldRegionPureHeights = // Collector.all(uncollapsedDesiredPrototypeI, { @@ -1527,17 +1524,9 @@ class Instantiator( IdT(packageCoord, initSteps, name))) } case _ => { - // Not sure about these three lines, but they seem to work. - val runeToBoundArgsForCall = - translateBoundArgsForCallee( - denizenName, - denizenBoundToDenizenCallerSuppliedThing, - substitutions, - perspectiveRegionT, - hinputs.getInstantiationBoundArgs(suppliedImplUnsubstituted)) val implNameS = translateImplId( - denizenName, denizenBoundToDenizenCallerSuppliedThing,substitutions, perspectiveRegionT, suppliedImplUnsubstituted, runeToBoundArgsForCall) + denizenName, denizenBoundToDenizenCallerSuppliedThing,substitutions, perspectiveRegionT, suppliedImplUnsubstituted) implNameS } }) @@ -1713,7 +1702,6 @@ class Instantiator( } } - // DO NOT SUBMIT why does this one not take in the collapsed id like the struct and interface things def translateCollapsedFunction( denizenName: IdT[IInstantiationNameT], denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, @@ -1758,11 +1746,11 @@ class Instantiator( vfail() } - val (bodySubjectiveIT, bodyIE) = + val (bodySubjectiveIT, bodyCE) = translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, bodyT) - val result = FunctionDefinitionI(newHeader, Map(), Map(), bodyIE) + val result = FunctionDefinitionI(newHeader, Map(), Map(), bodyCE) monouts.functions.put(result.header.id, result) result @@ -1870,69 +1858,37 @@ class Instantiator( // localVariableI.coord.kind) val resultSubjectiveIT = localSubjectiveIT - val resultIE = + val resultCE = LocalLookupIE( localVariableI, RegionCollapserIndividual.collapseCoord(resultSubjectiveIT)) - (resultSubjectiveIT, resultIE) + (resultSubjectiveIT, resultCE) } case ReferenceMemberLookupTE(range, structExprT, memberNameT, memberCoordT, variability) => { - val (structSubjectiveIT, structIE) = + val (structSubjectiveIT, structCE) = translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, structExprT) - val structSubjectiveStructIT = structSubjectiveIT.kind.expectStruct() val memberName = translateVarName(memberNameT) -// // We can't translate ReferenceMemberLookupTE.memberCoord's kind here because we'll -// // translate its template args' regions incorrectly according to their current mutabilities. -// // They need to be the mutabilities at the time they were introduced, see CTOTFIPB. So -// // instead, we look it up from the struct definition. -// val structDef = vassertSome(monouts.structs.get(structSubjectiveStructIT.id)) -// val defMemberCoord: CoordT = vimpl() -//// vassertSome(structDef.members.find(_.name == memberName)) match { -//// case NormalStructMemberT(name, variability, tyype) => tyype.reference -//// case VariadicStructMemberT(name, tyype) => vimpl() -// } -// // However, the resulting coord's region *should* have the current mutability. - val memberCoordS = translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, memberCoordT) -// val resultOwnership = -// (memberCoordI.ownership, resultRegion) match { -// case (OwnI, RegionTemplataI(_)) => OwnI -//// case (MutableShareI, RegionTemplataI(true)) => MutableShareI -//// case (MutableShareI, RegionTemplataI(false)) => ImmutableShareI -// case (ImmutableShareI, _) => ImmutableShareI -// case other => vimpl(other) -// } - val resultSubjectiveIT = memberCoordS - val resultIE = + val resultCE = ReferenceMemberLookupIE( range, - structIE, + structCE, RegionCollapserIndividual.collapseVarName(memberName), RegionCollapserIndividual.collapseCoord(resultSubjectiveIT.coord), translateVariability(variability)) - (resultSubjectiveIT.coord, resultIE) + (resultSubjectiveIT.coord, resultCE) } case StaticSizedArrayLookupTE(range, arrayExprT, arrayType, indexExprT, elementTypeT, variability) => { - // DO NOT SUBMIT combine a lot of this with the ReferenceMemberLookupTE case - val (arraySubjectiveIT, arrayIE) = + val (arraySubjectiveIT, arrayCE) = translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayExprT) -// // We can't translate StaticSizedArrayLookupTE.elementTypeT's kind here because we'll -// // translate its template args' regions incorrectly according to their current mutabilities. -// // They need to be the mutabilities at the time they were introduced, see CTOTFIPB. So -// // instead, we look it up from the struct definition. -// val elementType = -// arraySubjectiveIT.kind match { -// case StaticSizedArrayIT(IdI(_, _, StaticSizedArrayNameI(_, _, _, RawArrayNameI(_, elementType, _)))) => { -// elementType -// } -// } + val elementTypeS = translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, elementTypeT).coord @@ -1941,21 +1897,16 @@ class Instantiator( translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, indexExprT) -// // However, the resulting coord's region *should* have the current mutability. -// val resultRegion = -// ITemplataI.expectRegionTemplata( -// translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, elementTypeT.region)) - val resultCoord = CoordI(elementTypeS.ownership, elementTypeS.kind) - val resultIE = + val resultCE = StaticSizedArrayLookupIE( range, - arrayIE, + arrayCE, indexCE, RegionCollapserIndividual.collapseCoord(resultCoord), translateVariability(variability)) - (resultCoord, resultIE) + (resultCoord, resultCE) } case AddressMemberLookupTE(range, structExpr, memberName, resultType2, variability) => { val (structIT, structCE) = @@ -2037,7 +1988,7 @@ class Instantiator( val (resultIT, resultCE) = expr match { case RestackifyTE(variable, inner) => { - val (innerIT, innerIE) = + val (innerIT, innerCE) = translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, inner) val (localIT, localI) = @@ -2045,14 +1996,14 @@ class Instantiator( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, variable) // env.addTranslatedVariable(variableT.name, vimpl(translatedVariable)) val subjectiveResultIT = CoordI[sI](MutableShareI, VoidIT()) - val exprIE = + val exprCE = RestackifyIE( - localI, innerIE, RegionCollapserIndividual.collapseCoord(subjectiveResultIT)) - (subjectiveResultIT, exprIE) + localI, innerCE, RegionCollapserIndividual.collapseCoord(subjectiveResultIT)) + (subjectiveResultIT, exprCE) } case LetNormalTE(variableT, innerTE) => { - val (innerIT, innerIE) = + val (innerIT, innerCE) = translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, innerTE) val (localIT, localI) = @@ -2060,25 +2011,25 @@ class Instantiator( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, variableT) // env.addTranslatedVariable(variableT.name, vimpl(translatedVariable)) val subjectiveResultIT = CoordI[sI](MutableShareI, VoidIT()) - val exprIE = + val exprCE = LetNormalIE( - localI, innerIE, RegionCollapserIndividual.collapseCoord(subjectiveResultIT)) - (subjectiveResultIT, exprIE) + localI, innerCE, RegionCollapserIndividual.collapseCoord(subjectiveResultIT)) + (subjectiveResultIT, exprCE) } case BlockTE(inner) => { - val (innerIT, innerIE) = + val (innerIT, innerCE) = translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, inner) val resultIT = innerIT - val resultIE = BlockIE(innerIE, RegionCollapserIndividual.collapseCoord(resultIT)) - (resultIT, resultIE) + val resultCE = BlockIE(innerCE, RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultCE) } case ReturnTE(inner) => { - val (innerIT, innerIE) = + val (innerIT, innerCE) = translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, inner) - val resultIE = ReturnIE(innerIE) - (CoordI[sI](MutableShareI, NeverIT(false)), resultIE) + val resultCE = ReturnIE(innerCE) + (CoordI[sI](MutableShareI, NeverIT(false)), resultCE) } case c @ ConsecutorTE(inners) => { val resultTT = c.result.coord @@ -2086,13 +2037,13 @@ class Instantiator( translateCoord( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, resultTT) .coord - val innersIE = + val innersCE = inners.map(innerTE => { translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, innerTE)._2 }) - val resultIE = ConsecutorIE(innersIE, RegionCollapserIndividual.collapseCoord(resultIT)) - (resultIT, resultIE) + val resultCE = ConsecutorIE(innersCE, RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultCE) } case ConstantIntTE(value, bits) => { val resultCE = @@ -2115,26 +2066,26 @@ class Instantiator( (CoordI[sI](MutableShareI, BoolIT()), resultCE) } case UnletTE(variable) => { - val (localIT, localIE) = + val (localIT, localCE) = translateLocalVariable( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, variable) val resultIT = localIT // val local = env.lookupOriginalTranslatedVariable(variable.name) - val resultIE = UnletIE(localIE, RegionCollapserIndividual.collapseCoord(resultIT)) - (resultIT, resultIE) + val resultCE = UnletIE(localCE, RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultCE) } case DiscardTE(innerTE) => { - val (innerIT, innerIE) = + val (innerIT, innerCE) = translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, innerTE) - val resultIE = DiscardIE(innerIE) - (CoordI[sI](MutableShareI, VoidIT()), resultIE) + val resultCE = DiscardIE(innerCE) + (CoordI[sI](MutableShareI, VoidIT()), resultCE) } case VoidLiteralTE() => { (CoordI[sI](MutableShareI, VoidIT()), VoidLiteralIE()) } case FunctionCallTE(prototypeT, args) => { - val innersIE = + val innersCE = args.map(argTE => { val (argIT, argCE) = translateRefExpr( @@ -2163,8 +2114,8 @@ class Instantiator( // .coord val returnCoordCT = RegionCollapserIndividual.collapseCoord(returnCoordIT) - val resultIE = FunctionCallIE(prototypeC, innersIE, returnCoordCT) - (returnCoordIT, resultIE) + val resultCE = FunctionCallIE(prototypeC, innersCE, returnCoordCT) + (returnCoordIT, resultCE) } case InterfaceFunctionCallTE(superFunctionPrototypeT, virtualParamIndex, resultReference, args) => { val (superFunctionPrototypeI, superFunctionPrototypeC) = @@ -2217,7 +2168,7 @@ class Instantiator( (typeS, resultCE) } case SoftLoadTE(originalInner, originalTargetOwnership) => { - val (innerIT, innerIE) = + val (innerIT, innerCE) = translateAddrExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, originalInner) val targetOwnership = @@ -2246,21 +2197,21 @@ class Instantiator( case other => vwat(other) } val resultIT = CoordI[sI](targetOwnership, innerIT.kind) - val resultIE = - SoftLoadIE(innerIE, targetOwnership, RegionCollapserIndividual.collapseCoord(resultIT)) - (resultIT, resultIE) + val resultCE = + SoftLoadIE(innerCE, targetOwnership, RegionCollapserIndividual.collapseCoord(resultIT)) + (resultIT, resultCE) } case ExternFunctionCallTE(prototype2, args) => { val (prototypeI, prototypeC) = translatePrototype( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, prototype2) - val argsIE = + val argsCE = args.map(argTE => { translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, argTE)._2 }) val resultIT = prototypeI.returnType - val resultIE = ExternFunctionCallIE(prototypeC, argsIE, prototypeC.returnType) - (resultIT, resultIE) + val resultCE = ExternFunctionCallIE(prototypeC, argsCE, prototypeC.returnType) + (resultIT, resultCE) } case ConstructTE(structTT, resultReference, args) => { val resultIT = @@ -2277,7 +2228,7 @@ class Instantiator( // monouts.immKindToDestructor.put(coord.kind, freePrototype) // } - val argsIE = + val argsCE = args.map(argTE => { translateExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, argTE)._2 @@ -2297,15 +2248,15 @@ class Instantiator( perspectiveRegionT, hinputs.getInstantiationBoundArgs(structTT.id))) - val resultIE = + val resultCE = ConstructIE( StructIT(RegionCollapserIndividual.collapseStructId(structIT.id)), RegionCollapserIndividual.collapseCoord(resultIT), - argsIE) - (resultIT, resultIE) + argsCE) + (resultIT, resultCE) } case DestroyTE(exprT, structTT, destinationReferenceVariables) => { - val (sourceIT, sourceIE) = + val (sourceIT, sourceCE) = translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, exprT) @@ -2332,19 +2283,19 @@ class Instantiator( // val structDef = vassertSome(monouts.structs.get(resultT.id)) // vassert(structDef.members.size == destinationReferenceVariables.size) - val resultIE = + val resultCE = DestroyIE( - sourceIE, + sourceCE, StructIT(RegionCollapserIndividual.collapseStructId(structIT)), destinationReferenceVariables.map(destRefVarT => { translateReferenceLocalVariable( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, destRefVarT)._2 })) - (CoordI[sI](MutableShareI, VoidIT()), resultIE) + (CoordI[sI](MutableShareI, VoidIT()), resultCE) } case DestroyStaticSizedArrayIntoLocalsTE(exprT, ssaTT, destinationReferenceVariables) => { - val (sourceIT, sourceIE) = translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, exprT) + val (sourceIT, sourceCE) = translateRefExpr(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, exprT) val (ssaIT, size) = sourceIT.kind match { case s @ StaticSizedArrayIT(IdI(_, _, StaticSizedArrayNameI(_, size, _, _))) => (s, size) @@ -2354,7 +2305,7 @@ class Instantiator( vassert(size == destinationReferenceVariables.size) val resultCE = DestroyStaticSizedArrayIntoLocalsIE( - sourceIE, + sourceCE, RegionCollapserIndividual.collapseStaticSizedArray(ssaIT), destinationReferenceVariables.map(destRefVarT => { translateReferenceLocalVariable( @@ -2363,7 +2314,6 @@ class Instantiator( (CoordI[sI](MutableShareI, VoidIT()), resultCE) } case MutateTE(destinationTT, sourceExpr) => { - // DO NOT SUBMIT change all IE to CE like this one val (destinationIT, destinationCE) = translateAddrExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, destinationTT) @@ -2376,16 +2326,12 @@ class Instantiator( } case u @ UpcastTE(innerExprUnsubstituted, targetSuperKind, untranslatedImplId) => { val implId = - translateImplId(denizenName, denizenBoundToDenizenCallerSuppliedThing, + translateImplId( + denizenName, + denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, - - untranslatedImplId, - translateBoundArgsForCallee(denizenName, denizenBoundToDenizenCallerSuppliedThing, - substitutions, - perspectiveRegionT, - - hinputs.getInstantiationBoundArgs(untranslatedImplId))) + untranslatedImplId) // val freePrototype = translatePrototype(freePrototypeT) val resultIT = translateCoord( @@ -2493,7 +2439,7 @@ class Instantiator( (resultIT, resultCE) } case LetAndLendTE(variable, sourceExprT, outerOwnershipT) => { - val (sourceSubjectiveIT, sourceIE) = + val (sourceSubjectiveIT, sourceCE) = translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, sourceExprT) @@ -2501,6 +2447,7 @@ class Instantiator( translateOwnership( substitutions, perspectiveRegionT, + // TODO: see if we can combine this with the other composeOwnerships function. composeOwnerships(outerOwnershipT, sourceSubjectiveIT.ownership), sourceExprT.result.coord.region) @@ -2510,13 +2457,13 @@ class Instantiator( translateLocalVariable( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, variable) - val resultIE = + val resultCE = LetAndLendIE( localI, - sourceIE, + sourceCE, resultOwnershipC, RegionCollapserIndividual.collapseCoord(resultIT)) - (resultIT, resultIE) + (resultIT, resultCE) } case BorrowToWeakTE(innerExpr) => { val (innerIT, innerCE) = @@ -2572,26 +2519,14 @@ class Instantiator( denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, - someImplUntranslatedId, - translateBoundArgsForCallee( - denizenName, - denizenBoundToDenizenCallerSuppliedThing, - substitutions, - perspectiveRegionT, - hinputs.getInstantiationBoundArgs(someImplUntranslatedId)))), + someImplUntranslatedId)), RegionCollapserIndividual.collapseImplId( translateImplId( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, - noneImplUntranslatedId, - translateBoundArgsForCallee( - denizenName, - denizenBoundToDenizenCallerSuppliedThing, - substitutions, - perspectiveRegionT, - hinputs.getInstantiationBoundArgs(noneImplUntranslatedId)))), + noneImplUntranslatedId)), resultCT) (resultIT, resultCE) } @@ -2749,11 +2684,11 @@ class Instantiator( (CoordI[sI](MutableShareI, VoidIT()), resultCE) } case DestroyMutRuntimeSizedArrayTE(arrayExpr) => { - val (arrayIT, arrayIE) = + val (arrayIT, arrayCE) = translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, arrayExpr) - val resultIE = DestroyMutRuntimeSizedArrayIE(arrayIE) - (CoordI.void[sI], resultIE) + val resultCE = DestroyMutRuntimeSizedArrayIE(arrayCE) + (CoordI.void[sI], resultCE) } case NewMutRuntimeSizedArrayTE(arrayTT, capacityExpr) => { val arrayIT = @@ -2767,14 +2702,14 @@ class Instantiator( }, arrayIT) - val (capacityIT, capacityIE) = + val (capacityIT, capacityCE) = translateRefExpr( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, capacityExpr) val resultCE = NewMutRuntimeSizedArrayIE( RegionCollapserIndividual.collapseRuntimeSizedArray(arrayIT), - capacityIE, + capacityCE, RegionCollapserIndividual.collapseCoord(resultIT)) (resultIT, resultCE) } @@ -2814,39 +2749,21 @@ class Instantiator( denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, - implIdT, - translateBoundArgsForCallee( - denizenName, - denizenBoundToDenizenCallerSuppliedThing, - substitutions, - perspectiveRegionT, - hinputs.getInstantiationBoundArgs(implIdT)))), + implIdT)), RegionCollapserIndividual.collapseImplId( translateImplId( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, - okResultImplIdT, - translateBoundArgsForCallee( - denizenName, - denizenBoundToDenizenCallerSuppliedThing, - substitutions, - perspectiveRegionT, - hinputs.getInstantiationBoundArgs(okResultImplIdT)))), + okResultImplIdT)), RegionCollapserIndividual.collapseImplId( translateImplId( denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, - errResultImplIdT, - translateBoundArgsForCallee( - denizenName, - denizenBoundToDenizenCallerSuppliedThing, - substitutions, - perspectiveRegionT, - hinputs.getInstantiationBoundArgs(errResultImplIdT)))), + errResultImplIdT)), RegionCollapserIndividual.collapseCoord(resultIT)) (resultIT, resultCE) } @@ -2935,6 +2852,68 @@ class Instantiator( } } + private def composeOwnerships(outerOwnership: OwnershipT, innerOwnership: OwnershipI, kind: KindIT[sI]) = { + // TODO: see if we can combine this with the other composeOwnerships function. + kind match { + case IntIT(_) | BoolIT() | VoidIT() => { + // We don't want any ImmutableShareH for primitives, it's better to only ever have one + // ownership for primitives. + MutableShareI + } + case _ => { + ((outerOwnership, innerOwnership) match { + case (OwnT, OwnI) => OwnI + // case (OwnT, ImmutableShareI) => ImmutableShareI + case (OwnT | BorrowT, MutableShareI | ImmutableShareI) => { + // We disregard whether it's a MutableShareI or ImmutableShareI because + // that was likely calculated under different circumstances from a + // different perspective region. + // We'll recalculate it now with out own perspective region. + // See IPOMFIC. + //if (regionIsMutable(substitutions, perspectiveRegionT, expectRegionPlaceholder(outerRegion))) { + MutableShareI + // } else { + // ImmutableShareI + // } + } + // case (OwnT, BorrowT) => BorrowT + case (OwnT, MutableBorrowI) => { + vregionmut() // here too maybe? + MutableBorrowI + } + // case (BorrowT, OwnT) => BorrowT + case (BorrowT, OwnI) => { + vregionmut() // we'll probably want a regionIsMutable call like above + MutableBorrowI + } + // case (BorrowT, BorrowT) => BorrowT + case (BorrowT, MutableBorrowI) => { + vregionmut() // we'll probably want a regionIsMutable call like above + MutableBorrowI + } + // case (BorrowT, WeakT) => WeakT + // case (BorrowT, ShareT) => ShareT + // case (WeakT, OwnT) => WeakT + case (WeakT, OwnI) => { + vregionmut() // here too maybe? + WeakI + } + // case (WeakT, BorrowT) => WeakT + // case (WeakT, WeakT) => WeakT + // case (WeakT, ShareT) => ShareT + // case (ShareT, ShareT) => ShareT + case (ShareT, MutableShareI) => { + vregionmut() // here too maybe? + MutableShareI + } + // case (OwnT, ShareT) => ShareT + case other => vwat(other) + }) + } + } + } + + // TODO: see if we can combine this with the other composeOwnerships function. def composeOwnerships( outerOwnership: OwnershipT, innerOwnership: OwnershipI): @@ -3041,9 +3020,7 @@ class Instantiator( denizenBoundToDenizenCallerSuppliedThing: DenizenBoundToDenizenCallerBoundArgS, substitutions: Map[IdT[INameT], Map[IdT[IPlaceholderNameT], ITemplataI[sI]]], perspectiveRegionT: GlobalRegionT, - implIdT: IdT[IImplNameT], - // DO NOT SUBMIT this seems to be redundant with what we do below - instantiationBoundArgs: InstantiationBoundArgumentsI): + implIdT: IdT[IImplNameT]): IdI[sI, IImplNameI[sI]] = { val IdT(module, steps, lastT) = implIdT @@ -3157,65 +3134,9 @@ class Instantiator( vassertSome(vassertSome(substitutions.get(placeholderId.initId(interner))).get(placeholderId)) match { case CoordTemplataI(region, CoordI(innerOwnership, kind)) => { + // TODO: see if we can combine this with the other composeOwnerships function. val combinedOwnership = - kind match { - case IntIT(_) | BoolIT() | VoidIT() => { - // We don't want any ImmutableShareH for primitives, it's better to only ever have one - // ownership for primitives. - MutableShareI - } - case _ => { - ((outerOwnership, innerOwnership) match { - case (OwnT, OwnI) => OwnI - // case (OwnT, ImmutableShareI) => ImmutableShareI - case (OwnT | BorrowT, MutableShareI | ImmutableShareI) => { - // We disregard whether it's a MutableShareI or ImmutableShareI because - // that was likely calculated under different circumstances from a - // different perspective region. - // We'll recalculate it now with out own perspective region. - // See IPOMFIC. - //if (regionIsMutable(substitutions, perspectiveRegionT, expectRegionPlaceholder(outerRegion))) { - MutableShareI - // } else { - // ImmutableShareI - // } - } - // case (OwnT, BorrowT) => BorrowT - case (OwnT, MutableBorrowI) => { - vregionmut() // here too maybe? - MutableBorrowI - } - // case (BorrowT, OwnT) => BorrowT - case (BorrowT, OwnI) => { - vregionmut() // we'll probably want a regionIsMutable call like above - MutableBorrowI - } - // case (BorrowT, BorrowT) => BorrowT - case (BorrowT, MutableBorrowI) => { - vregionmut() // we'll probably want a regionIsMutable call like above - MutableBorrowI - } - // case (BorrowT, WeakT) => WeakT - // case (BorrowT, ShareT) => ShareT - // case (WeakT, OwnT) => WeakT - case (WeakT, OwnI) => { - vregionmut() // here too maybe? - WeakI - } - // case (WeakT, BorrowT) => WeakT - // case (WeakT, WeakT) => WeakT - // case (WeakT, ShareT) => ShareT - // case (ShareT, ShareT) => ShareT - case (ShareT, MutableShareI) => { - vregionmut() // here too maybe? - MutableShareI - } - // case (OwnT, ShareT) => ShareT - case other => vwat(other) - // DO NOT SUBMIT combine this with what's elsewhere in this file - }) - } - } + composeOwnerships(outerOwnership, innerOwnership, kind) // vassert(innerRegion == translateTemplata(denizenName, denizenBoundToDenizenCallerSuppliedThing, substitutions, perspectiveRegionT, outerRegion)) CoordTemplataI(RegionTemplataI(0), CoordI(combinedOwnership, kind)) } diff --git a/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/names.scala b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/names.scala index cb2dd97b5..bf962db88 100644 --- a/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/names.scala +++ b/Frontend/InstantiatingPass/src/dev/vale/instantiating/ast/names.scala @@ -270,7 +270,9 @@ case class OverrideDispatcherCaseNameI[+R <: IRegionsModeI]( sealed trait IVarNameI[+R <: IRegionsModeI] extends INameI[R] case class TypingPassBlockResultVarNameI[+R <: IRegionsModeI](life: LocationInFunctionEnvironmentI) extends IVarNameI[R] case class TypingPassFunctionResultVarNameI[+R <: IRegionsModeI]() extends IVarNameI[R] -case class TypingPassTemporaryVarNameI[+R <: IRegionsModeI](life: LocationInFunctionEnvironmentI) extends IVarNameI[R] +case class TypingPassTemporaryVarNameI[+R <: IRegionsModeI](life: LocationInFunctionEnvironmentI) extends IVarNameI[R] { + vpass() +} case class TypingPassPatternMemberNameI[+R <: IRegionsModeI](life: LocationInFunctionEnvironmentI) extends IVarNameI[R] case class TypingIgnoredParamNameI[+R <: IRegionsModeI](num: Int) extends IVarNameI[R] case class TypingPassPatternDestructureeNameI[+R <: IRegionsModeI](life: LocationInFunctionEnvironmentI) extends IVarNameI[R] diff --git a/Frontend/InstantiatingPass/test/dev/vale/instantiating/InstantiatedTests.scala b/Frontend/InstantiatingPass/test/dev/vale/instantiating/InstantiatedTests.scala index 3c168e3e6..7db735f56 100644 --- a/Frontend/InstantiatingPass/test/dev/vale/instantiating/InstantiatedTests.scala +++ b/Frontend/InstantiatingPass/test/dev/vale/instantiating/InstantiatedTests.scala @@ -2,7 +2,7 @@ package dev.vale.instantiating import dev.vale.options.GlobalOptions import dev.vale.{Builtins, FileCoordinateMap, Interner, Keywords, PackageCoordinate, Tests} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ object InstantiatingCompilation { def test(code: String*): InstantiatedCompilation = { diff --git a/Frontend/IntegrationTests/test/dev/vale/AfterRegionsIntegrationTests.scala b/Frontend/IntegrationTests/test/dev/vale/AfterRegionsIntegrationTests.scala index 5c117b149..2e1ed683e 100644 --- a/Frontend/IntegrationTests/test/dev/vale/AfterRegionsIntegrationTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/AfterRegionsIntegrationTests.scala @@ -16,7 +16,7 @@ import dev.vale.typing.templata.MutabilityTemplataT import dev.vale.typing.types._ import dev.vale.typing.{HinputsT, ICompileErrorT} import dev.vale.von.{IVonData, VonBool, VonFloat, VonInt} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class AfterRegionsIntegrationTests extends FunSuite with Matchers { diff --git a/Frontend/IntegrationTests/test/dev/vale/ArithmeticTestsA.scala b/Frontend/IntegrationTests/test/dev/vale/ArithmeticTestsA.scala index 2a21e1034..18c827cef 100644 --- a/Frontend/IntegrationTests/test/dev/vale/ArithmeticTestsA.scala +++ b/Frontend/IntegrationTests/test/dev/vale/ArithmeticTestsA.scala @@ -8,7 +8,7 @@ import dev.vale.typing.types.StrT import dev.vale.testvm.StructInstanceV import dev.vale.von.VonInt import dev.vale.{finalast => m} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class ArithmeticTestsA extends FunSuite with Matchers { test("Dividing") { diff --git a/Frontend/IntegrationTests/test/dev/vale/ArrayListTest.scala b/Frontend/IntegrationTests/test/dev/vale/ArrayListTest.scala index 390ea743b..8c4391c75 100644 --- a/Frontend/IntegrationTests/test/dev/vale/ArrayListTest.scala +++ b/Frontend/IntegrationTests/test/dev/vale/ArrayListTest.scala @@ -6,7 +6,7 @@ import dev.vale.typing.names.{CodeVarNameT, IdT} import dev.vale.typing.types.VaryingT import dev.vale.typing.names.CodeVarNameT import dev.vale.von.VonInt -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class ArrayListTest extends FunSuite with Matchers { test("Simple ArrayList, no optionals") { diff --git a/Frontend/IntegrationTests/test/dev/vale/ArrayTests.scala b/Frontend/IntegrationTests/test/dev/vale/ArrayTests.scala index 8c5bd21d1..52177c340 100644 --- a/Frontend/IntegrationTests/test/dev/vale/ArrayTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/ArrayTests.scala @@ -13,7 +13,7 @@ import dev.vale.typing.names.CodeVarNameT import dev.vale.typing.templata.MutabilityTemplataT import dev.vale.typing.types._ import dev.vale.von.{VonBool, VonInt, VonStr} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class ArrayTests extends FunSuite with Matchers { test("Returning static array from function and dotting it") { @@ -21,9 +21,12 @@ class ArrayTests extends FunSuite with Matchers { """ |func makeArray() [#5]int { return [#](2, 3, 4, 5, 6); } |exported func main() int { - | return makeArray().3; + | a = makeArray(); + | x = a.3; + | [_, _, _, _, _] = a; + | return x; |} - """.stripMargin) + """.stripMargin, false) compile.evalForKind(Vector()) match { case VonInt(5) => } } diff --git a/Frontend/IntegrationTests/test/dev/vale/BlockTests.scala b/Frontend/IntegrationTests/test/dev/vale/BlockTests.scala index bfc5b9ddb..2802e6641 100644 --- a/Frontend/IntegrationTests/test/dev/vale/BlockTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/BlockTests.scala @@ -5,7 +5,7 @@ import dev.vale.postparsing._ import dev.vale.typing._ import dev.vale.typing.types.BoolT import dev.vale.von.VonInt -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class BlockTests extends FunSuite with Matchers { test("Empty block") { diff --git a/Frontend/IntegrationTests/test/dev/vale/ClosureTests.scala b/Frontend/IntegrationTests/test/dev/vale/ClosureTests.scala index e260b37ba..6d0abc315 100644 --- a/Frontend/IntegrationTests/test/dev/vale/ClosureTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/ClosureTests.scala @@ -11,7 +11,7 @@ import dev.vale.typing._ import dev.vale.typing.ast._ import dev.vale.typing.env.ReferenceLocalVariableT import dev.vale.typing.types._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import dev.vale.typing.templata.MutabilityTemplataT import dev.vale.von.VonInt diff --git a/Frontend/IntegrationTests/test/dev/vale/ConjunctionTests.scala b/Frontend/IntegrationTests/test/dev/vale/ConjunctionTests.scala index ec6886deb..7eb44b55c 100644 --- a/Frontend/IntegrationTests/test/dev/vale/ConjunctionTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/ConjunctionTests.scala @@ -1,7 +1,7 @@ package dev.vale import dev.vale.von.VonBool -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class ConjunctionTests extends FunSuite with Matchers { test("And") { diff --git a/Frontend/IntegrationTests/test/dev/vale/FloatTests.scala b/Frontend/IntegrationTests/test/dev/vale/FloatTests.scala index bbb764377..9e39759c4 100644 --- a/Frontend/IntegrationTests/test/dev/vale/FloatTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/FloatTests.scala @@ -5,7 +5,7 @@ import dev.vale.typing.expression.CallCompiler import dev.vale.typing._ import dev.vale.typing.types._ import dev.vale.von.VonInt -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class FloatTests extends FunSuite with Matchers { test("Print float") { diff --git a/Frontend/IntegrationTests/test/dev/vale/HammerTests.scala b/Frontend/IntegrationTests/test/dev/vale/HammerTests.scala index 20fd91b7a..17f1e70f8 100644 --- a/Frontend/IntegrationTests/test/dev/vale/HammerTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/HammerTests.scala @@ -7,7 +7,7 @@ import dev.vale.testvm.PanicException import dev.vale.simplifying._ import dev.vale.von.VonInt import dev.vale.{finalast => m} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.List diff --git a/Frontend/IntegrationTests/test/dev/vale/HashMapTest.scala b/Frontend/IntegrationTests/test/dev/vale/HashMapTest.scala index 967ab7e47..a6bedb49f 100644 --- a/Frontend/IntegrationTests/test/dev/vale/HashMapTest.scala +++ b/Frontend/IntegrationTests/test/dev/vale/HashMapTest.scala @@ -4,7 +4,7 @@ import dev.vale.typing.env.ReferenceLocalVariableT import dev.vale.typing._ import dev.vale.typing.types._ import dev.vale.von.VonInt -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class HashMapTest extends FunSuite with Matchers { test("Monomorphize problem") { diff --git a/Frontend/IntegrationTests/test/dev/vale/IfTests.scala b/Frontend/IntegrationTests/test/dev/vale/IfTests.scala index 2ea0cc7b1..e50b02cb1 100644 --- a/Frontend/IntegrationTests/test/dev/vale/IfTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/IfTests.scala @@ -8,7 +8,7 @@ import dev.vale.postparsing._ import dev.vale.typing._ import dev.vale.typing.types._ import dev.vale.von.{VonInt, VonStr} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class IfTests extends FunSuite with Matchers { test("Simple true branch returning an int") { diff --git a/Frontend/IntegrationTests/test/dev/vale/ImportTests.scala b/Frontend/IntegrationTests/test/dev/vale/ImportTests.scala index a88579bc7..4ec469d5d 100644 --- a/Frontend/IntegrationTests/test/dev/vale/ImportTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/ImportTests.scala @@ -4,7 +4,7 @@ import dev.vale.passmanager.FullCompilationOptions import dev.vale.finalast._ import dev.vale.von.VonInt import dev.vale.{finalast => m} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.List diff --git a/Frontend/IntegrationTests/test/dev/vale/InferTemplateTests.scala b/Frontend/IntegrationTests/test/dev/vale/InferTemplateTests.scala index de1cb5924..ce29da296 100644 --- a/Frontend/IntegrationTests/test/dev/vale/InferTemplateTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/InferTemplateTests.scala @@ -7,7 +7,7 @@ import dev.vale.typing.types._ import dev.vale.typing.templata.simpleName import dev.vale.typing.types.StructTT import dev.vale.von.VonInt -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class InferTemplateTests extends FunSuite with Matchers { test("Test inferring a borrowed argument") { diff --git a/Frontend/IntegrationTests/test/dev/vale/IntegrationTestsA.scala b/Frontend/IntegrationTests/test/dev/vale/IntegrationTestsA.scala index 0b2a0a0a3..d747d4a3b 100644 --- a/Frontend/IntegrationTests/test/dev/vale/IntegrationTestsA.scala +++ b/Frontend/IntegrationTests/test/dev/vale/IntegrationTestsA.scala @@ -18,7 +18,7 @@ import java.io.FileNotFoundException import dev.vale.typing.ast import dev.vale.{finalast => m} import dev.vale.testvm.ReferenceV -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import dev.vale.passmanager.FullCompilation import dev.vale.finalast.IdH import dev.vale.instantiating.ast.HinputsI @@ -109,8 +109,6 @@ class RunCompilation( } class IntegrationTestsA extends FunSuite with Matchers { - - // test("Scratch scratch") { // val compile = // RunCompilation.test( diff --git a/Frontend/IntegrationTests/test/dev/vale/OptTests.scala b/Frontend/IntegrationTests/test/dev/vale/OptTests.scala index eaf80b76d..261fdb727 100644 --- a/Frontend/IntegrationTests/test/dev/vale/OptTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/OptTests.scala @@ -4,7 +4,7 @@ import dev.vale.typing.env.ReferenceLocalVariableT import dev.vale.typing._ import dev.vale.typing.types._ import dev.vale.von.VonInt -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class OptTests extends FunSuite with Matchers { test("Test empty and get for Some") { diff --git a/Frontend/IntegrationTests/test/dev/vale/OwnershipTests.scala b/Frontend/IntegrationTests/test/dev/vale/OwnershipTests.scala index 37101b248..d8d657fcf 100644 --- a/Frontend/IntegrationTests/test/dev/vale/OwnershipTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/OwnershipTests.scala @@ -12,7 +12,7 @@ import dev.vale.typing._ import dev.vale.typing.ast._ import dev.vale.typing.templata.functionName import dev.vale.typing.types._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import dev.vale.von.VonInt class OwnershipTests extends FunSuite with Matchers { diff --git a/Frontend/IntegrationTests/test/dev/vale/PackTests.scala b/Frontend/IntegrationTests/test/dev/vale/PackTests.scala index 6d71288eb..c1f1aca03 100644 --- a/Frontend/IntegrationTests/test/dev/vale/PackTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/PackTests.scala @@ -2,7 +2,7 @@ package dev.vale //import dev.vale.typingpass.types.{IntT, PackTT} import dev.vale.typing.ast.TupleTE import dev.vale.von.VonInt -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class PackTests extends FunSuite with Matchers { test("Extract seq") { diff --git a/Frontend/IntegrationTests/test/dev/vale/PatternTests.scala b/Frontend/IntegrationTests/test/dev/vale/PatternTests.scala index 2ab9227b8..723d17e28 100644 --- a/Frontend/IntegrationTests/test/dev/vale/PatternTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/PatternTests.scala @@ -10,7 +10,7 @@ import dev.vale.typing.ast.{NormalStructMemberT, ReferenceMemberTypeT} import dev.vale.typing.names.{IdT, KindPlaceholderNameT, KindPlaceholderTemplateNameT, StructNameT, StructTemplateNameT} import dev.vale.typing.types.IntT import dev.vale.von.VonInt -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class PatternTests extends FunSuite with Matchers { // To get something like this to work would be rather involved. diff --git a/Frontend/IntegrationTests/test/dev/vale/PrintTests.scala b/Frontend/IntegrationTests/test/dev/vale/PrintTests.scala index e933b3cc0..2df0a9ee7 100644 --- a/Frontend/IntegrationTests/test/dev/vale/PrintTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/PrintTests.scala @@ -1,6 +1,6 @@ package dev.vale -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class PrintTests extends FunSuite with Matchers { test("Println'ing an int") { diff --git a/Frontend/IntegrationTests/test/dev/vale/PureFunctionTests.scala b/Frontend/IntegrationTests/test/dev/vale/PureFunctionTests.scala index 1fe8cd0f8..fdee2624c 100644 --- a/Frontend/IntegrationTests/test/dev/vale/PureFunctionTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/PureFunctionTests.scala @@ -7,7 +7,7 @@ import dev.vale.typing.types.StrT import dev.vale.testvm.StructInstanceV import dev.vale.von.VonInt import dev.vale.{finalast => m} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class PureFunctionTests extends FunSuite with Matchers { test("Simple pure function") { diff --git a/Frontend/IntegrationTests/test/dev/vale/ResultTests.scala b/Frontend/IntegrationTests/test/dev/vale/ResultTests.scala index c75304006..38a4cf60f 100644 --- a/Frontend/IntegrationTests/test/dev/vale/ResultTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/ResultTests.scala @@ -2,7 +2,7 @@ package dev.vale import dev.vale.testvm.PanicException import dev.vale.von.{VonInt, VonStr} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class ResultTests extends FunSuite with Matchers { test("Test borrow is_ok and expect for Ok") { diff --git a/Frontend/IntegrationTests/test/dev/vale/StringTests.scala b/Frontend/IntegrationTests/test/dev/vale/StringTests.scala index 82eb418a8..a3cce84f2 100644 --- a/Frontend/IntegrationTests/test/dev/vale/StringTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/StringTests.scala @@ -3,7 +3,7 @@ package dev.vale import dev.vale.typing.ast.ConstantStrTE import dev.vale.typing._ import dev.vale.von.{VonInt, VonStr} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class StringTests extends FunSuite with Matchers { test("Simple string") { diff --git a/Frontend/IntegrationTests/test/dev/vale/StructTests.scala b/Frontend/IntegrationTests/test/dev/vale/StructTests.scala index 8d27d2297..d3395f1ec 100644 --- a/Frontend/IntegrationTests/test/dev/vale/StructTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/StructTests.scala @@ -2,7 +2,7 @@ package dev.vale import dev.vale.testvm.PanicException import dev.vale.von.VonInt -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class StructTests extends FunSuite with Matchers { test("Make empty imm struct") { @@ -99,6 +99,24 @@ class StructTests extends FunSuite with Matchers { compile.evalForKind(Vector()) match { case VonInt(7) => } } + test("Ignore destructure") { + val compile = RunCompilation.test( + """ + |struct Marine { + | hp int; + |} + |exported func main() int { + | m = Marine(4); + | Marine[_] = m; + | return 42; + |} + """.stripMargin) + + compile.evalForKind(Vector()) match { + case VonInt(42) => + } + } + test("Sugar destructure") { val compile = RunCompilation.test( """ diff --git a/Frontend/IntegrationTests/test/dev/vale/TupleTests.scala b/Frontend/IntegrationTests/test/dev/vale/TupleTests.scala index 94a927044..705440fea 100644 --- a/Frontend/IntegrationTests/test/dev/vale/TupleTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/TupleTests.scala @@ -4,7 +4,7 @@ import dev.vale.typing.ast.TupleTE import dev.vale.typing.types.IntT import dev.vale.typing._ import dev.vale.von.{VonBool, VonInt} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class TupleTests extends FunSuite with Matchers { test("Returning tuple from function and dotting it") { diff --git a/Frontend/IntegrationTests/test/dev/vale/VirtualTests.scala b/Frontend/IntegrationTests/test/dev/vale/VirtualTests.scala index 6af17c51d..205c3ed1b 100644 --- a/Frontend/IntegrationTests/test/dev/vale/VirtualTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/VirtualTests.scala @@ -10,7 +10,7 @@ import dev.vale.typing.ast._ import dev.vale.typing.templata.ITemplataT.{expectCoord, expectCoordTemplata} import dev.vale.typing.types._ import dev.vale.von.{VonInt, VonStr} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class VirtualTests extends FunSuite with Matchers { diff --git a/Frontend/IntegrationTests/test/dev/vale/WeakTests.scala b/Frontend/IntegrationTests/test/dev/vale/WeakTests.scala index df0f8f44f..e0c4f0548 100644 --- a/Frontend/IntegrationTests/test/dev/vale/WeakTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/WeakTests.scala @@ -13,7 +13,7 @@ import dev.vale.typing.ast._ import dev.vale.typing.names.CodeVarNameT import dev.vale.typing.types._ import dev.vale.von.VonInt -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class WeakTests extends FunSuite with Matchers { test("Make and lock weak ref then destroy own, with struct") { diff --git a/Frontend/IntegrationTests/test/dev/vale/WhileTests.scala b/Frontend/IntegrationTests/test/dev/vale/WhileTests.scala index 972aace49..0907f4ba7 100644 --- a/Frontend/IntegrationTests/test/dev/vale/WhileTests.scala +++ b/Frontend/IntegrationTests/test/dev/vale/WhileTests.scala @@ -1,7 +1,7 @@ package dev.vale import dev.vale.von.VonInt -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class WhileTests extends FunSuite with Matchers { test("Simple while loop that doesnt execute") { diff --git a/Frontend/ParsingPass/src/dev/vale/parsing/StringParserTests.scala b/Frontend/ParsingPass/src/dev/vale/parsing/StringParserTests.scala index 3c8e99caf..c63fb7d0b 100644 --- a/Frontend/ParsingPass/src/dev/vale/parsing/StringParserTests.scala +++ b/Frontend/ParsingPass/src/dev/vale/parsing/StringParserTests.scala @@ -4,8 +4,9 @@ import dev.vale.lexing.{Lexer, LexingIterator} import dev.vale.parsing.ast._ import dev.vale.{Collector, Interner, Keywords, StrI, vimpl} import dev.vale.parsing.ast.{ConstantIntPE, ConstantStrPE, FunctionCallPE, LookupNameP, LookupPE, NameP, StrInterpolatePE} -import org.scalatest.FunSuite import org.scalatest.Matchers.convertToAnyShouldWrapper +import org.scalatest._ +import org.scalatest._ class StringParserTests extends FunSuite with Collector with TestParseUtils { test("Simple string") { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/AfterRegionsTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/AfterRegionsTests.scala index e1799c0d7..3eaef5ab6 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/AfterRegionsTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/AfterRegionsTests.scala @@ -3,7 +3,7 @@ package dev.vale.parsing import dev.vale.lexing.{BadExpressionEnd, BadStartOfStatementError, ForgotSetKeyword} import dev.vale.parsing.ast._ import dev.vale.{Collector, StrI} -import org.scalatest.FunSuite +import org.scalatest._ class AfterRegionsTests extends FunSuite with Collector with TestParseUtils { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/ExpressionTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/ExpressionTests.scala index b41b44869..bff67997a 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/ExpressionTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/ExpressionTests.scala @@ -3,7 +3,7 @@ package dev.vale.parsing import dev.vale.{Collector, StrI} import dev.vale.lexing.{CantUseThatLocalName, CantUseBreakInExpression, CantUseReturnInExpression} import dev.vale.parsing.ast._ -import org.scalatest.FunSuite +import org.scalatest._ class ExpressionTests extends FunSuite with Collector with TestParseUtils { test("Simple int") { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/IfTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/IfTests.scala index ad49439b6..98e455fc4 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/IfTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/IfTests.scala @@ -4,7 +4,7 @@ import dev.vale.{Collector, StrI, vimpl} import dev.vale.parsing.ast.{AugmentPE, BinaryCallPE, BlockPE, BorrowP, ConsecutorPE, ConstantBoolPE, ConstantIntPE, DestructureP, FunctionCallPE, IfPE, LetPE, LocalNameDeclarationP, LookupNameP, LookupPE, MethodCallPE, NameP, NotPE, PatternPP, VoidPE} import dev.vale.parsing.ast._ import dev.vale.options.GlobalOptions -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class IfTests extends FunSuite with Matchers with Collector with TestParseUtils { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/ImplTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/ImplTests.scala index a34edb1be..d65f4754c 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/ImplTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/ImplTests.scala @@ -4,7 +4,7 @@ import dev.vale.lexing.Lexer import dev.vale.{Collector, Interner, StrI, vassertOne, vimpl} import dev.vale.parsing.ast.{CallPT, IDenizenP, GenericParameterP, GenericParametersP, ImplP, MutabilityPT, MutableP, NameOrRunePT, NameP, TopLevelImplP} import dev.vale.options.GlobalOptions -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class ImplTests extends FunSuite with Matchers with Collector with TestParseUtils { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/LoadTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/LoadTests.scala index dfb6d10bf..bce98781f 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/LoadTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/LoadTests.scala @@ -7,7 +7,7 @@ import dev.vale.{Collector, Interner, Keywords, vassert, vimpl} import net.liftweb.json._ import dev.vale.parsing.ast.ConstantStrPE import dev.vale.von.{JsonSyntax, VonPrinter} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import java.nio.charset.Charset diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/ParseSamplesTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/ParseSamplesTests.scala index b467a9757..52b27ea20 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/ParseSamplesTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/ParseSamplesTests.scala @@ -2,7 +2,7 @@ package dev.vale.parsing import dev.vale.{Collector, Err, Interner, Keywords, Ok, Tests, vfail} import dev.vale.options.GlobalOptions -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/StatementTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/StatementTests.scala index b1cc94bab..8d7e6832e 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/StatementTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/StatementTests.scala @@ -5,7 +5,7 @@ import dev.vale.parsing.ast.{AugmentPE, BlockPE, BorrowP, ConsecutorPE, Constant import dev.vale.parsing.ast._ import dev.vale.lexing.{CantUseThatLocalName, BadExpressionEnd, BadStartOfStatementError, ForgotSetKeyword} import dev.vale.options.GlobalOptions -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class StatementTests extends FunSuite with Collector with TestParseUtils { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/StructTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/StructTests.scala index b2993cf10..bfa7e8f99 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/StructTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/StructTests.scala @@ -5,7 +5,7 @@ import dev.vale.options.GlobalOptions import dev.vale.{Collector, FileCoordinate, FileCoordinateMap, IPackageResolver, Interner, PackageCoordinate, StrI, vassertOne, vassertSome} import dev.vale.parsing.ast.{BorrowP, CallPT, ExportAttributeP, FinalP, GenericParameterP, GenericParametersP, ImmutableP, IntTypePR, InterpretedPT, MutabilityPT, MutableP, NameOrRunePT, NameP, NormalStructMemberP, OwnP, RuntimeSizedArrayPT, ShareP, StaticSizedArrayPT, StructMembersP, StructP, TemplateRulesP, TopLevelStructP, TypedPR, VariabilityPT, VariadicStructMemberP, VaryingP, WeakP} import dev.vale.parsing.ast._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class StructTests extends FunSuite with Collector with TestParseUtils { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/TopLevelTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/TopLevelTests.scala index 472cadba5..98250a791 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/TopLevelTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/TopLevelTests.scala @@ -4,7 +4,7 @@ import dev.vale.{Collector, Interner, StrI, vassertOne, vassertSome} import dev.vale.parsing.ast.{BlockPE, CallPT, ExportAsP, FileP, FunctionP, ImportP, NameOrRunePT, NameP, RegionRunePT, TopLevelExportAsP, TopLevelFunctionP, TopLevelImportP, TopLevelStructP, VoidPE} import dev.vale.lexing.{BadStartOfStatementError, IParseError, Lexer, UnrecognizedDenizenError} import dev.vale.options.GlobalOptions -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/WhileTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/WhileTests.scala index 179684ffd..d8f9fa6b7 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/WhileTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/WhileTests.scala @@ -4,7 +4,7 @@ import dev.vale.{Collector, Interner, StrI} import dev.vale.parsing.ast._ import dev.vale.lexing.{Lexer, LexingIterator} import dev.vale.options.GlobalOptions -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class WhileTests extends FunSuite with Collector with TestParseUtils { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/functions/AfterRegionsFunctionTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/functions/AfterRegionsFunctionTests.scala index 8a98101a2..3d239faff 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/functions/AfterRegionsFunctionTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/functions/AfterRegionsFunctionTests.scala @@ -4,7 +4,7 @@ import dev.vale.lexing.{BadFunctionBodyError, LightFunctionMustHaveParamTypes} import dev.vale.parsing._ import dev.vale.parsing.ast._ import dev.vale.{Collector, StrI, vassertOne, vimpl} -import org.scalatest.FunSuite +import org.scalatest._ class AfterRegionsFunctionTests extends FunSuite with Collector with TestParseUtils { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/functions/FunctionTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/functions/FunctionTests.scala index a951702c8..1d3b71ac1 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/functions/FunctionTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/functions/FunctionTests.scala @@ -4,8 +4,8 @@ import dev.vale.{Collector, StrI, vassertOne, vimpl} import dev.vale.parsing.ast._ import dev.vale.parsing._ import dev.vale.lexing.{BadFunctionBodyError, LightFunctionMustHaveParamTypes} -import org.scalatest.Matchers.convertToAnyShouldWrapper -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ +import org.scalatest._ class FunctionTests extends FunSuite with Collector with TestParseUtils { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/patterns/CaptureAndDestructureTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/patterns/CaptureAndDestructureTests.scala index f4d2f4458..a697aade4 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/patterns/CaptureAndDestructureTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/patterns/CaptureAndDestructureTests.scala @@ -5,7 +5,7 @@ import dev.vale.parsing.ast.{DestinationLocalP, DestructureP, LocalNameDeclarati import dev.vale.parsing._ import dev.vale.parsing.ast.Patterns.capturedWithType import dev.vale.parsing.ast.{DestructureP, LocalNameDeclarationP, NameOrRunePT, NameP, PatternPP, TuplePT} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class CaptureAndDestructureTests extends FunSuite with Matchers with Collector with TestParseUtils { private def compile[T](code: String): PatternPP = { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/patterns/CaptureAndTypeTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/patterns/CaptureAndTypeTests.scala index 680e81a81..13280c745 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/patterns/CaptureAndTypeTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/patterns/CaptureAndTypeTests.scala @@ -6,7 +6,7 @@ import dev.vale.parsing.ast.Patterns.{capturedWithType, capturedWithTypeRune} import dev.vale.parsing._ import dev.vale.parsing.ast._ import dev.vale.Collector -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class CaptureAndTypeTests extends FunSuite with Matchers with Collector with TestParseUtils { // private def compile[T](parser: CombinatorParsers.Parser[T], code: String): T = { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/patterns/DestructureParserTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/patterns/DestructureParserTests.scala index 3efb05a1f..215594739 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/patterns/DestructureParserTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/patterns/DestructureParserTests.scala @@ -5,7 +5,7 @@ import dev.vale.parsing.ast.{DestinationLocalP, DestructureP, IgnoredLocalNameDe import dev.vale.parsing.ast.Patterns._ import dev.vale.parsing._ import dev.vale.Collector -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class DestructureParserTests extends FunSuite with Matchers with Collector with TestParseUtils { private def compile[T](code: String): PatternPP = { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/patterns/PatternParserTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/patterns/PatternParserTests.scala index 3975b5fc0..7142cb1df 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/patterns/PatternParserTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/patterns/PatternParserTests.scala @@ -6,7 +6,7 @@ import dev.vale.parsing.ast.{AbstractP, DestructureP, IgnoredLocalNameDeclaratio import dev.vale.parsing.ast.Patterns._ import dev.vale.parsing._ import dev.vale.parsing.ast._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class PatternParserTests extends FunSuite with Matchers with Collector with TestParseUtils { private def compile[T](code: String): PatternPP = { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/patterns/TypeAndDestructureTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/patterns/TypeAndDestructureTests.scala index 5448138ca..2c174884e 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/patterns/TypeAndDestructureTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/patterns/TypeAndDestructureTests.scala @@ -5,7 +5,7 @@ import dev.vale.parsing.ast.{CallPT, DestinationLocalP, DestructureP, IgnoredLoc import dev.vale.parsing.ast.Patterns._ import dev.vale.parsing._ import dev.vale.Collector -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class TypeAndDestructureTests extends FunSuite with Matchers with Collector with TestParseUtils { private def compile[T](code: String): PatternPP = { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/patterns/TypeTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/patterns/TypeTests.scala index 10c49d76a..b1f6be16a 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/patterns/TypeTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/patterns/TypeTests.scala @@ -6,7 +6,7 @@ import dev.vale.parsing.ast.{AnonymousRunePT, BorrowP, CallPT, FinalP, IgnoredLo import dev.vale.parsing.ast.Patterns.{fromEnv, withType} import dev.vale.parsing._ import dev.vale.parsing.ast._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class TypeTests extends FunSuite with Matchers with Collector with TestParseUtils { private def compile[T](code: String): PatternPP = { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/rules/CoordRuleTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/rules/CoordRuleTests.scala index 2fd4f6dd9..44862f5f5 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/rules/CoordRuleTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/rules/CoordRuleTests.scala @@ -5,7 +5,7 @@ import dev.vale.parsing.ast.{AnonymousRunePT, ComponentsPR, CoordTypePR, EqualsP import dev.vale.parsing.templex.TemplexParser import dev.vale.parsing._ import dev.vale.parsing.ast.PatternPP -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class CoordRuleTests extends FunSuite with Matchers with Collector with TestParseUtils { private def compile[T](code: String): IRulexPR = { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/rules/KindRuleTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/rules/KindRuleTests.scala index 3cd933541..833c8a64b 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/rules/KindRuleTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/rules/KindRuleTests.scala @@ -5,7 +5,7 @@ import dev.vale.parsing.ast.{AnonymousRunePT, CallPT, ComponentsPR, EqualsPR, Fi import dev.vale.parsing.templex.TemplexParser import dev.vale.parsing._ import dev.vale.parsing.ast._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class KindRuleTests extends FunSuite with Matchers with Collector with TestParseUtils { private def compile[T](code: String): IRulexPR = { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/rules/RuleTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/rules/RuleTests.scala index 2adbfba4d..537031565 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/rules/RuleTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/rules/RuleTests.scala @@ -6,7 +6,7 @@ import dev.vale.parsing.templex.TemplexParser import dev.vale.parsing._ import dev.vale.parsing.ast.PatternPP import dev.vale.Collector -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class RuleTests extends FunSuite with Matchers with Collector with TestParseUtils { private def compile[T](code: String): IRulexPR = { diff --git a/Frontend/ParsingPass/test/dev/vale/parsing/rules/RulesEnumsTests.scala b/Frontend/ParsingPass/test/dev/vale/parsing/rules/RulesEnumsTests.scala index defcd55e9..e310a61ff 100644 --- a/Frontend/ParsingPass/test/dev/vale/parsing/rules/RulesEnumsTests.scala +++ b/Frontend/ParsingPass/test/dev/vale/parsing/rules/RulesEnumsTests.scala @@ -6,7 +6,7 @@ import dev.vale.parsing.ast.{BorrowP, BuiltinCallPR, EqualsPR, IRulexPR, Immutab import dev.vale.parsing.templex.TemplexParser import dev.vale.parsing._ import dev.vale.parsing.ast._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class RulesEnumsTests extends FunSuite with Matchers with Collector with TestParseUtils { private def compile[T](code: String): IRulexPR = { diff --git a/Frontend/PostParsingPass/test/dev/vale/postparsing/AfterRegionsErrorTests.scala b/Frontend/PostParsingPass/test/dev/vale/postparsing/AfterRegionsErrorTests.scala index 04d3dbe9a..f07c084f2 100644 --- a/Frontend/PostParsingPass/test/dev/vale/postparsing/AfterRegionsErrorTests.scala +++ b/Frontend/PostParsingPass/test/dev/vale/postparsing/AfterRegionsErrorTests.scala @@ -5,7 +5,7 @@ import dev.vale.postparsing.patterns.{AtomSP, CaptureS} import dev.vale.postparsing.rules.{LiteralSR, MaybeCoercingLookupSR, MutabilityLiteralSL, RuneUsage} import dev.vale.solver.IncompleteSolve import dev.vale._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class AfterRegionsErrorTests extends FunSuite with Matchers with Collector { diff --git a/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParserErrorHumanizerTests.scala b/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParserErrorHumanizerTests.scala index ab9aaa523..517802d4a 100644 --- a/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParserErrorHumanizerTests.scala +++ b/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParserErrorHumanizerTests.scala @@ -4,7 +4,7 @@ import dev.vale.{CodeLocationS, Err, FileCoordinateMap, Interner, Ok, RangeS, So import dev.vale.options.GlobalOptions import dev.vale.parsing._ import dev.vale.postparsing.rules._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class PostParserErrorHumanizerTests extends FunSuite with Matchers { diff --git a/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParserTests.scala b/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParserTests.scala index a2cf65f30..a90647818 100644 --- a/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParserTests.scala +++ b/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParserTests.scala @@ -11,7 +11,7 @@ import dev.vale.parsing.ast._ import dev.vale.postparsing.patterns._ import dev.vale.postparsing.rules._ import dev.vale.solver.IncompleteSolve -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class PostParserTests extends FunSuite with Matchers with Collector { diff --git a/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParserVariableTests.scala b/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParserVariableTests.scala index 108db2808..b099774b9 100644 --- a/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParserVariableTests.scala +++ b/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParserVariableTests.scala @@ -3,7 +3,7 @@ package dev.vale.postparsing import dev.vale.{Collector, Err, FileCoordinateMap, Interner, Ok, SourceCodeUtils, StrI, vassert, vfail} import dev.vale.options.GlobalOptions import dev.vale.parsing.Parser -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.runtime.Nothing$ diff --git a/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParsingParametersTests.scala b/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParsingParametersTests.scala index d6ce7ff51..3939ded30 100644 --- a/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParsingParametersTests.scala +++ b/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParsingParametersTests.scala @@ -9,7 +9,7 @@ import dev.vale.parsing._ import dev.vale.parsing.ast._ import dev.vale.postparsing.patterns.AtomSP import dev.vale.postparsing.rules._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class PostParsingParametersTests extends FunSuite with Matchers with Collector { diff --git a/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParsingRuleTests.scala b/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParsingRuleTests.scala index 7514b71a2..098ae3aa4 100644 --- a/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParsingRuleTests.scala +++ b/Frontend/PostParsingPass/test/dev/vale/postparsing/PostParsingRuleTests.scala @@ -4,7 +4,7 @@ import dev.vale.{Err, FileCoordinateMap, Interner, Ok, RangeS, SourceCodeUtils, import dev.vale.options.GlobalOptions import dev.vale.parsing._ import dev.vale.postparsing._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.List diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hamuts.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hamuts.scala index cc74ad16c..16c81d908 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hamuts.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/Hamuts.scala @@ -130,17 +130,16 @@ case class Hamuts( def addStructOriginatingFromTypingPass(structTT: StructIT[cI], structDefH: StructDefinitionH): Hamuts = { vassert(structTToStructH.contains(structTT)) - structTToStructDefH.get(structTT) match { - case Some(existingDef) => { - // DO NOT SUBMIT - // Added all this to help VmdSiteGen. Apparently it calls this method twice with the same structs sometimes? - vassert(existingDef.id == structDefH.id) - vassert(existingDef.members.map(_.name) == structDefH.members.map(_.name)) - vassert(existingDef.members.map(_.tyype) == structDefH.members.map(_.tyype)) - vassert(structDefs.exists(_.id == structDefH.id)) - this - } - case None => { + // structTToStructDefH.get(structTT) match { + // case Some(existingDef) => { + // // Added all this to help VmdSiteGen. Apparently it calls this method twice with the same structs sometimes? + // vassert(existingDef.id == structDefH.id) + // vassert(existingDef.members.map(_.name) == structDefH.members.map(_.name)) + // vassert(existingDef.members.map(_.tyype) == structDefH.members.map(_.tyype)) + // vassert(structDefs.exists(_.id == structDefH.id)) + // this + // } + // case None => { Hamuts( humanNameToFullNameToId, structTToStructH, @@ -156,8 +155,8 @@ case class Hamuts( packageCoordToExportNameToKind, packageCoordToExternNameToFunction, packageCoordToExternNameToKind) - } - } + // } + // } } def addStructOriginatingFromHammer(structDefH: StructDefinitionH): Hamuts = { diff --git a/Frontend/SimplifyingPass/src/dev/vale/simplifying/TypeHammer.scala b/Frontend/SimplifyingPass/src/dev/vale/simplifying/TypeHammer.scala index 0b1d1f13c..f4808ee4f 100644 --- a/Frontend/SimplifyingPass/src/dev/vale/simplifying/TypeHammer.scala +++ b/Frontend/SimplifyingPass/src/dev/vale/simplifying/TypeHammer.scala @@ -102,8 +102,12 @@ class TypeHammer( val variability = Conversions.evaluateVariabilityTemplata(variabilityI) val size = ssaIT.size val definition = StaticSizedArrayDefinitionHT(name, size, mutability, variability, memberReferenceH) - hamuts.addStaticSizedArray(ssaIT, definition) - StaticSizedArrayHT(name) + val result = StaticSizedArrayHT(name) + hamuts.staticSizedArrays.find(_._2.kind == result) match { + case Some(x) => vwat(x) + case None => hamuts.addStaticSizedArray(ssaIT, definition) + } + result } } } @@ -120,11 +124,8 @@ class TypeHammer( // val variability = Conversions.evaluateVariability(variabilityI) val definition = RuntimeSizedArrayDefinitionHT(nameH, mutability, memberReferenceH) val result = RuntimeSizedArrayHT(nameH) - // DO NOT SUBMIT a few options: - // - do this for SSAs too - // - nuke the way we were doing names for hamuts, make proper names finally hamuts.runtimeSizedArrays.values.find(_.kind == result) match { - case Some(x) => + case Some(x) => vwat(x) case None => hamuts.addRuntimeSizedArray(rsaIT, definition) } result diff --git a/Frontend/SimplifyingPass/test/dev/vale/simplifying/HammerTest.scala b/Frontend/SimplifyingPass/test/dev/vale/simplifying/HammerTest.scala index 00add2ff0..34932a5dd 100644 --- a/Frontend/SimplifyingPass/test/dev/vale/simplifying/HammerTest.scala +++ b/Frontend/SimplifyingPass/test/dev/vale/simplifying/HammerTest.scala @@ -6,7 +6,7 @@ import dev.vale.parsing.ast.FileP import dev.vale.highertyping.ICompileErrorA import dev.vale.Result import dev.vale.typing._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import dev.vale.finalast.VariableIdH import dev.vale.postparsing.ICompileErrorS diff --git a/Frontend/Solver/test/dev/vale/solver/SolverTests.scala b/Frontend/Solver/test/dev/vale/solver/SolverTests.scala index fc5eaf469..7acef87d2 100644 --- a/Frontend/Solver/test/dev/vale/solver/SolverTests.scala +++ b/Frontend/Solver/test/dev/vale/solver/SolverTests.scala @@ -1,7 +1,7 @@ package dev.vale.solver import dev.vale.{Collector, Err, Interner, Ok, RangeS, vassert, vfail} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.Map diff --git a/Frontend/Solver/test/dev/vale/solver/TestRuleSolver.scala b/Frontend/Solver/test/dev/vale/solver/TestRuleSolver.scala index 0bfa3cc80..de9228701 100644 --- a/Frontend/Solver/test/dev/vale/solver/TestRuleSolver.scala +++ b/Frontend/Solver/test/dev/vale/solver/TestRuleSolver.scala @@ -1,7 +1,7 @@ package dev.vale.solver import dev.vale.{Err, Interner, Ok, RangeS, Result, vassert, vassertSome, vfail, vimpl, vwat} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.Map diff --git a/Frontend/Solver/test/dev/vale/solver/TestRules.scala b/Frontend/Solver/test/dev/vale/solver/TestRules.scala index 62ed901ad..377936971 100644 --- a/Frontend/Solver/test/dev/vale/solver/TestRules.scala +++ b/Frontend/Solver/test/dev/vale/solver/TestRules.scala @@ -1,7 +1,7 @@ package dev.vale.solver import dev.vale.Err -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.Map diff --git a/Frontend/TestVM/src/dev/vale/testvm/FunctionVivem.scala b/Frontend/TestVM/src/dev/vale/testvm/FunctionVivem.scala index 800f4dec8..d030f0419 100644 --- a/Frontend/TestVM/src/dev/vale/testvm/FunctionVivem.scala +++ b/Frontend/TestVM/src/dev/vale/testvm/FunctionVivem.scala @@ -54,7 +54,7 @@ object FunctionVivem { // of pulling it all in as one giant namespace. In that case, it prefixes things such as // v::builtins::arith. We can add other prefixes here too as needed. .replaceAllLiterally("v::builtins::arith", "") match { - case """__vbi_addI32(i32, i32)""" => VivemExterns.addI32 + case """__vbi_addI32""" => VivemExterns.addI32 case """__vbi_addFloatFloat""" => VivemExterns.addFloatFloat case """__vbi_panic""" => VivemExterns.panic case """__vbi_multiplyI32""" => VivemExterns.multiplyI32 diff --git a/Frontend/TestVM/test/dev/vale/testvm/VivemTests.scala b/Frontend/TestVM/test/dev/vale/testvm/VivemTests.scala index 79e59428c..e85021679 100644 --- a/Frontend/TestVM/test/dev/vale/testvm/VivemTests.scala +++ b/Frontend/TestVM/test/dev/vale/testvm/VivemTests.scala @@ -4,7 +4,7 @@ import dev.vale.{Interner, Keywords, PackageCoordinate, PackageCoordinateMap, St import dev.vale.finalast._ import dev.vale.finalast._ import dev.vale.von.{VonArray, VonInt, VonMember, VonObject, VonStr} -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class VivemTests extends FunSuite with Matchers { test("Return 7") { @@ -41,10 +41,10 @@ class VivemTests extends FunSuite with Matchers { val addPrototype = PrototypeH( IdH( - "__vbi_addI32(i32, i32)", + "__vbi_addI32", PackageCoordinate.BUILTIN(interner, keywords), - "__vbi_addI32(i32, i32)", - "__vbi_addI32(i32, i32)"), + "__vbi_addI32", + "__vbi_addI32"), Vector(CoordH(MutableShareH,InlineH,IntHT.i32), CoordH(MutableShareH,InlineH,IntHT.i32)), CoordH(MutableShareH,InlineH,IntHT.i32)) val main = diff --git a/Frontend/TypingPass/src/dev/vale/typing/Compiler.scala b/Frontend/TypingPass/src/dev/vale/typing/Compiler.scala index 1670cca37..7569dc90a 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/Compiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/Compiler.scala @@ -577,10 +577,11 @@ class Compiler( nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, ranges: List[RangeS], + callLocation: LocationInDenizen, patterns1: Vector[AtomSP], patternInputExprs2: Vector[ReferenceExpressionTE] ): ReferenceExpressionTE = { - expressionCompiler.translatePatternList(coutputs, nenv, life, ranges, patterns1, patternInputExprs2) + expressionCompiler.translatePatternList(coutputs, nenv, life, ranges, callLocation, patterns1, patternInputExprs2) } // override def evaluateParent(env: IEnvironment, coutputs: CompilerOutputs, callRange: List[RangeS], sparkHeader: FunctionHeaderT): Unit = { @@ -869,7 +870,7 @@ class Compiler( coutputs, exportEnv, List(structA.range), LocationInDenizen(Vector()), templata, Vector()) match { case ResolveSuccess(kind) => kind case ResolveFailure(range, reason) => { - vimpl() // DO NOT SUBMIT + throw CompileErrorExceptionT(CouldntEvaluateStruct(range, reason)) } } @@ -910,7 +911,7 @@ class Compiler( coutputs, exportEnv, List(interfaceA.range), LocationInDenizen(Vector()), templata, Vector()) match { case ResolveSuccess(kind) => kind case ResolveFailure(range, reason) => { - vimpl() // DO NOT SUBMIT + throw CompileErrorExceptionT(CouldntEvaluateInterface(range, reason)) } } diff --git a/Frontend/TypingPass/src/dev/vale/typing/CompilerErrorReporter.scala b/Frontend/TypingPass/src/dev/vale/typing/CompilerErrorReporter.scala index bf4cf39b1..2c45459f2 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/CompilerErrorReporter.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/CompilerErrorReporter.scala @@ -82,6 +82,14 @@ case class CouldntEvaluatImpl(range: List[RangeS], eff: IIncompleteOrFailedCompi override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() vpass() } +case class CouldntEvaluateStruct(range: List[RangeS], eff: IIncompleteOrFailedCompilerSolve) extends ICompileErrorT { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + vpass() +} +case class CouldntEvaluateInterface(range: List[RangeS], eff: IIncompleteOrFailedCompilerSolve) extends ICompileErrorT { + override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() + vpass() +} case class CouldntFindOverrideT(range: List[RangeS], fff: FindFunctionFailure) extends ICompileErrorT { override def equals(obj: Any): Boolean = vcurious(); override def hashCode(): Int = vcurious() vpass() diff --git a/Frontend/TypingPass/src/dev/vale/typing/expression/ExpressionCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/expression/ExpressionCompiler.scala index 040a21fce..8d69611e4 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/expression/ExpressionCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/expression/ExpressionCompiler.scala @@ -435,7 +435,9 @@ class ExpressionCompiler( nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, parentRanges: List[RangeS], - callLocation: LocationInDenizen, // DO NOT SUBMIT rename this, it conflicts with some introduced ones below + // Called outer because there are other calls below that come with their own call locations. + // We should probably figure out how to make life, parentRanges, and callLocations into one unified thing. + outerCallLocation: LocationInDenizen, expr1: IExpressionSE): (ExpressionT, Set[CoordT]) = { Profiler.frame(() => { @@ -507,7 +509,7 @@ class ExpressionCompiler( case OwnershippedSE(range, sourceSE, loadAsP) => { val (sourceTE, returnsFromInner) = evaluateAndCoerceToReferenceExpression( - coutputs, nenv, life + 0, parentRanges, callLocation, sourceSE); + coutputs, nenv, life + 0, parentRanges, outerCallLocation, sourceSE); val resultExpr2 = sourceTE.result.underlyingCoord.ownership match { case OwnT => { @@ -517,10 +519,10 @@ class ExpressionCompiler( sourceTE } case LoadAsBorrowP => { - localHelper.makeTemporaryLocal(coutputs, nenv, range :: parentRanges, callLocation, life + 1, sourceTE, BorrowT) + localHelper.makeTemporaryLocal(coutputs, nenv, range :: parentRanges, outerCallLocation, life + 1, sourceTE, BorrowT) } case LoadAsWeakP => { - val expr = localHelper.makeTemporaryLocal(coutputs, nenv, range :: parentRanges, callLocation, life + 3, sourceTE, BorrowT) + val expr = localHelper.makeTemporaryLocal(coutputs, nenv, range :: parentRanges, outerCallLocation, life + 3, sourceTE, BorrowT) weakAlias(coutputs, expr) } case UseP => vcurious() @@ -564,7 +566,7 @@ class ExpressionCompiler( case LocalLoadSE(range, nameA, targetOwnership) => { val name = nameTranslator.translateVarNameStep(nameA) val lookupExpr1 = - evaluateLookupForLoad(coutputs, nenv, range :: parentRanges, callLocation, name, targetOwnership) match { + evaluateLookupForLoad(coutputs, nenv, range :: parentRanges, outerCallLocation, name, targetOwnership) match { case (None) => { throw CompileErrorExceptionT(RangedInternalErrorT(range :: parentRanges, "Couldnt find " + name)) } @@ -606,7 +608,7 @@ class ExpressionCompiler( case LocalMutateSE(range, name, sourceExpr1) => { val (unconvertedSourceExpr2, returnsFromSource) = evaluateAndCoerceToReferenceExpression( - coutputs, nenv, life, parentRanges, callLocation, sourceExpr1) + coutputs, nenv, life, parentRanges, outerCallLocation, sourceExpr1) // We do this after the source because of statements like these: // set ship = foo(ship); @@ -625,7 +627,7 @@ class ExpressionCompiler( val isConvertible = templataCompiler.isTypeConvertible( - coutputs, nenv.snapshot, range :: parentRanges, callLocation, unconvertedSourceExpr2.result.coord, destinationExpr2.result.coord) + coutputs, nenv.snapshot, range :: parentRanges, outerCallLocation, unconvertedSourceExpr2.result.coord, destinationExpr2.result.coord) if (!isConvertible) { throw CompileErrorExceptionT( CouldntConvertForMutateT( @@ -633,7 +635,7 @@ class ExpressionCompiler( } vassert(isConvertible) val convertedSourceExpr2 = - convertHelper.convert(nenv.snapshot, coutputs, range :: parentRanges, callLocation, unconvertedSourceExpr2, destinationExpr2.result.coord); + convertHelper.convert(nenv.snapshot, coutputs, range :: parentRanges, outerCallLocation, unconvertedSourceExpr2, destinationExpr2.result.coord); val exprTE = destinationExpr2 match { @@ -650,9 +652,9 @@ class ExpressionCompiler( } case ExprMutateSE(range, destinationExpr1, sourceExpr1) => { val (unconvertedSourceExpr2, returnsFromSource) = - evaluateAndCoerceToReferenceExpression(coutputs, nenv, life + 0, parentRanges, callLocation, sourceExpr1) + evaluateAndCoerceToReferenceExpression(coutputs, nenv, life + 0, parentRanges, outerCallLocation, sourceExpr1) val (destinationExpr2, returnsFromDestination) = - evaluateExpectedAddressExpression(coutputs, nenv, life + 1, parentRanges, callLocation, destinationExpr1) + evaluateExpectedAddressExpression(coutputs, nenv, life + 1, parentRanges, outerCallLocation, destinationExpr1) if (destinationExpr2.variability != VaryingT) { destinationExpr2 match { case ReferenceMemberLookupTE(range, structExpr, memberName, _, _) => { @@ -674,12 +676,12 @@ class ExpressionCompiler( } val isConvertible = - templataCompiler.isTypeConvertible(coutputs, nenv.snapshot, range :: parentRanges, callLocation, unconvertedSourceExpr2.result.coord, destinationExpr2.result.coord) + templataCompiler.isTypeConvertible(coutputs, nenv.snapshot, range :: parentRanges, outerCallLocation, unconvertedSourceExpr2.result.coord, destinationExpr2.result.coord) if (!isConvertible) { throw CompileErrorExceptionT(CouldntConvertForMutateT(range :: parentRanges, destinationExpr2.result.coord, unconvertedSourceExpr2.result.coord)) } val convertedSourceExpr2 = - convertHelper.convert(nenv.snapshot, coutputs, range :: parentRanges, callLocation, unconvertedSourceExpr2, destinationExpr2.result.coord); + convertHelper.convert(nenv.snapshot, coutputs, range :: parentRanges, outerCallLocation, unconvertedSourceExpr2, destinationExpr2.result.coord); val mutate2 = MutateTE(destinationExpr2, convertedSourceExpr2); (mutate2, returnsFromSource ++ returnsFromDestination) @@ -690,13 +692,13 @@ class ExpressionCompiler( } case IndexSE(range, containerExpr1, indexExpr1) => { val (unborrowedContainerExpr2, returnsFromContainerExpr) = - evaluate(coutputs, nenv, life + 0, parentRanges, callLocation, containerExpr1); + evaluate(coutputs, nenv, life + 0, parentRanges, outerCallLocation, containerExpr1); val containerExpr2 = - dotBorrow(coutputs, nenv, range :: parentRanges, callLocation, life + 1, unborrowedContainerExpr2) + dotBorrow(coutputs, nenv, range :: parentRanges, outerCallLocation, life + 1, unborrowedContainerExpr2) val (indexExpr2, returnsFromIndexExpr) = evaluateAndCoerceToReferenceExpression( - coutputs, nenv, life + 2, parentRanges, callLocation, indexExpr1); + coutputs, nenv, life + 2, parentRanges, outerCallLocation, indexExpr1); val exprTemplata = containerExpr2.result.coord.kind match { @@ -735,9 +737,9 @@ class ExpressionCompiler( case DotSE(range, containerExpr1, memberNameStr, borrowContainer) => { val memberName = interner.intern(CodeVarNameT(memberNameStr)) val (unborrowedContainerExpr2, returnsFromContainerExpr) = - evaluate(coutputs, nenv, life + 0, parentRanges, callLocation, containerExpr1) + evaluate(coutputs, nenv, life + 0, parentRanges, outerCallLocation, containerExpr1) val containerExpr2 = - dotBorrow(coutputs, nenv, range :: parentRanges, callLocation, life + 1, unborrowedContainerExpr2) + dotBorrow(coutputs, nenv, range :: parentRanges, outerCallLocation, life + 1, unborrowedContainerExpr2) val expr2 = containerExpr2.result.coord.kind match { @@ -794,28 +796,28 @@ class ExpressionCompiler( (expr2, returnsFromContainerExpr) } case FunctionSE(functionS @ FunctionS(range, name, _, _, _, _, _, _, _, _)) => { - val callExpr2 = evaluateClosure(coutputs, nenv, range :: parentRanges, callLocation, name, functionS) + val callExpr2 = evaluateClosure(coutputs, nenv, range :: parentRanges, outerCallLocation, name, functionS) (callExpr2, Set()) } case TupleSE(range, elements1) => { val (exprs2, returnsFromElements) = - evaluateAndCoerceToReferenceExpressions(coutputs, nenv, life + 0, parentRanges, callLocation, elements1); + evaluateAndCoerceToReferenceExpressions(coutputs, nenv, life + 0, parentRanges, outerCallLocation, elements1); // would we need a sequence templata? probably right? - val expr2 = sequenceCompiler.evaluate(nenv.snapshot, coutputs, parentRanges, callLocation, exprs2) + val expr2 = sequenceCompiler.evaluate(nenv.snapshot, coutputs, parentRanges, outerCallLocation, exprs2) (expr2, returnsFromElements) } case StaticArrayFromValuesSE(range, rules, maybeElementTypeRuneA, mutabilityRune, variabilityRune, sizeRuneA, elements1) => { val (exprs2, returnsFromElements) = evaluateAndCoerceToReferenceExpressions( - coutputs, nenv, life, parentRanges, callLocation, elements1); + coutputs, nenv, life, parentRanges, outerCallLocation, elements1); // would we need a sequence templata? probably right? val expr2 = arrayCompiler.evaluateStaticSizedArrayFromValues( coutputs, nenv.snapshot, range :: parentRanges, - callLocation, + outerCallLocation, rules.toVector, maybeElementTypeRuneA.map(_.rune), sizeRuneA.rune, @@ -828,13 +830,13 @@ class ExpressionCompiler( case StaticArrayFromCallableSE(range, rules, maybeElementTypeRune, maybeMutabilityRune, maybeVariabilityRune, sizeRuneA, callableAE) => { val (callableTE, returnsFromCallable) = evaluateAndCoerceToReferenceExpression( - coutputs, nenv, life, parentRanges, callLocation, callableAE); + coutputs, nenv, life, parentRanges, outerCallLocation, callableAE); val expr2 = arrayCompiler.evaluateStaticSizedArrayFromCallable( coutputs, nenv.snapshot, range :: parentRanges, - callLocation, + outerCallLocation, rules.toVector, maybeElementTypeRune.map(_.rune), sizeRuneA.rune, @@ -851,7 +853,7 @@ class ExpressionCompiler( nenv, life + 0, parentRanges, - callLocation, + outerCallLocation, sizeAE); val (maybeCallableTE, returnsFromCallable) = maybeCallableAE match { @@ -859,7 +861,7 @@ class ExpressionCompiler( case Some(callableAE) => { val (callableTE, rets) = evaluateAndCoerceToReferenceExpression( - coutputs, nenv, life + 1, parentRanges, callLocation, callableAE); + coutputs, nenv, life + 1, parentRanges, outerCallLocation, callableAE); (Some(callableTE), rets) } } @@ -870,7 +872,7 @@ class ExpressionCompiler( coutputs, nenv.snapshot, range :: parentRanges, - callLocation, + outerCallLocation, rulesA.toVector, maybeElementTypeRune.map(_.rune), mutabilityRune.rune, @@ -882,7 +884,7 @@ class ExpressionCompiler( case LetSE(range, rulesA, pattern, sourceExpr1) => { val (sourceExpr2, returnsFromSource) = evaluateAndCoerceToReferenceExpression( - coutputs, nenv, life + 0, parentRanges, callLocation, sourceExpr1) + coutputs, nenv, life + 0, parentRanges, outerCallLocation, sourceExpr1) val runeTypeSolveEnv = @@ -924,7 +926,7 @@ class ExpressionCompiler( nenv, life + 1, parentRanges, - callLocation, + outerCallLocation, rulesA.toVector, runeToType, pattern, @@ -955,7 +957,7 @@ class ExpressionCompiler( val (conditionExpr, returnsFromCondition) = evaluateAndCoerceToReferenceExpression( - coutputs, nenv, life + 1, parentRanges, callLocation, conditionSE) + coutputs, nenv, life + 1, parentRanges, outerCallLocation, conditionSE) if (conditionExpr.result.coord != CoordT(ShareT, GlobalRegionT(), BoolT())) { throw CompileErrorExceptionT(IfConditionIsntBoolean(conditionSE.range :: parentRanges, conditionExpr.result.coord)) } @@ -970,7 +972,7 @@ class ExpressionCompiler( thenFate, life + 2, parentRanges, - callLocation, + outerCallLocation, thenBodySE) val uncoercedThenBlock2 = BlockTE(thenExpressionsWithResult) @@ -990,7 +992,7 @@ class ExpressionCompiler( elseFate, life + 3, parentRanges, - callLocation, + outerCallLocation, elseBodySE) val uncoercedElseBlock2 = BlockTE(elseExpressionsWithResult) @@ -1016,8 +1018,8 @@ class ExpressionCompiler( case (_, NeverT(true)) => uncoercedThenBlock2.result.coord case (a, b) if a == b => uncoercedThenBlock2.result.coord case (a : ICitizenTT, b : ICitizenTT) => { - val aAncestors = ancestorHelper.getParents(coutputs, parentRanges, callLocation, nenv.snapshot, a, true).toSet - val bAncestors = ancestorHelper.getParents(coutputs, parentRanges, callLocation, nenv.snapshot, b, true).toSet + val aAncestors = ancestorHelper.getParents(coutputs, parentRanges, outerCallLocation, nenv.snapshot, a, true).toSet + val bAncestors = ancestorHelper.getParents(coutputs, parentRanges, outerCallLocation, nenv.snapshot, b, true).toSet val commonAncestors = aAncestors.intersect(bAncestors) if (uncoercedElseBlock2.result.coord.ownership != uncoercedElseBlock2.result.coord.ownership) { @@ -1037,8 +1039,8 @@ class ExpressionCompiler( throw CompileErrorExceptionT(CantReconcileBranchesResults(range :: parentRanges, uncoercedThenBlock2.result.coord, uncoercedElseBlock2.result.coord)) } } - val thenExpr2 = convertHelper.convert(thenFate.snapshot, coutputs, range :: parentRanges, callLocation, uncoercedThenBlock2, commonType) - val elseExpr2 = convertHelper.convert(elseFate.snapshot, coutputs, range :: parentRanges, callLocation, uncoercedElseBlock2, commonType) + val thenExpr2 = convertHelper.convert(thenFate.snapshot, coutputs, range :: parentRanges, outerCallLocation, uncoercedThenBlock2, commonType) + val elseExpr2 = convertHelper.convert(elseFate.snapshot, coutputs, range :: parentRanges, outerCallLocation, uncoercedElseBlock2, commonType) val ifExpr2 = IfTE(conditionExpr, thenExpr2, elseExpr2) @@ -1086,7 +1088,7 @@ class ExpressionCompiler( loopBlockFate, life + 1, parentRanges, - callLocation, + outerCallLocation, bodySE) val uncoercedBodyBlock2 = BlockTE(bodyExpressionsWithResult) @@ -1127,7 +1129,7 @@ class ExpressionCompiler( loopBlockFate, life + 1, parentRanges, - callLocation, + outerCallLocation, bodySE) bodyExpressionsWithResult.result.coord } @@ -1145,7 +1147,7 @@ class ExpressionCompiler( nenv, life + 1, range :: parentRanges, - callLocation, + outerCallLocation, newGlobalFunctionGroupExpression( callEnv, coutputs, interner.intern(CodeNameS(keywords.List))), Vector(RuneParentEnvLookupSR(range, RuneUsage(range, SelfRuneS()))), @@ -1171,7 +1173,7 @@ class ExpressionCompiler( loopBlockFate, life + 1, parentRanges, - callLocation, + outerCallLocation, bodySE) // We store the iteration result in a local because the loop body will have @@ -1188,7 +1190,7 @@ class ExpressionCompiler( nenv, life + 4, range :: parentRanges, - callLocation, + outerCallLocation, newGlobalFunctionGroupExpression(callEnv, coutputs, interner.intern(CodeNameS(keywords.add))), Vector(), Vector(), @@ -1228,13 +1230,13 @@ class ExpressionCompiler( exprsSE.init.zipWithIndex.map({ case (exprSE, index) => val (undroppedExprTE, returns) = evaluateAndCoerceToReferenceExpression( - coutputs, nenv, life + index, parentRanges, callLocation, exprSE) + coutputs, nenv, life + index, parentRanges, outerCallLocation, exprSE) val exprTE = undroppedExprTE.result.kind match { case VoidT() => undroppedExprTE case _ => { destructorCompiler.drop( - nenv.snapshot, coutputs, exprSE.range :: parentRanges, callLocation, undroppedExprTE) + nenv.snapshot, coutputs, exprSE.range :: parentRanges, outerCallLocation, undroppedExprTE) } } (exprTE, returns) @@ -1246,7 +1248,7 @@ class ExpressionCompiler( nenv, life + (exprsSE.size - 1), parentRanges, - callLocation, + outerCallLocation, exprsSE.last) (Compiler.consecutive(initExprsTE :+ lastExprTE), (initReturnsUnflattened.flatten ++ lastReturns).toSet) @@ -1261,7 +1263,7 @@ class ExpressionCompiler( childEnvironment, life, parentRanges, - callLocation, + outerCallLocation, b) val block2 = BlockTE(expressionsWithResult) @@ -1275,7 +1277,7 @@ class ExpressionCompiler( case DestructSE(range, innerAE) => { val (innerExpr2, returnsFromArrayExpr) = evaluateAndCoerceToReferenceExpression( - coutputs, nenv, life + 0, parentRanges, callLocation, innerAE); + coutputs, nenv, life + 0, parentRanges, outerCallLocation, innerAE); // should just ignore others, TODO impl vcheck(innerExpr2.result.coord.ownership == OwnT, "can only destruct own") @@ -1307,7 +1309,7 @@ class ExpressionCompiler( })) } case interfaceTT @ InterfaceTT(_) => { - destructorCompiler.drop(nenv.snapshot, coutputs, range :: parentRanges, callLocation, innerExpr2) + destructorCompiler.drop(nenv.snapshot, coutputs, range :: parentRanges, outerCallLocation, innerExpr2) } case _ => vfail("Can't destruct type: " + innerExpr2.kind) } @@ -1330,19 +1332,19 @@ class ExpressionCompiler( } case ReturnSE(range, innerExprA) => { val (uncastedInnerExpr2, returnsFromInnerExpr) = - evaluateAndCoerceToReferenceExpression(coutputs, nenv, life + 0, parentRanges, callLocation, innerExprA); + evaluateAndCoerceToReferenceExpression(coutputs, nenv, life + 0, parentRanges, outerCallLocation, innerExprA); val innerExpr2 = nenv.maybeReturnType match { case None => (uncastedInnerExpr2) case Some(returnType) => { - templataCompiler.isTypeConvertible(coutputs, nenv.snapshot, range :: parentRanges, callLocation, uncastedInnerExpr2.result.coord, returnType) match { + templataCompiler.isTypeConvertible(coutputs, nenv.snapshot, range :: parentRanges, outerCallLocation, uncastedInnerExpr2.result.coord, returnType) match { case (false) => { throw CompileErrorExceptionT( CouldntConvertForReturnT(range :: parentRanges, returnType, uncastedInnerExpr2.result.coord)) } case (true) => { - convertHelper.convert(nenv.snapshot, coutputs, range :: parentRanges, callLocation, uncastedInnerExpr2, returnType) + convertHelper.convert(nenv.snapshot, coutputs, range :: parentRanges, outerCallLocation, uncastedInnerExpr2, returnType) } } } @@ -1362,7 +1364,7 @@ class ExpressionCompiler( val destructExprs = localHelper.unletAndDropAll( - coutputs, nenv, range :: parentRanges, callLocation, reversedVariablesToDestruct) + coutputs, nenv, range :: parentRanges, outerCallLocation, reversedVariablesToDestruct) val getResultExpr = localHelper.unletLocalWithoutDropping(nenv, resultVariable) @@ -1382,7 +1384,7 @@ class ExpressionCompiler( whileNenv, nenv, range :: parentRanges, - callLocation, + outerCallLocation, life, VoidLiteralTE()) val dropsAndBreakTE = Compiler.consecutive(Vector(dropsTE, BreakTE())) @@ -1675,11 +1677,12 @@ class ExpressionCompiler( nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, parentRanges: List[RangeS], + callLocation: LocationInDenizen, patterns1: Vector[AtomSP], patternInputExprs2: Vector[ReferenceExpressionTE] ): ReferenceExpressionTE = { patternCompiler.translatePatternList( - coutputs, nenv, life, parentRanges, patterns1, patternInputExprs2, + coutputs, nenv, life, parentRanges, callLocation, patterns1, patternInputExprs2, (coutputs, nenv, liveCaptureLocals) => VoidLiteralTE()) } diff --git a/Frontend/TypingPass/src/dev/vale/typing/expression/PatternCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/expression/PatternCompiler.scala index a659619d6..02e8b239c 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/expression/PatternCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/expression/PatternCompiler.scala @@ -51,6 +51,7 @@ class PatternCompiler( nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, parentRanges: List[RangeS], + callLocation: LocationInDenizen, patternsA: Vector[AtomSP], patternInputsTE: Vector[ReferenceExpressionTE], // This would be a continuation-ish lambda that evaluates: @@ -62,7 +63,7 @@ class PatternCompiler( ReferenceExpressionTE = { Profiler.frame(() => { iterateTranslateListAndMaybeContinue( - coutputs, nenv, life, parentRanges, Vector(), patternsA.toList, patternInputsTE.toList, afterPatternsSuccessContinuation) + coutputs, nenv, life, parentRanges, callLocation, Vector(), patternsA.toList, patternInputsTE.toList, afterPatternsSuccessContinuation) }) } @@ -71,6 +72,7 @@ class PatternCompiler( nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, parentRanges: List[RangeS], + callLocation: LocationInDenizen, liveCaptureLocals: Vector[ILocalVariableT], patternsA: List[AtomSP], patternInputsTE: List[ReferenceExpressionTE], @@ -87,12 +89,12 @@ class PatternCompiler( case (Nil, Nil) => afterPatternsSuccessContinuation(coutputs, nenv, liveCaptureLocals) case (headPatternA :: tailPatternsA, headPatternInputTE :: tailPatternInputsTE) => { innerTranslateSubPatternAndMaybeContinue( - coutputs, nenv, life + 0, parentRanges, headPatternA, liveCaptureLocals, headPatternInputTE, + coutputs, nenv, life + 0, parentRanges, callLocation, headPatternA, liveCaptureLocals, headPatternInputTE, (coutputs, nenv, life, liveCaptureLocals) => { vassert(liveCaptureLocals.map(_.name) == liveCaptureLocals.map(_.name).distinct) iterateTranslateListAndMaybeContinue( - coutputs, nenv, life + 1, parentRanges, liveCaptureLocals, tailPatternsA, tailPatternInputsTE, afterPatternsSuccessContinuation) + coutputs, nenv, life + 1, parentRanges, callLocation, liveCaptureLocals, tailPatternsA, tailPatternInputsTE, afterPatternsSuccessContinuation) }) } case _ => vfail("wat") @@ -175,7 +177,7 @@ class PatternCompiler( } } - innerTranslateSubPatternAndMaybeContinue(coutputs, nenv, life, parentRanges, pattern, Vector(), convertedInputExpr, afterPatternsSuccessContinuation) + innerTranslateSubPatternAndMaybeContinue(coutputs, nenv, life, parentRanges, callLocation, pattern, Vector(), convertedInputExpr, afterPatternsSuccessContinuation) }) } @@ -184,6 +186,7 @@ class PatternCompiler( nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, parentRanges: List[RangeS], + callLocation: LocationInDenizen, pattern: AtomSP, previousLiveCaptureLocals: Vector[ILocalVariableT], inputExpr: ReferenceExpressionTE, @@ -197,6 +200,7 @@ class PatternCompiler( vassert(previousLiveCaptureLocals.map(_.name) == previousLiveCaptureLocals.map(_.name).distinct) val AtomSP(range, maybeCaptureLocalVarA, coordRuneA, maybeDestructure) = pattern + // DO NOT SUBMIT make test that we have the right type in there, cuz the coordRuneA seems to be unused // We make it here instead of down in the maybeDestructure clauses because whether we destructure it or not // is unrelated to whether we destructure it. @@ -242,22 +246,35 @@ class PatternCompiler( vassert(liveCaptureLocals.map(_.name) == liveCaptureLocals.map(_.name).distinct) Compiler.consecutive( - currentInstructions :+ + currentInstructions ++ (maybeDestructure match { case None => { - // Do nothing - afterSubPatternSuccessContinuation(coutputs, nenv, life + 0, liveCaptureLocals) + // If we get here, we aren't destructuring, or doing anything with the exprToDestructureOrDropOrPassTE. + + // If it's an own, we should drop it immediately, instead of waiting for the containing block to drop it. + (if (exprToDestructureOrDropOrPassTE.result.coord.ownership == OwnT) { + List( + destructorCompiler.drop( + nenv.snapshot, coutputs, range :: parentRanges, callLocation, exprToDestructureOrDropOrPassTE)) + } else { + List() + }) ++ + List( + // ...and then continue on. + afterSubPatternSuccessContinuation(coutputs, nenv, life + 0, liveCaptureLocals)) } case Some(listOfMaybeDestructureMemberPatterns) => { exprToDestructureOrDropOrPassTE.result.coord.ownership match { case OwnT => { // We aren't capturing the var, so the destructuring should consume the incoming value. - destructureOwning( - coutputs, nenv, life + 1, range :: parentRanges, liveCaptureLocals, exprToDestructureOrDropOrPassTE, listOfMaybeDestructureMemberPatterns, afterSubPatternSuccessContinuation) + List( + destructureOwning( + coutputs, nenv, life + 1, range :: parentRanges, callLocation, liveCaptureLocals, exprToDestructureOrDropOrPassTE, listOfMaybeDestructureMemberPatterns, afterSubPatternSuccessContinuation)) } case BorrowT | ShareT => { - destructureNonOwningAndMaybeContinue( - coutputs, nenv, life + 2, range :: parentRanges, liveCaptureLocals, exprToDestructureOrDropOrPassTE, listOfMaybeDestructureMemberPatterns, afterSubPatternSuccessContinuation) + List( + destructureNonOwningAndMaybeContinue( + coutputs, nenv, life + 2, range :: parentRanges, callLocation, liveCaptureLocals, exprToDestructureOrDropOrPassTE, listOfMaybeDestructureMemberPatterns, afterSubPatternSuccessContinuation)) } } } @@ -269,6 +286,7 @@ class PatternCompiler( nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, parentRanges: List[RangeS], + callLocation: LocationInDenizen, initialLiveCaptureLocals: Vector[ILocalVariableT], inputExpr: ReferenceExpressionTE, listOfMaybeDestructureMemberPatterns: Vector[AtomSP], @@ -287,7 +305,7 @@ class PatternCompiler( // Since we're receiving an owning reference, and we're *not* capturing // it in a variable, it will be destroyed and we will harvest its parts. translateDestroyStructInnerAndMaybeContinue( - coutputs, nenv, life + 0, parentRanges, initialLiveCaptureLocals, listOfMaybeDestructureMemberPatterns, inputExpr, afterDestructureSuccessContinuation) + coutputs, nenv, life + 0, parentRanges, callLocation, initialLiveCaptureLocals, listOfMaybeDestructureMemberPatterns, inputExpr, afterDestructureSuccessContinuation) } case staticSizedArrayT @ contentsStaticSizedArrayTT(sizeTemplata, _, _, elementType) => { val size = @@ -313,7 +331,7 @@ class PatternCompiler( } val lets = makeLetsForOwnAndMaybeContinue( - coutputs, nenv, life + 4, parentRanges, liveCaptureLocals, elementLocals.toList, listOfMaybeDestructureMemberPatterns.toList, afterDestructureSuccessContinuation) + coutputs, nenv, life + 4, parentRanges, callLocation, liveCaptureLocals, elementLocals.toList, listOfMaybeDestructureMemberPatterns.toList, afterDestructureSuccessContinuation) Compiler.consecutive(Vector(destroyTE, lets)) } case rsa @ contentsRuntimeSizedArrayTT(_, _) => { @@ -331,6 +349,7 @@ class PatternCompiler( nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, range: List[RangeS], + callLocation: LocationInDenizen, liveCaptureLocals: Vector[ILocalVariableT], containerTE: ReferenceExpressionTE, listOfMaybeDestructureMemberPatterns: Vector[AtomSP], @@ -347,7 +366,7 @@ class PatternCompiler( Vector( letTE, iterateDestructureNonOwningAndMaybeContinue( - coutputs, nenv, life + 1, range, liveCaptureLocals, containerTE.result.coord, containerAliasingExprTE, 0, listOfMaybeDestructureMemberPatterns.toList, afterDestructureSuccessContinuation))) + coutputs, nenv, life + 1, range, callLocation, liveCaptureLocals, containerTE.result.coord, containerAliasingExprTE, 0, listOfMaybeDestructureMemberPatterns.toList, afterDestructureSuccessContinuation))) } private def iterateDestructureNonOwningAndMaybeContinue( @@ -355,6 +374,7 @@ class PatternCompiler( nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, parentRanges: List[RangeS], + callLocation: LocationInDenizen, liveCaptureLocals: Vector[ILocalVariableT], expectedContainerCoord: CoordT, containerAliasingExprTE: ReferenceExpressionTE, @@ -401,7 +421,7 @@ class PatternCompiler( val loadExpr = SoftLoadTE(memberAddrExprTE, coerceToOwnership) innerTranslateSubPatternAndMaybeContinue( - coutputs, nenv, life + 1, parentRanges, headMaybeDestructureMemberPattern, liveCaptureLocals, loadExpr, + coutputs, nenv, life + 1, parentRanges, callLocation, headMaybeDestructureMemberPattern, liveCaptureLocals, loadExpr, (coutputs, nenv, life, liveCaptureLocals) => { vassert(liveCaptureLocals.map(_.name) == liveCaptureLocals.map(_.name).distinct) @@ -411,6 +431,7 @@ class PatternCompiler( nenv, life, parentRanges, + callLocation, liveCaptureLocals, expectedContainerCoord, containerAliasingExprTE, @@ -427,8 +448,9 @@ class PatternCompiler( nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, parentRanges: List[RangeS], + callLocation: LocationInDenizen, initialLiveCaptureLocals: Vector[ILocalVariableT], - innerPatternMaybes: Vector[AtomSP], + innerPatterns: Vector[AtomSP], inputStructExpr: ReferenceExpressionTE, afterDestroySuccessContinuation: (CompilerOutputs, NodeEnvironmentBox, LocationInFunctionEnvironmentT, Vector[ILocalVariableT]) => ReferenceExpressionTE ): ReferenceExpressionTE = { @@ -460,8 +482,8 @@ class PatternCompiler( val liveCaptureLocals = initialLiveCaptureLocals ++ memberLocals vassert(liveCaptureLocals.map(_.name) == liveCaptureLocals.map(_.name).distinct) - if (memberLocals.size != innerPatternMaybes.size) { - throw CompileErrorExceptionT(WrongNumberOfDestructuresError(parentRanges, innerPatternMaybes.size, memberLocals.size)) + if (memberLocals.size != innerPatterns.size) { + throw CompileErrorExceptionT(WrongNumberOfDestructuresError(parentRanges, innerPatterns.size, memberLocals.size)) } val restTE = makeLetsForOwnAndMaybeContinue( @@ -469,9 +491,10 @@ class PatternCompiler( nenv, life + 0, parentRanges, + callLocation, liveCaptureLocals, memberLocals.toList, - innerPatternMaybes.toList, + innerPatterns.toList, afterDestroySuccessContinuation) Compiler.consecutive(Vector(destroyTE, restTE)) } @@ -481,16 +504,17 @@ class PatternCompiler( nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, parentRanges: List[RangeS], + callLocation: LocationInDenizen, initialLiveCaptureLocals: Vector[ILocalVariableT], memberLocalVariables: List[ILocalVariableT], - innerPatternMaybes: List[AtomSP], + innerPatterns: List[AtomSP], afterLetsSuccessContinuation: (CompilerOutputs, NodeEnvironmentBox, LocationInFunctionEnvironmentT, Vector[ILocalVariableT]) => ReferenceExpressionTE ): ReferenceExpressionTE = { vassert(initialLiveCaptureLocals.map(_.name) == initialLiveCaptureLocals.map(_.name).distinct) - vassert(memberLocalVariables.size == innerPatternMaybes.size) + vassert(memberLocalVariables.size == innerPatterns.size) - (memberLocalVariables, innerPatternMaybes) match { + (memberLocalVariables, innerPatterns) match { case (Nil, Nil) => { afterLetsSuccessContinuation(coutputs, nenv, life + 0, initialLiveCaptureLocals) } @@ -500,12 +524,12 @@ class PatternCompiler( vassert(liveCaptureLocals.size == initialLiveCaptureLocals.size - 1) innerTranslateSubPatternAndMaybeContinue( - coutputs, nenv, life + 1, headInnerPattern.range :: parentRanges, headInnerPattern, liveCaptureLocals, unletExpr, + coutputs, nenv, life + 1, headInnerPattern.range :: parentRanges, callLocation, headInnerPattern, liveCaptureLocals, unletExpr, (coutputs, nenv, life, liveCaptureLocals) => { vassert(initialLiveCaptureLocals.map(_.name) == initialLiveCaptureLocals.map(_.name).distinct) makeLetsForOwnAndMaybeContinue( - coutputs, nenv, life, parentRanges, liveCaptureLocals, tailMemberLocalVariables, tailInnerPatternMaybes, afterLetsSuccessContinuation) + coutputs, nenv, life, parentRanges, callLocation, liveCaptureLocals, tailMemberLocalVariables, tailInnerPatternMaybes, afterLetsSuccessContinuation) }) } } diff --git a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionBodyCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionBodyCompiler.scala index 4b41934ee..e35f9517e 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionBodyCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionBodyCompiler.scala @@ -38,6 +38,7 @@ trait IBodyCompilerDelegate { nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, parentRanges: List[RangeS], + callLocation: LocationInDenizen, patterns1: Vector[AtomSP], patternInputExprs2: Vector[ReferenceExpressionTE]): ReferenceExpressionTE @@ -164,7 +165,7 @@ class BodyCompiler( val startingEnv = env.snapshot val patternsTE = - evaluateLets(env, coutputs, life + 0, body1.range :: parentRanges, params1, params2); + evaluateLets(env, coutputs, life + 0, body1.range :: parentRanges, callLocation, params1, params2); val (statementsFromBlock, returnsFromInsideMaybeWithNever) = delegate.evaluateBlockStatements( @@ -224,10 +225,11 @@ class BodyCompiler( // Produce the lets at the start of a function. private def evaluateLets( - nenv: NodeEnvironmentBox, + nenv: NodeEnvironmentBox, coutputs: CompilerOutputs, - life: LocationInFunctionEnvironmentT, - range: List[RangeS], + life: LocationInFunctionEnvironmentT, + range: List[RangeS], + callLocation: LocationInDenizen, params1: Vector[ParameterS], params2: Vector[ParameterT]): ReferenceExpressionTE = { @@ -235,7 +237,7 @@ class BodyCompiler( params2.zipWithIndex.map({ case (p, index) => ArgLookupTE(index, p.tyype) }) val letExprs2 = delegate.translatePatternList( - coutputs, nenv, life, range, params1.map(_.pattern), paramLookups2); + coutputs, nenv, life, range, callLocation, params1.map(_.pattern), paramLookups2); // todo: at this point, to allow for recursive calls, add a callable type to the environment // for everything inside the body to use diff --git a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompiler.scala index 11cfd5596..4b59d5a8e 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompiler.scala @@ -44,6 +44,7 @@ trait IFunctionCompilerDelegate { nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, ranges: List[RangeS], + callLocation: LocationInDenizen, patterns1: Vector[AtomSP], patternInputExprs2: Vector[ReferenceExpressionTE]): ReferenceExpressionTE diff --git a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerCore.scala b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerCore.scala index 2d4a33d87..434993a7f 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerCore.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/function/FunctionCompilerCore.scala @@ -50,10 +50,11 @@ class FunctionCompilerCore( nenv: NodeEnvironmentBox, life: LocationInFunctionEnvironmentT, parentRanges: List[RangeS], + callLocation: LocationInDenizen, patterns1: Vector[AtomSP], patternInputExprs2: Vector[ReferenceExpressionTE] ): ReferenceExpressionTE = { - delegate.translatePatternList(coutputs, nenv, life, parentRanges, patterns1, patternInputExprs2) + delegate.translatePatternList(coutputs, nenv, life, parentRanges, callLocation, patterns1, patternInputExprs2) } }) diff --git a/Frontend/TypingPass/src/dev/vale/typing/names/names.scala b/Frontend/TypingPass/src/dev/vale/typing/names/names.scala index 5651eb4ff..c242dc9f5 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/names/names.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/names/names.scala @@ -281,7 +281,9 @@ case class OverrideDispatcherCaseNameT( sealed trait IVarNameT extends INameT case class TypingPassBlockResultVarNameT(life: LocationInFunctionEnvironmentT) extends IVarNameT case class TypingPassFunctionResultVarNameT() extends IVarNameT -case class TypingPassTemporaryVarNameT(life: LocationInFunctionEnvironmentT) extends IVarNameT +case class TypingPassTemporaryVarNameT(life: LocationInFunctionEnvironmentT) extends IVarNameT { + vpass() +} case class TypingPassPatternMemberNameT(life: LocationInFunctionEnvironmentT) extends IVarNameT case class TypingIgnoredParamNameT(num: Int) extends IVarNameT case class TypingPassPatternDestructureeNameT(life: LocationInFunctionEnvironmentT) extends IVarNameT diff --git a/Frontend/TypingPass/test/dev/vale/typing/AfterRegionsErrorTests.scala b/Frontend/TypingPass/test/dev/vale/typing/AfterRegionsErrorTests.scala index 8c10ada12..95d2c8aee 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/AfterRegionsErrorTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/AfterRegionsErrorTests.scala @@ -9,7 +9,7 @@ import dev.vale.typing.templata._ import dev.vale.typing.types._ import dev.vale.{Collector, Err, Ok, vwat, _} //import dev.vale.typingpass.infer.NotEnoughToSolveError -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ class AfterRegionsErrorTests extends FunSuite with Matchers { diff --git a/Frontend/TypingPass/test/dev/vale/typing/AfterRegionsTests.scala b/Frontend/TypingPass/test/dev/vale/typing/AfterRegionsTests.scala index af6999cb3..280db665b 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/AfterRegionsTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/AfterRegionsTests.scala @@ -9,7 +9,7 @@ import dev.vale.typing.templata._ import dev.vale.typing.types._ import dev.vale.{Collector, Err, Ok, vassert, vwat, _} //import dev.vale.typingpass.infer.NotEnoughToSolveError -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.io.Source diff --git a/Frontend/TypingPass/test/dev/vale/typing/CompilerLambdaTests.scala b/Frontend/TypingPass/test/dev/vale/typing/CompilerLambdaTests.scala index fae5bfb9e..d2cbc33a3 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/CompilerLambdaTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/CompilerLambdaTests.scala @@ -13,7 +13,7 @@ import dev.vale.typing.templata._ import dev.vale.typing.types._ import dev.vale.{CodeLocationS, Collector, Err, FileCoordinateMap, PackageCoordinate, RangeS, Tests, vassert, vassertOne, vpass, _} //import dev.vale.typingpass.infer.NotEnoughToSolveError -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.List import scala.io.Source diff --git a/Frontend/TypingPass/test/dev/vale/typing/CompilerMutateTests.scala b/Frontend/TypingPass/test/dev/vale/typing/CompilerMutateTests.scala index 603539d9b..a9dd3cca9 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/CompilerMutateTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/CompilerMutateTests.scala @@ -14,7 +14,7 @@ import dev.vale.typing.types._ import dev.vale.typing.ast._ import dev.vale.typing.templata._ import dev.vale.typing.types._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.List import scala.io.Source diff --git a/Frontend/TypingPass/test/dev/vale/typing/CompilerOwnershipTests.scala b/Frontend/TypingPass/test/dev/vale/typing/CompilerOwnershipTests.scala index 4427d5386..2ed36d50a 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/CompilerOwnershipTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/CompilerOwnershipTests.scala @@ -9,7 +9,7 @@ import dev.vale.typing.names.CodeVarNameT import dev.vale.vassert import dev.vale.typing.templata._ import dev.vale.typing.types._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.List import scala.io.Source diff --git a/Frontend/TypingPass/test/dev/vale/typing/CompilerProjectTests.scala b/Frontend/TypingPass/test/dev/vale/typing/CompilerProjectTests.scala index d3c0d3685..5265a49f8 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/CompilerProjectTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/CompilerProjectTests.scala @@ -6,7 +6,7 @@ import dev.vale.typing.names.{CitizenNameT, CitizenTemplateNameT, IdT, FunctionN import dev.vale.typing.templata.CoordTemplataT import dev.vale.typing.types._ import dev.vale.typing.types._ -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.List diff --git a/Frontend/TypingPass/test/dev/vale/typing/CompilerSolverTests.scala b/Frontend/TypingPass/test/dev/vale/typing/CompilerSolverTests.scala index 5aab6bf2c..c449e7dfd 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/CompilerSolverTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/CompilerSolverTests.scala @@ -20,7 +20,7 @@ import dev.vale.typing.ast._ import dev.vale.typing.templata._ import dev.vale.typing.types._ //import dev.vale.typingpass.infer.NotEnoughToSolveError -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.io.Source diff --git a/Frontend/TypingPass/test/dev/vale/typing/CompilerVirtualTests.scala b/Frontend/TypingPass/test/dev/vale/typing/CompilerVirtualTests.scala index 6d5cd947d..9699f34a5 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/CompilerVirtualTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/CompilerVirtualTests.scala @@ -6,7 +6,7 @@ import dev.vale.typing.templata.CoordTemplataT import dev.vale.typing.types._ import dev.vale.{Collector, StrI, Tests, vassert} import dev.vale.typing.types.InterfaceTT -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.Set diff --git a/Frontend/TypingPass/test/dev/vale/typing/InProgressTests.scala b/Frontend/TypingPass/test/dev/vale/typing/InProgressTests.scala index d133a51a8..6e518eafd 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/InProgressTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/InProgressTests.scala @@ -11,7 +11,7 @@ import dev.vale.typing.templata.{CoordTemplataT, IntegerTemplataT, KindTemplataT import dev.vale.typing.types.{BoolT, BorrowT, CoordT, ImmutableT, IntT, InterfaceTT, OwnT, KindPlaceholderT, RuntimeSizedArrayTT, ShareT, StructTT, VoidT} import dev.vale.{Collector, Err, Ok, PackageCoordinate, StrI, Tests, vassert, vassertOne, vfail, vimpl, vwat} //import dev.vale.typingpass.infer.NotEnoughToSolveError -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.io.Source diff --git a/Frontend/TypingPass/test/dev/vale/typing/TodoTests.scala b/Frontend/TypingPass/test/dev/vale/typing/TodoTests.scala index fe1312fa6..5797450e2 100644 --- a/Frontend/TypingPass/test/dev/vale/typing/TodoTests.scala +++ b/Frontend/TypingPass/test/dev/vale/typing/TodoTests.scala @@ -13,7 +13,7 @@ import dev.vale.typing.templata._ import dev.vale.typing.types._ import dev.vale.{CodeLocationS, Collector, Err, FileCoordinateMap, Ok, PackageCoordinate, RangeS, Tests, vassert, vassertOne, vpass, vwat, _} //import dev.vale.typingpass.infer.NotEnoughToSolveError -import org.scalatest.{FunSuite, Matchers} +import org.scalatest._ import scala.collection.immutable.List import scala.io.Source diff --git a/Frontend/Von/test/dev/vale/von/VonTest.scala b/Frontend/Von/test/dev/vale/von/VonTest.scala index 904b4615f..efa6be11b 100644 --- a/Frontend/Von/test/dev/vale/von/VonTest.scala +++ b/Frontend/Von/test/dev/vale/von/VonTest.scala @@ -1,6 +1,6 @@ package dev.vale.von -import org.scalatest.{FunSuite, Matchers, _} +import org.scalatest._ class VonTest extends FunSuite with Matchers { From dce4494db26bccf0e683caf9bafcfdf9754c493d Mon Sep 17 00:00:00 2001 From: Evan Ovadia <> Date: Tue, 11 Jul 2023 13:26:21 -0400 Subject: [PATCH 5/5] Fixed the underscore/ignore pattern problem --- .../typing/expression/PatternCompiler.scala | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/Frontend/TypingPass/src/dev/vale/typing/expression/PatternCompiler.scala b/Frontend/TypingPass/src/dev/vale/typing/expression/PatternCompiler.scala index 02e8b239c..fe369c62e 100644 --- a/Frontend/TypingPass/src/dev/vale/typing/expression/PatternCompiler.scala +++ b/Frontend/TypingPass/src/dev/vale/typing/expression/PatternCompiler.scala @@ -251,13 +251,17 @@ class PatternCompiler( case None => { // If we get here, we aren't destructuring, or doing anything with the exprToDestructureOrDropOrPassTE. - // If it's an own, we should drop it immediately, instead of waiting for the containing block to drop it. - (if (exprToDestructureOrDropOrPassTE.result.coord.ownership == OwnT) { - List( - destructorCompiler.drop( - nenv.snapshot, coutputs, range :: parentRanges, callLocation, exprToDestructureOrDropOrPassTE)) - } else { - List() + (maybeCaptureLocalVarA match { + case None => { + // If we didn't store it, and we aren't destructuring it, then we're just ignoring it. Let's drop it. + List( + destructorCompiler.drop( + nenv.snapshot, coutputs, range :: parentRanges, callLocation, exprToDestructureOrDropOrPassTE)) + } + case Some(_) => { + // We aren't destructuring it, but we stored it, so just do nothing. + List() + } }) ++ List( // ...and then continue on.