Skip to content

Commit

Permalink
feat: simplify substitutions passed to computeType (#873)
Browse files Browse the repository at this point in the history
### Summary of Changes

`computeType` takes type parameter substitutions as an argument, which
get applied before the result is returned. Previously, the substitutions
were used as they were given. Now they get simplified before they are
applied.
  • Loading branch information
lars-reimann authored Feb 10, 2024
1 parent 0daafb9 commit aa444d4
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions packages/safe-ds-lang/src/language/typing/safe-ds-type-computer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,17 +143,27 @@ export class SafeDsTypeComputer {
// -----------------------------------------------------------------------------------------------------------------

/**
* Computes the type of the given node.
* Computes the type of the given node and applies the given substitutions for type parameters. The result gets
* simplified as much as possible.
*/
computeType(node: AstNode | undefined, substitutions: TypeParameterSubstitutions = NO_SUBSTITUTIONS): Type {
if (!node) {
return UnknownType;
}

// Ignore type parameter substitutions for caching
const unsubstitutedType = this.nodeTypeCache.get(this.getNodeId(node), () =>
this.simplifyType(this.doComputeType(node)),
);
return unsubstitutedType.substituteTypeParameters(substitutions);
if (isEmpty(substitutions)) {
return unsubstitutedType;
}

// Substitute type parameters
const simplifiedSubstitutions = new Map(
[...substitutions].map(([typeParameter, type]) => [typeParameter, this.simplifyType(type)]),
);
return unsubstitutedType.substituteTypeParameters(simplifiedSubstitutions);
}

private getNodeId(node: AstNode) {
Expand Down Expand Up @@ -615,7 +625,11 @@ export class SafeDsTypeComputer {
// Simplify type
// -----------------------------------------------------------------------------------------------------------------

private simplifyType(type: Type): Type {
/**
* Returns an equivalent type that is simplified as much as possible. Types computed by {@link computeType} are
* already simplified, so this method is mainly useful for types that are constructed or modified manually.
*/
simplifyType(type: Type): Type {
const unwrappedType = type.unwrap();

if (unwrappedType instanceof LiteralType) {
Expand Down

0 comments on commit aa444d4

Please sign in to comment.