Skip to content

Commit 9b55e39

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 99ac8ae commit 9b55e39

21 files changed

+467
-143
lines changed

include/swift/Sema/ConstraintSystem.h

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

1518+
/// A map of expressions to the ExprPatterns that they are being solved as
1519+
/// a part of.
1520+
llvm::SmallMapVector<Expr *, ExprPattern *, 2> exprPatterns;
1521+
15181522
/// The set of parameters that have been inferred to be 'isolated'.
15191523
llvm::SmallVector<ParamDecl *, 2> isolatedParams;
15201524

@@ -1700,6 +1704,16 @@ class Solution {
17001704
: nullptr;
17011705
}
17021706

1707+
/// Retrieve the solved ExprPattern that corresponds to provided
1708+
/// sub-expression.
1709+
NullablePtr<ExprPattern> getExprPatternFor(Expr *E) const {
1710+
auto result = exprPatterns.find(E);
1711+
if (result == exprPatterns.end())
1712+
return nullptr;
1713+
1714+
return result->second;
1715+
}
1716+
17031717
/// This method implements functionality of `Expr::isTypeReference`
17041718
/// with data provided by a given solution.
17051719
bool isTypeReference(Expr *E) const;
@@ -2163,6 +2177,10 @@ class ConstraintSystem {
21632177
llvm::SmallMapVector<const CaseLabelItem *, CaseLabelItemInfo, 4>
21642178
caseLabelItems;
21652179

2180+
/// A map of expressions to the ExprPatterns that they are being solved as
2181+
/// a part of.
2182+
llvm::SmallMapVector<Expr *, ExprPattern *, 2> exprPatterns;
2183+
21662184
/// The set of parameters that have been inferred to be 'isolated'.
21672185
llvm::SmallSetVector<ParamDecl *, 2> isolatedParams;
21682186

@@ -2754,6 +2772,9 @@ class ConstraintSystem {
27542772
/// The length of \c caseLabelItems.
27552773
unsigned numCaseLabelItems;
27562774

2775+
/// The length of \c exprPatterns.
2776+
unsigned numExprPatterns;
2777+
27572778
/// The length of \c isolatedParams.
27582779
unsigned numIsolatedParams;
27592780

@@ -3175,6 +3196,15 @@ class ConstraintSystem {
31753196
caseLabelItems[item] = info;
31763197
}
31773198

3199+
/// Record a given ExprPattern as the parent of its sub-expression.
3200+
void setExprPatternFor(Expr *E, ExprPattern *EP) {
3201+
assert(E);
3202+
assert(EP);
3203+
auto inserted = exprPatterns.insert({E, EP}).second;
3204+
assert(inserted && "Mapping already defined?");
3205+
(void)inserted;
3206+
}
3207+
31783208
Optional<CaseLabelItemInfo> getCaseLabelItemInfo(
31793209
const CaseLabelItem *item) const {
31803210
auto known = caseLabelItems.find(item);
@@ -4299,6 +4329,11 @@ class ConstraintSystem {
42994329
/// \returns \c true if constraint generation failed, \c false otherwise
43004330
bool generateConstraints(SingleValueStmtExpr *E);
43014331

4332+
/// Generate constraints for an array of ExprPatterns, forming a conjunction
4333+
/// that solves each expression in turn.
4334+
void generateConstraints(ArrayRef<ExprPattern *> exprPatterns,
4335+
ConstraintLocatorBuilder locator);
4336+
43024337
/// Generate constraints for the given (unchecked) expression.
43034338
///
43044339
/// \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
@@ -8581,6 +8581,9 @@ namespace {
85818581
return Action::SkipChildren();
85828582
}
85838583

8584+
NullablePtr<Pattern>
8585+
rewritePattern(Pattern *pattern, DeclContext *DC);
8586+
85848587
/// Rewrite the target, producing a new target.
85858588
Optional<SyntacticElementTarget>
85868589
rewriteTarget(SyntacticElementTarget target);
@@ -8827,12 +8830,68 @@ static Expr *wrapAsyncLetInitializer(
88278830
return resultInit;
88288831
}
88298832

8833+
static Pattern *rewriteExprPattern(const SyntacticElementTarget &matchTarget,
8834+
Type patternTy,
8835+
RewriteTargetFn rewriteTarget) {
8836+
auto *EP = matchTarget.getExprPattern();
8837+
8838+
// See if we can simplify to another kind of pattern.
8839+
if (auto simplified = TypeChecker::trySimplifyExprPattern(EP, patternTy))
8840+
return simplified.get();
8841+
8842+
auto resultTarget = rewriteTarget(matchTarget);
8843+
if (!resultTarget)
8844+
return nullptr;
8845+
8846+
EP->setMatchExpr(resultTarget->getAsExpr());
8847+
EP->getMatchVar()->setInterfaceType(patternTy->mapTypeOutOfContext());
8848+
EP->setType(patternTy);
8849+
return EP;
8850+
}
8851+
8852+
/// Attempt to rewrite either an ExprPattern, or a pattern that was solved as
8853+
/// an ExprPattern, e.g an EnumElementPattern that could not refer to an enum
8854+
/// case.
8855+
static Optional<Pattern *>
8856+
tryRewriteExprPattern(Pattern *P, Solution &solution, Type patternTy,
8857+
RewriteTargetFn rewriteTarget) {
8858+
// See if we have a match expression target.
8859+
auto matchTarget = solution.getTargetFor(P);
8860+
if (!matchTarget)
8861+
return None;
8862+
8863+
return rewriteExprPattern(*matchTarget, patternTy, rewriteTarget);
8864+
}
8865+
8866+
NullablePtr<Pattern> ExprWalker::rewritePattern(Pattern *pattern,
8867+
DeclContext *DC) {
8868+
auto &solution = Rewriter.solution;
8869+
8870+
// Figure out the pattern type.
8871+
auto patternTy = solution.getResolvedType(pattern);
8872+
patternTy = patternTy->reconstituteSugar(/*recursive=*/false);
8873+
8874+
// Coerce the pattern to its appropriate type.
8875+
TypeResolutionOptions patternOptions(TypeResolverContext::InExpression);
8876+
patternOptions |= TypeResolutionFlags::OverrideType;
8877+
8878+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
8879+
return ::tryRewriteExprPattern(
8880+
EP, solution, ty, [&](auto target) { return rewriteTarget(target); });
8881+
};
8882+
8883+
auto contextualPattern = ContextualPattern::forRawPattern(pattern, DC);
8884+
return TypeChecker::coercePatternToType(contextualPattern, patternTy,
8885+
patternOptions, tryRewritePattern);
8886+
}
8887+
88308888
/// Apply the given solution to the initialization target.
88318889
///
88328890
/// \returns the resulting initialization expression.
88338891
static Optional<SyntacticElementTarget>
88348892
applySolutionToInitialization(Solution &solution, SyntacticElementTarget target,
8835-
Expr *initializer) {
8893+
Expr *initializer,
8894+
RewriteTargetFn rewriteTarget) {
88368895
auto wrappedVar = target.getInitializationWrappedVar();
88378896
Type initType;
88388897
if (wrappedVar) {
@@ -8897,10 +8956,14 @@ applySolutionToInitialization(Solution &solution, SyntacticElementTarget target,
88978956

88988957
finalPatternType = finalPatternType->reconstituteSugar(/*recursive =*/false);
88998958

8959+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
8960+
return ::tryRewriteExprPattern(EP, solution, ty, rewriteTarget);
8961+
};
8962+
89008963
// Apply the solution to the pattern as well.
89018964
auto contextualPattern = target.getContextualPattern();
89028965
if (auto coercedPattern = TypeChecker::coercePatternToType(
8903-
contextualPattern, finalPatternType, options)) {
8966+
contextualPattern, finalPatternType, options, tryRewritePattern)) {
89048967
resultTarget.setPattern(coercedPattern);
89058968
} else {
89068969
return None;
@@ -9047,10 +9110,15 @@ static Optional<SyntacticElementTarget> applySolutionToForEachStmt(
90479110
TypeResolutionOptions options(TypeResolverContext::ForEachStmt);
90489111
options |= TypeResolutionFlags::OverrideType;
90499112

9113+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
9114+
return ::tryRewriteExprPattern(EP, solution, ty, rewriteTarget);
9115+
};
9116+
90509117
// Apply the solution to the pattern as well.
90519118
auto contextualPattern = target.getContextualPattern();
90529119
auto coercedPattern = TypeChecker::coercePatternToType(
9053-
contextualPattern, forEachStmtInfo.initType, options);
9120+
contextualPattern, forEachStmtInfo.initType, options,
9121+
tryRewritePattern);
90549122
if (!coercedPattern)
90559123
return None;
90569124

@@ -9138,7 +9206,8 @@ ExprWalker::rewriteTarget(SyntacticElementTarget target) {
91389206
switch (target.getExprContextualTypePurpose()) {
91399207
case CTP_Initialization: {
91409208
auto initResultTarget = applySolutionToInitialization(
9141-
solution, target, rewrittenExpr);
9209+
solution, target, rewrittenExpr,
9210+
[&](auto target) { return rewriteTarget(target); });
91429211
if (!initResultTarget)
91439212
return None;
91449213

@@ -9229,47 +9298,11 @@ ExprWalker::rewriteTarget(SyntacticElementTarget target) {
92299298
ConstraintSystem &cs = solution.getConstraintSystem();
92309299
auto info = *cs.getCaseLabelItemInfo(*caseLabelItem);
92319300

9232-
// Figure out the pattern type.
9233-
Type patternType = solution.simplifyType(solution.getType(info.pattern));
9234-
patternType = patternType->reconstituteSugar(/*recursive=*/false);
9235-
9236-
// Check whether this enum element is resolved via ~= application.
9237-
if (auto *enumElement = dyn_cast<EnumElementPattern>(info.pattern)) {
9238-
if (auto target = cs.getTargetFor(enumElement)) {
9239-
auto *EP = target->getExprPattern();
9240-
auto enumType = solution.getResolvedType(EP);
9241-
9242-
auto *matchCall = target->getAsExpr();
9243-
9244-
auto *result = matchCall->walk(*this);
9245-
if (!result)
9246-
return None;
9247-
9248-
{
9249-
auto *matchVar = EP->getMatchVar();
9250-
matchVar->setInterfaceType(enumType->mapTypeOutOfContext());
9251-
}
9252-
9253-
EP->setMatchExpr(result);
9254-
EP->setType(enumType);
9255-
9256-
(*caseLabelItem)->setPattern(EP, /*resolved=*/true);
9257-
return target;
9258-
}
9259-
}
9260-
9261-
// Coerce the pattern to its appropriate type.
9262-
TypeResolutionOptions patternOptions(TypeResolverContext::InExpression);
9263-
patternOptions |= TypeResolutionFlags::OverrideType;
9264-
auto contextualPattern =
9265-
ContextualPattern::forRawPattern(info.pattern,
9266-
target.getDeclContext());
9267-
if (auto coercedPattern = TypeChecker::coercePatternToType(
9268-
contextualPattern, patternType, patternOptions)) {
9269-
(*caseLabelItem)->setPattern(coercedPattern, /*resolved=*/true);
9270-
} else {
9301+
auto pattern = rewritePattern(info.pattern, target.getDeclContext());
9302+
if (!pattern)
92719303
return None;
9272-
}
9304+
9305+
(*caseLabelItem)->setPattern(pattern.get(), /*resolved=*/true);
92739306

92749307
// If there is a guard expression, coerce that.
92759308
if (auto *guardExpr = info.guardExpr) {
@@ -9337,8 +9370,13 @@ ExprWalker::rewriteTarget(SyntacticElementTarget target) {
93379370
options |= TypeResolutionFlags::OverrideType;
93389371
}
93399372

9373+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
9374+
return ::tryRewriteExprPattern(
9375+
EP, solution, ty, [&](auto target) { return rewriteTarget(target); });
9376+
};
9377+
93409378
if (auto coercedPattern = TypeChecker::coercePatternToType(
9341-
contextualPattern, patternType, options)) {
9379+
contextualPattern, patternType, options, tryRewritePattern)) {
93429380
auto resultTarget = target;
93439381
resultTarget.setPattern(coercedPattern);
93449382
return resultTarget;

lib/Sema/CSGen.cpp

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2393,12 +2393,6 @@ namespace {
23932393
// function, to set the type of the pattern.
23942394
auto setType = [&](Type type) {
23952395
CS.setType(pattern, type);
2396-
if (auto PE = dyn_cast<ExprPattern>(pattern)) {
2397-
// Set the type of the pattern's sub-expression as well, so code
2398-
// completion can retrieve the expression's type in case it is a code
2399-
// completion token.
2400-
CS.setType(PE->getSubExpr(), type);
2401-
}
24022396
return type;
24032397
};
24042398

@@ -2816,15 +2810,12 @@ namespace {
28162810
return setType(patternType);
28172811
}
28182812

2819-
// Refutable patterns occur when checking the PatternBindingDecls in an
2820-
// if/let or while/let condition. They always require an initial value,
2821-
// so they always allow unspecified types.
2822-
case PatternKind::Expr:
2823-
// TODO: we could try harder here, e.g. for enum elements to provide the
2824-
// enum type.
2825-
return setType(
2826-
CS.createTypeVariable(
2827-
CS.getConstraintLocator(locator), TVO_CanBindToNoEscape));
2813+
case PatternKind::Expr: {
2814+
// We generate constraints for ExprPatterns in a separate pass. For
2815+
// now, just create a type variable.
2816+
return setType(CS.createTypeVariable(CS.getConstraintLocator(locator),
2817+
TVO_CanBindToNoEscape));
2818+
}
28282819
}
28292820

28302821
llvm_unreachable("Unhandled pattern kind");
@@ -4627,8 +4618,20 @@ Type ConstraintSystem::generateConstraints(
46274618
bool bindPatternVarsOneWay, PatternBindingDecl *patternBinding,
46284619
unsigned patternIndex) {
46294620
ConstraintGenerator cg(*this, nullptr);
4630-
return cg.getTypeForPattern(pattern, locator, bindPatternVarsOneWay,
4631-
patternBinding, patternIndex);
4621+
auto ty = cg.getTypeForPattern(pattern, locator, bindPatternVarsOneWay,
4622+
patternBinding, patternIndex);
4623+
assert(ty);
4624+
4625+
// Gather the ExprPatterns, and form a conjunction for their expressions.
4626+
SmallVector<ExprPattern *, 4> exprPatterns;
4627+
pattern->forEachNode([&](Pattern *P) {
4628+
if (auto *EP = dyn_cast<ExprPattern>(P))
4629+
exprPatterns.push_back(EP);
4630+
});
4631+
if (!exprPatterns.empty())
4632+
generateConstraints(exprPatterns, getConstraintLocator(pattern));
4633+
4634+
return ty;
46324635
}
46334636

46344637
bool ConstraintSystem::generateConstraints(StmtCondition condition,

0 commit comments

Comments
 (0)