Skip to content

Commit 867b093

Browse files
committed
[CS] Allow ExprPatterns to be type-checked in the solver
Previously we would wait until CSApply, which would trigger their type-checking in `coercePatternToType`. This caused a number of bugs, and hampered solver-based completion, which does not run CSApply. Instead, form a conjunction of all the ExprPatterns present, which preserves some of the previous isolation behavior (though does not provide complete isolation). We can then modify `coercePatternToType` to accept a closure, which allows the solver to take over rewriting the ExprPatterns it has already solved. This then sets the stage for the complete removal of `coercePatternToType`, and doing all pattern type-checking in the solver.
1 parent 209c60d commit 867b093

21 files changed

+489
-142
lines changed

include/swift/Sema/ConstraintSystem.h

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1500,6 +1500,10 @@ class Solution {
15001500
llvm::SmallMapVector<const CaseLabelItem *, CaseLabelItemInfo, 4>
15011501
caseLabelItems;
15021502

1503+
/// A map of expressions to the ExprPatterns that they are being solved as
1504+
/// a part of.
1505+
llvm::SmallMapVector<Expr *, ExprPattern *, 2> exprPatterns;
1506+
15031507
/// The set of parameters that have been inferred to be 'isolated'.
15041508
llvm::SmallVector<ParamDecl *, 2> isolatedParams;
15051509

@@ -1685,6 +1689,16 @@ class Solution {
16851689
: nullptr;
16861690
}
16871691

1692+
/// Retrieve the solved ExprPattern that corresponds to provided
1693+
/// sub-expression.
1694+
NullablePtr<ExprPattern> getExprPatternFor(Expr *E) const {
1695+
auto result = exprPatterns.find(E);
1696+
if (result == exprPatterns.end())
1697+
return nullptr;
1698+
1699+
return result->second;
1700+
}
1701+
16881702
/// This method implements functionality of `Expr::isTypeReference`
16891703
/// with data provided by a given solution.
16901704
bool isTypeReference(Expr *E) const;
@@ -2148,6 +2162,10 @@ class ConstraintSystem {
21482162
llvm::SmallMapVector<const CaseLabelItem *, CaseLabelItemInfo, 4>
21492163
caseLabelItems;
21502164

2165+
/// A map of expressions to the ExprPatterns that they are being solved as
2166+
/// a part of.
2167+
llvm::SmallMapVector<Expr *, ExprPattern *, 2> exprPatterns;
2168+
21512169
/// The set of parameters that have been inferred to be 'isolated'.
21522170
llvm::SmallSetVector<ParamDecl *, 2> isolatedParams;
21532171

@@ -2745,6 +2763,9 @@ class ConstraintSystem {
27452763
/// The length of \c caseLabelItems.
27462764
unsigned numCaseLabelItems;
27472765

2766+
/// The length of \c exprPatterns.
2767+
unsigned numExprPatterns;
2768+
27482769
/// The length of \c isolatedParams.
27492770
unsigned numIsolatedParams;
27502771

@@ -3166,6 +3187,15 @@ class ConstraintSystem {
31663187
caseLabelItems[item] = info;
31673188
}
31683189

3190+
/// Record a given ExprPattern as the parent of its sub-expression.
3191+
void setExprPatternFor(Expr *E, ExprPattern *EP) {
3192+
assert(E);
3193+
assert(EP);
3194+
auto inserted = exprPatterns.insert({E, EP}).second;
3195+
assert(inserted && "Mapping already defined?");
3196+
(void)inserted;
3197+
}
3198+
31693199
Optional<CaseLabelItemInfo> getCaseLabelItemInfo(
31703200
const CaseLabelItem *item) const {
31713201
auto known = caseLabelItems.find(item);
@@ -4315,6 +4345,11 @@ class ConstraintSystem {
43154345
/// \returns \c true if constraint generation failed, \c false otherwise
43164346
bool generateConstraints(SingleValueStmtExpr *E);
43174347

4348+
/// Generate constraints for an array of ExprPatterns, forming a conjunction
4349+
/// that solves each expression in turn.
4350+
void generateConstraints(ArrayRef<ExprPattern *> exprPatterns,
4351+
ConstraintLocatorBuilder locator);
4352+
43184353
/// Generate constraints for the given (unchecked) expression.
43194354
///
43204355
/// \returns a possibly-sanitized expression, or null if an error occurred.

lib/IDE/TypeCheckCompletionCallback.cpp

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,13 @@ Type swift::ide::getTypeForCompletion(const constraints::Solution &S,
8181
/// \endcode
8282
/// If the code completion expression occurs in such an AST, return the
8383
/// declaration of the \c $match variable, otherwise return \c nullptr.
84-
static VarDecl *getMatchVarIfInPatternMatch(Expr *E, ConstraintSystem &CS) {
84+
static VarDecl *getMatchVarIfInPatternMatch(Expr *E, const Solution &S) {
85+
if (auto EP = S.getExprPatternFor(E))
86+
return EP.get()->getMatchVar();
87+
88+
// TODO: Once ExprPattern type-checking is fully moved into the solver,
89+
// the below can be deleted.
90+
auto &CS = S.getConstraintSystem();
8591
auto &Context = CS.getASTContext();
8692

8793
auto *Binary = dyn_cast_or_null<BinaryExpr>(CS.getParentExpr(E));
@@ -109,20 +115,21 @@ static VarDecl *getMatchVarIfInPatternMatch(Expr *E, ConstraintSystem &CS) {
109115
}
110116

111117
Type swift::ide::getPatternMatchType(const constraints::Solution &S, Expr *E) {
112-
if (auto MatchVar = getMatchVarIfInPatternMatch(E, S.getConstraintSystem())) {
113-
Type MatchVarType;
114-
// If the MatchVar has an explicit type, it's not part of the solution. But
115-
// we can look it up in the constraint system directly.
116-
if (auto T = S.getConstraintSystem().getVarType(MatchVar)) {
117-
MatchVarType = T;
118-
} else {
119-
MatchVarType = getTypeForCompletion(S, MatchVar);
120-
}
121-
if (MatchVarType) {
122-
return MatchVarType;
123-
}
124-
}
125-
return nullptr;
118+
auto MatchVar = getMatchVarIfInPatternMatch(E, S);
119+
if (!MatchVar)
120+
return nullptr;
121+
122+
if (S.hasType(MatchVar))
123+
return S.getResolvedType(MatchVar);
124+
125+
// If the ExprPattern wasn't solved as part of the constraint system, it's
126+
// not part of the solution.
127+
// TODO: This can be removed once ExprPattern type-checking is fully part
128+
// of the constraint system.
129+
if (auto T = S.getConstraintSystem().getVarType(MatchVar))
130+
return T;
131+
132+
return getTypeForCompletion(S, MatchVar);
126133
}
127134

128135
void swift::ide::getSolutionSpecificVarTypes(

lib/Sema/CSApply.cpp

Lines changed: 83 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -8688,6 +8688,9 @@ namespace {
86888688
return Action::SkipChildren();
86898689
}
86908690

8691+
NullablePtr<Pattern>
8692+
rewritePattern(Pattern *pattern, DeclContext *DC);
8693+
86918694
/// Rewrite the target, producing a new target.
86928695
Optional<SyntacticElementTarget>
86938696
rewriteTarget(SyntacticElementTarget target);
@@ -8934,12 +8937,68 @@ static Expr *wrapAsyncLetInitializer(
89348937
return resultInit;
89358938
}
89368939

8940+
static Pattern *rewriteExprPattern(const SyntacticElementTarget &matchTarget,
8941+
Type patternTy,
8942+
RewriteTargetFn rewriteTarget) {
8943+
auto *EP = matchTarget.getExprPattern();
8944+
8945+
// See if we can simplify to another kind of pattern.
8946+
if (auto simplified = TypeChecker::trySimplifyExprPattern(EP, patternTy))
8947+
return simplified.get();
8948+
8949+
auto resultTarget = rewriteTarget(matchTarget);
8950+
if (!resultTarget)
8951+
return nullptr;
8952+
8953+
EP->setMatchExpr(resultTarget->getAsExpr());
8954+
EP->getMatchVar()->setInterfaceType(patternTy->mapTypeOutOfContext());
8955+
EP->setType(patternTy);
8956+
return EP;
8957+
}
8958+
8959+
/// Attempt to rewrite either an ExprPattern, or a pattern that was solved as
8960+
/// an ExprPattern, e.g an EnumElementPattern that could not refer to an enum
8961+
/// case.
8962+
static Optional<Pattern *>
8963+
tryRewriteExprPattern(Pattern *P, Solution &solution, Type patternTy,
8964+
RewriteTargetFn rewriteTarget) {
8965+
// See if we have a match expression target.
8966+
auto matchTarget = solution.getTargetFor(P);
8967+
if (!matchTarget)
8968+
return None;
8969+
8970+
return rewriteExprPattern(*matchTarget, patternTy, rewriteTarget);
8971+
}
8972+
8973+
NullablePtr<Pattern> ExprWalker::rewritePattern(Pattern *pattern,
8974+
DeclContext *DC) {
8975+
auto &solution = Rewriter.solution;
8976+
8977+
// Figure out the pattern type.
8978+
auto patternTy = solution.getResolvedType(pattern);
8979+
patternTy = patternTy->reconstituteSugar(/*recursive=*/false);
8980+
8981+
// Coerce the pattern to its appropriate type.
8982+
TypeResolutionOptions patternOptions(TypeResolverContext::InExpression);
8983+
patternOptions |= TypeResolutionFlags::OverrideType;
8984+
8985+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
8986+
return ::tryRewriteExprPattern(
8987+
EP, solution, ty, [&](auto target) { return rewriteTarget(target); });
8988+
};
8989+
8990+
auto contextualPattern = ContextualPattern::forRawPattern(pattern, DC);
8991+
return TypeChecker::coercePatternToType(contextualPattern, patternTy,
8992+
patternOptions, tryRewritePattern);
8993+
}
8994+
89378995
/// Apply the given solution to the initialization target.
89388996
///
89398997
/// \returns the resulting initialization expression.
89408998
static Optional<SyntacticElementTarget>
89418999
applySolutionToInitialization(Solution &solution, SyntacticElementTarget target,
8942-
Expr *initializer) {
9000+
Expr *initializer,
9001+
RewriteTargetFn rewriteTarget) {
89439002
auto wrappedVar = target.getInitializationWrappedVar();
89449003
Type initType;
89459004
if (wrappedVar) {
@@ -9004,10 +9063,14 @@ applySolutionToInitialization(Solution &solution, SyntacticElementTarget target,
90049063

90059064
finalPatternType = finalPatternType->reconstituteSugar(/*recursive =*/false);
90069065

9066+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
9067+
return ::tryRewriteExprPattern(EP, solution, ty, rewriteTarget);
9068+
};
9069+
90079070
// Apply the solution to the pattern as well.
90089071
auto contextualPattern = target.getContextualPattern();
90099072
if (auto coercedPattern = TypeChecker::coercePatternToType(
9010-
contextualPattern, finalPatternType, options)) {
9073+
contextualPattern, finalPatternType, options, tryRewritePattern)) {
90119074
resultTarget.setPattern(coercedPattern);
90129075
} else {
90139076
return None;
@@ -9154,10 +9217,15 @@ static Optional<SyntacticElementTarget> applySolutionToForEachStmt(
91549217
TypeResolutionOptions options(TypeResolverContext::ForEachStmt);
91559218
options |= TypeResolutionFlags::OverrideType;
91569219

9220+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
9221+
return ::tryRewriteExprPattern(EP, solution, ty, rewriteTarget);
9222+
};
9223+
91579224
// Apply the solution to the pattern as well.
91589225
auto contextualPattern = target.getContextualPattern();
91599226
auto coercedPattern = TypeChecker::coercePatternToType(
9160-
contextualPattern, forEachStmtInfo.initType, options);
9227+
contextualPattern, forEachStmtInfo.initType, options,
9228+
tryRewritePattern);
91619229
if (!coercedPattern)
91629230
return None;
91639231

@@ -9245,7 +9313,8 @@ ExprWalker::rewriteTarget(SyntacticElementTarget target) {
92459313
switch (target.getExprContextualTypePurpose()) {
92469314
case CTP_Initialization: {
92479315
auto initResultTarget = applySolutionToInitialization(
9248-
solution, target, rewrittenExpr);
9316+
solution, target, rewrittenExpr,
9317+
[&](auto target) { return rewriteTarget(target); });
92499318
if (!initResultTarget)
92509319
return None;
92519320

@@ -9336,47 +9405,11 @@ ExprWalker::rewriteTarget(SyntacticElementTarget target) {
93369405
ConstraintSystem &cs = solution.getConstraintSystem();
93379406
auto info = *cs.getCaseLabelItemInfo(*caseLabelItem);
93389407

9339-
// Figure out the pattern type.
9340-
Type patternType = solution.simplifyType(solution.getType(info.pattern));
9341-
patternType = patternType->reconstituteSugar(/*recursive=*/false);
9342-
9343-
// Check whether this enum element is resolved via ~= application.
9344-
if (auto *enumElement = dyn_cast<EnumElementPattern>(info.pattern)) {
9345-
if (auto target = cs.getTargetFor(enumElement)) {
9346-
auto *EP = target->getExprPattern();
9347-
auto enumType = solution.getResolvedType(EP);
9348-
9349-
auto *matchCall = target->getAsExpr();
9350-
9351-
auto *result = matchCall->walk(*this);
9352-
if (!result)
9353-
return None;
9354-
9355-
{
9356-
auto *matchVar = EP->getMatchVar();
9357-
matchVar->setInterfaceType(enumType->mapTypeOutOfContext());
9358-
}
9359-
9360-
EP->setMatchExpr(result);
9361-
EP->setType(enumType);
9362-
9363-
(*caseLabelItem)->setPattern(EP, /*resolved=*/true);
9364-
return target;
9365-
}
9366-
}
9367-
9368-
// Coerce the pattern to its appropriate type.
9369-
TypeResolutionOptions patternOptions(TypeResolverContext::InExpression);
9370-
patternOptions |= TypeResolutionFlags::OverrideType;
9371-
auto contextualPattern =
9372-
ContextualPattern::forRawPattern(info.pattern,
9373-
target.getDeclContext());
9374-
if (auto coercedPattern = TypeChecker::coercePatternToType(
9375-
contextualPattern, patternType, patternOptions)) {
9376-
(*caseLabelItem)->setPattern(coercedPattern, /*resolved=*/true);
9377-
} else {
9408+
auto pattern = rewritePattern(info.pattern, target.getDeclContext());
9409+
if (!pattern)
93789410
return None;
9379-
}
9411+
9412+
(*caseLabelItem)->setPattern(pattern.get(), /*resolved=*/true);
93809413

93819414
// If there is a guard expression, coerce that.
93829415
if (auto *guardExpr = info.guardExpr) {
@@ -9444,8 +9477,13 @@ ExprWalker::rewriteTarget(SyntacticElementTarget target) {
94449477
options |= TypeResolutionFlags::OverrideType;
94459478
}
94469479

9480+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
9481+
return ::tryRewriteExprPattern(
9482+
EP, solution, ty, [&](auto target) { return rewriteTarget(target); });
9483+
};
9484+
94479485
if (auto coercedPattern = TypeChecker::coercePatternToType(
9448-
contextualPattern, patternType, options)) {
9486+
contextualPattern, patternType, options, tryRewritePattern)) {
94499487
auto resultTarget = target;
94509488
resultTarget.setPattern(coercedPattern);
94519489
return resultTarget;

lib/Sema/CSGen.cpp

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2453,12 +2453,6 @@ namespace {
24532453
// function, to set the type of the pattern.
24542454
auto setType = [&](Type type) {
24552455
CS.setType(pattern, type);
2456-
if (auto PE = dyn_cast<ExprPattern>(pattern)) {
2457-
// Set the type of the pattern's sub-expression as well, so code
2458-
// completion can retrieve the expression's type in case it is a code
2459-
// completion token.
2460-
CS.setType(PE->getSubExpr(), type);
2461-
}
24622456
return type;
24632457
};
24642458

@@ -2883,15 +2877,12 @@ namespace {
28832877
return setType(patternType);
28842878
}
28852879

2886-
// Refutable patterns occur when checking the PatternBindingDecls in an
2887-
// if/let or while/let condition. They always require an initial value,
2888-
// so they always allow unspecified types.
2889-
case PatternKind::Expr:
2890-
// TODO: we could try harder here, e.g. for enum elements to provide the
2891-
// enum type.
2892-
return setType(
2893-
CS.createTypeVariable(CS.getConstraintLocator(locator),
2894-
TVO_CanBindToNoEscape | TVO_CanBindToHole));
2880+
case PatternKind::Expr: {
2881+
// We generate constraints for ExprPatterns in a separate pass. For
2882+
// now, just create a type variable.
2883+
return setType(CS.createTypeVariable(CS.getConstraintLocator(locator),
2884+
TVO_CanBindToNoEscape));
2885+
}
28952886
}
28962887

28972888
llvm_unreachable("Unhandled pattern kind");
@@ -4750,8 +4741,20 @@ Type ConstraintSystem::generateConstraints(
47504741
bool bindPatternVarsOneWay, PatternBindingDecl *patternBinding,
47514742
unsigned patternIndex) {
47524743
ConstraintGenerator cg(*this, nullptr);
4753-
return cg.getTypeForPattern(pattern, locator, bindPatternVarsOneWay,
4754-
patternBinding, patternIndex);
4744+
auto ty = cg.getTypeForPattern(pattern, locator, bindPatternVarsOneWay,
4745+
patternBinding, patternIndex);
4746+
assert(ty);
4747+
4748+
// Gather the ExprPatterns, and form a conjunction for their expressions.
4749+
SmallVector<ExprPattern *, 4> exprPatterns;
4750+
pattern->forEachNode([&](Pattern *P) {
4751+
if (auto *EP = dyn_cast<ExprPattern>(P))
4752+
exprPatterns.push_back(EP);
4753+
});
4754+
if (!exprPatterns.empty())
4755+
generateConstraints(exprPatterns, getConstraintLocator(pattern));
4756+
4757+
return ty;
47554758
}
47564759

47574760
bool ConstraintSystem::generateConstraints(StmtCondition condition,

0 commit comments

Comments
 (0)