Lazy Diagnostic storage allocation (#10852)

close #10727



Changelog:
- add: implement lazy allocation of `DiagnosticStorage` objects
- update: compiler phases to make sure they don't allocate redundant `DiagnosticStorage` objects
- update: cleanup `DiagnosticStorage` class

# Important Notes
As a result, all 10MB of redundant `DiagnosticStorage` allocations are gone

#### Before
![2024-08-21-170148_2092x171_scrot](https://github.com/user-attachments/assets/c1fd34d5-019d-472f-b523-a5c31b87f454)

#### After
![2024-08-21-170058_1693x131_scrot](https://github.com/user-attachments/assets/10d71d81-42b7-4b3c-a49f-ca6267bc6ccf)
This commit is contained in:
Dmitry Bushev 2024-08-23 20:48:25 +03:00 committed by GitHub
parent 582b7f9a2e
commit 3bfe963e32
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
92 changed files with 1534 additions and 1657 deletions

View File

@ -61,7 +61,7 @@ public final class PrivateConstructorAnalysis implements IRPass {
var ctorsCnt = type.members().size(); var ctorsCnt = type.members().size();
if (!(privateCtorsCnt == ctorsCnt || publicCtorsCnt == ctorsCnt)) { if (!(privateCtorsCnt == ctorsCnt || publicCtorsCnt == ctorsCnt)) {
assert type.location().isDefined(); assert type.location().isDefined();
return Syntax.apply( return new Syntax(
type.location().get(), type.location().get(),
InconsistentConstructorVisibility$.MODULE$, InconsistentConstructorVisibility$.MODULE$,
type.passData(), type.passData(),
@ -71,14 +71,14 @@ public final class PrivateConstructorAnalysis implements IRPass {
return binding; return binding;
}); });
return ir.copy( return ir.copy(
ir.imports(), ir.copy$default$1(),
ir.exports(), ir.copy$default$2(),
newBindings, newBindings,
ir.isPrivate(), ir.copy$default$4(),
ir.location(), ir.copy$default$5(),
ir.passData(), ir.copy$default$6(),
ir.diagnostics(), ir.copy$default$7(),
ir.id()); ir.copy$default$8());
} }
/** Not supported on a single expression. */ /** Not supported on a single expression. */

View File

@ -85,8 +85,7 @@ public final class PrivateModuleAnalysis implements IRPass {
ImportExport.apply( ImportExport.apply(
resolvedImp.importDef(), resolvedImp.importDef(),
new ImportExport.ImportPrivateModule(importedModuleName), new ImportExport.ImportPrivateModule(importedModuleName),
ImportExport.apply$default$3(), ImportExport.apply$default$3()));
ImportExport.apply$default$4()));
} }
return null; return null;
}); });
@ -99,8 +98,7 @@ public final class PrivateModuleAnalysis implements IRPass {
ImportExport.apply( ImportExport.apply(
moduleIr.exports().apply(0), moduleIr.exports().apply(0),
new ImportExport.ExportSymbolsFromPrivateModule(moduleContext.getName().toString()), new ImportExport.ExportSymbolsFromPrivateModule(moduleContext.getName().toString()),
ImportExport.apply$default$3(), ImportExport.apply$default$3()));
ImportExport.apply$default$4()));
} }
// Ensure that private modules are not exported // Ensure that private modules are not exported
@ -116,8 +114,7 @@ public final class PrivateModuleAnalysis implements IRPass {
ImportExport.apply( ImportExport.apply(
associatedExportIR.get(), associatedExportIR.get(),
new ImportExport.ExportPrivateModule(expModuleRef.getName().toString()), new ImportExport.ExportPrivateModule(expModuleRef.getName().toString()),
ImportExport.apply$default$3(), ImportExport.apply$default$3()));
ImportExport.apply$default$4()));
} }
return null; return null;
}); });
@ -134,12 +131,12 @@ public final class PrivateModuleAnalysis implements IRPass {
return moduleIr.copy( return moduleIr.copy(
convertedImports, convertedImports,
convertedExports, convertedExports,
moduleIr.bindings(), moduleIr.copy$default$3(),
moduleIr.isPrivate(), moduleIr.copy$default$4(),
moduleIr.location(), moduleIr.copy$default$5(),
moduleIr.passData(), moduleIr.copy$default$6(),
moduleIr.diagnostics(), moduleIr.copy$default$7(),
moduleIr.id()); moduleIr.copy$default$8());
} }
@Override @Override

View File

@ -72,14 +72,14 @@ public class PrivateSymbolsAnalysis implements IRPass {
ir.bindings() ir.bindings()
.map(binding -> binding.mapExpressions(expr -> processExpression(expr, bindingsMap))); .map(binding -> binding.mapExpressions(expr -> processExpression(expr, bindingsMap)));
return ir.copy( return ir.copy(
ir.imports(), ir.copy$default$1(),
ir.exports(), ir.copy$default$2(),
newBindings, newBindings,
ir.isPrivate(), ir.copy$default$4(),
ir.location(), ir.copy$default$5(),
ir.passData(), ir.copy$default$6(),
ir.diagnostics(), ir.copy$default$7(),
ir.id()); ir.copy$default$8());
} }
/** Not supported for expressions. */ /** Not supported for expressions. */
@ -98,11 +98,11 @@ public class PrivateSymbolsAnalysis implements IRPass {
yield caseExpr.copy( yield caseExpr.copy(
newScrutinee, newScrutinee,
newBranches, newBranches,
caseExpr.isNested(), caseExpr.copy$default$3(),
caseExpr.location(), caseExpr.copy$default$4(),
caseExpr.passData(), caseExpr.copy$default$5(),
caseExpr.diagnostics(), caseExpr.copy$default$6(),
caseExpr.id()); caseExpr.copy$default$7());
} }
case Name name -> processName(name, bindingsMap); case Name name -> processName(name, bindingsMap);
default -> expr.mapExpressions(e -> processExpression(e, bindingsMap)); default -> expr.mapExpressions(e -> processExpression(e, bindingsMap));
@ -116,11 +116,11 @@ public class PrivateSymbolsAnalysis implements IRPass {
return branch.copy( return branch.copy(
newPat, newPat,
newExpr, newExpr,
branch.terminalBranch(), branch.copy$default$3(),
branch.location(), branch.copy$default$4(),
branch.passData(), branch.copy$default$5(),
branch.diagnostics(), branch.copy$default$6(),
branch.id()); branch.copy$default$7());
} }
private Pattern processCasePattern(Pattern pattern, BindingsMap bindingsMap) { private Pattern processCasePattern(Pattern pattern, BindingsMap bindingsMap) {

View File

@ -78,7 +78,7 @@ public final class TypeInference implements IRPass {
protected void encounteredIncompatibleTypes( protected void encounteredIncompatibleTypes(
IR relatedIr, TypeRepresentation expected, TypeRepresentation provided) { IR relatedIr, TypeRepresentation expected, TypeRepresentation provided) {
relatedIr relatedIr
.diagnostics() .getDiagnostics()
.add( .add(
new Warning.TypeMismatch( new Warning.TypeMismatch(
relatedIr.location(), expected.toString(), provided.toString())); relatedIr.location(), expected.toString(), provided.toString()));
@ -88,7 +88,7 @@ public final class TypeInference implements IRPass {
protected void encounteredInvocationOfNonFunctionType( protected void encounteredInvocationOfNonFunctionType(
IR relatedIr, TypeRepresentation type) { IR relatedIr, TypeRepresentation type) {
relatedIr relatedIr
.diagnostics() .getDiagnostics()
.add(new Warning.NotInvokable(relatedIr.location(), type.toString())); .add(new Warning.NotInvokable(relatedIr.location(), type.toString()));
} }
}; };

View File

@ -5,7 +5,6 @@ import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.enso.compiler.PackageRepository; import org.enso.compiler.PackageRepository;
import org.enso.compiler.context.CompilerContext; import org.enso.compiler.context.CompilerContext;
import org.enso.compiler.core.ir.Diagnostic;
import org.enso.compiler.core.ir.DiagnosticStorage; import org.enso.compiler.core.ir.DiagnosticStorage;
import org.enso.compiler.core.ir.MetadataStorage; import org.enso.compiler.core.ir.MetadataStorage;
import org.enso.compiler.core.ir.Module; import org.enso.compiler.core.ir.Module;
@ -14,8 +13,6 @@ import org.enso.compiler.core.ir.expression.errors.ImportExport;
import org.enso.compiler.core.ir.module.scope.Export; import org.enso.compiler.core.ir.module.scope.Export;
import org.enso.compiler.data.BindingsMap.ResolvedType; import org.enso.compiler.data.BindingsMap.ResolvedType;
import org.enso.compiler.pass.IRPass; import org.enso.compiler.pass.IRPass;
import scala.collection.immutable.Seq;
import scala.collection.immutable.Seq$;
import scala.jdk.javaapi.CollectionConverters; import scala.jdk.javaapi.CollectionConverters;
/** /**
@ -224,15 +221,14 @@ public final class ExportSymbolAnalysis {
private static ImportExport createModuleDoesNotExistError(Export.Module exportIr, String modFQN) { private static ImportExport createModuleDoesNotExistError(Export.Module exportIr, String modFQN) {
assert modFQN.contains("."); assert modFQN.contains(".");
return ImportExport.apply( return new ImportExport(exportIr, new ImportExport.ModuleDoesNotExist(modFQN), emptyPassData());
exportIr, new ImportExport.ModuleDoesNotExist(modFQN), emptyPassData(), emptyDiagnostics());
} }
private static ImportExport createSymbolDoesNotExistError( private static ImportExport createSymbolDoesNotExistError(
Name symbolIr, String symbolName, String modFQN) { Name symbolIr, String symbolName, String modFQN) {
assert modFQN.contains("."); assert modFQN.contains(".");
assert !symbolName.contains("."); assert !symbolName.contains(".");
return ImportExport.apply( return new ImportExport(
symbolIr, symbolIr,
new ImportExport.SymbolDoesNotExist(symbolName, modFQN), new ImportExport.SymbolDoesNotExist(symbolName, modFQN),
emptyPassData(), emptyPassData(),
@ -242,7 +238,7 @@ public final class ExportSymbolAnalysis {
private static ImportExport createNoSuchConstructorError( private static ImportExport createNoSuchConstructorError(
Name symbolIr, String typeName, String consName) { Name symbolIr, String typeName, String consName) {
assert !consName.contains("."); assert !consName.contains(".");
return ImportExport.apply( return new ImportExport(
symbolIr, symbolIr,
new ImportExport.NoSuchConstructor(typeName, consName), new ImportExport.NoSuchConstructor(typeName, consName),
emptyPassData(), emptyPassData(),
@ -253,7 +249,7 @@ public final class ExportSymbolAnalysis {
Export.Module exportIr, String modFQN, String typeName) { Export.Module exportIr, String modFQN, String typeName) {
assert modFQN.contains("."); assert modFQN.contains(".");
assert !typeName.contains("."); assert !typeName.contains(".");
return ImportExport.apply( return new ImportExport(
exportIr, exportIr,
new ImportExport.TypeDoesNotExist(typeName, modFQN), new ImportExport.TypeDoesNotExist(typeName, modFQN),
emptyPassData(), emptyPassData(),
@ -266,6 +262,6 @@ public final class ExportSymbolAnalysis {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private static DiagnosticStorage emptyDiagnostics() { private static DiagnosticStorage emptyDiagnostics() {
return DiagnosticStorage.apply((Seq<Diagnostic>) Seq$.MODULE$.empty()); return new DiagnosticStorage(DiagnosticStorage.$lessinit$greater$default$1());
} }
} }

View File

@ -411,12 +411,12 @@ case object AliasAnalysis extends IRPass {
alias.AliasMetadata.ChildScope(graph, currentScope) alias.AliasMetadata.ChildScope(graph, currentScope)
) )
) )
case binding @ Expression.Binding(name, expression, _, _, _) => case binding @ Expression.Binding(name, expression, _, _) =>
if ( if (
!parentScope.hasSymbolOccurrenceAs[GraphOccurrence.Def](name.name) !parentScope.hasSymbolOccurrenceAs[GraphOccurrence.Def](name.name)
) { ) {
val isSuspended = expression match { val isSuspended = expression match {
case Expression.Block(_, _, _, isSuspended, _, _) => isSuspended case Expression.Block(_, _, _, isSuspended, _) => isSuspended
case _ => false case _ => false
} }
val occurrenceId = graph.nextId() val occurrenceId = graph.nextId()
@ -476,7 +476,7 @@ case object AliasAnalysis extends IRPass {
parentScope: Scope parentScope: Scope
): Type = { ): Type = {
value match { value match {
case member @ `type`.Set.Member(label, memberType, value, _, _, _) => case member @ `type`.Set.Member(label, memberType, value, _, _) =>
val memberTypeScope = memberType match { val memberTypeScope = memberType match {
case _: Literal => parentScope case _: Literal => parentScope
case _ => parentScope.addChild() case _ => parentScope.addChild()
@ -537,8 +537,7 @@ case object AliasAnalysis extends IRPass {
): List[DefinitionArgument] = { ): List[DefinitionArgument] = {
args.map { args.map {
case arg @ DefinitionArgument.Specified( case arg @ DefinitionArgument.Specified(
selfName @ Name.Self(_, true, _, _), selfName @ Name.Self(_, true, _),
_,
_, _,
_, _,
_, _,
@ -573,7 +572,6 @@ case object AliasAnalysis extends IRPass {
value, value,
suspended, suspended,
_, _,
_,
_ _
) => ) =>
val nameOccursInScope = val nameOccursInScope =
@ -685,7 +683,7 @@ case object AliasAnalysis extends IRPass {
graph: Graph, graph: Graph,
parentScope: Graph.Scope parentScope: Graph.Scope
): List[CallArgument] = { ): List[CallArgument] = {
args.map { case arg @ CallArgument.Specified(_, expr, _, _, _) => args.map { case arg @ CallArgument.Specified(_, expr, _, _) =>
val currentScope = expr match { val currentScope = expr match {
case _: Literal => parentScope case _: Literal => parentScope
case _ => parentScope.addChild() case _ => parentScope.addChild()

View File

@ -80,8 +80,8 @@ case object AmbiguousImportsAnalysis extends IRPass {
/** Analyses ambiguous symbols in the given import. /** Analyses ambiguous symbols in the given import.
* @param imp current import * @param imp current import
* @param module current module
* @param bindingMap binding map of the current module * @param bindingMap binding map of the current module
* @param encounteredSymbols already encountered symbols
* @return A list of errors, if any encountered, or an import IR, potentially with some * @return A list of errors, if any encountered, or an import IR, potentially with some
* warnings attached. * warnings attached.
*/ */
@ -100,7 +100,6 @@ case object AmbiguousImportsAnalysis extends IRPass {
_, _,
_, _,
false, false,
_,
_ _
) => ) =>
getImportTargets(moduleImport, bindingMap) match { getImportTargets(moduleImport, bindingMap) match {
@ -152,7 +151,6 @@ case object AmbiguousImportsAnalysis extends IRPass {
hiddenNames, hiddenNames,
_, _,
false, false,
_,
_ _
) => ) =>
getImportTargets(moduleImport, bindingMap) match { getImportTargets(moduleImport, bindingMap) match {
@ -211,7 +209,6 @@ case object AmbiguousImportsAnalysis extends IRPass {
_, _,
_, _,
false, false,
_,
_ _
) => ) =>
val symbolPath = importPath.name val symbolPath = importPath.name
@ -235,7 +232,6 @@ case object AmbiguousImportsAnalysis extends IRPass {
_, _,
_, _,
false, false,
_,
_ _
) => ) =>
tryAddEncounteredSymbol( tryAddEncounteredSymbol(
@ -250,7 +246,7 @@ case object AmbiguousImportsAnalysis extends IRPass {
} }
// Polyglot import // Polyglot import
case polyImport @ imports.Polyglot(entity, rename, _, _, _) => case polyImport @ imports.Polyglot(entity, rename, _, _) =>
val symbolName = rename.getOrElse(entity.getVisibleName) val symbolName = rename.getOrElse(entity.getVisibleName)
val symbolPath = entity match { val symbolPath = entity match {
case imports.Polyglot.Java(packageName, className) => case imports.Polyglot.Java(packageName, className) =>

View File

@ -69,9 +69,9 @@ case object BindingAnalysis extends IRPass {
case method: definition.Method.Explicit => case method: definition.Method.Explicit =>
val ref = method.methodReference val ref = method.methodReference
ref.typePointer match { ref.typePointer match {
case Some(Name.Qualified(List(), _, _, _)) => case Some(Name.Qualified(List(), _, _)) =>
Some(ModuleMethod(ref.methodName.name)) Some(ModuleMethod(ref.methodName.name))
case Some(Name.Qualified(List(n), _, _, _)) => case Some(Name.Qualified(List(n), _, _)) =>
val shadowed = definedSumTypes.exists(_.name == n.name) val shadowed = definedSumTypes.exists(_.name == n.name)
if (!shadowed && n.name == moduleContext.getName().item) if (!shadowed && n.name == moduleContext.getName().item)
Some(ModuleMethod(ref.methodName.name)) Some(ModuleMethod(ref.methodName.name))

View File

@ -172,7 +172,7 @@ case object CachePreferenceAnalysis extends IRPass {
} }
} }
def analyseSelfCallArgument( private def analyseSelfCallArgument(
callArgument: CallArgument, callArgument: CallArgument,
weights: WeightInfo weights: WeightInfo
): CallArgument = { ): CallArgument = {
@ -198,7 +198,7 @@ case object CachePreferenceAnalysis extends IRPass {
weights: WeightInfo weights: WeightInfo
): DefinitionArgument = { ): DefinitionArgument = {
argument match { argument match {
case spec @ DefinitionArgument.Specified(_, _, defValue, _, _, _, _) => case spec @ DefinitionArgument.Specified(_, _, defValue, _, _, _) =>
spec spec
.copy(defaultValue = defValue.map(analyseExpression(_, weights))) .copy(defaultValue = defValue.map(analyseExpression(_, weights)))
.updateMetadata(new MetadataPair(this, weights)) .updateMetadata(new MetadataPair(this, weights))

View File

@ -43,7 +43,7 @@ import scala.collection.mutable
* *
* This pass requires the context to provide: * This pass requires the context to provide:
* *
* - A [[LocalScope]], where relevant. * - A [[org.enso.compiler.context.LocalScope]], where relevant.
* *
* It requires that all members of [[org.enso.compiler.core.ir.IRKind.Primitive]] have been removed * It requires that all members of [[org.enso.compiler.core.ir.IRKind.Primitive]] have been removed
* from the IR by the time it runs. * from the IR by the time it runs.
@ -166,7 +166,7 @@ case object DataflowAnalysis extends IRPass {
method method
.copy(body = analyseExpression(body, info)) .copy(body = analyseExpression(body, info))
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case tp @ Definition.Type(_, params, members, _, _, _) => case tp @ Definition.Type(_, params, members, _, _) =>
val tpDep = asStatic(tp) val tpDep = asStatic(tp)
val newParams = params.map { param => val newParams = params.map { param =>
val paramDep = asStatic(param) val paramDep = asStatic(param)
@ -249,7 +249,7 @@ case object DataflowAnalysis extends IRPass {
case foreign: Foreign => case foreign: Foreign =>
foreign.updateMetadata(new MetadataPair(this, info)) foreign.updateMetadata(new MetadataPair(this, info))
case block @ Expression.Block(expressions, returnValue, _, _, _, _) => case block @ Expression.Block(expressions, returnValue, _, _, _) =>
val retValDep = asStatic(returnValue) val retValDep = asStatic(returnValue)
val blockDep = asStatic(block) val blockDep = asStatic(block)
info.dependents.updateAt(retValDep, Set(blockDep)) info.dependents.updateAt(retValDep, Set(blockDep))
@ -261,7 +261,7 @@ case object DataflowAnalysis extends IRPass {
returnValue = analyseExpression(returnValue, info) returnValue = analyseExpression(returnValue, info)
) )
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case binding @ Expression.Binding(name, expression, _, _, _) => case binding @ Expression.Binding(name, expression, _, _) =>
val expressionDep = asStatic(expression) val expressionDep = asStatic(expression)
val nameDep = asStatic(name) val nameDep = asStatic(name)
val bindingDep = asStatic(binding) val bindingDep = asStatic(binding)
@ -331,7 +331,7 @@ case object DataflowAnalysis extends IRPass {
info: DependencyInfo info: DependencyInfo
): Application = { ): Application = {
application match { application match {
case prefix @ Application.Prefix(fn, args, _, _, _, _) => case prefix @ Application.Prefix(fn, args, _, _, _) =>
val fnDep = asStatic(fn) val fnDep = asStatic(fn)
val prefixDep = asStatic(prefix) val prefixDep = asStatic(prefix)
info.dependents.updateAt(fnDep, Set(prefixDep)) info.dependents.updateAt(fnDep, Set(prefixDep))
@ -348,7 +348,7 @@ case object DataflowAnalysis extends IRPass {
arguments = args.map(analyseCallArgument(_, info)) arguments = args.map(analyseCallArgument(_, info))
) )
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case force @ Application.Force(target, _, _, _) => case force @ Application.Force(target, _, _) =>
val targetDep = asStatic(target) val targetDep = asStatic(target)
val forceDep = asStatic(force) val forceDep = asStatic(force)
info.dependents.updateAt(targetDep, Set(forceDep)) info.dependents.updateAt(targetDep, Set(forceDep))
@ -357,7 +357,7 @@ case object DataflowAnalysis extends IRPass {
force force
.copy(target = analyseExpression(target, info)) .copy(target = analyseExpression(target, info))
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case vector @ Application.Sequence(items, _, _, _) => case vector @ Application.Sequence(items, _, _) =>
val vectorDep = asStatic(vector) val vectorDep = asStatic(vector)
items.foreach(it => { items.foreach(it => {
val itemDep = asStatic(it) val itemDep = asStatic(it)
@ -368,7 +368,7 @@ case object DataflowAnalysis extends IRPass {
vector vector
.copy(items = items.map(analyseExpression(_, info))) .copy(items = items.map(analyseExpression(_, info)))
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case tSet @ Application.Typeset(expr, _, _, _) => case tSet @ Application.Typeset(expr, _, _) =>
val tSetDep = asStatic(tSet) val tSetDep = asStatic(tSet)
expr.foreach(exp => { expr.foreach(exp => {
val exprDep = asStatic(exp) val exprDep = asStatic(exp)
@ -394,7 +394,7 @@ case object DataflowAnalysis extends IRPass {
*/ */
def analyseType(typ: Type, info: DependencyInfo): Type = { def analyseType(typ: Type, info: DependencyInfo): Type = {
typ match { typ match {
case asc @ Type.Ascription(typed, signature, _, _, _, _) => case asc @ Type.Ascription(typed, signature, _, _, _) =>
val ascrDep = asStatic(asc) val ascrDep = asStatic(asc)
val typedDep = asStatic(typed) val typedDep = asStatic(typed)
val sigDep = asStatic(signature) val sigDep = asStatic(signature)
@ -409,7 +409,7 @@ case object DataflowAnalysis extends IRPass {
) )
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case fun @ Type.Function(args, result, _, _, _) => case fun @ Type.Function(args, result, _, _) =>
val funDep = asStatic(fun) val funDep = asStatic(fun)
val argDeps = args.map(asStatic) val argDeps = args.map(asStatic)
val resDep = asStatic(result) val resDep = asStatic(result)
@ -423,7 +423,7 @@ case object DataflowAnalysis extends IRPass {
result = analyseExpression(result, info) result = analyseExpression(result, info)
) )
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case ctx @ Type.Context(typed, context, _, _, _) => case ctx @ Type.Context(typed, context, _, _) =>
val ctxDep = asStatic(ctx) val ctxDep = asStatic(ctx)
val typedDep = asStatic(typed) val typedDep = asStatic(typed)
val contextDep = asStatic(context) val contextDep = asStatic(context)
@ -437,7 +437,7 @@ case object DataflowAnalysis extends IRPass {
context = analyseExpression(context, info) context = analyseExpression(context, info)
) )
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case err @ Type.Error(typed, error, _, _, _) => case err @ Type.Error(typed, error, _, _) =>
val errDep = asStatic(err) val errDep = asStatic(err)
val typedDep = asStatic(typed) val typedDep = asStatic(typed)
val errorDep = asStatic(error) val errorDep = asStatic(error)
@ -451,7 +451,7 @@ case object DataflowAnalysis extends IRPass {
error = analyseExpression(error, info) error = analyseExpression(error, info)
) )
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case member @ `type`.Set.Member(_, memberType, value, _, _, _) => case member @ `type`.Set.Member(_, memberType, value, _, _) =>
val memberDep = asStatic(member) val memberDep = asStatic(member)
val memberTypeDep = asStatic(memberType) val memberTypeDep = asStatic(memberType)
val valueDep = asStatic(value) val valueDep = asStatic(value)
@ -465,7 +465,7 @@ case object DataflowAnalysis extends IRPass {
value = analyseExpression(value, info) value = analyseExpression(value, info)
) )
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case concat @ `type`.Set.Concat(left, right, _, _, _) => case concat @ `type`.Set.Concat(left, right, _, _) =>
val concatDep = asStatic(concat) val concatDep = asStatic(concat)
val leftDep = asStatic(left) val leftDep = asStatic(left)
val rightDep = asStatic(right) val rightDep = asStatic(right)
@ -479,7 +479,7 @@ case object DataflowAnalysis extends IRPass {
right = analyseExpression(right, info) right = analyseExpression(right, info)
) )
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case eq @ `type`.Set.Equality(left, right, _, _, _) => case eq @ `type`.Set.Equality(left, right, _, _) =>
val eqDep = asStatic(eq) val eqDep = asStatic(eq)
val leftDep = asStatic(left) val leftDep = asStatic(left)
val rightDep = asStatic(right) val rightDep = asStatic(right)
@ -491,7 +491,7 @@ case object DataflowAnalysis extends IRPass {
left = analyseExpression(left, info), left = analyseExpression(left, info),
right = analyseExpression(right, info) right = analyseExpression(right, info)
).updateMetadata(new MetadataPair(this, info)) ).updateMetadata(new MetadataPair(this, info))
case intersect @ `type`.Set.Intersection(left, right, _, _, _) => case intersect @ `type`.Set.Intersection(left, right, _, _) =>
val intersectDep = asStatic(intersect) val intersectDep = asStatic(intersect)
val leftDep = asStatic(left) val leftDep = asStatic(left)
val rightDep = asStatic(right) val rightDep = asStatic(right)
@ -505,7 +505,7 @@ case object DataflowAnalysis extends IRPass {
right = analyseExpression(right, info) right = analyseExpression(right, info)
) )
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case union @ `type`.Set.Union(operands, _, _, _) => case union @ `type`.Set.Union(operands, _, _) =>
val unionDep = asStatic(union) val unionDep = asStatic(union)
val opDeps = operands.map(asStatic) val opDeps = operands.map(asStatic)
opDeps.foreach(info.dependents.updateAt(_, Set(unionDep))) opDeps.foreach(info.dependents.updateAt(_, Set(unionDep)))
@ -513,7 +513,7 @@ case object DataflowAnalysis extends IRPass {
union union
.copy(operands = operands.map(analyseExpression(_, info))) .copy(operands = operands.map(analyseExpression(_, info)))
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case subsumption @ `type`.Set.Subsumption(left, right, _, _, _) => case subsumption @ `type`.Set.Subsumption(left, right, _, _) =>
val subDep = asStatic(subsumption) val subDep = asStatic(subsumption)
val leftDep = asStatic(left) val leftDep = asStatic(left)
val rightDep = asStatic(right) val rightDep = asStatic(right)
@ -658,13 +658,13 @@ case object DataflowAnalysis extends IRPass {
): Pattern = { ): Pattern = {
val patternDep = asStatic(pattern) val patternDep = asStatic(pattern)
pattern match { pattern match {
case named @ Pattern.Name(name, _, _, _) => case named @ Pattern.Name(name, _, _) =>
val nameDep = asStatic(name) val nameDep = asStatic(name)
info.dependents.updateAt(nameDep, Set(patternDep)) info.dependents.updateAt(nameDep, Set(patternDep))
info.dependencies.updateAt(patternDep, Set(nameDep)) info.dependencies.updateAt(patternDep, Set(nameDep))
named.updateMetadata(new MetadataPair(this, info)) named.updateMetadata(new MetadataPair(this, info))
case cons @ Pattern.Constructor(constructor, fields, _, _, _) => case cons @ Pattern.Constructor(constructor, fields, _, _) =>
val consDep = asStatic(constructor) val consDep = asStatic(constructor)
info.dependents.updateAt(consDep, Set(patternDep)) info.dependents.updateAt(consDep, Set(patternDep))
info.dependencies.updateAt(patternDep, Set(consDep)) info.dependencies.updateAt(patternDep, Set(consDep))
@ -682,7 +682,7 @@ case object DataflowAnalysis extends IRPass {
.updateMetadata(new MetadataPair(this, info)) .updateMetadata(new MetadataPair(this, info))
case literal: Pattern.Literal => case literal: Pattern.Literal =>
literal.updateMetadata(new MetadataPair(this, info)) literal.updateMetadata(new MetadataPair(this, info))
case Pattern.Type(name, tpe, _, _, _) => case Pattern.Type(name, tpe, _, _) =>
val nameDep = asStatic(name) val nameDep = asStatic(name)
info.dependents.updateAt(nameDep, Set(patternDep)) info.dependents.updateAt(nameDep, Set(patternDep))
info.dependencies.updateAt(patternDep, Set(nameDep)) info.dependencies.updateAt(patternDep, Set(nameDep))
@ -714,7 +714,7 @@ case object DataflowAnalysis extends IRPass {
info: DependencyInfo info: DependencyInfo
): DefinitionArgument = { ): DefinitionArgument = {
argument match { argument match {
case spec @ DefinitionArgument.Specified(_, _, defValue, _, _, _, _) => case spec @ DefinitionArgument.Specified(_, _, defValue, _, _, _) =>
val specDep = asStatic(spec) val specDep = asStatic(spec)
defValue.foreach(expr => { defValue.foreach(expr => {
val exprDep = asStatic(expr) val exprDep = asStatic(expr)
@ -744,7 +744,7 @@ case object DataflowAnalysis extends IRPass {
info: DependencyInfo info: DependencyInfo
): CallArgument = { ): CallArgument = {
argument match { argument match {
case spec @ CallArgument.Specified(name, value, _, _, _) => case spec @ CallArgument.Specified(name, value, _, _) =>
val specDep = asStatic(spec) val specDep = asStatic(spec)
val valueDep = asStatic(value) val valueDep = asStatic(value)
info.dependents.updateAt(valueDep, Set(specDep)) info.dependents.updateAt(valueDep, Set(specDep))

View File

@ -116,14 +116,14 @@ case object DemandAnalysis extends IRPass {
analyseType(typ, isInsideCallArgument) analyseType(typ, isInsideCallArgument)
case cse: Case => case cse: Case =>
analyseCase(cse, isInsideCallArgument) analyseCase(cse, isInsideCallArgument)
case block @ Expression.Block(expressions, retVal, _, _, _, _) => case block @ Expression.Block(expressions, retVal, _, _, _) =>
block.copy( block.copy(
expressions = expressions.map(x => expressions = expressions.map(x =>
analyseExpression(x, isInsideCallArgument = false) analyseExpression(x, isInsideCallArgument = false)
), ),
returnValue = analyseExpression(retVal, isInsideCallArgument = false) returnValue = analyseExpression(retVal, isInsideCallArgument = false)
) )
case binding @ Expression.Binding(_, expression, _, _, _) => case binding @ Expression.Binding(_, expression, _, _) =>
binding.copy(expression = binding.copy(expression =
analyseExpression( analyseExpression(
expression, expression,
@ -219,7 +219,7 @@ case object DemandAnalysis extends IRPass {
isInsideCallArgument: Boolean isInsideCallArgument: Boolean
): Application = ): Application =
application match { application match {
case pref @ Application.Prefix(fn, args, _, _, _, _) => case pref @ Application.Prefix(fn, args, _, _, _) =>
val newFun = fn match { val newFun = fn match {
case n: Name => n case n: Name => n
case e => analyseExpression(e, isInsideCallArgument = false) case e => analyseExpression(e, isInsideCallArgument = false)
@ -228,14 +228,14 @@ case object DemandAnalysis extends IRPass {
function = newFun, function = newFun,
arguments = args.map(analyseCallArgument) arguments = args.map(analyseCallArgument)
) )
case force @ Application.Force(target, _, _, _) => case force @ Application.Force(target, _, _) =>
force.copy(target = force.copy(target =
analyseExpression( analyseExpression(
target, target,
isInsideCallArgument isInsideCallArgument
) )
) )
case vec @ Application.Sequence(items, _, _, _) => case vec @ Application.Sequence(items, _, _) =>
vec.copy(items = vec.copy(items =
items.map( items.map(
analyseExpression( analyseExpression(
@ -244,7 +244,7 @@ case object DemandAnalysis extends IRPass {
) )
) )
) )
case tSet @ Application.Typeset(expr, _, _, _) => case tSet @ Application.Typeset(expr, _, _) =>
tSet.copy( tSet.copy(
expression = expression =
expr.map(analyseExpression(_, isInsideCallArgument = false)) expr.map(analyseExpression(_, isInsideCallArgument = false))
@ -266,7 +266,7 @@ case object DemandAnalysis extends IRPass {
*/ */
def analyseCallArgument(arg: CallArgument): CallArgument = { def analyseCallArgument(arg: CallArgument): CallArgument = {
arg match { arg match {
case spec @ CallArgument.Specified(_, expr, _, _, _) => case spec @ CallArgument.Specified(_, expr, _, _) =>
spec.copy( spec.copy(
value = analyseExpression( value = analyseExpression(
expr, expr,
@ -285,7 +285,7 @@ case object DemandAnalysis extends IRPass {
arg: DefinitionArgument arg: DefinitionArgument
): DefinitionArgument = { ): DefinitionArgument = {
arg match { arg match {
case spec @ DefinitionArgument.Specified(_, _, default, _, _, _, _) => case spec @ DefinitionArgument.Specified(_, _, default, _, _, _) =>
spec.copy( spec.copy(
defaultValue = default.map(x => defaultValue = default.map(x =>
analyseExpression( analyseExpression(
@ -322,7 +322,7 @@ case object DemandAnalysis extends IRPass {
isInsideCallArgument: Boolean isInsideCallArgument: Boolean
): Case = ): Case =
cse match { cse match {
case expr @ Case.Expr(scrutinee, branches, _, _, _, _) => case expr @ Case.Expr(scrutinee, branches, _, _, _) =>
expr.copy( expr.copy(
scrutinee = analyseExpression( scrutinee = analyseExpression(
scrutinee, scrutinee,

View File

@ -28,7 +28,7 @@ import org.enso.compiler.pass.analyse.alias.AliasMetadata
import org.enso.compiler.pass.analyse.alias.graph.{Graph, GraphOccurrence} import org.enso.compiler.pass.analyse.alias.graph.{Graph, GraphOccurrence}
/** This pass attaches [[FramePointer]] as metadata to all the IR elements that already /** This pass attaches [[FramePointer]] as metadata to all the IR elements that already
* have [[org.enso.compiler.pass.analyse.alias.Info.Occurrence]] attached. * have [[org.enso.compiler.pass.analyse.alias.AliasMetadata.Occurrence]] attached.
* It does not replace the IR elements with errors, it just attaches metadata. * It does not replace the IR elements with errors, it just attaches metadata.
*/ */
case object FramePointerAnalysis extends IRPass { case object FramePointerAnalysis extends IRPass {
@ -112,7 +112,7 @@ case object FramePointerAnalysis extends IRPass {
): Unit = { ): Unit = {
args.foreach { arg => args.foreach { arg =>
arg.name match { arg.name match {
case Name.Self(loc, synthetic, _, _) if loc.isEmpty && synthetic => case Name.Self(loc, synthetic, _) if loc.isEmpty && synthetic =>
// synthetic self argument has occurrence attached, but there is no Occurence.Def for it. // synthetic self argument has occurrence attached, but there is no Occurence.Def for it.
// So we have to handle it specially. // So we have to handle it specially.
updateMeta(arg, new FramePointer(0, 1)) updateMeta(arg, new FramePointer(0, 1))
@ -146,7 +146,7 @@ case object FramePointerAnalysis extends IRPass {
case Function.Lambda(args, body, _, _, _, _) => case Function.Lambda(args, body, _, _, _, _) =>
processArgumentDefs(args, graph) processArgumentDefs(args, graph)
processExpression(body, graph) processExpression(body, graph)
case binding @ Expression.Binding(name, expr, _, _, _) => case binding @ Expression.Binding(name, expr, _, _) =>
maybeAttachFramePointer(binding, graph) maybeAttachFramePointer(binding, graph)
maybeAttachFramePointer(name, graph) maybeAttachFramePointer(name, graph)
processExpression(expr, graph) processExpression(expr, graph)
@ -204,17 +204,17 @@ case object FramePointerAnalysis extends IRPass {
graph: Graph graph: Graph
): Unit = { ): Unit = {
application match { application match {
case app @ Application.Prefix(func, arguments, _, _, _, _) => case app @ Application.Prefix(func, arguments, _, _, _) =>
maybeAttachFramePointer(app, graph) maybeAttachFramePointer(app, graph)
processExpression(func, graph) processExpression(func, graph)
processCallArguments(arguments, graph) processCallArguments(arguments, graph)
case Application.Force(expr, _, _, _) => case Application.Force(expr, _, _) =>
processExpression(expr, graph) processExpression(expr, graph)
case Application.Sequence(items, _, _, _) => case Application.Sequence(items, _, _) =>
items.foreach { item => items.foreach { item =>
processExpression(item, graph) processExpression(item, graph)
} }
case Application.Typeset(expr, _, _, _) => case Application.Typeset(expr, _, _) =>
expr.foreach(processExpression(_, graph)) expr.foreach(processExpression(_, graph))
case _ => case _ =>
throw new CompilerError( throw new CompilerError(
@ -227,8 +227,7 @@ case object FramePointerAnalysis extends IRPass {
arguments: List[CallArgument], arguments: List[CallArgument],
graph: Graph graph: Graph
): Unit = { ): Unit = {
arguments.foreach { arguments.foreach { case arg @ CallArgument.Specified(name, value, _, _) =>
case arg @ CallArgument.Specified(name, value, _, _, _) =>
maybeAttachFramePointer(arg, graph) maybeAttachFramePointer(arg, graph)
name.foreach(maybeAttachFramePointer(_, graph)) name.foreach(maybeAttachFramePointer(_, graph))
processExpression(value, graph) processExpression(value, graph)
@ -236,7 +235,7 @@ case object FramePointerAnalysis extends IRPass {
} }
/** Attaches [[FramePointerMeta]] metadata to the given `ir` if there is an /** Attaches [[FramePointerMeta]] metadata to the given `ir` if there is an
* appropriate [[Info.Occurrence]] already attached to it. * appropriate [[AliasMetadata.Occurrence]] already attached to it.
* @param ir IR to attach the frame pointer metadata to. * @param ir IR to attach the frame pointer metadata to.
* @param graph Alias analysis graph * @param graph Alias analysis graph
* @return Copy of `ir` with attached metadata, or just the `ir` if nothing * @return Copy of `ir` with attached metadata, or just the `ir` if nothing

View File

@ -62,7 +62,7 @@ case object GatherDiagnostics extends IRPass {
* @return `ir`, with all diagnostics from its subtree associated with it * @return `ir`, with all diagnostics from its subtree associated with it
*/ */
private def gatherMetadata(ir: IR): DiagnosticsMeta = { private def gatherMetadata(ir: IR): DiagnosticsMeta = {
val diagnostics = ir.preorder.collect { val diagnostics = ir.preorder.flatMap {
case err: Diagnostic => case err: Diagnostic =>
List(err) List(err)
case arg: DefinitionArgument => case arg: DefinitionArgument =>
@ -71,7 +71,7 @@ case object GatherDiagnostics extends IRPass {
.getMetadata(TypeSignatures) .getMetadata(TypeSignatures)
.map(_.signature.preorder.collect(collectDiagnostics)) .map(_.signature.preorder.collect(collectDiagnostics))
.getOrElse(Nil) .getOrElse(Nil)
typeSignatureDiagnostics ++ arg.diagnostics.toList typeSignatureDiagnostics ++ diagnosticsList(arg)
case x: definition.Method => case x: definition.Method =>
val typeSignatureDiagnostics = val typeSignatureDiagnostics =
x.getMetadata(TypeSignatures) x.getMetadata(TypeSignatures)
@ -81,16 +81,16 @@ case object GatherDiagnostics extends IRPass {
x.getMetadata(GenericAnnotations) x.getMetadata(GenericAnnotations)
.map(_.annotations.flatMap(_.preorder.collect(collectDiagnostics))) .map(_.annotations.flatMap(_.preorder.collect(collectDiagnostics)))
.getOrElse(Nil) .getOrElse(Nil)
typeSignatureDiagnostics ++ annotationsDiagnostics ++ x.diagnostics.toList typeSignatureDiagnostics ++ annotationsDiagnostics ++ diagnosticsList(x)
case x: Expression => case x: Expression =>
val typeSignatureDiagnostics = val typeSignatureDiagnostics =
x.getMetadata(TypeSignatures) x.getMetadata(TypeSignatures)
.map(_.signature.preorder.collect(collectDiagnostics)) .map(_.signature.preorder.collect(collectDiagnostics))
.getOrElse(Nil) .getOrElse(Nil)
typeSignatureDiagnostics ++ x.diagnostics.toList typeSignatureDiagnostics ++ diagnosticsList(x)
case x => case x =>
x.diagnostics.toList diagnosticsList(x)
}.flatten }
DiagnosticsMeta( DiagnosticsMeta(
diagnostics.distinctBy(d => new DiagnosticKeys(d)) diagnostics.distinctBy(d => new DiagnosticKeys(d))
) )
@ -100,6 +100,9 @@ case object GatherDiagnostics extends IRPass {
case err: Diagnostic => err case err: Diagnostic => err
} }
private def diagnosticsList(ir: IR): List[Diagnostic] =
if (ir.diagnostics() eq null) Nil else ir.diagnostics().toList
final private class DiagnosticKeys(private val diagnostic: Diagnostic) { final private class DiagnosticKeys(private val diagnostic: Diagnostic) {
/** Equals is based on type of diagnostic, its location and its diagnostic keys. /** Equals is based on type of diagnostic, its location and its diagnostic keys.

View File

@ -63,7 +63,6 @@ case object ImportSymbolAnalysis extends IRPass {
_, _,
_, _,
_, _,
_,
_ _
) => ) =>
bindingMap.resolvedImports.find(_.importDef == imp) match { bindingMap.resolvedImports.find(_.importDef == imp) match {
@ -96,7 +95,6 @@ case object ImportSymbolAnalysis extends IRPass {
_, _,
_, _,
isSynthetic, isSynthetic,
_,
_ _
) if isAll && !isSynthetic => ) if isAll && !isSynthetic =>
bindingMap.resolvedImports.find(_.importDef == imp) match { bindingMap.resolvedImports.find(_.importDef == imp) match {

View File

@ -100,7 +100,7 @@ case object TailCall extends IRPass {
/** Performs tail call analysis on a top-level definition in a module. /** Performs tail call analysis on a top-level definition in a module.
* *
* @param definition the top-level definition to analyse * @param moduleDefinition the top-level definition to analyse
* @return `definition`, annotated with tail call information * @return `definition`, annotated with tail call information
*/ */
private def analyseModuleBinding( private def analyseModuleBinding(
@ -189,14 +189,7 @@ case object TailCall extends IRPass {
throw new CompilerError( throw new CompilerError(
"Comments should not be present during tail call analysis." "Comments should not be present during tail call analysis."
) )
case block @ Expression.Block( case block @ Expression.Block(expressions, returnValue, _, _, _) =>
expressions,
returnValue,
_,
_,
_,
_
) =>
block block
.copy( .copy(
expressions = expressions.map( expressions = expressions.map(
@ -207,7 +200,7 @@ case object TailCall extends IRPass {
.updateMetadata( .updateMetadata(
new MetadataPair(this, TailPosition.fromBool(isInTailPosition)) new MetadataPair(this, TailPosition.fromBool(isInTailPosition))
) )
case binding @ Expression.Binding(_, expression, _, _, _) => case binding @ Expression.Binding(_, expression, _, _) =>
binding binding
.copy( .copy(
expression = analyseExpression(expression, isInTailPosition = false) expression = analyseExpression(expression, isInTailPosition = false)
@ -241,7 +234,7 @@ case object TailCall extends IRPass {
* or not * or not
* @return `literal`, annotated with tail position metdata * @return `literal`, annotated with tail position metdata
*/ */
def analyseLiteral( private def analyseLiteral(
literal: Literal, literal: Literal,
isInTailPosition: Boolean isInTailPosition: Boolean
): Literal = { ): Literal = {
@ -262,7 +255,7 @@ case object TailCall extends IRPass {
isInTailPosition: Boolean isInTailPosition: Boolean
): Application = { ): Application = {
application match { application match {
case app @ Application.Prefix(fn, args, _, _, _, _) => case app @ Application.Prefix(fn, args, _, _, _) =>
app app
.copy( .copy(
function = analyseExpression(fn, isInTailPosition = false), function = analyseExpression(fn, isInTailPosition = false),
@ -271,7 +264,7 @@ case object TailCall extends IRPass {
.updateMetadata( .updateMetadata(
new MetadataPair(this, TailPosition.fromBool(isInTailPosition)) new MetadataPair(this, TailPosition.fromBool(isInTailPosition))
) )
case force @ Application.Force(target, _, _, _) => case force @ Application.Force(target, _, _) =>
force force
.copy( .copy(
target = analyseExpression(target, isInTailPosition) target = analyseExpression(target, isInTailPosition)
@ -279,7 +272,7 @@ case object TailCall extends IRPass {
.updateMetadata( .updateMetadata(
new MetadataPair(this, TailPosition.fromBool(isInTailPosition)) new MetadataPair(this, TailPosition.fromBool(isInTailPosition))
) )
case vector @ Application.Sequence(items, _, _, _) => case vector @ Application.Sequence(items, _, _) =>
vector vector
.copy(items = .copy(items =
items.map(analyseExpression(_, isInTailPosition = false)) items.map(analyseExpression(_, isInTailPosition = false))
@ -287,7 +280,7 @@ case object TailCall extends IRPass {
.updateMetadata( .updateMetadata(
new MetadataPair(this, TailPosition.fromBool(isInTailPosition)) new MetadataPair(this, TailPosition.fromBool(isInTailPosition))
) )
case tSet @ Application.Typeset(expr, _, _, _) => case tSet @ Application.Typeset(expr, _, _) =>
tSet tSet
.copy(expression = .copy(expression =
expr.map(analyseExpression(_, isInTailPosition = false)) expr.map(analyseExpression(_, isInTailPosition = false))
@ -305,9 +298,9 @@ case object TailCall extends IRPass {
* @param argument the argument to analyse * @param argument the argument to analyse
* @return `argument`, annotated with tail position metadata * @return `argument`, annotated with tail position metadata
*/ */
def analyseCallArg(argument: CallArgument): CallArgument = { private def analyseCallArg(argument: CallArgument): CallArgument = {
argument match { argument match {
case arg @ CallArgument.Specified(_, expr, _, _, _) => case arg @ CallArgument.Specified(_, expr, _, _) =>
arg arg
.copy( .copy(
// Note [Call Argument Tail Position] // Note [Call Argument Tail Position]
@ -364,7 +357,7 @@ case object TailCall extends IRPass {
*/ */
def analyseCase(caseExpr: Case, isInTailPosition: Boolean): Case = { def analyseCase(caseExpr: Case, isInTailPosition: Boolean): Case = {
caseExpr match { caseExpr match {
case caseExpr @ Case.Expr(scrutinee, branches, _, _, _, _) => case caseExpr @ Case.Expr(scrutinee, branches, _, _, _) =>
caseExpr caseExpr
.copy( .copy(
scrutinee = analyseExpression(scrutinee, isInTailPosition = false), scrutinee = analyseExpression(scrutinee, isInTailPosition = false),
@ -423,13 +416,13 @@ case object TailCall extends IRPass {
pattern: Pattern pattern: Pattern
): Pattern = { ): Pattern = {
pattern match { pattern match {
case namePat @ Pattern.Name(name, _, _, _) => case namePat @ Pattern.Name(name, _, _) =>
namePat namePat
.copy( .copy(
name = analyseName(name, isInTailPosition = false) name = analyseName(name, isInTailPosition = false)
) )
.updateMetadata(new MetadataPair(this, TailPosition.NotTail)) .updateMetadata(new MetadataPair(this, TailPosition.NotTail))
case cons @ Pattern.Constructor(constructor, fields, _, _, _) => case cons @ Pattern.Constructor(constructor, fields, _, _) =>
cons cons
.copy( .copy(
constructor = analyseName(constructor, isInTailPosition = false), constructor = analyseName(constructor, isInTailPosition = false),
@ -439,7 +432,7 @@ case object TailCall extends IRPass {
case literal: Pattern.Literal => case literal: Pattern.Literal =>
literal literal
.updateMetadata(new MetadataPair(this, TailPosition.NotTail)) .updateMetadata(new MetadataPair(this, TailPosition.NotTail))
case tpePattern @ Pattern.Type(name, tpe, _, _, _) => case tpePattern @ Pattern.Type(name, tpe, _, _) =>
tpePattern tpePattern
.copy( .copy(
name = analyseName(name, isInTailPosition = false), name = analyseName(name, isInTailPosition = false),
@ -490,9 +483,11 @@ case object TailCall extends IRPass {
* @param arg the argument definition to analyse * @param arg the argument definition to analyse
* @return `arg`, annotated with tail position metadata * @return `arg`, annotated with tail position metadata
*/ */
def analyseDefArgument(arg: DefinitionArgument): DefinitionArgument = { private def analyseDefArgument(
arg: DefinitionArgument
): DefinitionArgument = {
arg match { arg match {
case arg @ DefinitionArgument.Specified(_, _, default, _, _, _, _) => case arg @ DefinitionArgument.Specified(_, _, default, _, _, _) =>
arg arg
.copy( .copy(
defaultValue = default.map(x => defaultValue = default.map(x =>

View File

@ -167,7 +167,7 @@ case object ComplexType extends IRPass {
): List[Definition] = { ): List[Definition] = {
var unusedSig: Option[Type.Ascription] = None var unusedSig: Option[Type.Ascription] = None
val sig = lastSignature match { val sig = lastSignature match {
case Some(Type.Ascription(typed, _, _, _, _, _)) => case Some(Type.Ascription(typed, _, _, _, _)) =>
typed match { typed match {
case literal: Name.Literal => case literal: Name.Literal =>
if (name.name == literal.name) { if (name.name == literal.name) {
@ -197,9 +197,9 @@ case object ComplexType extends IRPass {
val res = lastSignature val res = lastSignature
lastSignature = Some(sig) lastSignature = Some(sig)
res res
case binding @ Expression.Binding(name, _, _, _, _) => case binding @ Expression.Binding(name, _, _, _) =>
matchSignaturesAndGenerate(name, binding) matchSignaturesAndGenerate(name, binding)
case funSugar @ Function.Binding(name, _, _, _, _, _, _, _) => case funSugar @ Function.Binding(name, _, _, _, _, _, _) =>
matchSignaturesAndGenerate(name, funSugar) matchSignaturesAndGenerate(name, funSugar)
case err: Error => Seq(err) case err: Error => Seq(err)
case ann: Name.GenericAnnotation => Seq(ann) case ann: Name.GenericAnnotation => Seq(ann)
@ -248,9 +248,14 @@ case object ComplexType extends IRPass {
signature: Option[Type.Ascription] signature: Option[Type.Ascription]
): List[Definition] = { ): List[Definition] = {
ir match { ir match {
case Expression.Binding(name, expr, location, passData, diagnostics) => case expressionBinding @ Expression.Binding(
name,
expr,
location,
passData
) =>
val realExpr = expr match { val realExpr = expr match {
case b @ Expression.Block(_, _, _, suspended, _, _) if suspended => case b @ Expression.Block(_, _, _, suspended, _) if suspended =>
b.copy(suspended = false) b.copy(suspended = false)
case _ => expr case _ => expr
} }
@ -263,18 +268,17 @@ case object ComplexType extends IRPass {
false, false,
location, location,
passData, passData,
diagnostics, expressionBinding.diagnosticsCopy,
signature signature
) )
case Function.Binding( case functionBinding @ Function.Binding(
name, name,
args, args,
body, body,
isPrivate, isPrivate,
location, location,
_, _,
passData, passData
diagnostics
) => ) =>
genForName( genForName(
typeName, typeName,
@ -284,7 +288,7 @@ case object ComplexType extends IRPass {
isPrivate, isPrivate,
location, location,
passData, passData,
diagnostics, functionBinding.diagnosticsCopy,
signature signature
) )
case _ => case _ =>
@ -324,14 +328,14 @@ case object ComplexType extends IRPass {
val newSig = val newSig =
signature.map(sig => sig.copy(typed = methodRef.duplicate()).duplicate()) signature.map(sig => sig.copy(typed = methodRef.duplicate()).duplicate())
val binding = definition.Method.Binding( val binding = new definition.Method.Binding(
methodRef.duplicate(), methodRef.duplicate(),
args.map(_.duplicate()), args.map(_.duplicate()),
isPrivate, isPrivate,
body.duplicate(), body.duplicate(),
location, location,
passData.duplicate, passData.duplicate,
diagnostics.copy diagnostics
) )
newSig.toList :+ binding newSig.toList :+ binding

View File

@ -95,15 +95,14 @@ case object FunctionBinding extends IRPass {
*/ */
def desugarExpression(ir: Expression): Expression = { def desugarExpression(ir: Expression): Expression = {
ir.transformExpressions { ir.transformExpressions {
case Function.Binding( case functionBinding @ Function.Binding(
name, _,
args, args,
body, body,
_, _,
location, location,
canBeTCO, canBeTCO,
passData, _
diagnostics
) => ) =>
if (args.isEmpty) { if (args.isEmpty) {
throw new CompilerError("The arguments list should not be empty.") throw new CompilerError("The arguments list should not be empty.")
@ -117,16 +116,16 @@ case object FunctionBinding extends IRPass {
.asInstanceOf[Function.Lambda] .asInstanceOf[Function.Lambda]
.copy(canBeTCO = canBeTCO, location = location) .copy(canBeTCO = canBeTCO, location = location)
Expression.Binding(name, lambda, location, passData, diagnostics) new Expression.Binding(functionBinding, lambda)
} }
} }
/** Performs desugaring on a module definition. /** Performs desugaring on a module definition.
* *
* @param definition the module definition to desugar * @param moduleDefinition the module definition to desugar
* @return `definition`, with any function definition sugar removed * @return `definition`, with any function definition sugar removed
*/ */
def desugarModuleSymbol( private def desugarModuleSymbol(
moduleDefinition: Definition moduleDefinition: Definition
): Definition = { ): Definition = {
moduleDefinition match { moduleDefinition match {
@ -150,19 +149,17 @@ case object FunctionBinding extends IRPass {
isPrivate, isPrivate,
_, _,
_, _,
_,
_ _
) if isPrivate && methRef.methodName.name == conversionMethodName => ) if isPrivate && methRef.methodName.name == conversionMethodName =>
errors.Conversion(meth, errors.Conversion.DeclaredAsPrivate) errors.Conversion(meth, errors.Conversion.DeclaredAsPrivate)
case meth @ definition.Method.Binding( case methodBinding @ definition.Method.Binding(
methRef, methRef,
args, args,
isPrivate, isPrivate,
body, body,
loc, _,
passData, _
diagnostics
) => ) =>
val methodName = methRef.methodName.name val methodName = methRef.methodName.name
@ -173,17 +170,10 @@ case object FunctionBinding extends IRPass {
new Function.Lambda(List(arg), body, None) new Function.Lambda(List(arg), body, None)
) )
new definition.Method.Explicit( new definition.Method.Explicit(methodBinding, newBody)
methRef,
newBody,
isPrivate,
loc,
passData,
diagnostics
)
} else { } else {
if (args.isEmpty) if (args.isEmpty)
errors.Conversion(meth, errors.Conversion.MissingArgs) errors.Conversion(methodBinding, errors.Conversion.MissingArgs)
else if (args.head.ascribedType.isEmpty) { else if (args.head.ascribedType.isEmpty) {
errors.Conversion( errors.Conversion(
args.head, args.head,
@ -271,13 +261,10 @@ case object FunctionBinding extends IRPass {
new Function.Lambda(List(arg), body, None) new Function.Lambda(List(arg), body, None)
) )
Right( Right(
definition.Method.Conversion( new definition.Method.Conversion(
methRef, methodBinding,
firstArgumentType, firstArgumentType,
newBody, newBody
loc,
passData,
diagnostics
) )
) )
} }

View File

@ -21,7 +21,7 @@ import org.enso.compiler.pass.analyse.{
TailCall TailCall
} }
import org.enso.compiler.pass.lint.UnusedBindings import org.enso.compiler.pass.lint.UnusedBindings
import org.enso.compiler.pass.optimise.{LambdaConsolidate} import org.enso.compiler.pass.optimise.LambdaConsolidate
import org.enso.compiler.pass.resolve.{ import org.enso.compiler.pass.resolve.{
DocumentationComments, DocumentationComments,
IgnoredBindings, IgnoredBindings,
@ -137,7 +137,7 @@ case object LambdaShorthandToLambda extends IRPass {
* @param supply the compiler's fresh name supply * @param supply the compiler's fresh name supply
* @return `name`, desugared where necessary * @return `name`, desugared where necessary
*/ */
def desugarName(name: Name, supply: FreshNameSupply): Expression = { private def desugarName(name: Name, supply: FreshNameSupply): Expression = {
name match { name match {
case blank: Name.Blank => case blank: Name.Blank =>
val newName = supply.newName() val newName = supply.newName()
@ -169,12 +169,12 @@ case object LambdaShorthandToLambda extends IRPass {
* @param freshNameSupply the compiler's supply of fresh names * @param freshNameSupply the compiler's supply of fresh names
* @return `application`, with any lambda shorthand arguments desugared * @return `application`, with any lambda shorthand arguments desugared
*/ */
def desugarApplication( private def desugarApplication(
application: Application, application: Application,
freshNameSupply: FreshNameSupply freshNameSupply: FreshNameSupply
): Expression = { ): Expression = {
application match { application match {
case p @ Application.Prefix(fn, args, _, _, _, _) => case p @ Application.Prefix(fn, args, _, _, _) =>
// Determine which arguments are lambda shorthand // Determine which arguments are lambda shorthand
val argIsUnderscore = determineLambdaShorthand(args) val argIsUnderscore = determineLambdaShorthand(args)
@ -183,7 +183,7 @@ case object LambdaShorthandToLambda extends IRPass {
args args
.zip(argIsUnderscore) .zip(argIsUnderscore)
.map(updateShorthandArg(_, freshNameSupply)) .map(updateShorthandArg(_, freshNameSupply))
.map { case s @ CallArgument.Specified(_, value, _, _, _) => .map { case s @ CallArgument.Specified(_, value, _, _) =>
s.copy(value = desugarExpression(value, freshNameSupply)) s.copy(value = desugarExpression(value, freshNameSupply))
} }
@ -250,9 +250,9 @@ case object LambdaShorthandToLambda extends IRPass {
case lam: Function.Lambda => lam.copy(location = p.location) case lam: Function.Lambda => lam.copy(location = p.location)
case result => result case result => result
} }
case f @ Application.Force(tgt, _, _, _) => case f @ Application.Force(tgt, _, _) =>
f.copy(target = desugarExpression(tgt, freshNameSupply)) f.copy(target = desugarExpression(tgt, freshNameSupply))
case vector @ Application.Sequence(items, _, _, _) => case vector @ Application.Sequence(items, _, _) =>
var bindings: List[Name] = List() var bindings: List[Name] = List()
val newItems = items.map { val newItems = items.map {
case blank: Name.Blank => case blank: Name.Blank =>
@ -280,7 +280,7 @@ case object LambdaShorthandToLambda extends IRPass {
) )
new Function.Lambda(List(defArg), body, locWithoutId) new Function.Lambda(List(defArg), body, locWithoutId)
} }
case tSet @ Application.Typeset(expr, _, _, _) => case tSet @ Application.Typeset(expr, _, _) =>
tSet.copy(expression = expr.map(desugarExpression(_, freshNameSupply))) tSet.copy(expression = expr.map(desugarExpression(_, freshNameSupply)))
case _: Operator => case _: Operator =>
throw new CompilerError( throw new CompilerError(
@ -297,8 +297,10 @@ case object LambdaShorthandToLambda extends IRPass {
* @return a list containing `true` for a given position if the arg in that * @return a list containing `true` for a given position if the arg in that
* position is lambda shorthand, otherwise `false` * position is lambda shorthand, otherwise `false`
*/ */
def determineLambdaShorthand(args: List[CallArgument]): List[Boolean] = { private def determineLambdaShorthand(
args.map { case CallArgument.Specified(_, value, _, _, _) => args: List[CallArgument]
): List[Boolean] = {
args.map { case CallArgument.Specified(_, value, _, _) =>
value match { value match {
case _: Name.Blank => true case _: Name.Blank => true
case _ => false case _ => false
@ -314,7 +316,7 @@ case object LambdaShorthandToLambda extends IRPass {
* @return the above described pair for a given position if the argument in * @return the above described pair for a given position if the argument in
* a given position is shorthand, otherwise [[None]]. * a given position is shorthand, otherwise [[None]].
*/ */
def updateShorthandArg( private def updateShorthandArg(
argAndIsShorthand: (CallArgument, Boolean), argAndIsShorthand: (CallArgument, Boolean),
freshNameSupply: FreshNameSupply freshNameSupply: FreshNameSupply
): CallArgument = { ): CallArgument = {
@ -322,7 +324,7 @@ case object LambdaShorthandToLambda extends IRPass {
val isShorthand = argAndIsShorthand._2 val isShorthand = argAndIsShorthand._2
arg match { arg match {
case s @ CallArgument.Specified(_, value, _, _, _) => case s @ CallArgument.Specified(_, value, _, _) =>
if (isShorthand) { if (isShorthand) {
val newName = freshNameSupply val newName = freshNameSupply
.newName() .newName()
@ -345,13 +347,13 @@ case object LambdaShorthandToLambda extends IRPass {
* @return a corresponding definition argument if `arg` `isShorthand`, * @return a corresponding definition argument if `arg` `isShorthand`,
* otherwise [[None]] * otherwise [[None]]
*/ */
def generateDefinitionArg( private def generateDefinitionArg(
arg: CallArgument, arg: CallArgument,
isShorthand: Boolean isShorthand: Boolean
): Option[DefinitionArgument] = { ): Option[DefinitionArgument] = {
if (isShorthand) { if (isShorthand) {
arg match { arg match {
case CallArgument.Specified(_, value, _, passData, diagnostics) => case specified @ CallArgument.Specified(_, value, _, passData) =>
// Note [Safe Casting to Name.Literal] // Note [Safe Casting to Name.Literal]
val defArgName = val defArgName =
Name.Literal( Name.Literal(
@ -361,14 +363,14 @@ case object LambdaShorthandToLambda extends IRPass {
) )
Some( Some(
DefinitionArgument.Specified( new DefinitionArgument.Specified(
defArgName, defArgName,
None, None,
None, None,
suspended = false, suspended = false,
None, None,
passData.duplicate, passData.duplicate,
diagnostics.copy specified.diagnosticsCopy
) )
) )
} }
@ -391,7 +393,7 @@ case object LambdaShorthandToLambda extends IRPass {
* @param freshNameSupply the compiler's supply of fresh names * @param freshNameSupply the compiler's supply of fresh names
* @return `caseExpr`, with any lambda shorthand desugared * @return `caseExpr`, with any lambda shorthand desugared
*/ */
def desugarCaseExpr( private def desugarCaseExpr(
caseExpr: Case.Expr, caseExpr: Case.Expr,
freshNameSupply: FreshNameSupply freshNameSupply: FreshNameSupply
): Expression = { ): Expression = {
@ -400,14 +402,14 @@ case object LambdaShorthandToLambda extends IRPass {
) )
caseExpr.scrutinee match { caseExpr.scrutinee match {
case Name.Blank(loc, passData, diagnostics) => case nameBlank: Name.Blank =>
val scrutineeName = val scrutineeName =
freshNameSupply freshNameSupply
.newName() .newName()
.copy( .copy(
location = loc, location = nameBlank.location,
passData = passData, passData = nameBlank.passData,
diagnostics = diagnostics diagnostics = nameBlank.diagnostics
) )
val lambdaArg = DefinitionArgument.Specified( val lambdaArg = DefinitionArgument.Specified(
@ -424,11 +426,10 @@ case object LambdaShorthandToLambda extends IRPass {
) )
new Function.Lambda( new Function.Lambda(
caseExpr,
List(lambdaArg), List(lambdaArg),
newCaseExpr, newCaseExpr,
caseExpr.location, caseExpr.location
passData = caseExpr.passData,
diagnostics = caseExpr.diagnostics
) )
case x => case x =>
caseExpr.copy( caseExpr.copy(

View File

@ -155,12 +155,12 @@ case object NestedPatternMatch extends IRPass {
* @param freshNameSupply the compiler's supply of fresh names * @param freshNameSupply the compiler's supply of fresh names
* @return `expr`, with any nested patterns desugared * @return `expr`, with any nested patterns desugared
*/ */
def desugarCase( private def desugarCase(
expr: Case, expr: Case,
freshNameSupply: FreshNameSupply freshNameSupply: FreshNameSupply
): Expression = { ): Expression = {
expr match { expr match {
case expr @ Case.Expr(scrutinee, branches, _, _, _, _) => case expr @ Case.Expr(scrutinee, branches, _, _, _) =>
val scrutineeBindingName = freshNameSupply.newName() val scrutineeBindingName = freshNameSupply.newName()
val scrutineeExpression = desugarExpression(scrutinee, freshNameSupply) val scrutineeExpression = desugarExpression(scrutinee, freshNameSupply)
val scrutineeBinding = val scrutineeBinding =
@ -198,14 +198,14 @@ case object NestedPatternMatch extends IRPass {
* @return `branch`, with any nested patterns desugared * @return `branch`, with any nested patterns desugared
*/ */
@scala.annotation.tailrec @scala.annotation.tailrec
def desugarCaseBranch( private def desugarCaseBranch(
branch: Case.Branch, branch: Case.Branch,
topBranchLocation: Option[IdentifiedLocation], topBranchLocation: Option[IdentifiedLocation],
freshNameSupply: FreshNameSupply freshNameSupply: FreshNameSupply
): Case.Branch = { ): Case.Branch = {
if (containsNestedPatterns(branch.pattern)) { if (containsNestedPatterns(branch.pattern)) {
branch.pattern match { branch.pattern match {
case cons @ Pattern.Constructor(constrName, fields, _, _, _) => case cons @ Pattern.Constructor(constrName, fields, _, _) =>
// Note [Unsafe Getting the Nested Field] // Note [Unsafe Getting the Nested Field]
val (lastNestedPattern, nestedPosition) = val (lastNestedPattern, nestedPosition) =
fields.zipWithIndex.findLast { case (pat, _) => isNested(pat) }.get fields.zipWithIndex.findLast { case (pat, _) => isNested(pat) }.get
@ -255,7 +255,7 @@ case object NestedPatternMatch extends IRPass {
throw new CompilerError( throw new CompilerError(
"Type patterns cannot be nested. This should be unreachable." "Type patterns cannot be nested. This should be unreachable."
) )
case Pattern.Documentation(_, _, _, _) => case Pattern.Documentation(_, _, _) =>
throw new CompilerError( throw new CompilerError(
"Branch documentation should be desugared at an earlier stage." "Branch documentation should be desugared at an earlier stage."
) )
@ -295,7 +295,7 @@ case object NestedPatternMatch extends IRPass {
* a success * a success
* @return a nested case expression of the form above * @return a nested case expression of the form above
*/ */
def generateNestedCase( private def generateNestedCase(
pattern: Pattern, pattern: Pattern,
nestedScrutinee: Expression, nestedScrutinee: Expression,
currentBranchExpr: Expression currentBranchExpr: Expression
@ -326,7 +326,7 @@ case object NestedPatternMatch extends IRPass {
def containsNestedPatterns(pattern: Pattern): Boolean = def containsNestedPatterns(pattern: Pattern): Boolean =
pattern match { pattern match {
case _: Pattern.Name => false case _: Pattern.Name => false
case Pattern.Constructor(_, fields, _, _, _) => case Pattern.Constructor(_, fields, _, _) =>
fields.exists { fields.exists {
case _: Pattern.Constructor => true case _: Pattern.Constructor => true
case _: Pattern.Name => false case _: Pattern.Name => false

View File

@ -70,18 +70,17 @@ case object OperatorToFunction extends IRPass {
ir: Expression, ir: Expression,
inlineContext: InlineContext inlineContext: InlineContext
): Expression = ): Expression =
ir.transformExpressions { ir.transformExpressions { case operatorBinary: Operator.Binary =>
case Operator.Binary(l, op, r, loc, passData, diag) => new Application.Prefix(
Application.Prefix( operatorBinary.operator,
op,
List( List(
l.mapExpressions(runExpression(_, inlineContext)), operatorBinary.left.mapExpressions(runExpression(_, inlineContext)),
r.mapExpressions(runExpression(_, inlineContext)) operatorBinary.right.mapExpressions(runExpression(_, inlineContext))
), ),
hasDefaultsSuspended = false, hasDefaultsSuspended = false,
loc, operatorBinary.location,
passData, operatorBinary.passData,
diag operatorBinary.diagnostics
) )
} }
} }

View File

@ -101,7 +101,7 @@ case object SectionsToBinOp extends IRPass {
inlineContext: InlineContext inlineContext: InlineContext
): Expression = { ): Expression = {
section match { section match {
case Section.Left(arg, op, loc, passData, diagnostics) => case sectionLeft @ Section.Left(arg, op, loc, passData) =>
val rightArgName = freshNameSupply.newName() val rightArgName = freshNameSupply.newName()
val rightCallArg = val rightCallArg =
CallArgument.Specified(None, rightArgName, None) CallArgument.Specified(None, rightArgName, None)
@ -124,13 +124,13 @@ case object SectionsToBinOp extends IRPass {
suspended = false, suspended = false,
None None
) )
val opCall = Application.Prefix( val opCall = new Application.Prefix(
function = op, function = op,
arguments = List(leftCallArg, rightCallArg), arguments = List(leftCallArg, rightCallArg),
hasDefaultsSuspended = false, hasDefaultsSuspended = false,
location = None, location = None,
passData, passData = passData,
diagnostics diagnostics = sectionLeft.diagnostics
) )
val rightLam = new Function.Lambda( val rightLam = new Function.Lambda(
@ -144,21 +144,20 @@ case object SectionsToBinOp extends IRPass {
rightLam, rightLam,
loc loc
) )
} else { } else {
val newArg = arg.mapExpressions(runExpression(_, inlineContext)) val newArg = arg.mapExpressions(runExpression(_, inlineContext))
Application.Prefix( new Application.Prefix(
function = op, function = op,
arguments = List(newArg), arguments = List(newArg),
hasDefaultsSuspended = false, hasDefaultsSuspended = false,
location = loc, location = loc,
passData, passData = passData,
diagnostics diagnostics = sectionLeft.diagnostics
) )
} }
case Section.Sides(op, loc, passData, diagnostics) => case sectionSides @ Section.Sides(op, loc, passData) =>
val leftArgName = freshNameSupply.newName() val leftArgName = freshNameSupply.newName()
val leftCallArg = val leftCallArg =
CallArgument.Specified(None, leftArgName, None) CallArgument.Specified(None, leftArgName, None)
@ -181,13 +180,13 @@ case object SectionsToBinOp extends IRPass {
None None
) )
val opCall = Application.Prefix( val opCall = new Application.Prefix(
function = op, function = op,
arguments = List(leftCallArg, rightCallArg), arguments = List(leftCallArg, rightCallArg),
hasDefaultsSuspended = false, hasDefaultsSuspended = false,
location = None, location = None,
passData, passData = passData,
diagnostics diagnostics = sectionSides.diagnostics
) )
val rightLambda = new Function.Lambda( val rightLambda = new Function.Lambda(
@ -221,7 +220,7 @@ case object SectionsToBinOp extends IRPass {
* The same is true of left sections. * The same is true of left sections.
*/ */
case Section.Right(op, arg, loc, passData, diagnostics) => case sectionRight @ Section.Right(op, arg, loc, passData) =>
val leftArgName = freshNameSupply.newName() val leftArgName = freshNameSupply.newName()
val leftCallArg = val leftCallArg =
CallArgument.Specified(None, leftArgName, None) CallArgument.Specified(None, leftArgName, None)
@ -247,13 +246,13 @@ case object SectionsToBinOp extends IRPass {
None None
) )
val opCall = Application.Prefix( val opCall = new Application.Prefix(
function = op, function = op,
arguments = List(leftCallArg, rightCallArg), arguments = List(leftCallArg, rightCallArg),
hasDefaultsSuspended = false, hasDefaultsSuspended = false,
location = None, location = None,
passData, passData = passData,
diagnostics diagnostics = sectionRight.diagnostics
) )
val leftLam = new Function.Lambda( val leftLam = new Function.Lambda(
@ -270,13 +269,13 @@ case object SectionsToBinOp extends IRPass {
} else { } else {
val newArg = arg.mapExpressions(runExpression(_, inlineContext)) val newArg = arg.mapExpressions(runExpression(_, inlineContext))
val opCall = Application.Prefix( val opCall = new Application.Prefix(
function = op, function = op,
arguments = List(leftCallArg, newArg), arguments = List(leftCallArg, newArg),
hasDefaultsSuspended = false, hasDefaultsSuspended = false,
location = None, location = None,
passData, passData = passData,
diagnostics diagnostics = sectionRight.diagnostics
) )
new Function.Lambda( new Function.Lambda(

View File

@ -42,7 +42,6 @@ case object ModuleNameConflicts extends IRPass {
None, None,
None, None,
true, true,
_,
_ _
) => ) =>
Some(mod) Some(mod)

View File

@ -48,19 +48,17 @@ object NoSelfInStatic extends IRPass {
} }
private def transformSelfToError: PartialFunction[Expression, Expression] = { private def transformSelfToError: PartialFunction[Expression, Expression] = {
case Name.Self(location, false, passData, diagnostics) => case nameSelf @ Name.Self(location, false, passData) =>
errors.Syntax( new errors.Syntax(
location.get, location.get,
errors.Syntax.InvalidSelfArgUsage, errors.Syntax.InvalidSelfArgUsage,
passData, passData,
diagnostics nameSelf.diagnostics
) )
} }
/** A method is static if it is either not defined within a type, or if it does not /** A method is static if it is either not defined within a type, or if it does not
* contain a non-synthetic `self` argument. * contain a non-synthetic `self` argument.
* @param method
* @return
*/ */
private def isStaticMethod( private def isStaticMethod(
method: definition.Method method: definition.Method
@ -70,8 +68,7 @@ object NoSelfInStatic extends IRPass {
): Option[DefinitionArgument] = { ): Option[DefinitionArgument] = {
arguments.collectFirst { arguments.collectFirst {
case arg @ DefinitionArgument.Specified( case arg @ DefinitionArgument.Specified(
Name.Self(_, false, _, _), Name.Self(_, false, _),
_,
_, _,
_, _,
_, _,

View File

@ -85,7 +85,7 @@ case object ShadowedPatternFields extends IRPass {
* @param expression the expression to lint * @param expression the expression to lint
* @return `expression`, with warnings for any shadowed pattern variables * @return `expression`, with warnings for any shadowed pattern variables
*/ */
def lintExpression( private def lintExpression(
expression: Expression expression: Expression
): Expression = { ): Expression = {
expression.transformExpressions { case cse: Case => expression.transformExpressions { case cse: Case =>
@ -100,7 +100,7 @@ case object ShadowedPatternFields extends IRPass {
*/ */
def lintCase(cse: Case): Case = { def lintCase(cse: Case): Case = {
cse match { cse match {
case expr @ Case.Expr(scrutinee, branches, _, _, _, _) => case expr @ Case.Expr(scrutinee, branches, _, _, _) =>
expr.copy( expr.copy(
scrutinee = lintExpression(scrutinee), scrutinee = lintExpression(scrutinee),
branches = branches.map(lintCaseBranch) branches = branches.map(lintCaseBranch)
@ -139,7 +139,7 @@ case object ShadowedPatternFields extends IRPass {
def go(pattern: Pattern, seenNames: mutable.Set[String]): Pattern = { def go(pattern: Pattern, seenNames: mutable.Set[String]): Pattern = {
pattern match { pattern match {
case named @ Pattern.Name(name, location, _, _) => case named @ Pattern.Name(name, location, _) =>
if (seenNames.contains(name.name)) { if (seenNames.contains(name.name)) {
val warning = warnings.Shadowed val warning = warnings.Shadowed
.PatternBinding(name.name, lastSeen(name.name), location) .PatternBinding(name.name, lastSeen(name.name), location)
@ -157,7 +157,7 @@ case object ShadowedPatternFields extends IRPass {
} else { } else {
named named
} }
case cons @ Pattern.Constructor(_, fields, _, _, _) => case cons @ Pattern.Constructor(_, fields, _, _) =>
val newFields = fields.reverse.map(go(_, seenNames)).reverse val newFields = fields.reverse.map(go(_, seenNames)).reverse
cons.copy( cons.copy(
@ -165,7 +165,7 @@ case object ShadowedPatternFields extends IRPass {
) )
case literal: Pattern.Literal => case literal: Pattern.Literal =>
literal literal
case typed @ Pattern.Type(name, _, location, _, _) => case typed @ Pattern.Type(name, _, location, _) =>
if (seenNames.contains(name.name)) { if (seenNames.contains(name.name)) {
val warning = warnings.Shadowed val warning = warnings.Shadowed
.PatternBinding(name.name, lastSeen(name.name), location) .PatternBinding(name.name, lastSeen(name.name), location)

View File

@ -130,7 +130,7 @@ case object UnusedBindings extends IRPass {
* @param context the inline context in which linting is taking place * @param context the inline context in which linting is taking place
* @return `function`, with any lints attached * @return `function`, with any lints attached
*/ */
def lintFunction( private def lintFunction(
function: Function, function: Function,
context: InlineContext context: InlineContext
): Function = { ): Function = {
@ -172,7 +172,7 @@ case object UnusedBindings extends IRPass {
* @param context the inline context in which linting is taking place * @param context the inline context in which linting is taking place
* @return `argument`, with any lints attached * @return `argument`, with any lints attached
*/ */
def lintFunctionArgument( private def lintFunctionArgument(
argument: DefinitionArgument, argument: DefinitionArgument,
context: InlineContext context: InlineContext
): DefinitionArgument = { ): DefinitionArgument = {
@ -199,11 +199,10 @@ case object UnusedBindings extends IRPass {
_, _,
_, _,
_, _,
_,
_ _
) => ) =>
s s
case s @ DefinitionArgument.Specified(name, _, default, _, _, _, _) => case s @ DefinitionArgument.Specified(name, _, default, _, _, _) =>
if (!isIgnored && !isUsed) { if (!isIgnored && !isUsed) {
val nameToReport = name match { val nameToReport = name match {
case literal: Name.Literal => case literal: Name.Literal =>
@ -225,7 +224,7 @@ case object UnusedBindings extends IRPass {
*/ */
def lintCase(cse: Case, context: InlineContext): Case = { def lintCase(cse: Case, context: InlineContext): Case = {
cse match { cse match {
case expr @ Case.Expr(scrutinee, branches, _, _, _, _) => case expr @ Case.Expr(scrutinee, branches, _, _, _) =>
expr.copy( expr.copy(
scrutinee = runExpression(scrutinee, context), scrutinee = runExpression(scrutinee, context),
branches = branches.map(lintCaseBranch(_, context)) branches = branches.map(lintCaseBranch(_, context))
@ -257,7 +256,7 @@ case object UnusedBindings extends IRPass {
*/ */
def lintPattern(pattern: Pattern): Pattern = { def lintPattern(pattern: Pattern): Pattern = {
pattern match { pattern match {
case n @ Pattern.Name(name, _, _, _) => case n @ Pattern.Name(name, _, _) =>
val isIgnored = name val isIgnored = name
.unsafeGetMetadata( .unsafeGetMetadata(
IgnoredBindings, IgnoredBindings,
@ -277,7 +276,7 @@ case object UnusedBindings extends IRPass {
if (!isIgnored && !isUsed) { if (!isIgnored && !isUsed) {
n.addDiagnostic(warnings.Unused.PatternBinding(name)) n.addDiagnostic(warnings.Unused.PatternBinding(name))
} else pattern } else pattern
case cons @ Pattern.Constructor(_, fields, _, _, _) => case cons @ Pattern.Constructor(_, fields, _, _) =>
if (!cons.isDesugared) { if (!cons.isDesugared) {
throw new CompilerError( throw new CompilerError(
"Nested patterns should not be present during linting." "Nested patterns should not be present during linting."
@ -287,7 +286,7 @@ case object UnusedBindings extends IRPass {
cons.copy( cons.copy(
fields = fields.map(lintPattern) fields = fields.map(lintPattern)
) )
case typed @ Pattern.Type(name, _, _, _, _) => case typed @ Pattern.Type(name, _, _, _) =>
val isIgnored = name val isIgnored = name
.unsafeGetMetadata( .unsafeGetMetadata(
IgnoredBindings, IgnoredBindings,

View File

@ -221,16 +221,16 @@ case object LambdaConsolidate extends IRPass {
if (isShadowed) { if (isShadowed) {
val restArgs = args.drop(ix + 1) val restArgs = args.drop(ix + 1)
arg match { arg match {
case spec @ DefinitionArgument.Specified(argName, _, _, _, _, _, _) => case spec @ DefinitionArgument.Specified(argName, _, _, _, _, _) =>
val mShadower = restArgs.collectFirst { val mShadower = restArgs.collectFirst {
case s @ DefinitionArgument.Specified(sName, _, _, _, _, _, _) case s @ DefinitionArgument.Specified(sName, _, _, _, _, _)
if sName.name == argName.name => if sName.name == argName.name =>
s s
} }
val shadower: IR = mShadower.getOrElse(Empty(spec.location)) val shadower: IR = mShadower.getOrElse(Empty(spec.location))
spec.diagnostics.add( spec.getDiagnostics.add(
warnings.Shadowed warnings.Shadowed
.FunctionParam(argName.name, shadower, spec.location) .FunctionParam(argName.name, shadower, spec.location)
) )
@ -249,9 +249,9 @@ case object LambdaConsolidate extends IRPass {
* @param body the function body to optimise * @param body the function body to optimise
* @return the directly chained lambdas in `body` * @return the directly chained lambdas in `body`
*/ */
def gatherChainedLambdas(body: Expression): List[Function.Lambda] = { private def gatherChainedLambdas(body: Expression): List[Function.Lambda] = {
body match { body match {
case Expression.Block(expressions, lam: Function.Lambda, _, _, _, _) case Expression.Block(expressions, lam: Function.Lambda, _, _, _)
if expressions.isEmpty => if expressions.isEmpty =>
lam :: gatherChainedLambdas(lam.body) lam :: gatherChainedLambdas(lam.body)
case l @ Function.Lambda(_, body, _, _, _, _) => case l @ Function.Lambda(_, body, _, _, _, _) =>
@ -271,7 +271,7 @@ case object LambdaConsolidate extends IRPass {
* @return `body` and `defaults` with any occurrence of the old name replaced * @return `body` and `defaults` with any occurrence of the old name replaced
* by the new name * by the new name
*/ */
def replaceUsages( private def replaceUsages(
body: Expression, body: Expression,
defaults: List[Option[Expression]], defaults: List[Option[Expression]],
argument: DefinitionArgument, argument: DefinitionArgument,
@ -296,7 +296,7 @@ case object LambdaConsolidate extends IRPass {
* be replaced * be replaced
* @return `expr`, with occurrences of the symbol for `argument` replaced * @return `expr`, with occurrences of the symbol for `argument` replaced
*/ */
def replaceInExpression( private def replaceInExpression(
expr: Expression, expr: Expression,
argument: DefinitionArgument, argument: DefinitionArgument,
toReplaceExpressionIds: Set[UUID @Identifier] toReplaceExpressionIds: Set[UUID @Identifier]
@ -314,7 +314,7 @@ case object LambdaConsolidate extends IRPass {
* replacement * replacement
* @return `name`, with the symbol replaced by `argument.name` * @return `name`, with the symbol replaced by `argument.name`
*/ */
def replaceInName( private def replaceInName(
name: Name, name: Name,
argument: DefinitionArgument, argument: DefinitionArgument,
toReplaceExpressionIds: Set[UUID @Identifier] toReplaceExpressionIds: Set[UUID @Identifier]
@ -348,7 +348,7 @@ case object LambdaConsolidate extends IRPass {
* @param args the consolidated list of function arguments * @param args the consolidated list of function arguments
* @return the set of aliasing identifiers shadowed by `args` * @return the set of aliasing identifiers shadowed by `args`
*/ */
def getShadowedBindingIds( private def getShadowedBindingIds(
args: List[DefinitionArgument] args: List[DefinitionArgument]
): Set[AliasGraph.Id] = { ): Set[AliasGraph.Id] = {
args args
@ -376,7 +376,7 @@ case object LambdaConsolidate extends IRPass {
* @return the set of usage IR identifiers for each shadowed argument, where * @return the set of usage IR identifiers for each shadowed argument, where
* an empty set represents a non-shadowed argument * an empty set represents a non-shadowed argument
*/ */
def usageIdsForShadowedArgs( private def usageIdsForShadowedArgs(
argsWithShadowed: List[(DefinitionArgument, Boolean)] argsWithShadowed: List[(DefinitionArgument, Boolean)]
): List[Set[UUID @Identifier]] = { ): List[Set[UUID @Identifier]] = {
argsWithShadowed.map { argsWithShadowed.map {
@ -447,7 +447,7 @@ case object LambdaConsolidate extends IRPass {
* @param usageIdsForShadowed the identifiers for usages of shadowed names * @param usageIdsForShadowed the identifiers for usages of shadowed names
* @return `args` and `body`, with any usages of shadowed symbols replaced * @return `args` and `body`, with any usages of shadowed symbols replaced
*/ */
def computeReplacedExpressions( private def computeReplacedExpressions(
args: List[DefinitionArgument], args: List[DefinitionArgument],
body: Expression, body: Expression,
usageIdsForShadowed: List[Set[UUID @Identifier]] usageIdsForShadowed: List[Set[UUID @Identifier]]

View File

@ -103,7 +103,7 @@ case object UnreachableMatchBranches extends IRPass {
* @param expression the expression to optimize * @param expression the expression to optimize
* @return `expression` with unreachable case branches removed * @return `expression` with unreachable case branches removed
*/ */
def optimizeExpression(expression: Expression): Expression = { private def optimizeExpression(expression: Expression): Expression = {
expression.transformExpressions { case cse: Case => expression.transformExpressions { case cse: Case =>
optimizeCase(cse) optimizeCase(cse)
} }
@ -118,9 +118,9 @@ case object UnreachableMatchBranches extends IRPass {
* @return `cse` with unreachable branches removed * @return `cse` with unreachable branches removed
*/ */
//noinspection DuplicatedCode //noinspection DuplicatedCode
def optimizeCase(cse: Case): Case = { private def optimizeCase(cse: Case): Case = {
cse match { cse match {
case expr @ Case.Expr(scrutinee, branches, _, _, _, _) => case expr @ Case.Expr(scrutinee, branches, _, _, _) =>
val reachableNonCatchAllBranches = branches.takeWhile(!isCatchAll(_)) val reachableNonCatchAllBranches = branches.takeWhile(!isCatchAll(_))
val firstCatchAll = branches.find(isCatchAll) val firstCatchAll = branches.find(isCatchAll)
val unreachableBranches = val unreachableBranches =
@ -178,7 +178,7 @@ case object UnreachableMatchBranches extends IRPass {
* @param branch the branch to check * @param branch the branch to check
* @return `true` if `branch` is catch-all, otherwise `false` * @return `true` if `branch` is catch-all, otherwise `false`
*/ */
def isCatchAll(branch: Case.Branch): Boolean = { private def isCatchAll(branch: Case.Branch): Boolean = {
branch.pattern match { branch.pattern match {
case _: Pattern.Name => true case _: Pattern.Name => true
case _: Pattern.Constructor => false case _: Pattern.Constructor => false

View File

@ -126,10 +126,10 @@ case object DocumentationComments extends IRPass {
private def resolveBranches(items: Seq[Case.Branch]): Seq[Case.Branch] = { private def resolveBranches(items: Seq[Case.Branch]): Seq[Case.Branch] = {
var lastDoc: Option[String] = None var lastDoc: Option[String] = None
items.flatMap { items.flatMap {
case Case.Branch(Pattern.Documentation(doc, _, _, _), _, _, _, _, _) => case Case.Branch(Pattern.Documentation(doc, _, _), _, _, _, _) =>
lastDoc = Some(doc) lastDoc = Some(doc)
None None
case branch @ Case.Branch(pattern, expression, _, _, _, _) => case branch @ Case.Branch(pattern, expression, _, _, _) =>
val resolved = val resolved =
branch.copy( branch.copy(
pattern = pattern.mapExpressions(resolveExpression), pattern = pattern.mapExpressions(resolveExpression),

View File

@ -72,7 +72,6 @@ case object ExpressionAnnotations extends IRPass {
arguments, arguments,
_, _,
_, _,
_,
_ _
) => ) =>
if (isKnownAnnotation(ann.name)) { if (isKnownAnnotation(ann.name)) {
@ -88,7 +87,7 @@ case object ExpressionAnnotations extends IRPass {
case realFun :: args => case realFun :: args =>
val recurFun = doExpression(realFun.value) val recurFun = doExpression(realFun.value)
val (finalFun, preArgs) = recurFun match { val (finalFun, preArgs) = recurFun match {
case Application.Prefix(nextFun, moreArgs, _, _, _, _) => case Application.Prefix(nextFun, moreArgs, _, _, _) =>
(nextFun, moreArgs) (nextFun, moreArgs)
case _ => (recurFun, List()) case _ => (recurFun, List())
} }

View File

@ -257,7 +257,7 @@ case object FullyQualifiedNames extends IRPass {
} else { } else {
lit lit
} }
case app @ Application.Prefix(_, List(_), _, _, _, _) => case app @ Application.Prefix(_, List(_), _, _, _) =>
app.function match { app.function match {
case lit: Name.Literal => case lit: Name.Literal =>
if (lit.isMethod) if (lit.isMethod)

View File

@ -135,7 +135,7 @@ case object IgnoredBindings extends IRPass {
* @param supply the compiler's supply of fresh names * @param supply the compiler's supply of fresh names
* @return `binding`, with any ignored bindings desugared * @return `binding`, with any ignored bindings desugared
*/ */
def resolveBinding( private def resolveBinding(
binding: Expression.Binding, binding: Expression.Binding,
supply: FreshNameSupply supply: FreshNameSupply
): Expression.Binding = { ): Expression.Binding = {
@ -203,15 +203,14 @@ case object IgnoredBindings extends IRPass {
* @param freshNameSupply the compiler's fresh name supply * @param freshNameSupply the compiler's fresh name supply
* @return `arg`, if `isIgnored` is `false`, otherwise `arg` with a new name * @return `arg`, if `isIgnored` is `false`, otherwise `arg` with a new name
*/ */
def genNewArg( private def genNewArg(
arg: DefinitionArgument, arg: DefinitionArgument,
isIgnored: Boolean, isIgnored: Boolean,
freshNameSupply: FreshNameSupply freshNameSupply: FreshNameSupply
): DefinitionArgument = { ): DefinitionArgument = {
arg match { arg match {
case spec @ DefinitionArgument.Specified( case spec @ DefinitionArgument.Specified(
Name.Self(_, _, _, _), Name.Self(_, _, _),
_,
_, _,
_, _,
_, _,
@ -258,9 +257,9 @@ case object IgnoredBindings extends IRPass {
* @param ir the definition argument to check * @param ir the definition argument to check
* @return `true` if `ir` represents an ignore, otherwise `false` * @return `true` if `ir` represents an ignore, otherwise `false`
*/ */
def isIgnoreArg(ir: DefinitionArgument): Boolean = { private def isIgnoreArg(ir: DefinitionArgument): Boolean = {
ir match { ir match {
case DefinitionArgument.Specified(name, _, _, _, _, _, _) => case DefinitionArgument.Specified(name, _, _, _, _, _) =>
isIgnore(name) isIgnore(name)
} }
} }
@ -284,9 +283,9 @@ case object IgnoredBindings extends IRPass {
* @param supply the compiler's fresh name supply * @param supply the compiler's fresh name supply
* @return `cse`, with any ignored bindings resolved * @return `cse`, with any ignored bindings resolved
*/ */
def resolveCase(cse: Case, supply: FreshNameSupply): Case = { private def resolveCase(cse: Case, supply: FreshNameSupply): Case = {
cse match { cse match {
case expr @ Case.Expr(scrutinee, branches, _, _, _, _) => case expr @ Case.Expr(scrutinee, branches, _, _, _) =>
expr.copy( expr.copy(
scrutinee = resolveExpression(scrutinee, supply), scrutinee = resolveExpression(scrutinee, supply),
branches = branches.map(resolveCaseBranch(_, supply)) branches = branches.map(resolveCaseBranch(_, supply))
@ -304,7 +303,7 @@ case object IgnoredBindings extends IRPass {
* @param supply the compiler's fresh name supply * @param supply the compiler's fresh name supply
* @return `branch`, with any ignored bindings resolved * @return `branch`, with any ignored bindings resolved
*/ */
def resolveCaseBranch( private def resolveCaseBranch(
branch: Case.Branch, branch: Case.Branch,
supply: FreshNameSupply supply: FreshNameSupply
): Case.Branch = { ): Case.Branch = {
@ -320,12 +319,12 @@ case object IgnoredBindings extends IRPass {
* @param supply the compiler's fresh name supply * @param supply the compiler's fresh name supply
* @return `pattern`, with any ignored bindings resolved * @return `pattern`, with any ignored bindings resolved
*/ */
def resolvePattern( private def resolvePattern(
pattern: Pattern, pattern: Pattern,
supply: FreshNameSupply supply: FreshNameSupply
): Pattern = { ): Pattern = {
pattern match { pattern match {
case named @ Pattern.Name(name, _, _, _) => case named @ Pattern.Name(name, _, _) =>
if (isIgnore(name)) { if (isIgnore(name)) {
val newName = supply val newName = supply
.newName(from = Some(name)) .newName(from = Some(name))
@ -344,12 +343,12 @@ case object IgnoredBindings extends IRPass {
name = setNotIgnored(name) name = setNotIgnored(name)
) )
} }
case cons @ Pattern.Constructor(_, fields, _, _, _) => case cons @ Pattern.Constructor(_, fields, _, _) =>
cons.copy( cons.copy(
fields = fields.map(resolvePattern(_, supply)) fields = fields.map(resolvePattern(_, supply))
) )
case literal: Pattern.Literal => literal case literal: Pattern.Literal => literal
case typed @ Pattern.Type(name, _, _, _, _) => case typed @ Pattern.Type(name, _, _, _) =>
if (isIgnore(name)) { if (isIgnore(name)) {
val newName = supply val newName = supply
.newName(from = Some(name)) .newName(from = Some(name))

View File

@ -145,8 +145,7 @@ case object MethodDefinitions extends IRPass {
case lambda: Function.Lambda => case lambda: Function.Lambda =>
val newArguments = lambda.arguments match { val newArguments = lambda.arguments match {
case (selfArg @ DefinitionArgument.Specified( case (selfArg @ DefinitionArgument.Specified(
Name.Self(_, _, _, _), Name.Self(_, _, _),
_,
_, _,
_, _,
_, _,

View File

@ -255,7 +255,7 @@ object Patterns extends IRPass {
} }
case None => consPat.copy(constructor = resolvedName) case None => consPat.copy(constructor = resolvedName)
} }
case tpePattern @ Pattern.Type(_, tpeName, _, _, _) => case tpePattern @ Pattern.Type(_, tpeName, _, _) =>
val resolution = tpeName match { val resolution = tpeName match {
case qual: Name.Qualified => case qual: Name.Qualified =>
val parts = qual.parts.map(_.name) val parts = qual.parts.map(_.name)

View File

@ -212,7 +212,7 @@ case object SuspendedArguments extends IRPass {
*/ */
private def resolveExpression(expression: Expression): Expression = { private def resolveExpression(expression: Expression): Expression = {
expression.transformExpressions { expression.transformExpressions {
case bind @ Expression.Binding(_, expr, _, _, _) => case bind @ Expression.Binding(_, expr, _, _) =>
val newExpr = bind.getMetadata(TypeSignatures) match { val newExpr = bind.getMetadata(TypeSignatures) match {
case Some(Signature(signature, _)) => case Some(Signature(signature, _)) =>
expr match { expr match {
@ -250,7 +250,7 @@ case object SuspendedArguments extends IRPass {
*/ */
private def toSegments(signature: Expression): List[Expression] = { private def toSegments(signature: Expression): List[Expression] = {
signature match { signature match {
case Type.Function(args, ret, _, _, _) => args :+ ret case Type.Function(args, ret, _, _) => args :+ ret
case _ => List(signature) case _ => List(signature)
} }
} }
@ -263,7 +263,7 @@ case object SuspendedArguments extends IRPass {
*/ */
def representsSuspended(value: Expression): Boolean = { def representsSuspended(value: Expression): Boolean = {
value match { value match {
case Name.Literal("Suspended", _, _, _, _, _) => true case Name.Literal("Suspended", _, _, _, _) => true
case _ => false case _ => false
} }
} }

View File

@ -89,7 +89,7 @@ case object TypeFunctions extends IRPass {
// === Pass Internals ======================================================= // === Pass Internals =======================================================
/** The names of the known typing functions. */ /** The names of the known typing functions. */
val knownTypingFunctions: Set[String] = Set( private val knownTypingFunctions: Set[String] = Set(
Type.Ascription.name, Type.Ascription.name,
Type.Context.name, Type.Context.name,
Type.Error.name, Type.Error.name,
@ -122,9 +122,9 @@ case object TypeFunctions extends IRPass {
* @param app the application to perform resolution in * @param app the application to perform resolution in
* @return `app`, with any typing functions resolved * @return `app`, with any typing functions resolved
*/ */
def resolveApplication(app: Application): Expression = { private def resolveApplication(app: Application): Expression = {
app match { app match {
case pre @ Application.Prefix(fn, arguments, _, _, _, _) => case pre @ Application.Prefix(fn, arguments, _, _, _) =>
fn match { fn match {
case name: Name if name.name == `type`.Set.Union.name => case name: Name if name.name == `type`.Set.Union.name =>
val members = flattenUnion(app).map(resolveExpression) val members = flattenUnion(app).map(resolveExpression)
@ -137,13 +137,13 @@ case object TypeFunctions extends IRPass {
arguments = arguments.map(resolveCallArgument) arguments = arguments.map(resolveCallArgument)
) )
} }
case force @ Application.Force(target, _, _, _) => case force @ Application.Force(target, _, _) =>
force.copy(target = resolveExpression(target)) force.copy(target = resolveExpression(target))
case seq @ Application.Sequence(items, _, _, _) => case seq @ Application.Sequence(items, _, _) =>
seq.copy( seq.copy(
items = items.map(resolveExpression) items = items.map(resolveExpression)
) )
case tSet @ Application.Typeset(expr, _, _, _) => case tSet @ Application.Typeset(expr, _, _) =>
tSet.copy( tSet.copy(
expression = expr.map(resolveExpression) expression = expr.map(resolveExpression)
) )
@ -154,9 +154,9 @@ case object TypeFunctions extends IRPass {
} }
} }
def flattenUnion(expr: Expression): List[Expression] = { private def flattenUnion(expr: Expression): List[Expression] = {
expr match { expr match {
case Application.Prefix(n: Name, args, _, _, _, _) case Application.Prefix(n: Name, args, _, _, _)
if n.name == `type`.Set.Union.name => if n.name == `type`.Set.Union.name =>
args.flatMap(arg => flattenUnion(arg.value)) args.flatMap(arg => flattenUnion(arg.value))
case _ => List(expr) case _ => List(expr)
@ -165,10 +165,13 @@ case object TypeFunctions extends IRPass {
/** Resolves a known typing function to its IR node. /** Resolves a known typing function to its IR node.
* *
* @param prefix the application to resolve * @param name the typing function name
* @param arguments the application arguments
* @param location the application location
* @param originalIR the application to resolve
* @return the IR node representing `prefix` * @return the IR node representing `prefix`
*/ */
def resolveKnownFunction( private def resolveKnownFunction(
name: Name, name: Name,
arguments: List[CallArgument], arguments: List[CallArgument],
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
@ -208,9 +211,9 @@ case object TypeFunctions extends IRPass {
* @param arg the argument to perform resolution in * @param arg the argument to perform resolution in
* @return `arg`, with any call arguments resolved * @return `arg`, with any call arguments resolved
*/ */
def resolveCallArgument(arg: CallArgument): CallArgument = { private def resolveCallArgument(arg: CallArgument): CallArgument = {
arg match { arg match {
case spec @ CallArgument.Specified(_, value, _, _, _) => case spec @ CallArgument.Specified(_, value, _, _) =>
spec.copy( spec.copy(
value = resolveExpression(value) value = resolveExpression(value)
) )
@ -230,9 +233,9 @@ case object TypeFunctions extends IRPass {
* @param arg the argument to check * @param arg the argument to check
* @return `true` if `arg` is valid, otherwise `false` * @return `true` if `arg` is valid, otherwise `false`
*/ */
def isValidCallArg(arg: CallArgument): Boolean = { private def isValidCallArg(arg: CallArgument): Boolean = {
arg match { arg match {
case CallArgument.Specified(name, _, _, _, _) => case CallArgument.Specified(name, _, _, _) =>
name.isEmpty name.isEmpty
} }
} }

View File

@ -97,7 +97,7 @@ case object TypeSignatures extends IRPass {
case _ => case _ =>
} }
val res = lastSignature match { val res = lastSignature match {
case Some(asc @ Type.Ascription(typed, sig, comment, _, _, _)) => case Some(asc @ Type.Ascription(typed, sig, comment, _, _)) =>
val methodRef = meth.methodReference val methodRef = meth.methodReference
val newMethodWithDoc = asc val newMethodWithDoc = asc
.getMetadata(DocumentationComments) .getMetadata(DocumentationComments)
@ -223,7 +223,6 @@ case object TypeSignatures extends IRPass {
_, _,
_, _,
_, _,
_,
_ _
) => ) =>
val sig = resolveExpression(ascribedType.duplicate()) val sig = resolveExpression(ascribedType.duplicate())
@ -273,7 +272,7 @@ case object TypeSignatures extends IRPass {
case binding: Expression.Binding => case binding: Expression.Binding =>
val newBinding = binding.mapExpressions(resolveExpression) val newBinding = binding.mapExpressions(resolveExpression)
val res = lastSignature match { val res = lastSignature match {
case Some(asc @ Type.Ascription(typed, sig, comment, _, _, _)) => case Some(asc @ Type.Ascription(typed, sig, comment, _, _)) =>
val name = binding.name val name = binding.name
val newBindingWithDoc = asc val newBindingWithDoc = asc
.getMetadata(DocumentationComments) .getMetadata(DocumentationComments)

View File

@ -3,7 +3,7 @@ package org.enso.compiler.phase
import org.enso.compiler.Compiler import org.enso.compiler.Compiler
import org.enso.compiler.context.CompilerContext.Module import org.enso.compiler.context.CompilerContext.Module
import org.enso.compiler.core.Implicits.AsMetadata import org.enso.compiler.core.Implicits.AsMetadata
import org.enso.compiler.core.ir.{DiagnosticStorage, MetadataStorage} import org.enso.compiler.core.ir.MetadataStorage
import org.enso.compiler.core.ir.module.scope.{Export, Import} import org.enso.compiler.core.ir.module.scope.{Export, Import}
import org.enso.compiler.data.BindingsMap import org.enso.compiler.data.BindingsMap
import org.enso.compiler.pass.analyse.BindingAnalysis import org.enso.compiler.pass.analyse.BindingAnalysis
@ -187,7 +187,6 @@ final class ImportResolver(compiler: Compiler) extends ImportResolverForIR {
onlyNames, onlyNames,
_, _,
isSynthetic, isSynthetic,
_,
_ _
) if !isSynthetic => ) if !isSynthetic =>
val exportsItself = curModName.equals(expName.name) val exportsItself = curModName.equals(expName.name)
@ -201,8 +200,7 @@ final class ImportResolver(compiler: Compiler) extends ImportResolverForIR {
None, None,
location = None, location = None,
isSynthetic = true, isSynthetic = true,
passData = new MetadataStorage(), passData = new MetadataStorage()
diagnostics = DiagnosticStorage()
) )
tryResolveImport(module.getIr, syntheticImport) match { tryResolveImport(module.getIr, syntheticImport) match {
case (_, Some(resolvedImp)) => case (_, Some(resolvedImp)) =>

View File

@ -424,7 +424,6 @@ final class EnsureCompiledJob(
_, _,
expression.errors.Resolution expression.errors.Resolution
.ResolverError(BindingsMap.ResolutionNotFound), .ResolverError(BindingsMap.ResolutionNotFound),
_,
_ _
) => ) =>
DataflowAnalysis.DependencyInfo.Type.Static( DataflowAnalysis.DependencyInfo.Type.Static(

View File

@ -1044,12 +1044,12 @@ public class TypeInferenceTest extends CompilerTest {
} }
private List<Diagnostic> getImmediateDiagnostics(IR ir) { private List<Diagnostic> getImmediateDiagnostics(IR ir) {
return CollectionConverters.asJava(ir.diagnostics().toList()); return CollectionConverters.asJava(ir.getDiagnostics().toList());
} }
private List<Diagnostic> getDescendantsDiagnostics(IR ir) { private List<Diagnostic> getDescendantsDiagnostics(IR ir) {
return CollectionConverters.asJava( return CollectionConverters.asJava(
ir.preorder().flatMap((node) -> node.diagnostics().toList())); ir.preorder().flatMap(node -> node.getDiagnostics().toList()));
} }
private Method findStaticMethod(Module module, String name) { private Method findStaticMethod(Module module, String name) {

View File

@ -128,9 +128,7 @@ public class ModuleTest {
assertNull("No IR by default", module.getIr()); assertNull("No IR by default", module.getIr());
var ir = var ir = new org.enso.compiler.core.ir.Module(nil(), nil(), nil(), false, Option.empty(), null);
new org.enso.compiler.core.ir.Module(
nil(), nil(), nil(), false, Option.empty(), null, null);
compilerContext.updateModule( compilerContext.updateModule(
module, module,
(u) -> { (u) -> {

View File

@ -3,7 +3,13 @@ package org.enso.compiler.test
import org.enso.compiler.context.{FreshNameSupply, InlineContext, ModuleContext} import org.enso.compiler.context.{FreshNameSupply, InlineContext, ModuleContext}
import org.enso.compiler.core.{EnsoParser, IR, Identifier} import org.enso.compiler.core.{EnsoParser, IR, Identifier}
import org.enso.compiler.core.Implicits.AsMetadata import org.enso.compiler.core.Implicits.AsMetadata
import org.enso.compiler.core.ir.{DefinitionArgument, Expression, Module, Name} import org.enso.compiler.core.ir.{
DefinitionArgument,
Diagnostic,
Expression,
Module,
Name
}
import org.enso.compiler.core.ir.module.scope.Definition import org.enso.compiler.core.ir.module.scope.Definition
import org.enso.compiler.core.ir.module.scope.definition import org.enso.compiler.core.ir.module.scope.definition
import org.enso.compiler.core.ir.MetadataStorage.MetadataPair import org.enso.compiler.core.ir.MetadataStorage.MetadataPair
@ -82,6 +88,21 @@ trait CompilerRunner {
} }
} }
/** Provides an extensions to work with diagnostic information attached to IR.
*
* @param ir the IR node
*/
implicit class DiagnosticStorageExt(ir: IR) {
/** Get the list of diagnostics attached to the provided IR node without
* unnecessary allocations of [[org.enso.compiler.core.ir.DiagnosticStorage]].
*
* @return the list of attached diagnostics
*/
def diagnosticsList: List[Diagnostic] =
if (ir.diagnostics() eq null) Nil else ir.diagnostics().toList
}
/** Provides an extension method allowing the running of a specified list of /** Provides an extension method allowing the running of a specified list of
* passes on the provided IR. * passes on the provided IR.
* *
@ -151,23 +172,23 @@ trait CompilerRunner {
*/ */
def asMethod: definition.Method = { def asMethod: definition.Method = {
new definition.Method.Explicit( new definition.Method.Explicit(
definition.Method.Binding(
Name.MethodReference( Name.MethodReference(
Some( Some(
Name.Qualified( Name.Qualified(
List( List(Name.Literal("TestType", isMethod = false, None)),
Name
.Literal("TestType", isMethod = false, None)
),
None None
) )
), ),
Name Name.Literal("testMethod", isMethod = false, None),
.Literal("testMethod", isMethod = false, None),
None None
), ),
ir, Nil,
false, false,
ir,
None None
),
ir
) )
} }

View File

@ -1,7 +1,6 @@
package org.enso.compiler.test.core.ir package org.enso.compiler.test.core.ir
import org.enso.compiler.core.ir.{Diagnostic, DiagnosticStorage, Empty} import org.enso.compiler.core.ir.{Diagnostic, DiagnosticStorage, Empty}
import org.enso.compiler.core.ir.expression.errors
import org.enso.compiler.core.ir.expression.warnings import org.enso.compiler.core.ir.expression.warnings
import org.enso.compiler.test.CompilerTest import org.enso.compiler.test.CompilerTest
@ -42,115 +41,5 @@ class DiagnosticStorageTest extends CompilerTest {
diagnostics.toList should contain(mkDiagnostic("b")) diagnostics.toList should contain(mkDiagnostic("b"))
diagnostics.toList should contain(mkDiagnostic("c")) diagnostics.toList should contain(mkDiagnostic("c"))
} }
"mapping across the diagnostics to produce a new sequence" in {
val diagnostics = new DiagnosticStorage(
List(
mkDiagnostic("a"),
mkDiagnostic("b"),
mkDiagnostic("c")
)
)
diagnostics.map(d => d.location) shouldEqual Seq(None, None, None)
}
"mapping across the diagnostics in place" in {
val diagnostics = new DiagnosticStorage(
List(
mkDiagnostic("a"),
mkDiagnostic("b"),
mkDiagnostic("c")
)
)
val expectedResult = List(
mkDiagnostic("aaa"),
mkDiagnostic("aaa"),
mkDiagnostic("aaa")
)
diagnostics.mapInPlace {
case s: warnings.Shadowed.FunctionParam =>
s.copy(shadowedName = "aaa")
case x => x
}
diagnostics.toList shouldEqual expectedResult
}
"collecting across the diagnostics to produce a new sequence" in {
val err = errors.Syntax(null, errors.Syntax.UnsupportedSyntax("aa"))
val diagnostics = new DiagnosticStorage(
List(
mkDiagnostic("a"),
mkDiagnostic("b"),
mkDiagnostic("c"),
err
)
)
diagnostics.collect { case e: errors.Syntax =>
e
} shouldEqual Seq(err)
}
"filtering the diagnostics" in {
val diagnostics = new DiagnosticStorage(
List(
mkDiagnostic("aa"),
mkDiagnostic("ba"),
mkDiagnostic("cd")
)
)
val result = new DiagnosticStorage(
List(mkDiagnostic("aa"), mkDiagnostic("ba"))
)
diagnostics.filter {
case s: warnings.Shadowed.FunctionParam =>
s.shadowedName.contains("a")
case _ => false
} shouldEqual result
}
"filtering the diagnostics in place" in {
val diagnostics = new DiagnosticStorage(
List(
mkDiagnostic("aa"),
mkDiagnostic("ba"),
mkDiagnostic("cd")
)
)
val result = List(mkDiagnostic("aa"), mkDiagnostic("ba"))
diagnostics.filterInPlace {
case s: warnings.Shadowed.FunctionParam =>
s.shadowedName.contains("a")
case _ => false
}
diagnostics.toList shouldEqual result
}
"folding over the diagnostics" in {
val diagnostics = new DiagnosticStorage(
List(
mkDiagnostic("a"),
mkDiagnostic("b"),
mkDiagnostic("cd")
)
)
diagnostics.foldLeft("")((str, d) =>
d match {
case f: warnings.Shadowed.FunctionParam => str + f.shadowedName
case _ => str
}
) shouldEqual "abcd"
}
} }
} }

View File

@ -232,7 +232,7 @@ class FramePointerAnalysisTest extends CompilerTest {
val syntheticSelfArg = findIRElement[DefinitionArgument.Specified]( val syntheticSelfArg = findIRElement[DefinitionArgument.Specified](
ir, ir,
_.name match { _.name match {
case Name.Self(loc, synthetic, _, _) if loc.isEmpty && synthetic => case Name.Self(loc, synthetic, _) if loc.isEmpty && synthetic =>
true true
case _ => false case _ => false
} }
@ -251,7 +251,7 @@ class FramePointerAnalysisTest extends CompilerTest {
val syntheticSelfArg = findIRElement[DefinitionArgument.Specified]( val syntheticSelfArg = findIRElement[DefinitionArgument.Specified](
ir, ir,
_.name match { _.name match {
case Name.Self(loc, synthetic, _, _) if loc.isEmpty && synthetic => case Name.Self(loc, synthetic, _) if loc.isEmpty && synthetic =>
true true
case _ => false case _ => false
} }

View File

@ -94,8 +94,14 @@ class GatherDiagnosticsTest extends CompilerTest {
List(), List(),
None None
), ),
new definition.Method.Explicit(method1Ref, lam, false, None), new definition.Method.Explicit(
new definition.Method.Explicit(method2Ref, error3, false, None) definition.Method.Binding(method1Ref, Nil, false, lam, None),
lam
),
new definition.Method.Explicit(
definition.Method.Binding(method2Ref, Nil, false, error3, None),
lam.copy(body = error3)
)
), ),
false, false,
None None

View File

@ -186,15 +186,11 @@ class TailCallTest extends CompilerTest {
.expressions(0) .expressions(0)
.asInstanceOf[Expression.Binding] .asInstanceOf[Expression.Binding]
.expression .expression
.diagnostics .diagnosticsList
.filter(_.isInstanceOf[Warning.WrongTco]) .count(_.isInstanceOf[Warning.WrongTco]) shouldEqual 1
.toList
.length shouldEqual 1
fnBody.returnValue.diagnostics fnBody.returnValue.diagnosticsList
.filter(_.isInstanceOf[Warning.WrongTco]) .count(_.isInstanceOf[Warning.WrongTco]) shouldEqual 0
.toList
.length shouldEqual 0
} }
} }
@ -225,10 +221,8 @@ class TailCallTest extends CompilerTest {
.returnValue .returnValue
.asInstanceOf[Application.Prefix] .asInstanceOf[Application.Prefix]
.function .function
.diagnostics .diagnosticsList
.filter(_.isInstanceOf[Warning.WrongTco]) .count(_.isInstanceOf[Warning.WrongTco]) shouldEqual 0
.toList
.length shouldEqual 0
} }
} }

View File

@ -244,7 +244,7 @@ class GenerateMethodBodiesTest extends CompilerTest {
bodyLambda.arguments.size shouldEqual 1 bodyLambda.arguments.size shouldEqual 1
val selfArg = bodyLambda.arguments.head.name val selfArg = bodyLambda.arguments.head.name
selfArg shouldEqual Name.Self(location = irBazSndArg.location) selfArg shouldEqual Name.Self(location = irBazSndArg.location)
resultLambda.diagnostics.collect { case w: Warning => resultLambda.diagnosticsList.collect { case w: Warning =>
w w
}.head shouldBe an[Warning.WrongSelfParameterPos] }.head shouldBe an[Warning.WrongSelfParameterPos]
} }
@ -293,7 +293,7 @@ class GenerateMethodBodiesTest extends CompilerTest {
val selfArg = resultArgs.head.name val selfArg = resultArgs.head.name
selfArg shouldBe a[Name.Self] selfArg shouldBe a[Name.Self]
selfArg.location shouldEqual irMethodAddSelfArg.head.name.location selfArg.location shouldEqual irMethodAddSelfArg.head.name.location
resultLambda.diagnostics.collect { case w: Warning => resultLambda.diagnosticsList.collect { case w: Warning =>
w w
} shouldBe empty } shouldBe empty
} }
@ -306,13 +306,13 @@ class GenerateMethodBodiesTest extends CompilerTest {
resultArgs.size shouldEqual 1 resultArgs.size shouldEqual 1
val selfArg = resultArgs(0).name val selfArg = resultArgs(0).name
selfArg should not be an[Name.Self] selfArg should not be an[Name.Self]
resultLambda.diagnostics.collect { case w: Warning => resultLambda.diagnosticsList.collect { case w: Warning =>
w w
}.head shouldBe an[Warning.WrongSelfParameterPos] }.head shouldBe an[Warning.WrongSelfParameterPos]
val nestedLmabda = resultLambda.body.asInstanceOf[Function.Lambda] val nestedLambda = resultLambda.body.asInstanceOf[Function.Lambda]
nestedLmabda.arguments.size shouldEqual 1 nestedLambda.arguments.size shouldEqual 1
nestedLmabda.arguments(0).name shouldBe an[Name.Self] nestedLambda.arguments(0).name shouldBe an[Name.Self]
} }
} }
@ -363,7 +363,7 @@ class GenerateMethodBodiesTest extends CompilerTest {
body.arguments.head.name shouldBe an[Name.Literal] body.arguments.head.name shouldBe an[Name.Literal]
body.arguments.head.name.name shouldBe ConstantsNames.THAT_ARGUMENT body.arguments.head.name.name shouldBe ConstantsNames.THAT_ARGUMENT
conversion.body.diagnostics.collect { case w: Warning => conversion.body.diagnosticsList.collect { case w: Warning =>
w w
}.head shouldBe an[Warning.WrongSelfParameterPos] }.head shouldBe an[Warning.WrongSelfParameterPos]
} }
@ -381,7 +381,7 @@ class GenerateMethodBodiesTest extends CompilerTest {
body.arguments.head.name shouldBe an[Name.Literal] body.arguments.head.name shouldBe an[Name.Literal]
body.arguments.head.name.name shouldBe ConstantsNames.THAT_ARGUMENT body.arguments.head.name.name shouldBe ConstantsNames.THAT_ARGUMENT
conversion.body.diagnostics.collect { case w: Warning => conversion.body.diagnosticsList.collect { case w: Warning =>
w w
}.head shouldBe an[Warning.WrongSelfParameterPos] }.head shouldBe an[Warning.WrongSelfParameterPos]
} }

View File

@ -55,7 +55,7 @@ class NoSelfInStaticTests extends CompilerTest {
| bar = self.x + self.x | bar = self.x + self.x
|""".stripMargin.preprocessModule.lint |""".stripMargin.preprocessModule.lint
val errs = ir.bindings.flatMap(_.preorder).collect { val errs = ir.bindings.flatMap(_.preorder).collect {
case err @ errors.Syntax(_, errors.Syntax.InvalidSelfArgUsage, _, _) => case err @ errors.Syntax(_, errors.Syntax.InvalidSelfArgUsage, _) =>
err err
} }
errs should have size 2 errs should have size 2
@ -68,7 +68,7 @@ class NoSelfInStaticTests extends CompilerTest {
|static_method x y = x + y + self.data |static_method x y = x + y + self.data
|""".stripMargin.preprocessModule.lint |""".stripMargin.preprocessModule.lint
val errs = ir.bindings.flatMap(_.preorder).collect { val errs = ir.bindings.flatMap(_.preorder).collect {
case err @ errors.Syntax(_, errors.Syntax.InvalidSelfArgUsage, _, _) => case err @ errors.Syntax(_, errors.Syntax.InvalidSelfArgUsage, _) =>
err err
} }
errs should have size 1 errs should have size 1
@ -85,7 +85,7 @@ class NoSelfInStaticTests extends CompilerTest {
| nested_method (x + y) | nested_method (x + y)
|""".stripMargin.preprocessModule.lint |""".stripMargin.preprocessModule.lint
val errs = ir.bindings.flatMap(_.preorder).collect { val errs = ir.bindings.flatMap(_.preorder).collect {
case err @ errors.Syntax(_, errors.Syntax.InvalidSelfArgUsage, _, _) => case err @ errors.Syntax(_, errors.Syntax.InvalidSelfArgUsage, _) =>
err err
} }
errs should have size 1 errs should have size 1
@ -103,7 +103,7 @@ class NoSelfInStaticTests extends CompilerTest {
| nested_method 42 | nested_method 42
|""".stripMargin.preprocessModule.lint |""".stripMargin.preprocessModule.lint
val errs = ir.bindings.flatMap(_.preorder).collect { val errs = ir.bindings.flatMap(_.preorder).collect {
case err @ errors.Syntax(_, errors.Syntax.InvalidSelfArgUsage, _, _) => case err @ errors.Syntax(_, errors.Syntax.InvalidSelfArgUsage, _) =>
err err
} }
errs should be(empty) errs should be(empty)
@ -119,7 +119,7 @@ class NoSelfInStaticTests extends CompilerTest {
|My_Type.extension_method = self.value + 1 |My_Type.extension_method = self.value + 1
|""".stripMargin.preprocessModule.lint |""".stripMargin.preprocessModule.lint
val errs = ir.bindings.flatMap(_.preorder).collect { val errs = ir.bindings.flatMap(_.preorder).collect {
case err @ errors.Syntax(_, errors.Syntax.InvalidSelfArgUsage, _, _) => case err @ errors.Syntax(_, errors.Syntax.InvalidSelfArgUsage, _) =>
err err
} }
errs should have size 1 errs should have size 1

View File

@ -73,11 +73,11 @@ class ShadowedPatternFieldsTest extends CompilerTest {
} }
"attach a shadowing warning to each shadowed field" in { "attach a shadowing warning to each shadowed field" in {
atLeast(1, pattern.fields.head.diagnostics.toList) shouldBe a[ atLeast(1, pattern.fields.head.diagnosticsList) shouldBe a[
warnings.Shadowed.PatternBinding warnings.Shadowed.PatternBinding
] ]
val warning = pattern.fields.head.diagnostics.collect { val warning = pattern.fields.head.diagnosticsList.collect {
case w: warnings.Shadowed.PatternBinding => w case w: warnings.Shadowed.PatternBinding => w
}.head }.head

View File

@ -94,7 +94,7 @@ class UnusedBindingsTest extends CompilerTest with Inside {
|""".stripMargin.preprocessExpression.get.lint |""".stripMargin.preprocessExpression.get.lint
.asInstanceOf[Function.Lambda] .asInstanceOf[Function.Lambda]
val lintMeta = ir.arguments.head.diagnostics.collect { val lintMeta = ir.arguments.head.diagnosticsList.collect {
case u: warnings.Unused.FunctionArgument => u case u: warnings.Unused.FunctionArgument => u
} }
@ -115,7 +115,7 @@ class UnusedBindingsTest extends CompilerTest with Inside {
inside(ir.bindings.head) { case definition: definition.Method.Explicit => inside(ir.bindings.head) { case definition: definition.Method.Explicit =>
inside(definition.body) { case f: Function.Lambda => inside(definition.body) { case f: Function.Lambda =>
val lintMeta = f.arguments(1).diagnostics.collect { val lintMeta = f.arguments(1).diagnosticsList.collect {
case u: warnings.Unused.FunctionArgument => u case u: warnings.Unused.FunctionArgument => u
} }
@ -135,7 +135,7 @@ class UnusedBindingsTest extends CompilerTest with Inside {
|""".stripMargin.preprocessExpression.get.lint |""".stripMargin.preprocessExpression.get.lint
.asInstanceOf[Function.Lambda] .asInstanceOf[Function.Lambda]
val lintMeta = ir.arguments.head.diagnostics.collect { val lintMeta = ir.arguments.head.diagnosticsList.collect {
case u: warnings.Unused => u case u: warnings.Unused => u
} }
@ -151,7 +151,7 @@ class UnusedBindingsTest extends CompilerTest with Inside {
|""".stripMargin.preprocessExpression.get.lint |""".stripMargin.preprocessExpression.get.lint
.asInstanceOf[Expression.Binding] .asInstanceOf[Expression.Binding]
val lintMeta = ir.diagnostics.collect { case u: warnings.Unused => val lintMeta = ir.diagnosticsList.collect { case u: warnings.Unused =>
u u
} }
@ -169,7 +169,7 @@ class UnusedBindingsTest extends CompilerTest with Inside {
|""".stripMargin.preprocessExpression.get.lint |""".stripMargin.preprocessExpression.get.lint
.asInstanceOf[Expression.Binding] .asInstanceOf[Expression.Binding]
val lintMeta = ir.diagnostics.collect { case u: warnings.Unused => val lintMeta = ir.diagnosticsList.collect { case u: warnings.Unused =>
u u
} }
@ -192,10 +192,12 @@ class UnusedBindingsTest extends CompilerTest with Inside {
val field1 = pattern.fields.head.asInstanceOf[Pattern.Name] val field1 = pattern.fields.head.asInstanceOf[Pattern.Name]
val field2 = pattern.fields(1).asInstanceOf[Pattern.Name] val field2 = pattern.fields(1).asInstanceOf[Pattern.Name]
val lintMeta1 = field1.diagnostics.collect { case u: warnings.Unused => val lintMeta1 = field1.diagnosticsList.collect {
case u: warnings.Unused =>
u u
} }
val lintMeta2 = field2.diagnostics.collect { case u: warnings.Unused => val lintMeta2 = field2.diagnosticsList.collect {
case u: warnings.Unused =>
u u
} }
@ -218,7 +220,7 @@ class UnusedBindingsTest extends CompilerTest with Inside {
inside(ir.bindings.head) { case definition: definition.Method.Explicit => inside(ir.bindings.head) { case definition: definition.Method.Explicit =>
inside(definition.body) { case f: Function.Lambda => inside(definition.body) { case f: Function.Lambda =>
val lintMeta = f.arguments(1).diagnostics.collect { val lintMeta = f.arguments(1).diagnosticsList.collect {
case u: warnings.Unused.FunctionArgument => u case u: warnings.Unused.FunctionArgument => u
} }
@ -245,10 +247,12 @@ class UnusedBindingsTest extends CompilerTest with Inside {
val field1 = pattern.fields.head.asInstanceOf[Pattern.Name] val field1 = pattern.fields.head.asInstanceOf[Pattern.Name]
val field2 = pattern.fields(1).asInstanceOf[Pattern.Name] val field2 = pattern.fields(1).asInstanceOf[Pattern.Name]
val lintMeta1 = field1.diagnostics.collect { case u: warnings.Unused => val lintMeta1 = field1.diagnosticsList.collect {
case u: warnings.Unused =>
u u
} }
val lintMeta2 = field2.diagnostics.collect { case u: warnings.Unused => val lintMeta2 = field2.diagnosticsList.collect {
case u: warnings.Unused =>
u u
} }

View File

@ -205,7 +205,6 @@ class GlobalNamesTest extends CompilerTest {
case errors.Resolution( case errors.Resolution(
name, name,
_: errors.Resolution.ResolverError, _: errors.Resolution.ResolverError,
_,
_ _
) => ) =>
name name
@ -227,7 +226,6 @@ class GlobalNamesTest extends CompilerTest {
case errors.Resolution( case errors.Resolution(
name, name,
_: errors.Resolution.ResolverError, _: errors.Resolution.ResolverError,
_,
_ _
) => ) =>
name name

View File

@ -744,7 +744,8 @@ class ImportExportTest
val origImport = mainIr.imports(0) val origImport = mainIr.imports(0)
val warn = mainIr val warn = mainIr
.imports(1) .imports(1)
.diagnostics .getDiagnostics
.toList
.collect({ case w: Warning.DuplicatedImport => w }) .collect({ case w: Warning.DuplicatedImport => w })
warn.size shouldEqual 1 warn.size shouldEqual 1
warn.head.originalImport shouldEqual origImport warn.head.originalImport shouldEqual origImport
@ -768,7 +769,8 @@ class ImportExportTest
val origImport = mainIr.imports(0) val origImport = mainIr.imports(0)
val warn = mainIr val warn = mainIr
.imports(1) .imports(1)
.diagnostics .getDiagnostics
.toList
.collect({ case w: Warning.DuplicatedImport => w }) .collect({ case w: Warning.DuplicatedImport => w })
warn.size shouldEqual 1 warn.size shouldEqual 1
warn.head.originalImport shouldEqual origImport warn.head.originalImport shouldEqual origImport
@ -792,7 +794,8 @@ class ImportExportTest
val origImport = mainIr.imports(0) val origImport = mainIr.imports(0)
val warn = mainIr val warn = mainIr
.imports(1) .imports(1)
.diagnostics .getDiagnostics
.toList
.collect({ case w: Warning.DuplicatedImport => w }) .collect({ case w: Warning.DuplicatedImport => w })
warn.size shouldEqual 1 warn.size shouldEqual 1
warn.head.originalImport shouldEqual origImport warn.head.originalImport shouldEqual origImport
@ -817,7 +820,8 @@ class ImportExportTest
val origImport = mainIr.imports(0) val origImport = mainIr.imports(0)
val warn = mainIr val warn = mainIr
.imports(1) .imports(1)
.diagnostics .getDiagnostics
.toList
.collect({ case w: Warning.DuplicatedImport => w }) .collect({ case w: Warning.DuplicatedImport => w })
warn.size shouldEqual 2 warn.size shouldEqual 2
warn.foreach(_.originalImport shouldEqual origImport) warn.foreach(_.originalImport shouldEqual origImport)
@ -888,7 +892,8 @@ class ImportExportTest
.getIr .getIr
val warns = mainIr val warns = mainIr
.imports(0) .imports(0)
.diagnostics .getDiagnostics
.toList
.collect({ case w: Warning.DuplicatedImport => w }) .collect({ case w: Warning.DuplicatedImport => w })
warns.size shouldEqual 1 warns.size shouldEqual 1
warns.head.symbolName shouldEqual "A_Type" warns.head.symbolName shouldEqual "A_Type"
@ -933,7 +938,8 @@ class ImportExportTest
val origImport = mainIr.imports(0) val origImport = mainIr.imports(0)
val warns = mainIr val warns = mainIr
.imports(1) .imports(1)
.diagnostics .getDiagnostics
.toList
.collect({ case w: Warning.DuplicatedImport => w }) .collect({ case w: Warning.DuplicatedImport => w })
warns.size shouldEqual 1 warns.size shouldEqual 1
warns.head.symbolName shouldEqual "A_Type" warns.head.symbolName shouldEqual "A_Type"
@ -975,7 +981,7 @@ class ImportExportTest
mainIr.imports.size shouldEqual 3 mainIr.imports.size shouldEqual 3
val origImport = mainIr.imports(0) val origImport = mainIr.imports(0)
val allWarns = val allWarns =
mainIr.imports.flatMap(_.diagnostics.collect({ mainIr.imports.flatMap(_.getDiagnostics.toList.collect({
case w: Warning.DuplicatedImport => w case w: Warning.DuplicatedImport => w
})) }))
allWarns.size shouldEqual 2 allWarns.size shouldEqual 2
@ -999,7 +1005,7 @@ class ImportExportTest
mainIr.imports.size shouldEqual 3 mainIr.imports.size shouldEqual 3
val origImport = mainIr.imports(0) val origImport = mainIr.imports(0)
val allWarns = val allWarns =
mainIr.imports.flatMap(_.diagnostics.collect({ mainIr.imports.flatMap(_.getDiagnostics.toList.collect({
case w: Warning.DuplicatedImport => w case w: Warning.DuplicatedImport => w
})) }))
allWarns.size shouldEqual 2 allWarns.size shouldEqual 2
@ -1022,7 +1028,8 @@ class ImportExportTest
mainIr.imports.size shouldEqual 2 mainIr.imports.size shouldEqual 2
val warn = mainIr val warn = mainIr
.imports(1) .imports(1)
.diagnostics .getDiagnostics
.toList
.collect({ case w: Warning.DuplicatedImport => w }) .collect({ case w: Warning.DuplicatedImport => w })
warn.size shouldEqual 1 warn.size shouldEqual 1
val arr = Persistance.write( val arr = Persistance.write(

View File

@ -90,7 +90,7 @@ trait TypeMatchers {
} else { } else {
items.lazyZip(t.operands).flatMap(findInequalityWitness).headOption items.lazyZip(t.operands).flatMap(findInequalityWitness).headOption
} }
case (In(typed, context), Type.Context(irTyped, irContext, _, _, _)) => case (In(typed, context), Type.Context(irTyped, irContext, _, _)) =>
findInequalityWitness(typed, irTyped).orElse( findInequalityWitness(typed, irTyped).orElse(
findInequalityWitness(context, irContext) findInequalityWitness(context, irContext)
) )

View File

@ -100,9 +100,20 @@ public interface IR {
@Identifier @Identifier
UUID getId(); UUID getId();
/** Storage for compiler diagnostics related to the IR node. */ /**
* Get the storage for compiler diagnostics related to the IR node.
*
* @return the diagnostic storage or {@code null} if not initialized
*/
DiagnosticStorage diagnostics(); DiagnosticStorage diagnostics();
/**
* Initialize and get the storage for compiler diagnostics associated with this IR node.
*
* @return the diagnostic storage of this node. The result is never {@code null}
*/
DiagnosticStorage getDiagnostics();
/** /**
* Creates a deep structural copy of `this`, representing the same structure. * Creates a deep structural copy of `this`, representing the same structure.
* *

View File

@ -104,8 +104,13 @@ final class TreeToIr {
methodReference = ex.toError(); methodReference = ex.toError();
} }
var signature = translateType(sig.getType()); var signature = translateType(sig.getType());
var ascription = new Type.Ascription(methodReference, signature, Option.empty(), var ascription =
getIdentifiedLocation(sig), meta(), diag()); new Type.Ascription(
methodReference,
signature,
Option.empty(),
getIdentifiedLocation(sig),
meta());
yield ascription; yield ascription;
} }
case Tree.TypeAnnotated anno -> translateTypeAnnotated(anno); case Tree.TypeAnnotated anno -> translateTypeAnnotated(anno);
@ -144,8 +149,7 @@ final class TreeToIr {
returnValue, returnValue,
combinedLocation, combinedLocation,
false, false,
meta(), meta()
diag()
)); ));
} }
}; };
@ -202,15 +206,21 @@ final class TreeToIr {
default -> bindings = translateModuleSymbol(expr, bindings); default -> bindings = translateModuleSymbol(expr, bindings);
} }
} }
if (diag.isEmpty()) {
yield new Module(imports.reverse(), exports.reverse(), bindings.reverse(), isPrivate, yield new Module(imports.reverse(), exports.reverse(), bindings.reverse(), isPrivate,
getIdentifiedLocation(module), meta(), DiagnosticStorage.apply(diag)); getIdentifiedLocation(module), meta(), new DiagnosticStorage(diag));
} else {
yield new Module(imports.reverse(), exports.reverse(), bindings.reverse(), isPrivate,
getIdentifiedLocation(module), meta());
}
} }
default -> new Module( default -> new Module(
nil(), nil(), nil(), nil(),
join(translateSyntaxError(module, new Syntax.UnsupportedSyntax("translateModule")), join(translateSyntaxError(module, new Syntax.UnsupportedSyntax("translateModule")),
nil()), nil()),
false, false,
getIdentifiedLocation(module), meta(), diag() getIdentifiedLocation(module),
meta()
); );
}; };
} }
@ -270,7 +280,7 @@ final class TreeToIr {
args, args,
irBody.reverse(), irBody.reverse(),
getIdentifiedLocation(inputAst), getIdentifiedLocation(inputAst),
meta(), diag() meta()
); );
yield join(type, appendTo); yield join(type, appendTo);
} }
@ -283,8 +293,7 @@ final class TreeToIr {
case Tree.ForeignFunction fn when fn.getBody() instanceof Tree.TextLiteral body -> { case Tree.ForeignFunction fn when fn.getBody() instanceof Tree.TextLiteral body -> {
var name = fn.getName(); var name = fn.getName();
var nameLoc = getIdentifiedLocation(name); var nameLoc = getIdentifiedLocation(name);
var methodRef = new Name.MethodReference(Option.empty(), buildName(name), nameLoc, meta(), var methodRef = new Name.MethodReference(Option.empty(), buildName(name), nameLoc, meta());
diag());
var args = translateArgumentsDefinition(fn.getArgs()); var args = translateArgumentsDefinition(fn.getArgs());
var languageName = fn.getLanguage().codeRepr(); var languageName = fn.getLanguage().codeRepr();
var language = languageName; var language = languageName;
@ -294,25 +303,24 @@ final class TreeToIr {
yield join(error, appendTo); yield join(error, appendTo);
} }
var text = buildTextConstant(body, body.getElements()); var text = buildTextConstant(body, body.getElements());
var def = new Foreign.Definition(language, text, getIdentifiedLocation(fn.getBody()), var def =
meta(), diag()); new Foreign.Definition(language, text, getIdentifiedLocation(fn.getBody()), meta());
// Foreign functions are always considered private // Foreign functions are always considered private
var binding = new Method.Binding( var binding = new Method.Binding(
methodRef, args, true, def, getIdentifiedLocation(inputAst), meta(), diag() methodRef, args, true, def, getIdentifiedLocation(inputAst), meta());
);
yield join(binding, appendTo); yield join(binding, appendTo);
} }
case Tree.AnnotatedBuiltin anno -> { case Tree.AnnotatedBuiltin anno -> {
var annotation = new Name.BuiltinAnnotation("@" + anno.getAnnotation().codeRepr(), var annotation = new Name.BuiltinAnnotation("@" + anno.getAnnotation().codeRepr(),
getIdentifiedLocation(anno), meta(), diag()); getIdentifiedLocation(anno), meta());
yield translateModuleSymbol(anno.getExpression(), join(annotation, appendTo)); yield translateModuleSymbol(anno.getExpression(), join(annotation, appendTo));
} }
case Tree.Annotated anno -> { case Tree.Annotated anno -> {
var annotationArgument = translateExpression(anno.getArgument()); var annotationArgument = translateExpression(anno.getArgument());
var annotation = new Name.GenericAnnotation(anno.getAnnotation().codeRepr(), var annotation = new Name.GenericAnnotation(anno.getAnnotation().codeRepr(),
annotationArgument, getIdentifiedLocation(anno), meta(), diag()); annotationArgument, getIdentifiedLocation(anno), meta());
yield translateModuleSymbol(anno.getExpression(), join(annotation, appendTo)); yield translateModuleSymbol(anno.getExpression(), join(annotation, appendTo));
} }
@ -334,7 +342,7 @@ final class TreeToIr {
false, false,
body.setLocation(aLoc), body.setLocation(aLoc),
expandToContain(getIdentifiedLocation(a), aLoc), expandToContain(getIdentifiedLocation(a), aLoc),
meta(), diag() meta()
); );
yield join(binding, appendTo); yield join(binding, appendTo);
} }
@ -343,7 +351,7 @@ final class TreeToIr {
var methodReference = translateMethodReference(sig.getVariable(), true); var methodReference = translateMethodReference(sig.getVariable(), true);
var signature = translateType(sig.getType()); var signature = translateType(sig.getType());
var ascription = new Type.Ascription(methodReference, signature, Option.empty(), var ascription = new Type.Ascription(methodReference, signature, Option.empty(),
getIdentifiedLocation(sig), meta(), diag()); getIdentifiedLocation(sig), meta());
yield join(ascription, appendTo); yield join(ascription, appendTo);
} }
@ -370,7 +378,7 @@ final class TreeToIr {
var constructorName = buildName(inputAst, cons.getConstructor()); var constructorName = buildName(inputAst, cons.getConstructor());
List<DefinitionArgument> args = translateArgumentsDefinition(cons.getArguments()); List<DefinitionArgument> args = translateArgumentsDefinition(cons.getArguments());
var cAt = getIdentifiedLocation(inputAst); var cAt = getIdentifiedLocation(inputAst);
return new Definition.Data(constructorName, args, nil(), isPrivate, cAt, meta(), diag()); return new Definition.Data(constructorName, args, nil(), isPrivate, cAt, meta());
} catch (SyntaxException ex) { } catch (SyntaxException ex) {
return ex.toError(); return ex.toError();
} }
@ -465,10 +473,10 @@ final class TreeToIr {
yield join(error, appendTo); yield join(error, appendTo);
} }
var text = buildTextConstant(body, body.getElements()); var text = buildTextConstant(body, body.getElements());
var def = new Foreign.Definition(language, text, getIdentifiedLocation(fn.getBody()), var def =
meta(), diag()); new Foreign.Definition(language, text, getIdentifiedLocation(fn.getBody()), meta());
var binding = new Function.Binding(name, args, def, false, getIdentifiedLocation(fn), true, var binding =
meta(), diag()); new Function.Binding(name, args, def, false, getIdentifiedLocation(fn), true, meta());
yield join(binding, appendTo); yield join(binding, appendTo);
} }
case Tree.Documented doc -> { case Tree.Documented doc -> {
@ -478,7 +486,7 @@ final class TreeToIr {
case Tree.AnnotatedBuiltin anno -> { case Tree.AnnotatedBuiltin anno -> {
var ir = new Name.BuiltinAnnotation("@" + anno.getAnnotation().codeRepr(), var ir = new Name.BuiltinAnnotation("@" + anno.getAnnotation().codeRepr(),
getIdentifiedLocation(anno), meta(), diag()); getIdentifiedLocation(anno), meta());
var annotation = translateAnnotation(ir, anno.getExpression(), nil()); var annotation = translateAnnotation(ir, anno.getExpression(), nil());
yield join(annotation, appendTo); yield join(annotation, appendTo);
} }
@ -486,7 +494,7 @@ final class TreeToIr {
case Tree.Annotated anno -> { case Tree.Annotated anno -> {
var annotationArgument = translateExpression(anno.getArgument()); var annotationArgument = translateExpression(anno.getArgument());
var annotation = new Name.GenericAnnotation(anno.getAnnotation().codeRepr(), var annotation = new Name.GenericAnnotation(anno.getAnnotation().codeRepr(),
annotationArgument, getIdentifiedLocation(anno), meta(), diag()); annotationArgument, getIdentifiedLocation(anno), meta());
yield translateTypeBodyExpression(anno.getExpression(), join(annotation, appendTo)); yield translateTypeBodyExpression(anno.getExpression(), join(annotation, appendTo));
} }
@ -540,8 +548,7 @@ final class TreeToIr {
case 1 -> fullQualifiedNames.head(); case 1 -> fullQualifiedNames.head();
default -> { default -> {
var name = fullQualifiedNames.head(); var name = fullQualifiedNames.head();
name = new Name.Literal(name.name(), true, name.location(), Option.empty(), name.passData(), name = new Name.Literal(name.name(), true, name.location(), Option.empty(), name.passData());
name.diagnostics());
List<Name> tail = (List<Name>) fullQualifiedNames.tail(); List<Name> tail = (List<Name>) fullQualifiedNames.tail();
tail = tail.reverse(); tail = tail.reverse();
final Option<IdentifiedLocation> loc = getIdentifiedLocation(app); final Option<IdentifiedLocation> loc = getIdentifiedLocation(app);
@ -549,19 +556,18 @@ final class TreeToIr {
if (segments == 2) { if (segments == 2) {
arg = tail.head(); arg = tail.head();
} else { } else {
arg = new Name.Qualified(tail, loc, meta(), diag()); arg = new Name.Qualified(tail, loc, meta());
} }
var ca = new CallArgument.Specified(Option.empty(), arg, loc, meta(), diag()); var ca = new CallArgument.Specified(Option.empty(), arg, loc, meta());
args = join(ca, args); args = join(ca, args);
yield name; yield name;
} }
}; };
if (in == null) { if (in == null) {
return new Application.Prefix(type, args, false, getIdentifiedLocation(app), meta(), diag()); return new Application.Prefix(type, args, false, getIdentifiedLocation(app), meta());
} else { } else {
var fn = new CallArgument.Specified(Option.empty(), type, getIdentifiedLocation(app), meta(), var fn = new CallArgument.Specified(Option.empty(), type, getIdentifiedLocation(app), meta());
diag()); return new Operator.Binary(fn, in, args.head(), getIdentifiedLocation(app), meta());
return new Operator.Binary(fn, in, args.head(), getIdentifiedLocation(app), meta(), diag());
} }
} }
@ -577,7 +583,7 @@ final class TreeToIr {
var location = new Location(identifiedLocation.end(), identifiedLocation.end()); var location = new Location(identifiedLocation.end(), identifiedLocation.end());
return new IdentifiedLocation(location, identifiedLocation.uuid()); return new IdentifiedLocation(location, identifiedLocation.uuid());
}); });
body = new Empty(emptyLocation, meta(), diag()); body = new Empty(emptyLocation, meta());
} }
String functionName = fn.getName().codeRepr(); String functionName = fn.getName().codeRepr();
@ -588,7 +594,7 @@ final class TreeToIr {
isPrivate, isPrivate,
ascribedBody, ascribedBody,
loc, loc,
meta(), diag() meta()
); );
return binding; return binding;
} }
@ -626,7 +632,7 @@ final class TreeToIr {
} }
var ascribedBody = addTypeAscription(functionName, body, returnType, loc); var ascribedBody = addTypeAscription(functionName, body, returnType, loc);
return new Expression.Binding(name, ascribedBody, loc, meta(), diag()); return new Expression.Binding(name, ascribedBody, loc, meta());
} else { } else {
if (body == null) { if (body == null) {
return translateSyntaxError(fun, Syntax.UnexpectedDeclarationInType$.MODULE$); return translateSyntaxError(fun, Syntax.UnexpectedDeclarationInType$.MODULE$);
@ -636,7 +642,7 @@ final class TreeToIr {
} }
var ascribedBody = addTypeAscription(functionName, body, returnType, loc); var ascribedBody = addTypeAscription(functionName, body, returnType, loc);
return new Function.Binding(name, args, ascribedBody, isPrivate, loc, true, meta(), diag()); return new Function.Binding(name, args, ascribedBody, isPrivate, loc, true, meta());
} }
} }
@ -665,13 +671,12 @@ final class TreeToIr {
} }
String comment = "the result of `" + functionName + "`"; String comment = "the result of `" + functionName + "`";
return new Type.Ascription(body, type, Option.apply(comment), loc, meta(), diag()); return new Type.Ascription(body, type, Option.apply(comment), loc, meta());
} }
private Type.Ascription translateTypeSignature(Tree sig, Tree type, Expression typeName) { private Type.Ascription translateTypeSignature(Tree sig, Tree type, Expression typeName) {
var fn = translateType(type); var fn = translateType(type);
return new Type.Ascription(typeName, fn, Option.empty(), getIdentifiedLocation(sig), meta(), return new Type.Ascription(typeName, fn, Option.empty(), getIdentifiedLocation(sig), meta());
diag());
} }
@ -704,9 +709,7 @@ final class TreeToIr {
} }
default -> throw translateEntity(sig, "translateMethodReference"); default -> throw translateEntity(sig, "translateMethodReference");
} }
return new Name.MethodReference(type, method, return new Name.MethodReference(type, method, loc, meta());
loc, meta(), diag()
);
} }
private Expression translateCall(Tree ast, boolean isMethod) throws SyntaxException { private Expression translateCall(Tree ast, boolean isMethod) throws SyntaxException {
@ -722,14 +725,14 @@ final class TreeToIr {
case Tree.App app -> { case Tree.App app -> {
var expr = translateExpression(app.getArg(), false); var expr = translateExpression(app.getArg(), false);
var loc = getIdentifiedLocation(app.getArg()); var loc = getIdentifiedLocation(app.getArg());
args.add(new CallArgument.Specified(Option.empty(), expr, loc, meta(), diag())); args.add(new CallArgument.Specified(Option.empty(), expr, loc, meta()));
tree = app.getFunc(); tree = app.getFunc();
} }
case Tree.NamedApp app -> { case Tree.NamedApp app -> {
var expr = translateExpression(app.getArg(), false); var expr = translateExpression(app.getArg(), false);
var loc = getIdentifiedLocation(app.getArg()); var loc = getIdentifiedLocation(app.getArg());
var id = buildName(app, app.getName()); var id = buildName(app, app.getName());
args.add(new CallArgument.Specified(Option.apply(id), expr, loc, meta(), diag())); args.add(new CallArgument.Specified(Option.apply(id), expr, loc, meta()));
tree = app.getFunc(); tree = app.getFunc();
} }
case Tree.OperatorBlockApplication app -> { case Tree.OperatorBlockApplication app -> {
@ -745,20 +748,17 @@ final class TreeToIr {
} }
var expr = switch (translateExpression(l.getExpression().getExpression(), true)) { var expr = switch (translateExpression(l.getExpression().getExpression(), true)) {
case Application.Prefix pref -> { case Application.Prefix pref -> {
var arg = new CallArgument.Specified(Option.empty(), self, self.location(), meta(), var arg = new CallArgument.Specified(Option.empty(), self, self.location(), meta());
diag());
yield new Application.Prefix(pref.function(), join(arg, pref.arguments()), false, yield new Application.Prefix(pref.function(), join(arg, pref.arguments()), false,
pref.location(), meta(), diag()); pref.location(), meta());
} }
case Expression any -> { case Expression any -> {
var arg = new CallArgument.Specified(Option.empty(), self, self.location(), meta(), var arg = new CallArgument.Specified(Option.empty(), self, self.location(), meta());
diag()); yield new Application.Prefix(any, join(arg, nil()), false, any.location(), meta());
yield new Application.Prefix(any, join(arg, nil()), false, any.location(), meta(),
diag());
} }
}; };
var loc = getIdentifiedLocation(l.getExpression().getExpression()); var loc = getIdentifiedLocation(l.getExpression().getExpression());
args.add(at, new CallArgument.Specified(Option.empty(), expr, loc, meta(), diag())); args.add(at, new CallArgument.Specified(Option.empty(), expr, loc, meta()));
self = expr; self = expr;
} }
return self; return self;
@ -775,7 +775,7 @@ final class TreeToIr {
if (oprApp.getLhs() != null) { if (oprApp.getLhs() != null) {
var self = translateExpression(oprApp.getLhs(), isMethod); var self = translateExpression(oprApp.getLhs(), isMethod);
var loc = getIdentifiedLocation(oprApp.getLhs()); var loc = getIdentifiedLocation(oprApp.getLhs());
args.add(new CallArgument.Specified(Option.empty(), self, loc, meta(), diag())); args.add(new CallArgument.Specified(Option.empty(), self, loc, meta()));
} }
} else if (args.isEmpty()) { } else if (args.isEmpty()) {
return null; return null;
@ -788,8 +788,7 @@ final class TreeToIr {
func, argsList, func, argsList,
hasDefaultsSuspended, hasDefaultsSuspended,
getIdentifiedLocation(ast), getIdentifiedLocation(ast),
meta(), meta()
diag()
); );
} }
} }
@ -802,7 +801,7 @@ final class TreeToIr {
case Tree.Group g -> case Tree.Group g ->
translateOldStyleLambdaArgumentName(g.getBody(), suspended, defaultValue); translateOldStyleLambdaArgumentName(g.getBody(), suspended, defaultValue);
case Tree.Wildcard wild -> case Tree.Wildcard wild ->
new Name.Blank(getIdentifiedLocation(wild.getToken()), meta(), diag()); new Name.Blank(getIdentifiedLocation(wild.getToken()), meta());
case Tree.OprApp app when "=".equals(app.getOpr().getRight().codeRepr()) -> { case Tree.OprApp app when "=".equals(app.getOpr().getRight().codeRepr()) -> {
if (defaultValue != null) { if (defaultValue != null) {
defaultValue[0] = translateExpression(app.getRhs(), false); defaultValue[0] = translateExpression(app.getRhs(), false);
@ -866,7 +865,7 @@ final class TreeToIr {
} }
var body = translateExpression(lambda.getBody(), false); var body = translateExpression(lambda.getBody(), false);
var at = getIdentifiedLocation(lambda); var at = getIdentifiedLocation(lambda);
yield new Function.Lambda(args, body, at, true, meta(), diag()); yield new Function.Lambda(args, body, at, true, meta());
} }
case Tree.OprApp app -> { case Tree.OprApp app -> {
var op = app.getOpr().getRight(); var op = app.getOpr().getRight();
@ -877,7 +876,7 @@ final class TreeToIr {
var errLoc = arr.size() > 1 ? getIdentifiedLocation(arr.get(1)) : at; var errLoc = arr.size() > 1 ? getIdentifiedLocation(arr.get(1)) : at;
var err = translateSyntaxError(errLoc.get(), Syntax.UnrecognizedToken$.MODULE$); var err = translateSyntaxError(errLoc.get(), Syntax.UnrecognizedToken$.MODULE$);
var name = buildName(app.getLhs()); var name = buildName(app.getLhs());
yield new Expression.Binding(name, err, at, meta(), diag()); yield new Expression.Binding(name, err, at, meta());
} else { } else {
yield translateSyntaxError(at.get(), Syntax.UnrecognizedToken$.MODULE$); yield translateSyntaxError(at.get(), Syntax.UnrecognizedToken$.MODULE$);
} }
@ -911,22 +910,21 @@ final class TreeToIr {
Option.apply(defaultValue[0]), Option.apply(defaultValue[0]),
isSuspended[0], isSuspended[0],
getIdentifiedLocation(arg), getIdentifiedLocation(arg),
meta(), meta()
diag()
); );
List<DefinitionArgument> args = join(arg_, nil()); List<DefinitionArgument> args = join(arg_, nil());
var body = translateExpression(app.getRhs(), false); var body = translateExpression(app.getRhs(), false);
if (body == null) { if (body == null) {
body = new Expression.Block( body = new Expression.Block(
nil(), new Name.Blank(Option.empty(), meta(), diag()), nil(), new Name.Blank(Option.empty(), meta()),
Option.empty(), true, meta(), diag() Option.empty(), true, meta()
); );
} }
var at = expandToContain(switch (body) { var at = expandToContain(switch (body) {
case Expression.Block __ -> getIdentifiedLocation(tree, 0, 1, null); case Expression.Block __ -> getIdentifiedLocation(tree, 0, 1, null);
default -> getIdentifiedLocation(tree); default -> getIdentifiedLocation(tree);
}, body.location()); }, body.location());
yield new Function.Lambda(args, body, at, true, meta(), diag()); yield new Function.Lambda(args, body, at, true, meta());
} }
default -> { default -> {
var lhs = unnamedCallArgument(app.getLhs()); var lhs = unnamedCallArgument(app.getLhs());
@ -951,7 +949,7 @@ final class TreeToIr {
var loc = getIdentifiedLocation(app); var loc = getIdentifiedLocation(app);
var both = applyOperator(op, lhs, rhs, loc); var both = applyOperator(op, lhs, rhs, loc);
expr = both; expr = both;
lhs = new CallArgument.Specified(Option.empty(), expr, loc, meta(), diag()); lhs = new CallArgument.Specified(Option.empty(), expr, loc, meta());
} }
yield expr; yield expr;
} }
@ -970,7 +968,8 @@ final class TreeToIr {
} }
yield new Application.Sequence( yield new Application.Sequence(
items.reverse(), items.reverse(),
getIdentifiedLocation(arr), meta(), diag() getIdentifiedLocation(arr),
meta()
); );
} }
case Tree.Number n -> translateNumber(n); case Tree.Number n -> translateNumber(n);
@ -997,12 +996,11 @@ final class TreeToIr {
var subexpression = useOrElse(applySkip(body), body); var subexpression = useOrElse(applySkip(body), body);
yield translateExpression(subexpression, false); yield translateExpression(subexpression, false);
} }
var fn = new Name.Literal(fullName, true, Option.empty(), Option.empty(), meta(), diag()); var fn = new Name.Literal(fullName, true, Option.empty(), Option.empty(), meta());
if (!checkArgs(args)) { if (!checkArgs(args)) {
yield translateSyntaxError(app, Syntax.UnexpectedExpression$.MODULE$); yield translateSyntaxError(app, Syntax.UnexpectedExpression$.MODULE$);
} }
yield new Application.Prefix(fn, args.reverse(), false, getIdentifiedLocation(tree), meta(), yield new Application.Prefix(fn, args.reverse(), false, getIdentifiedLocation(tree), meta());
diag());
} }
case Tree.BodyBlock body -> { case Tree.BodyBlock body -> {
var expressions = new java.util.ArrayList<Expression>(); var expressions = new java.util.ArrayList<Expression>();
@ -1038,7 +1036,7 @@ final class TreeToIr {
var id = IdentifiedLocation.create(patched, last.location().get().id()); var id = IdentifiedLocation.create(patched, last.location().get().id());
last = last.setLocation(Option.apply(id)); last = last.setLocation(Option.apply(id));
} }
yield new Expression.Block(list, last, locationWithANewLine, false, meta(), diag()); yield new Expression.Block(list, last, locationWithANewLine, false, meta());
} }
case Tree.Assignment assign -> { case Tree.Assignment assign -> {
var name = buildNameOrQualifiedName(assign.getPattern()); var name = buildNameOrQualifiedName(assign.getPattern());
@ -1046,7 +1044,7 @@ final class TreeToIr {
if (expr == null) { if (expr == null) {
expr = translateSyntaxError(assign, Syntax.UnexpectedExpression$.MODULE$); expr = translateSyntaxError(assign, Syntax.UnexpectedExpression$.MODULE$);
} }
yield new Expression.Binding(name, expr, getIdentifiedLocation(tree), meta(), diag()); yield new Expression.Binding(name, expr, getIdentifiedLocation(tree), meta());
} }
case Tree.ArgumentBlockApplication body -> { case Tree.ArgumentBlockApplication body -> {
List<Expression> expressions = nil(); List<Expression> expressions = nil();
@ -1062,10 +1060,10 @@ final class TreeToIr {
last = translateExpression(expr, false); last = translateExpression(expr, false);
} }
if (last == null) { if (last == null) {
last = new Name.Blank(Option.empty(), meta(), diag()); last = new Name.Blank(Option.empty(), meta());
} }
var block = new Expression.Block(expressions.reverse(), last, getIdentifiedLocation(body), var block =
false, meta(), diag()); new Expression.Block(expressions.reverse(), last, getIdentifiedLocation(body), false, meta());
if (body.getLhs() != null) { if (body.getLhs() != null) {
var fn = translateExpression(body.getLhs(), isMethod); var fn = translateExpression(body.getLhs(), isMethod);
List<CallArgument> args = nil(); List<CallArgument> args = nil();
@ -1114,11 +1112,13 @@ final class TreeToIr {
if (branch.getDocumentation() != null) { if (branch.getDocumentation() != null) {
var comment = translateComment(cas, branch.getDocumentation()); var comment = translateComment(cas, branch.getDocumentation());
var loc = getIdentifiedLocation(cas); var loc = getIdentifiedLocation(cas);
var doc = new Pattern.Documentation(comment.doc(), loc, meta(), diag()); var doc = new Pattern.Documentation(comment.doc(), loc, meta());
var br = new Case.Branch( var br = new Case.Branch(
doc, doc,
new Empty(Option.empty(), meta(), diag()), new Empty(Option.empty(), meta()),
loc, meta(), diag() true,
loc,
meta()
); );
branches = join(br, branches); branches = join(br, branches);
} }
@ -1128,12 +1128,13 @@ final class TreeToIr {
var br = new Case.Branch( var br = new Case.Branch(
translatePattern(branch.getPattern()), translatePattern(branch.getPattern()),
translateExpression(branch.getExpression(), false), translateExpression(branch.getExpression(), false),
getIdentifiedLocation(branch.getExpression()), meta(), diag() true,
getIdentifiedLocation(branch.getExpression()), meta()
); );
branches = join(br, branches); branches = join(br, branches);
} }
} }
yield new Case.Expr(expr, branches.reverse(), getIdentifiedLocation(tree), meta(), diag()); yield new Case.Expr(expr, branches.reverse(), false, getIdentifiedLocation(tree), meta());
} }
case Tree.Function fun -> { case Tree.Function fun -> {
var name = buildName(fun.getName()); var name = buildName(fun.getName());
@ -1156,12 +1157,9 @@ final class TreeToIr {
n.copy$default$6() n.copy$default$6()
); );
case Expression expr -> { case Expression expr -> {
var negate = new Name.Literal("negate", true, Option.empty(), Option.empty(), meta(), var negate = new Name.Literal("negate", true, Option.empty(), Option.empty(), meta());
diag()); var arg = new CallArgument.Specified(Option.empty(), expr, expr.location(), meta());
var arg = new CallArgument.Specified(Option.empty(), expr, expr.location(), meta(), yield new Application.Prefix(negate, join(arg, nil()), false, expr.location(), meta());
diag());
yield new Application.Prefix(negate, join(arg, nil()), false, expr.location(), meta(),
diag());
} }
case null -> case null ->
translateSyntaxError(tree, new Syntax.UnsupportedSyntax("Strange unary -")); translateSyntaxError(tree, new Syntax.UnsupportedSyntax("Strange unary -"));
@ -1172,18 +1170,17 @@ final class TreeToIr {
Option.empty(), Option.empty(),
methodName, methodName,
methodName.location(), methodName.location(),
meta(), diag() meta()
); );
var opName = buildName(Option.empty(), sig.getOperator(), true); var opName = buildName(Option.empty(), sig.getOperator(), true);
var signature = translateTypeCallArgument(sig.getType()); var signature = translateTypeCallArgument(sig.getType());
yield new Operator.Binary(methodReference, opName, signature, getIdentifiedLocation(sig), yield new Operator.Binary(methodReference, opName, signature, getIdentifiedLocation(sig), meta());
meta(), diag());
} }
case Tree.TemplateFunction templ -> translateExpression(templ.getAst(), false); case Tree.TemplateFunction templ -> translateExpression(templ.getAst(), false);
case Tree.Wildcard wild -> new Name.Blank(getIdentifiedLocation(wild), meta(), diag()); case Tree.Wildcard wild -> new Name.Blank(getIdentifiedLocation(wild), meta());
case Tree.AnnotatedBuiltin anno -> { case Tree.AnnotatedBuiltin anno -> {
var ir = new Name.BuiltinAnnotation("@" + anno.getAnnotation().codeRepr(), var ir = new Name.BuiltinAnnotation("@" + anno.getAnnotation().codeRepr(),
getIdentifiedLocation(anno), meta(), diag()); getIdentifiedLocation(anno), meta());
yield translateAnnotation(ir, anno.getExpression(), nil()); yield translateAnnotation(ir, anno.getExpression(), nil());
} }
// Documentation can be attached to an expression in a few cases, like if someone documents a line of an // Documentation can be attached to an expression in a few cases, like if someone documents a line of an
@ -1193,7 +1190,7 @@ final class TreeToIr {
var fn = translateExpression(app.getFunc(), isMethod); var fn = translateExpression(app.getFunc(), isMethod);
var loc = getIdentifiedLocation(app); var loc = getIdentifiedLocation(app);
if (app.getArg() instanceof Tree.SuspendedDefaultArguments) { if (app.getArg() instanceof Tree.SuspendedDefaultArguments) {
yield new Application.Prefix(fn, nil(), true, loc, meta(), diag()); yield new Application.Prefix(fn, nil(), true, loc, meta());
} else { } else {
yield fn.setLocation(loc); yield fn.setLocation(loc);
} }
@ -1204,7 +1201,7 @@ final class TreeToIr {
Option.empty(), Option.empty(),
methodName, methodName,
getIdentifiedLocation(autoscopedIdentifier), getIdentifiedLocation(autoscopedIdentifier),
meta(), diag() meta()
); );
} }
case Tree.Private __ -> translateSyntaxError(tree, Syntax.UnexpectedExpression$.MODULE$); case Tree.Private __ -> translateSyntaxError(tree, Syntax.UnexpectedExpression$.MODULE$);
@ -1217,23 +1214,23 @@ final class TreeToIr {
for (var warning : tree.getWarnings()) { for (var warning : tree.getWarnings()) {
var message = Parser.getWarningMessage(warning); var message = Parser.getWarningMessage(warning);
var irWarning = new Warning.Syntax(ir, message); var irWarning = new Warning.Syntax(ir, message);
ir.diagnostics().add(irWarning); ir.getDiagnostics().add(irWarning);
} }
} }
private Operator applyOperator(Token.Operator op, CallArgument lhs, CallArgument rhs, private Operator applyOperator(Token.Operator op, CallArgument lhs, CallArgument rhs,
Option<IdentifiedLocation> loc) { Option<IdentifiedLocation> loc) {
var name = new Name.Literal( var name = new Name.Literal(
op.codeRepr(), true, getIdentifiedLocation(op), Option.empty(), meta(), diag() op.codeRepr(), true, getIdentifiedLocation(op), Option.empty(), meta()
); );
if (lhs == null && rhs == null) { if (lhs == null && rhs == null) {
return new Section.Sides(name, loc, meta(), diag()); return new Section.Sides(name, loc, meta());
} else if (lhs == null) { } else if (lhs == null) {
return new Section.Right(name, rhs, loc, meta(), diag()); return new Section.Right(name, rhs, loc, meta());
} else if (rhs == null) { } else if (rhs == null) {
return new Section.Left(lhs, name, loc, meta(), diag()); return new Section.Left(lhs, name, loc, meta());
} else { } else {
return new Operator.Binary(lhs, name, rhs, loc, meta(), diag()); return new Operator.Binary(lhs, name, rhs, loc, meta());
} }
} }
@ -1328,8 +1325,7 @@ final class TreeToIr {
var literal = translateType(app.getLhs()); var literal = translateType(app.getLhs());
var body = translateType(app.getRhs()); var body = translateType(app.getRhs());
if (body == null) { if (body == null) {
yield new Syntax(getIdentifiedLocation(app).get(), yield new Syntax(getIdentifiedLocation(app).get(), Syntax.UnexpectedExpression$.MODULE$, meta());
Syntax.UnexpectedExpression$.MODULE$, meta(), diag());
} }
var args = switch (body) { var args = switch (body) {
case Type.Function fn -> { case Type.Function fn -> {
@ -1338,7 +1334,7 @@ final class TreeToIr {
} }
default -> join(literal, nil()); default -> join(literal, nil());
}; };
yield new Type.Function(args, body, Option.empty(), meta(), diag()); yield new Type.Function(args, body, Option.empty(), meta());
} }
default -> { default -> {
var lhs = translateTypeCallArgument(app.getLhs()); var lhs = translateTypeCallArgument(app.getLhs());
@ -1347,10 +1343,10 @@ final class TreeToIr {
op.codeRepr(), true, op.codeRepr(), true,
getIdentifiedLocation(app), getIdentifiedLocation(app),
Option.empty(), Option.empty(),
meta(), diag() meta()
); );
var loc = getIdentifiedLocation(app); var loc = getIdentifiedLocation(app);
yield new Operator.Binary(lhs, name, rhs, loc, meta(), diag()); yield new Operator.Binary(lhs, name, rhs, loc, meta());
} }
}; };
} }
@ -1366,13 +1362,14 @@ final class TreeToIr {
} }
yield new Application.Literal.Sequence( yield new Application.Literal.Sequence(
items.reverse(), items.reverse(),
getIdentifiedLocation(arr), meta(), diag() getIdentifiedLocation(arr),
meta()
); );
} }
case Tree.Ident id -> buildName(getIdentifiedLocation(id), id.getToken(), false); case Tree.Ident id -> buildName(getIdentifiedLocation(id), id.getToken(), false);
case Tree.Group group -> translateType(group.getBody()); case Tree.Group group -> translateType(group.getBody());
case Tree.UnaryOprApp un -> translateType(un.getRhs()); case Tree.UnaryOprApp un -> translateType(un.getRhs());
case Tree.Wildcard wild -> new Name.Blank(getIdentifiedLocation(wild), meta(), diag()); case Tree.Wildcard wild -> new Name.Blank(getIdentifiedLocation(wild), meta());
case Tree.TypeAnnotated anno -> translateTypeAnnotatedToOperator(anno); case Tree.TypeAnnotated anno -> translateTypeAnnotatedToOperator(anno);
default -> translateSyntaxError(tree, new Syntax.UnsupportedSyntax("translateType")); default -> translateSyntaxError(tree, new Syntax.UnsupportedSyntax("translateType"));
}; };
@ -1384,7 +1381,7 @@ final class TreeToIr {
Expression translateTypeAnnotated(Tree.TypeAnnotated anno) { Expression translateTypeAnnotated(Tree.TypeAnnotated anno) {
var type = translateType(anno.getType()); var type = translateType(anno.getType());
var expr = translateExpression(anno.getExpression()); var expr = translateExpression(anno.getExpression());
return new Type.Ascription(expr, type, Option.empty(), getIdentifiedLocation(anno), meta(), diag()); return new Type.Ascription(expr, type, Option.empty(), getIdentifiedLocation(anno), meta());
} }
/** /**
@ -1394,14 +1391,13 @@ final class TreeToIr {
var type = translateTypeCallArgument(anno.getType()); var type = translateTypeCallArgument(anno.getType());
var expr = translateCallArgument(anno.getExpression()); var expr = translateCallArgument(anno.getExpression());
var opName = new Name.Literal(anno.getOperator().codeRepr(), true, Option.empty(), var opName = new Name.Literal(anno.getOperator().codeRepr(), true, Option.empty(),
Option.empty(), meta(), diag()); Option.empty(), meta());
return new Operator.Binary( return new Operator.Binary(
expr, expr,
opName, opName,
type, type,
getIdentifiedLocation(anno), getIdentifiedLocation(anno),
meta(), diag() meta());
);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -1415,13 +1411,13 @@ final class TreeToIr {
} }
List<CallArgument> allArgs = (List<CallArgument>) pref.arguments().appendedAll(args.reverse()); List<CallArgument> allArgs = (List<CallArgument>) pref.arguments().appendedAll(args.reverse());
final CallArgument.Specified blockArg = new CallArgument.Specified(Option.empty(), block, final CallArgument.Specified blockArg = new CallArgument.Specified(Option.empty(), block,
block.location(), meta(), diag()); block.location(), meta());
List<CallArgument> withBlockArgs = (List<CallArgument>) allArgs.appended(blockArg); List<CallArgument> withBlockArgs = (List<CallArgument>) allArgs.appended(blockArg);
if (!checkArgs(withBlockArgs)) { if (!checkArgs(withBlockArgs)) {
return translateSyntaxError(pref.location().get(), Syntax.UnexpectedExpression$.MODULE$); return translateSyntaxError(pref.location().get(), Syntax.UnexpectedExpression$.MODULE$);
} }
return new Application.Prefix(pref.function(), withBlockArgs, pref.hasDefaultsSuspended(), return new Application.Prefix(pref.function(), withBlockArgs, pref.hasDefaultsSuspended(),
pref.location(), meta(), diag()); pref.location(), meta());
} }
private Application.Prefix translateAnnotation(Name.BuiltinAnnotation ir, Tree expr, private Application.Prefix translateAnnotation(Name.BuiltinAnnotation ir, Tree expr,
@ -1442,7 +1438,7 @@ final class TreeToIr {
yield translateAnnotation(ir, null, callArgs); yield translateAnnotation(ir, null, callArgs);
} }
case null -> { case null -> {
yield new Application.Prefix(ir, callArgs, false, ir.location(), meta(), diag()); yield new Application.Prefix(ir, callArgs, false, ir.location(), meta());
} }
default -> { default -> {
var arg = translateCallArgument(expr); var arg = translateCallArgument(expr);
@ -1464,7 +1460,7 @@ final class TreeToIr {
var fracPart = ast.getFractionalDigits(); var fracPart = ast.getFractionalDigits();
String literal = fracPart != null ? intPart.codeRepr() + "." + fracPart.getDigits().codeRepr() String literal = fracPart != null ? intPart.codeRepr() + "." + fracPart.getDigits().codeRepr()
: intPart.codeRepr(); : intPart.codeRepr();
return new Literal.Number(base, literal, getIdentifiedLocation(ast), meta(), diag()); return new Literal.Number(base, literal, getIdentifiedLocation(ast), meta());
} }
Literal translateLiteral(Tree.TextLiteral txt) throws SyntaxException { Literal translateLiteral(Tree.TextLiteral txt) throws SyntaxException {
@ -1479,7 +1475,7 @@ final class TreeToIr {
} }
// Splices are not yet supported in the IR. // Splices are not yet supported in the IR.
var value = buildTextConstant(txt, txt.getElements()); var value = buildTextConstant(txt, txt.getElements());
return new Literal.Text(value, getIdentifiedLocation(txt), meta(), diag()); return new Literal.Text(value, getIdentifiedLocation(txt), meta());
} }
private String buildTextConstant(Tree at, Iterable<TextElement> elements) throws SyntaxException { private String buildTextConstant(Tree at, Iterable<TextElement> elements) throws SyntaxException {
@ -1517,7 +1513,7 @@ final class TreeToIr {
Tree pattern = def.getPattern(); Tree pattern = def.getPattern();
Name name = switch (pattern) { Name name = switch (pattern) {
case Tree.Wildcard wild -> case Tree.Wildcard wild ->
new Name.Blank(getIdentifiedLocation(wild.getToken()), meta(), diag()); new Name.Blank(getIdentifiedLocation(wild.getToken()), meta());
case Tree.Ident id -> { case Tree.Ident id -> {
Expression identifier = translateIdent(id, false); Expression identifier = translateIdent(id, false);
yield switch (identifier) { yield switch (identifier) {
@ -1540,8 +1536,7 @@ final class TreeToIr {
defaultValue, defaultValue,
isSuspended, isSuspended,
getIdentifiedLocation(def), getIdentifiedLocation(def),
meta(), meta()
diag()
); );
} }
@ -1557,12 +1552,12 @@ final class TreeToIr {
case Tree.NamedApp app -> { case Tree.NamedApp app -> {
var expr = translateExpression(app.getArg(), false); var expr = translateExpression(app.getArg(), false);
var id = sanitizeName(buildName(app, app.getName())); var id = sanitizeName(buildName(app, app.getName()));
yield new CallArgument.Specified(Option.apply(id), expr, loc, meta(), diag()); yield new CallArgument.Specified(Option.apply(id), expr, loc, meta());
} }
case null -> null; case null -> null;
default -> { default -> {
var expr = translateExpression(arg, false); var expr = translateExpression(arg, false);
yield new CallArgument.Specified(Option.empty(), expr, loc, meta(), diag()); yield new CallArgument.Specified(Option.empty(), expr, loc, meta());
} }
}; };
} }
@ -1570,7 +1565,7 @@ final class TreeToIr {
CallArgument.Specified translateTypeCallArgument(Tree arg) { CallArgument.Specified translateTypeCallArgument(Tree arg) {
var loc = getIdentifiedLocation(arg); var loc = getIdentifiedLocation(arg);
var expr = translateType(arg); var expr = translateType(arg);
return new CallArgument.Specified(Option.empty(), expr, loc, meta(), diag()); return new CallArgument.Specified(Option.empty(), expr, loc, meta());
} }
CallArgument.Specified unnamedCallArgument(Tree arg) { CallArgument.Specified unnamedCallArgument(Tree arg) {
@ -1579,7 +1574,7 @@ final class TreeToIr {
} }
var loc = getIdentifiedLocation(arg); var loc = getIdentifiedLocation(arg);
var expr = translateExpression(arg); var expr = translateExpression(arg);
return new CallArgument.Specified(Option.empty(), expr, loc, meta(), diag()); return new CallArgument.Specified(Option.empty(), expr, loc, meta());
} }
/** /**
@ -1601,7 +1596,6 @@ final class TreeToIr {
* Translates a pattern in a case expression from its [[AST]] representation into [[IR]]. * Translates a pattern in a case expression from its [[AST]] representation into [[IR]].
* *
* @param block the case pattern to translate * @param block the case pattern to translate
* @return
*/ */
Pattern translatePattern(Tree block) throws SyntaxException { Pattern translatePattern(Tree block) throws SyntaxException {
var pattern = maybeManyParensed(block); var pattern = maybeManyParensed(block);
@ -1611,23 +1605,22 @@ final class TreeToIr {
case Tree.Ident id when id.getToken().isTypeOrConstructor() || !fields.isEmpty() -> { case Tree.Ident id when id.getToken().isTypeOrConstructor() || !fields.isEmpty() -> {
yield new Pattern.Constructor( yield new Pattern.Constructor(
sanitizeName(buildName(id)), fields, sanitizeName(buildName(id)), fields,
getIdentifiedLocation(id), meta(), diag() getIdentifiedLocation(id), meta()
); );
} }
case Tree.Ident id -> case Tree.Ident id ->
new Pattern.Name(buildName(id), getIdentifiedLocation(id), meta(), diag()); new Pattern.Name(buildName(id), getIdentifiedLocation(id), meta());
case Tree.OprApp app when isDotOperator(app.getOpr().getRight()) -> { case Tree.OprApp app when isDotOperator(app.getOpr().getRight()) -> {
var qualifiedName = buildQualifiedName(app); var qualifiedName = buildQualifiedName(app);
yield new Pattern.Constructor( yield new Pattern.Constructor(
qualifiedName, fields, getIdentifiedLocation(app), meta(), diag() qualifiedName, fields, getIdentifiedLocation(app), meta()
); );
} }
case Tree.Wildcard wild -> translateWildcardPattern(wild); case Tree.Wildcard wild -> translateWildcardPattern(wild);
case Tree.TextLiteral lit -> case Tree.TextLiteral lit ->
new Pattern.Literal(translateLiteral(lit), getIdentifiedLocation(lit), meta(), diag()); new Pattern.Literal(translateLiteral(lit), getIdentifiedLocation(lit), meta());
case Tree.Number num -> case Tree.Number num ->
new Pattern.Literal((Literal) translateNumber(num), getIdentifiedLocation(num), meta(), new Pattern.Literal((Literal) translateNumber(num), getIdentifiedLocation(num), meta());
diag());
case Tree.UnaryOprApp num when num.getOpr().codeRepr().equals("-") -> { case Tree.UnaryOprApp num when num.getOpr().codeRepr().equals("-") -> {
var n = (Literal.Number) translateExpression(num.getRhs()); var n = (Literal.Number) translateExpression(num.getRhs());
var t = n.copy( var t = n.copy(
@ -1638,13 +1631,12 @@ final class TreeToIr {
n.copy$default$5(), n.copy$default$5(),
n.copy$default$6() n.copy$default$6()
); );
yield new Pattern.Literal(t, getIdentifiedLocation(num), meta(), diag()); yield new Pattern.Literal(t, getIdentifiedLocation(num), meta());
} }
case Tree.TypeAnnotated anno -> { case Tree.TypeAnnotated anno -> {
var type = buildNameOrQualifiedName(maybeManyParensed(anno.getType())); var type = buildNameOrQualifiedName(maybeManyParensed(anno.getType()));
var expr = buildNameOrQualifiedName(maybeManyParensed(anno.getExpression())); var expr = buildNameOrQualifiedName(maybeManyParensed(anno.getExpression()));
yield new Pattern.Type(expr, type instanceof Name ? (Name) type : null, Option.empty(), yield new Pattern.Type(expr, type instanceof Name ? (Name) type : null, Option.empty(), meta());
meta(), diag());
} }
case Tree.Group group -> translatePattern(group.getBody()); case Tree.Group group -> translatePattern(group.getBody());
default -> throw translateEntity(pattern, "translatePattern"); default -> throw translateEntity(pattern, "translatePattern");
@ -1663,8 +1655,8 @@ final class TreeToIr {
private Pattern.Name translateWildcardPattern(Tree.Wildcard wild) { private Pattern.Name translateWildcardPattern(Tree.Wildcard wild) {
var at = getIdentifiedLocation(wild); var at = getIdentifiedLocation(wild);
var blank = new Name.Blank(at, meta(), diag()); var blank = new Name.Blank(at, meta());
return new Pattern.Name(blank, at, meta(), diag()); return new Pattern.Name(blank, at, meta());
} }
private Name.Qualified buildQualifiedName(Tree t) throws SyntaxException { private Name.Qualified buildQualifiedName(Tree t) throws SyntaxException {
@ -1673,7 +1665,7 @@ final class TreeToIr {
private Name.Qualified buildQualifiedName(Tree t, Option<IdentifiedLocation> loc, private Name.Qualified buildQualifiedName(Tree t, Option<IdentifiedLocation> loc,
boolean generateId) throws SyntaxException { boolean generateId) throws SyntaxException {
return new Name.Qualified(qualifiedNameSegments(t, generateId), loc, meta(), diag()); return new Name.Qualified(qualifiedNameSegments(t, generateId), loc, meta());
} }
private Name buildNameOrQualifiedName(Tree t) throws SyntaxException { private Name buildNameOrQualifiedName(Tree t) throws SyntaxException {
@ -1686,7 +1678,7 @@ final class TreeToIr {
if (segments.length() == 1) { if (segments.length() == 1) {
return segments.head(); return segments.head();
} else { } else {
return new Name.Qualified(segments, loc, meta(), diag()); return new Name.Qualified(segments, loc, meta());
} }
} }
@ -1728,7 +1720,7 @@ final class TreeToIr {
return switch (tree) { return switch (tree) {
case Tree.Ident id -> sanitizeName(buildName(id, generateId)); case Tree.Ident id -> sanitizeName(buildName(id, generateId));
case Tree.Wildcard wild -> case Tree.Wildcard wild ->
new Name.Blank(getIdentifiedLocation(wild.getToken(), generateId), meta(), diag()); new Name.Blank(getIdentifiedLocation(wild.getToken(), generateId), meta());
default -> throw translateEntity(tree, "qualifiedNameSegment"); default -> throw translateEntity(tree, "qualifiedNameSegment");
}; };
} }
@ -1788,8 +1780,7 @@ final class TreeToIr {
new Polyglot.Java(pkg.toString(), cls), new Polyglot.Java(pkg.toString(), cls),
rename.map(name -> name.name()), rename.map(name -> name.name()),
getIdentifiedLocation(imp), getIdentifiedLocation(imp),
meta(), meta()
diag()
); );
} }
var isAll = imp.getAll() != null; var isAll = imp.getAll() != null;
@ -1813,7 +1804,7 @@ final class TreeToIr {
qualifiedName, rename, isAll || onlyNames.isDefined() || hidingNames.isDefined(), qualifiedName, rename, isAll || onlyNames.isDefined() || hidingNames.isDefined(),
onlyNames, onlyNames,
hidingNames, getIdentifiedLocation(imp), false, hidingNames, getIdentifiedLocation(imp), false,
meta(), diag() meta()
); );
} catch (SyntaxException err) { } catch (SyntaxException err) {
if (err.where instanceof Invalid invalid) { if (err.where instanceof Invalid invalid) {
@ -1877,7 +1868,7 @@ final class TreeToIr {
return new Export.Module( return new Export.Module(
qualifiedName, rename, onlyNames, qualifiedName, rename, onlyNames,
getIdentifiedLocation(exp), false, getIdentifiedLocation(exp), false,
meta(), diag() meta()
); );
} catch (SyntaxException err) { } catch (SyntaxException err) {
if (err.where instanceof Invalid invalid) { if (err.where instanceof Invalid invalid) {
@ -1896,16 +1887,16 @@ final class TreeToIr {
*/ */
Comment.Documentation translateComment(Tree where, DocComment doc) throws SyntaxException { Comment.Documentation translateComment(Tree where, DocComment doc) throws SyntaxException {
var text = buildTextConstant(where, doc.getElements()); var text = buildTextConstant(where, doc.getElements());
return new Comment.Documentation(text, getIdentifiedLocation(where), meta(), diag()); return new Comment.Documentation(text, getIdentifiedLocation(where), meta());
} }
Syntax translateSyntaxError(Tree where, Syntax.Reason reason) { Syntax translateSyntaxError(Tree where, Syntax.Reason reason) {
var at = getIdentifiedLocation(where).get(); var at = getIdentifiedLocation(where).get();
return new Syntax(at, reason, meta(), diag()); return new Syntax(at, reason, meta());
} }
Syntax translateSyntaxError(IdentifiedLocation where, Syntax.Reason reason) { Syntax translateSyntaxError(IdentifiedLocation where, Syntax.Reason reason) {
return new Syntax(where, reason, meta(), diag()); return new Syntax(where, reason, meta());
} }
SyntaxException translateEntity(Tree where, String msg) throws SyntaxException { SyntaxException translateEntity(Tree where, String msg) throws SyntaxException {
@ -1943,7 +1934,7 @@ final class TreeToIr {
private Name.Literal buildName(Option<IdentifiedLocation> loc, Token id, boolean isMethod) { private Name.Literal buildName(Option<IdentifiedLocation> loc, Token id, boolean isMethod) {
final String name = id.codeRepr(); final String name = id.codeRepr();
return new Name.Literal(name, isMethod, loc, Option.empty(), meta(), diag()); return new Name.Literal(name, isMethod, loc, Option.empty(), meta());
} }
private Name sanitizeName(Name.Literal id) { private Name sanitizeName(Name.Literal id) {
@ -2052,10 +2043,6 @@ final class TreeToIr {
return new MetadataStorage(); return new MetadataStorage();
} }
private DiagnosticStorage diag() {
return DiagnosticStorage.apply(nil());
}
private static int castToInt(long presumablyInt) { private static int castToInt(long presumablyInt) {
int value = (int) presumablyInt; int value = (int) presumablyInt;
if (value != presumablyInt) { if (value != presumablyInt) {

View File

@ -467,14 +467,23 @@ public final class IrPersistance {
@Override @Override
protected void writeObject(DiagnosticStorage obj, Output out) throws IOException { protected void writeObject(DiagnosticStorage obj, Output out) throws IOException {
if (obj == null) {
out.writeBoolean(false);
} else {
out.writeBoolean(true);
out.writeInline(List.class, obj.toList()); out.writeInline(List.class, obj.toList());
} }
}
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected DiagnosticStorage readObject(Input in) throws IOException, ClassNotFoundException { protected DiagnosticStorage readObject(Input in) throws IOException, ClassNotFoundException {
if (in.readBoolean()) {
var diags = in.readInline(List.class); var diags = in.readInline(List.class);
return new DiagnosticStorage(diags); return new DiagnosticStorage(diags);
} else {
return null;
}
} }
} }
} }

View File

@ -55,7 +55,7 @@ object Implicits {
* @return [[ir]] with added diagnostics * @return [[ir]] with added diagnostics
*/ */
def addDiagnostic(diagnostic: Diagnostic): T = { def addDiagnostic(diagnostic: Diagnostic): T = {
ir.diagnostics.add(diagnostic) ir.getDiagnostics.add(diagnostic)
ir ir
} }
} }

View File

@ -39,16 +39,15 @@ object CallArgument {
* @param value the expression being passed as the argument's value * @param value the expression being passed as the argument's value
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Specified( sealed case class Specified(
override val name: Option[Name], override val name: Option[Name],
override val value: Expression, override val value: Expression,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends CallArgument ) extends CallArgument
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -56,8 +55,6 @@ object CallArgument {
* @param name the name of the argument being called, if present * @param name the name of the argument being called, if present
* @param value the expression being passed as the argument's value * @param value the expression being passed as the argument's value
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param shouldBeSuspended whether or not the argument should be passed
* suspended
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node * @param diagnostics compiler diagnostics for this node
* @param id the identifier for the new node * @param id the identifier for the new node
@ -79,13 +76,8 @@ object CallArgument {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Specified( val res = Specified(name, value, location, passData)
name, res.diagnostics = diagnostics
value,
location,
passData,
diagnostics
)
res.id = id res.id = id
res res
} else this } else this
@ -116,8 +108,7 @@ object CallArgument {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -52,7 +52,6 @@ object DefinitionArgument {
* @param suspended whether or not the argument has its execution suspended * @param suspended whether or not the argument has its execution suspended
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Specified( sealed case class Specified(
override val name: Name, override val name: Name,
@ -60,12 +59,42 @@ object DefinitionArgument {
override val defaultValue: Option[Expression], override val defaultValue: Option[Expression],
override val suspended: Boolean, override val suspended: Boolean,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends DefinitionArgument ) extends DefinitionArgument
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Create a [[Specified]] object.
*
* @param name the name of the argument
* @param ascribedType the explicitly ascribed type of the argument, if present
* @param defaultValue the default value of the argument, if present
* @param suspended whether or not the argument has its execution suspended
* @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node
* @param diagnostics the compiler diagnostics
*/
def this(
name: Name,
ascribedType: Option[Expression],
defaultValue: Option[Expression],
suspended: Boolean,
location: Option[IdentifiedLocation],
passData: MetadataStorage,
diagnostics: DiagnosticStorage
) = {
this(
name,
ascribedType,
defaultValue,
suspended,
location,
passData
)
this.diagnostics = diagnostics
}
/** Creates a copy of `this`. /** Creates a copy of `this`.
* *
* @param name the name of the argument * @param name the name of the argument
@ -105,9 +134,9 @@ object DefinitionArgument {
defaultValue, defaultValue,
suspended, suspended,
location, location,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -148,8 +177,7 @@ object DefinitionArgument {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -24,67 +24,6 @@ final class DiagnosticStorage(initDiagnostics: Seq[Diagnostic] = Seq())
diagnostics = newDiagnostics.toList ::: diagnostics diagnostics = newDiagnostics.toList ::: diagnostics
} }
/** Applies the function `f` across the diagnostic storage, producing a
* result sequence.
*
* @param f the function to apply
* @tparam R the result type of `f`
* @return the sequence that results from applying `f` over the storage
*/
def map[R](f: Diagnostic => R): Seq[R] = {
diagnostics.map(f)
}
/** Applies the function `f` across the diagnostic storage in place.
*
* @param f the function to apply
*/
def mapInPlace(f: Diagnostic => Diagnostic): Unit = {
diagnostics = diagnostics.map(f)
}
/** Performs a collection operation on the diagnostics storage, producing
* a new sequence.
*
* @param pf the partial function to apply
* @tparam R the result type of the partial function
* @return the result of collecting across the storage with `pf`
*/
def collect[R](pf: PartialFunction[Diagnostic, R]): Seq[R] = {
diagnostics.collect(pf)
}
/** Filters the elements of the diagnostic storage using the predicate.
*
* @param pred the predicate to filter with
* @return a new diagnostic storage instance containing elements matching
* `pred`
*/
def filter(pred: Diagnostic => Boolean): DiagnosticStorage = {
new DiagnosticStorage(diagnostics.filter(pred))
}
/** Filters the elements of the diagnostic storage in place using the
* predicate.
*
* @param pred the predicate to filter with
*/
def filterInPlace(pred: Diagnostic => Boolean): Unit = {
diagnostics = diagnostics.filter(pred)
}
/** Performs a left fold over the diagnostic storage to produce a result.
*
* @param init the starting value
* @param op the operator to use to fold
* @tparam L the result type of the fold
* @return the result of folding over the storage using `op` starting wit
* `init`
*/
def foldLeft[L](init: L)(op: (L, Diagnostic) => L): L = {
diagnostics.foldLeft(init)(op)
}
/** Checks two diagnostics storages for equality. /** Checks two diagnostics storages for equality.
* *
* @param obj the object to check against `this` * @param obj the object to check against `this`
@ -119,16 +58,6 @@ final class DiagnosticStorage(initDiagnostics: Seq[Diagnostic] = Seq())
* @return a shallow copy of this * @return a shallow copy of this
*/ */
def copy: DiagnosticStorage = { def copy: DiagnosticStorage = {
DiagnosticStorage(this.diagnostics) new DiagnosticStorage(this.diagnostics)
} }
} }
object DiagnosticStorage {
/** Creates a new instance of the diagnostics storage.
*
* @param initDiagnostics the initial diagnostics to construct it with
* @return a new diagnostics storage instance
*/
def apply(initDiagnostics: Seq[Diagnostic] = Seq()): DiagnosticStorage =
new DiagnosticStorage(initDiagnostics)
}

View File

@ -9,15 +9,14 @@ import java.util.UUID
* *
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Empty( sealed case class Empty(
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends IR ) extends IR
with Expression with Expression
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this` /** Creates a copy of `this`
@ -40,7 +39,8 @@ sealed case class Empty(
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Empty(location, passData, diagnostics) val res = Empty(location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -57,8 +57,7 @@ sealed case class Empty(
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -53,17 +53,16 @@ object Expression {
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param suspended whether or not the block is suspended * @param suspended whether or not the block is suspended
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Block( sealed case class Block(
expressions: List[Expression], expressions: List[Expression],
returnValue: Expression, returnValue: Expression,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
suspended: Boolean = false, suspended: Boolean = false,
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Expression ) extends Expression
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -100,9 +99,9 @@ object Expression {
returnValue, returnValue,
location, location,
suspended, suspended,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -133,8 +132,7 @@ object Expression {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -190,18 +188,27 @@ object Expression {
* @param expression the expression being bound to `name` * @param expression the expression being bound to `name`
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Binding( sealed case class Binding(
name: Name, name: Name,
expression: Expression, expression: Expression,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Expression ) extends Expression
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Create a [[Binding]] object from a [[Function.Binding]].
*
* @param ir the function binding
* @param lambda the body of the function
*/
def this(ir: Function.Binding, lambda: Function.Lambda) = {
this(ir.name, lambda, ir.location, ir.passData)
this.diagnostics = ir.diagnostics
}
/** Creates a copy of `this`. /** Creates a copy of `this`.
* *
* @param name the name being bound to * @param name the name being bound to
@ -228,7 +235,8 @@ object Expression {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Binding(name, expression, location, passData, diagnostics) val res = Binding(name, expression, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -257,8 +265,7 @@ object Expression {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -45,17 +45,16 @@ object Function {
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param canBeTCO whether or not the function can be tail-call optimised * @param canBeTCO whether or not the function can be tail-call optimised
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Lambda( sealed case class Lambda(
override val arguments: List[DefinitionArgument], override val arguments: List[DefinitionArgument],
bodyReference: Persistance.Reference[Expression], bodyReference: Persistance.Reference[Expression],
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
override val canBeTCO: Boolean, override val canBeTCO: Boolean,
passData: MetadataStorage, passData: MetadataStorage
diagnostics: DiagnosticStorage
) extends Function ) extends Function
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
def this( def this(
@ -63,19 +62,33 @@ object Function {
body: Expression, body: Expression,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
canBeTCO: Boolean = true, canBeTCO: Boolean = true,
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = new DiagnosticStorage()
) = { ) = {
this( this(
arguments, arguments,
Persistance.Reference.of(body, true), Persistance.Reference.of(body, true),
location, location,
canBeTCO, canBeTCO,
passData, passData
diagnostics
) )
} }
def this(
ir: expression.Case.Expr,
arguments: List[DefinitionArgument],
body: Expression,
location: Option[IdentifiedLocation]
) = {
this(
arguments,
Persistance.Reference.of(body, true),
location,
true,
ir.passData
)
diagnostics = ir.diagnostics
}
override lazy val body: Expression = bodyReference.get(classOf[Expression]) override lazy val body: Expression = bodyReference.get(classOf[Expression])
override val isPrivate: Boolean = false override val isPrivate: Boolean = false
@ -115,9 +128,9 @@ object Function {
Persistance.Reference.of(body, false), Persistance.Reference.of(body, false),
location, location,
canBeTCO, canBeTCO,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -148,8 +161,7 @@ object Function {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -195,6 +207,7 @@ object Function {
} }
object Lambda { object Lambda {
def unapply(l: Lambda): Some[ def unapply(l: Lambda): Some[
( (
List[DefinitionArgument], List[DefinitionArgument],
@ -226,7 +239,6 @@ object Function {
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param canBeTCO whether or not the function can be tail-call optimised * @param canBeTCO whether or not the function can be tail-call optimised
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics the compiler diagnostics for this node
*/ */
sealed case class Binding( sealed case class Binding(
name: Name, name: Name,
@ -235,10 +247,10 @@ object Function {
override val isPrivate: Boolean, override val isPrivate: Boolean,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
override val canBeTCO: Boolean = true, override val canBeTCO: Boolean = true,
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Function ) extends Function
with IRKind.Sugar with IRKind.Sugar
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -284,9 +296,9 @@ object Function {
isPrivate, isPrivate,
location, location,
canBeTCO, canBeTCO,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -323,8 +335,7 @@ object Function {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -0,0 +1,28 @@
package org.enso.compiler.core.ir
import org.enso.compiler.core.IR
trait LazyDiagnosticStorage { self: IR =>
private[this] var _diagnostics: DiagnosticStorage = _
protected def diagnostics_=(diagnostics: DiagnosticStorage): Unit = {
assert(_diagnostics eq null)
_diagnostics = diagnostics
}
override def diagnostics: DiagnosticStorage = {
_diagnostics
}
def diagnosticsCopy: DiagnosticStorage = {
if (_diagnostics eq null) _diagnostics else _diagnostics.copy
}
override def getDiagnostics: DiagnosticStorage = {
if (_diagnostics eq null) {
_diagnostics = new DiagnosticStorage()
}
_diagnostics
}
}

View File

@ -6,7 +6,8 @@ import org.enso.compiler.core.{IR, Identifier}
import java.util.UUID import java.util.UUID
trait LazyId { self: IR => trait LazyId { self: IR =>
private[this] var _id: UUID @Identifier = null
private[this] var _id: UUID @Identifier = _
protected def id: UUID @Identifier = { protected def id: UUID @Identifier = {
_id _id
@ -19,7 +20,7 @@ trait LazyId { self: IR =>
_id _id
} }
def id_=(id: UUID @Identifier) = { def id_=(id: UUID @Identifier): Unit = {
assert(_id == null) assert(_id == null)
_id = id _id = id
} }

View File

@ -33,15 +33,14 @@ object Literal {
* @param value the textual representation of the numeric literal * @param value the textual representation of the numeric literal
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Number( sealed case class Number(
base: Option[String], base: Option[String],
value: String, value: String,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Literal ) extends Literal
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -70,7 +69,8 @@ object Literal {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Number(base, value, location, passData, diagnostics) val res = Number(base, value, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -87,8 +87,7 @@ object Literal {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -170,14 +169,13 @@ object Literal {
* @param text the text of the literal * @param text the text of the literal
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Text( sealed case class Text(
text: String, text: String,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Literal ) extends Literal
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -203,7 +201,8 @@ object Literal {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Text(text, location, passData, diagnostics) val res = Text(text, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -220,8 +219,7 @@ object Literal {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -17,7 +17,6 @@ import java.util.UUID
* @param isPrivate whether or not this module is private (project-private) * @param isPrivate whether or not this module is private (project-private)
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
final case class Module( final case class Module(
imports: List[Import], imports: List[Import],
@ -25,12 +24,35 @@ final case class Module(
bindings: List[Definition], bindings: List[Definition],
isPrivate: Boolean, isPrivate: Boolean,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends IR ) extends IR
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Create a module.
*
* @param imports the import statements that bring other modules into scope
* @param exports the export statements for this module
* @param bindings the top-level bindings for this module
* @param isPrivate whether or not this module is private (project-private)
* @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node
* @param diagnostics the compiler diagnostics
*/
def this(
imports: List[Import],
exports: List[Export],
bindings: List[Definition],
isPrivate: Boolean,
location: Option[IdentifiedLocation],
passData: MetadataStorage,
diagnostics: DiagnosticStorage
) = {
this(imports, exports, bindings, isPrivate, location, passData)
this.diagnostics = diagnostics
}
/** Creates a copy of `this`. /** Creates a copy of `this`.
* *
* @param imports the import statements that bring other modules into scope * @param imports the import statements that bring other modules into scope
@ -69,9 +91,9 @@ final case class Module(
bindings, bindings,
isPrivate, isPrivate,
location, location,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -104,8 +126,7 @@ final case class Module(
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -41,16 +41,15 @@ object Name {
* @param methodName the method on `typeName` * @param methodName the method on `typeName`
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
final case class MethodReference( final case class MethodReference(
typePointer: Option[Name], typePointer: Option[Name],
methodName: Name, methodName: Name,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Name ) extends Name
with IRKind.Sugar with IRKind.Sugar
with LazyDiagnosticStorage
with LazyId { with LazyId {
override val name: String = showCode() override val name: String = showCode()
@ -86,9 +85,9 @@ object Name {
typePointer, typePointer,
methodName, methodName,
location, location,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -119,8 +118,7 @@ object Name {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -171,9 +169,7 @@ object Name {
*/ */
def isSameReferenceAs(that: MethodReference): Boolean = { def isSameReferenceAs(that: MethodReference): Boolean = {
val sameTypePointer = typePointer val sameTypePointer = typePointer
.map(thisTp => .map(thisTp => that.typePointer.exists(_.name == thisTp.name))
that.typePointer.map(_.name == thisTp.name).getOrElse(false)
)
.getOrElse(that.typePointer.isEmpty) .getOrElse(that.typePointer.isEmpty)
sameTypePointer && (methodName.name == that.methodName.name) sameTypePointer && (methodName.name == that.methodName.name)
} }
@ -211,16 +207,15 @@ object Name {
* @param parts the segments of the name * @param parts the segments of the name
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
* @return a copy of `this`, updated with the specified values * @return a copy of `this`, updated with the specified values
*/ */
final case class Qualified( final case class Qualified(
parts: List[Name], parts: List[Name],
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Name ) extends Name
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
override val name: String = parts.map(_.name).mkString(".") override val name: String = parts.map(_.name).mkString(".")
@ -255,13 +250,8 @@ object Name {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = val res = Qualified(parts, location, passData)
Qualified( res.diagnostics = diagnostics
parts,
location,
passData,
diagnostics
)
res.id = id res.id = id
res res
} else this } else this
@ -286,8 +276,7 @@ object Name {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -302,14 +291,13 @@ object Name {
* *
* @param location the source location that the node corresponds to. * @param location the source location that the node corresponds to.
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Blank( sealed case class Blank(
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Name ) extends Name
with IRKind.Sugar with IRKind.Sugar
with LazyDiagnosticStorage
with LazyId { with LazyId {
override val name: String = "_" override val name: String = "_"
@ -333,7 +321,8 @@ object Name {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Blank(location, passData, diagnostics) val res = Blank(location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -350,8 +339,7 @@ object Name {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -386,10 +374,10 @@ object Name {
sealed case class Special( sealed case class Special(
specialName: Special.Ident, specialName: Special.Ident,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Name ) extends Name
with IRKind.Sugar with IRKind.Sugar
with LazyDiagnosticStorage
with LazyId { with LazyId {
override val name: String = s"<special::${specialName}>" override val name: String = s"<special::${specialName}>"
@ -415,7 +403,8 @@ object Name {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Special(specialName, location, passData, diagnostics) val res = Special(specialName, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -431,8 +420,7 @@ object Name {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -481,16 +469,15 @@ object Name {
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param originalName the name which this literal has replaced, if any * @param originalName the name which this literal has replaced, if any
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Literal( sealed case class Literal(
override val name: String, override val name: String,
override val isMethod: Boolean, override val isMethod: Boolean,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
originalName: Option[Name] = None, originalName: Option[Name] = None,
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Name ) extends Name
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -522,8 +509,8 @@ object Name {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = val res = Literal(name, isMethod, location, originalName, passData)
Literal(name, isMethod, location, originalName, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -540,8 +527,7 @@ object Name {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -599,15 +585,14 @@ object Name {
* @param name the annotation text of the name * @param name the annotation text of the name
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class BuiltinAnnotation( sealed case class BuiltinAnnotation(
override val name: String, override val name: String,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Annotation ) extends Annotation
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -633,7 +618,8 @@ object Name {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = BuiltinAnnotation(name, location, passData, diagnostics) val res = BuiltinAnnotation(name, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -650,8 +636,7 @@ object Name {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -692,15 +677,14 @@ object Name {
* @param expression the annotation expression * @param expression the annotation expression
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class GenericAnnotation( sealed case class GenericAnnotation(
override val name: String, override val name: String,
expression: Expression, expression: Expression,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Annotation ) extends Annotation
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -730,7 +714,8 @@ object Name {
|| id != this.id || id != this.id
) { ) {
val res = val res =
GenericAnnotation(name, expression, location, passData, diagnostics) GenericAnnotation(name, expression, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -747,8 +732,7 @@ object Name {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -788,16 +772,34 @@ object Name {
/** A representation of the name `self`, used to refer to the current type. /** A representation of the name `self`, used to refer to the current type.
* *
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param synthetic the flag indicating that the name was generated
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Self( sealed case class Self(
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
synthetic: Boolean = false, synthetic: Boolean = false,
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Name ) extends Name
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Create a [[Self]] object.
*
* @param location the source location that the node corresponds to
* @param synthetic the flag indicating that the name was generated
* @param passData the pass metadata associated with this node
* @param diagnostics the compiler diagnostics
*/
def this(
location: Option[IdentifiedLocation],
synthetic: Boolean,
passData: MetadataStorage,
diagnostics: DiagnosticStorage
) = {
this(location, synthetic, passData)
this.diagnostics = diagnostics
}
override val name: String = ConstantsNames.SELF_ARGUMENT override val name: String = ConstantsNames.SELF_ARGUMENT
/** Creates a copy of `self`. /** Creates a copy of `self`.
@ -822,7 +824,8 @@ object Name {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Self(location, synthetic, passData, diagnostics) val res = Self(location, synthetic, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -839,8 +842,7 @@ object Name {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -876,14 +878,29 @@ object Name {
* *
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class SelfType( sealed case class SelfType(
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Name ) extends Name
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Create a [[SelfType]] object.
*
* @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node
* @param diagnostics the compiler diagnostics
*/
def this(
location: Option[IdentifiedLocation],
passData: MetadataStorage,
diagnostics: DiagnosticStorage
) = {
this(location, passData)
this.diagnostics = diagnostics
}
override val name: String = ConstantsNames.SELF_TYPE_ARGUMENT override val name: String = ConstantsNames.SELF_TYPE_ARGUMENT
/** Creates a copy of `Self`. /** Creates a copy of `Self`.
@ -906,7 +923,8 @@ object Name {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = SelfType(location, passData, diagnostics) val res = SelfType(location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -923,8 +941,7 @@ object Name {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -38,14 +38,13 @@ object Pattern {
* @param name the name that constitutes the pattern * @param name the name that constitutes the pattern
* @param location the source location for this IR node * @param location the source location for this IR node
* @param passData any pass metadata associated with the node * @param passData any pass metadata associated with the node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Name( sealed case class Name(
name: IRName, name: IRName,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Pattern ) extends Pattern
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -71,7 +70,8 @@ object Pattern {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Name(name, location, passData, diagnostics) val res = Name(name, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -94,8 +94,7 @@ object Pattern {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -138,15 +137,14 @@ object Pattern {
* @param fields the asserted fields of the constructor * @param fields the asserted fields of the constructor
* @param location the source location for this IR node * @param location the source location for this IR node
* @param passData any pass metadata associated with this node * @param passData any pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Constructor( sealed case class Constructor(
constructor: IRName, constructor: IRName,
fields: List[Pattern], fields: List[Pattern],
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Pattern ) extends Pattern
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -175,8 +173,8 @@ object Pattern {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = val res = Constructor(constructor, fields, location, passData)
Constructor(constructor, fields, location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -207,8 +205,7 @@ object Pattern {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -238,7 +235,7 @@ object Pattern {
* *
* @return the fields from `this` * @return the fields from `this`
*/ */
def fieldsAsNamed: List[Option[Pattern.Name]] = { private def fieldsAsNamed: List[Option[Pattern.Name]] = {
fields.map { fields.map {
case f: Name => Some(f) case f: Name => Some(f)
case _ => None case _ => None
@ -299,14 +296,13 @@ object Pattern {
* @param literal the literal representing the pattern * @param literal the literal representing the pattern
* @param location the source location for this IR node * @param location the source location for this IR node
* @param passData any pass metadata associated with the node * @param passData any pass metadata associated with the node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Literal( sealed case class Literal(
literal: IRLiteral, literal: IRLiteral,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Pattern ) extends Pattern
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -332,7 +328,8 @@ object Pattern {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Literal(literal, location, passData, diagnostics) val res = Literal(literal, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -355,8 +352,7 @@ object Pattern {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -395,21 +391,20 @@ object Pattern {
* A type pattern matches on types. Type pattern is composed of two parts: * A type pattern matches on types. Type pattern is composed of two parts:
* - a single identifier (e.g. `a` or `_`) * - a single identifier (e.g. `a` or `_`)
* - a (potentially fully qualified) type name * - a (potentially fully qualified) type name
* E.g., `a : Foo -> ...` or `_ : Bar -> ...`` * E.g., `a : Foo -> ...` or `_ : Bar -> ...`
* *
* @param name the name of the bound variable, or wildcard * @param name the name of the bound variable, or wildcard
* @param tpe the name of the type to match on * @param tpe the name of the type to match on
* @param location the source location for this IR node * @param location the source location for this IR node
* @param passData any pass metadata associated with the node * @param passData any pass metadata associated with the node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Type( sealed case class Type(
name: IRName, name: IRName,
tpe: IRName, tpe: IRName,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Pattern ) extends Pattern
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -438,7 +433,8 @@ object Pattern {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Type(name, tpe, location, passData, diagnostics) val res = Type(name, tpe, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -467,8 +463,7 @@ object Pattern {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -514,14 +509,13 @@ object Pattern {
* @param doc the documentation entity * @param doc the documentation entity
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
final case class Documentation( final case class Documentation(
doc: String, doc: String,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Pattern ) extends Pattern
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** @inheritdoc */ /** @inheritdoc */
@ -559,7 +553,8 @@ object Pattern {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Documentation(doc, location, passData, diagnostics) val res = Documentation(doc, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -577,8 +572,7 @@ object Pattern {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -37,9 +37,9 @@ object Type {
args: List[Expression], args: List[Expression],
result: Expression, result: Expression,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Type ) extends Type
with LazyDiagnosticStorage
with LazyId { with LazyId {
def copy( def copy(
@ -58,7 +58,8 @@ object Type {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Function(args, result, location, passData, diagnostics) val res = Function(args, result, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -89,8 +90,7 @@ object Type {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -133,18 +133,17 @@ object Type {
* @param comment a comment that may be used to add context to the type error * @param comment a comment that may be used to add context to the type error
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Ascription( sealed case class Ascription(
typed: Expression, typed: Expression,
signature: Expression, signature: Expression,
comment: Option[String], comment: Option[String],
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Type ) extends Type
with module.scope.Definition with module.scope.Definition
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -176,8 +175,8 @@ object Type {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = val res = Ascription(typed, signature, comment, location, passData)
Ascription(typed, signature, comment, location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -206,8 +205,7 @@ object Type {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -255,16 +253,15 @@ object Type {
* @param context the context being ascribed to `typed` * @param context the context being ascribed to `typed`
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Context( sealed case class Context(
typed: Expression, typed: Expression,
context: Expression, context: Expression,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Type ) extends Type
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates ac opy of `this`. /** Creates ac opy of `this`.
@ -293,7 +290,8 @@ object Type {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Context(typed, context, location, passData, diagnostics) val res = Context(typed, context, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -322,8 +320,7 @@ object Type {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -368,16 +365,15 @@ object Type {
* @param error the error being ascribed * @param error the error being ascribed
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Error( sealed case class Error(
typed: Expression, typed: Expression,
error: Expression, error: Expression,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Type ) extends Type
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -406,7 +402,8 @@ object Type {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Error(typed, error, location, passData, diagnostics) val res = Error(typed, error, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -435,8 +432,7 @@ object Type {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -20,19 +20,46 @@ object Application {
* argument defaults in `function` suspended * argument defaults in `function` suspended
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Prefix( sealed case class Prefix(
function: Expression, function: Expression,
arguments: List[CallArgument], arguments: List[CallArgument],
hasDefaultsSuspended: Boolean, hasDefaultsSuspended: Boolean,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Application ) extends Application
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Create a prefix application.
*
* @param function the function being called
* @param arguments the arguments to the function being called
* @param hasDefaultsSuspended whether the function application has any
* argument defaults in `function` suspended
* @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node
* @param diagnostics the compiler diagnostics
*/
def this(
function: Expression,
arguments: List[CallArgument],
hasDefaultsSuspended: Boolean,
location: Option[IdentifiedLocation],
passData: MetadataStorage,
diagnostics: DiagnosticStorage
) = {
this(
function,
arguments,
hasDefaultsSuspended,
location,
passData
)
this.diagnostics = diagnostics
}
/** Creates a copy of `this`. /** Creates a copy of `this`.
* *
* @param function the function being called * @param function the function being called
@ -69,9 +96,9 @@ object Application {
arguments, arguments,
hasDefaultsSuspended, hasDefaultsSuspended,
location, location,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -102,8 +129,7 @@ object Application {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -148,15 +174,14 @@ object Application {
* @param target the expression being forced * @param target the expression being forced
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Force( sealed case class Force(
target: Expression, target: Expression,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Application ) extends Application
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -182,7 +207,8 @@ object Application {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Force(target, location, passData, diagnostics) val res = Force(target, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -205,8 +231,7 @@ object Application {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -268,15 +293,14 @@ object Application {
* @param expression the expression of the typeset body * @param expression the expression of the typeset body
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Typeset( sealed case class Typeset(
expression: Option[Expression], expression: Option[Expression],
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Literal ) extends Literal
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
override def mapExpressions( override def mapExpressions(
@ -307,8 +331,8 @@ object Application {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Typeset(expression, location, passData)
val res = Typeset(expression, location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -333,8 +357,7 @@ object Application {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -373,15 +396,14 @@ object Application {
* @param items the items being put in the vector * @param items the items being put in the vector
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Sequence( sealed case class Sequence(
items: List[Expression], items: List[Expression],
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Literal ) extends Literal
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
override def mapExpressions( override def mapExpressions(
@ -412,8 +434,8 @@ object Application {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Sequence(items, location, passData)
val res = Sequence(items, location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -438,8 +460,7 @@ object Application {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -36,29 +36,18 @@ object Case {
* @param isNested if true, the flag indicates that the expr represents a desugared nested case * @param isNested if true, the flag indicates that the expr represents a desugared nested case
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Expr( sealed case class Expr(
scrutinee: Expression, scrutinee: Expression,
branches: Seq[Branch], branches: Seq[Branch],
isNested: Boolean, isNested: Boolean,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Case ) extends Case
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
def this(
scrutinee: Expression,
branches: Seq[Branch],
location: Option[IdentifiedLocation],
passData: MetadataStorage,
diagnostics: DiagnosticStorage
) = {
this(scrutinee, branches, false, location, passData, diagnostics)
}
/** Creates a copy of `this`. /** Creates a copy of `this`.
* *
* @param scrutinee the expression whose value is being matched on * @param scrutinee the expression whose value is being matched on
@ -88,8 +77,8 @@ object Case {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = val res = Expr(scrutinee, branches, isNested, location, passData)
Expr(scrutinee, branches, isNested, location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -121,8 +110,7 @@ object Case {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -169,29 +157,6 @@ object Case {
} }
} }
object Expr {
def apply(
scrutinee: Expression,
branches: Seq[Branch],
location: Option[IdentifiedLocation]
): Expr =
apply(
scrutinee,
branches,
location,
new MetadataStorage(),
new DiagnosticStorage()
)
def apply(
scrutinee: Expression,
branches: Seq[Branch],
location: Option[IdentifiedLocation],
passData: MetadataStorage,
diagnostics: DiagnosticStorage
): Expr = new Expr(scrutinee, branches, location, passData, diagnostics)
}
/** A branch in a case statement. /** A branch in a case statement.
* *
* @param pattern the pattern that attempts to match against the scrutinee * @param pattern the pattern that attempts to match against the scrutinee
@ -199,29 +164,18 @@ object Case {
* @param terminalBranch the flag indicating whether the branch represents the final pattern to be checked * @param terminalBranch the flag indicating whether the branch represents the final pattern to be checked
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Branch( sealed case class Branch(
pattern: Pattern, pattern: Pattern,
expression: Expression, expression: Expression,
terminalBranch: Boolean, terminalBranch: Boolean,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Case ) extends Case
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
def this(
pattern: Pattern,
expression: Expression,
location: Option[IdentifiedLocation],
passData: MetadataStorage,
diagnostics: DiagnosticStorage
) = {
this(pattern, expression, true, location, passData, diagnostics)
}
/** Creates a copy of `this`. /** Creates a copy of `this`.
* *
* @param pattern the pattern that attempts to match against the scrutinee * @param pattern the pattern that attempts to match against the scrutinee
@ -250,15 +204,14 @@ object Case {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Branch( val res = Branch(
pattern, pattern,
expression, expression,
terminalBranch, terminalBranch,
location, location,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -288,8 +241,7 @@ object Case {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -332,28 +284,4 @@ object Case {
s"${pattern.showCode(indent)} -> $bodyStr" s"${pattern.showCode(indent)} -> $bodyStr"
} }
} }
object Branch {
def apply(
pattern: Pattern,
expression: Expression,
location: Option[IdentifiedLocation]
): Branch =
apply(
pattern,
expression,
location,
new MetadataStorage(),
new DiagnosticStorage()
)
def apply(
pattern: Pattern,
expression: Expression,
location: Option[IdentifiedLocation],
passData: MetadataStorage,
diagnostics: DiagnosticStorage
): Branch =
new Branch(pattern, expression, location, passData, diagnostics)
}
} }

View File

@ -33,15 +33,14 @@ object Comment {
* @param doc the documentation entity * @param doc the documentation entity
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Documentation( sealed case class Documentation(
doc: String, doc: String,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Comment ) extends Comment
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -67,8 +66,8 @@ object Comment {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Documentation(doc, location, passData)
val res = Documentation(doc, location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -85,8 +84,7 @@ object Comment {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -33,15 +33,14 @@ object Error {
* *
* @param ir the IR that is invalid * @param ir the IR that is invalid
* @param passData any annotations from compiler passes * @param passData any annotations from compiler passes
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class InvalidIR( sealed case class InvalidIR(
ir: IR, ir: IR,
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Error ) extends Error
with Diagnostic.Kind.Static with Diagnostic.Kind.Static
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -64,8 +63,8 @@ object Error {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = InvalidIR(ir, passData)
val res = InvalidIR(ir, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -87,8 +86,7 @@ object Error {
), ),
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -37,16 +37,15 @@ object Foreign {
* @param code the code written in `lang` * @param code the code written in `lang`
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Definition( sealed case class Definition(
lang: String, lang: String,
code: String, code: String,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Foreign ) extends Foreign
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -75,8 +74,8 @@ object Foreign {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Definition(lang, code, location, passData)
val res = Definition(lang, code, location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -93,8 +92,7 @@ object Foreign {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -35,17 +35,16 @@ object Operator {
* @param right the right operand to `operator` * @param right the right operand to `operator`
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Binary( sealed case class Binary(
left: CallArgument, left: CallArgument,
operator: Name, operator: Name,
right: CallArgument, right: CallArgument,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Operator ) extends Operator
with IRKind.Sugar with IRKind.Sugar
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -77,9 +76,8 @@ object Operator {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Binary(left, operator, right, location, passData)
val res = res.diagnostics = diagnostics
Binary(left, operator, right, location, passData, diagnostics)
res.id = id res.id = id
res res
} else this } else this
@ -114,8 +112,7 @@ object Operator {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -34,16 +34,15 @@ object Section {
* @param operator the operator * @param operator the operator
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Left( sealed case class Left(
arg: CallArgument, arg: CallArgument,
operator: Name, operator: Name,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Section ) extends Section
with IRKind.Sugar with IRKind.Sugar
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -72,8 +71,8 @@ object Section {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Left(arg, operator, location, passData)
val res = Left(arg, operator, location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -103,8 +102,7 @@ object Section {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -147,15 +145,14 @@ object Section {
* @param operator the operator * @param operator the operator
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Sides( sealed case class Sides(
operator: Name, operator: Name,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Section ) extends Section
with IRKind.Sugar with IRKind.Sugar
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -181,7 +178,8 @@ object Section {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Sides(operator, location, passData, diagnostics) val res = Sides(operator, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -205,8 +203,7 @@ object Section {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -247,16 +244,15 @@ object Section {
* @param arg the argument (on the right of the operator) * @param arg the argument (on the right of the operator)
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Right( sealed case class Right(
operator: Name, operator: Name,
arg: CallArgument, arg: CallArgument,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Section ) extends Section
with IRKind.Sugar with IRKind.Sugar
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -285,8 +281,8 @@ object Section {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Right(operator, arg, location, passData)
val res = Right(operator, arg, location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -316,8 +312,7 @@ object Section {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -11,18 +11,18 @@ import java.util.UUID
* @param storedIr the IR that contains the error * @param storedIr the IR that contains the error
* @param reason the explanation for the error * @param reason the explanation for the error
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler dianostics for this node
*/ */
sealed case class Conversion( sealed case class Conversion(
storedIr: IR, storedIr: IR,
reason: Conversion.Reason, reason: Conversion.Reason,
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Error ) extends Error
with Diagnostic.Kind.Interactive with Diagnostic.Kind.Interactive
with IRKind.Primitive with IRKind.Primitive
with Name with Name
with LazyDiagnosticStorage
with LazyId { with LazyId {
override val name: String = "conversion_error" override val name: String = "conversion_error"
override def mapExpressions( override def mapExpressions(
@ -59,8 +59,8 @@ sealed case class Conversion(
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Conversion(storedIr, reason, passData)
val res = Conversion(storedIr, reason, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -82,8 +82,7 @@ sealed case class Conversion(
), ),
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
} }

View File

@ -13,20 +13,36 @@ import scala.annotation.unused
* @param ir the original statement * @param ir the original statement
* @param reason the reason it's erroneous * @param reason the reason it's erroneous
* @param passData the pass data * @param passData the pass data
* @param diagnostics the attached diagnostics
*/ */
sealed case class ImportExport( sealed case class ImportExport(
ir: IR, ir: IR,
reason: ImportExport.Reason, reason: ImportExport.Reason,
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Error ) extends Error
with Diagnostic.Kind.Interactive with Diagnostic.Kind.Interactive
with org.enso.compiler.core.ir.module.scope.Import with org.enso.compiler.core.ir.module.scope.Import
with org.enso.compiler.core.ir.module.scope.Export with org.enso.compiler.core.ir.module.scope.Export
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Create an erroneous import or export statement.
*
* @param ir the original statement
* @param reason the reason it's erroneous
* @param passData the pass data
* @param diagnostics the attached diagnostics
*/
def this(
ir: IR,
reason: ImportExport.Reason,
passData: MetadataStorage,
diagnostics: DiagnosticStorage
) = {
this(ir, reason, passData)
this.diagnostics = diagnostics
}
/** Creates a copy of `this`. /** Creates a copy of `this`.
* *
* @param ir the original IR * @param ir the original IR
@ -50,8 +66,8 @@ sealed case class ImportExport(
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = ImportExport(ir, reason, passData)
val res = ImportExport(ir, reason, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -67,8 +83,7 @@ sealed case class ImportExport(
copy( copy(
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -115,8 +130,7 @@ sealed case class ImportExport(
object ImportExport { object ImportExport {
/** A reason for a statement being erroneous. /** A reason for a statement being erroneous. */
*/
sealed trait Reason { sealed trait Reason {
/** @param source Location of the original import/export IR. /** @param source Location of the original import/export IR.

View File

@ -11,18 +11,35 @@ import java.util.UUID
* @param originalPattern pattern that resulted in the error * @param originalPattern pattern that resulted in the error
* @param reason the cause of this error * @param reason the cause of this error
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
* @return a copy of `this`, updated with the specified values * @return a copy of `this`, updated with the specified values
*/ */
sealed case class Pattern( sealed case class Pattern(
originalPattern: org.enso.compiler.core.ir.Pattern, originalPattern: org.enso.compiler.core.ir.Pattern,
reason: Pattern.Reason, reason: Pattern.Reason,
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Error ) extends Error
with Diagnostic.Kind.Interactive with Diagnostic.Kind.Interactive
with org.enso.compiler.core.ir.Pattern with org.enso.compiler.core.ir.Pattern
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Create a [[Pattern]] object.
*
* @param originalPattern pattern that resulted in the error
* @param reason the cause of this error
* @param passData the pass metadata associated with this node
* @param diagnostics the compiler diagnostics
*/
def this(
originalPattern: org.enso.compiler.core.ir.Pattern,
reason: Pattern.Reason,
passData: MetadataStorage,
diagnostics: DiagnosticStorage
) = {
this(originalPattern, reason, passData)
this.diagnostics = diagnostics
}
override def mapExpressions( override def mapExpressions(
fn: java.util.function.Function[Expression, Expression] fn: java.util.function.Function[Expression, Expression]
): Pattern = ): Pattern =
@ -54,8 +71,8 @@ sealed case class Pattern(
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Pattern(originalPattern, reason, passData)
val res = Pattern(originalPattern, reason, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -78,12 +95,11 @@ sealed case class Pattern(
), ),
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
override def message(source: (IdentifiedLocation => String)): String = override def message(source: IdentifiedLocation => String): String =
reason.explain reason.explain
override def diagnosticKeys(): Array[Any] = Array(reason) override def diagnosticKeys(): Array[Any] = Array(reason)
@ -99,8 +115,7 @@ sealed case class Pattern(
object Pattern { object Pattern {
/** A representation of the reason the pattern is erroneous. /** A representation of the reason the pattern is erroneous. */
*/
sealed trait Reason { sealed trait Reason {
/** Provides a human-readable explanation of the error. /** Provides a human-readable explanation of the error.

View File

@ -36,15 +36,14 @@ object Redefined {
* *
* @param location the source location of the error * @param location the source location of the error
* @param passData the pass metadata for this node * @param passData the pass metadata for this node
* @param diagnostics compiler diagnostics associated with the node
*/ */
sealed case class SelfArg( sealed case class SelfArg(
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Redefined ) extends Redefined
with Diagnostic.Kind.Interactive with Diagnostic.Kind.Interactive
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `self`. /** Creates a copy of `self`.
@ -67,8 +66,8 @@ object Redefined {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = SelfArg(location, passData)
val res = SelfArg(location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -85,8 +84,7 @@ object Redefined {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -124,18 +122,17 @@ object Redefined {
* @param location the location in the source to which this error * @param location the location in the source to which this error
* corresponds * corresponds
* @param passData the pass metadata for the error * @param passData the pass metadata for the error
* @param diagnostics any diagnostics associated with this error.
*/ */
sealed case class Conversion( sealed case class Conversion(
targetType: Option[Name], targetType: Option[Name],
sourceType: Name, sourceType: Name,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Redefined ) extends Redefined
with Diagnostic.Kind.Interactive with Diagnostic.Kind.Interactive
with module.scope.Definition with module.scope.Definition
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -166,9 +163,8 @@ object Redefined {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Conversion(targetType, sourceType, location, passData)
val res = res.diagnostics = diagnostics
Conversion(targetType, sourceType, location, passData, diagnostics)
res.id = id res.id = id
res res
} else this } else this
@ -200,8 +196,7 @@ object Redefined {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -256,21 +251,19 @@ object Redefined {
* *
* @param typeName the name of the type the method was being redefined on * @param typeName the name of the type the method was being redefined on
* @param methodName the method name being redefined on `atomName` * @param methodName the method name being redefined on `atomName`
* @param location the location in the source to which this error * @param location the location in the source to which this error corresponds
* corresponds
* @param passData the pass metadata for the error * @param passData the pass metadata for the error
* @param diagnostics any diagnostics associated with this error.
*/ */
sealed case class Method( sealed case class Method(
typeName: Option[Name], typeName: Option[Name],
methodName: Name, methodName: Name,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Redefined ) extends Redefined
with Diagnostic.Kind.Interactive with Diagnostic.Kind.Interactive
with module.scope.Definition with module.scope.Definition
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -300,9 +293,8 @@ object Redefined {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Method(typeName, methodName, location, passData)
val res = res.diagnostics = diagnostics
Method(typeName, methodName, location, passData, diagnostics)
res.id = id res.id = id
res res
} else this } else this
@ -334,8 +326,7 @@ object Redefined {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -390,21 +381,19 @@ object Redefined {
* *
* @param atomName the name of the atom that clashes with the method * @param atomName the name of the atom that clashes with the method
* @param methodName the method name being redefined in the module * @param methodName the method name being redefined in the module
* @param location the location in the source to which this error * @param location the location in the source to which this error corresponds
* corresponds
* @param passData the pass metadata for the error * @param passData the pass metadata for the error
* @param diagnostics any diagnostics associated with this error.
*/ */
sealed case class MethodClashWithAtom( sealed case class MethodClashWithAtom(
atomName: Name, atomName: Name,
methodName: Name, methodName: Name,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Redefined ) extends Redefined
with Diagnostic.Kind.Interactive with Diagnostic.Kind.Interactive
with module.scope.Definition with module.scope.Definition
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -434,14 +423,13 @@ object Redefined {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = MethodClashWithAtom( val res = MethodClashWithAtom(
atomName, atomName,
methodName, methodName,
location, location,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -471,8 +459,7 @@ object Redefined {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -520,20 +507,18 @@ object Redefined {
/** An error representing the redefinition of an atom in a given module. /** An error representing the redefinition of an atom in a given module.
* *
* @param typeName the name of the atom being redefined * @param typeName the name of the atom being redefined
* @param location the location in the source to which this error * @param location the location in the source to which this error corresponds
* corresponds
* @param passData the pass metadata for the error * @param passData the pass metadata for the error
* @param diagnostics any diagnostics associated with this error.
*/ */
sealed case class Type( sealed case class Type(
typeName: Name, typeName: Name,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Redefined ) extends Redefined
with Diagnostic.Kind.Interactive with Diagnostic.Kind.Interactive
with module.scope.Definition with module.scope.Definition
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -561,9 +546,8 @@ object Redefined {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Type(typeName, location, passData)
val res = res.diagnostics = diagnostics
Type(typeName, location, passData, diagnostics)
res.id = id res.id = id
res res
} else this } else this
@ -586,8 +570,7 @@ object Redefined {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -633,17 +616,16 @@ object Redefined {
* @param location the location in the source to which this error * @param location the location in the source to which this error
* corresponds * corresponds
* @param passData the pass metadata for the error * @param passData the pass metadata for the error
* @param diagnostics any diagnostics associated with this error.
*/ */
sealed case class Arg( sealed case class Arg(
name: Name, name: Name,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Redefined ) extends Redefined
with Diagnostic.Kind.Interactive with Diagnostic.Kind.Interactive
with module.scope.Definition with module.scope.Definition
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -671,9 +653,8 @@ object Redefined {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Arg(name, location, passData)
val res = res.diagnostics = diagnostics
Arg(name, location, passData, diagnostics)
res.id = id res.id = id
res res
} else this } else this
@ -696,8 +677,7 @@ object Redefined {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -744,15 +724,14 @@ object Redefined {
* *
* @param invalidBinding the invalid binding * @param invalidBinding the invalid binding
* @param passData the pass metadata for the error * @param passData the pass metadata for the error
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Binding( sealed case class Binding(
invalidBinding: Expression.Binding, invalidBinding: Expression.Binding,
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Redefined ) extends Redefined
with Diagnostic.Kind.Interactive with Diagnostic.Kind.Interactive
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -775,8 +754,8 @@ object Redefined {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Binding(invalidBinding, passData)
val res = Binding(invalidBinding, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -799,8 +778,7 @@ object Redefined {
), ),
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -11,18 +11,35 @@ import java.util.UUID
* @param originalName the original name that could not be resolved * @param originalName the original name that could not be resolved
* @param reason the cause of this error * @param reason the cause of this error
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Resolution( sealed case class Resolution(
originalName: Name, originalName: Name,
reason: Resolution.Reason, reason: Resolution.Reason,
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Error ) extends Error
with Diagnostic.Kind.Interactive with Diagnostic.Kind.Interactive
with IRKind.Primitive with IRKind.Primitive
with Name with Name
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Create a [[Resolution]] object.
*
* @param originalName the original name that could not be resolved
* @param reason the cause of this error
* @param passData the pass metadata associated with this node
* @param diagnostics the compiler diagnostics
*/
def this(
originalName: Name,
reason: Resolution.Reason,
passData: MetadataStorage,
diagnostics: DiagnosticStorage
) = {
this(originalName, reason, passData)
this.diagnostics = diagnostics
}
override val name: String = originalName.name override val name: String = originalName.name
override def mapExpressions( override def mapExpressions(
@ -58,8 +75,8 @@ sealed case class Resolution(
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Resolution(originalName, reason, passData)
val res = Resolution(originalName, reason, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -82,8 +99,7 @@ sealed case class Resolution(
), ),
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -110,8 +126,7 @@ sealed case class Resolution(
object Resolution { object Resolution {
/** A representation of a symbol resolution error. /** A representation of a symbol resolution error. */
*/
sealed trait Reason { sealed trait Reason {
def explain(originalName: Name): String def explain(originalName: Name): String
} }

View File

@ -13,21 +13,37 @@ import scala.annotation.unused
* @param at the error location * @param at the error location
* @param reason the cause of this error * @param reason the cause of this error
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Syntax( sealed case class Syntax(
at: IdentifiedLocation, at: IdentifiedLocation,
reason: Syntax.Reason, reason: Syntax.Reason,
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Error ) extends Error
with Diagnostic.Kind.Interactive with Diagnostic.Kind.Interactive
with module.scope.Definition with module.scope.Definition
with module.scope.Export with module.scope.Export
with module.scope.Import with module.scope.Import
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Create a syntax error.
*
* @param at the error location
* @param reason the cause of this error
* @param passData the pass metadata associated with this node
* @param diagnostics the compiler diagnostics
*/
def this(
at: IdentifiedLocation,
reason: Syntax.Reason,
passData: MetadataStorage,
diagnostics: DiagnosticStorage
) = {
this(at, reason, passData)
this.diagnostics = diagnostics
}
/** Creates a copy of `this`. /** Creates a copy of `this`.
* *
* @param ast the error location * @param ast the error location
@ -51,7 +67,8 @@ sealed case class Syntax(
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Syntax(at, reason, passData, diagnostics) val res = Syntax(at, reason, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -67,8 +84,7 @@ sealed case class Syntax(
copy( copy(
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -117,12 +133,10 @@ sealed case class Syntax(
object Syntax { object Syntax {
/** A common type for all syntax errors expected by the language. /** A common type for all syntax errors expected by the language. */
*/
sealed trait Reason { sealed trait Reason {
/** @return a human-readable description of the error. /** @return a human-readable description of the error. */
*/
def explanation: String def explanation: String
} }

View File

@ -48,15 +48,14 @@ object Unexpected {
* *
* @param ir the erroneous signature * @param ir the erroneous signature
* @param passData any pass metadata associated with this node * @param passData any pass metadata associated with this node
* @param diagnostics any compiler diagnostics for this node
*/ */
sealed case class TypeSignature( sealed case class TypeSignature(
override val ir: IR, override val ir: IR,
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Unexpected ) extends Unexpected
with IRKind.Primitive with IRKind.Primitive
with org.enso.compiler.core.ir.module.scope.Definition with org.enso.compiler.core.ir.module.scope.Definition
with LazyDiagnosticStorage
with LazyId { with LazyId {
override val entity: String = "type signature" override val entity: String = "type signature"
@ -80,8 +79,8 @@ object Unexpected {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = TypeSignature(ir, passData)
val res = TypeSignature(ir, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -113,8 +112,7 @@ object Unexpected {
), ),
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -7,6 +7,7 @@ import org.enso.compiler.core.ir.{
Expression, Expression,
IRKind, IRKind,
IdentifiedLocation, IdentifiedLocation,
LazyDiagnosticStorage,
LazyId, LazyId,
MetadataStorage, MetadataStorage,
Name Name
@ -51,17 +52,16 @@ object Definition {
* @param members the members of this union * @param members the members of this union
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Type( sealed case class Type(
name: Name, name: Name,
params: List[DefinitionArgument], params: List[DefinitionArgument],
members: List[Data], members: List[Data],
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Definition ) extends Definition
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
def copy( def copy(
@ -82,8 +82,8 @@ object Definition {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = val res = Type(name, params, members, location, passData)
Type(name, params, members, location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -114,8 +114,7 @@ object Definition {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -167,7 +166,6 @@ object Definition {
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param isPrivate If the constructor is private (project-private). * @param isPrivate If the constructor is private (project-private).
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Data( sealed case class Data(
name: Name, name: Name,
@ -175,10 +173,10 @@ object Definition {
annotations: List[Name.GenericAnnotation], annotations: List[Name.GenericAnnotation],
isPrivate: Boolean = false, isPrivate: Boolean = false,
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends IR ) extends IR
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -218,9 +216,9 @@ object Definition {
annotations, annotations,
isPrivate, isPrivate,
location, location,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -251,8 +249,7 @@ object Definition {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -304,17 +301,16 @@ object Definition {
* @param body the body of the complex type * @param body the body of the complex type
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class SugaredType( sealed case class SugaredType(
name: Name, name: Name,
arguments: List[DefinitionArgument], arguments: List[DefinitionArgument],
body: List[IR], body: List[IR],
location: Option[IdentifiedLocation], location: Option[IdentifiedLocation],
passData: MetadataStorage = new MetadataStorage(), passData: MetadataStorage = new MetadataStorage()
diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Definition ) extends Definition
with IRKind.Sugar with IRKind.Sugar
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -351,9 +347,9 @@ object Definition {
arguments, arguments,
body, body,
location, location,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -392,8 +388,7 @@ object Definition {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -8,6 +8,7 @@ import org.enso.compiler.core.ir.{
Expression, Expression,
IRKind, IRKind,
IdentifiedLocation, IdentifiedLocation,
LazyDiagnosticStorage,
LazyId, LazyId,
MetadataStorage, MetadataStorage,
Name Name
@ -45,7 +46,6 @@ object Export {
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param isSynthetic is this export compiler-generated * @param isSynthetic is this export compiler-generated
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Module( sealed case class Module(
name: Name.Qualified, name: Name.Qualified,
@ -53,11 +53,11 @@ object Export {
onlyNames: Option[List[Name.Literal]], onlyNames: Option[List[Name.Literal]],
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
isSynthetic: Boolean = false, isSynthetic: Boolean = false,
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends IR ) extends IR
with IRKind.Primitive with IRKind.Primitive
with Export with Export
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -92,16 +92,15 @@ object Export {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Module( val res = Module(
name, name,
rename, rename,
onlyNames, onlyNames,
location, location,
isSynthetic, isSynthetic,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -118,8 +117,7 @@ object Export {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -8,6 +8,7 @@ import org.enso.compiler.core.ir.{
Expression, Expression,
IRKind, IRKind,
IdentifiedLocation, IdentifiedLocation,
LazyDiagnosticStorage,
LazyId, LazyId,
MetadataStorage, MetadataStorage,
Name Name
@ -47,7 +48,6 @@ object Import {
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param isSynthetic is this import compiler-generated * @param isSynthetic is this import compiler-generated
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Module( sealed case class Module(
name: Name.Qualified, name: Name.Qualified,
@ -57,10 +57,10 @@ object Import {
hiddenNames: Option[List[Name.Literal]], hiddenNames: Option[List[Name.Literal]],
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
isSynthetic: Boolean = false, isSynthetic: Boolean = false,
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Import ) extends Import
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -109,9 +109,9 @@ object Import {
hiddenNames, hiddenNames,
location, location,
isSynthetic, isSynthetic,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -144,8 +144,7 @@ object Import {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -49,38 +49,36 @@ object Method {
* @param isStaticWrapperForInstanceMethod true if this method represents a static wrapper for instance method, false otherwise * @param isStaticWrapperForInstanceMethod true if this method represents a static wrapper for instance method, false otherwise
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Explicit( sealed case class Explicit(
methodReference: Name.MethodReference, methodReference: Name.MethodReference,
bodyReference: Persistance.Reference[Expression], bodyReference: Persistance.Reference[Expression],
isStatic: Boolean, isStatic: Boolean,
isPrivate: Boolean, override val isPrivate: Boolean,
isStaticWrapperForInstanceMethod: Boolean, isStaticWrapperForInstanceMethod: Boolean,
location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
passData: MetadataStorage, override val passData: MetadataStorage
diagnostics: DiagnosticStorage
) extends Method ) extends Method
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
def this(
methodReference: Name.MethodReference, /** Create an [[Explicit]] object from [[Method.Binding]].
body: Expression, *
isPrivate: Boolean, * @param ir the method binding IR
location: Option[IdentifiedLocation], * @param body the method body expression
passData: MetadataStorage = new MetadataStorage(), */
diagnostics: DiagnosticStorage = DiagnosticStorage() def this(ir: Method.Binding, body: Expression) = {
) = {
this( this(
methodReference, ir.methodReference,
Persistance.Reference.of(body, false), Persistance.Reference.of(body, false),
Explicit.computeIsStatic(body), Explicit.computeIsStatic(body),
isPrivate, ir.isPrivate,
Explicit.computeIsStaticWrapperForInstanceMethod(body), Explicit.computeIsStaticWrapperForInstanceMethod(body),
location, ir.location,
passData, ir.passData
diagnostics )
); diagnostics = ir.diagnostics
} }
lazy val body: Expression = bodyReference.get(classOf[Expression]) lazy val body: Expression = bodyReference.get(classOf[Expression])
@ -128,9 +126,9 @@ object Method {
isPrivate, isPrivate,
isStaticWrapperForInstanceMethod, isStaticWrapperForInstanceMethod,
location, location,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -160,9 +158,7 @@ object Method {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy
else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -211,6 +207,7 @@ object Method {
} }
object Explicit { object Explicit {
def unapply(m: Explicit): Option[ def unapply(m: Explicit): Option[
( (
Name.MethodReference, Name.MethodReference,
@ -254,7 +251,6 @@ object Method {
* @param body the body of the method * @param body the body of the method
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Binding( sealed case class Binding(
override val methodReference: Name.MethodReference, override val methodReference: Name.MethodReference,
@ -262,12 +258,43 @@ object Method {
isPrivate: Boolean, isPrivate: Boolean,
override val body: Expression, override val body: Expression,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Method ) extends Method
with IRKind.Sugar with IRKind.Sugar
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Create a [[Binding]] object.
*
* @param methodReference a reference to the method being defined
* @param arguments the arguments to the method
* @param isPrivate if the method is declared as private (project-private).
* i.e. with prepended `private` keyword.
* @param body the body of the method
* @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node
* @param diagnostics the compiler diagnostics
*/
def this(
methodReference: Name.MethodReference,
arguments: List[DefinitionArgument],
isPrivate: Boolean,
body: Expression,
location: Option[IdentifiedLocation],
passData: MetadataStorage,
diagnostics: DiagnosticStorage
) = {
this(
methodReference,
arguments,
isPrivate,
body,
location,
passData
)
this.diagnostics = diagnostics
}
/** Creates a copy of `this`. /** Creates a copy of `this`.
* *
* @param methodReference a reference to the method being defined * @param methodReference a reference to the method being defined
@ -305,9 +332,9 @@ object Method {
isPrivate, isPrivate,
body, body,
location, location,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -344,9 +371,7 @@ object Method {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy
else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -408,19 +433,33 @@ object Method {
* @param body the body of the method * @param body the body of the method
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Conversion( sealed case class Conversion(
override val methodReference: Name.MethodReference, override val methodReference: Name.MethodReference,
sourceTypeName: Expression, sourceTypeName: Expression,
override val body: Expression, override val body: Expression,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Method ) extends Method
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Create a conversion method from [[Method.Binding]].
*
* @param ir the method binding IR
* @param sourceTypeName the type of the source value for this conversion
* @param body the body of the method
*/
def this(
ir: Method.Binding,
sourceTypeName: Expression,
body: Expression
) = {
this(ir.methodReference, sourceTypeName, body, ir.location, ir.passData)
diagnostics = ir.diagnostics
}
// Conversion methods cannot be private for now // Conversion methods cannot be private for now
override val isPrivate: Boolean = false override val isPrivate: Boolean = false
@ -455,15 +494,14 @@ object Method {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Conversion( val res = Conversion(
methodReference, methodReference,
sourceTypeName, sourceTypeName,
body, body,
location, location,
passData, passData
diagnostics
) )
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -498,9 +536,7 @@ object Method {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy
else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
} }

View File

@ -8,6 +8,7 @@ import org.enso.compiler.core.ir.{
Expression, Expression,
IRKind, IRKind,
IdentifiedLocation, IdentifiedLocation,
LazyDiagnosticStorage,
LazyId, LazyId,
MetadataStorage MetadataStorage
} }
@ -17,20 +18,18 @@ import java.util.UUID
/** An import of a polyglot class. /** An import of a polyglot class.
* *
* @param entity language-specific information on the imported entity * @param entity language-specific information on the imported entity
* @param rename the name this object should be visible under in the * @param rename the name this object should be visible under in the importing scope
* importing scope
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Polyglot( sealed case class Polyglot(
entity: Polyglot.Entity, entity: Polyglot.Entity,
rename: Option[String], rename: Option[String],
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Import ) extends Import
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -60,8 +59,8 @@ sealed case class Polyglot(
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = val res = Polyglot(entity, rename, location, passData)
Polyglot(entity, rename, location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -78,8 +77,7 @@ sealed case class Polyglot(
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -37,17 +37,16 @@ object Set {
* @param value the member's value, if given * @param value the member's value, if given
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Member( sealed case class Member(
label: Name, label: Name,
memberType: Expression, memberType: Expression,
value: Expression, value: Expression,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Set ) extends Set
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -79,8 +78,8 @@ object Set {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = val res = Member(label, memberType, value, location, passData)
Member(label, memberType, value, location, passData, diagnostics) res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -116,8 +115,7 @@ object Set {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -171,16 +169,15 @@ object Set {
* @param right the right operand * @param right the right operand
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Subsumption( sealed case class Subsumption(
left: Expression, left: Expression,
right: Expression, right: Expression,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Set ) extends Set
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -209,7 +206,8 @@ object Set {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Subsumption(left, right, location, passData, diagnostics) val res = Subsumption(left, right, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -238,8 +236,7 @@ object Set {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -285,16 +282,15 @@ object Set {
* @param right the right operand * @param right the right operand
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Equality( sealed case class Equality(
left: Expression, left: Expression,
right: Expression, right: Expression,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Set ) extends Set
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -323,7 +319,8 @@ object Set {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Equality(left, right, location, passData, diagnostics) val res = Equality(left, right, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -352,8 +349,7 @@ object Set {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -399,16 +395,15 @@ object Set {
* @param right the right operand * @param right the right operand
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Concat( sealed case class Concat(
left: Expression, left: Expression,
right: Expression, right: Expression,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Set ) extends Set
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -437,7 +432,8 @@ object Set {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Concat(left, right, location, passData, diagnostics) val res = Concat(left, right, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -466,8 +462,7 @@ object Set {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -511,21 +506,19 @@ object Set {
* @param operands the operands * @param operands the operands
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Union( sealed case class Union(
operands: List[Expression], operands: List[Expression],
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Set ) extends Set
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
* *
* @param left the left operand * @param operands the list of expressions
* @param right the right operand
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node * @param diagnostics compiler diagnostics for this node
@ -546,7 +539,8 @@ object Set {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Union(operands, location, passData, diagnostics) val res = Union(operands, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -571,8 +565,7 @@ object Set {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )
@ -616,16 +609,15 @@ object Set {
* @param right the right operand * @param right the right operand
* @param location the source location that the node corresponds to * @param location the source location that the node corresponds to
* @param passData the pass metadata associated with this node * @param passData the pass metadata associated with this node
* @param diagnostics compiler diagnostics for this node
*/ */
sealed case class Intersection( sealed case class Intersection(
left: Expression, left: Expression,
right: Expression, right: Expression,
override val location: Option[IdentifiedLocation], override val location: Option[IdentifiedLocation],
override val passData: MetadataStorage = new MetadataStorage(), override val passData: MetadataStorage = new MetadataStorage()
override val diagnostics: DiagnosticStorage = DiagnosticStorage()
) extends Set ) extends Set
with IRKind.Primitive with IRKind.Primitive
with LazyDiagnosticStorage
with LazyId { with LazyId {
/** Creates a copy of `this`. /** Creates a copy of `this`.
@ -654,7 +646,8 @@ object Set {
|| diagnostics != this.diagnostics || diagnostics != this.diagnostics
|| id != this.id || id != this.id
) { ) {
val res = Intersection(left, right, location, passData, diagnostics) val res = Intersection(left, right, location, passData)
res.diagnostics = diagnostics
res.id = id res.id = id
res res
} else this } else this
@ -683,8 +676,7 @@ object Set {
location = if (keepLocations) location else None, location = if (keepLocations) location else None,
passData = passData =
if (keepMetadata) passData.duplicate else new MetadataStorage(), if (keepMetadata) passData.duplicate else new MetadataStorage(),
diagnostics = diagnostics = if (keepDiagnostics) diagnosticsCopy else null,
if (keepDiagnostics) diagnostics.copy else DiagnosticStorage(),
id = if (keepIdentifiers) id else null id = if (keepIdentifiers) id else null
) )

View File

@ -9,7 +9,6 @@ import java.util.Objects;
import java.util.UUID; import java.util.UUID;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Supplier; import java.util.function.Supplier;
import org.enso.compiler.core.ir.DiagnosticStorage;
import org.enso.compiler.core.ir.IdentifiedLocation; import org.enso.compiler.core.ir.IdentifiedLocation;
import org.enso.compiler.core.ir.Location; import org.enso.compiler.core.ir.Location;
import org.enso.compiler.core.ir.MetadataStorage; import org.enso.compiler.core.ir.MetadataStorage;
@ -288,8 +287,7 @@ public class IrPersistanceTest {
@Test @Test
public void serializeModule() throws Exception { public void serializeModule() throws Exception {
var meta = new MetadataStorage(); var meta = new MetadataStorage();
var diag = new DiagnosticStorage(nil()); var m = new Module(nil(), nil(), nil(), true, Option.empty(), meta);
var m = new Module(nil(), nil(), nil(), true, Option.empty(), meta, diag);
var out = serde(Module.class, m, -1); var out = serde(Module.class, m, -1);

View File

@ -71,7 +71,6 @@ final class SuggestionBuilder[A: IndexedSource](
params, params,
List(), List(),
_, _,
_,
_ _
) => ) =>
val tpe = val tpe =
@ -83,7 +82,6 @@ final class SuggestionBuilder[A: IndexedSource](
params, params,
members, members,
_, _,
_,
_ _
) => ) =>
val tpe = val tpe =
@ -95,7 +93,6 @@ final class SuggestionBuilder[A: IndexedSource](
annotations, annotations,
isPrivate, isPrivate,
_, _,
_,
_ _
) if !isPrivate => ) if !isPrivate =>
buildAtomConstructor( buildAtomConstructor(
@ -123,7 +120,7 @@ final class SuggestionBuilder[A: IndexedSource](
case m @ definition.Method case m @ definition.Method
.Explicit( .Explicit(
Name.MethodReference(typePtr, methodName, _, _, _), Name.MethodReference(typePtr, methodName, _, _),
Function.Lambda(args, body, _, _, _, _), Function.Lambda(args, body, _, _, _, _),
_, _,
_, _,
@ -162,11 +159,10 @@ final class SuggestionBuilder[A: IndexedSource](
case conversionMeth @ definition.Method case conversionMeth @ definition.Method
.Conversion( .Conversion(
Name.MethodReference(typePtr, _, _, _, _), Name.MethodReference(typePtr, _, _, _),
_, _,
Function.Lambda(args, body, _, _, _, _), Function.Lambda(args, body, _, _, _, _),
_, _,
_,
_ _
) if !conversionMeth.isPrivate => ) if !conversionMeth.isPrivate =>
val selfType = typePtr.flatMap { typePointer => val selfType = typePtr.flatMap { typePointer =>
@ -187,7 +183,6 @@ final class SuggestionBuilder[A: IndexedSource](
name, name,
Function.Lambda(args, body, _, _, _, _), Function.Lambda(args, body, _, _, _, _),
_, _,
_,
_ _
) if name.location.isDefined => ) if name.location.isDefined =>
val typeSignature = ir.getMetadata(TypeSignatures) val typeSignature = ir.getMetadata(TypeSignatures)
@ -206,7 +201,7 @@ final class SuggestionBuilder[A: IndexedSource](
) )
go(tree += Tree.Node(function, subforest), scope) go(tree += Tree.Node(function, subforest), scope)
case Expression.Binding(name, expr, _, _, _) case Expression.Binding(name, expr, _, _)
if name.location.isDefined => if name.location.isDefined =>
val typeSignature = ir.getMetadata(TypeSignatures) val typeSignature = ir.getMetadata(TypeSignatures)
val local = buildLocal( val local = buildLocal(
@ -571,7 +566,6 @@ final class SuggestionBuilder[A: IndexedSource](
defaultValue, defaultValue,
suspended, suspended,
_, _,
_,
_ _
) +: vtail => ) +: vtail =>
if (isStatic) { if (isStatic) {
@ -770,7 +764,7 @@ final class SuggestionBuilder[A: IndexedSource](
*/ */
private def buildDefaultValue(expr: IR): String = private def buildDefaultValue(expr: IR): String =
expr match { expr match {
case Application.Prefix(name, path, _, _, _, _) => case Application.Prefix(name, path, _, _, _) =>
path.map(_.value.showCode()).mkString(".") + "." + name.showCode() path.map(_.value.showCode()).mkString(".") + "." + name.showCode()
case other => other.showCode() case other => other.showCode()
} }

View File

@ -232,7 +232,7 @@ class IrToTruffle(
private def registerPolyglotImports(module: Module): Unit = private def registerPolyglotImports(module: Module): Unit =
module.imports.foreach { module.imports.foreach {
case poly @ imports.Polyglot(i: imports.Polyglot.Java, _, _, _, _) => case poly @ imports.Polyglot(i: imports.Polyglot.Java, _, _, _) =>
var hostSymbol = context.lookupJavaClass(i.getJavaName) var hostSymbol = context.lookupJavaClass(i.getJavaName)
if (hostSymbol == null) { if (hostSymbol == null) {
val err = Text.create( val err = Text.create(
@ -1296,7 +1296,7 @@ class IrToTruffle(
"Comments should not be present during codegen." "Comments should not be present during codegen."
) )
case err: Error => processError(err) case err: Error => processError(err)
case Foreign.Definition(_, _, _, _, _) => case Foreign.Definition(_, _, _, _) =>
throw new CompilerError( throw new CompilerError(
s"Foreign expressions not yet implemented: $ir." s"Foreign expressions not yet implemented: $ir."
) )
@ -1410,7 +1410,7 @@ class IrToTruffle(
subjectToInstrumentation: Boolean subjectToInstrumentation: Boolean
): RuntimeExpression = ): RuntimeExpression =
caseExpr match { caseExpr match {
case Case.Expr(scrutinee, branches, isNested, location, _, _) => case Case.Expr(scrutinee, branches, isNested, location, _) =>
val scrutineeNode = this.run(scrutinee, subjectToInstrumentation) val scrutineeNode = this.run(scrutinee, subjectToInstrumentation)
val maybeCases = branches.map(processCaseBranch) val maybeCases = branches.map(processCaseBranch)
@ -1473,7 +1473,7 @@ class IrToTruffle(
) )
branch.pattern match { branch.pattern match {
case named @ Pattern.Name(_, _, _, _) => case named: Pattern.Name =>
val arg = List(genArgFromMatchField(named)) val arg = List(genArgFromMatchField(named))
val branchCodeNode = childProcessor.processFunctionBody( val branchCodeNode = childProcessor.processFunctionBody(
@ -1486,7 +1486,7 @@ class IrToTruffle(
CatchAllBranchNode.build(branchCodeNode.getCallTarget, true) CatchAllBranchNode.build(branchCodeNode.getCallTarget, true)
Right(branchNode) Right(branchNode)
case cons @ Pattern.Constructor(constructor, _, _, _, _) => case cons @ Pattern.Constructor(constructor, _, _, _) =>
if (!cons.isDesugared) { if (!cons.isDesugared) {
throw new CompilerError( throw new CompilerError(
"Nested patterns desugaring must have taken place by the " + "Nested patterns desugaring must have taken place by the " +
@ -1705,7 +1705,7 @@ class IrToTruffle(
) )
) )
} }
case Pattern.Type(varName, tpeName, location, _, _) => case Pattern.Type(varName, tpeName, location, _) =>
tpeName.getMetadata(Patterns) match { tpeName.getMetadata(Patterns) match {
case None => case None =>
Left(BadPatternMatch.NonVisibleType(tpeName.name)) Left(BadPatternMatch.NonVisibleType(tpeName.name))
@ -1720,7 +1720,7 @@ class IrToTruffle(
) match { ) match {
case Some(tpe) => case Some(tpe) =>
val argOfType = List( val argOfType = List(
DefinitionArgument.Specified( new DefinitionArgument.Specified(
varName, varName,
None, None,
None, None,
@ -1754,7 +1754,7 @@ class IrToTruffle(
asScope(mod.unsafeAsModule()).getPolyglotSymbol(symbol.name) asScope(mod.unsafeAsModule()).getPolyglotSymbol(symbol.name)
if (polySymbol != null) { if (polySymbol != null) {
val argOfType = List( val argOfType = List(
DefinitionArgument.Specified( new DefinitionArgument.Specified(
varName, varName,
None, None,
None, None,
@ -1792,7 +1792,6 @@ class IrToTruffle(
case errors.Pattern( case errors.Pattern(
_, _,
errors.Pattern.WrongArity(name, expected, actual), errors.Pattern.WrongArity(name, expected, actual),
_,
_ _
) => ) =>
Left(BadPatternMatch.WrongArgCount(name, expected, actual)) Left(BadPatternMatch.WrongArgCount(name, expected, actual))
@ -1814,8 +1813,8 @@ class IrToTruffle(
* @param name the pattern field to generate from * @param name the pattern field to generate from
* @return `name` as a function definition argument. * @return `name` as a function definition argument.
*/ */
def genArgFromMatchField(name: Pattern.Name): DefinitionArgument = { private def genArgFromMatchField(name: Pattern.Name): DefinitionArgument = {
DefinitionArgument.Specified( new DefinitionArgument.Specified(
name.name, name.name,
None, None,
None, None,
@ -1909,13 +1908,12 @@ class IrToTruffle(
resolver.resolveName(literalName, fpMeta) resolver.resolveName(literalName, fpMeta)
case Name.MethodReference( case Name.MethodReference(
None, None,
Name.Literal(nameStr, _, _, _, _, _), Name.Literal(nameStr, _, _, _, _),
_,
_, _,
_ _
) => ) =>
DynamicSymbolNode.buildUnresolvedConstructor(nameStr) DynamicSymbolNode.buildUnresolvedConstructor(nameStr)
case Name.Self(location, _, passData, _) => case Name.Self(location, _, passData) =>
processName( processName(
Name.Literal( Name.Literal(
ConstantsNames.SELF_ARGUMENT, ConstantsNames.SELF_ARGUMENT,
@ -1932,7 +1930,7 @@ class IrToTruffle(
"a Self occurence must be resolved" "a Self occurence must be resolved"
).target ).target
) )
case Name.Special(name, _, _, _) => case Name.Special(name, _, _) =>
val fun = name match { val fun = name match {
case Special.NewRef => context.getBuiltins.special().getNewRef case Special.NewRef => context.getBuiltins.special().getNewRef
case Special.ReadRef => context.getBuiltins.special().getReadRef case Special.ReadRef => context.getBuiltins.special().getReadRef
@ -2061,14 +2059,14 @@ class IrToTruffle(
@throws[CompilerError] @throws[CompilerError]
private def processLiteral(literal: Literal): RuntimeExpression = private def processLiteral(literal: Literal): RuntimeExpression =
literal match { literal match {
case lit @ Literal.Number(_, _, location, _, _) => case lit: Literal.Number =>
val node = lit.numericValue match { val node = lit.numericValue match {
case l: Long => LiteralNode.build(l) case l: Long => LiteralNode.build(l)
case d: Double => LiteralNode.build(d) case d: Double => LiteralNode.build(d)
case b: BigInteger => LiteralNode.build(b) case b: BigInteger => LiteralNode.build(b)
} }
setLocation(node, location) setLocation(node, lit.location)
case Literal.Text(text, location, _, _) => case Literal.Text(text, location, _) =>
setLocation(LiteralNode.build(text), location) setLocation(LiteralNode.build(text), location)
} }
@ -2088,7 +2086,7 @@ class IrToTruffle(
*/ */
private def processError(error: Error): RuntimeExpression = { private def processError(error: Error): RuntimeExpression = {
val payload: Atom = error match { val payload: Atom = error match {
case Error.InvalidIR(_, _, _) => case Error.InvalidIR(_, _) =>
throw new CompilerError("Unexpected Invalid IR during codegen.") throw new CompilerError("Unexpected Invalid IR during codegen.")
case err: errors.Syntax => case err: errors.Syntax =>
context.getBuiltins context.getBuiltins
@ -2189,7 +2187,7 @@ class IrToTruffle(
val (argSlotIdxs, _, argExpressions) = slots val (argSlotIdxs, _, argExpressions) = slots
val bodyExpr = body match { val bodyExpr = body match {
case Foreign.Definition(lang, code, _, _, _) => case Foreign.Definition(lang, code, _, _) =>
buildForeignBody( buildForeignBody(
lang, lang,
body.location, body.location,
@ -2346,16 +2344,16 @@ class IrToTruffle(
subjectToInstrumentation: Boolean subjectToInstrumentation: Boolean
): RuntimeExpression = ): RuntimeExpression =
application match { application match {
case Application.Prefix(fn, Nil, true, _, _, _) => case Application.Prefix(fn, Nil, true, _, _) =>
run(fn, subjectToInstrumentation) run(fn, subjectToInstrumentation)
case app: Application.Prefix => case app: Application.Prefix =>
processApplicationWithArgs(app, subjectToInstrumentation) processApplicationWithArgs(app, subjectToInstrumentation)
case Application.Force(expr, location, _, _) => case Application.Force(expr, location, _) =>
setLocation( setLocation(
ForceNode.build(this.run(expr, subjectToInstrumentation)), ForceNode.build(this.run(expr, subjectToInstrumentation)),
location location
) )
case Application.Sequence(items, location, _, _) => case Application.Sequence(items, location, _) =>
val itemNodes = items.map(run(_, subjectToInstrumentation)).toArray val itemNodes = items.map(run(_, subjectToInstrumentation)).toArray
setLocation(SequenceLiteralNode.build(itemNodes), location) setLocation(SequenceLiteralNode.build(itemNodes), location)
case _: Application.Typeset => case _: Application.Typeset =>
@ -2386,7 +2384,7 @@ class IrToTruffle(
application: Application.Prefix, application: Application.Prefix,
subjectToInstrumentation: Boolean subjectToInstrumentation: Boolean
): RuntimeExpression = { ): RuntimeExpression = {
val Application.Prefix(fn, args, hasDefaultsSuspended, loc, _, _) = val Application.Prefix(fn, args, hasDefaultsSuspended, loc, _) =
application application
val callArgFactory = val callArgFactory =
new CallArgumentProcessor(scope, scopeName, currentVarName) new CallArgumentProcessor(scope, scopeName, currentVarName)
@ -2448,13 +2446,7 @@ class IrToTruffle(
subjectToInstrumentation: Boolean subjectToInstrumentation: Boolean
): callable.argument.CallArgument = ): callable.argument.CallArgument =
arg match { arg match {
case CallArgument.Specified( case CallArgument.Specified(name, value, _, _) =>
name,
value,
_,
_,
_
) =>
def scopeInfo() = { def scopeInfo() = {
arg arg
.unsafeGetMetadata( .unsafeGetMetadata(