Skip to content

Commit 43583f3

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 df89f75 commit 43583f3

23 files changed

+499
-147
lines changed

include/swift/Sema/ConstraintLocatorPathElts.def

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,9 @@ CUSTOM_LOCATOR_PATH_ELT(TernaryBranch)
222222
/// Performing a pattern patch.
223223
CUSTOM_LOCATOR_PATH_ELT(PatternMatch)
224224

225+
/// A conjunction for the ExprPatterns in a pattern.
226+
SIMPLE_LOCATOR_PATH_ELT(ExprPatternConjunction)
227+
225228
/// Points to a particular attribute associated with one of
226229
/// the arguments e.g. `inout` or its type e.g. `@escaping`.
227230
///

include/swift/Sema/ConstraintSystem.h

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -699,13 +699,27 @@ T *getAsStmt(ASTNode node) {
699699
return nullptr;
700700
}
701701

702+
template <typename T>
703+
bool isPattern(ASTNode node) {
704+
if (node.isNull() || !node.is<Pattern *>())
705+
return false;
706+
707+
auto *P = node.get<Pattern *>();
708+
return isa<T>(P);
709+
}
710+
702711
template <typename T = Pattern>
703712
T *getAsPattern(ASTNode node) {
704713
if (auto *P = node.dyn_cast<Pattern *>())
705714
return dyn_cast_or_null<T>(P);
706715
return nullptr;
707716
}
708717

718+
template <typename T = Pattern>
719+
T *castToPattern(ASTNode node) {
720+
return cast<T>(node.get<Pattern *>());
721+
}
722+
709723
template <typename T = Stmt> T *castToStmt(ASTNode node) {
710724
return cast<T>(node.get<Stmt *>());
711725
}
@@ -1515,6 +1529,10 @@ class Solution {
15151529
llvm::SmallMapVector<const CaseLabelItem *, CaseLabelItemInfo, 4>
15161530
caseLabelItems;
15171531

1532+
/// A map of expressions to the ExprPatterns that they are being solved as
1533+
/// a part of.
1534+
llvm::SmallMapVector<Expr *, ExprPattern *, 2> exprPatterns;
1535+
15181536
/// The set of parameters that have been inferred to be 'isolated'.
15191537
llvm::SmallVector<ParamDecl *, 2> isolatedParams;
15201538

@@ -1700,6 +1718,20 @@ class Solution {
17001718
: nullptr;
17011719
}
17021720

1721+
CaseLabelItemInfo getCaseLabelItemInfo(CaseLabelItem *labelItem) {
1722+
auto result = caseLabelItems.find(labelItem);
1723+
assert(result != caseLabelItems.end());
1724+
return result->second;
1725+
}
1726+
1727+
NullablePtr<ExprPattern> getExprPattern(Expr *E) const {
1728+
auto result = exprPatterns.find(E);
1729+
if (result == exprPatterns.end())
1730+
return nullptr;
1731+
1732+
return result->second;
1733+
}
1734+
17031735
/// This method implements functionality of `Expr::isTypeReference`
17041736
/// with data provided by a given solution.
17051737
bool isTypeReference(Expr *E) const;
@@ -2163,6 +2195,10 @@ class ConstraintSystem {
21632195
llvm::SmallMapVector<const CaseLabelItem *, CaseLabelItemInfo, 4>
21642196
caseLabelItems;
21652197

2198+
/// A map of expressions to the ExprPatterns that they are being solved as
2199+
/// a part of.
2200+
llvm::SmallMapVector<Expr *, ExprPattern *, 2> exprPatterns;
2201+
21662202
/// The set of parameters that have been inferred to be 'isolated'.
21672203
llvm::SmallSetVector<ParamDecl *, 2> isolatedParams;
21682204

@@ -2754,6 +2790,9 @@ class ConstraintSystem {
27542790
/// The length of \c caseLabelItems.
27552791
unsigned numCaseLabelItems;
27562792

2793+
/// The length of \c exprPatterns.
2794+
unsigned numExprPatterns;
2795+
27572796
/// The length of \c isolatedParams.
27582797
unsigned numIsolatedParams;
27592798

@@ -3175,6 +3214,14 @@ class ConstraintSystem {
31753214
caseLabelItems[item] = info;
31763215
}
31773216

3217+
void setExprPatternFor(Expr *E, ExprPattern *EP) {
3218+
assert(E);
3219+
assert(EP);
3220+
auto inserted = exprPatterns.insert({E, EP}).second;
3221+
assert(inserted && "Mapping already defined?");
3222+
(void)inserted;
3223+
}
3224+
31783225
Optional<CaseLabelItemInfo> getCaseLabelItemInfo(
31793226
const CaseLabelItem *item) const {
31803227
auto known = caseLabelItems.find(item);
@@ -4299,6 +4346,9 @@ class ConstraintSystem {
42994346
/// \returns \c true if constraint generation failed, \c false otherwise
43004347
bool generateConstraints(SingleValueStmtExpr *E);
43014348

4349+
void generateConstraints(ArrayRef<ExprPattern *> exprPatterns,
4350+
ConstraintLocatorBuilder locator);
4351+
43024352
/// Generate constraints for the given (unchecked) expression.
43034353
///
43044354
/// \returns a possibly-sanitized expression, or null if an error occurred.
@@ -4323,6 +4373,10 @@ class ConstraintSystem {
43234373
[[nodiscard]]
43244374
bool generateConstraints(StmtCondition condition, DeclContext *dc);
43254375

4376+
[[nodiscard]]
4377+
bool generateConstraints(CaseLabelItem *caseLabelItem, DeclContext *dc,
4378+
Type convertTy, ConstraintLocator *locator);
4379+
43264380
/// Generate constraints for a case statement.
43274381
///
43284382
/// \param subjectType The type of the "subject" expression in the enclosing

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.getExprPattern(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: 85 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -8574,6 +8574,9 @@ namespace {
85748574
return Action::SkipChildren();
85758575
}
85768576

8577+
NullablePtr<Pattern>
8578+
rewritePattern(Pattern *pattern, DeclContext *DC);
8579+
85778580
/// Rewrite the target, producing a new target.
85788581
Optional<SyntacticElementTarget>
85798582
rewriteTarget(SyntacticElementTarget target);
@@ -8820,12 +8823,68 @@ static Expr *wrapAsyncLetInitializer(
88208823
return resultInit;
88218824
}
88228825

8826+
static Pattern *rewriteExprPattern(SyntacticElementTarget matchTarget,
8827+
Type patternTy,
8828+
RewriteTargetFn rewriteTarget) {
8829+
auto *EP = matchTarget.getExprPattern();
8830+
8831+
// See if we can simplify to another kind of pattern.
8832+
if (auto simplified = TypeChecker::trySimplifyExprPattern(EP, patternTy))
8833+
return simplified.get();
8834+
8835+
auto resultTarget = rewriteTarget(matchTarget);
8836+
if (!resultTarget)
8837+
return nullptr;
8838+
8839+
matchTarget = *resultTarget;
8840+
8841+
EP->setMatchExpr(matchTarget.getAsExpr());
8842+
EP->getMatchVar()->setInterfaceType(patternTy->mapTypeOutOfContext());
8843+
EP->setType(patternTy);
8844+
return EP;
8845+
}
8846+
8847+
static Optional<Pattern *>
8848+
tryRewriteExprPattern(Pattern *P, Solution &solution, Type patternTy,
8849+
RewriteTargetFn rewriteTarget) {
8850+
// We may either have an ExprPattern, or a pattern that was mapped to an
8851+
// ExprPattern, such as an EnumElementPattern.
8852+
auto matchTarget = solution.getTargetFor(P);
8853+
if (!matchTarget)
8854+
return None;
8855+
8856+
return rewriteExprPattern(*matchTarget, patternTy, rewriteTarget);
8857+
}
8858+
8859+
NullablePtr<Pattern> ExprWalker::rewritePattern(Pattern *pattern,
8860+
DeclContext *DC) {
8861+
auto &solution = Rewriter.solution;
8862+
8863+
// Figure out the pattern type.
8864+
auto patternTy = solution.getResolvedType(pattern);
8865+
patternTy = patternTy->reconstituteSugar(/*recursive=*/false);
8866+
8867+
// Coerce the pattern to its appropriate type.
8868+
TypeResolutionOptions patternOptions(TypeResolverContext::InExpression);
8869+
patternOptions |= TypeResolutionFlags::OverrideType;
8870+
8871+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
8872+
return ::tryRewriteExprPattern(
8873+
EP, solution, ty, [&](auto target) { return rewriteTarget(target); });
8874+
};
8875+
8876+
auto contextualPattern = ContextualPattern::forRawPattern(pattern, DC);
8877+
return TypeChecker::coercePatternToType(contextualPattern, patternTy,
8878+
patternOptions, tryRewritePattern);
8879+
}
8880+
88238881
/// Apply the given solution to the initialization target.
88248882
///
88258883
/// \returns the resulting initialization expression.
88268884
static Optional<SyntacticElementTarget>
88278885
applySolutionToInitialization(Solution &solution, SyntacticElementTarget target,
8828-
Expr *initializer) {
8886+
Expr *initializer,
8887+
RewriteTargetFn rewriteTarget) {
88298888
auto wrappedVar = target.getInitializationWrappedVar();
88308889
Type initType;
88318890
if (wrappedVar) {
@@ -8890,10 +8949,15 @@ applySolutionToInitialization(Solution &solution, SyntacticElementTarget target,
88908949

88918950
finalPatternType = finalPatternType->reconstituteSugar(/*recursive =*/false);
88928951

8952+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
8953+
return ::tryRewriteExprPattern(
8954+
EP, solution, ty, [&](auto target) { return rewriteTarget(target); });
8955+
};
8956+
88938957
// Apply the solution to the pattern as well.
88948958
auto contextualPattern = target.getContextualPattern();
88958959
if (auto coercedPattern = TypeChecker::coercePatternToType(
8896-
contextualPattern, finalPatternType, options)) {
8960+
contextualPattern, finalPatternType, options, tryRewritePattern)) {
88978961
resultTarget.setPattern(coercedPattern);
88988962
} else {
88998963
return None;
@@ -9040,10 +9104,16 @@ static Optional<SyntacticElementTarget> applySolutionToForEachStmt(
90409104
TypeResolutionOptions options(TypeResolverContext::ForEachStmt);
90419105
options |= TypeResolutionFlags::OverrideType;
90429106

9107+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
9108+
return ::tryRewriteExprPattern(
9109+
EP, solution, ty, [&](auto target) { return rewriteTarget(target); });
9110+
};
9111+
90439112
// Apply the solution to the pattern as well.
90449113
auto contextualPattern = target.getContextualPattern();
90459114
auto coercedPattern = TypeChecker::coercePatternToType(
9046-
contextualPattern, forEachStmtInfo.initType, options);
9115+
contextualPattern, forEachStmtInfo.initType, options,
9116+
tryRewritePattern);
90479117
if (!coercedPattern)
90489118
return None;
90499119

@@ -9131,7 +9201,8 @@ ExprWalker::rewriteTarget(SyntacticElementTarget target) {
91319201
switch (target.getExprContextualTypePurpose()) {
91329202
case CTP_Initialization: {
91339203
auto initResultTarget = applySolutionToInitialization(
9134-
solution, target, rewrittenExpr);
9204+
solution, target, rewrittenExpr,
9205+
[&](auto target) { return rewriteTarget(target); });
91359206
if (!initResultTarget)
91369207
return None;
91379208

@@ -9222,47 +9293,11 @@ ExprWalker::rewriteTarget(SyntacticElementTarget target) {
92229293
ConstraintSystem &cs = solution.getConstraintSystem();
92239294
auto info = *cs.getCaseLabelItemInfo(*caseLabelItem);
92249295

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

92679302
// If there is a guard expression, coerce that.
92689303
if (auto *guardExpr = info.guardExpr) {
@@ -9330,8 +9365,13 @@ ExprWalker::rewriteTarget(SyntacticElementTarget target) {
93309365
options |= TypeResolutionFlags::OverrideType;
93319366
}
93329367

9368+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
9369+
return ::tryRewriteExprPattern(
9370+
EP, solution, ty, [&](auto target) { return rewriteTarget(target); });
9371+
};
9372+
93339373
if (auto coercedPattern = TypeChecker::coercePatternToType(
9334-
contextualPattern, patternType, options)) {
9374+
contextualPattern, patternType, options, tryRewritePattern)) {
93359375
auto resultTarget = target;
93369376
resultTarget.setPattern(coercedPattern);
93379377
return resultTarget;

0 commit comments

Comments
 (0)