Skip to content

[CSGen] Allow _ pattern to be a hole #60203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Aug 8, 2022
Merged
Show file tree
Hide file tree
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
25 changes: 14 additions & 11 deletions include/swift/Sema/CSFix.h
Original file line number Diff line number Diff line change
Expand Up @@ -298,9 +298,9 @@ enum class FixKind : uint8_t {
/// Ignore `ErrorExpr` or `ErrorType` during pre-check.
IgnoreInvalidASTNode,

/// Ignore a named pattern whose type we couldn't infer. This issue should
/// already have been diagnosed elsewhere.
IgnoreInvalidNamedPattern,
/// Ignore a named or `_` pattern whose type we couldn't infer.
/// This issue should already have been diagnosed elsewhere.
IgnoreUnresolvedPatternVar,

/// Resolve type of `nil` by providing a contextual type.
SpecifyContextualTypeForNil,
Expand Down Expand Up @@ -2287,6 +2287,10 @@ class UseRawValue final : public ConstraintFix {

bool diagnose(const Solution &solution, bool asNote = false) const override;

bool diagnoseForAmbiguity(CommonFixesArray commonFixes) const override {
return diagnose(*commonFixes.front().first);
}

static UseRawValue *create(ConstraintSystem &cs, Type rawReprType,
Type expectedType, ConstraintLocator *locator);

Expand Down Expand Up @@ -2746,10 +2750,10 @@ class IgnoreInvalidASTNode final : public ConstraintFix {
}
};

class IgnoreInvalidNamedPattern final : public ConstraintFix {
IgnoreInvalidNamedPattern(ConstraintSystem &cs, NamedPattern *pattern,
ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::IgnoreInvalidNamedPattern, locator) {}
class IgnoreUnresolvedPatternVar final : public ConstraintFix {
IgnoreUnresolvedPatternVar(ConstraintSystem &cs, Pattern *pattern,
ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::IgnoreUnresolvedPatternVar, locator) {}

public:
std::string getName() const override {
Expand All @@ -2762,12 +2766,11 @@ class IgnoreInvalidNamedPattern final : public ConstraintFix {
return diagnose(*commonFixes.front().first);
}

static IgnoreInvalidNamedPattern *create(ConstraintSystem &cs,
NamedPattern *pattern,
ConstraintLocator *locator);
static IgnoreUnresolvedPatternVar *
create(ConstraintSystem &cs, Pattern *pattern, ConstraintLocator *locator);

static bool classof(ConstraintFix *fix) {
return fix->getKind() == FixKind::IgnoreInvalidNamedPattern;
return fix->getKind() == FixKind::IgnoreUnresolvedPatternVar;
}
};

Expand Down
33 changes: 33 additions & 0 deletions include/swift/Sema/ConstraintLocator.h
Original file line number Diff line number Diff line change
Expand Up @@ -1076,6 +1076,39 @@ class LocatorPathElt::PatternBindingElement final
}
};

class LocatorPathElt::PatternDecl : public StoredIntegerElement<1> {
public:
PatternDecl(ConstraintLocator::PathElementKind kind)
: StoredIntegerElement(kind, /*placeholder=*/0) {
assert(classof(this) && "classof needs updating");
}

static bool classof(const LocatorPathElt *elt) {
return elt->getKind() == ConstraintLocator::NamedPatternDecl ||
elt->getKind() == ConstraintLocator::AnyPatternDecl;
}
};

class LocatorPathElt::NamedPatternDecl final
: public LocatorPathElt::PatternDecl {
public:
NamedPatternDecl() : PatternDecl(ConstraintLocator::NamedPatternDecl) {}

static bool classof(const LocatorPathElt *elt) {
return elt->getKind() == ConstraintLocator::NamedPatternDecl;
}
};

class LocatorPathElt::AnyPatternDecl final
: public LocatorPathElt::PatternDecl {
public:
AnyPatternDecl() : PatternDecl(ConstraintLocator::AnyPatternDecl) {}

static bool classof(const LocatorPathElt *elt) {
return elt->getKind() == ConstraintLocator::AnyPatternDecl;
}
};

namespace details {
template <typename CustomPathElement>
class PathElement {
Expand Down
8 changes: 6 additions & 2 deletions include/swift/Sema/ConstraintLocatorPathElts.def
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,12 @@ CUSTOM_LOCATOR_PATH_ELT(SyntacticElement)
/// The element of the pattern binding declaration.
CUSTOM_LOCATOR_PATH_ELT(PatternBindingElement)

/// The variable declared by a named pattern.
SIMPLE_LOCATOR_PATH_ELT(NamedPatternDecl)
/// A declaration introduced by a pattern: name (i.e. `x`) or `_`
ABSTRACT_LOCATOR_PATH_ELT(PatternDecl)
/// The variable declared by a named pattern.
CUSTOM_LOCATOR_PATH_ELT(NamedPatternDecl)
/// The anonymous variable declared by a `_` pattern.
CUSTOM_LOCATOR_PATH_ELT(AnyPatternDecl)

#undef LOCATOR_PATH_ELT
#undef CUSTOM_LOCATOR_PATH_ELT
Expand Down
2 changes: 1 addition & 1 deletion lib/Sema/BuilderTransform.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -758,7 +758,7 @@ class BuilderClosureVisitor
// If needed, generate constraints for everything in the case statement.
if (cs) {
auto locator = cs->getConstraintLocator(
subjectExpr, LocatorPathElt::ContextualType(CTP_Initialization));
subjectExpr, LocatorPathElt::ContextualType(CTP_CaseStmt));
Type subjectType = cs->getType(subjectExpr);

if (cs->generateConstraints(caseStmt, dc, subjectType, locator)) {
Expand Down
8 changes: 4 additions & 4 deletions lib/Sema/CSBindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ bool BindingSet::isDelayed() const {
// allows us to produce more specific errors because the type variable in
// the expression that introduced the placeholder might be diagnosable using
// fixForHole.
if (locator->isLastElement<LocatorPathElt::NamedPatternDecl>()) {
if (locator->isLastElement<LocatorPathElt::PatternDecl>()) {
return true;
}

Expand Down Expand Up @@ -2061,16 +2061,16 @@ TypeVariableBinding::fixForHole(ConstraintSystem &cs) const {
return std::make_pair(fix, /*impact=*/(unsigned)10);
}

if (auto pattern = getAsPattern<NamedPattern>(dstLocator->getAnchor())) {
if (auto pattern = getAsPattern(dstLocator->getAnchor())) {
if (dstLocator->getPath().size() == 1 &&
dstLocator->isLastElement<LocatorPathElt::NamedPatternDecl>()) {
dstLocator->isLastElement<LocatorPathElt::PatternDecl>()) {
// Not being able to infer the type of a variable in a pattern binding
// decl is more dramatic than anything that could happen inside the
// expression because we want to preferrably point the diagnostic to a
// part of the expression that caused us to be unable to infer the
// variable's type.
ConstraintFix *fix =
IgnoreInvalidNamedPattern::create(cs, pattern, dstLocator);
IgnoreUnresolvedPatternVar::create(cs, pattern, dstLocator);
return std::make_pair(fix, /*impact=*/(unsigned)100);
}
}
Expand Down
12 changes: 6 additions & 6 deletions lib/Sema/CSFix.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2004,18 +2004,18 @@ IgnoreResultBuilderWithReturnStmts::create(ConstraintSystem &cs, Type builderTy,
IgnoreResultBuilderWithReturnStmts(cs, builderTy, locator);
}

bool IgnoreInvalidNamedPattern::diagnose(const Solution &solution,
bool asNote) const {
bool IgnoreUnresolvedPatternVar::diagnose(const Solution &solution,
bool asNote) const {
// Not being able to infer the type of a pattern should already have been
// diagnosed on the pattern's initializer or as a structural issue of the AST.
return true;
}

IgnoreInvalidNamedPattern *
IgnoreInvalidNamedPattern::create(ConstraintSystem &cs, NamedPattern *pattern,
ConstraintLocator *locator) {
IgnoreUnresolvedPatternVar *
IgnoreUnresolvedPatternVar::create(ConstraintSystem &cs, Pattern *pattern,
ConstraintLocator *locator) {
return new (cs.getAllocator())
IgnoreInvalidNamedPattern(cs, pattern, locator);
IgnoreUnresolvedPatternVar(cs, pattern, locator);
}

bool SpecifyBaseTypeForOptionalUnresolvedMember::diagnose(
Expand Down
45 changes: 36 additions & 9 deletions lib/Sema/CSGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2265,9 +2265,11 @@ namespace {
->getUnderlyingType();
}

auto underlyingType =
getTypeForPattern(paren->getSubPattern(), locator,
externalPatternType, bindPatternVarsOneWay);
auto *subPattern = paren->getSubPattern();
auto underlyingType = getTypeForPattern(
subPattern,
locator.withPathElement(LocatorPathElt::PatternMatch(subPattern)),
externalPatternType, bindPatternVarsOneWay);

if (!underlyingType)
return Type();
Expand All @@ -2286,11 +2288,34 @@ namespace {
return setType(type);
}
case PatternKind::Any: {
return setType(
externalPatternType
? externalPatternType
: CS.createTypeVariable(CS.getConstraintLocator(locator),
TVO_CanBindToNoEscape));
Type type;

// If this is a situation like `[let] _ = <expr>`, return
// initializer expression.
auto getInitializerExpr = [&locator]() -> Expr * {
auto last = locator.last();
if (!last)
return nullptr;

auto contextualTy = last->getAs<LocatorPathElt::ContextualType>();
return (contextualTy && contextualTy->isFor(CTP_Initialization))
? locator.trySimplifyToExpr()
: nullptr;
};

// Always prefer a contextual type when it's available.
if (externalPatternType) {
type = externalPatternType;
} else if (auto *initializer = getInitializerExpr()) {
// For initialization always assume a type of initializer.
type = CS.getType(initializer)->getRValueType();
} else {
type = CS.createTypeVariable(
CS.getConstraintLocator(pattern,
ConstraintLocator::AnyPatternDecl),
TVO_CanBindToNoEscape | TVO_CanBindToHole);
}
return setType(type);
}

case PatternKind::Named: {
Expand Down Expand Up @@ -2671,7 +2696,9 @@ namespace {
// and we're matching the type of that subpattern to the parameter
// types.
Type subPatternType = getTypeForPattern(
subPattern, locator, Type(), bindPatternVarsOneWay);
subPattern,
locator.withPathElement(LocatorPathElt::PatternMatch(subPattern)),
Type(), bindPatternVarsOneWay);

if (!subPatternType)
return Type();
Expand Down
8 changes: 6 additions & 2 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7328,7 +7328,11 @@ ConstraintSystem::SolutionKind ConstraintSystem::simplifyConformsToConstraint(
TypeChecker::conformsToProtocol(rawValue, protocol,
DC->getParentModule())) {
auto *fix = UseRawValue::create(*this, type, protocolTy, loc);
return recordFix(fix) ? SolutionKind::Error : SolutionKind::Solved;
// Since this is a conformance requirement failure (where the
// source is most likely an argument), let's increase its impact
// to disambiguate vs. conversion failure of the same kind.
return recordFix(fix, /*impact=*/2) ? SolutionKind::Error
: SolutionKind::Solved;
}
}

Expand Down Expand Up @@ -12938,7 +12942,7 @@ ConstraintSystem::SolutionKind ConstraintSystem::simplifyFixConstraint(
case FixKind::IgnoreInvalidASTNode: {
return recordFix(fix, 10) ? SolutionKind::Error : SolutionKind::Solved;
}
case FixKind::IgnoreInvalidNamedPattern: {
case FixKind::IgnoreUnresolvedPatternVar: {
return recordFix(fix, 100) ? SolutionKind::Error : SolutionKind::Solved;
}

Expand Down
6 changes: 6 additions & 0 deletions lib/Sema/ConstraintLocator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ unsigned LocatorPathElt::getNewSummaryFlags() const {
case ConstraintLocator::PackElement:
case ConstraintLocator::PatternBindingElement:
case ConstraintLocator::NamedPatternDecl:
case ConstraintLocator::AnyPatternDecl:
return 0;

case ConstraintLocator::FunctionArgument:
Expand Down Expand Up @@ -447,6 +448,11 @@ void LocatorPathElt::dump(raw_ostream &out) const {
out << "named pattern decl";
break;
}

case ConstraintLocator::AnyPatternDecl: {
out << "'_' pattern decl";
break;
}
}
}

Expand Down
9 changes: 9 additions & 0 deletions lib/Sema/ConstraintSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5277,6 +5277,15 @@ void constraints::simplifyLocator(ASTNode &anchor,
break;
}

case ConstraintLocator::AnyPatternDecl: {
// This element is just a marker for `_` pattern since it doesn't
// have a declaration. We need to make sure that it only appaears
// when anchored on `AnyPattern`.
assert(getAsPattern<AnyPattern>(anchor));
path = path.slice(1);
break;
}

case ConstraintLocator::ImplicitConversion:
break;

Expand Down
1 change: 1 addition & 0 deletions test/Constraints/patterns.swift
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,7 @@ func rdar63510989() {
}

func test(e: E) {
if case .single(_) = e {} // Ok
if case .single(_ as Value) = e {} // Ok
if case .single(let v as Value) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
Expand Down
37 changes: 37 additions & 0 deletions test/Constraints/result_builder_diags.swift
Original file line number Diff line number Diff line change
Expand Up @@ -855,3 +855,40 @@ func test_invalid_result_is_diagnosed() {
S<Int>()
}
}

func test_associated_values_dont_block_solver_when_unresolved() {
@resultBuilder
struct Builder {
static func buildBlock<T>(_ t: T) -> T { t }
static func buildEither<T>(first: T) -> T { first }
static func buildEither<T>(second: T) -> T { second }
}

struct Value {
enum Kind {
case a(String)
case b
}

var kind: Kind
}

struct Container {
var prop: Value? = nil
}

struct TestWithAny {
var container: Container

@Builder var body: String {
let v = container.prop.kind // expected-error {{value of optional type 'Value?' must be unwrapped to refer to member 'kind' of wrapped base type 'Value'}}
// expected-note@-1 {{chain the optional using '?' to access member 'kind' only for non-'nil' base values}}
// expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}

switch v.kind { // expected-error {{value of type 'Value.Kind' has no member 'kind'}}
case .a(_): "a"
case .b: "b"
}
}
}
}
4 changes: 2 additions & 2 deletions test/Sema/enum_raw_representable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,10 @@ rdar32431165_2(42, E_32431165.bar)
// or constructing raw representable type from second, both ways are valid.
do {
E_32431165.bar == "bar"
// expected-error@-1 {{binary operator '==' cannot be applied to operands of type 'E_32431165' and 'String'}} expected-note@-1 {{partially matching parameter lists: (String, String)}}
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{17-17=.rawValue}}

"bar" == E_32431165.bar
// expected-error@-1 {{binary operator '==' cannot be applied to operands of type 'String' and 'E_32431165'}} expected-note@-1 {{partially matching parameter lists: (String, String)}}
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{26-26=.rawValue}}
}

func rdar32431165_overloaded() -> Int { 42 } // expected-note {{'rdar32431165_overloaded()' produces 'Int', not the expected contextual result type 'E_32431165'}}
Expand Down