Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions Analysis/src/ConstraintSolver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1814,6 +1814,39 @@ bool ConstraintSolver::tryDispatch(const FunctionCheckConstraint& c, NotNull<con
TypeId expectedArgTy = follow(expectedArgs[i + typeOffset]);
AstExpr* expr = unwrapGroup(c.callSite->args.data[i]);

// If the expected type is a function type whose signature contains generics from the calling function,
// and the actual argument is a lambda with its own generics, instantiate the calling function's generics
// with fresh types to avoid conflicts with the actual type's generics.
const auto lambdaExpr = expr->as<AstExprFunction>();
bool argHasGenerics = lambdaExpr && (lambdaExpr->generics.size > 0 || lambdaExpr->genericPacks.size > 0);

if (get<FunctionType>(expectedArgTy) && ContainsGenerics::hasGeneric(expectedArgTy, NotNull{&genericTypesAndPacks}) && argHasGenerics)
{
DenseHashMap<TypeId, TypeId> freshReplacements{nullptr};
DenseHashMap<TypePackId, TypePackId> freshReplacementPacks{nullptr};

for (auto generic : ftv->generics)
{
if (auto gty = get<GenericType>(follow(generic)))
{
freshReplacements[generic] = freshType(arena, builtinTypes, constraint->scope, Polarity::Mixed);
trackInteriorFreeType(constraint->scope, freshReplacements[generic]);
}
}

for (auto genericPack : ftv->genericPacks)
{
freshReplacementPacks[genericPack] = arena->freshTypePack(constraint->scope, Polarity::Mixed);
trackInteriorFreeTypePack(constraint->scope, freshReplacementPacks[genericPack]);
}

Replacer freshReplacer{arena, std::move(freshReplacements), std::move(freshReplacementPacks)};
if (auto instantiated = freshReplacer.substitute(expectedArgTy))
{
expectedArgTy = *instantiated;
}
}

PushTypeResult result =
pushTypeInto(c.astTypes, c.astExpectedTypes, NotNull{this}, constraint, NotNull{&u2}, NotNull{&subtyping}, expectedArgTy, expr);

Expand Down