From 18952c877845a79d5a806fc54734d113791bb146 Mon Sep 17 00:00:00 2001 From: Dan Zheng Date: Thu, 18 Apr 2019 08:29:22 -0700 Subject: [PATCH 1/3] Revert "[TF] Introduce callables. (#24086)" This reverts commit f7c7edfc52627a516002d955f6cd55de2b0e305f. --- include/swift/AST/Attr.def | 60 +++----- include/swift/AST/Decl.h | 77 +--------- include/swift/AST/DeclNodes.def | 4 +- include/swift/AST/DiagnosticsParse.def | 13 -- include/swift/AST/DiagnosticsSema.def | 25 +-- include/swift/AST/DiagnosticsSema.h | 4 +- include/swift/Demangling/DemangleNodes.def | 2 - include/swift/IDE/CodeCompletion.h | 2 - include/swift/IDE/SyntaxModel.h | 2 - include/swift/Parse/Parser.h | 12 +- include/swift/Serialization/ModuleFormat.h | 2 +- lib/AST/ASTDumper.cpp | 7 - lib/AST/ASTMangler.cpp | 17 --- lib/AST/ASTPrinter.cpp | 41 ----- lib/AST/ASTScope.cpp | 4 +- lib/AST/Decl.cpp | 56 ------- lib/AST/LookupVisibleDecls.cpp | 4 +- lib/Demangling/Demangler.cpp | 4 - lib/Demangling/NodePrinter.cpp | 7 - lib/Demangling/OldRemangler.cpp | 7 - lib/Demangling/Remangler.cpp | 5 - lib/FrontendTool/ReferenceDependencies.cpp | 2 - lib/IDE/CodeCompletion.cpp | 9 -- lib/IDE/REPLCodeCompletion.cpp | 2 - lib/IRGen/GenClass.cpp | 8 - lib/IRGen/GenDecl.cpp | 6 - lib/IRGen/GenObjC.cpp | 5 - lib/IRGen/GenObjC.h | 4 - lib/Index/IndexSymbol.cpp | 5 - lib/Parse/ParseDecl.cpp | 144 +----------------- lib/Parse/ParseExpr.cpp | 8 +- lib/Parse/ParsePattern.cpp | 18 +-- lib/Parse/Parser.cpp | 3 +- lib/SILGen/SILGenDecl.cpp | 4 +- lib/Sema/CSApply.cpp | 56 ------- lib/Sema/CSDiag.cpp | 15 +- lib/Sema/CSSimplify.cpp | 54 ------- lib/Sema/ConstraintLocator.cpp | 7 - lib/Sema/ConstraintLocator.h | 7 - lib/Sema/TypeCheckAttr.cpp | 2 - lib/Sema/TypeCheckDecl.cpp | 40 +---- lib/Sema/TypeCheckNameLookup.cpp | 6 - lib/Sema/TypeCheckProtocol.cpp | 4 - lib/Serialization/Serialization.cpp | 63 -------- test/AutoDiff/simple_model.swift | 97 ++++++++++-- test/Sema/immutability.swift | 3 +- .../complete_override.swift.response | 9 -- .../model_autodiff_runtime.swift | 36 +++-- test/decl/call/callables.swift | 136 ----------------- test/decl/call/generic.swift | 43 ------ .../lib/SwiftLang/SwiftLangSupport.cpp | 7 - tools/swift-ide-test/swift-ide-test.cpp | 2 - utils/gyb_sourcekit_support/UIDs.py | 3 - utils/gyb_syntax_support/DeclNodes.py | 20 --- utils/gyb_syntax_support/ExprNodes.py | 2 - .../NodeSerializationCodes.py | 1 - utils/gyb_syntax_support/Token.py | 1 - 57 files changed, 157 insertions(+), 1030 deletions(-) delete mode 100644 test/decl/call/callables.swift delete mode 100644 test/decl/call/generic.swift diff --git a/include/swift/AST/Attr.def b/include/swift/AST/Attr.def index 88c3d63ec7cf5..67ca13e6ed86e 100644 --- a/include/swift/AST/Attr.def +++ b/include/swift/AST/Attr.def @@ -122,8 +122,7 @@ DECL_ATTR(available, Available, AllowMultipleAttributes | LongAttribute, 1) CONTEXTUAL_SIMPLE_DECL_ATTR(final, Final, - // SWIFT_ENABLE_TENSORFLOW - OnClass | OnFunc | OnAccessor | OnCall | OnVar | OnSubscript | + OnClass | OnFunc | OnAccessor | OnVar | OnSubscript | DeclModifier, 2) DECL_ATTR(objc, ObjC, @@ -135,8 +134,7 @@ CONTEXTUAL_SIMPLE_DECL_ATTR(required, Required, DeclModifier, 4) CONTEXTUAL_SIMPLE_DECL_ATTR(optional, Optional, - // SWIFT_ENABLE_TENSORFLOW - OnConstructor | OnFunc | OnAccessor | OnCall | OnVar | OnSubscript | + OnConstructor | OnFunc | OnAccessor | OnVar | OnSubscript | DeclModifier, 5) SIMPLE_DECL_ATTR(dynamicCallable, DynamicCallable, @@ -192,8 +190,7 @@ DECL_ATTR(_semantics, Semantics, AllowMultipleAttributes | UserInaccessible, 21) CONTEXTUAL_SIMPLE_DECL_ATTR(dynamic, Dynamic, - // SWIFT_ENABLE_TENSORFLOW - OnFunc | OnAccessor | OnCall | OnVar | OnSubscript | OnConstructor | + OnFunc | OnAccessor | OnVar | OnSubscript | OnConstructor | DeclModifier, 22) CONTEXTUAL_SIMPLE_DECL_ATTR(infix, Infix, @@ -209,16 +206,13 @@ CONTEXTUAL_SIMPLE_DECL_ATTR(postfix, Postfix, DeclModifier, 25) SIMPLE_DECL_ATTR(_transparent, Transparent, - // SWIFT_ENABLE_TENSORFLOW - OnFunc | OnAccessor | OnCall | OnConstructor | OnVar | UserInaccessible, + OnFunc | OnAccessor | OnConstructor | OnVar | UserInaccessible, 26) SIMPLE_DECL_ATTR(requires_stored_property_inits, RequiresStoredPropertyInits, OnClass, 27) SIMPLE_DECL_ATTR(nonobjc, NonObjC, - // SWIFT_ENABLE_TENSORFLOW - OnExtension | OnFunc | OnAccessor | OnCall | OnVar | OnSubscript | - OnConstructor, + OnExtension | OnFunc | OnAccessor | OnVar | OnSubscript | OnConstructor, 30) SIMPLE_DECL_ATTR(_fixed_layout, FixedLayout, OnVar | OnClass | OnStruct | @@ -228,27 +222,23 @@ SIMPLE_DECL_ATTR(inlinable, Inlinable, OnVar | OnSubscript | OnAbstractFunction, 32) DECL_ATTR(_specialize, Specialize, - // SWIFT_ENABLE_TENSORFLOW - OnConstructor | OnFunc | OnAccessor | OnCall | + OnConstructor | OnFunc | OnAccessor | AllowMultipleAttributes | LongAttribute | UserInaccessible, 33) SIMPLE_DECL_ATTR(objcMembers, ObjCMembers, OnClass, 34) CONTEXTUAL_SIMPLE_DECL_ATTR(__consuming, Consuming, - // SWIFT_ENABLE_TENSORFLOW - OnFunc | OnAccessor | OnCall | + OnFunc | OnAccessor | DeclModifier | UserInaccessible | NotSerialized, 40) CONTEXTUAL_SIMPLE_DECL_ATTR(mutating, Mutating, - // SWIFT_ENABLE_TENSORFLOW - OnFunc | OnAccessor | OnCall | + OnFunc | OnAccessor | DeclModifier | NotSerialized, 41) CONTEXTUAL_SIMPLE_DECL_ATTR(nonmutating, NonMutating, - // SWIFT_ENABLE_TENSORFLOW - OnFunc | OnAccessor | OnCall | + OnFunc | OnAccessor | DeclModifier | NotSerialized, 42) CONTEXTUAL_SIMPLE_DECL_ATTR(convenience, Convenience, @@ -256,9 +246,7 @@ CONTEXTUAL_SIMPLE_DECL_ATTR(convenience, Convenience, DeclModifier | NotSerialized, 43) CONTEXTUAL_SIMPLE_DECL_ATTR(override, Override, - // SWIFT_ENABLE_TENSORFLOW - OnFunc | OnAccessor | OnCall | OnVar | OnSubscript | OnConstructor | - OnAssociatedType | + OnFunc | OnAccessor | OnVar | OnSubscript | OnConstructor | OnAssociatedType | DeclModifier | NotSerialized, 44) SIMPLE_DECL_ATTR(_hasStorage, HasStorage, @@ -266,9 +254,8 @@ SIMPLE_DECL_ATTR(_hasStorage, HasStorage, UserInaccessible | NotSerialized, 45) DECL_ATTR(private, AccessControl, - // SWIFT_ENABLE_TENSORFLOW - OnFunc | OnAccessor | OnCall | OnExtension | OnGenericType | OnVar | - OnSubscript | OnConstructor | + OnFunc | OnAccessor | OnExtension | OnGenericType | OnVar | OnSubscript | + OnConstructor | DeclModifier | NotSerialized, 46) DECL_ATTR_ALIAS(fileprivate, AccessControl) @@ -316,8 +303,7 @@ DECL_ATTR(_alignment, Alignment, UserInaccessible, 56) SIMPLE_DECL_ATTR(rethrows, Rethrows, - // SWIFT_ENABLE_TENSORFLOW - OnFunc | OnAccessor | OnCall | OnConstructor | + OnFunc | OnAccessor | OnConstructor | RejectByParser, 57) DECL_ATTR(_swift_native_objc_runtime_base, SwiftNativeObjCRuntimeBase, @@ -344,16 +330,14 @@ SIMPLE_DECL_ATTR(usableFromInline, UsableFromInline, LongAttribute, 64) SIMPLE_DECL_ATTR(discardableResult, DiscardableResult, - // SWIFT_ENABLE_TENSORFLOW - OnFunc | OnAccessor | OnCall | OnConstructor | + OnFunc | OnAccessor | OnConstructor | LongAttribute, 65) SIMPLE_DECL_ATTR(GKInspectable, GKInspectable, OnVar, 66) DECL_ATTR(_implements, Implements, - // SWIFT_ENABLE_TENSORFLOW - OnFunc | OnAccessor | OnCall | OnVar | OnSubscript | OnTypeAlias | + OnFunc | OnAccessor | OnVar | OnSubscript | OnTypeAlias | UserInaccessible | NotSerialized, 67) DECL_ATTR(_objcRuntimeName, ObjCRuntimeName, @@ -369,8 +353,7 @@ DECL_ATTR(_restatedObjCConformance, RestatedObjCConformance, NotSerialized, 70) // NOTE: 71 is unused SIMPLE_DECL_ATTR(_implicitly_unwrapped_optional, ImplicitlyUnwrappedOptional, - // SWIFT_ENABLE_TENSORFLOW - OnFunc | OnAccessor | OnCall | OnVar | OnParam | OnSubscript | OnConstructor | + OnFunc | OnAccessor | OnVar | OnParam | OnSubscript | OnConstructor | RejectByParser, 72) DECL_ATTR(_optimize, Optimize, @@ -382,8 +365,7 @@ DECL_ATTR(_clangImporterSynthesizedType, ClangImporterSynthesizedType, LongAttribute | RejectByParser | UserInaccessible | NotSerialized, 74) SIMPLE_DECL_ATTR(_weakLinked, WeakLinked, - // SWIFT_ENABLE_TENSORFLOW - OnNominalType | OnAssociatedType | OnFunc | OnAccessor | OnCall | OnVar | + OnNominalType | OnAssociatedType | OnFunc | OnAccessor | OnVar | OnSubscript | OnConstructor | OnEnumElement | UserInaccessible, 75) SIMPLE_DECL_ATTR(_frozen, Frozen, @@ -399,9 +381,7 @@ SIMPLE_DECL_ATTR(_hasInitialValue, HasInitialValue, UserInaccessible, 78) SIMPLE_DECL_ATTR(_nonoverride, NonOverride, - // SWIFT_ENABLE_TENSORFLOW - OnFunc | OnAccessor | OnCall | OnVar | OnSubscript | OnConstructor | - OnAssociatedType | + OnFunc | OnAccessor | OnVar | OnSubscript | OnConstructor | OnAssociatedType | UserInaccessible | NotSerialized, 79) DECL_ATTR(_dynamicReplacement, DynamicReplacement, @@ -417,8 +397,8 @@ DECL_ATTR(_private, PrivateImport, // SWIFT_ENABLE_TENSORFLOW DECL_ATTR(differentiable, Differentiable, - OnAccessor | OnConstructor | OnFunc | OnCall | OnVar | OnSubscript | - LongAttribute | AllowMultipleAttributes, + OnAccessor | OnConstructor | OnFunc | OnVar | OnSubscript | LongAttribute | + AllowMultipleAttributes, 83) DECL_ATTR(differentiating, Differentiating, OnFunc | LongAttribute | AllowMultipleAttributes | diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h index 6ca07cf9e2aee..51ce9fa5d15c7 100644 --- a/include/swift/AST/Decl.h +++ b/include/swift/AST/Decl.h @@ -53,8 +53,6 @@ namespace swift { struct ASTNode; class ASTPrinter; class ASTWalker; - // SWIFT_ENABLE_TENSORFLOW - class CallDecl; class ConstructorDecl; class DestructorDecl; class DiagnosticEngine; @@ -138,8 +136,6 @@ enum class DescriptiveDeclKind : uint8_t { GenericStruct, GenericClass, GenericType, - // SWIFT_ENABLE_TENSORFLOW - Call, Subscript, Constructor, Destructor, @@ -5731,9 +5727,7 @@ class FuncDecl : public AbstractFunctionDecl { static bool classof(const Decl *D) { return D->getKind() == DeclKind::Func || - D->getKind() == DeclKind::Accessor || - // SWIFT_ENABLE_TENSORFLOW - D->getKind() == DeclKind::Call; + D->getKind() == DeclKind::Accessor; } static bool classof(const AbstractFunctionDecl *D) { return classof(static_cast(D)); @@ -5886,60 +5880,7 @@ AbstractStorageDecl::AccessorRecord::getAccessor(AccessorKind kind) const { } return nullptr; } - -// SWIFT_ENABLE_TENSORFLOW -/// CallDecl - Declares a callable method for a type. For example: -/// -/// \code -/// struct Adder { -/// var base: Int -/// call(_ x: Int) -> Int { -/// return base + x -/// } -/// } -/// \endcode -class CallDecl final : public FuncDecl { - CallDecl(DeclName fullName, SourceLoc declLoc, bool throws, - SourceLoc throwsLoc, unsigned numParameterLists, - GenericParamList *genericParams, DeclContext *parent) - : FuncDecl(DeclKind::Call, - /*staticLoc*/ SourceLoc(), StaticSpellingKind::None, - /*func loc*/ declLoc, /*name*/ fullName, /*name loc*/ declLoc, - throws, throwsLoc, numParameterLists, genericParams, parent) {} - - static CallDecl *createImpl(ASTContext &ctx, DeclName fullName, - SourceLoc declLoc, bool throws, - SourceLoc throwsLoc, - GenericParamList *genericParams, - DeclContext *parent, ClangNode clangNode); - -public: - static CallDecl *createDeserialized(ASTContext &ctx, DeclName name, - SourceLoc declLoc, bool throws, - SourceLoc throwsLoc, - GenericParamList *genericParams, - DeclContext *parent); - - static CallDecl *create(ASTContext &ctx, DeclName fullName, SourceLoc declLoc, - bool throws, SourceLoc throwsLoc, - GenericParamList *genericParams, - ParameterList *parameterList, - TypeLoc fnRetType, DeclContext *parent, - ClangNode clangNode = ClangNode()); - - static bool classof(const Decl *D) { - return D->getKind() == DeclKind::Call; - } - static bool classof(const AbstractFunctionDecl *D) { - return classof(static_cast(D)); - } - static bool classof(const DeclContext *DC) { - if (auto D = DC->getAsDecl()) - return classof(D); - return false; - } -}; - + /// \brief This represents a 'case' declaration in an 'enum', which may declare /// one or more individual comma-separated EnumElementDecls. class EnumCaseDecl final : public Decl, @@ -6852,8 +6793,6 @@ inline ParamDecl **AbstractFunctionDecl::getImplicitSelfDeclStorage() { return cast(this)->getImplicitSelfDeclStorage(); case DeclKind::Func: case DeclKind::Accessor: - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: return cast(this)->getImplicitSelfDeclStorage(); } } @@ -6862,13 +6801,11 @@ inline ParamDecl **FuncDecl::getImplicitSelfDeclStorage() { if (!hasImplicitSelfDecl()) return nullptr; - if (isa(this)) - return reinterpret_cast(static_cast(this)+1); - // SWIFT_ENABLE_TENSORFLOW - else if (isa(this)) - return reinterpret_cast(static_cast(this)+1); - assert(getKind() == DeclKind::Func && "no new kinds of functions"); - return reinterpret_cast(this+1); + if (!isa(this)) { + assert(getKind() == DeclKind::Func && "no new kinds of functions"); + return reinterpret_cast(this+1); + } + return reinterpret_cast(static_cast(this)+1); } inline DeclIterator &DeclIterator::operator++() { diff --git a/include/swift/AST/DeclNodes.def b/include/swift/AST/DeclNodes.def index 64518f048ee9c..eca225a8f88c1 100644 --- a/include/swift/AST/DeclNodes.def +++ b/include/swift/AST/DeclNodes.def @@ -170,9 +170,7 @@ ABSTRACT_DECL(Value, Decl) ABSTRACT_FUNCTION_DECL(Destructor, AbstractFunctionDecl) ABSTRACT_FUNCTION_DECL(Func, AbstractFunctionDecl) ABSTRACT_FUNCTION_DECL(Accessor, FuncDecl) - // SWIFT_ENABLE_TENSORFLOW - ABSTRACT_FUNCTION_DECL(Call, FuncDecl) - DECL_RANGE(AbstractFunction, Constructor, Call) + DECL_RANGE(AbstractFunction, Constructor, Accessor) VALUE_DECL(EnumElement, ValueDecl) DECL_RANGE(Value, Enum, EnumElement) diff --git a/include/swift/AST/DiagnosticsParse.def b/include/swift/AST/DiagnosticsParse.def index 526b30e825481..0129dc7313c75 100644 --- a/include/swift/AST/DiagnosticsParse.def +++ b/include/swift/AST/DiagnosticsParse.def @@ -398,19 +398,6 @@ ERROR(subscript_without_get,none, ERROR(subscript_static,none, "subscript cannot be marked %0", (StaticSpellingKind)) -// SWIFT_ENABLE_TENSORFLOW -// `call` method -ERROR(call_decl_static,none, - "'call' method cannot be marked %0", (StaticSpellingKind)) -ERROR(call_decl_wrong_scope,none, - "'call' methods may only be declared within a type", ()) -ERROR(expected_lparen_call,PointsToFirstBadToken, - "expected '(' for 'call' member parameters", ()) -ERROR(call_decl_cannot_have_name,PointsToFirstBadToken, - "'call' method cannot have a name", ()) -ERROR(call_decl_expected_func_keyword,PointsToFirstBadToken, - "'call' must be followed by 'func'", ()) - // initializer ERROR(invalid_nested_init,none, "missing '%select{super.|self.}0' at initializer invocation", (bool)) diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def index f24d67a95fb94..cefcfed6c06fa 100644 --- a/include/swift/AST/DiagnosticsSema.def +++ b/include/swift/AST/DiagnosticsSema.def @@ -1052,7 +1052,6 @@ NOTE(archetype_declared_in_type,none, NOTE(unbound_generic_parameter_explicit_fix,none, "explicitly specify the generic arguments to fix this issue", ()) -// SWIFT_ENABLE_TENSORFLOW ERROR(invalid_dynamic_callable_type,none, "@dynamicCallable attribute requires %0 to have either a valid " "'dynamicallyCall(withArguments:)' method or " @@ -1690,17 +1689,15 @@ ERROR(witness_requires_class_implementation,none, (DeclName, Type)) ERROR(witness_not_accessible_proto,none, "%select{initializer %1|method %1|%select{|setter for }2property %1" - // SWIFT_ENABLE_TENSORFLOW - "|subscript%select{| setter}2|'call' method}0 must be declared " + "|subscript%select{| setter}2}0 must be declared " "%select{%error|fileprivate|internal|public|%error}3 because it matches a " "requirement in %select{private|fileprivate|internal|public|%error}4 protocol " "%5", (RequirementKind, DeclName, bool, AccessLevel, AccessLevel, DeclName)) ERROR(witness_not_accessible_type,none, "%select{initializer %1|method %1|%select{|setter for }2property %1" - // SWIFT_ENABLE_TENSORFLOW - "|subscript%select{| setter}2|'call' method}0 must be as accessible as " - "its enclosing type because it matches a requirement in protocol %5", + "|subscript%select{| setter}2}0 must be as accessible as its enclosing " + "type because it matches a requirement in protocol %5", (RequirementKind, DeclName, bool, AccessLevel, AccessLevel, DeclName)) ERROR(type_witness_not_accessible_proto,none, "%0 %1 must be declared %select{%error|fileprivate|internal|public|%error}2 " @@ -1764,24 +1761,19 @@ NOTE(inherited_protocol_does_not_conform,none, "type %0 does not conform to inherited protocol %1", (Type, Type)) NOTE(no_witnesses,none, "protocol requires " - // SWIFT_ENABLE_TENSORFLOW - "%select{initializer %1|function %1|property %1|subscript|'call' method}0 " - "with type %2%select{|; do you want to add a stub?}3", + "%select{initializer %1|function %1|property %1|subscript}0 with type %2" + "%select{|; do you want to add a stub?}3", (RequirementKind, DeclName, Type, bool)) NOTE(missing_witnesses_general,none, "do you want to add protocol stubs?", ()) NOTE(ambiguous_witnesses,none, "multiple matching " "%select{initializers named %1|functions named %1|properties named %1|" - // SWIFT_ENABLE_TENSORFLOW - "subscript operators|'call' method}0 with type %2", - (RequirementKind, DeclName, Type)) + "subscript operators}0 with type %2", (RequirementKind, DeclName, Type)) NOTE(ambiguous_witnesses_wrong_name,none, "multiple matching " "%select{initializers named %1|functions named %1|properties named %1|" - // SWIFT_ENABLE_TENSORFLOW - "subscript operators|'call' method}0 with type %2", - (RequirementKind, DeclName, Type)) + "subscript operators}0 with type %2", (RequirementKind, DeclName, Type)) NOTE(no_witnesses_type,none, "protocol requires nested type %0; do you want to add it?", (Identifier)) NOTE(default_associated_type_req_fail,none, @@ -1845,8 +1837,7 @@ NOTE(protocol_witness_renamed,none, "rename to %0 to satisfy this requirement%1", (DeclName, StringRef)) NOTE(protocol_witness_kind_conflict,none, "candidate is not %select{an initializer|a function|a variable|" - // SWIFT_ENABLE_TENSORFLOW - "a subscript|a 'call' method}0", (RequirementKind)) + "a subscript}0", (RequirementKind)) NOTE(protocol_witness_type_conflict,none, "candidate has non-matching type %0%1", (Type, StringRef)) NOTE(protocol_witness_missing_requirement,none, diff --git a/include/swift/AST/DiagnosticsSema.h b/include/swift/AST/DiagnosticsSema.h index ac79da8255eaa..5b3e9fd1ce1a5 100644 --- a/include/swift/AST/DiagnosticsSema.h +++ b/include/swift/AST/DiagnosticsSema.h @@ -29,9 +29,7 @@ namespace swift { Constructor, Func, Var, - Subscript, - // SWIFT_ENABLE_TENSORFLOW - Call + Subscript }; // Declare common diagnostics objects with their appropriate types. diff --git a/include/swift/Demangling/DemangleNodes.def b/include/swift/Demangling/DemangleNodes.def index 4df1e5a0e3484..e58a8be35df7f 100644 --- a/include/swift/Demangling/DemangleNodes.def +++ b/include/swift/Demangling/DemangleNodes.def @@ -42,8 +42,6 @@ NODE(BoundGenericOtherNominalType) NODE(BoundGenericTypeAlias) NODE(BoundGenericFunction) NODE(BuiltinTypeName) -// SWIFT_ENABLE_TENSORFLOW -CONTEXT_NODE(CallDeclaration) NODE(CFunctionPointer) CONTEXT_NODE(Class) NODE(ClassMetadataBaseOffset) diff --git a/include/swift/IDE/CodeCompletion.h b/include/swift/IDE/CodeCompletion.h index 8c57712a223d5..293e2d4ef1fa2 100644 --- a/include/swift/IDE/CodeCompletion.h +++ b/include/swift/IDE/CodeCompletion.h @@ -398,8 +398,6 @@ enum class CodeCompletionDeclKind { Constructor, Destructor, Subscript, - // SWIFT_ENABLE_TENSORFLOW - Call, StaticMethod, InstanceMethod, PrefixOperatorFunction, diff --git a/include/swift/IDE/SyntaxModel.h b/include/swift/IDE/SyntaxModel.h index 30a1deaaeefa9..a80b181265383 100644 --- a/include/swift/IDE/SyntaxModel.h +++ b/include/swift/IDE/SyntaxModel.h @@ -97,8 +97,6 @@ enum class SyntaxStructureKind : uint8_t { EnumElement, TypeAlias, Subscript, - // SWIFT_ENABLE_TENSORFLOW - Call, AssociatedType, GenericTypeParam, diff --git a/include/swift/Parse/Parser.h b/include/swift/Parse/Parser.h index 71844fd5a33c0..67958ff51d70f 100644 --- a/include/swift/Parse/Parser.h +++ b/include/swift/Parse/Parser.h @@ -457,9 +457,7 @@ class Parser { } SourceLoc consumeIdentifier(Identifier *Result = nullptr) { - // SWIFT_ENABLE_TENSORFLOW - assert(Tok.isAny(tok::identifier, tok::kw_self, tok::kw_Self, - tok::kw_call)); + assert(Tok.isAny(tok::identifier, tok::kw_self, tok::kw_Self)); if (Result) *Result = Context.getIdentifier(Tok.getText()); return consumeToken(); @@ -961,9 +959,6 @@ class Parser { ParserResult parseDeclProtocol(ParseDeclOptions Flags, DeclAttributes &Attributes); - // SWIFT_ENABLE_TENSORFLOW - ParserResult - parseDeclCall(ParseDeclOptions Flags, DeclAttributes &Attributes); ParserResult parseDeclSubscript(ParseDeclOptions Flags, DeclAttributes &Attributes, SmallVectorImpl &Decls); @@ -1124,9 +1119,6 @@ class Parser { Closure, /// A subscript. Subscript, - // SWIFT_ENABLE_TENSORFLOW - /// A callable method. - Call, /// A curried argument clause. Curried, /// An enum element. @@ -1165,8 +1157,6 @@ class Parser { DefaultArgumentInfo &defaultArgs); ParserStatus parseFunctionSignature(Identifier functionName, DeclName &fullName, - // SWIFT_ENABLE_TENSORFLOW - ParameterContextKind paramContext, ParameterList *&bodyParams, DefaultArgumentInfo &defaultArgs, SourceLoc &throws, diff --git a/include/swift/Serialization/ModuleFormat.h b/include/swift/Serialization/ModuleFormat.h index 4a72f143b0992..f8114cb87a813 100644 --- a/include/swift/Serialization/ModuleFormat.h +++ b/include/swift/Serialization/ModuleFormat.h @@ -52,7 +52,7 @@ const uint16_t SWIFTMODULE_VERSION_MAJOR = 0; /// describe what change you made. The content of this comment isn't important; /// it just ensures a conflict if two people change the module format. /// Don't worry about adhering to the 80-column limit for this line. -const uint16_t SWIFTMODULE_VERSION_MINOR = 473; // Last change: `call` declarations +const uint16_t SWIFTMODULE_VERSION_MINOR = 472; // Last change: `@differentiating` wrt using DeclIDField = BCFixed<31>; diff --git a/lib/AST/ASTDumper.cpp b/lib/AST/ASTDumper.cpp index 11ede60149841..844f9f6e6e2c0 100644 --- a/lib/AST/ASTDumper.cpp +++ b/lib/AST/ASTDumper.cpp @@ -1057,13 +1057,6 @@ namespace { PrintWithColorRAII(OS, ParenthesisColor) << ')'; } - // SWIFT_ENABLE_TENSORFLOW - void visitCallDecl(CallDecl *CD) { - printCommonFD(CD, "call_decl"); - printAbstractFunctionDecl(CD); - PrintWithColorRAII(OS, ParenthesisColor) << ')'; - } - void visitAccessorDecl(AccessorDecl *AD) { printCommonFD(AD, "accessor_decl"); OS << " " << getAccessorKindString(AD->getAccessorKind()); diff --git a/lib/AST/ASTMangler.cpp b/lib/AST/ASTMangler.cpp index 3dabb1783a674..31bec235eb49c 100644 --- a/lib/AST/ASTMangler.cpp +++ b/lib/AST/ASTMangler.cpp @@ -2240,23 +2240,6 @@ void ASTMangler::appendEntity(const ValueDecl *decl) { accessor->getStorage(), accessor->isStatic()); } - // SWIFT_ENABLE_TENSORFLOW - // Handle call declarations specially. - if (auto callDecl = dyn_cast(decl)) { - appendContextOf(decl); - bindGenericParameters(decl->getDeclContext()); - appendDeclType(decl); - StringRef privateDiscriminator = getPrivateDiscriminatorIfNecessary(decl); - if (!privateDiscriminator.empty()) { - appendIdentifier(privateDiscriminator); - appendOperator("Ll"); - } - appendOperator("fF"); - if (callDecl->isStatic()) - appendOperator("Z"); - return; - } - if (auto storageDecl = dyn_cast(decl)) return appendAccessorEntity("p", storageDecl, decl->isStatic()); if (isa(decl)) diff --git a/lib/AST/ASTPrinter.cpp b/lib/AST/ASTPrinter.cpp index 11e267b9b9b38..4c3f559b4c85f 100644 --- a/lib/AST/ASTPrinter.cpp +++ b/lib/AST/ASTPrinter.cpp @@ -2876,47 +2876,6 @@ void PrintAST::visitDestructorDecl(DestructorDecl *decl) { printBodyIfNecessary(decl); } -// SWIFT_ENABLE_TENSORFLOW -void PrintAST::visitCallDecl(CallDecl *decl) { - printDocumentationComment(decl); - printAttributes(decl); - printAccess(decl); - printContextIfNeeded(decl); - recordDeclLoc(decl, [&]{ - Printer << "call"; - }, [&] { // Parameters - printGenericDeclGenericParams(decl); - printFunctionParameters(decl); - }); - Printer << " -> "; - - Printer.callPrintStructurePre(PrintStructureKind::FunctionReturnType); - Type ResultTy = decl->getResultInterfaceType(); - if (ResultTy && !ResultTy->isVoid()) { - TypeLoc ResultTyLoc = decl->getBodyResultTypeLoc(); - if (!ResultTyLoc.getTypeRepr()) - ResultTyLoc = TypeLoc::withoutLoc(ResultTy); - // FIXME: Hacky way to workaround the fact that 'Self' as return - // TypeRepr is not getting 'typechecked'. See - // \c resolveTopLevelIdentTypeComponent function in TypeCheckType.cpp. - if (auto *simId = dyn_cast_or_null(ResultTyLoc.getTypeRepr())) { - if (simId->getIdentifier().str() == "Self") - ResultTyLoc = TypeLoc::withoutLoc(ResultTy); - } - Printer << " -> "; - Printer.callPrintStructurePre(PrintStructureKind::FunctionReturnType); - if (decl->getAttrs().hasAttribute()) - printTypeLocForImplicitlyUnwrappedOptional(ResultTyLoc); - else - printTypeLoc(ResultTyLoc); - Printer.printStructurePost(PrintStructureKind::FunctionReturnType); - } - printGenericDeclGenericRequirements(decl); - Printer.printStructurePost(PrintStructureKind::FunctionReturnType); - printGenericDeclGenericRequirements(decl); - printBodyIfNecessary(decl); -} - void PrintAST::visitInfixOperatorDecl(InfixOperatorDecl *decl) { Printer.printKeyword("infix"); Printer << " " << tok::kw_operator << " "; diff --git a/lib/AST/ASTScope.cpp b/lib/AST/ASTScope.cpp index 1f0d65ff63c68..677d1401210a3 100644 --- a/lib/AST/ASTScope.cpp +++ b/lib/AST/ASTScope.cpp @@ -918,9 +918,7 @@ ASTScope *ASTScope::createIfNeeded(const ASTScope *parent, Decl *decl) { case DeclKind::Func: case DeclKind::Accessor: case DeclKind::Constructor: - case DeclKind::Destructor: - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: { + case DeclKind::Destructor: { auto abstractFunction = cast(decl); // If we have a generic function and our parent isn't describing our generic diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp index ef9b231f545fc..c8a9b6e39c25e 100644 --- a/lib/AST/Decl.cpp +++ b/lib/AST/Decl.cpp @@ -150,8 +150,6 @@ DescriptiveDeclKind Decl::getDescriptiveKind() const { TRIVIAL_KIND(GenericTypeParam); TRIVIAL_KIND(AssociatedType); TRIVIAL_KIND(Protocol); - // SWIFT_ENABLE_TENSORFLOW - TRIVIAL_KIND(Call); TRIVIAL_KIND(Subscript); TRIVIAL_KIND(Constructor); TRIVIAL_KIND(Destructor); @@ -280,8 +278,6 @@ StringRef Decl::getDescriptiveKindName(DescriptiveDeclKind K) { ENTRY(GenericStruct, "generic struct"); ENTRY(GenericClass, "generic class"); ENTRY(GenericType, "generic type"); - // SWIFT_ENABLE_TENSORFLOW - ENTRY(Call, "call method"); ENTRY(Subscript, "subscript"); ENTRY(Constructor, "initializer"); ENTRY(Destructor, "deinitializer"); @@ -866,8 +862,6 @@ ImportKind ImportDecl::getBestImportKind(const ValueDecl *VD) { case DeclKind::Constructor: case DeclKind::Destructor: case DeclKind::GenericTypeParam: - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: case DeclKind::Subscript: case DeclKind::EnumElement: case DeclKind::Param: @@ -1907,11 +1901,6 @@ bool ValueDecl::isInstanceMember() const { // enum elements and function parameters are not instance members. return false; - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: - // Call declarations are always instance members. - return true; - case DeclKind::Subscript: // Subscripts are always instance members. return true; @@ -5876,51 +5865,6 @@ bool FuncDecl::isBinaryOperator() const { !params->get(1)->isVariadic(); } -// SWIFT_ENABLE_TENSORFLOW -CallDecl *CallDecl::createImpl(ASTContext &ctx, DeclName name, - SourceLoc declLoc, bool throws, - SourceLoc throwsLoc, - GenericParamList *genericParams, - DeclContext *parent, ClangNode clangNode) { - bool hasImplicitSelfDecl = parent->isTypeContext(); - size_t size = sizeof(CallDecl) + (hasImplicitSelfDecl - ? sizeof(ParamDecl *) - : 0); - void *buffer = - allocateMemoryForDecl(ctx, size, !clangNode.isNull()); - auto *D = ::new (buffer) - CallDecl(name, declLoc, throws, throwsLoc, hasImplicitSelfDecl, - genericParams, parent); - if (clangNode) - D->setClangNode(clangNode); - if (hasImplicitSelfDecl) - *D->getImplicitSelfDeclStorage() = nullptr; - - return D; -} - -CallDecl *CallDecl::createDeserialized(ASTContext &ctx, DeclName name, - SourceLoc declLoc, bool throws, - SourceLoc throwsLoc, - GenericParamList *genericParams, - DeclContext *parent) { - return createImpl(ctx, name, declLoc, throws, throwsLoc, genericParams, - parent, ClangNode()); -} - -CallDecl *CallDecl::create(ASTContext &ctx, DeclName name, SourceLoc declLoc, - bool throws, SourceLoc throwsLoc, - GenericParamList *genericParams, - ParameterList *bodyParams, TypeLoc fnRetType, - DeclContext *parent, ClangNode clangNode) { - auto *D = CallDecl::createImpl( - ctx, name, declLoc, throws, throwsLoc, genericParams, parent, clangNode); - D->setParameters(bodyParams); - D->getBodyResultTypeLoc() = fnRetType; - return D; -} -// SWIFT_ENABLE_TENSORFLOW END - ConstructorDecl::ConstructorDecl(DeclName Name, SourceLoc ConstructorLoc, OptionalTypeKind Failability, SourceLoc FailabilityLoc, diff --git a/lib/AST/LookupVisibleDecls.cpp b/lib/AST/LookupVisibleDecls.cpp index dd3f2be4b45b5..0dc97091e519f 100644 --- a/lib/AST/LookupVisibleDecls.cpp +++ b/lib/AST/LookupVisibleDecls.cpp @@ -336,9 +336,7 @@ static void doDynamicLookup(VisibleDeclConsumer &Consumer, // with the same signature. case DeclKind::Accessor: - case DeclKind::Func: - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: { + case DeclKind::Func: { auto FD = cast(D); assert(FD->hasImplicitSelfDecl() && "should not find free functions"); (void)FD; diff --git a/lib/Demangling/Demangler.cpp b/lib/Demangling/Demangler.cpp index a14d2a4bf9086..2a7ec847053cc 100644 --- a/lib/Demangling/Demangler.cpp +++ b/lib/Demangling/Demangler.cpp @@ -2704,10 +2704,6 @@ NodePointer Demangler::demangleFunctionEntity() { Args = TypeAndMaybePrivateName; Kind = Node::Kind::Allocator; break; case 'c': Args = TypeAndMaybePrivateName; Kind = Node::Kind::Constructor; break; - // SWIFT_ENABLE_TENSORFLOW - case 'F': - Args = TypeAndMaybePrivateName; Kind = Node::Kind::CallDeclaration; break; - // SWIFT_ENABLE_TENSORFLOW END case 'U': Args = TypeAndIndex; Kind = Node::Kind::ExplicitClosure; break; case 'u': Args = TypeAndIndex; Kind = Node::Kind::ImplicitClosure; break; case 'A': Args = Index; Kind = Node::Kind::DefaultArgumentInitializer; break; diff --git a/lib/Demangling/NodePrinter.cpp b/lib/Demangling/NodePrinter.cpp index 0683ded41aae9..8d07d058a1989 100644 --- a/lib/Demangling/NodePrinter.cpp +++ b/lib/Demangling/NodePrinter.cpp @@ -319,8 +319,6 @@ class NodePrinter { case Node::Kind::AssociatedTypeMetadataAccessor: case Node::Kind::AssociatedTypeWitnessTableAccessor: case Node::Kind::AutoClosureType: - // SWIFT_ENABLE_TENSORFLOW - case Node::Kind::CallDeclaration: case Node::Kind::ClassMetadataBaseOffset: case Node::Kind::CFunctionPointer: case Node::Kind::Constructor: @@ -1043,11 +1041,6 @@ NodePointer NodePrinter::print(NodePointer Node, bool asPrefixContext) { return printEntity(Node, asPrefixContext, TypePrinting::FunctionStyle, /*hasName*/false, /*ExtraName*/"", /*ExtraIndex*/-1, "subscript"); - // SWIFT_ENABLE_TENSORFLOW - case Node::Kind::CallDeclaration: - return printEntity(Node, asPrefixContext, TypePrinting::FunctionStyle, - /*hasName*/false, /*ExtraName*/"", /*ExtraIndex*/-1, - "call"); case Node::Kind::GenericTypeParamDecl: return printEntity(Node, asPrefixContext, TypePrinting::NoType, /*hasName*/true); diff --git a/lib/Demangling/OldRemangler.cpp b/lib/Demangling/OldRemangler.cpp index 39e9bb00a4920..6f423ab5b88bc 100644 --- a/lib/Demangling/OldRemangler.cpp +++ b/lib/Demangling/OldRemangler.cpp @@ -985,13 +985,6 @@ void Remangler::mangleFunction(Node *node, EntityContext &ctx) { mangleNamedAndTypedEntity(node, 'F', "", ctx); } -// SWIFT_ENABLE_TENSORFLOW -void Remangler::mangleCallDeclaration(Node *node, EntityContext &ctx) { - Out << 'f'; - mangleEntityContext(node->getChild(0), ctx); - Out << 'F'; -} - void Remangler::mangleVariable(Node *node, EntityContext &ctx) { mangleNamedAndTypedEntity(node, 'v', "", ctx); } diff --git a/lib/Demangling/Remangler.cpp b/lib/Demangling/Remangler.cpp index dad59f8af5048..2aef67cc9f1d1 100644 --- a/lib/Demangling/Remangler.cpp +++ b/lib/Demangling/Remangler.cpp @@ -730,11 +730,6 @@ void Remangler::mangleConstructor(Node *node) { mangleAnyConstructor(node, 'c'); } -void Remangler::mangleCallDeclaration(Node *node) { - mangleChildNodes(node); - Buffer << "fF"; -} - void Remangler::mangleCoroutineContinuationPrototype(Node *node) { mangleChildNodes(node); Buffer << "TC"; diff --git a/lib/FrontendTool/ReferenceDependencies.cpp b/lib/FrontendTool/ReferenceDependencies.cpp index 857e49b835c70..f4cce1d1d93f2 100644 --- a/lib/FrontendTool/ReferenceDependencies.cpp +++ b/lib/FrontendTool/ReferenceDependencies.cpp @@ -307,8 +307,6 @@ void ProvidesEmitter::emitTopLevelDecl(const Decl *const D, case DeclKind::GenericTypeParam: case DeclKind::AssociatedType: case DeclKind::Param: - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: case DeclKind::Subscript: case DeclKind::Constructor: case DeclKind::Destructor: diff --git a/lib/IDE/CodeCompletion.cpp b/lib/IDE/CodeCompletion.cpp index 3de3f15d83d1d..078713dd47795 100644 --- a/lib/IDE/CodeCompletion.cpp +++ b/lib/IDE/CodeCompletion.cpp @@ -623,9 +623,6 @@ CodeCompletionResult::getCodeCompletionDeclKind(const Decl *D) { return CodeCompletionDeclKind::PrecedenceGroup; case DeclKind::EnumElement: return CodeCompletionDeclKind::EnumElement; - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: - return CodeCompletionDeclKind::Call; case DeclKind::Subscript: return CodeCompletionDeclKind::Subscript; } @@ -668,10 +665,6 @@ void CodeCompletionResult::print(raw_ostream &OS) const { case CodeCompletionDeclKind::Destructor: Prefix.append("[Destructor]"); break; - // SWIFT_ENABLE_TENSORFLOW - case CodeCompletionDeclKind::Call: - Prefix.append("[Call]"); - break; case CodeCompletionDeclKind::Subscript: Prefix.append("[Subscript]"); break; @@ -5990,8 +5983,6 @@ void swift::ide::copyCodeCompletionResults(CodeCompletionResultSink &targetSink, case CodeCompletionDeclKind::EnumElement: case CodeCompletionDeclKind::Constructor: case CodeCompletionDeclKind::Destructor: - // SWIFT_ENABLE_TENSORFLOW - case CodeCompletionDeclKind::Call: case CodeCompletionDeclKind::Subscript: case CodeCompletionDeclKind::StaticMethod: case CodeCompletionDeclKind::InstanceMethod: diff --git a/lib/IDE/REPLCodeCompletion.cpp b/lib/IDE/REPLCodeCompletion.cpp index 0a400143973e4..fa971e0c73fd4 100644 --- a/lib/IDE/REPLCodeCompletion.cpp +++ b/lib/IDE/REPLCodeCompletion.cpp @@ -119,8 +119,6 @@ static void toDisplayString(CodeCompletionResult *Result, case CodeCompletionDeclKind::Destructor: continue; - // SWIFT_ENABLE_TENSORFLOW - case CodeCompletionDeclKind::Call: case CodeCompletionDeclKind::Subscript: case CodeCompletionDeclKind::StaticMethod: case CodeCompletionDeclKind::InstanceMethod: diff --git a/lib/IRGen/GenClass.cpp b/lib/IRGen/GenClass.cpp index 9bd046529270a..03478ab57c473 100644 --- a/lib/IRGen/GenClass.cpp +++ b/lib/IRGen/GenClass.cpp @@ -1515,14 +1515,6 @@ namespace { getMethodList(constructor).push_back(constructor); } - // SWIFT_ENABLE_TENSORFLOW - /// Call methods need to be collected into the appropriate methods list. - void visitCallDecl(CallDecl *method) { - if (!isBuildingProtocol() && !requiresObjCMethodDescriptor(method)) - return; - getMethodList(method).push_back(method); - } - /// Determine whether the given destructor has an Objective-C /// definition. bool hasObjCDeallocDefinition(DestructorDecl *destructor) { diff --git a/lib/IRGen/GenDecl.cpp b/lib/IRGen/GenDecl.cpp index 41bdb6d78036a..238cac95c92aa 100644 --- a/lib/IRGen/GenDecl.cpp +++ b/lib/IRGen/GenDecl.cpp @@ -1717,10 +1717,6 @@ void IRGenModule::emitGlobalDecl(Decl *D) { case DeclKind::Param: llvm_unreachable("there are no global function parameters"); - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: - llvm_unreachable("there are no global call declarations"); - case DeclKind::Subscript: llvm_unreachable("there are no global subscript operations"); @@ -3671,8 +3667,6 @@ void IRGenModule::emitNestedTypeDecls(DeclRange members) { continue; case DeclKind::Var: - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: case DeclKind::Subscript: case DeclKind::PatternBinding: case DeclKind::Func: diff --git a/lib/IRGen/GenObjC.cpp b/lib/IRGen/GenObjC.cpp index c67a930cb6b39..2cedbaa0c6080 100644 --- a/lib/IRGen/GenObjC.cpp +++ b/lib/IRGen/GenObjC.cpp @@ -1418,11 +1418,6 @@ bool irgen::requiresObjCMethodDescriptor(ConstructorDecl *constructor) { return constructor->isObjC(); } -// SWIFT_ENABLE_TENSORFLOW -bool irgen::requiresObjCMethodDescriptor(CallDecl *method) { - return method->isObjC(); -} - bool irgen::requiresObjCPropertyDescriptor(IRGenModule &IGM, VarDecl *property) { // Don't generate a descriptor for a property without any accessors. diff --git a/lib/IRGen/GenObjC.h b/lib/IRGen/GenObjC.h index db15b10044947..6f00b503abedd 100644 --- a/lib/IRGen/GenObjC.h +++ b/lib/IRGen/GenObjC.h @@ -203,10 +203,6 @@ namespace irgen { /// True if the ConstructorDecl requires an ObjC method descriptor. bool requiresObjCMethodDescriptor(ConstructorDecl *constructor); - // SWIFT_ENABLE_TENSORFLOW - /// True if the CallDecl requires an ObjC method descriptor. - bool requiresObjCMethodDescriptor(CallDecl *method); - /// True if the VarDecl requires ObjC accessor methods and a property /// descriptor. bool requiresObjCPropertyDescriptor(IRGenModule &IGM, diff --git a/lib/Index/IndexSymbol.cpp b/lib/Index/IndexSymbol.cpp index 975f51e98f455..bef053624bade 100644 --- a/lib/Index/IndexSymbol.cpp +++ b/lib/Index/IndexSymbol.cpp @@ -199,11 +199,6 @@ SymbolInfo index::getSymbolInfoForDecl(const Decl *D) { info.Kind = SymbolKind::InstanceProperty; info.SubKind = SymbolSubKind::SwiftSubscript; break; - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: - info.Kind = SymbolKind::InstanceMethod; - // info.SubKind = SymbolSubKind::SwiftCall; - break; case DeclKind::Constructor: info.Kind = SymbolKind::Constructor; break; case DeclKind::Destructor: info.Kind = SymbolKind::Destructor; break; case DeclKind::Param: diff --git a/lib/Parse/ParseDecl.cpp b/lib/Parse/ParseDecl.cpp index 50afdcb571603..b589fdadd7f35 100644 --- a/lib/Parse/ParseDecl.cpp +++ b/lib/Parse/ParseDecl.cpp @@ -3105,18 +3105,6 @@ Parser::parseDecl(ParseDeclOptions Flags, StaticLoc = SourceLoc(); // we handled static if present. MayNeedOverrideCompletion = true; break; - // SWIFT_ENABLE_TENSORFLOW - case tok::kw_call: - // Collect all modifiers into a modifier list. - DeclParsingContext.setCreateSyntax(SyntaxKind::CallDecl); - if (StaticLoc.isValid()) { - diagnose(Tok, diag::call_decl_static, StaticSpelling) - .fixItRemove(SourceRange(StaticLoc)); - StaticLoc = SourceLoc(); - } - DeclResult = parseDeclCall(Flags, Attributes); - MayNeedOverrideCompletion = true; - break; case tok::kw_subscript: { DeclParsingContext.setCreateSyntax(SyntaxKind::SubscriptDecl); if (StaticLoc.isValid()) { @@ -3196,8 +3184,6 @@ Parser::parseDecl(ParseDeclOptions Flags, SmallVector Keywords; switch (OrigTok.getKind()) { case tok::kw_func: - // SWIFT_ENABLE_TENSORFLOW - case tok::kw_call: case tok::kw_subscript: case tok::kw_var: case tok::kw_let: @@ -3573,8 +3559,7 @@ parseIdentifierDeclName(Parser &P, Identifier &Result, SourceLoc &Loc, StringRef DeclKindName, tok ResyncT1, tok ResyncT2, tok ResyncT3, tok ResyncT4, TokenProperty ResyncP1) { - // SWIFT_ENABLE_TENSORFLOW - if (P.Tok.is(tok::identifier) || P.Tok.is(tok::kw_call)) { + if (P.Tok.is(tok::identifier)) { Loc = P.consumeIdentifier(&Result); // We parsed an identifier for the declaration. If we see another @@ -5756,13 +5741,9 @@ Parser::parseDeclFunc(SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, ParameterList *BodyParams; SourceLoc throwsLoc; bool rethrows; - // SWIFT_ENABLE_TENSORFLOW - ParameterContextKind paramContext = SimpleName.isOperator() ? - ParameterContextKind::Operator : ParameterContextKind::Function; ParserStatus SignatureStatus = - // SWIFT_ENABLE_TENSORFLOW - parseFunctionSignature(SimpleName, FullName, paramContext, BodyParams, - DefaultArgs, throwsLoc, rethrows, FuncRetTy); + parseFunctionSignature(SimpleName, FullName, BodyParams, DefaultArgs, + throwsLoc, rethrows, FuncRetTy); SignatureHasCodeCompletion |= SignatureStatus.hasCodeCompletion(); if (SignatureStatus.hasCodeCompletion() && !CodeCompletion) { @@ -5833,122 +5814,6 @@ Parser::parseDeclFunc(SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, return DCC.fixupParserResult(FD); } -// SWIFT_ENABLE_TENSORFLOW -/// \brief Parse a `call` declaration, returning null on error. The caller -/// handles this case and does recovery as appropriate. -/// -/// \verbatim -/// decl-call: -/// attribute-list? 'mutating'? 'call' 'func' -/// generic-params? func-signature where-clause? -/// stmt-brace? -/// \endverbatim -/// -/// \note The caller of this method must ensure that the next token is 'call'. -ParserResult -Parser::parseDeclCall(ParseDeclOptions Flags, DeclAttributes &Attributes) { - assert(Tok.is(tok::kw_call)); - SourceLoc callLoc = consumeToken(tok::kw_call); - // `call` keyword must be followed by `func`. - if (!consumeIf(tok::kw_func)) - diagnose(Tok, diag::call_decl_expected_func_keyword); - - // Reject `call` declarations outside of types. - if (!Flags.contains(PD_HasContainerType)) - diagnose(Tok, diag::call_decl_wrong_scope); - - // Reject named `call` declarations. e.g. `call func foo()'. - if (Tok.is(tok::identifier) && - (peekToken().is(tok::l_paren) || startsWithLess(peekToken()))) { - diagnose(Tok, diag::call_decl_cannot_have_name).fixItRemove(Tok.getLoc()); - consumeToken(tok::identifier); - } - - auto simpleName = Context.getIdentifier("$call"); - DebuggerContextChange DCC(*this, simpleName, DeclKind::Call); - - // Parse the generic parameters, if present. - Scope genericsScope(this, ScopeKind::Generics); - auto genericParamsResult = maybeParseGenericParams(); - bool signatureHasCodeCompletion = false; - GenericParamList *genericParams = genericParamsResult.getPtrOrNull(); - if (genericParamsResult.hasCodeCompletion()) - return makeParserCodeCompletionStatus(); - - DefaultArgumentInfo defaultArgs; - TypeRepr *funcRetTy = nullptr; - DeclName fullName; - ParameterList *params; - SourceLoc throwsLoc; - bool rethrows; - ParserStatus signatureStatus = - parseFunctionSignature(simpleName, fullName, ParameterContextKind::Call, - params, defaultArgs, throwsLoc, rethrows, - funcRetTy); - - signatureHasCodeCompletion |= signatureStatus.hasCodeCompletion(); - if (signatureStatus.hasCodeCompletion() && !CodeCompletion) { - // Trigger delayed parsing, no need to continue. - return signatureStatus; - } - - diagnoseWhereClauseInGenericParamList(genericParams); - - // Create the 'call` declaration and add it to the parent scope. - auto *CD = CallDecl::create(Context, fullName, callLoc, - /*throws*/ throwsLoc.isValid(), throwsLoc, - /*genericParams*/ nullptr, params, funcRetTy, - CurDeclContext); - - // Parse a 'where' clause if present, adding it to our GenericParamList. - if (Tok.is(tok::kw_where)) { - ContextChange CC(*this, CD); - - auto whereStatus = parseFreestandingGenericWhereClause(genericParams); - signatureHasCodeCompletion |= whereStatus.hasCodeCompletion(); - if (whereStatus.hasCodeCompletion() && !CodeCompletion) { - // Trigger delayed parsing, no need to continue. - return whereStatus; - } - } - - CD->setGenericParams(genericParams); - - // Protocol method arguments may not have default values. - if (Flags.contains(PD_InProtocol) && defaultArgs.HasDefaultArgument) { - diagnose(callLoc, diag::protocol_method_argument_init); - return nullptr; - } - - // Add the 'rethrows' attribute. - if (rethrows) - Attributes.add(new (Context) RethrowsAttr(throwsLoc)); - - // Add the attributes here so if we need them while parsing the body - // they are available. - CD->getAttrs() = Attributes; - - // Pass the function signature to code completion. - if (signatureHasCodeCompletion) - CodeCompletion->setParsedDecl(CD); - - defaultArgs.setFunctionContext(CD, CD->getParameters()); - setLocalDiscriminator(CD); - - if (Flags.contains(PD_InProtocol)) { - if (Tok.is(tok::l_brace)) { - diagnose(Tok, diag::protocol_method_with_body); - skipSingle(); - } - } else { - parseAbstractFunctionBody(CD); - } - - addToScope(CD); - return DCC.fixupParserResult(CD); -} -// SWIFT_ENABLE_TENSORFLOW END - /// Parse function body into \p AFD. void Parser::parseAbstractFunctionBody(AbstractFunctionDecl *AFD) { Scope S(this, ScopeKind::FunctionBody); @@ -6168,8 +6033,7 @@ Parser::parseDeclEnumCase(ParseDeclOptions Flags, return Status; } - // SWIFT_ENABLE_TENSORFLOW - if (Tok.is(tok::identifier) || Tok.is(tok::kw_call)) { + if (Tok.is(tok::identifier)) { Status |= parseIdentifierDeclName(*this, Name, NameLoc, "enum 'case'", tok::l_paren, tok::kw_case, tok::colon, tok::r_brace); diff --git a/lib/Parse/ParseExpr.cpp b/lib/Parse/ParseExpr.cpp index 48e969441d77c..17c73ed7a9448 100644 --- a/lib/Parse/ParseExpr.cpp +++ b/lib/Parse/ParseExpr.cpp @@ -1537,8 +1537,6 @@ ParserResult Parser::parseExprPrimary(Diag<> ID, bool isExprBasic) { case tok::identifier: // foo case tok::kw_self: // self - // SWIFT_ENABLE_TENSORFLOW - case tok::kw_call: // call, treated as a keyword when parsing declarations // If we are parsing a refutable pattern and are inside a let/var pattern, // the identifiers change to be value bindings instead of decl references. @@ -2129,8 +2127,7 @@ DeclName Parser::parseUnqualifiedDeclName(bool afterDot, // Consume the base name. DeclBaseName baseName; SourceLoc baseNameLoc; - // SWIFT_ENABLE_TENSORFLOW - if (Tok.isAny(tok::identifier, tok::kw_Self, tok::kw_self, tok::kw_call)) { + if (Tok.isAny(tok::identifier, tok::kw_Self, tok::kw_self)) { baseName = Context.getIdentifier(Tok.getText()); baseNameLoc = consumeToken(); } else if (allowOperators && Tok.isAnyOperator()) { @@ -2238,8 +2235,7 @@ DeclName Parser::parseUnqualifiedDeclName(bool afterDot, /// expr-identifier: /// unqualified-decl-name generic-args? Expr *Parser::parseExprIdentifier() { - // SWIFT_ENABLE_TENSORFLOW - assert(Tok.isAny(tok::identifier, tok::kw_self, tok::kw_Self, tok::kw_call)); + assert(Tok.isAny(tok::identifier, tok::kw_self, tok::kw_Self)); SyntaxParsingContext IDSyntaxContext(SyntaxContext, SyntaxKind::IdentifierExpr); Token IdentTok = Tok; diff --git a/lib/Parse/ParsePattern.cpp b/lib/Parse/ParsePattern.cpp index 33ee4c2044ddd..b8af9b38bb52c 100644 --- a/lib/Parse/ParsePattern.cpp +++ b/lib/Parse/ParsePattern.cpp @@ -89,8 +89,6 @@ static ParserStatus parseDefaultArgument( Diag<> diagID = { DiagID() }; switch (paramContext) { case Parser::ParameterContextKind::Function: - // SWIFT_ENABLE_TENSORFLOW - case Parser::ParameterContextKind::Call: case Parser::ParameterContextKind::Operator: case Parser::ParameterContextKind::Initializer: break; @@ -543,8 +541,6 @@ mapParsedParameters(Parser &parser, case Parser::ParameterContextKind::Curried: case Parser::ParameterContextKind::Initializer: case Parser::ParameterContextKind::Function: - // SWIFT_ENABLE_TENSORFLOW - case Parser::ParameterContextKind::Call: isKeywordArgumentByDefault = true; break; } @@ -609,8 +605,6 @@ mapParsedParameters(Parser &parser, assert((paramContext == Parser::ParameterContextKind::Function || paramContext == Parser::ParameterContextKind::Operator || paramContext == Parser::ParameterContextKind::Initializer || - // SWIFT_ENABLE_TENSORFLOW - paramContext == Parser::ParameterContextKind::Call || paramContext == Parser::ParameterContextKind::EnumElement) && "Default arguments are only permitted on the first param clause"); DefaultArgumentKind kind = getDefaultArgKind(param.DefaultArg); @@ -636,10 +630,6 @@ Parser::parseSingleParameterClause(ParameterContextKind paramContext, // If we don't have the leading '(', complain. Diag<> diagID; switch (paramContext) { - // SWIFT_ENABLE_TENSORFLOW - case ParameterContextKind::Call: - diagID = diag::expected_lparen_call; - break; case ParameterContextKind::Function: case ParameterContextKind::Operator: diagID = diag::func_decl_without_paren; @@ -726,8 +716,6 @@ Parser::parseFunctionArguments(SmallVectorImpl &NamePieces, ParserStatus Parser::parseFunctionSignature(Identifier SimpleName, DeclName &FullName, - // SWIFT_ENABLE_TENSORFLOW - ParameterContextKind paramContext, ParameterList *&bodyParams, DefaultArgumentInfo &defaultArgs, SourceLoc &throwsLoc, @@ -737,6 +725,8 @@ Parser::parseFunctionSignature(Identifier SimpleName, SmallVector NamePieces; ParserStatus Status; + ParameterContextKind paramContext = SimpleName.isOperator() ? + ParameterContextKind::Operator : ParameterContextKind::Function; Status |= parseFunctionArguments(NamePieces, bodyParams, paramContext, defaultArgs); FullName = DeclName(Context, SimpleName, NamePieces); @@ -922,9 +912,7 @@ ParserResult Parser::parsePattern() { PatternCtx.setCreateSyntax(SyntaxKind::WildcardPattern); return makeParserResult(new (Context) AnyPattern(consumeToken(tok::kw__))); - case tok::identifier: - // SWIFT_ENABLE_TENSORFLOW - case tok::kw_call: { + case tok::identifier: { PatternCtx.setCreateSyntax(SyntaxKind::IdentifierPattern); Identifier name; SourceLoc loc = consumeIdentifier(&name); diff --git a/lib/Parse/Parser.cpp b/lib/Parse/Parser.cpp index eeba08f4cc563..34ac137cc5c6f 100644 --- a/lib/Parse/Parser.cpp +++ b/lib/Parse/Parser.cpp @@ -826,8 +826,7 @@ bool Parser::parseSpecificIdentifier(StringRef expected, SourceLoc &loc, /// its name in Result. Otherwise, emit an error and return true. bool Parser::parseAnyIdentifier(Identifier &Result, SourceLoc &Loc, const Diagnostic &D) { - // SWIFT_ENABLE_TENSORFLOW - if (Tok.is(tok::identifier) || Tok.isAnyOperator() || Tok.is(tok::kw_call)) { + if (Tok.is(tok::identifier) || Tok.isAnyOperator()) { Result = Context.getIdentifier(Tok.getText()); Loc = Tok.getLoc(); consumeToken(); diff --git a/lib/SILGen/SILGenDecl.cpp b/lib/SILGen/SILGenDecl.cpp index f3cb4fd74476c..3960392e6ba67 100644 --- a/lib/SILGen/SILGenDecl.cpp +++ b/lib/SILGen/SILGenDecl.cpp @@ -1399,9 +1399,7 @@ void SILGenModule::emitExternalWitnessTable(ProtocolConformance *c) { void SILGenModule::emitExternalDefinition(Decl *d) { switch (d->getKind()) { case DeclKind::Func: - case DeclKind::Accessor: - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: { + case DeclKind::Accessor: { emitFunction(cast(d)); break; } diff --git a/lib/Sema/CSApply.cpp b/lib/Sema/CSApply.cpp index 869fadd1392a0..7567729619e6e 100644 --- a/lib/Sema/CSApply.cpp +++ b/lib/Sema/CSApply.cpp @@ -7549,11 +7549,6 @@ Expr *ExprRewriter::finishApply(ApplyExpr *apply, Type openedType, llvm_unreachable("Unhandled DeclTypeCheckingSemantics in switch."); }; - // SWIFT_ENABLE_TENSORFLOW - // Save the original potentially lvalue function for rewriting `call` method - // applications. - auto *originalFn = fn; - // SWIFT_ENABLE_TENSORFLOW END // The function is always an rvalue. fn = cs.coerceToRValue(fn); @@ -7764,57 +7759,6 @@ Expr *ExprRewriter::finishApply(ApplyExpr *apply, Type openedType, return finishApply(apply, openedType, locator); } - // SWIFT_ENABLE_TENSORFLOW - // Handle `call` method applications. - auto &ctx = cs.getASTContext(); - - TupleExpr *arg = dyn_cast(apply->getArg()); - if (auto parenExpr = dyn_cast(apply->getArg())) - arg = TupleExpr::createImplicit(ctx, parenExpr->getSubExpr(), {}); - - // Get resolved `call` method and verify it. - auto loc = locator.withPathElement(ConstraintLocator::ApplyFunction); - auto selected = solution.getOverloadChoice(cs.getConstraintLocator(loc)); - auto choice = selected.choice; - if (auto *method = dyn_cast(selected.choice.getDecl())) { - auto methodType = - simplifyType(selected.openedType)->castTo(); - auto selfParam = method->getImplicitSelfDecl(); - // Diagnose `mutating` method call on immutable value. - if (!cs.getType(originalFn)->hasLValueType() && selfParam->isInOut()) { - AssignmentFailure failure(originalFn, cs, originalFn->getLoc(), - diag::cannot_pass_rvalue_mutating_subelement, - diag::cannot_pass_rvalue_mutating); - failure.diagnose(); - return nullptr; - } - // Create direct reference to `call` method. - bool isDynamic = choice.getKind() == OverloadChoiceKind::DeclViaDynamic; - Expr *declRef = buildMemberRef(originalFn, selected.openedFullType, - /*dotLoc=*/SourceLoc(), choice, - DeclNameLoc(fn->getEndLoc()), - selected.openedType, loc, loc, - /*Implicit=*/true, - choice.getFunctionRefKind(), - AccessSemantics::Ordinary, isDynamic); - if (!declRef) - return nullptr; - declRef->setImplicit(apply->isImplicit()); - apply->setFn(declRef); - // Coerce argument to input type of `call` method. - SmallVector argLabelsScratch; - auto *arg = coerceCallArguments(apply->getArg(), methodType, apply, - apply->getArgumentLabels(argLabelsScratch), - apply->hasTrailingClosure(), loc); - if (!arg) - return nullptr; - apply->setArg(arg); - cs.setType(apply, methodType->getResult()); - cs.cacheExprTypes(apply); - return apply; - } - // SWIFT_ENABLE_TENSORFLOW END - // Handle @dynamicCallable applications. // At this point, all other ApplyExpr cases have been handled. return finishApplyDynamicCallable(*this, cs, solution, apply, locator); diff --git a/lib/Sema/CSDiag.cpp b/lib/Sema/CSDiag.cpp index 98bd12556d368..eb96bfeac9a49 100644 --- a/lib/Sema/CSDiag.cpp +++ b/lib/Sema/CSDiag.cpp @@ -5328,18 +5328,9 @@ bool FailureDiagnosis::visitApplyExpr(ApplyExpr *callExpr) { !fnType->is() && !fnType->is()) { auto arg = callExpr->getArg(); - // SWIFT_ENABLE_TENSORFLOW - auto isDynamicCallable = - CS.DynamicCallableCache[fnType->getCanonicalType()].isValid(); - - auto *nominal = fnType->getAnyNominal(); - auto hasCallDecls = nominal && - llvm::any_of(nominal->getMembers(), [](Decl *member) { - return isa(member); - }); // Diagnose @dynamicCallable errors. - if (isDynamicCallable) { + if (CS.DynamicCallableCache[fnType->getCanonicalType()].isValid()) { auto dynamicCallableMethods = CS.DynamicCallableCache[fnType->getCanonicalType()]; @@ -5393,9 +5384,7 @@ bool FailureDiagnosis::visitApplyExpr(ApplyExpr *callExpr) { } } - // SWIFT_ENABLE_TENSORFLOW - if (!isDynamicCallable && !hasCallDecls) - return true; + return true; } bool hasTrailingClosure = callArgHasTrailingClosure(callExpr->getArg()); diff --git a/lib/Sema/CSSimplify.cpp b/lib/Sema/CSSimplify.cpp index 9a4107d8678a3..37893bb1a2a07 100644 --- a/lib/Sema/CSSimplify.cpp +++ b/lib/Sema/CSSimplify.cpp @@ -4585,60 +4585,6 @@ ConstraintSystem::simplifyApplicableFnConstraint( return simplified; } - // SWIFT_ENABLE_TENSORFLOW - // Handle applications of types with `call` methods. - if (desugar2->mayHaveMembers()) { - auto &ctx = getASTContext(); - // Get all `call` methods of the nominal type. - SmallVector callDecls; - auto candidates = - lookupMember(desugar2, DeclName(ctx.getIdentifier("$call"))); - for (auto entry : candidates) { - auto callDecl = dyn_cast(entry.getValueDecl()); - if (!callDecl) - continue; - callDecls.push_back(callDecl); - } - - // Handle `call` methods calls. - if (!callDecls.empty()) { - // Create a type variable for the `call` method. - auto loc = getConstraintLocator(locator); - auto tv = createTypeVariable(loc, TVO_CanBindToLValue); - - // Record the `call` method overload set. - SmallVector choices; - for (auto candidate : callDecls) { - TC.validateDecl(candidate); - if (candidate->isInvalid()) continue; - choices.push_back( - OverloadChoice(type2, candidate, FunctionRefKind::SingleApply)); - } - if (choices.empty()) return SolutionKind::Error; - addOverloadSet(tv, choices, DC, loc); - - // Create type variables for each parameter type. - SmallVector tvParams; - for (unsigned i : range(func1->getNumParams())) { - auto param = func1->getParams()[i]; - auto paramType = param.getPlainType(); - - auto *tvParam = createTypeVariable(loc); - auto locatorBuilder = - locator.withPathElement(LocatorPathElt::getTupleElement(i)); - addConstraint(ConstraintKind::ArgumentConversion, paramType, - tvParam, locatorBuilder); - tvParams.push_back(AnyFunctionType::Param(tvParam)); - } - // Create target function type and an applicable function constraint. - AnyFunctionType *funcType = - FunctionType::get(tvParams, func1->getResult()); - addConstraint(ConstraintKind::ApplicableFunction, funcType, tv, locator); - - return SolutionKind::Solved; - } - } - // Handle applications of @dynamicCallable types. return simplifyDynamicCallableApplicableFnConstraint(type1, origType2, subflags, locator); diff --git a/lib/Sema/ConstraintLocator.cpp b/lib/Sema/ConstraintLocator.cpp index 75fa6fb9b6f62..6b84550c78c81 100644 --- a/lib/Sema/ConstraintLocator.cpp +++ b/lib/Sema/ConstraintLocator.cpp @@ -54,8 +54,6 @@ void ConstraintLocator::Profile(llvm::FoldingSetNodeID &id, Expr *anchor, case MemberRefBase: case UnresolvedMember: case SubscriptMember: - // SWIFT_ENABLE_TENSORFLOW - case CallMethod: case ConstructorMember: case LValueConversion: case RValueAdjustment: @@ -196,11 +194,6 @@ void ConstraintLocator::dump(SourceManager *sm, raw_ostream &out) { out << "sequence iterator type"; break; - // SWIFT_ENABLE_TENSORFLOW - case CallMethod: - out << "call method"; - break; - case SubscriptMember: out << "subscript member"; break; diff --git a/lib/Sema/ConstraintLocator.h b/lib/Sema/ConstraintLocator.h index 675be446b4abc..83e5de54cc743 100644 --- a/lib/Sema/ConstraintLocator.h +++ b/lib/Sema/ConstraintLocator.h @@ -85,9 +85,6 @@ class ConstraintLocator : public llvm::FoldingSetNode { MemberRefBase, /// \brief The lookup for a subscript member. SubscriptMember, - // SWIFT_ENABLE_TENSORFLOW - /// \brief The lookup for a call method. - CallMethod, /// \brief The lookup for a constructor member. ConstructorMember, /// \brief An implicit @lvalue-to-inout conversion; only valid for operator @@ -144,8 +141,6 @@ class ConstraintLocator : public llvm::FoldingSetNode { case MemberRefBase: case UnresolvedMember: case SubscriptMember: - // SWIFT_ENABLE_TENSORFLOW - case CallMethod: case ConstructorMember: case LValueConversion: case RValueAdjustment: @@ -209,8 +204,6 @@ class ConstraintLocator : public llvm::FoldingSetNode { case LValueConversion: case RValueAdjustment: case SubscriptMember: - // SWIFT_ENABLE_TENSORFLOW - case CallMethod: case OpenedGeneric: case GenericParameter: case GenericArgument: diff --git a/lib/Sema/TypeCheckAttr.cpp b/lib/Sema/TypeCheckAttr.cpp index 750bb5830c438..da7254d900316 100644 --- a/lib/Sema/TypeCheckAttr.cpp +++ b/lib/Sema/TypeCheckAttr.cpp @@ -768,8 +768,6 @@ void TypeChecker::checkDeclAttributesEarly(Decl *D) { StringRef OnlyKind; switch (PossibleDeclKinds) { case DeclAttribute::OnAccessor: OnlyKind = "accessor"; break; - // SWIFT_ENABLE_TENSORFLOW - case DeclAttribute::OnCall: OnlyKind = "call"; break; case DeclAttribute::OnClass: OnlyKind = "class"; break; case DeclAttribute::OnConstructor: OnlyKind = "init"; break; case DeclAttribute::OnDestructor: OnlyKind = "deinit"; break; diff --git a/lib/Sema/TypeCheckDecl.cpp b/lib/Sema/TypeCheckDecl.cpp index e23f703bb25b8..6fc8fc66afb0e 100644 --- a/lib/Sema/TypeCheckDecl.cpp +++ b/lib/Sema/TypeCheckDecl.cpp @@ -3284,42 +3284,6 @@ class DeclChecker : public DeclVisitor { } } - // SWIFT_ENABLE_TENSORFLOW - void visitCallDecl(CallDecl *CD) { - TC.validateDecl(CD); - - if (!CD->isInvalid()) { - checkGenericParams(CD->getGenericParams(), CD); - TC.checkReferencedGenericParams(CD); - TC.checkProtocolSelfRequirements(CD); - } - - checkAccessControl(TC, CD); - - if (!checkOverrides(CD)) { - // If a method has an 'override' keyword but does not - // override anything, complain. - if (auto *OA = CD->getAttrs().getAttribute()) { - if (!CD->getOverriddenDecl()) { - TC.diagnose(CD, diag::method_does_not_override) - .highlight(OA->getLocation()); - OA->setInvalid(); - } - } - } - - if (requiresDefinition(CD) && !CD->hasBody()) { - // Complain if we should have a body. - TC.diagnose(CD->getLoc(), diag::func_decl_without_brace); - } else { - // Record the body. - TC.definedFunctions.push_back(CD); - } - - if (CD->getAttrs().hasAttribute()) - TC.checkDynamicReplacementAttribute(CD); - } - void visitModuleDecl(ModuleDecl *) { } void visitEnumCaseDecl(EnumCaseDecl *ECD) { @@ -4156,9 +4120,7 @@ void TypeChecker::validateDecl(ValueDecl *D) { } case DeclKind::Func: - case DeclKind::Accessor: - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: { + case DeclKind::Accessor: { auto *FD = cast(D); assert(!FD->hasInterfaceType()); diff --git a/lib/Sema/TypeCheckNameLookup.cpp b/lib/Sema/TypeCheckNameLookup.cpp index 7921cb53100d4..c52696575c890 100644 --- a/lib/Sema/TypeCheckNameLookup.cpp +++ b/lib/Sema/TypeCheckNameLookup.cpp @@ -625,12 +625,6 @@ static bool isPlausibleTypo(DeclRefKind refKind, DeclName typedName, if (!candidate->hasName()) return false; - // SWIFT_ENABLE_TENSORFLOW - // Ignore `call` declarations. Otherwise, "did you mean '$call'" diagnostics - // will be produced. - if (isa(candidate)) - return false; - // An operator / identifier mismatch is never a plausible typo. auto fn = dyn_cast(candidate); if (typedName.isOperator() != (fn && fn->isOperator())) diff --git a/lib/Sema/TypeCheckProtocol.cpp b/lib/Sema/TypeCheckProtocol.cpp index aa5395375751e..fb2d3422cb4e7 100644 --- a/lib/Sema/TypeCheckProtocol.cpp +++ b/lib/Sema/TypeCheckProtocol.cpp @@ -1964,10 +1964,6 @@ static diag::RequirementKind getRequirementKind(ValueDecl *VD) { if (isa(VD)) return diag::RequirementKind::Constructor; - // SWIFT_ENABLE_TENSORFLOW - if (isa(VD)) - return diag::RequirementKind::Call; - if (isa(VD)) return diag::RequirementKind::Func; diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp index f928e3d0be350..3b54e9fe49571 100644 --- a/lib/Serialization/Serialization.cpp +++ b/lib/Serialization/Serialization.cpp @@ -1755,8 +1755,6 @@ static bool shouldSerializeMember(Decl *D) { case DeclKind::Param: case DeclKind::Func: case DeclKind::Accessor: - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: return true; } @@ -3405,67 +3403,6 @@ void Serializer::writeDecl(const Decl *D) { break; } - // SWIFT_ENABLE_TENSORFLOW - case DeclKind::Call: { - auto fn = cast(D); - verifyAttrSerializable(fn); - - auto contextID = addDeclContextRef(fn->getDeclContext()); - - unsigned abbrCode = DeclTypeAbbrCodes[CallLayout::Code]; - SmallVector nameComponentsAndDependencies; - nameComponentsAndDependencies.push_back( - addDeclBaseNameRef(fn->getFullName().getBaseName())); - for (auto argName : fn->getFullName().getArgumentNames()) - nameComponentsAndDependencies.push_back(addDeclBaseNameRef(argName)); - - uint8_t rawAccessLevel = getRawStableAccessLevel(fn->getFormalAccess()); - uint8_t rawDefaultArgumentResilienceExpansion = - getRawStableResilienceExpansion( - fn->getDefaultArgumentResilienceExpansion()); - - Type ty = fn->getInterfaceType(); - for (auto dependency : collectDependenciesFromType(ty->getCanonicalType())) - nameComponentsAndDependencies.push_back(addTypeRef(dependency)); - - CallLayout::emitRecord(Out, ScratchRecord, abbrCode, - contextID, - fn->isImplicit(), - fn->isStatic(), - uint8_t( - getStableStaticSpelling(fn->getStaticSpelling())), - fn->isObjC(), - uint8_t( - getStableSelfAccessKind(fn->getSelfAccessKind())), - fn->hasDynamicSelf(), - fn->hasForcedStaticDispatch(), - fn->hasThrows(), - addGenericEnvironmentRef( - fn->getGenericEnvironment()), - addTypeRef(fn->getResultInterfaceType()), - addDeclRef(fn->getOperatorDecl()), - addDeclRef(fn->getOverriddenDecl()), - fn->getFullName().getArgumentNames().size() + - fn->getFullName().isCompoundName(), - rawAccessLevel, - fn->needsNewVTableEntry(), - rawDefaultArgumentResilienceExpansion, - nameComponentsAndDependencies); - - writeGenericParams(fn->getGenericParams()); - - // Write the body parameters. - writeParameterList(fn->getParameters()); - - if (auto errorConvention = fn->getForeignErrorConvention()) - writeForeignErrorConvention(*errorConvention); - - writeInlinableBodyTextIfNeeded(fn); - - break; - } - // SWIFT_ENABLE_TENSORFLOW END - case DeclKind::EnumElement: { auto elem = cast(D); auto contextID = addDeclContextRef(elem->getDeclContext()); diff --git a/test/AutoDiff/simple_model.swift b/test/AutoDiff/simple_model.swift index ac850308ce1ed..f9b6a6cec6e33 100644 --- a/test/AutoDiff/simple_model.swift +++ b/test/AutoDiff/simple_model.swift @@ -5,32 +5,97 @@ import StdlibUnittest var SimpleModelTests = TestSuite("SimpleModel") -protocol Layer : Differentiable, VectorNumeric { - @differentiable - call func(_ input: Float) -> Float +struct DenseLayer : Equatable { + @differentiable(wrt: self, vjp: vjpW) + let w: Float + func vjpW() -> (Float, (Float) -> DenseLayer) { + return (w, { dw in DenseLayer(w: dw, b: 0) } ) + } + + @differentiable(wrt: self, vjp: vjpB) + let b: Float + func vjpB() -> (Float, (Float) -> DenseLayer) { + return (b, { db in DenseLayer(w: 0, b: db) } ) + } } -struct DenseLayer : Layer { - let w, b: Float +extension DenseLayer : Differentiable, VectorNumeric { + typealias TangentVector = DenseLayer + typealias CotangentVector = DenseLayer + typealias Scalar = Float + static var zero: DenseLayer { + return DenseLayer(w: 0, b: 0) + } + static func + (lhs: DenseLayer, rhs: DenseLayer) -> DenseLayer { + return DenseLayer(w: lhs.w + rhs.w, b: lhs.b + rhs.b) + } + static func - (lhs: DenseLayer, rhs: DenseLayer) -> DenseLayer { + return DenseLayer(w: lhs.w - rhs.w, b: lhs.b - rhs.b) + } + static func * (lhs: DenseLayer, rhs: DenseLayer) -> DenseLayer { + return DenseLayer(w: lhs.w * rhs.w, b: lhs.b * rhs.b) + } + static func * (lhs: Float, rhs: DenseLayer) -> DenseLayer { + return DenseLayer(w: lhs * rhs.w, b: lhs * rhs.b) + } +} - @differentiable - call func(_ input: Float) -> Float { +extension DenseLayer { + func prediction(for input: Float) -> Float { return input * w + b } } -struct Model : Layer { - let l1, l2, l3: DenseLayer +struct Model : Equatable { + @differentiable(wrt: self, vjp: vjpL1) + let l1: DenseLayer + func vjpL1() -> (DenseLayer, (DenseLayer) -> Model) { + return (l1, { dl1 in Model(l1: dl1, l2: DenseLayer.zero, l3: DenseLayer.zero) } ) + } - @differentiable - call func(_ input: Float) -> Float { - // This model is silly because it has no nonlinearities. - // But it is simple and good enough for testing purposes. - return l3(l2(l1(input))) + @differentiable(wrt: self, vjp: vjpL2) + let l2: DenseLayer + func vjpL2() -> (DenseLayer, (DenseLayer) -> Model) { + return (l2, { dl2 in Model(l1: DenseLayer.zero, l2: dl2, l3: DenseLayer.zero) } ) + } + + @differentiable(wrt: self, vjp: vjpL3) + let l3: DenseLayer + func vjpL3() -> (DenseLayer, (DenseLayer) -> Model) { + return (l3, { dl3 in Model(l1: DenseLayer.zero, l2: DenseLayer.zero, l3: dl3) } ) + } +} + +extension Model : Differentiable, VectorNumeric { + typealias TangentVector = Model + typealias CotangentVector = Model + typealias Scalar = Float + static var zero: Model { + return Model(l1: DenseLayer.zero, l2: DenseLayer.zero, l3: DenseLayer.zero) + } + static func + (lhs: Model, rhs: Model) -> Model { + return Model(l1: lhs.l1 + rhs.l1, l2: lhs.l2 + rhs.l2, l3: lhs.l3 + rhs.l3) + } + static func - (lhs: Model, rhs: Model) -> Model { + return Model(l1: lhs.l1 - rhs.l1, l2: lhs.l2 - rhs.l2, l3: lhs.l3 - rhs.l3) + } + static func * (lhs: Model, rhs: Model) -> Model { + return Model(l1: lhs.l1 * rhs.l1, l2: lhs.l2 * rhs.l2, l3: lhs.l3 * rhs.l3) + } + static func * (lhs: Float, rhs: Model) -> Model { + return Model(l1: lhs * rhs.l1, l2: lhs * rhs.l2, l3: lhs * rhs.l3) } } extension Model { + func prediction(for input: Float) -> Float { + // This "model" is silly because it doesn't have nonlinearities. But it's + // simple and good enough for testing purposes. + let activation1 = l1.prediction(for: input) + let activation2 = l2.prediction(for: activation1) + return l3.prediction(for: activation2) + } + func loss(of prediction: Float, from label: Float) -> Float { return (prediction - label) * (prediction - label) } @@ -42,8 +107,8 @@ SimpleModelTests.test("gradient") { let label: Float = 3 let input: Float = 1 let gradModel = model.gradient { model -> Float in - let prediction = model(input) - return model.loss(of: prediction, from: label) + let pred = model.prediction(for: input) + return model.loss(of: pred, from: label) } let expectedGrad = Model(l1: DenseLayer(w: -4, b: -4), l2: DenseLayer(w: -4, b: -4), diff --git a/test/Sema/immutability.swift b/test/Sema/immutability.swift index b2e19a9c0340a..7043fbe1e8dc4 100644 --- a/test/Sema/immutability.swift +++ b/test/Sema/immutability.swift @@ -59,8 +59,7 @@ class FooClass { self = FooClass() // expected-error {{cannot assign to value: 'self' is immutable}} } - // SWIFT_ENABLE_TENSORFLOW - mutating init(a : Bool) {} // expected-error {{'mutating' modifier cannot be applied to this declaration}} {{3-12=}} + mutating init(a : Bool) {} // expected-error {{'mutating' may only be used on 'func' declarations}} {{3-12=}} mutating // expected-error {{'mutating' isn't valid on methods in classes or class-bound protocols}} {{3-12=}} func baz() {} diff --git a/test/SourceKit/CodeComplete/complete_override.swift.response b/test/SourceKit/CodeComplete/complete_override.swift.response index 903819202678a..4ec04873a57b3 100644 --- a/test/SourceKit/CodeComplete/complete_override.swift.response +++ b/test/SourceKit/CodeComplete/complete_override.swift.response @@ -9,15 +9,6 @@ key.context: source.codecompletion.context.none, key.num_bytes_to_erase: 0 }, - { - key.kind: source.lang.swift.keyword, - key.name: "call", - key.sourcetext: "call", - key.description: "call", - key.typename: "", - key.context: source.codecompletion.context.none, - key.num_bytes_to_erase: 0 - }, { key.kind: source.lang.swift.keyword, key.name: "class", diff --git a/test/TensorFlowRuntime/model_autodiff_runtime.swift b/test/TensorFlowRuntime/model_autodiff_runtime.swift index 58579dbec6acd..248d769559ba5 100644 --- a/test/TensorFlowRuntime/model_autodiff_runtime.swift +++ b/test/TensorFlowRuntime/model_autodiff_runtime.swift @@ -22,8 +22,8 @@ public protocol Layer: Differentiable & KeyPathIterable where AllDifferentiableVariables : KeyPathIterable { associatedtype Input: Differentiable associatedtype Output: Differentiable - @differentiable - call func(_ input: Input) -> Output + @differentiable(wrt: (self, input)) + func applied(to input: Input) -> Output } @_fixed_layout @@ -40,7 +40,7 @@ public struct Dense: Layer { } @differentiable - public call func(_ input: Tensor) -> Tensor { + public func applied(to input: Tensor) -> Tensor { return activation(matmul(input, weight) + bias) } } @@ -78,7 +78,7 @@ public struct Conv2D: Layer { } @differentiable - public call func(_ input: Tensor) -> Tensor { + public func applied(to input: Tensor) -> Tensor { return activation(input.convolved2D(withFilter: filter, strides: (1, strides.0, strides.1, 1), padding: padding) + bias) @@ -116,7 +116,9 @@ public class RiemannSGD: Optimizer ModelADTests.testAllBackends("SimpleLayerAD") { let ones = Tensor(ones: [2, 2]) let dense = Dense(inputSize: 2, outputSize: 2, activation: { $0 }) - let grad = gradient(at: dense) { dense in dense(ones).sum() } + let grad = gradient(at: dense) { dense in + dense.applied(to: ones).sum() + } expectEqual([[2, 2], [2, 2]], grad.weight) expectEqual([2, 2], grad.bias) } @@ -128,9 +130,10 @@ ModelADTests.testAllBackends("XORTraining") { l1 = Dense(inputSize: 2, outputSize: hiddenSize, activation: relu) l2 = Dense(inputSize: hiddenSize, outputSize: 1, activation: relu) } - @differentiable - call func(_ input: Tensor) -> Tensor { - return l2(l1(input)) + @differentiable(wrt: (self, input)) + func applied(to input: Tensor) -> Tensor { + let h1 = l1.applied(to: input) + return l2.applied(to: h1) } } var classifier = Classifier(hiddenSize: 4) @@ -139,12 +142,12 @@ ModelADTests.testAllBackends("XORTraining") { let y: Tensor = [0, 1, 1, 0] for _ in 0..<1000 { let 𝛁model = classifier.gradient { classifier -> Tensor in - let ŷ = classifier(x) + let ŷ = classifier.applied(to: x) return meanSquaredError(predicted: ŷ, expected: y) } optimizer.update(&classifier.allDifferentiableVariables, along: 𝛁model) } - _ = classifier([[0, 0], [0, 1], [1, 0], [1, 1]]) + print(classifier.applied(to: [[0, 0], [0, 1], [1, 0], [1, 1]])) } ModelADTests.testAllBackends("WithRespectToModel") { @@ -152,17 +155,18 @@ ModelADTests.testAllBackends("WithRespectToModel") { var bar: Tensor var baz: Tensor - @differentiable - call func(_ input: Tensor) -> Tensor { + @differentiable(wrt: (self, input)) + func applied(to input: Tensor) -> Tensor { return bar + input } } let x = Tensor(0) var model = Foo(bar: x, baz: x) - let 𝛁model = gradient(at: model) { model in model(x) } - expectEqual( - Foo.AllDifferentiableVariables(bar: Tensor(1.0), baz: Tensor(0.0)), - 𝛁model) + let d = gradient(at: model) { model in + model.applied(to: x) + } + expectEqual(Foo.AllDifferentiableVariables(bar: Tensor(1.0), + baz: Tensor(0.0)), d) } runAllTests() diff --git a/test/decl/call/callables.swift b/test/decl/call/callables.swift deleted file mode 100644 index 68cacc7302514..0000000000000 --- a/test/decl/call/callables.swift +++ /dev/null @@ -1,136 +0,0 @@ -// RUN: %target-typecheck-verify-swift - -struct SimpleCallable { - call func(_ x: Float) -> Float { - return x - } -} - -// Simple test. - -let foo = SimpleCallable() -_ = foo(1) -_ = foo(foo(1)) - -// Test direct `call` member references. - -_ = { foo(1) }() -_ = [1, 2, 3].map { foo($0) } -let _: (Float) -> Float = { foo($0) } - -func callable() -> SimpleCallable { - return SimpleCallable() -} -extension SimpleCallable { - var foo: SimpleCallable { - return self - } - func bar() -> SimpleCallable { - return self - } -} - -_ = foo.foo(1) -_ = foo.bar()(1) -_ = callable()(1) - -struct MultipleArgsCallable { - call func(x: Int, y: Float) -> [Int] { - return [x] - } -} - -let bar = MultipleArgsCallable() -_ = bar(x: 1, y: 1) -_ = bar(x: bar(x: 1, y: 1)[0], y: 1) - -struct Extended {} -extension Extended { - @discardableResult - call func() -> Extended { - return self - } -} -var extended = Extended() -extended()()() - -struct OptionalCallable { - call func() -> OptionalCallable? { - return self - } -} -var optional = OptionalCallable() -_ = optional()?()?() - -struct VariadicCallable { - call func(_ args: Int...) -> [Int] { - return args - } -} -var variadic = VariadicCallable() -_ = variadic() -_ = variadic(1, 2, 3) - -struct Mutating { - var x: Int - mutating call func() { - x += 1 - } -} -func testMutating(_ x: Mutating, _ y: inout Mutating) { - _ = x() // expected-error {{cannot use mutating member on immutable value: 'x' is a 'let' constant}} - _ = y() -} - -struct Throwing { - call func() throws -> Throwing { - return self - } -} -var throwing = Throwing() -_ = try throwing() - -enum BinaryOperation { - case add, subtract, multiply, divide -} -extension BinaryOperation { - call func(_ lhs: Float, _ rhs: Float) -> Float { - switch self { - case .add: return lhs + rhs - case .subtract: return lhs - rhs - case .multiply: return lhs * rhs - case .divide: return lhs / rhs - } - } -} -_ = BinaryOperation.add(1, 2) - -class BaseClass { - call func() -> Self { - return self - } -} -class SubClass : BaseClass { - override call func() -> Self { - return self - } -} - -func testIUO(a: SimpleCallable!, b: MultipleArgsCallable!, c: Extended!, - d: OptionalCallable!, e: Throwing!) { - _ = a(1) - _ = b(x: 1, y: 1) - _ = c() - _ = d()?()?() - _ = try? e() -} - -// Errors. - -// TODO: Fix this error. Ideally, it should be "extra argument in call". -// expected-error @+2 {{cannot call value of non-function type 'SimpleCallable'}} -// expected-error @+1 {{cannot invoke 'foo' with an argument list of type '(Int, Int)'}} -_ = foo(1, 1) - -_ = bar(1, 1) // expected-error {{missing argument labels 'x:y:' in call}} -let _: (Float) -> Float = foo // expected-error {{cannot convert value of type 'SimpleCallable' to specified type '(Float) -> Float'}} diff --git a/test/decl/call/generic.swift b/test/decl/call/generic.swift deleted file mode 100644 index 3a31f7d96f070..0000000000000 --- a/test/decl/call/generic.swift +++ /dev/null @@ -1,43 +0,0 @@ -// RUN: %target-typecheck-verify-swift - -protocol P0 { - call func(x: Self) -} - -struct ConcreteType { - call func(_ x: T, _ y: U) -> (T, U) { - return (x, y) - } - - call func(_ fn: @escaping (T) -> U) -> (T) -> U { - return fn - } -} - -let concrete = ConcreteType() -_ = concrete(1, 3.0) -_ = concrete(concrete, { concrete($0, $1) } as ([Int], Float) -> ([Int], Float)) - -func generic(_ x: T, _ y: U) { - _ = concrete(x, x) - _ = concrete(x, y) -} - -struct GenericType { - let collection: T - call func(_ x: U) -> Bool where U == T.Element, U : Equatable { - return collection.contains(x) - } -} - -// Test conditional conformance. -extension GenericType where T.Element : Numeric { - call func(initialValue: T.Element) -> T.Element { - return collection.reduce(initialValue, +) - } -} - -let genericString = GenericType<[String]>(collection: ["Hello", "world", "!"]) -_ = genericString("Hello") -let genericInt = GenericType>(collection: [1, 2, 3]) -_ = genericInt(initialValue: 1) diff --git a/tools/SourceKit/lib/SwiftLang/SwiftLangSupport.cpp b/tools/SourceKit/lib/SwiftLang/SwiftLangSupport.cpp index b099ee2587f6d..aac8587ed690a 100644 --- a/tools/SourceKit/lib/SwiftLang/SwiftLangSupport.cpp +++ b/tools/SourceKit/lib/SwiftLang/SwiftLangSupport.cpp @@ -271,8 +271,6 @@ UIdent SwiftLangSupport::getUIDForCodeCompletionDeclKind( case CodeCompletionDeclKind::Constructor: return KindRefConstructor; case CodeCompletionDeclKind::Destructor: return KindRefDestructor; case CodeCompletionDeclKind::Subscript: return KindRefSubscript; - // SWIFT_ENABLE_TENSORFLOW - case CodeCompletionDeclKind::Call: return KindRefCall; case CodeCompletionDeclKind::StaticMethod: return KindRefMethodClass; case CodeCompletionDeclKind::InstanceMethod: return KindRefMethodInstance; case CodeCompletionDeclKind::PrefixOperatorFunction: return KindRefFunctionPrefixOperator; @@ -300,8 +298,6 @@ UIdent SwiftLangSupport::getUIDForCodeCompletionDeclKind( case CodeCompletionDeclKind::Constructor: return KindDeclConstructor; case CodeCompletionDeclKind::Destructor: return KindDeclDestructor; case CodeCompletionDeclKind::Subscript: return KindDeclSubscript; - // SWIFT_ENABLE_TENSORFLOW - case CodeCompletionDeclKind::Call: return KindDeclCall; case CodeCompletionDeclKind::StaticMethod: return KindDeclMethodClass; case CodeCompletionDeclKind::InstanceMethod: return KindDeclMethodInstance; case CodeCompletionDeclKind::PrefixOperatorFunction: return KindDeclFunctionPrefixOperator; @@ -404,9 +400,6 @@ UIdent SwiftLangSupport::getUIDForSyntaxStructureKind( return KindDeclTypeAlias; case SyntaxStructureKind::Subscript: return KindDeclSubscript; - // SWIFT_ENABLE_TENSORFLOW - case SyntaxStructureKind::Call: - return KindDeclCall; case SyntaxStructureKind::AssociatedType: return KindDeclAssociatedType; case SyntaxStructureKind::GenericTypeParam: diff --git a/tools/swift-ide-test/swift-ide-test.cpp b/tools/swift-ide-test/swift-ide-test.cpp index fdfc949e9ac8b..67d0393cd7d83 100644 --- a/tools/swift-ide-test/swift-ide-test.cpp +++ b/tools/swift-ide-test/swift-ide-test.cpp @@ -1107,8 +1107,6 @@ class StructureAnnotator : public ide::SyntaxModelWalker { case SyntaxStructureKind::EnumElement: return "enum-elem"; case SyntaxStructureKind::TypeAlias: return "typealias"; case SyntaxStructureKind::Subscript: return "subscript"; - // SWIFT_ENABLE_TENSORFLOW - case SyntaxStructureKind::Call: return "call"; case SyntaxStructureKind::AssociatedType: return "associatedtype"; case SyntaxStructureKind::GenericTypeParam: return "generic-param"; case SyntaxStructureKind::Parameter: return "param"; diff --git a/utils/gyb_sourcekit_support/UIDs.py b/utils/gyb_sourcekit_support/UIDs.py index 9d5cf2a78b845..c3b8c0c34f227 100644 --- a/utils/gyb_sourcekit_support/UIDs.py +++ b/utils/gyb_sourcekit_support/UIDs.py @@ -276,9 +276,6 @@ def __init__(self, internal_name, external_name): KIND('RefPrecedenceGroup', 'source.lang.swift.ref.precedencegroup'), KIND('DeclSubscript', 'source.lang.swift.decl.function.subscript'), KIND('RefSubscript', 'source.lang.swift.ref.function.subscript'), - # SWIFT_ENABLE_TENSORFLOW - KIND('DeclCall', 'source.lang.swift.decl.function.call'), - KIND('RefCall', 'source.lang.swift.ref.function.call'), KIND('DeclVarGlobal', 'source.lang.swift.decl.var.global'), KIND('RefVarGlobal', 'source.lang.swift.ref.var.global'), KIND('DeclVarInstance', 'source.lang.swift.decl.var.instance'), diff --git a/utils/gyb_syntax_support/DeclNodes.py b/utils/gyb_syntax_support/DeclNodes.py index c411d0e7d2774..adad59c895b1c 100644 --- a/utils/gyb_syntax_support/DeclNodes.py +++ b/utils/gyb_syntax_support/DeclNodes.py @@ -380,8 +380,6 @@ 'SpacedBinaryOperatorToken', 'PrefixOperatorToken', 'PostfixOperatorToken', - # SWIFT_ENABLE_TENSORFLOW - 'CallToken', ]), Child('GenericParameterClause', kind='GenericParameterClause', is_optional=True), @@ -451,24 +449,6 @@ Child('Getter', kind='CodeBlock')]), ]), - # SWIFT_ENABLE_TENSORFLOW - Node('CallDecl', kind='Decl', - children=[ - Child('Attributes', kind='AttributeList', - is_optional=True), - Child('Modifiers', kind='ModifierList', - is_optional=True), - Child('CallKeyword', kind='CallToken'), - Child('FuncKeyword', kind='FuncToken'), - Child('GenericParameterClause', kind='GenericParameterClause', - is_optional=True), - Child('Signature', kind='FunctionSignature'), - Child('GenericWhereClause', kind='GenericWhereClause', - is_optional=True), - # the body is not necessary inside a protocol definition - Child('Body', kind='CodeBlock', is_optional=True), - ]), - # access-level-modifier -> 'private' | 'private' '(' 'set' ')' # | 'fileprivate' | 'fileprivate' '(' 'set' ')' # | 'internal' | 'internal' '(' 'set' ')' diff --git a/utils/gyb_syntax_support/ExprNodes.py b/utils/gyb_syntax_support/ExprNodes.py index f4999eccad87e..6ff0c5db2a6fc 100644 --- a/utils/gyb_syntax_support/ExprNodes.py +++ b/utils/gyb_syntax_support/ExprNodes.py @@ -74,8 +74,6 @@ 'IdentifierToken', 'SelfToken', 'CapitalSelfToken', - # SWIFT_ENABLE_TENSORFLOW - 'CallToken', 'DollarIdentifierToken', 'SpacedBinaryOperatorToken', ]), diff --git a/utils/gyb_syntax_support/NodeSerializationCodes.py b/utils/gyb_syntax_support/NodeSerializationCodes.py index 61da4dc15e968..8a39f9f0a2bf3 100644 --- a/utils/gyb_syntax_support/NodeSerializationCodes.py +++ b/utils/gyb_syntax_support/NodeSerializationCodes.py @@ -241,7 +241,6 @@ 'DifferentiableAttributeFuncSpecifier': 235, 'FunctionDeclName': 236, 'DifferentiatingAttributeArguments': 237, - 'CallDecl': 238, } diff --git a/utils/gyb_syntax_support/Token.py b/utils/gyb_syntax_support/Token.py index c91353dd4ca5a..cd389b4df63af 100644 --- a/utils/gyb_syntax_support/Token.py +++ b/utils/gyb_syntax_support/Token.py @@ -335,7 +335,6 @@ def macro_name(self): serialization_code=118, description='TensorFlow operation', protocol='ExpressibleByTensorFlowOp'), - DeclKeyword('Call', 'call', serialization_code=119), ] SYNTAX_TOKEN_MAP = {token.name + 'Token': token for token in SYNTAX_TOKENS} From 42296460151c8b419feb2fa67d4b5fc01e1a4dd6 Mon Sep 17 00:00:00 2001 From: Dan Zheng Date: Thu, 18 Apr 2019 09:53:00 -0700 Subject: [PATCH 2/3] Revert "Fix `call` declaration serialization. (#24121)" This reverts commit 6466a84d637607f2c29aeadd6dfa57ef6c3b58c8. --- .../Serialization/DeclTypeRecordNodes.def | 2 - include/swift/Serialization/ModuleFormat.h | 32 ------------ lib/Serialization/Deserialization.cpp | 50 ++++++------------- lib/Serialization/Serialization.cpp | 2 - 4 files changed, 14 insertions(+), 72 deletions(-) diff --git a/include/swift/Serialization/DeclTypeRecordNodes.def b/include/swift/Serialization/DeclTypeRecordNodes.def index 7850229c5f3b4..cb4ba520dffee 100644 --- a/include/swift/Serialization/DeclTypeRecordNodes.def +++ b/include/swift/Serialization/DeclTypeRecordNodes.def @@ -128,8 +128,6 @@ DECL(EXTENSION) DECL(DESTRUCTOR) DECL(PRECEDENCE_GROUP) DECL(ACCESSOR) -// SWIFT_ENABLE_TENSORFLOW -DECL(CALL) #ifndef DECL_ATTR #define DECL_ATTR(NAME, CLASS, OPTIONS, CODE) RECORD_VAL(CLASS##_DECL_ATTR, 100+CODE) diff --git a/include/swift/Serialization/ModuleFormat.h b/include/swift/Serialization/ModuleFormat.h index f8114cb87a813..e7e0f63d5f42e 100644 --- a/include/swift/Serialization/ModuleFormat.h +++ b/include/swift/Serialization/ModuleFormat.h @@ -1110,38 +1110,6 @@ namespace decls_block { // - inlinable body text, if any >; - // SWIFT_ENABLE_TENSORFLOW - // TODO: remove the unnecessary FuncDecl components here - using CallLayout = BCRecordLayout< - CALL_DECL, - DeclContextIDField, // context decl - BCFixed<1>, // implicit? - BCFixed<1>, // is 'static' or 'class'? - StaticSpellingKindField, // spelling of 'static' or 'class' - BCFixed<1>, // isObjC? - SelfAccessKindField, // self access kind - BCFixed<1>, // has dynamic self? - BCFixed<1>, // has forced static dispatch? - BCFixed<1>, // throws? - GenericEnvironmentIDField, // generic environment - TypeIDField, // result interface type - DeclIDField, // operator decl - DeclIDField, // overridden function - BCVBR<5>, // 0 for a simple name, otherwise the number of parameter name - // components plus one - AccessLevelField, // access level - BCFixed<1>, // requires a new vtable slot - BCFixed<1>, // default argument resilience expansion - BCArray // name components, - // followed by TypeID dependencies - // The record is trailed by: - // - its _silgen_name, if any - // - its generic parameters, if any - // - body parameter patterns - // - the foreign error convention, if any - // - inlinable body text, if any - >; - using PatternBindingLayout = BCRecordLayout< PATTERN_BINDING_DECL, DeclContextIDField, // context decl diff --git a/lib/Serialization/Deserialization.cpp b/lib/Serialization/Deserialization.cpp index 00c75fedfbc03..4a667378be8c0 100644 --- a/lib/Serialization/Deserialization.cpp +++ b/lib/Serialization/Deserialization.cpp @@ -3147,11 +3147,8 @@ ModuleFile::getDeclCheckedImpl(DeclID DID) { } case decls_block::FUNC_DECL: - case decls_block::ACCESSOR_DECL: - // SWIFT_ENABLE_TENSORFLOW - case decls_block::CALL_DECL: { + case decls_block::ACCESSOR_DECL: { bool isAccessor = (recordID == decls_block::ACCESSOR_DECL); - bool isCall = (recordID == decls_block::CALL_DECL); DeclContextID contextID; bool isImplicit; @@ -3169,23 +3166,8 @@ ModuleFile::getDeclCheckedImpl(DeclID DID) { uint8_t rawDefaultArgumentResilienceExpansion; ArrayRef nameAndDependencyIDs; - // SWIFT_ENABLE_TENSORFLOW - if (isAccessor) { - decls_block::AccessorLayout::readRecord(scratch, contextID, isImplicit, - isStatic, rawStaticSpelling, isObjC, - rawMutModifier, hasDynamicSelf, - hasForcedStaticDispatch, throws, - genericEnvID, - resultInterfaceTypeID, - overriddenID, - accessorStorageDeclID, - rawAccessorKind, - rawAccessLevel, - needsNewVTableEntry, - rawDefaultArgumentResilienceExpansion, - nameAndDependencyIDs); - } else if (isCall) { - decls_block::CallLayout::readRecord(scratch, contextID, isImplicit, + if (!isAccessor) { + decls_block::FuncLayout::readRecord(scratch, contextID, isImplicit, isStatic, rawStaticSpelling, isObjC, rawMutModifier, hasDynamicSelf, hasForcedStaticDispatch, throws, @@ -3198,14 +3180,15 @@ ModuleFile::getDeclCheckedImpl(DeclID DID) { rawDefaultArgumentResilienceExpansion, nameAndDependencyIDs); } else { - decls_block::FuncLayout::readRecord(scratch, contextID, isImplicit, + decls_block::AccessorLayout::readRecord(scratch, contextID, isImplicit, isStatic, rawStaticSpelling, isObjC, rawMutModifier, hasDynamicSelf, hasForcedStaticDispatch, throws, genericEnvID, resultInterfaceTypeID, - associatedDeclID, overriddenID, - numNameComponentsBiased, + overriddenID, + accessorStorageDeclID, + rawAccessorKind, rawAccessLevel, needsNewVTableEntry, rawDefaultArgumentResilienceExpansion, @@ -3298,24 +3281,19 @@ ModuleFile::getDeclCheckedImpl(DeclID DID) { return declOrOffset; FuncDecl *fn; - // SWIFT_ENABLE_TENSORFLOW - if (isAccessor) { + if (!isAccessor) { + fn = FuncDecl::createDeserialized( + ctx, /*StaticLoc=*/SourceLoc(), staticSpelling.getValue(), + /*FuncLoc=*/SourceLoc(), name, /*NameLoc=*/SourceLoc(), + /*Throws=*/throws, /*ThrowsLoc=*/SourceLoc(), + genericParams, DC); + } else { fn = AccessorDecl::createDeserialized( ctx, /*FuncLoc=*/SourceLoc(), /*AccessorKeywordLoc=*/SourceLoc(), accessorKind, storage, /*StaticLoc=*/SourceLoc(), staticSpelling.getValue(), /*Throws=*/throws, /*ThrowsLoc=*/SourceLoc(), genericParams, DC); - } else if (isCall) { - fn = CallDecl::createDeserialized( - ctx, name, /*declLoc=*/ SourceLoc(), /*throws*/ throws, - /*throwsLoc*/ SourceLoc(), genericParams, DC); - } else { - fn = FuncDecl::createDeserialized( - ctx, /*StaticLoc=*/SourceLoc(), staticSpelling.getValue(), - /*FuncLoc=*/SourceLoc(), name, /*NameLoc=*/SourceLoc(), - /*Throws=*/throws, /*ThrowsLoc=*/SourceLoc(), - genericParams, DC); } fn->setEarlyAttrValidation(); declOrOffset = fn; diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp index 3b54e9fe49571..54b93b4ca7275 100644 --- a/lib/Serialization/Serialization.cpp +++ b/lib/Serialization/Serialization.cpp @@ -4156,8 +4156,6 @@ void Serializer::writeAllDeclsAndTypes() { registerDeclTypeAbbr(); registerDeclTypeAbbr(); registerDeclTypeAbbr(); - // SWIFT_ENABLE_TENSORFLOW - registerDeclTypeAbbr(); registerDeclTypeAbbr(); registerDeclTypeAbbr(); registerDeclTypeAbbr(); From 4382b73ac94a269d1b29855af2dc51e0fcb94360 Mon Sep 17 00:00:00 2001 From: Dan Zheng Date: Thu, 18 Apr 2019 08:03:15 -0700 Subject: [PATCH 3/3] Reimplement callables using `func call`. Remove `call` declarations. Treat methods named `func call` as call-syntax delegate methods. --- include/swift/AST/Decl.h | 3 + include/swift/AST/KnownIdentifiers.def | 2 + lib/Sema/CSApply.cpp | 57 +++++++ lib/Sema/CSDiag.cpp | 16 +- lib/Sema/CSSimplify.cpp | 53 +++++++ .../Inputs/call_method_other_module.swift} | 4 +- .../call_method_cross_module.swift} | 4 +- test/Sema/call_method_generic.swift | 43 ++++++ .../call_method_protocol.swift} | 22 +-- test/Sema/call_method_simple.swift | 145 ++++++++++++++++++ .../round_trip_parse_gen.swift.withkinds | 7 +- test/Syntax/round_trip_parse_gen.swift | 5 - .../update-checkout-config.json | 2 +- 13 files changed, 336 insertions(+), 27 deletions(-) rename test/{decl/call/Inputs/callable_other_module.swift => Sema/Inputs/call_method_other_module.swift} (66%) rename test/{decl/call/callable_cross_module.swift => Sema/call_method_cross_module.swift} (71%) create mode 100644 test/Sema/call_method_generic.swift rename test/{decl/call/protocol.swift => Sema/call_method_protocol.swift} (53%) create mode 100644 test/Sema/call_method_simple.swift diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h index 51ce9fa5d15c7..8e696e776e442 100644 --- a/include/swift/AST/Decl.h +++ b/include/swift/AST/Decl.h @@ -5610,6 +5610,9 @@ class FuncDecl : public AbstractFunctionDecl { bool isStatic() const { return Bits.FuncDecl.IsStatic; } + bool isCallable() const { + return getName().str() == "call" && isInstanceMember(); + } /// \returns the way 'static'/'class' was spelled in the source. StaticSpellingKind getStaticSpelling() const { return static_cast(Bits.FuncDecl.StaticSpelling); diff --git a/include/swift/AST/KnownIdentifiers.def b/include/swift/AST/KnownIdentifiers.def index 019be35af5e16..949e9f55281ba 100644 --- a/include/swift/AST/KnownIdentifiers.def +++ b/include/swift/AST/KnownIdentifiers.def @@ -31,6 +31,8 @@ IDENTIFIER(Any) IDENTIFIER(ArrayLiteralElement) IDENTIFIER(atIndexedSubscript) IDENTIFIER_(bridgeToObjectiveC) +// SWIFT_ENABLE_TENSORFLOW +IDENTIFIER(call) IDENTIFIER_WITH_NAME(code_, "_code") IDENTIFIER(CodingKeys) IDENTIFIER(combine) diff --git a/lib/Sema/CSApply.cpp b/lib/Sema/CSApply.cpp index 7567729619e6e..9587140ce8670 100644 --- a/lib/Sema/CSApply.cpp +++ b/lib/Sema/CSApply.cpp @@ -7549,6 +7549,11 @@ Expr *ExprRewriter::finishApply(ApplyExpr *apply, Type openedType, llvm_unreachable("Unhandled DeclTypeCheckingSemantics in switch."); }; + // SWIFT_ENABLE_TENSORFLOW + // Save the original potentially lvalue function for rewriting call method + // applications. + auto *originalFn = fn; + // SWIFT_ENABLE_TENSORFLOW END // The function is always an rvalue. fn = cs.coerceToRValue(fn); @@ -7759,6 +7764,58 @@ Expr *ExprRewriter::finishApply(ApplyExpr *apply, Type openedType, return finishApply(apply, openedType, locator); } + // SWIFT_ENABLE_TENSORFLOW + // Handle call method applications. + auto &ctx = cs.getASTContext(); + + TupleExpr *arg = dyn_cast(apply->getArg()); + if (auto parenExpr = dyn_cast(apply->getArg())) + arg = TupleExpr::createImplicit(ctx, parenExpr->getSubExpr(), {}); + + // Get resolved call method and verify it. + auto loc = locator.withPathElement(ConstraintLocator::ApplyFunction); + auto selected = solution.getOverloadChoice(cs.getConstraintLocator(loc)); + auto choice = selected.choice; + auto *callMethod = dyn_cast(selected.choice.getDecl()); + if (callMethod && callMethod->isCallable()) { + auto methodType = + simplifyType(selected.openedType)->castTo(); + auto selfParam = callMethod->getImplicitSelfDecl(); + // Diagnose `mutating` method call on immutable value. + if (!cs.getType(originalFn)->hasLValueType() && selfParam->isInOut()) { + AssignmentFailure failure(originalFn, cs, originalFn->getLoc(), + diag::cannot_pass_rvalue_mutating_subelement, + diag::cannot_pass_rvalue_mutating); + failure.diagnose(); + return nullptr; + } + // Create direct reference to call method. + bool isDynamic = choice.getKind() == OverloadChoiceKind::DeclViaDynamic; + Expr *declRef = buildMemberRef(originalFn, selected.openedFullType, + /*dotLoc=*/SourceLoc(), choice, + DeclNameLoc(fn->getEndLoc()), + selected.openedType, loc, loc, + /*Implicit=*/true, + choice.getFunctionRefKind(), + AccessSemantics::Ordinary, isDynamic); + if (!declRef) + return nullptr; + declRef->setImplicit(apply->isImplicit()); + apply->setFn(declRef); + // Coerce argument to input type of call method. + SmallVector argLabelsScratch; + auto *arg = coerceCallArguments(apply->getArg(), methodType, apply, + apply->getArgumentLabels(argLabelsScratch), + apply->hasTrailingClosure(), loc); + if (!arg) + return nullptr; + apply->setArg(arg); + cs.setType(apply, methodType->getResult()); + cs.cacheExprTypes(apply); + return apply; + } + // SWIFT_ENABLE_TENSORFLOW END + // Handle @dynamicCallable applications. // At this point, all other ApplyExpr cases have been handled. return finishApplyDynamicCallable(*this, cs, solution, apply, locator); diff --git a/lib/Sema/CSDiag.cpp b/lib/Sema/CSDiag.cpp index eb96bfeac9a49..e4671f077799a 100644 --- a/lib/Sema/CSDiag.cpp +++ b/lib/Sema/CSDiag.cpp @@ -5328,9 +5328,19 @@ bool FailureDiagnosis::visitApplyExpr(ApplyExpr *callExpr) { !fnType->is() && !fnType->is()) { auto arg = callExpr->getArg(); + // SWIFT_ENABLE_TENSORFLOW + auto isDynamicCallable = + CS.DynamicCallableCache[fnType->getCanonicalType()].isValid(); + + auto *nominal = fnType->getAnyNominal(); + auto hasCallMethods = nominal && + llvm::any_of(nominal->getMembers(), [](Decl *member) { + auto funcDecl = dyn_cast(member); + return funcDecl && funcDecl->isCallable(); + }); // Diagnose @dynamicCallable errors. - if (CS.DynamicCallableCache[fnType->getCanonicalType()].isValid()) { + if (isDynamicCallable) { auto dynamicCallableMethods = CS.DynamicCallableCache[fnType->getCanonicalType()]; @@ -5384,7 +5394,9 @@ bool FailureDiagnosis::visitApplyExpr(ApplyExpr *callExpr) { } } - return true; + // SWIFT_ENABLE_TENSORFLOW + if (!isDynamicCallable && !hasCallMethods) + return true; } bool hasTrailingClosure = callArgHasTrailingClosure(callExpr->getArg()); diff --git a/lib/Sema/CSSimplify.cpp b/lib/Sema/CSSimplify.cpp index 37893bb1a2a07..cec94913e7157 100644 --- a/lib/Sema/CSSimplify.cpp +++ b/lib/Sema/CSSimplify.cpp @@ -4585,6 +4585,59 @@ ConstraintSystem::simplifyApplicableFnConstraint( return simplified; } + // SWIFT_ENABLE_TENSORFLOW + // Handle applications of types with call methods. + if (desugar2->mayHaveMembers()) { + auto &ctx = getASTContext(); + // Get all call methods of the nominal type. + SmallVector callMethods; + auto candidates = lookupMember(desugar2, DeclName(ctx.Id_call)); + for (auto entry : candidates) { + auto callMethod = dyn_cast(entry.getValueDecl()); + if (!callMethod) + continue; + callMethods.push_back(callMethod); + } + + // Handle call methods calls. + if (!callMethods.empty()) { + // Create a type variable for the call method. + auto loc = getConstraintLocator(locator); + auto tv = createTypeVariable(loc, TVO_CanBindToLValue); + + // Record the call method overload set. + SmallVector choices; + for (auto candidate : callMethods) { + TC.validateDecl(candidate); + if (candidate->isInvalid()) continue; + choices.push_back( + OverloadChoice(type2, candidate, FunctionRefKind::SingleApply)); + } + if (choices.empty()) return SolutionKind::Error; + addOverloadSet(tv, choices, DC, loc); + + // Create type variables for each parameter type. + SmallVector tvParams; + for (unsigned i : range(func1->getNumParams())) { + auto param = func1->getParams()[i]; + auto paramType = param.getPlainType(); + + auto *tvParam = createTypeVariable(loc); + auto locatorBuilder = + locator.withPathElement(LocatorPathElt::getTupleElement(i)); + addConstraint(ConstraintKind::ArgumentConversion, paramType, + tvParam, locatorBuilder); + tvParams.push_back(AnyFunctionType::Param(tvParam)); + } + // Create target function type and an applicable function constraint. + AnyFunctionType *funcType = + FunctionType::get(tvParams, func1->getResult()); + addConstraint(ConstraintKind::ApplicableFunction, funcType, tv, locator); + + return SolutionKind::Solved; + } + } + // Handle applications of @dynamicCallable types. return simplifyDynamicCallableApplicableFnConstraint(type1, origType2, subflags, locator); diff --git a/test/decl/call/Inputs/callable_other_module.swift b/test/Sema/Inputs/call_method_other_module.swift similarity index 66% rename from test/decl/call/Inputs/callable_other_module.swift rename to test/Sema/Inputs/call_method_other_module.swift index d11e0c32170bd..8ddf37d3fac37 100644 --- a/test/decl/call/Inputs/callable_other_module.swift +++ b/test/Sema/Inputs/call_method_other_module.swift @@ -1,13 +1,13 @@ public protocol Layer : Differentiable { @differentiable - call func(_ input: Float) -> Float + func call(_ input: Float) -> Float } public struct Dense : Differentiable { public init() {} @differentiable - public call func(_ input: Float) -> Float { + public func call(_ input: Float) -> Float { return input * 2 } } diff --git a/test/decl/call/callable_cross_module.swift b/test/Sema/call_method_cross_module.swift similarity index 71% rename from test/decl/call/callable_cross_module.swift rename to test/Sema/call_method_cross_module.swift index 70d11f3ef0393..d97628cf20b88 100644 --- a/test/decl/call/callable_cross_module.swift +++ b/test/Sema/call_method_cross_module.swift @@ -1,8 +1,8 @@ // RUN: %empty-directory(%t) -// RUN: %target-swift-frontend -emit-module -primary-file %S/Inputs/callable_other_module.swift -emit-module-path %t/callable_other_module.swiftmodule +// RUN: %target-swift-frontend -emit-module -primary-file %S/Inputs/call_method_other_module.swift -emit-module-path %t/call_method_other_module.swiftmodule // RUN: %target-swift-frontend -typecheck -I %t -primary-file %s -verify -import callable_other_module +import call_method_other_module func testLayer(_ layer: L) -> Float { return layer(1) diff --git a/test/Sema/call_method_generic.swift b/test/Sema/call_method_generic.swift new file mode 100644 index 0000000000000..b07e57d2012d8 --- /dev/null +++ b/test/Sema/call_method_generic.swift @@ -0,0 +1,43 @@ +// RUN: %target-typecheck-verify-swift + +protocol P0 { + func call(x: Self) +} + +struct ConcreteType { + func call(_ x: T, _ y: U) -> (T, U) { + return (x, y) + } + + func call(_ fn: @escaping (T) -> U) -> (T) -> U { + return fn + } +} + +let concrete = ConcreteType() +_ = concrete(1, 3.0) +_ = concrete(concrete, concrete.call as ([Int], Float) -> ([Int], Float)) + +func generic(_ x: T, _ y: U) { + _ = concrete(x, x) + _ = concrete(x, y) +} + +struct GenericType { + let collection: T + func call(_ x: U) -> Bool where U == T.Element, U : Equatable { + return collection.contains(x) + } +} + +// Test conditional conformance. +extension GenericType where T.Element : Numeric { + func call(initialValue: T.Element) -> T.Element { + return collection.reduce(initialValue, +) + } +} + +let genericString = GenericType<[String]>(collection: ["Hello", "world", "!"]) +_ = genericString("Hello") +let genericInt = GenericType>(collection: [1, 2, 3]) +_ = genericInt(initialValue: 1) diff --git a/test/decl/call/protocol.swift b/test/Sema/call_method_protocol.swift similarity index 53% rename from test/decl/call/protocol.swift rename to test/Sema/call_method_protocol.swift index 84fbbfcbdee13..da7efbbf53e27 100644 --- a/test/decl/call/protocol.swift +++ b/test/Sema/call_method_protocol.swift @@ -1,8 +1,8 @@ // RUN: %target-typecheck-verify-swift protocol P0 { - // expected-note @+1 {{protocol requires 'call' method with type '() -> Missing'; do you want to add a stub?}} - call func() -> Self + // expected-note @+1 {{protocol requires function 'call()' with type '() -> Missing'; do you want to add a stub?}} + func call() -> Self } func testProtocol(_ x: P0) { _ = x() @@ -12,16 +12,18 @@ func testGeneric(_ x: T) { } protocol P1 { - call func() -> Self + func call() -> Self } extension P1 { - call func() -> Self { + // expected-note @+1 {{found this candidate}} + func call() -> Self { return self } } protocol P2 {} extension P2 { - call func(x: Int, y: Int) -> Int { + // expected-note @+1 {{found this candidate}} + func call(x: Int, y: Int) -> Int { return x + y } } @@ -30,13 +32,13 @@ extension P2 { struct Missing : P0 {} struct S0 : P0 { @discardableResult - call func() -> S0 { return self } + func call() -> S0 { return self } } let s0 = S0() s0() struct S1 : P1 { - call func() -> S1 { return self } + func call() -> S1 { return self } } let s1 = S1() @@ -44,12 +46,14 @@ _ = s1()() struct Conforming : P0 & P1 & P2 {} let conforming = Conforming() -_ = conforming() _ = conforming(x: 1, y: 2) +_ = conforming().call(x:y:)(1, 2) +_ = conforming.call(x:y:) +_ = conforming.call // expected-error {{ambiguous use of 'call'}} protocol P3 {} extension P3 { - call func() -> Self { return self } + func call() -> Self { return self } } struct S3 : P3 {} diff --git a/test/Sema/call_method_simple.swift b/test/Sema/call_method_simple.swift new file mode 100644 index 0000000000000..69c16c7d2589f --- /dev/null +++ b/test/Sema/call_method_simple.swift @@ -0,0 +1,145 @@ +// RUN: %target-typecheck-verify-swift + +struct SimpleCallable { + func call(_ x: Float) -> Float { + return x + } +} + +// Simple test. + +let foo = SimpleCallable() +_ = foo(1) +_ = foo(foo(1)) + +// Test direct `call` member references. + +_ = foo.call(1) +_ = [1, 2, 3].map(foo.call) +_ = foo.call(foo(1)) +_ = foo(foo.call(1)) +let _: (Float) -> Float = foo.call + +func callable() -> SimpleCallable { + return SimpleCallable() +} +extension SimpleCallable { + var foo: SimpleCallable { + return self + } + func bar() -> SimpleCallable { + return self + } +} + +_ = foo.foo(1) +_ = foo.bar()(1) +_ = callable()(1) +_ = [1, 2, 3].map(foo.foo.call) +_ = [1, 2, 3].map(foo.bar().call) +_ = [1, 2, 3].map(callable().call) + +struct MultipleArgsCallable { + func call(x: Int, y: Float) -> [Int] { + return [x] + } +} + +let bar = MultipleArgsCallable() +_ = bar(x: 1, y: 1) +_ = bar.call(x: 1, y: 1) +_ = bar(x: bar.call(x: 1, y: 1)[0], y: 1) +_ = bar.call(x: bar(x: 1, y: 1)[0], y: 1) + +struct Extended {} +extension Extended { + @discardableResult + func call() -> Extended { + return self + } +} +var extended = Extended() +extended()().call()() + +struct OptionalCallable { + func call() -> OptionalCallable? { + return self + } +} +var optional = OptionalCallable() +_ = optional()?.call()?() + +struct VariadicCallable { + func call(_ args: Int...) -> [Int] { + return args + } +} +var variadic = VariadicCallable() +_ = variadic() +_ = variadic(1, 2, 3) + +struct Mutating { + var x: Int + mutating func call() { + x += 1 + } +} +func testMutating(_ x: Mutating, _ y: inout Mutating) { + _ = x() // expected-error {{cannot use mutating member on immutable value: 'x' is a 'let' constant}} + _ = x.call() // expected-error {{cannot use mutating member on immutable value: 'x' is a 'let' constant}} + _ = y() + _ = y.call() +} + +struct Throwing { + func call() throws -> Throwing { + return self + } +} +var throwing = Throwing() +_ = try throwing() + +enum BinaryOperation { + case add, subtract, multiply, divide +} +extension BinaryOperation { + func call(_ lhs: Float, _ rhs: Float) -> Float { + switch self { + case .add: return lhs + rhs + case .subtract: return lhs - rhs + case .multiply: return lhs * rhs + case .divide: return lhs / rhs + } + } +} +_ = BinaryOperation.add(1, 2) + +class BaseClass { + func call() -> Self { + return self + } +} +class SubClass : BaseClass { + override func call() -> Self { + return self + } +} + +func testIUO(a: SimpleCallable!, b: MultipleArgsCallable!, c: Extended!, + d: OptionalCallable!, e: Throwing!) { + _ = a(1) + _ = b(x: 1, y: 1) + _ = c() + _ = d()?.call()?() + _ = try? e() +} + +// Errors. + +// TODO: Fix this error. Ideally, it should be "extra argument in call". +// expected-error @+2 {{cannot call value of non-function type 'SimpleCallable'}} +// expected-error @+1 {{cannot invoke 'foo' with an argument list of type '(Int, Int)'}} +_ = foo(1, 1) + +_ = bar(1, 1) // expected-error {{missing argument labels 'x:y:' in call}} +let _: (Float) -> Float = foo // expected-error {{cannot convert value of type 'SimpleCallable' to specified type '(Float) -> Float'}} diff --git a/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds b/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds index 8f39865de46f6..c294f0fe28ce2 100644 --- a/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds +++ b/test/Syntax/Outputs/round_trip_parse_gen.swift.withkinds @@ -591,9 +591,4 @@ func negateDerivative(_ x func bazDerivative(_ x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x, { v in v }) -} - -protocol Layer : Differentiable { - @differentiable - call func(_ input: Float) -> Float -} +} diff --git a/test/Syntax/round_trip_parse_gen.swift b/test/Syntax/round_trip_parse_gen.swift index d6c711c295ed1..32a969409683d 100644 --- a/test/Syntax/round_trip_parse_gen.swift +++ b/test/Syntax/round_trip_parse_gen.swift @@ -592,8 +592,3 @@ func bazDerivative(_ x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) { return (x, { v in v }) } - -protocol Layer : Differentiable { - @differentiable - call func(_ input: Float) -> Float -} diff --git a/utils/update_checkout/update-checkout-config.json b/utils/update_checkout/update-checkout-config.json index 0e18e7abc59bc..48499c141edec 100644 --- a/utils/update_checkout/update-checkout-config.json +++ b/utils/update_checkout/update-checkout-config.json @@ -242,7 +242,7 @@ "icu": "release-61-1", "tensorflow": "447e512d332ab86172a3b13119900b4d021d0c65", "tensorflow-swift-bindings": "a7ccb727514414d31df9e403f34fa923bdf6a519", - "tensorflow-swift-apis": "904dd507b7fcd86dd75b497a6356eeb30846f3cc" + "tensorflow-swift-apis": "cc4abe206dce7f47fabebfcf28effdcc2ad5992b" } } }