Skip to content

Commit

Permalink
feat: clamp default values of parameter types to upper bound (#921)
Browse files Browse the repository at this point in the history
### Summary of Changes

The default value of a type parameter is now clamped to its upper bound
during inference of type parameters for calls.
  • Loading branch information
lars-reimann authored Feb 25, 2024
1 parent 35dc826 commit 76ad869
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -832,25 +832,29 @@ export class SafeDsTypeComputer {

// Normalize substitutions
for (const [typeParameter, substitution] of state.substitutions) {
let newSubstitution = substitution;

// Replace unknown types by default values or lower bound (Nothing)
if (substitution === UnknownType) {
if (newSubstitution === UnknownType) {
const defaultValueType = this.computeType(typeParameter.defaultValue);
if (defaultValueType === UnknownType) {
state.substitutions.set(typeParameter, this.coreTypes.Nothing);
continue;
} else {
state.substitutions.set(typeParameter, defaultValueType);
newSubstitution = defaultValueType;
}
continue;
}

// Clamp to upper bound
const upperBound = this.computeUpperBound(typeParameter, {
stopAtTypeParameterType: true,
}).substituteTypeParameters(state.substitutions);

if (!this.typeChecker.isSubtypeOf(substitution, upperBound)) {
state.substitutions.set(typeParameter, upperBound);
if (!this.typeChecker.isSubtypeOf(newSubstitution, upperBound)) {
newSubstitution = upperBound;
}

state.substitutions.set(typeParameter, newSubstitution);
}

return state.substitutions;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
package tests.typing.expressions.calls.typeParameterInference.clampToUpperBound

class C1<T sub Int>(p1: T)
class C1<T sub Int = String>(p1: T)

@Pure fun f1<T sub Int>(p1: T) -> r1: T
@Pure fun f1<T sub Int = String>(p1: T) -> r1: T

pipeline myPipeline {
// $TEST$ serialization C1<Int>
»C1("")«;

// $TEST$ serialization C1<Int>
»C1()«;

// $TEST$ serialization Int
»f1("")«;

// $TEST$ serialization Int
»f1()«;
}

0 comments on commit 76ad869

Please sign in to comment.