Skip to content

Push FunctionTypeRepr Input Invariants Up #17191

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 2 commits into from
Jun 15, 2018
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
3 changes: 3 additions & 0 deletions include/swift/AST/DiagnosticsCommon.def
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,9 @@ ERROR(generic_signature_not_minimal,none,
ERROR(attr_only_on_parameters, none,
"'%0' may only be used on parameters", (StringRef))

ERROR(function_type_no_parens,none,
"single argument function types require parentheses", ())

#ifndef DIAG_NO_UNDEF
# if defined(DIAG)
# undef DIAG
Expand Down
2 changes: 0 additions & 2 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -3465,8 +3465,6 @@ ERROR(objc_invalid_with_generic_params,none,
ERROR(objc_convention_invalid,none,
"%0 is not representable in Objective-C, so it cannot be used"
" with '@convention(%1)'", (Type, StringRef))
ERROR(function_type_no_parens,none,
"single argument function types require parentheses", ())
WARNING(paren_void_probably_void,none,
"when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?", ())
NOTE(not_objc_empty_protocol_composition,none,
Expand Down
13 changes: 8 additions & 5 deletions include/swift/AST/TypeRepr.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ namespace swift {
class DeclContext;
class GenericEnvironment;
class IdentTypeRepr;
class TupleTypeRepr;
class TypeDecl;

enum class TypeReprKind : uint8_t {
Expand Down Expand Up @@ -467,21 +468,23 @@ inline IdentTypeRepr::ComponentRange IdentTypeRepr::getComponentRange() {

/// \brief A function type.
/// \code
/// Foo -> Bar
/// (Foo) -> Bar
/// (Foo, Bar) -> Baz
/// (x: Foo, y: Bar) -> Baz
/// \endcode
class FunctionTypeRepr : public TypeRepr {
// These three are only used in SIL mode, which is the only time
// we can have polymorphic function values.
GenericParamList *GenericParams;
GenericEnvironment *GenericEnv;

TypeRepr *ArgsTy;
TupleTypeRepr *ArgsTy;
TypeRepr *RetTy;
SourceLoc ArrowLoc;
SourceLoc ThrowsLoc;

public:
FunctionTypeRepr(GenericParamList *genericParams, TypeRepr *argsTy,
FunctionTypeRepr(GenericParamList *genericParams, TupleTypeRepr *argsTy,
SourceLoc throwsLoc, SourceLoc arrowLoc, TypeRepr *retTy)
: TypeRepr(TypeReprKind::Function),
GenericParams(genericParams),
Expand All @@ -498,7 +501,7 @@ class FunctionTypeRepr : public TypeRepr {
GenericEnv = genericEnv;
}

TypeRepr *getArgsTypeRepr() const { return ArgsTy; }
TupleTypeRepr *getArgsTypeRepr() const { return ArgsTy; }
TypeRepr *getResultTypeRepr() const { return RetTy; }
bool throws() const { return ThrowsLoc.isValid(); }

Expand All @@ -511,7 +514,7 @@ class FunctionTypeRepr : public TypeRepr {
static bool classof(const FunctionTypeRepr *T) { return true; }

private:
SourceLoc getStartLocImpl() const { return ArgsTy->getStartLoc(); }
SourceLoc getStartLocImpl() const;
SourceLoc getEndLocImpl() const { return RetTy->getEndLoc(); }
SourceLoc getLocImpl() const { return ArrowLoc; }

Expand Down
15 changes: 10 additions & 5 deletions lib/AST/TypeRepr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,12 @@ TypeRepr *CloneVisitor::visitCompoundIdentTypeRepr(CompoundIdentTypeRepr *T) {
}

TypeRepr *CloneVisitor::visitFunctionTypeRepr(FunctionTypeRepr *T) {
return new (Ctx) FunctionTypeRepr(/*FIXME: Clone?*/T->getGenericParams(),
visit(T->getArgsTypeRepr()),
T->getThrowsLoc(),
T->getArrowLoc(),
visit(T->getResultTypeRepr()));
return new (Ctx) FunctionTypeRepr(
/*FIXME: Clone?*/T->getGenericParams(),
cast<TupleTypeRepr>(visit(T->getArgsTypeRepr())),
T->getThrowsLoc(),
T->getArrowLoc(),
visit(T->getResultTypeRepr()));
}

TypeRepr *CloneVisitor::visitArrayTypeRepr(ArrayTypeRepr *T) {
Expand Down Expand Up @@ -478,6 +479,10 @@ SILBoxTypeRepr *SILBoxTypeRepr::create(ASTContext &C,
ArgLAngleLoc, GenericArgs, ArgRAngleLoc);
}

SourceLoc FunctionTypeRepr::getStartLocImpl() const {
return ArgsTy->getStartLoc();
}

SourceLoc SILBoxTypeRepr::getStartLocImpl() const {
if (GenericParams && GenericParams->getSourceRange().isValid())
return GenericParams->getSourceRange().Start;
Expand Down
46 changes: 27 additions & 19 deletions lib/Parse/ParseType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,24 +44,6 @@ TypeRepr *Parser::applyAttributeToType(TypeRepr *ty,

// Apply 'inout' or '__shared' or '__owned'
if (specifierLoc.isValid()) {
if (auto *fnTR = dyn_cast<FunctionTypeRepr>(ty)) {
// If the input to the function isn't parenthesized, apply the inout
// to the first (only) parameter, as we would in Swift 2. (This
// syntax is deprecated in Swift 3.)
TypeRepr *argsTR = fnTR->getArgsTypeRepr();
if (!isa<TupleTypeRepr>(argsTR)) {
auto *newArgsTR =
new (Context) InOutTypeRepr(argsTR, specifierLoc);
auto *newTR =
new (Context) FunctionTypeRepr(fnTR->getGenericParams(),
newArgsTR,
fnTR->getThrowsLoc(),
fnTR->getArrowLoc(),
fnTR->getResultTypeRepr());
newTR->setGenericEnvironment(fnTR->getGenericEnvironment());
return newTR;
}
}
switch (specifier) {
case VarDecl::Specifier::Owned:
ty = new (Context) OwnedTypeRepr(ty, specifierLoc);
Expand Down Expand Up @@ -461,7 +443,33 @@ ParserResult<TypeRepr> Parser::parseType(Diag<> MessageID,
}
SyntaxContext->addSyntax(Builder.build());
}
tyR = new (Context) FunctionTypeRepr(generics, tyR, throwsLoc, arrowLoc,

TupleTypeRepr *argsTyR = nullptr;
if (auto *TTArgs = dyn_cast<TupleTypeRepr>(tyR)) {
argsTyR = TTArgs;
} else {
bool isVoid = false;
if (const auto Void = dyn_cast<SimpleIdentTypeRepr>(tyR)) {
if (Void->getIdentifier().str() == "Void") {
isVoid = true;
}
}

if (isVoid) {
diagnose(tyR->getStartLoc(), diag::function_type_no_parens)
.fixItReplace(tyR->getStartLoc(), "()");
argsTyR = TupleTypeRepr::createEmpty(Context, tyR->getSourceRange());
} else {
diagnose(tyR->getStartLoc(), diag::function_type_no_parens)
.highlight(tyR->getSourceRange())
.fixItInsert(tyR->getStartLoc(), "(")
.fixItInsertAfter(tyR->getEndLoc(), ")");
argsTyR = TupleTypeRepr::create(Context, {tyR},
tyR->getSourceRange());
}
}

tyR = new (Context) FunctionTypeRepr(generics, argsTyR, throwsLoc, arrowLoc,
SecondHalf.get());
} else if (generics) {
// Only function types may be generic.
Expand Down
55 changes: 52 additions & 3 deletions lib/Sema/TypeCheckConstraints.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1474,6 +1474,53 @@ TypeExpr *PreCheckExpression::simplifyTypeExpr(Expr *E) {
if (auto *AE = dyn_cast<ArrowExpr>(E)) {
if (!AE->isFolded()) return nullptr;

auto diagnoseMissingParens = [](TypeChecker &TC, TypeRepr *tyR) {
bool isVoid = false;
if (const auto Void = dyn_cast<SimpleIdentTypeRepr>(tyR)) {
if (Void->getIdentifier().str() == "Void") {
isVoid = true;
}
}

if (isVoid) {
TC.diagnose(tyR->getStartLoc(), diag::function_type_no_parens)
.fixItReplace(tyR->getStartLoc(), "()");
} else {
TC.diagnose(tyR->getStartLoc(), diag::function_type_no_parens)
.highlight(tyR->getSourceRange())
.fixItInsert(tyR->getStartLoc(), "(")
.fixItInsertAfter(tyR->getEndLoc(), ")");
}
};

auto extractInputTypeRepr = [&](Expr *E) -> TupleTypeRepr * {
if (!E)
return nullptr;
if (auto *TyE = dyn_cast<TypeExpr>(E)) {
auto ArgRepr = TyE->getTypeRepr();
if (auto *TTyRepr = dyn_cast<TupleTypeRepr>(ArgRepr))
return TTyRepr;
diagnoseMissingParens(TC, ArgRepr);
return TupleTypeRepr::create(TC.Context, {ArgRepr},
ArgRepr->getSourceRange());
}
if (auto *TE = dyn_cast<TupleExpr>(E))
if (TE->getNumElements() == 0)
return TupleTypeRepr::createEmpty(TC.Context, TE->getSourceRange());

// When simplifying a type expr like "(P1 & P2) -> (P3 & P4) -> Int",
// it may have been folded at the same time; recursively simplify it.
if (auto ArgsTypeExpr = simplifyTypeExpr(E)) {
auto ArgRepr = ArgsTypeExpr->getTypeRepr();
if (auto *TTyRepr = dyn_cast<TupleTypeRepr>(ArgRepr))
return TTyRepr;
diagnoseMissingParens(TC, ArgRepr);
return TupleTypeRepr::create(TC.Context, {ArgRepr},
ArgRepr->getSourceRange());
}
return nullptr;
};

auto extractTypeRepr = [&](Expr *E) -> TypeRepr * {
if (!E)
return nullptr;
Expand All @@ -1490,12 +1537,14 @@ TypeExpr *PreCheckExpression::simplifyTypeExpr(Expr *E) {
return nullptr;
};

TypeRepr *ArgsTypeRepr = extractTypeRepr(AE->getArgsExpr());
TupleTypeRepr *ArgsTypeRepr = extractInputTypeRepr(AE->getArgsExpr());
if (!ArgsTypeRepr) {
TC.diagnose(AE->getArgsExpr()->getLoc(),
diag::expected_type_before_arrow);
ArgsTypeRepr =
new (TC.Context) ErrorTypeRepr(AE->getArgsExpr()->getSourceRange());
auto ArgRange = AE->getArgsExpr()->getSourceRange();
auto ErrRepr =
new (TC.Context) ErrorTypeRepr(ArgRange);
ArgsTypeRepr = TupleTypeRepr::create(TC.Context, {ErrRepr}, ArgRange);
}

TypeRepr *ResultTypeRepr = extractTypeRepr(AE->getResultExpr());
Expand Down
78 changes: 22 additions & 56 deletions lib/Sema/TypeCheckType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2032,7 +2032,7 @@ Type TypeResolver::resolveAttributedType(TypeAttributes &attrs,
attrs.clearAttribute(TAK_autoclosure);
}

auto *FuncTyInput = dyn_cast<TupleTypeRepr>(fnRepr->getArgsTypeRepr());
auto *FuncTyInput = fnRepr->getArgsTypeRepr();
if ((!FuncTyInput || FuncTyInput->getNumElements() != 0)
&& attrs.has(TAK_autoclosure)) {
TC.diagnose(attrs.getLoc(TAK_autoclosure),
Expand Down Expand Up @@ -2206,43 +2206,18 @@ Type TypeResolver::resolveASTFunctionType(FunctionTypeRepr *repr,

// If this is a function type without parens around the parameter list,
// diagnose this and produce a fixit to add them.
if (!isa<TupleTypeRepr>(repr->getArgsTypeRepr()) &&
!repr->isWarnedAbout()) {
auto args = repr->getArgsTypeRepr();

bool isVoid = false;
if (const auto Void = dyn_cast<SimpleIdentTypeRepr>(args)) {
if (Void->getIdentifier().str() == "Void") {
isVoid = true;
}
}
if (isVoid) {
TC.diagnose(args->getStartLoc(), diag::function_type_no_parens)
.fixItReplace(args->getStartLoc(), "()");
} else {
TC.diagnose(args->getStartLoc(), diag::function_type_no_parens)
.highlight(args->getSourceRange())
.fixItInsert(args->getStartLoc(), "(")
.fixItInsertAfter(args->getEndLoc(), ")");
}

// Don't emit this warning three times when in generics.
repr->setWarned();
} else if (isa<TupleTypeRepr>(repr->getArgsTypeRepr()) &&
!repr->isWarnedAbout()) {
if (!repr->isWarnedAbout()) {
// If someone wrote (Void) -> () in Swift 3, they probably meant
// () -> (), but (Void) -> () is (()) -> () so emit a warning
// asking if they meant () -> ().
auto args = repr->getArgsTypeRepr();
if (const auto Tuple = dyn_cast<TupleTypeRepr>(args)) {
if (Tuple->getNumElements() == 1) {
if (const auto Void =
dyn_cast<SimpleIdentTypeRepr>(Tuple->getElementType(0))) {
if (Void->getIdentifier().str() == "Void") {
TC.diagnose(args->getStartLoc(), diag::paren_void_probably_void)
.fixItReplace(args->getSourceRange(), "()");
repr->setWarned();
}
if (args->getNumElements() == 1) {
if (const auto Void =
dyn_cast<SimpleIdentTypeRepr>(args->getElementType(0))) {
if (Void->getIdentifier().str() == "Void") {
TC.diagnose(args->getStartLoc(), diag::paren_void_probably_void)
.fixItReplace(args->getSourceRange(), "()");
repr->setWarned();
}
}
}
Expand Down Expand Up @@ -2390,29 +2365,20 @@ Type TypeResolver::resolveSILFunctionType(FunctionTypeRepr *repr,
&*resolveSILFunctionGenericParams);
}

if (auto tuple = dyn_cast<TupleTypeRepr>(repr->getArgsTypeRepr())) {
// SIL functions cannot be variadic.
if (tuple->hasEllipsis()) {
TC.diagnose(tuple->getEllipsisLoc(), diag::sil_function_ellipsis);
}
// SIL functions cannot have parameter names.
for (auto &element : tuple->getElements()) {
if (element.UnderscoreLoc.isValid())
TC.diagnose(element.UnderscoreLoc, diag::sil_function_input_label);
}

for (auto elt : tuple->getElements()) {
auto param = resolveSILParameter(elt.Type,
options | TypeResolutionFlags::ImmediateFunctionInput);
params.push_back(param);
if (!param.getType()) return nullptr;
auto argsTuple = repr->getArgsTypeRepr();
// SIL functions cannot be variadic.
if (argsTuple->hasEllipsis()) {
TC.diagnose(argsTuple->getEllipsisLoc(), diag::sil_function_ellipsis);
}
// SIL functions cannot have parameter names.
for (auto &element : argsTuple->getElements()) {
if (element.UnderscoreLoc.isValid())
TC.diagnose(element.UnderscoreLoc, diag::sil_function_input_label);
}

if (param.getType()->hasError())
hasError = true;
}
} else {
SILParameterInfo param = resolveSILParameter(repr->getArgsTypeRepr(),
options | TypeResolutionFlags::ImmediateFunctionInput);
for (auto elt : argsTuple->getElements()) {
auto param = resolveSILParameter(elt.Type,
options | TypeResolutionFlags::ImmediateFunctionInput);
params.push_back(param);
if (!param.getType()) return nullptr;

Expand Down
2 changes: 1 addition & 1 deletion test/IDE/complete_crashes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ func flip<A, B, C>(_ f: A -> B -> C) -> B -> A -> C { }
func rdar22688199() {
let f = flip(curried)(#^RDAR_22688199^#
}
// FLIP_CURRIED: Pattern/CurrModule: ['(']{#Int#}, {#Int#}[')'][#(Int) -> ()#]
// FLIP_CURRIED: Pattern/CurrModule: ['(']{#(Int, Int)#}[')'][#(Int) -> ()#]

// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=RDAR_22836263
func rdar22836263() {
Expand Down
4 changes: 2 additions & 2 deletions test/IRGen/bridge_object_arm64.sil
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ entry(%c : $C, %w : $Builtin.Word):
// CHECK: br label %tagged-cont
// CHECK: tagged-cont:
// CHECK: phi [[C]] [ [[TAGGED_RESULT]], %tagged-pointer ], [ [[MASKED_RESULT]], %not-tagged-pointer ]
sil @convert_from_bridge_object : $Builtin.BridgeObject -> (ObjC, Builtin.Word) {
sil @convert_from_bridge_object : $(Builtin.BridgeObject) -> (ObjC, Builtin.Word) {
entry(%b : $Builtin.BridgeObject):
%c = bridge_object_to_ref %b : $Builtin.BridgeObject to $ObjC
%w = bridge_object_to_word %b : $Builtin.BridgeObject to $Builtin.Word
%t = tuple (%c : $ObjC, %w : $Builtin.Word)
return %t : $(ObjC, Builtin.Word)
}

sil @convert_from_native_bridge_object : $Builtin.BridgeObject -> C {
sil @convert_from_native_bridge_object : $(Builtin.BridgeObject) -> C {
entry(%b : $Builtin.BridgeObject):
%c = bridge_object_to_ref %b : $Builtin.BridgeObject to $C
return %c : $C
Expand Down
4 changes: 2 additions & 2 deletions test/IRGen/bridge_object_armv7.sil
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,15 @@ entry(%c : $C, %w : $Builtin.Word):
// CHECK: [[BOBITS:%.*]] = ptrtoint [[BRIDGE:%swift.bridge\*]] %0 to i32
// CHECK: [[MASKED_BITS:%.*]] = and i32 [[BOBITS]], -4
// CHECK: inttoptr i32 [[MASKED_BITS]] to [[C:%objc_object\*]]
sil @convert_from_bridge_object : $Builtin.BridgeObject -> (ObjC, Builtin.Word) {
sil @convert_from_bridge_object : $(Builtin.BridgeObject) -> (ObjC, Builtin.Word) {
entry(%b : $Builtin.BridgeObject):
%c = bridge_object_to_ref %b : $Builtin.BridgeObject to $ObjC
%w = bridge_object_to_word %b : $Builtin.BridgeObject to $Builtin.Word
%t = tuple (%c : $ObjC, %w : $Builtin.Word)
return %t : $(ObjC, Builtin.Word)
}

sil @convert_from_native_bridge_object : $Builtin.BridgeObject -> C {
sil @convert_from_native_bridge_object : $(Builtin.BridgeObject) -> C {
entry(%b : $Builtin.BridgeObject):
%c = bridge_object_to_ref %b : $Builtin.BridgeObject to $C
return %c : $C
Expand Down
4 changes: 2 additions & 2 deletions test/IRGen/bridge_object_x86_64.sil
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ entry(%c : $C, %w : $Builtin.Word):
// CHECK: tagged-cont:
// CHECK: phi [[C]] [ [[TAGGED_RESULT]], %tagged-pointer ], [ [[MASKED_RESULT]], %not-tagged-pointer ]

sil @convert_from_bridge_object : $Builtin.BridgeObject -> (ObjC, Builtin.Word) {
sil @convert_from_bridge_object : $(Builtin.BridgeObject) -> (ObjC, Builtin.Word) {
entry(%b : $Builtin.BridgeObject):
%c = bridge_object_to_ref %b : $Builtin.BridgeObject to $ObjC
%w = bridge_object_to_word %b : $Builtin.BridgeObject to $Builtin.Word
Expand All @@ -61,7 +61,7 @@ entry(%b : $Builtin.BridgeObject):
// CHECK: [[MASKED_BITS:%.*]] = and i64 [[BOBITS]], 72057594037927928
// CHECK: [[RESULT:%.*]] = inttoptr i64 [[MASKED_BITS]] to [[C:%T13bridge_object1CC\*]]
// CHECK: ret %T13bridge_object1CC* [[RESULT]]
sil @convert_from_native_bridge_object : $Builtin.BridgeObject -> C {
sil @convert_from_native_bridge_object : $(Builtin.BridgeObject) -> C {
entry(%b : $Builtin.BridgeObject):
%c = bridge_object_to_ref %b : $Builtin.BridgeObject to $C
return %c : $C
Expand Down
Loading