Skip to content

[ConstraintSystem] Detect invalid implicit ref to initializer on non-… #22442

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
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
5 changes: 5 additions & 0 deletions lib/AST/Expr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,11 @@ bool Expr::isTypeReference(
continue;
}

if (auto *USE = dyn_cast<UnresolvedSpecializeExpr>(expr)) {
expr = USE->getSubExpr();
continue;
}

// Anything else is not statically derived.
return false;
} while (true);
Expand Down
26 changes: 6 additions & 20 deletions lib/Sema/CSApply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,7 @@ getImplicitMemberReferenceAccessSemantics(Expr *base, VarDecl *member,
/// This method could be used on not yet fully type-checked AST.
bool ConstraintSystem::isTypeReference(const Expr *E) {
return E->isTypeReference(
[&](const Expr *E) -> Type { return getType(E); },
[&](const Expr *E) -> Type { return simplifyType(getType(E)); },
[&](const Expr *E) -> Decl * {
if (auto *UDE = dyn_cast<UnresolvedDotExpr>(E)) {
return findResolvedMemberRef(
Expand All @@ -244,13 +244,17 @@ bool ConstraintSystem::isTypeReference(const Expr *E) {
getConstraintLocator(UME, ConstraintLocator::UnresolvedMember));
}

if (isa<OverloadSetRefExpr>(E))
return findResolvedMemberRef(
getConstraintLocator(const_cast<Expr *>(E)));

return nullptr;
});
}

bool ConstraintSystem::isStaticallyDerivedMetatype(const Expr *E) {
return E->isStaticallyDerivedMetatype(
[&](const Expr *E) -> Type { return getType(E); },
[&](const Expr *E) -> Type { return simplifyType(getType(E)); },
[&](const Expr *E) -> bool { return isTypeReference(E); });
}

Expand Down Expand Up @@ -7395,24 +7399,6 @@ Expr *ExprRewriter::finishApply(ApplyExpr *apply, Type openedType,
if (auto metaTy = cs.getType(fn)->getAs<AnyMetatypeType>()) {
auto ty = metaTy->getInstanceType();

if (!cs.isTypeReference(fn)) {
bool isExistentialType = false;
// If this is an attempt to initialize existential type.
if (auto metaType = cs.getType(fn)->getAs<MetatypeType>()) {
auto instanceType = metaType->getInstanceType();
isExistentialType = instanceType->isExistentialType();
}

if (!isExistentialType) {
// If the metatype value isn't a type expression,
// the user should reference '.init' explicitly, for clarity.
cs.TC
.diagnose(apply->getArg()->getStartLoc(),
diag::missing_init_on_metatype_initialization)
.fixItInsert(apply->getArg()->getStartLoc(), ".init");
}
}

// If we're "constructing" a tuple type, it's simply a conversion.
if (auto tupleTy = ty->getAs<TupleType>()) {
// FIXME: Need an AST to represent this properly.
Expand Down
8 changes: 8 additions & 0 deletions lib/Sema/CSDiagnostics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1530,3 +1530,11 @@ bool InitOnProtocolMetatypeFailure::diagnoseAsError() {

return true;
}

bool ImplicitInitOnNonConstMetatypeFailure::diagnoseAsError() {
auto *apply = cast<ApplyExpr>(getRawAnchor());
auto loc = apply->getArg()->getStartLoc();
emitDiagnostic(loc, diag::missing_init_on_metatype_initialization)
.fixItInsert(loc, ".init");
return true;
}
19 changes: 19 additions & 0 deletions lib/Sema/CSDiagnostics.h
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,25 @@ class InitOnProtocolMetatypeFailure final : public InvalidInitRefFailure {
bool diagnoseAsError() override;
};

/// Diagnose an attempt to construct an instance using non-constant
/// metatype base without explictly specifying `init`:
///
/// ```swift
/// let foo = Int.self
/// foo(0) // should be `foo.init(0)`
/// ```
class ImplicitInitOnNonConstMetatypeFailure final
: public InvalidInitRefFailure {
public:
ImplicitInitOnNonConstMetatypeFailure(Expr *root, ConstraintSystem &cs,
Type baseTy,
const ConstructorDecl *init,
ConstraintLocator *locator)
: InvalidInitRefFailure(root, cs, baseTy, init, SourceRange(), locator) {}

bool diagnoseAsError() override;
};

} // end namespace constraints
} // end namespace swift

Expand Down
14 changes: 14 additions & 0 deletions lib/Sema/CSFix.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,12 @@ bool AllowInvalidInitRef::diagnose(Expr *root, bool asNote) const {
getLocator());
return failure.diagnose(asNote);
}

case RefKind::NonConstMetatype: {
ImplicitInitOnNonConstMetatypeFailure failure(root, getConstraintSystem(),
BaseType, Init, getLocator());
return failure.diagnose(asNote);
}
}
}

Expand All @@ -308,6 +314,14 @@ AllowInvalidInitRef *AllowInvalidInitRef::onProtocolMetatype(
isStaticallyDerived, baseRange, locator);
}

AllowInvalidInitRef *
AllowInvalidInitRef::onNonConstMetatype(ConstraintSystem &cs, Type baseTy,
ConstructorDecl *init,
ConstraintLocator *locator) {
return create(RefKind::NonConstMetatype, cs, baseTy, init,
/*isStaticallyDerived=*/false, SourceRange(), locator);
}

AllowInvalidInitRef *
AllowInvalidInitRef::create(RefKind kind, ConstraintSystem &cs, Type baseTy,
ConstructorDecl *init, bool isStaticallyDerived,
Expand Down
11 changes: 10 additions & 1 deletion lib/Sema/CSFix.h
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,11 @@ class AllowInvalidPartialApplication final : public ConstraintFix {
};

class AllowInvalidInitRef final : public ConstraintFix {
enum class RefKind { DynamicOnMetatype, ProtocolMetatype } Kind;
enum class RefKind {
DynamicOnMetatype,
ProtocolMetatype,
NonConstMetatype,
} Kind;

Type BaseType;
const ConstructorDecl *Init;
Expand Down Expand Up @@ -573,6 +577,11 @@ class AllowInvalidInitRef final : public ConstraintFix {
bool isStaticallyDerived, SourceRange baseRange,
ConstraintLocator *locator);

static AllowInvalidInitRef *onNonConstMetatype(ConstraintSystem &cs,
Type baseTy,
ConstructorDecl *init,
ConstraintLocator *locator);

private:
static AllowInvalidInitRef *create(RefKind kind, ConstraintSystem &cs,
Type baseTy, ConstructorDecl *init,
Expand Down
10 changes: 10 additions & 0 deletions lib/Sema/ConstraintSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1752,6 +1752,16 @@ static void validateInitializerRef(ConstraintSystem &cs, ConstructorDecl *init,
} else if (auto *CE = dyn_cast<CallExpr>(anchor)) {
baseExpr = CE->getFn();
baseType = getType(baseExpr);
// If this is an initializer call without explicit mention
// of `.init` on metatype value.
if (auto *MTT = baseType->getAs<MetatypeType>()) {
auto instanceType = MTT->getInstanceType();
if (!cs.isTypeReference(baseExpr) && !instanceType->isExistentialType()) {
(void)cs.recordFix(AllowInvalidInitRef::onNonConstMetatype(
cs, baseType, init, locator));
return;
}
}
// Initializer reference which requires contextual base type e.g. `.init(...)`.
} else if (auto *UME = dyn_cast<UnresolvedMemberExpr>(anchor)) {
// We need to find type variable which represents contextual base.
Expand Down
5 changes: 5 additions & 0 deletions test/Constraints/construction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,8 @@ SR_5245(s: SR_5245.S(f: [.e1, .e2]))

// rdar://problem/34670592 - Compiler crash on heterogeneous collection literal
_ = Array([1, "hello"]) // Ok

func init_via_non_const_metatype(_ s1: S1.Type) {
_ = s1(i: 42) // expected-error {{initializing from a metatype value must reference 'init' explicitly}} {{9-9=.init}}
_ = s1.init(i: 42) // ok
}