Skip to content

Commit e63ea98

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 1cfdf95 commit e63ea98

20 files changed

+465
-146
lines changed

include/swift/Sema/ConstraintSystem.h

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -706,6 +706,11 @@ T *getAsPattern(ASTNode node) {
706706
return nullptr;
707707
}
708708

709+
template <typename T = Pattern>
710+
T *castToPattern(ASTNode node) {
711+
return cast<T>(node.get<Pattern *>());
712+
}
713+
709714
template <typename T = Stmt> T *castToStmt(ASTNode node) {
710715
return cast<T>(node.get<Stmt *>());
711716
}
@@ -1515,6 +1520,10 @@ class Solution {
15151520
llvm::SmallMapVector<const CaseLabelItem *, CaseLabelItemInfo, 4>
15161521
caseLabelItems;
15171522

1523+
/// A map of expressions to the ExprPatterns that they are being solved as
1524+
/// a part of.
1525+
llvm::SmallMapVector<Expr *, ExprPattern *, 2> exprPatterns;
1526+
15181527
/// The set of parameters that have been inferred to be 'isolated'.
15191528
llvm::SmallVector<ParamDecl *, 2> isolatedParams;
15201529

@@ -1700,6 +1709,16 @@ class Solution {
17001709
: nullptr;
17011710
}
17021711

1712+
/// Retrieve the solved ExprPattern that corresponds to provided
1713+
/// sub-expression.
1714+
NullablePtr<ExprPattern> getExprPatternFor(Expr *E) const {
1715+
auto result = exprPatterns.find(E);
1716+
if (result == exprPatterns.end())
1717+
return nullptr;
1718+
1719+
return result->second;
1720+
}
1721+
17031722
/// This method implements functionality of `Expr::isTypeReference`
17041723
/// with data provided by a given solution.
17051724
bool isTypeReference(Expr *E) const;
@@ -2163,6 +2182,10 @@ class ConstraintSystem {
21632182
llvm::SmallMapVector<const CaseLabelItem *, CaseLabelItemInfo, 4>
21642183
caseLabelItems;
21652184

2185+
/// A map of expressions to the ExprPatterns that they are being solved as
2186+
/// a part of.
2187+
llvm::SmallMapVector<Expr *, ExprPattern *, 2> exprPatterns;
2188+
21662189
/// The set of parameters that have been inferred to be 'isolated'.
21672190
llvm::SmallSetVector<ParamDecl *, 2> isolatedParams;
21682191

@@ -2754,6 +2777,9 @@ class ConstraintSystem {
27542777
/// The length of \c caseLabelItems.
27552778
unsigned numCaseLabelItems;
27562779

2780+
/// The length of \c exprPatterns.
2781+
unsigned numExprPatterns;
2782+
27572783
/// The length of \c isolatedParams.
27582784
unsigned numIsolatedParams;
27592785

@@ -3175,6 +3201,15 @@ class ConstraintSystem {
31753201
caseLabelItems[item] = info;
31763202
}
31773203

3204+
/// Record a given ExprPattern as the parent of its sub-expression.
3205+
void setExprPatternFor(Expr *E, ExprPattern *EP) {
3206+
assert(E);
3207+
assert(EP);
3208+
auto inserted = exprPatterns.insert({E, EP}).second;
3209+
assert(inserted && "Mapping already defined?");
3210+
(void)inserted;
3211+
}
3212+
31783213
Optional<CaseLabelItemInfo> getCaseLabelItemInfo(
31793214
const CaseLabelItem *item) const {
31803215
auto known = caseLabelItems.find(item);
@@ -4299,6 +4334,11 @@ class ConstraintSystem {
42994334
/// \returns \c true if constraint generation failed, \c false otherwise
43004335
bool generateConstraints(SingleValueStmtExpr *E);
43014336

4337+
/// Generate constraints for an array of ExprPatterns, forming a conjunction
4338+
/// that solves each expression in turn.
4339+
void generateConstraints(ArrayRef<ExprPattern *> exprPatterns,
4340+
ConstraintLocatorBuilder locator);
4341+
43024342
/// Generate constraints for the given (unchecked) expression.
43034343
///
43044344
/// \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
@@ -8582,6 +8582,9 @@ namespace {
85828582
return Action::SkipChildren();
85838583
}
85848584

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

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

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

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

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

@@ -9139,7 +9207,8 @@ ExprWalker::rewriteTarget(SyntacticElementTarget target) {
91399207
switch (target.getExprContextualTypePurpose()) {
91409208
case CTP_Initialization: {
91419209
auto initResultTarget = applySolutionToInitialization(
9142-
solution, target, rewrittenExpr);
9210+
solution, target, rewrittenExpr,
9211+
[&](auto target) { return rewriteTarget(target); });
91439212
if (!initResultTarget)
91449213
return None;
91459214

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

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

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

9374+
auto tryRewritePattern = [&](Pattern *EP, Type ty) {
9375+
return ::tryRewriteExprPattern(
9376+
EP, solution, ty, [&](auto target) { return rewriteTarget(target); });
9377+
};
9378+
93419379
if (auto coercedPattern = TypeChecker::coercePatternToType(
9342-
contextualPattern, patternType, options)) {
9380+
contextualPattern, patternType, options, tryRewritePattern)) {
93439381
auto resultTarget = target;
93449382
resultTarget.setPattern(coercedPattern);
93459383
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)