/Volumes/compiler/apple/swift/lib/Sema/TypeCheckAttr.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===--- TypeCheckAttr.cpp - Type Checking for Attributes -----------------===// |
2 | | // |
3 | | // This source file is part of the Swift.org open source project |
4 | | // |
5 | | // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors |
6 | | // Licensed under Apache License v2.0 with Runtime Library Exception |
7 | | // |
8 | | // See https://swift.org/LICENSE.txt for license information |
9 | | // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
10 | | // |
11 | | //===----------------------------------------------------------------------===// |
12 | | // |
13 | | // This file implements semantic analysis for attributes. |
14 | | // |
15 | | //===----------------------------------------------------------------------===// |
16 | | |
17 | | #include "MiscDiagnostics.h" |
18 | | #include "TypeCheckAvailability.h" |
19 | | #include "TypeCheckConcurrency.h" |
20 | | #include "TypeCheckDistributed.h" |
21 | | #include "TypeCheckMacros.h" |
22 | | #include "TypeCheckObjC.h" |
23 | | #include "TypeCheckType.h" |
24 | | #include "TypeChecker.h" |
25 | | #include "swift/AST/ASTVisitor.h" |
26 | | #include "swift/AST/ClangModuleLoader.h" |
27 | | #include "swift/AST/Decl.h" |
28 | | #include "swift/AST/DiagnosticsParse.h" |
29 | | #include "swift/AST/DiagnosticsSema.h" |
30 | | #include "swift/AST/Effects.h" |
31 | | #include "swift/AST/GenericEnvironment.h" |
32 | | #include "swift/AST/ImportCache.h" |
33 | | #include "swift/AST/ModuleNameLookup.h" |
34 | | #include "swift/AST/NameLookup.h" |
35 | | #include "swift/AST/NameLookupRequests.h" |
36 | | #include "swift/AST/ParameterList.h" |
37 | | #include "swift/AST/PropertyWrappers.h" |
38 | | #include "swift/AST/SourceFile.h" |
39 | | #include "swift/AST/StorageImpl.h" |
40 | | #include "swift/AST/SwiftNameTranslation.h" |
41 | | #include "swift/AST/TypeCheckRequests.h" |
42 | | #include "swift/AST/Types.h" |
43 | | #include "swift/Parse/Lexer.h" |
44 | | #include "swift/Parse/Parser.h" |
45 | | #include "swift/Sema/IDETypeChecking.h" |
46 | | #include "clang/Basic/CharInfo.h" |
47 | | #include "llvm/ADT/MapVector.h" |
48 | | #include "llvm/ADT/STLExtras.h" |
49 | | #include "llvm/Support/Debug.h" |
50 | | |
51 | | using namespace swift; |
52 | | |
53 | | namespace { |
54 | | /// This visits each attribute on a decl. The visitor should return true if |
55 | | /// the attribute is invalid and should be marked as such. |
56 | | class AttributeChecker : public AttributeVisitor<AttributeChecker> { |
57 | | ASTContext &Ctx; |
58 | | Decl *D; |
59 | | |
60 | | public: |
61 | 4.85M | AttributeChecker(Decl *D) : Ctx(D->getASTContext()), D(D) {} |
62 | | |
63 | | /// This emits a diagnostic with a fixit to remove the attribute. |
64 | | template<typename ...ArgTypes> |
65 | | InFlightDiagnostic diagnoseAndRemoveAttr(DeclAttribute *attr, |
66 | 2.96k | ArgTypes &&...Args) { |
67 | 2.96k | return swift::diagnoseAndRemoveAttr(D, attr, |
68 | 2.96k | std::forward<ArgTypes>(Args)...); |
69 | 2.96k | } TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeENS2_11AccessLevelEEEERPS4_S7_EEENS2_18InFlightDiagnosticESA_DpOT_ Line | Count | Source | 66 | 33 | ArgTypes &&...Args) { | 67 | 33 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 33 | std::forward<ArgTypes>(Args)...); | 69 | 33 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeENS2_19DescriptiveDeclKindEEEERPNS2_14SimpleDeclAttrILNS2_12DeclAttrKindE58EEES7_EEENS2_18InFlightDiagnosticEPS4_DpOT_ Line | Count | Source | 66 | 3 | ArgTypes &&...Args) { | 67 | 3 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 3 | std::forward<ArgTypes>(Args)...); | 69 | 3 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeENS2_19DescriptiveDeclKindEEEERPNS2_14SimpleDeclAttrILNS2_12DeclAttrKindE18EEES7_EEENS2_18InFlightDiagnosticEPS4_DpOT_ Line | Count | Source | 66 | 3 | ArgTypes &&...Args) { | 67 | 3 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 3 | std::forward<ArgTypes>(Args)...); | 69 | 3 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeENS2_19DescriptiveDeclKindEEEERPNS2_16BackDeployedAttrES7_EEENS2_18InFlightDiagnosticEPS4_DpOT_ Line | Count | Source | 66 | 72 | ArgTypes &&...Args) { | 67 | 72 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 72 | std::forward<ArgTypes>(Args)...); | 69 | 72 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeEEEERPNS2_16BackDeployedAttrEEEENS2_18InFlightDiagnosticEPS4_DpOT_ Line | Count | Source | 66 | 12 | ArgTypes &&...Args) { | 67 | 12 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 12 | std::forward<ArgTypes>(Args)...); | 69 | 12 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeEEEERPS4_EEENS2_18InFlightDiagnosticES9_DpOT_ Line | Count | Source | 66 | 419 | ArgTypes &&...Args) { | 67 | 419 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 419 | std::forward<ArgTypes>(Args)...); | 69 | 419 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJEEEEEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 1.47k | ArgTypes &&...Args) { | 67 | 1.47k | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 1.47k | std::forward<ArgTypes>(Args)...); | 69 | 1.47k | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJN4llvm9StringRefEEEES5_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 54 | ArgTypes &&...Args) { | 67 | 54 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 54 | std::forward<ArgTypes>(Args)...); | 69 | 54 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJbNS2_4TypeEEEERbRS4_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 117 | ArgTypes &&...Args) { | 67 | 117 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 117 | std::forward<ArgTypes>(Args)...); | 69 | 117 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeEEEERPNS2_14SimpleDeclAttrILNS2_12DeclAttrKindE18EEEEEENS2_18InFlightDiagnosticEPS4_DpOT_ Line | Count | Source | 66 | 3 | ArgTypes &&...Args) { | 67 | 3 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 3 | std::forward<ArgTypes>(Args)...); | 69 | 3 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJNS2_8DeclNameENS2_11AccessLevelEEEES4_S5_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 150 | ArgTypes &&...Args) { | 67 | 150 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 150 | std::forward<ArgTypes>(Args)...); | 69 | 150 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeEEEERPNS2_14SimpleDeclAttrILNS2_12DeclAttrKindE22EEEEEENS2_18InFlightDiagnosticEPS4_DpOT_ Line | Count | Source | 66 | 36 | ArgTypes &&...Args) { | 67 | 36 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 36 | std::forward<ArgTypes>(Args)...); | 69 | 36 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJNS2_12DeclBaseNameENS2_11AccessLevelEEEES4_RS5_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 24 | ArgTypes &&...Args) { | 67 | 24 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 24 | std::forward<ArgTypes>(Args)...); | 69 | 24 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeEEEERPNS2_14SimpleDeclAttrILNS2_12DeclAttrKindE37EEEEEENS2_18InFlightDiagnosticEPS4_DpOT_ Line | Count | Source | 66 | 6 | ArgTypes &&...Args) { | 67 | 6 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 6 | std::forward<ArgTypes>(Args)...); | 69 | 6 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_9ValueDeclEEEERPS4_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 45 | ArgTypes &&...Args) { | 67 | 45 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 45 | std::forward<ArgTypes>(Args)...); | 69 | 45 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJbEEERbEEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 6 | ArgTypes &&...Args) { | 67 | 6 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 6 | std::forward<ArgTypes>(Args)...); | 69 | 6 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPNS2_9ValueDeclEEEEPNS2_15NominalTypeDeclEEEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 6 | ArgTypes &&...Args) { | 67 | 6 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 6 | std::forward<ArgTypes>(Args)...); | 69 | 6 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPNS2_9ValueDeclEEEERPNS2_9ClassDeclEEEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 12 | ArgTypes &&...Args) { | 67 | 12 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 12 | std::forward<ArgTypes>(Args)...); | 69 | 12 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeEEEERPNS2_12OptimizeAttrEEEENS2_18InFlightDiagnosticEPS4_DpOT_ Line | Count | Source | 66 | 6 | ArgTypes &&...Args) { | 67 | 6 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 6 | std::forward<ArgTypes>(Args)...); | 69 | 6 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeEEEERPNS2_14SimpleDeclAttrILNS2_12DeclAttrKindE51EEEEEENS2_18InFlightDiagnosticEPS4_DpOT_ Line | Count | Source | 66 | 6 | ArgTypes &&...Args) { | 67 | 6 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 6 | std::forward<ArgTypes>(Args)...); | 69 | 6 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJN4llvm9StringRefENS2_19DescriptiveDeclKindEPKNS2_4DeclEEEES5_S6_RPS7_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 33 | ArgTypes &&...Args) { | 67 | 33 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 33 | std::forward<ArgTypes>(Args)...); | 69 | 33 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJNS2_11AccessLevelENS2_19DescriptiveDeclKindEEEERS4_S5_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 24 | ArgTypes &&...Args) { | 67 | 24 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 24 | std::forward<ArgTypes>(Args)...); | 69 | 24 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJN4llvm9StringRefEbEEENSt3__112basic_stringIcNS8_11char_traitsIcEENS8_9allocatorIcEEEEbEEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 16 | ArgTypes &&...Args) { | 67 | 16 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 16 | std::forward<ArgTypes>(Args)...); | 69 | 16 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJNS2_14ActorIsolationEPKNS2_9ValueDeclEEEERS4_RPS5_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 24 | ArgTypes &&...Args) { | 67 | 24 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 24 | std::forward<ArgTypes>(Args)...); | 69 | 24 | } |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeEN4llvm9StringRefEEEERPNS2_13RawLayoutAttrERA7_KcEEENS2_18InFlightDiagnosticEPS4_DpOT_ TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJNS2_18ReferenceOwnershipEEEES4_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 9 | ArgTypes &&...Args) { | 67 | 9 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 9 | std::forward<ArgTypes>(Args)...); | 69 | 9 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJNS2_14SelfAccessKindENS2_19DescriptiveDeclKindEbEEERS4_S5_bEEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 51 | ArgTypes &&...Args) { | 67 | 51 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 51 | std::forward<ArgTypes>(Args)...); | 69 | 51 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJNS2_14SelfAccessKindEEEERS4_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 3 | ArgTypes &&...Args) { | 67 | 3 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 3 | std::forward<ArgTypes>(Args)...); | 69 | 3 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJNS2_14SelfAccessKindES4_EEES4_RS4_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 33 | ArgTypes &&...Args) { | 67 | 33 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 33 | std::forward<ArgTypes>(Args)...); | 69 | 33 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeEEEERPNS2_25AbstractAccessControlAttrEEEENS2_18InFlightDiagnosticEPS4_DpOT_ Line | Count | Source | 66 | 45 | ArgTypes &&...Args) { | 67 | 45 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 45 | std::forward<ArgTypes>(Args)...); | 69 | 45 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeES6_EEERPNS2_14SimpleDeclAttrILNS2_12DeclAttrKindE5EEERPNS2_25AbstractAccessControlAttrEEEENS2_18InFlightDiagnosticEPS4_DpOT_ Line | Count | Source | 66 | 12 | ArgTypes &&...Args) { | 67 | 12 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 12 | std::forward<ArgTypes>(Args)...); | 69 | 12 | } |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJNS2_11AccessLevelEEEES4_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJNS2_11AccessLevelEjEEES4_RZNS0_21visitSetterAccessAttrEPNS2_16SetterAccessAttrEE3$_6EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 27 | ArgTypes &&...Args) { | 67 | 27 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 27 | std::forward<ArgTypes>(Args)...); | 69 | 27 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJNS2_19DescriptiveDeclKindEEEES4_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 12 | ArgTypes &&...Args) { | 67 | 12 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 12 | std::forward<ArgTypes>(Args)...); | 69 | 12 | } |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJNS2_8DeclNameEEEES4_EEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ Line | Count | Source | 66 | 6 | ArgTypes &&...Args) { | 67 | 6 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 6 | std::forward<ArgTypes>(Args)...); | 69 | 6 | } |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJjEEEiEEENS2_18InFlightDiagnosticEPNS2_13DeclAttributeEDpOT_ TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21diagnoseAndRemoveAttrIJRN5swift4DiagIJPKNS2_13DeclAttributeEN4llvm9StringRefEEEERPS4_RS8_EEENS2_18InFlightDiagnosticESB_DpOT_ Line | Count | Source | 66 | 177 | ArgTypes &&...Args) { | 67 | 177 | return swift::diagnoseAndRemoveAttr(D, attr, | 68 | 177 | std::forward<ArgTypes>(Args)...); | 69 | 177 | } |
|
70 | | |
71 | | /// Emits a diagnostic with a fixit to remove the attribute if the attribute |
72 | | /// is applied to a non-public declaration. Returns true if a diagnostic was |
73 | | /// emitted. |
74 | | bool diagnoseAndRemoveAttrIfDeclIsNonPublic(DeclAttribute *attr, |
75 | 2.89k | bool isError) { |
76 | 2.89k | if (auto *VD = dyn_cast<ValueDecl>(D)) { |
77 | 2.03k | auto access = |
78 | 2.03k | VD->getFormalAccessScope(/*useDC=*/nullptr, |
79 | 2.03k | /*treatUsableFromInlineAsPublic=*/true); |
80 | 2.03k | if (!access.isPublic()) { |
81 | 33 | diagnoseAndRemoveAttr( |
82 | 33 | attr, |
83 | 33 | isError ? diag::attr_not_on_decl_with_invalid_access_level |
84 | 33 | : diag::attr_has_no_effect_on_decl_with_access_level, |
85 | 33 | attr, access.accessLevelForDiagnostics()); |
86 | 33 | return true; |
87 | 33 | } |
88 | 2.03k | } |
89 | 2.85k | return false; |
90 | 2.89k | } |
91 | | |
92 | | /// Emits a diagnostic if there is no availability specified for the given |
93 | | /// platform, as required by the given attribute. Returns true if a diagnostic |
94 | | /// was emitted. |
95 | 1.08k | bool diagnoseMissingAvailability(DeclAttribute *attr, PlatformKind platform) { |
96 | 1.08k | auto IntroVer = D->getIntroducedOSVersion(platform); |
97 | 1.08k | if (IntroVer.has_value()) |
98 | 1.07k | return false; |
99 | | |
100 | 9 | if (auto *VD = dyn_cast<ValueDecl>(D)) { |
101 | 9 | diagnose(attr->AtLoc, diag::attr_requires_decl_availability_for_platform, |
102 | 9 | attr, VD->getName(), prettyPlatformString(platform)); |
103 | 9 | } else { |
104 | 0 | diagnose(attr->AtLoc, diag::attr_requires_availability_for_platform, attr, |
105 | 0 | prettyPlatformString(platform)); |
106 | 0 | } |
107 | 9 | return true; |
108 | 1.08k | } |
109 | | |
110 | | template <typename... ArgTypes> |
111 | 3.19k | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { |
112 | 3.19k | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); |
113 | 3.19k | } TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRN5swift9SourceLocERNS2_4DiagIJPKNS2_13DeclAttributeEN4llvm9StringRefEEEERPNS2_23OriginallyDefinedInAttrESA_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 3 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 3 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 3 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRN5swift9SourceLocERNS2_4DiagIJPKNS2_13DeclAttributeEEEERPNS2_23OriginallyDefinedInAttrEEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 3 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 3 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 3 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRKN5swift9SourceLocERNS2_4DiagIJPKNS2_13DeclAttributeENS2_8DeclNameEN4llvm9StringRefEEEERPS7_SA_SC_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 9 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 9 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 9 | } |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRKN5swift9SourceLocERNS2_4DiagIJPKNS2_13DeclAttributeEN4llvm9StringRefEEEERPS7_SB_EEENS2_18InFlightDiagnosticEDpOT_ TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRN5swift9SourceLocERNS2_4DiagIJEEEEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 213 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 213 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 213 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJEEEEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 782 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 782 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 782 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJPKNS2_13DeclAttributeENS2_19DescriptiveDeclKindEEEERPNS2_16BackDeployedAttrES8_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 12 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 12 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 12 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRN5swift9SourceLocERNS2_4DiagIJPKNS2_13DeclAttributeEN4llvm9StringRefEEEERPNS2_16BackDeployedAttrESA_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 6 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 6 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 6 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRN5swift9SourceLocERNS2_4DiagIJPKNS2_13DeclAttributeEPKNS2_9ValueDeclEN4llvm9StringRefEEEERPNS2_16BackDeployedAttrERPS9_SD_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 15 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 15 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 15 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRKN5swift9SourceLocERNS2_4DiagIJPKNS2_9ValueDeclEEEERPS7_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 15 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 15 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 15 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRN5swift9SourceLocERNS2_4DiagIJPKNS2_13DeclAttributeEPKNS2_9ValueDeclEN4llvm9StringRefENSC_12VersionTupleEEEERPNS2_16BackDeployedAttrERPS9_SD_RKSE_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 15 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 15 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 15 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRKN5swift9SourceLocERNS2_4DiagIJPKNS2_9ValueDeclEN4llvm9StringRefENSA_12VersionTupleEEEERPS7_SB_RKSC_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 15 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 15 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 15 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_19DescriptiveDeclKindEEEES5_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 69 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 69 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 69 | } |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_19DescriptiveDeclKindEN4llvm9StringRefENS6_12VersionTupleEEEES5_S7_RKS8_EEENS2_18InFlightDiagnosticEDpOT_ TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJN4llvm9StringRefENS5_12VersionTupleEEEES6_RKS7_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 42 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 42 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 42 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRN5swift9SourceLocERNS2_4DiagIJNS2_19DescriptiveDeclKindEEEES6_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 135 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 135 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 135 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRN5swift9SourceLocERNS2_4DiagIJbjbjbbEEEbRjbS8_bbEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 219 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 219 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 219 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_4TypeEEEERS5_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 54 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 54 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 54 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRKN5swift9SourceLocERNS2_4DiagIJNS2_4TypeEEEERS7_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 9 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 9 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 9 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRPN5swift13SubscriptDeclERNS2_4DiagIJNS2_4TypeEEEERS7_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 9 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 9 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 9 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRPN5swift13SubscriptDeclERNS2_4DiagIJEEEEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 6 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 6 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 6 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRN5swift9SourceLocERNS2_4DiagIJNS2_4TypeEEEEPNS2_12OptionalTypeEEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 45 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 45 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 45 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJjEEERjEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 105 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 105 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 105 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_8DeclNameEEEES5_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 12 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 12 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 12 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJPKNS2_12ProtocolDeclENS2_8DeclNameEEEERPS5_S8_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 3 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 3 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 3 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJPKNS2_15NominalTypeDeclEPKNS2_12ProtocolDeclEEEERPS5_RPS8_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 3 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 3 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 3 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_10IdentifierEPNS2_9ValueDeclEEEERS5_RPNS2_9ClassDeclEEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 3 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 3 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 3 | } |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_8DeclNameEEEENS2_12DeclBaseNameEEEENS2_18InFlightDiagnosticEDpOT_ TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_11DeclNameRefEEEES5_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 6 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 6 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 6 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRPN5swift9ValueDeclERNS2_4DiagIJNS2_4TypeEEEERS7_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 24 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 24 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 24 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRPN5swift9ValueDeclERNS2_4DiagIJEEEEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 24 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 24 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 24 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_10IdentifierEEEES5_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 9 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 9 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 9 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_8DeclNameEjEEENS2_10IdentifierEiEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 6 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 6 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 6 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJbEEEbEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 6 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 6 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 6 | } |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJPKNS2_9ValueDeclEEEERPNS2_15NominalTypeDeclEEEENS2_18InFlightDiagnosticEDpOT_ TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_8DeclNameENS2_11AccessLevelEEEENS2_10IdentifierES6_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 9 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 9 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 9 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRPKN5swift8FuncDeclERNS2_4DiagIJN4llvm9StringRefENS2_12ObjCSelectorEEEES9_RSA_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 24 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 24 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 24 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRPKN5swift8FuncDeclERNS2_4DiagIJNS2_8DeclNameEEEERS8_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 18 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 18 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 18 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRPKN5swift8FuncDeclERNS2_4DiagIJNS2_12ObjCSelectorEEEERS8_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 24 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 24 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 24 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_8DeclNameEN4llvm9StringRefEEEENS2_10IdentifierERS7_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 12 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 12 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 12 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_4TypeES5_EEERS5_S8_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 8 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 8 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 8 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJPKNS2_9ValueDeclES7_bEEERPNS2_20AbstractFunctionDeclERPNS2_8FuncDeclERbEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 8 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 8 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 8 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJPKNS2_9ValueDeclEbEEERPNS2_20AbstractFunctionDeclERbEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 8 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 8 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 8 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJPKNS2_9ValueDeclEbEEERPNS2_8FuncDeclERbEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 8 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 8 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 8 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJN4llvm9StringRefEEEERA8_KcEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 3 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 3 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 3 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJPKNS2_9ValueDeclEEEERS7_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 3 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 3 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 3 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocENS2_10DiagnosticEEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 66 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 66 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 66 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJN4llvm9StringRefEEEERKS6_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 3 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 3 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 3 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJN4llvm9StringRefEEEES6_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 42 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 42 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 42 | } |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJPKNS2_13DeclAttributeEEEERPNS2_14SimpleDeclAttrILNS2_12DeclAttrKindE102EEEEEENS2_18InFlightDiagnosticEDpOT_ TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJPKNS2_13DeclAttributeEEEERPNS2_11SectionAttrEEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 3 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 3 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 3 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJN4llvm9StringRefEEEERS6_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 9 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 9 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 9 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJRPN5swift15ConstructorDeclERNS2_4DiagIJNS2_4TypeEEEERS7_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 12 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 12 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 12 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJN4llvm9StringRefES6_EEES6_S6_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 33 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 33 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 33 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJbPKNS2_4DeclEEEEbRPS5_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 18 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 18 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 18 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_11AccessLevelENS2_19DescriptiveDeclKindES5_EEERS5_S6_S5_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 75 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 75 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 75 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_11AccessLevelENS2_19DescriptiveDeclKindES5_EEES5_S6_RS5_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 216 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 216 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 216 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_11AccessLevelES5_EEES5_S5_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 267 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 267 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 267 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_11AccessLevelENS2_19DescriptiveDeclKindES5_EEES5_S6_S5_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 405 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 405 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 405 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_11AccessLevelEjS5_EEERS5_RZNS0_21visitSetterAccessAttrEPNS2_16SetterAccessAttrEE3$_7S5_EEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 36 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 36 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 36 | } |
TypeCheckAttr.cpp:_ZNK12_GLOBAL__N_116AttributeChecker8diagnoseIJN5swift9SourceLocERNS2_4DiagIJNS2_8DeclNameEEEENS2_10IdentifierEEEENS2_18InFlightDiagnosticEDpOT_ Line | Count | Source | 111 | 6 | InFlightDiagnostic diagnose(ArgTypes &&... Args) const { | 112 | 6 | return Ctx.Diags.diagnose(std::forward<ArgTypes>(Args)...); | 113 | 6 | } |
|
114 | | |
115 | | /// Deleting this ensures that all attributes are covered by the visitor |
116 | | /// below. |
117 | | bool visitDeclAttribute(DeclAttribute *A) = delete; |
118 | | |
119 | 513k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {}TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker19visitSILGenNameAttrEPN5swift14SILGenNameAttrE Line | Count | Source | 119 | 5.08k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker17visitExportedAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE5EEE Line | Count | Source | 119 | 2.84k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker15visitInlineAttrEPN5swift10InlineAttrE Line | Count | Source | 119 | 20.4k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker18visitSemanticsAttrEPN5swift13SemanticsAttrE Line | Count | Source | 119 | 11.3k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker36visitRequiresStoredPropertyInitsAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE19EEE Line | Count | Source | 119 | 30 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker19visitHasStorageAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE26EEE Line | Count | Source | 119 | 328k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker22visitRawDocCommentAttrEPN5swift17RawDocCommentAttrE Line | Count | Source | 119 | 72.5k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker16visitEffectsAttrEPN5swift11EffectsAttrE Line | Count | Source | 119 | 4.64k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker20visitObjCBridgedAttrEPN5swift15ObjCBridgedAttrE TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker31visitObjCNonLazyRealizationAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE31EEE Line | Count | Source | 119 | 78 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker28visitSynthesizedProtocolAttrEPN5swift23SynthesizedProtocolAttrE TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker17visitTestableAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE33EEE Line | Count | Source | 119 | 204 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker19visitAtRethrowsAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE35EEE Line | Count | Source | 119 | 141 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker24visitShowInInterfaceAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE38EEE Line | Count | Source | 119 | 27 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker24visitObjCRuntimeNameAttrEPN5swift19ObjCRuntimeNameAttrE Line | Count | Source | 119 | 266 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker37visitStaticInitializeObjCMetadataAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE45EEE Unexecuted instantiation: TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker32visitRestatedObjCConformanceAttrEPN5swift27RestatedObjCConformanceAttrE Unexecuted instantiation: TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker37visitClangImporterSynthesizedTypeAttrEPN5swift32ClangImporterSynthesizedTypeAttrE TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker19visitWeakLinkedAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE50EEE Line | Count | Source | 119 | 250 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker35visitForbidSerializingReferenceAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE52EEE TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker24visitHasInitialValueAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE53EEE Line | Count | Source | 119 | 372 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker22visitPrivateImportAttrEPN5swift17PrivateImportAttrE Line | Count | Source | 119 | 102 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker29visitAlwaysEmitIntoClientAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE58EEE Line | Count | Source | 119 | 51.6k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker27visitDisfavoredOverloadAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE62EEE Line | Count | Source | 119 | 2.26k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker31visitProjectedValuePropertyAttrEPN5swift26ProjectedValuePropertyAttrE Line | Count | Source | 119 | 482 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker41visitHasMissingDesignatedInitializersAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE67EEE Line | Count | Source | 119 | 1.25k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker40visitInheritsConvenienceInitializersAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE68EEE Line | Count | Source | 119 | 534 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker28visitOriginallyDefinedInAttrEPN5swift23OriginallyDefinedInAttrE TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21visitNoDerivativeAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE75EEE Line | Count | Source | 119 | 220 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker28visitSpecializeExtensionAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE77EEE Line | Count | Source | 119 | 372 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker18visitAtReasyncAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE80EEE Line | Count | Source | 119 | 3 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker28visitImplicitSelfCaptureAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE82EEE Line | Count | Source | 119 | 285 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker28visitInheritActorContextAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE83EEE Line | Count | Source | 119 | 285 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker25visitLexicalLifetimesAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE85EEE Line | Count | Source | 119 | 12 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker34visitEmitAssemblyVisionRemarksAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE87EEE Line | Count | Source | 119 | 3 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker20visitNonSendableAttrEPN5swift15NonSendableAttrE Line | Count | Source | 119 | 78 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker16visitNoLocksAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE90EEE Line | Count | Source | 119 | 9 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21visitNoAllocationAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE91EEE Line | Count | Source | 119 | 3 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker23visitPreconcurrencyAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE92EEE Line | Count | Source | 119 | 2.26k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker21visitBackDeployedAttrEPN5swift16BackDeployedAttrE TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker22visitDocumentationAttrEPN5swift17DocumentationAttrE Line | Count | Source | 119 | 33 | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker20visitConvenienceAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE119EEE Line | Count | Source | 119 | 4.79k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker27visitReferenceOwnershipAttrEPN5swift22ReferenceOwnershipAttrE Line | Count | Source | 119 | 2.25k | #define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {} |
Unexecuted instantiation: TypeCheckAttr.cpp:_ZN12_GLOBAL__N_116AttributeChecker17visitIsolatedAttrEPN5swift14SimpleDeclAttrILNS1_12DeclAttrKindE126EEE |
120 | | IGNORED_ATTR(AlwaysEmitIntoClient) |
121 | | IGNORED_ATTR(HasInitialValue) |
122 | | IGNORED_ATTR(ClangImporterSynthesizedType) |
123 | | IGNORED_ATTR(Convenience) |
124 | | IGNORED_ATTR(Effects) |
125 | | IGNORED_ATTR(Exported) |
126 | | IGNORED_ATTR(ForbidSerializingReference) |
127 | | IGNORED_ATTR(HasStorage) |
128 | | IGNORED_ATTR(HasMissingDesignatedInitializers) |
129 | | IGNORED_ATTR(InheritsConvenienceInitializers) |
130 | | IGNORED_ATTR(Inline) |
131 | | IGNORED_ATTR(ObjCBridged) |
132 | | IGNORED_ATTR(ObjCNonLazyRealization) |
133 | | IGNORED_ATTR(ObjCRuntimeName) |
134 | | IGNORED_ATTR(RawDocComment) |
135 | | IGNORED_ATTR(RequiresStoredPropertyInits) |
136 | | IGNORED_ATTR(RestatedObjCConformance) |
137 | | IGNORED_ATTR(Semantics) |
138 | | IGNORED_ATTR(NoLocks) |
139 | | IGNORED_ATTR(NoAllocation) |
140 | | IGNORED_ATTR(EmitAssemblyVisionRemarks) |
141 | | IGNORED_ATTR(ShowInInterface) |
142 | | IGNORED_ATTR(SILGenName) |
143 | | IGNORED_ATTR(StaticInitializeObjCMetadata) |
144 | | IGNORED_ATTR(SynthesizedProtocol) |
145 | | IGNORED_ATTR(Testable) |
146 | | IGNORED_ATTR(WeakLinked) |
147 | | IGNORED_ATTR(PrivateImport) |
148 | | IGNORED_ATTR(DisfavoredOverload) |
149 | | IGNORED_ATTR(ProjectedValueProperty) |
150 | | IGNORED_ATTR(ReferenceOwnership) |
151 | | IGNORED_ATTR(OriginallyDefinedIn) |
152 | | IGNORED_ATTR(NoDerivative) |
153 | | IGNORED_ATTR(SpecializeExtension) |
154 | | IGNORED_ATTR(NonSendable) |
155 | | IGNORED_ATTR(AtRethrows) |
156 | | IGNORED_ATTR(AtReasync) |
157 | | IGNORED_ATTR(ImplicitSelfCapture) |
158 | | IGNORED_ATTR(InheritActorContext) |
159 | | IGNORED_ATTR(Isolated) |
160 | | IGNORED_ATTR(Preconcurrency) |
161 | | IGNORED_ATTR(BackDeployed) |
162 | | IGNORED_ATTR(Documentation) |
163 | | IGNORED_ATTR(LexicalLifetimes) |
164 | | #undef IGNORED_ATTR |
165 | | |
166 | 1.23k | void visitAlignmentAttr(AlignmentAttr *attr) { |
167 | | // Alignment must be a power of two. |
168 | 1.23k | auto value = attr->getValue(); |
169 | 1.23k | if (value == 0 || (value & (value - 1)) != 0) |
170 | 6 | diagnose(attr->getLocation(), diag::alignment_not_power_of_two); |
171 | 1.23k | } |
172 | | |
173 | 165 | void visitBorrowedAttr(BorrowedAttr *attr) { |
174 | | // These criteria are the same preconditions laid out by |
175 | | // AbstractStorageDecl::requiresOpaqueModifyCoroutine(). |
176 | | |
177 | 165 | assert(!D->hasClangNode() && "@_borrowed on imported declaration?"); |
178 | | |
179 | 165 | if (D->getAttrs().hasAttribute<DynamicAttr>()) { |
180 | 3 | diagnose(attr->getLocation(), diag::borrowed_with_objc_dynamic, |
181 | 3 | D->getDescriptiveKind()) |
182 | 3 | .fixItRemove(attr->getRange()); |
183 | 3 | D->getAttrs().removeAttribute(attr); |
184 | 3 | return; |
185 | 3 | } |
186 | | |
187 | 162 | auto dc = D->getDeclContext(); |
188 | 162 | auto protoDecl = dyn_cast<ProtocolDecl>(dc); |
189 | 162 | if (protoDecl && protoDecl->isObjC()) { |
190 | 3 | diagnose(attr->getLocation(), diag::borrowed_on_objc_protocol_requirement, |
191 | 3 | D->getDescriptiveKind()) |
192 | 3 | .fixItRemove(attr->getRange()); |
193 | 3 | D->getAttrs().removeAttribute(attr); |
194 | 3 | return; |
195 | 3 | } |
196 | 162 | } |
197 | | |
198 | | void visitTransparentAttr(TransparentAttr *attr); |
199 | | void visitMutationAttr(DeclAttribute *attr); |
200 | 28.8k | void visitMutatingAttr(MutatingAttr *attr) { visitMutationAttr(attr); } |
201 | 714 | void visitNonMutatingAttr(NonMutatingAttr *attr) { visitMutationAttr(attr); } |
202 | 198 | void visitBorrowingAttr(BorrowingAttr *attr) { visitMutationAttr(attr); } |
203 | 633 | void visitConsumingAttr(ConsumingAttr *attr) { visitMutationAttr(attr); } |
204 | 4.31k | void visitLegacyConsumingAttr(LegacyConsumingAttr *attr) { visitMutationAttr(attr); } |
205 | 12 | void visitResultDependsOnSelfAttr(ResultDependsOnSelfAttr *attr) { |
206 | 12 | visitMutationAttr(attr); |
207 | 12 | } |
208 | | void visitDynamicAttr(DynamicAttr *attr); |
209 | | |
210 | 1.03k | void visitIndirectAttr(IndirectAttr *attr) { |
211 | 1.03k | if (auto caseDecl = dyn_cast<EnumElementDecl>(D)) { |
212 | | // An indirect case should have a payload. |
213 | 831 | if (!caseDecl->hasAssociatedValues()) |
214 | 6 | diagnose(attr->getLocation(), diag::indirect_case_without_payload, |
215 | 6 | caseDecl->getBaseIdentifier()); |
216 | | // If the enum is already indirect, its cases don't need to be. |
217 | 825 | else if (caseDecl->getParentEnum()->getAttrs() |
218 | 825 | .hasAttribute<IndirectAttr>()) |
219 | 3 | diagnose(attr->getLocation(), diag::indirect_case_in_indirect_enum); |
220 | 831 | } |
221 | 1.03k | } |
222 | | |
223 | 228 | void visitWarnUnqualifiedAccessAttr(WarnUnqualifiedAccessAttr *attr) { |
224 | 228 | if (!D->getDeclContext()->isTypeContext()) { |
225 | 6 | diagnoseAndRemoveAttr(attr, diag::attr_methods_only, attr); |
226 | 6 | } |
227 | 228 | } |
228 | | |
229 | | void visitFinalAttr(FinalAttr *attr); |
230 | | void visitMoveOnlyAttr(MoveOnlyAttr *attr); |
231 | 72 | void visitCompileTimeConstAttr(CompileTimeConstAttr *attr) {} |
232 | | void visitIBActionAttr(IBActionAttr *attr); |
233 | | void visitIBSegueActionAttr(IBSegueActionAttr *attr); |
234 | | void visitLazyAttr(LazyAttr *attr); |
235 | | void visitIBDesignableAttr(IBDesignableAttr *attr); |
236 | | void visitIBInspectableAttr(IBInspectableAttr *attr); |
237 | | void visitGKInspectableAttr(GKInspectableAttr *attr); |
238 | | void visitIBOutletAttr(IBOutletAttr *attr); |
239 | | void visitLLDBDebuggerFunctionAttr(LLDBDebuggerFunctionAttr *attr); |
240 | | void visitNSManagedAttr(NSManagedAttr *attr); |
241 | | void visitOverrideAttr(OverrideAttr *attr); |
242 | | void visitNonOverrideAttr(NonOverrideAttr *attr); |
243 | | void visitAccessControlAttr(AccessControlAttr *attr); |
244 | | void visitSetterAccessAttr(SetterAccessAttr *attr); |
245 | | void visitSPIAccessControlAttr(SPIAccessControlAttr *attr); |
246 | | bool visitAbstractAccessControlAttr(AbstractAccessControlAttr *attr); |
247 | | |
248 | | void visitObjCAttr(ObjCAttr *attr); |
249 | | void visitNonObjCAttr(NonObjCAttr *attr); |
250 | | void visitObjCImplementationAttr(ObjCImplementationAttr *attr); |
251 | | void visitObjCMembersAttr(ObjCMembersAttr *attr); |
252 | | |
253 | | void visitOptionalAttr(OptionalAttr *attr); |
254 | | |
255 | | void visitAvailableAttr(AvailableAttr *attr); |
256 | | |
257 | | void visitCDeclAttr(CDeclAttr *attr); |
258 | | void visitExposeAttr(ExposeAttr *attr); |
259 | | void visitExternAttr(ExternAttr *attr); |
260 | | void visitUsedAttr(UsedAttr *attr); |
261 | | void visitSectionAttr(SectionAttr *attr); |
262 | | |
263 | | void visitDynamicCallableAttr(DynamicCallableAttr *attr); |
264 | | |
265 | | void visitDynamicMemberLookupAttr(DynamicMemberLookupAttr *attr); |
266 | | |
267 | | void visitNSCopyingAttr(NSCopyingAttr *attr); |
268 | | void visitRequiredAttr(RequiredAttr *attr); |
269 | | void visitRethrowsAttr(RethrowsAttr *attr); |
270 | | |
271 | | void checkApplicationMainAttribute(DeclAttribute *attr, |
272 | | Identifier Id_ApplicationDelegate, |
273 | | Identifier Id_Kit, |
274 | | Identifier Id_ApplicationMain); |
275 | | |
276 | | void visitNSApplicationMainAttr(NSApplicationMainAttr *attr); |
277 | | void visitUIApplicationMainAttr(UIApplicationMainAttr *attr); |
278 | | void visitMainTypeAttr(MainTypeAttr *attr); |
279 | | |
280 | | void visitUnsafeNoObjCTaggedPointerAttr(UnsafeNoObjCTaggedPointerAttr *attr); |
281 | | void visitSwiftNativeObjCRuntimeBaseAttr( |
282 | | SwiftNativeObjCRuntimeBaseAttr *attr); |
283 | | |
284 | | void checkOperatorAttribute(DeclAttribute *attr); |
285 | | |
286 | 1.69k | void visitInfixAttr(InfixAttr *attr) { checkOperatorAttribute(attr); } |
287 | 495 | void visitPostfixAttr(PostfixAttr *attr) { checkOperatorAttribute(attr); } |
288 | 1.75k | void visitPrefixAttr(PrefixAttr *attr) { checkOperatorAttribute(attr); } |
289 | | |
290 | | void visitSpecializeAttr(SpecializeAttr *attr); |
291 | | |
292 | | void visitFixedLayoutAttr(FixedLayoutAttr *attr); |
293 | | void visitUsableFromInlineAttr(UsableFromInlineAttr *attr); |
294 | | void visitInlinableAttr(InlinableAttr *attr); |
295 | | void visitOptimizeAttr(OptimizeAttr *attr); |
296 | | void visitExclusivityAttr(ExclusivityAttr *attr); |
297 | | |
298 | | void visitDiscardableResultAttr(DiscardableResultAttr *attr); |
299 | | void visitDynamicReplacementAttr(DynamicReplacementAttr *attr); |
300 | | void visitTypeEraserAttr(TypeEraserAttr *attr); |
301 | | void visitStorageRestrictionsAttr(StorageRestrictionsAttr *attr); |
302 | | void visitImplementsAttr(ImplementsAttr *attr); |
303 | | void visitNoMetadataAttr(NoMetadataAttr *attr); |
304 | | |
305 | | void visitFrozenAttr(FrozenAttr *attr); |
306 | | |
307 | | void visitCustomAttr(CustomAttr *attr); |
308 | | void visitPropertyWrapperAttr(PropertyWrapperAttr *attr); |
309 | | void visitResultBuilderAttr(ResultBuilderAttr *attr); |
310 | | |
311 | | void visitImplementationOnlyAttr(ImplementationOnlyAttr *attr); |
312 | | void visitSPIOnlyAttr(SPIOnlyAttr *attr); |
313 | | void visitNonEphemeralAttr(NonEphemeralAttr *attr); |
314 | | void checkOriginalDefinedInAttrs(ArrayRef<OriginallyDefinedInAttr *> Attrs); |
315 | | |
316 | | void visitDifferentiableAttr(DifferentiableAttr *attr); |
317 | | void visitDerivativeAttr(DerivativeAttr *attr); |
318 | | void visitTransposeAttr(TransposeAttr *attr); |
319 | | |
320 | | void visitActorAttr(ActorAttr *attr); |
321 | | void visitDistributedActorAttr(DistributedActorAttr *attr); |
322 | | void visitGlobalActorAttr(GlobalActorAttr *attr); |
323 | | void visitAsyncAttr(AsyncAttr *attr); |
324 | | void visitMarkerAttr(MarkerAttr *attr); |
325 | | |
326 | | void visitReasyncAttr(ReasyncAttr *attr); |
327 | | void visitNonisolatedAttr(NonisolatedAttr *attr); |
328 | | |
329 | | void visitNoImplicitCopyAttr(NoImplicitCopyAttr *attr); |
330 | | |
331 | | void visitAlwaysEmitConformanceMetadataAttr(AlwaysEmitConformanceMetadataAttr *attr); |
332 | | |
333 | | void visitUnavailableFromAsyncAttr(UnavailableFromAsyncAttr *attr); |
334 | | |
335 | | void visitUnsafeInheritExecutorAttr(UnsafeInheritExecutorAttr *attr); |
336 | | |
337 | | bool visitLifetimeAttr(DeclAttribute *attr); |
338 | | void visitEagerMoveAttr(EagerMoveAttr *attr); |
339 | | void visitNoEagerMoveAttr(NoEagerMoveAttr *attr); |
340 | | |
341 | | void visitCompilerInitializedAttr(CompilerInitializedAttr *attr); |
342 | | |
343 | | void checkAvailableAttrs(ArrayRef<AvailableAttr *> Attrs); |
344 | | void checkBackDeployedAttrs(ArrayRef<BackDeployedAttr *> Attrs); |
345 | | |
346 | | void visitKnownToBeLocalAttr(KnownToBeLocalAttr *attr); |
347 | | |
348 | | void visitSendableAttr(SendableAttr *attr); |
349 | | |
350 | | void visitMacroRoleAttr(MacroRoleAttr *attr); |
351 | | |
352 | | void visitRawLayoutAttr(RawLayoutAttr *attr); |
353 | | |
354 | | void visitNonEscapableAttr(NonEscapableAttr *attr); |
355 | | void visitUnsafeNonEscapableResultAttr(UnsafeNonEscapableResultAttr *attr); |
356 | | }; |
357 | | |
358 | | } // end anonymous namespace |
359 | | |
360 | 1.45k | void AttributeChecker::visitNoImplicitCopyAttr(NoImplicitCopyAttr *attr) { |
361 | | // Only allow for this attribute to be used when experimental move only is |
362 | | // enabled. |
363 | 1.45k | if (!D->getASTContext().LangOpts.hasFeature(Feature::NoImplicitCopy)) { |
364 | 6 | auto error = |
365 | 6 | diag::experimental_moveonly_feature_can_only_be_used_when_enabled; |
366 | 6 | diagnoseAndRemoveAttr(attr, error); |
367 | 6 | return; |
368 | 6 | } |
369 | | |
370 | 1.45k | if (auto *funcDecl = dyn_cast<FuncDecl>(D)) { |
371 | 15 | if (visitLifetimeAttr(attr)) |
372 | 0 | return; |
373 | | |
374 | | // We only handle non-lvalue arguments today. |
375 | 15 | if (funcDecl->isMutating()) { |
376 | 3 | auto error = diag::noimplicitcopy_attr_valid_only_on_local_let_params; |
377 | 3 | diagnoseAndRemoveAttr(attr, error); |
378 | 3 | return; |
379 | 3 | } |
380 | 12 | return; |
381 | 15 | } |
382 | | |
383 | 1.43k | auto *dc = D->getDeclContext(); |
384 | | |
385 | | // If we have a param decl that is marked as no implicit copy, change our |
386 | | // default specifier to be owned. |
387 | 1.43k | if (auto *paramDecl = dyn_cast<ParamDecl>(D)) { |
388 | | // We only handle non-lvalue arguments today. |
389 | 921 | if (paramDecl->getSpecifier() == ParamDecl::Specifier::InOut) { |
390 | 0 | auto error = diag::noimplicitcopy_attr_valid_only_on_local_let_params; |
391 | 0 | diagnoseAndRemoveAttr(attr, error); |
392 | 0 | return; |
393 | 0 | } |
394 | 921 | return; |
395 | 921 | } |
396 | | |
397 | 516 | auto *vd = dyn_cast<VarDecl>(D); |
398 | 516 | if (!vd) { |
399 | 0 | auto error = diag::noimplicitcopy_attr_valid_only_on_local_let_params; |
400 | 0 | diagnoseAndRemoveAttr(attr, error); |
401 | 0 | return; |
402 | 0 | } |
403 | | |
404 | | // If we have a 'var' instead of a 'let', bail. We only support on local |
405 | | // lets. |
406 | 516 | if (!vd->isLet()) { |
407 | 42 | auto error = diag::noimplicitcopy_attr_valid_only_on_local_let_params; |
408 | 42 | diagnoseAndRemoveAttr(attr, error); |
409 | 42 | return; |
410 | 42 | } |
411 | | |
412 | | // We only support local lets. |
413 | 474 | if (!dc->isLocalContext()) { |
414 | 12 | auto error = diag::noimplicitcopy_attr_valid_only_on_local_let_params; |
415 | 12 | diagnoseAndRemoveAttr(attr, error); |
416 | 12 | return; |
417 | 12 | } |
418 | | |
419 | | // We do not support static vars either yet. |
420 | 462 | if (dc->isTypeContext() && vd->isStatic()) { |
421 | 0 | auto error = diag::noimplicitcopy_attr_valid_only_on_local_let_params; |
422 | 0 | diagnoseAndRemoveAttr(attr, error); |
423 | 0 | return; |
424 | 0 | } |
425 | 462 | } |
426 | | |
427 | 12 | void AttributeChecker::visitAlwaysEmitConformanceMetadataAttr(AlwaysEmitConformanceMetadataAttr *attr) { |
428 | 12 | return; |
429 | 12 | } |
430 | | |
431 | 35.0k | void AttributeChecker::visitTransparentAttr(TransparentAttr *attr) { |
432 | 35.0k | DeclContext *dc = D->getDeclContext(); |
433 | | // Protocol declarations cannot be transparent. |
434 | 35.0k | if (isa<ProtocolDecl>(dc)) |
435 | 3 | diagnoseAndRemoveAttr(attr, diag::transparent_in_protocols_not_supported); |
436 | | // Class declarations cannot be transparent. |
437 | 35.0k | if (isa<ClassDecl>(dc)) { |
438 | | |
439 | | // @transparent is always ok on implicitly generated accessors: they can |
440 | | // be dispatched (even in classes) when the references are within the |
441 | | // class themselves. |
442 | 15 | if (!(isa<AccessorDecl>(D) && D->isImplicit())) |
443 | 15 | diagnoseAndRemoveAttr(attr, diag::transparent_in_classes_not_supported); |
444 | 15 | } |
445 | | |
446 | 35.0k | if (auto *VD = dyn_cast<VarDecl>(D)) { |
447 | | // Stored properties and variables can't be transparent. |
448 | 4.85k | if (VD->hasStorage()) |
449 | 3 | diagnoseAndRemoveAttr(attr, diag::attribute_invalid_on_stored_property, |
450 | 3 | attr); |
451 | 4.85k | } |
452 | 35.0k | } |
453 | | |
454 | 34.7k | void AttributeChecker::visitMutationAttr(DeclAttribute *attr) { |
455 | 34.7k | FuncDecl *FD = cast<FuncDecl>(D); |
456 | | |
457 | 34.7k | SelfAccessKind attrModifier; |
458 | 34.7k | switch (attr->getKind()) { |
459 | 4.31k | case DeclAttrKind::DAK_LegacyConsuming: |
460 | 4.31k | attrModifier = SelfAccessKind::LegacyConsuming; |
461 | 4.31k | break; |
462 | 28.8k | case DeclAttrKind::DAK_Mutating: |
463 | 28.8k | attrModifier = SelfAccessKind::Mutating; |
464 | 28.8k | break; |
465 | 714 | case DeclAttrKind::DAK_NonMutating: |
466 | 714 | attrModifier = SelfAccessKind::NonMutating; |
467 | 714 | break; |
468 | 633 | case DeclAttrKind::DAK_Consuming: |
469 | 633 | attrModifier = SelfAccessKind::Consuming; |
470 | 633 | break; |
471 | 198 | case DeclAttrKind::DAK_Borrowing: |
472 | 198 | attrModifier = SelfAccessKind::Borrowing; |
473 | 198 | break; |
474 | 12 | case DeclAttrKind::DAK_ResultDependsOnSelf: |
475 | 12 | attrModifier = SelfAccessKind::ResultDependsOnSelf; |
476 | 12 | break; |
477 | 0 | default: |
478 | 0 | llvm_unreachable("unhandled attribute kind"); |
479 | 34.7k | } |
480 | | |
481 | 34.7k | auto DC = FD->getDeclContext(); |
482 | | // mutation attributes may only appear in type context. |
483 | 34.7k | if (auto contextTy = DC->getDeclaredInterfaceType()) { |
484 | | // 'mutating' and 'nonmutating' are not valid on types |
485 | | // with reference semantics. |
486 | 34.7k | if (contextTy->hasReferenceSemantics()) { |
487 | 165 | switch (attrModifier) { |
488 | 30 | case SelfAccessKind::Consuming: |
489 | 102 | case SelfAccessKind::LegacyConsuming: |
490 | 105 | case SelfAccessKind::Borrowing: |
491 | 114 | case SelfAccessKind::ResultDependsOnSelf: |
492 | | // It's still OK to specify the ownership convention of methods in |
493 | | // classes. |
494 | 114 | break; |
495 | | |
496 | 30 | case SelfAccessKind::Mutating: |
497 | 51 | case SelfAccessKind::NonMutating: |
498 | 51 | diagnoseAndRemoveAttr(attr, diag::mutating_invalid_classes, |
499 | 51 | attrModifier, FD->getDescriptiveKind(), |
500 | 51 | DC->getSelfProtocolDecl() != nullptr); |
501 | 51 | break; |
502 | 165 | } |
503 | 165 | } |
504 | 34.7k | } else { |
505 | 3 | diagnoseAndRemoveAttr(attr, diag::mutating_invalid_global_scope, |
506 | 3 | attrModifier); |
507 | 3 | } |
508 | | |
509 | | // Verify we don't have more than one ownership specifier. |
510 | 34.7k | if ((FD->getAttrs().hasAttribute<MutatingAttr>() + |
511 | 34.7k | FD->getAttrs().hasAttribute<NonMutatingAttr>() + |
512 | 34.7k | FD->getAttrs().hasAttribute<LegacyConsumingAttr>() + |
513 | 34.7k | FD->getAttrs().hasAttribute<ConsumingAttr>() + |
514 | 34.7k | FD->getAttrs().hasAttribute<BorrowingAttr>() + |
515 | 34.7k | FD->getAttrs().hasAttribute<ResultDependsOnSelfAttr>()) > 1) { |
516 | 27 | if (auto *NMA = FD->getAttrs().getAttribute<NonMutatingAttr>()) { |
517 | 15 | if (attrModifier != SelfAccessKind::NonMutating) { |
518 | 9 | diagnoseAndRemoveAttr(NMA, diag::functions_mutating_and_not, |
519 | 9 | SelfAccessKind::NonMutating, attrModifier); |
520 | 9 | } |
521 | 15 | } |
522 | | |
523 | 27 | if (auto *MUA = FD->getAttrs().getAttribute<MutatingAttr>()) { |
524 | 18 | if (attrModifier != SelfAccessKind::Mutating) { |
525 | 9 | diagnoseAndRemoveAttr(MUA, diag::functions_mutating_and_not, |
526 | 9 | SelfAccessKind::Mutating, attrModifier); |
527 | 9 | } |
528 | 18 | } |
529 | | |
530 | 27 | if (auto *CSA = FD->getAttrs().getAttribute<LegacyConsumingAttr>()) { |
531 | 9 | if (attrModifier != SelfAccessKind::LegacyConsuming) { |
532 | 9 | diagnoseAndRemoveAttr(CSA, diag::functions_mutating_and_not, |
533 | 9 | SelfAccessKind::LegacyConsuming, attrModifier); |
534 | 9 | } |
535 | 9 | } |
536 | | |
537 | 27 | if (auto *CSA = FD->getAttrs().getAttribute<ConsumingAttr>()) { |
538 | 6 | if (attrModifier != SelfAccessKind::Consuming) { |
539 | 0 | diagnoseAndRemoveAttr(CSA, diag::functions_mutating_and_not, |
540 | 0 | SelfAccessKind::Consuming, attrModifier); |
541 | 0 | } |
542 | 6 | } |
543 | | |
544 | 27 | if (auto *BSA = FD->getAttrs().getAttribute<BorrowingAttr>()) { |
545 | 12 | if (attrModifier != SelfAccessKind::Borrowing) { |
546 | 6 | diagnoseAndRemoveAttr(BSA, diag::functions_mutating_and_not, |
547 | 6 | SelfAccessKind::Borrowing, attrModifier); |
548 | 6 | } |
549 | 12 | } |
550 | | |
551 | 27 | if (auto *RDSA = FD->getAttrs().getAttribute<ResultDependsOnSelfAttr>()) { |
552 | 0 | if (attrModifier != SelfAccessKind::ResultDependsOnSelf) { |
553 | 0 | diagnoseAndRemoveAttr(RDSA, diag::functions_mutating_and_not, |
554 | 0 | SelfAccessKind::ResultDependsOnSelf, |
555 | 0 | attrModifier); |
556 | 0 | } |
557 | 0 | } |
558 | 27 | } |
559 | | |
560 | 34.7k | if (auto *RDSA = FD->getAttrs().getAttribute<ResultDependsOnSelfAttr>()) { |
561 | 9 | if (FD->getResultTypeRepr() == nullptr) { |
562 | 3 | diagnoseAndRemoveAttr(RDSA, diag::result_depends_on_no_result, |
563 | 3 | attr->getAttrName()); |
564 | 3 | } |
565 | 9 | if (FD->getDescriptiveKind() != DescriptiveDeclKind::Method) { |
566 | 0 | diagnoseAndRemoveAttr(RDSA, diag::attr_methods_only, attr); |
567 | 0 | } |
568 | 9 | } |
569 | | // Verify that we don't have a static function. |
570 | 34.7k | if (FD->isStatic()) |
571 | 12 | diagnoseAndRemoveAttr(attr, diag::static_functions_not_mutating); |
572 | 34.7k | } |
573 | | |
574 | 2.79k | void AttributeChecker::visitDynamicAttr(DynamicAttr *attr) { |
575 | | // Members cannot be both dynamic and @_transparent. |
576 | 2.79k | if (D->getAttrs().hasAttribute<TransparentAttr>()) |
577 | 0 | diagnoseAndRemoveAttr(attr, diag::dynamic_with_transparent); |
578 | 2.79k | } |
579 | | |
580 | | /// Replaces asynchronous IBActionAttr/IBSegueActionAttr function declarations |
581 | | /// with a synchronous function. The body of the original function is moved |
582 | | /// inside of a task executed on the MainActor |
583 | 12 | static void emitFixItIBActionRemoveAsync(ASTContext &ctx, const FuncDecl &FD) { |
584 | | // If we don't have an async loc for some reason, things will explode |
585 | 12 | if (!FD.getAsyncLoc()) |
586 | 0 | return; |
587 | | |
588 | 12 | std::string replacement = ""; |
589 | | |
590 | | // attributes, function name and everything up to `async` (exclusive) |
591 | 12 | replacement += |
592 | 12 | CharSourceRange(ctx.SourceMgr, FD.getSourceRangeIncludingAttrs().Start, |
593 | 12 | FD.getAsyncLoc()) |
594 | 12 | .str(); |
595 | | |
596 | 12 | CharSourceRange returnType = Lexer::getCharSourceRangeFromSourceRange( |
597 | 12 | ctx.SourceMgr, FD.getResultTypeSourceRange()); |
598 | | |
599 | | // If we have a return type, include that here |
600 | 12 | if (returnType.isValid()) { |
601 | 6 | replacement += |
602 | 6 | (llvm::Twine("-> ") + Lexer::getCharSourceRangeFromSourceRange( |
603 | 6 | ctx.SourceMgr, FD.getResultTypeSourceRange()) |
604 | 6 | .str()) |
605 | 6 | .str(); |
606 | 6 | } |
607 | | |
608 | 12 | if (!FD.hasBody()) { |
609 | | // If we don't have any body, the sourcelocs won't work and will result in |
610 | | // crashes, so just swap out what we can |
611 | | |
612 | 3 | SourceLoc endLoc = |
613 | 3 | returnType.isValid() ? returnType.getEnd() : FD.getAsyncLoc(); |
614 | 3 | ctx.Diags |
615 | 3 | .diagnose(FD.getAsyncLoc(), diag::remove_async_add_task, &FD) |
616 | 3 | .fixItReplace( |
617 | 3 | SourceRange(FD.getSourceRangeIncludingAttrs().Start, endLoc), |
618 | 3 | replacement); |
619 | 3 | return; |
620 | 3 | } |
621 | | |
622 | 9 | if (returnType.isValid()) |
623 | 6 | replacement += " "; // insert space between type name and lbrace |
624 | | |
625 | 9 | replacement += "{\nTask { @MainActor in"; |
626 | | |
627 | | // If the body of the function is just "{}", there isn't anything to wrap. |
628 | | // stepping over the braces to grab just the body will result in the `Start` |
629 | | // location of the source range to come after the `End` of the range, and we |
630 | | // will overflow. Dance around this by just appending the end of the fix to |
631 | | // the replacement. |
632 | 9 | if (FD.getBody()->getLBraceLoc() != |
633 | 9 | FD.getBody()->getRBraceLoc().getAdvancedLocOrInvalid(-1)) { |
634 | | // We actually have a body, so add that to the string |
635 | 6 | CharSourceRange functionBody( |
636 | 6 | ctx.SourceMgr, FD.getBody()->getLBraceLoc().getAdvancedLocOrInvalid(1), |
637 | 6 | FD.getBody()->getRBraceLoc().getAdvancedLocOrInvalid(-1)); |
638 | 6 | replacement += functionBody.str(); |
639 | 6 | } |
640 | 9 | replacement += " }\n}"; |
641 | | |
642 | 9 | ctx.Diags |
643 | 9 | .diagnose(FD.getAsyncLoc(), diag::remove_async_add_task, &FD) |
644 | 9 | .fixItReplace(SourceRange(FD.getSourceRangeIncludingAttrs().Start, |
645 | 9 | FD.getBody()->getRBraceLoc()), |
646 | 9 | replacement); |
647 | 9 | } |
648 | | |
649 | | static bool |
650 | | validateIBActionSignature(ASTContext &ctx, DeclAttribute *attr, |
651 | | const FuncDecl *FD, unsigned minParameters, |
652 | 684 | unsigned maxParameters, bool hasVoidResult = true) { |
653 | 684 | bool valid = true; |
654 | | |
655 | 684 | auto arity = FD->getParameters()->size(); |
656 | 684 | auto resultType = FD->getResultInterfaceType(); |
657 | | |
658 | 684 | if (arity < minParameters || arity > maxParameters) { |
659 | 21 | auto diagID = diag::invalid_ibaction_argument_count; |
660 | 21 | if (minParameters == maxParameters) |
661 | 15 | diagID = diag::invalid_ibaction_argument_count_exact; |
662 | 6 | else if (minParameters == 0) |
663 | 0 | diagID = diag::invalid_ibaction_argument_count_max; |
664 | 21 | ctx.Diags.diagnose(FD, diagID, attr->getAttrName(), minParameters, |
665 | 21 | maxParameters); |
666 | 21 | valid = false; |
667 | 21 | } |
668 | | |
669 | 684 | if (resultType->isVoid() != hasVoidResult) { |
670 | 6 | ctx.Diags.diagnose(FD, diag::invalid_ibaction_result, attr->getAttrName(), |
671 | 6 | hasVoidResult); |
672 | 6 | valid = false; |
673 | 6 | } |
674 | | |
675 | 684 | if (FD->isAsyncContext()) { |
676 | 12 | ctx.Diags.diagnose(FD->getAsyncLoc(), diag::attr_decl_async, |
677 | 12 | attr->getAttrName(), FD->getDescriptiveKind()); |
678 | 12 | emitFixItIBActionRemoveAsync(ctx, *FD); |
679 | 12 | valid = false; |
680 | 12 | } |
681 | | |
682 | | // We don't need to check here that parameter or return types are |
683 | | // ObjC-representable; IsObjCRequest will validate that. |
684 | | |
685 | 684 | if (!valid) |
686 | 39 | attr->setInvalid(); |
687 | 684 | return valid; |
688 | 684 | } |
689 | | |
690 | 279 | static bool isiOS(ASTContext &ctx) { |
691 | 279 | return ctx.LangOpts.Target.isiOS(); |
692 | 279 | } |
693 | | |
694 | 279 | static bool iswatchOS(ASTContext &ctx) { |
695 | 279 | return ctx.LangOpts.Target.isWatchOS(); |
696 | 279 | } |
697 | | |
698 | 279 | static bool isRelaxedIBAction(ASTContext &ctx) { |
699 | 279 | return isiOS(ctx) || iswatchOS(ctx); |
700 | 279 | } |
701 | | |
702 | 288 | void AttributeChecker::visitIBActionAttr(IBActionAttr *attr) { |
703 | | // Only instance methods can be IBActions. |
704 | 288 | const FuncDecl *FD = cast<FuncDecl>(D); |
705 | 288 | if (!FD->isPotentialIBActionTarget()) { |
706 | 9 | diagnoseAndRemoveAttr(attr, diag::invalid_ibaction_decl, |
707 | 9 | attr->getAttrName()); |
708 | 9 | return; |
709 | 9 | } |
710 | | |
711 | 279 | if (isRelaxedIBAction(Ctx)) |
712 | | // iOS, tvOS, and watchOS allow 0-2 parameters to an @IBAction method. |
713 | 0 | validateIBActionSignature(Ctx, attr, FD, /*minParams=*/0, /*maxParams=*/2); |
714 | 279 | else |
715 | | // macOS allows 1 parameter to an @IBAction method. |
716 | 279 | validateIBActionSignature(Ctx, attr, FD, /*minParams=*/1, /*maxParams=*/1); |
717 | 279 | } |
718 | | |
719 | 405 | void AttributeChecker::visitIBSegueActionAttr(IBSegueActionAttr *attr) { |
720 | | // Only instance methods can be IBActions. |
721 | 405 | const FuncDecl *FD = cast<FuncDecl>(D); |
722 | 405 | if (!FD->isPotentialIBActionTarget()) |
723 | 9 | diagnoseAndRemoveAttr(attr, diag::invalid_ibaction_decl, |
724 | 9 | attr->getAttrName()); |
725 | | |
726 | 405 | if (!validateIBActionSignature(Ctx, attr, FD, |
727 | 405 | /*minParams=*/1, /*maxParams=*/3, |
728 | 405 | /*hasVoidResult=*/false)) |
729 | 12 | return; |
730 | | |
731 | | // If the IBSegueAction method's selector belongs to one of the ObjC method |
732 | | // families (like -newDocumentSegue: or -copyScreen), it would return the |
733 | | // object at +1, but the caller would expect it to be +0 and would therefore |
734 | | // leak it. |
735 | | // |
736 | | // To prevent that, diagnose if the selector belongs to one of the method |
737 | | // families and suggest that the user change the Swift name or Obj-C selector. |
738 | 393 | auto currentSelector = FD->getObjCSelector(); |
739 | | |
740 | 393 | SmallString<32> prefix("make"); |
741 | | |
742 | 393 | switch (currentSelector.getSelectorFamily()) { |
743 | 369 | case ObjCSelectorFamily::None: |
744 | | // No error--exit early. |
745 | 369 | return; |
746 | | |
747 | 3 | case ObjCSelectorFamily::Alloc: |
748 | 6 | case ObjCSelectorFamily::Init: |
749 | 18 | case ObjCSelectorFamily::New: |
750 | | // Fix-it will replace the "alloc"/"init"/"new" in the selector with "make". |
751 | 18 | break; |
752 | | |
753 | 3 | case ObjCSelectorFamily::Copy: |
754 | | // Fix-it will replace the "copy" in the selector with "makeCopy". |
755 | 3 | prefix += "Copy"; |
756 | 3 | break; |
757 | | |
758 | 3 | case ObjCSelectorFamily::MutableCopy: |
759 | | // Fix-it will replace the "mutable" in the selector with "makeMutable". |
760 | 3 | prefix += "Mutable"; |
761 | 3 | break; |
762 | 393 | } |
763 | | |
764 | | // Emit the actual error. |
765 | 24 | diagnose(FD, diag::ibsegueaction_objc_method_family, attr->getAttrName(), |
766 | 24 | currentSelector); |
767 | | |
768 | | // The rest of this is just fix-it generation. |
769 | | |
770 | | /// Replaces the first word of \c oldName with the prefix, where "word" is a |
771 | | /// sequence of lowercase characters. |
772 | 42 | auto replacingPrefix = [&](Identifier oldName) -> Identifier { |
773 | 42 | SmallString<32> scratch = prefix; |
774 | 42 | scratch += oldName.str().drop_while(clang::isLowercase); |
775 | 42 | return Ctx.getIdentifier(scratch); |
776 | 42 | }; |
777 | | |
778 | | // Suggest changing the Swift name of the method, unless there is already an |
779 | | // explicit selector. |
780 | 24 | if (!FD->getAttrs().hasAttribute<ObjCAttr>() || |
781 | 24 | !FD->getAttrs().getAttribute<ObjCAttr>()->hasName()) { |
782 | 18 | auto newSwiftBaseName = replacingPrefix(FD->getBaseIdentifier()); |
783 | 18 | auto argumentNames = FD->getName().getArgumentNames(); |
784 | 18 | DeclName newSwiftName(Ctx, newSwiftBaseName, argumentNames); |
785 | | |
786 | 18 | auto diag = diagnose(FD, diag::fixit_rename_in_swift, newSwiftName); |
787 | 18 | fixDeclarationName(diag, FD, newSwiftName); |
788 | 18 | } |
789 | | |
790 | | // Suggest changing just the selector to one with a different first piece. |
791 | 24 | auto oldPieces = currentSelector.getSelectorPieces(); |
792 | 24 | SmallVector<Identifier, 4> newPieces(oldPieces.begin(), oldPieces.end()); |
793 | 24 | newPieces[0] = replacingPrefix(newPieces[0]); |
794 | 24 | ObjCSelector newSelector(Ctx, currentSelector.getNumArgs(), newPieces); |
795 | | |
796 | 24 | auto diag = diagnose(FD, diag::fixit_rename_in_objc, newSelector); |
797 | 24 | fixDeclarationObjCName(diag, FD, currentSelector, newSelector); |
798 | 24 | } |
799 | | |
800 | 27 | void AttributeChecker::visitIBDesignableAttr(IBDesignableAttr *attr) { |
801 | 27 | if (auto *ED = dyn_cast<ExtensionDecl>(D)) { |
802 | 9 | if (auto nominalDecl = ED->getExtendedNominal()) { |
803 | 9 | if (!isa<ClassDecl>(nominalDecl)) |
804 | 6 | diagnoseAndRemoveAttr(attr, diag::invalid_ibdesignable_extension); |
805 | 9 | } |
806 | 9 | } |
807 | 27 | } |
808 | | |
809 | 63 | void AttributeChecker::visitIBInspectableAttr(IBInspectableAttr *attr) { |
810 | | // Only instance properties can be 'IBInspectable'. |
811 | 63 | auto *VD = cast<VarDecl>(D); |
812 | 63 | if (!VD->getDeclContext()->getSelfClassDecl() || VD->isStatic()) |
813 | 12 | diagnoseAndRemoveAttr(attr, diag::attr_must_be_used_on_class_instance, |
814 | 12 | attr->getAttrName()); |
815 | 63 | } |
816 | | |
817 | 60 | void AttributeChecker::visitGKInspectableAttr(GKInspectableAttr *attr) { |
818 | | // Only instance properties can be 'GKInspectable'. |
819 | 60 | auto *VD = cast<VarDecl>(D); |
820 | 60 | if (!VD->getDeclContext()->getSelfClassDecl() || VD->isStatic()) |
821 | 9 | diagnoseAndRemoveAttr(attr, diag::attr_must_be_used_on_class_instance, |
822 | 9 | attr->getAttrName()); |
823 | 60 | } |
824 | | |
825 | | static llvm::Optional<Diag<bool, Type>> |
826 | 354 | isAcceptableOutletType(Type type, bool &isArray, ASTContext &ctx) { |
827 | 354 | if (type->isObjCExistentialType() || type->isAny()) |
828 | 48 | return llvm::None; // @objc existential types are okay |
829 | | |
830 | 306 | auto nominal = type->getAnyNominal(); |
831 | | |
832 | 306 | if (auto classDecl = dyn_cast_or_null<ClassDecl>(nominal)) { |
833 | 129 | if (classDecl->isObjC()) |
834 | 114 | return llvm::None; // @objc class types are okay. |
835 | 15 | return diag::iboutlet_nonobjc_class; |
836 | 129 | } |
837 | | |
838 | 177 | if (type->isString()) { |
839 | | // String is okay because it is bridged to NSString. |
840 | | // FIXME: BridgesTypes.def is almost sufficient for this. |
841 | 24 | return llvm::None; |
842 | 24 | } |
843 | | |
844 | 153 | if (type->isArray()) { |
845 | | // Arrays of arrays are not allowed. |
846 | 54 | if (isArray) |
847 | 3 | return diag::iboutlet_nonobject_type; |
848 | | |
849 | 51 | isArray = true; |
850 | | |
851 | | // Handle Array<T>. T must be an Objective-C class or protocol. |
852 | 51 | auto boundTy = type->castTo<BoundGenericStructType>(); |
853 | 51 | auto boundArgs = boundTy->getGenericArgs(); |
854 | 51 | assert(boundArgs.size() == 1 && "invalid Array declaration"); |
855 | 0 | Type elementTy = boundArgs.front(); |
856 | 51 | return isAcceptableOutletType(elementTy, isArray, ctx); |
857 | 54 | } |
858 | | |
859 | 99 | if (type->isExistentialType()) |
860 | 21 | return diag::iboutlet_nonobjc_protocol; |
861 | | |
862 | | // No other types are permitted. |
863 | 78 | return diag::iboutlet_nonobject_type; |
864 | 99 | } |
865 | | |
866 | 303 | void AttributeChecker::visitIBOutletAttr(IBOutletAttr *attr) { |
867 | | // Only instance properties can be 'IBOutlet'. |
868 | 303 | auto *VD = cast<VarDecl>(D); |
869 | 303 | if (!VD->getDeclContext()->getSelfClassDecl() || VD->isStatic()) |
870 | 9 | diagnoseAndRemoveAttr(attr, diag::attr_must_be_used_on_class_instance, |
871 | 9 | attr->getAttrName()); |
872 | | |
873 | 303 | if (!VD->isSettable(nullptr)) { |
874 | | // Allow non-mutable IBOutlet properties in module interfaces, |
875 | | // as they may have been private(set) |
876 | 12 | SourceFile *Parent = VD->getDeclContext()->getParentSourceFile(); |
877 | 12 | if (!Parent || Parent->Kind != SourceFileKind::Interface) |
878 | 9 | diagnoseAndRemoveAttr(attr, diag::iboutlet_only_mutable); |
879 | 12 | } |
880 | | |
881 | | // Verify that the field type is valid as an outlet. |
882 | 303 | auto type = VD->getTypeInContext(); |
883 | | |
884 | 303 | if (VD->isInvalid()) |
885 | 0 | return; |
886 | | |
887 | | // Look through ownership types, and optionals. |
888 | 303 | type = type->getReferenceStorageReferent(); |
889 | 303 | bool wasOptional = false; |
890 | 303 | if (Type underlying = type->getOptionalObjectType()) { |
891 | 255 | type = underlying; |
892 | 255 | wasOptional = true; |
893 | 255 | } |
894 | | |
895 | 303 | bool isArray = false; |
896 | 303 | if (auto isError = isAcceptableOutletType(type, isArray, Ctx)) |
897 | 117 | diagnoseAndRemoveAttr(attr, isError.value(), |
898 | 117 | /*array=*/isArray, type); |
899 | | |
900 | | // Skip remaining diagnostics if the property has an |
901 | | // attached wrapper. |
902 | 303 | if (VD->hasAttachedPropertyWrapper()) |
903 | 3 | return; |
904 | | |
905 | | // If the type wasn't optional, an array, or unowned, complain. |
906 | 300 | if (!wasOptional && !isArray) { |
907 | 45 | diagnose(attr->getLocation(), diag::iboutlet_non_optional, type); |
908 | 45 | auto typeRange = VD->getTypeSourceRangeForDiagnostics(); |
909 | 45 | { // Only one diagnostic can be active at a time. |
910 | 45 | auto diag = diagnose(typeRange.Start, diag::note_make_optional, |
911 | 45 | OptionalType::get(type)); |
912 | 45 | if (type->hasSimpleTypeRepr()) { |
913 | 45 | diag.fixItInsertAfter(typeRange.End, "?"); |
914 | 45 | } else { |
915 | 0 | diag.fixItInsert(typeRange.Start, "(") |
916 | 0 | .fixItInsertAfter(typeRange.End, ")?"); |
917 | 0 | } |
918 | 45 | } |
919 | 45 | { // Only one diagnostic can be active at a time. |
920 | 45 | auto diag = diagnose(typeRange.Start, |
921 | 45 | diag::note_make_implicitly_unwrapped_optional); |
922 | 45 | if (type->hasSimpleTypeRepr()) { |
923 | 45 | diag.fixItInsertAfter(typeRange.End, "!"); |
924 | 45 | } else { |
925 | 0 | diag.fixItInsert(typeRange.Start, "(") |
926 | 0 | .fixItInsertAfter(typeRange.End, ")!"); |
927 | 0 | } |
928 | 45 | } |
929 | 45 | } |
930 | 300 | } |
931 | | |
932 | 243 | void AttributeChecker::visitNSManagedAttr(NSManagedAttr *attr) { |
933 | | // @NSManaged only applies to instance methods and properties within a class. |
934 | 243 | if (cast<ValueDecl>(D)->isStatic() || |
935 | 243 | !D->getDeclContext()->getSelfClassDecl()) { |
936 | 12 | diagnoseAndRemoveAttr(attr, diag::attr_NSManaged_not_instance_member); |
937 | 12 | } |
938 | | |
939 | 243 | if (auto *method = dyn_cast<FuncDecl>(D)) { |
940 | | // Separate out the checks for methods. |
941 | 33 | if (method->hasBody()) |
942 | 9 | diagnoseAndRemoveAttr(attr, diag::attr_NSManaged_method_body); |
943 | | |
944 | 33 | return; |
945 | 33 | } |
946 | | |
947 | | // Everything below deals with restrictions on @NSManaged properties. |
948 | 210 | auto *VD = cast<VarDecl>(D); |
949 | | |
950 | | // @NSManaged properties cannot be @NSCopying |
951 | 210 | if (auto *NSCopy = VD->getAttrs().getAttribute<NSCopyingAttr>()) |
952 | 3 | diagnoseAndRemoveAttr(NSCopy, diag::attr_NSManaged_NSCopying); |
953 | | |
954 | 210 | } |
955 | | |
956 | | void AttributeChecker:: |
957 | 27 | visitLLDBDebuggerFunctionAttr(LLDBDebuggerFunctionAttr *attr) { |
958 | | // This is only legal when debugger support is on. |
959 | 27 | if (!D->getASTContext().LangOpts.DebuggerSupport) |
960 | 0 | diagnoseAndRemoveAttr(attr, diag::attr_for_debugger_support_only); |
961 | 27 | } |
962 | | |
963 | 33.1k | void AttributeChecker::visitOverrideAttr(OverrideAttr *attr) { |
964 | 33.1k | if (!isa<ClassDecl>(D->getDeclContext()) && |
965 | 33.1k | !isa<ProtocolDecl>(D->getDeclContext()) && |
966 | 33.1k | !isa<ExtensionDecl>(D->getDeclContext())) |
967 | 105 | diagnoseAndRemoveAttr(attr, diag::override_nonclass_decl); |
968 | 33.1k | } |
969 | | |
970 | 342 | void AttributeChecker::visitNonOverrideAttr(NonOverrideAttr *attr) { |
971 | 342 | if (auto overrideAttr = D->getAttrs().getAttribute<OverrideAttr>()) |
972 | 3 | diagnoseAndRemoveAttr(overrideAttr, diag::nonoverride_and_override_attr); |
973 | | |
974 | 342 | if (!isa<ClassDecl>(D->getDeclContext()) && |
975 | 342 | !isa<ProtocolDecl>(D->getDeclContext()) && |
976 | 342 | !isa<ExtensionDecl>(D->getDeclContext())) { |
977 | 3 | diagnoseAndRemoveAttr(attr, diag::nonoverride_wrong_decl_context); |
978 | 3 | } |
979 | 342 | } |
980 | | |
981 | 1.39k | void AttributeChecker::visitLazyAttr(LazyAttr *attr) { |
982 | | // lazy may only be used on properties. |
983 | 1.39k | auto *VD = cast<VarDecl>(D); |
984 | | |
985 | 1.39k | auto attrs = VD->getAttrs(); |
986 | | // 'lazy' is not allowed to have reference attributes |
987 | 1.39k | if (auto *refAttr = attrs.getAttribute<ReferenceOwnershipAttr>()) |
988 | 9 | diagnoseAndRemoveAttr(attr, diag::lazy_not_strong, refAttr->get()); |
989 | | |
990 | 1.39k | auto varDC = VD->getDeclContext(); |
991 | | |
992 | | // 'lazy' is not allowed on a global variable or on a static property (which |
993 | | // are already lazily initialized). |
994 | 1.39k | if (VD->isStatic() || varDC->isModuleScopeContext()) |
995 | 6 | diagnoseAndRemoveAttr(attr, diag::lazy_on_already_lazy_global); |
996 | 1.39k | } |
997 | | |
998 | | bool AttributeChecker::visitAbstractAccessControlAttr( |
999 | 802k | AbstractAccessControlAttr *attr) { |
1000 | | // Access control attr may only be used on value decls, extensions and |
1001 | | // imports. |
1002 | 802k | if (!isa<ValueDecl>(D) && !isa<ExtensionDecl>(D) && !isa<ImportDecl>(D)) { |
1003 | 0 | diagnoseAndRemoveAttr(attr, diag::invalid_decl_modifier, attr); |
1004 | 0 | return true; |
1005 | 0 | } |
1006 | | |
1007 | 802k | if (auto extension = dyn_cast<ExtensionDecl>(D)) { |
1008 | 2.41k | if (!extension->getInherited().empty()) { |
1009 | 9 | diagnoseAndRemoveAttr(attr, diag::extension_access_with_conformances, |
1010 | 9 | attr); |
1011 | 9 | return true; |
1012 | 9 | } |
1013 | 2.41k | } |
1014 | | |
1015 | | // And not on certain value decls. |
1016 | 802k | if (isa<DestructorDecl>(D) || isa<EnumElementDecl>(D)) { |
1017 | 0 | diagnoseAndRemoveAttr(attr, diag::invalid_decl_modifier, attr); |
1018 | 0 | return true; |
1019 | 0 | } |
1020 | | |
1021 | | // Or within protocols. |
1022 | 802k | if (isa<ProtocolDecl>(D->getDeclContext())) { |
1023 | 33 | diagnoseAndRemoveAttr(attr, diag::access_control_in_protocol, attr); |
1024 | 33 | diagnose(attr->getLocation(), diag::access_control_in_protocol_detail); |
1025 | 33 | return true; |
1026 | 33 | } |
1027 | | |
1028 | 802k | SourceFile *File = D->getDeclContext()->getParentSourceFile(); |
1029 | 802k | if (auto importDecl = dyn_cast<ImportDecl>(D)) { |
1030 | 765 | if (attr->getAccess() == AccessLevel::Open) { |
1031 | 3 | diagnoseAndRemoveAttr(attr, diag::access_level_on_import_unsupported, |
1032 | 3 | attr); |
1033 | 3 | return true; |
1034 | 3 | } |
1035 | | |
1036 | 762 | if (attr->getAccess() != AccessLevel::Public) { |
1037 | 438 | if (auto exportedAttr = D->getAttrs().getAttribute<ExportedAttr>()) { |
1038 | 12 | diagnoseAndRemoveAttr(attr, diag::access_level_conflict_with_exported, |
1039 | 12 | exportedAttr, attr); |
1040 | 12 | return true; |
1041 | 12 | } |
1042 | 438 | } |
1043 | 762 | } |
1044 | | |
1045 | 802k | if (attr->getAccess() == AccessLevel::Package && |
1046 | 802k | D->getASTContext().LangOpts.PackageName.empty() && |
1047 | 802k | File && File->Kind != SourceFileKind::Interface) { |
1048 | | // `package` modifier used outside of a package. |
1049 | 18 | diagnose(attr->getLocation(), diag::access_control_requires_package_name, |
1050 | 18 | isa<ValueDecl>(D), D); |
1051 | 18 | return true; |
1052 | 18 | } |
1053 | | |
1054 | 802k | return false; |
1055 | 802k | } |
1056 | | |
1057 | 801k | void AttributeChecker::visitAccessControlAttr(AccessControlAttr *attr) { |
1058 | 801k | visitAbstractAccessControlAttr(attr); |
1059 | | |
1060 | 801k | if (auto extension = dyn_cast<ExtensionDecl>(D)) { |
1061 | 2.41k | if (attr->getAccess() == AccessLevel::Open) { |
1062 | 9 | auto diag = |
1063 | 9 | diagnose(attr->getLocation(), diag::access_control_extension_open); |
1064 | 9 | diag.fixItRemove(attr->getRange()); |
1065 | 84 | for (auto Member : extension->getMembers()) { |
1066 | 84 | if (auto *VD = dyn_cast<ValueDecl>(Member)) { |
1067 | 54 | if (VD->getAttrs().hasAttribute<AccessControlAttr>()) |
1068 | 24 | continue; |
1069 | | |
1070 | 30 | StringRef accessLevel = VD->isObjC() ? "open " : "public "; |
1071 | | |
1072 | 30 | if (auto *FD = dyn_cast<FuncDecl>(VD)) |
1073 | 15 | diag.fixItInsert(FD->getFuncLoc(), accessLevel); |
1074 | | |
1075 | 30 | if (auto *VAD = dyn_cast<VarDecl>(VD)) |
1076 | 15 | diag.fixItInsert(VAD->getParentPatternBinding()->getLoc(), |
1077 | 15 | accessLevel); |
1078 | 30 | } |
1079 | 84 | } |
1080 | | |
1081 | 9 | attr->setInvalid(); |
1082 | 9 | return; |
1083 | 9 | } |
1084 | | |
1085 | 2.40k | NominalTypeDecl *nominal = extension->getExtendedNominal(); |
1086 | | |
1087 | | // Extension is ill-formed; suppress the attribute. |
1088 | 2.40k | if (!nominal) { |
1089 | 0 | attr->setInvalid(); |
1090 | 0 | return; |
1091 | 0 | } |
1092 | | |
1093 | 2.40k | AccessLevel typeAccess = nominal->getFormalAccess(); |
1094 | 2.40k | if (attr->getAccess() > typeAccess) { |
1095 | 75 | diagnose(attr->getLocation(), diag::access_control_extension_more, |
1096 | 75 | typeAccess, nominal->getDescriptiveKind(), attr->getAccess()) |
1097 | 75 | .fixItRemove(attr->getRange()); |
1098 | 75 | attr->setInvalid(); |
1099 | 75 | return; |
1100 | 75 | } |
1101 | | |
1102 | 799k | } else if (auto extension = dyn_cast<ExtensionDecl>(D->getDeclContext())) { |
1103 | 287k | AccessLevel maxAccess = extension->getMaxAccessLevel(); |
1104 | 287k | if (std::min(attr->getAccess(), AccessLevel::Public) > maxAccess) { |
1105 | | // FIXME: It would be nice to say what part of the requirements actually |
1106 | | // end up being problematic. |
1107 | 42 | auto diag = diagnose(attr->getLocation(), |
1108 | 42 | diag::access_control_ext_requirement_member_more, |
1109 | 42 | attr->getAccess(), |
1110 | 42 | D->getDescriptiveKind(), |
1111 | 42 | maxAccess); |
1112 | 42 | swift::fixItAccess(diag, cast<ValueDecl>(D), maxAccess); |
1113 | 42 | return; |
1114 | 42 | } |
1115 | | |
1116 | 287k | if (auto extAttr = |
1117 | 287k | extension->getAttrs().getAttribute<AccessControlAttr>()) { |
1118 | 948 | AccessLevel defaultAccess = extension->getDefaultAccessLevel(); |
1119 | 948 | if (attr->getAccess() > defaultAccess) { |
1120 | 267 | auto diag = diagnose(attr->getLocation(), |
1121 | 267 | diag::access_control_ext_member_more, |
1122 | 267 | attr->getAccess(), |
1123 | 267 | extAttr->getAccess()); |
1124 | | // Don't try to fix this one; it's just a warning, and fixing it can |
1125 | | // lead to diagnostic fights between this and "declaration must be at |
1126 | | // least this accessible" checking for overrides and protocol |
1127 | | // requirements. |
1128 | 681 | } else if (attr->getAccess() == defaultAccess) { |
1129 | 405 | diagnose(attr->getLocation(), |
1130 | 405 | diag::access_control_ext_member_redundant, |
1131 | 405 | attr->getAccess(), |
1132 | 405 | D->getDescriptiveKind(), |
1133 | 405 | extAttr->getAccess()) |
1134 | 405 | .fixItRemove(attr->getRange()); |
1135 | 405 | } |
1136 | 286k | } else { |
1137 | 286k | if (auto VD = dyn_cast<ValueDecl>(D)) { |
1138 | 286k | if (!isa<NominalTypeDecl>(VD)) { |
1139 | | // Emit warning when trying to declare non-@objc `open` member inside |
1140 | | // an extension. |
1141 | 271k | if (!VD->isObjC() && attr->getAccess() == AccessLevel::Open) { |
1142 | 15 | diagnose(attr->getLocation(), |
1143 | 15 | diag::access_control_non_objc_open_member, |
1144 | 15 | VD->getDescriptiveKind()) |
1145 | 15 | .fixItReplace(attr->getRange(), "public"); |
1146 | 15 | } |
1147 | 271k | } |
1148 | 286k | } |
1149 | 286k | } |
1150 | 287k | } |
1151 | | |
1152 | 801k | if (attr->getAccess() == AccessLevel::Open) { |
1153 | 12.3k | auto classDecl = dyn_cast<ClassDecl>(D); |
1154 | 12.3k | if (!(classDecl && !classDecl->isActor()) && |
1155 | 12.3k | !D->isSyntacticallyOverridable() && |
1156 | 12.3k | !attr->isInvalid()) { |
1157 | 39 | diagnose(attr->getLocation(), diag::access_control_open_bad_decl) |
1158 | 39 | .fixItReplace(attr->getRange(), "public"); |
1159 | 39 | attr->setInvalid(); |
1160 | 39 | } |
1161 | 12.3k | } |
1162 | 801k | } |
1163 | | |
1164 | | void AttributeChecker::visitSetterAccessAttr( |
1165 | 990 | SetterAccessAttr *attr) { |
1166 | 990 | auto storage = dyn_cast<AbstractStorageDecl>(D); |
1167 | 990 | if (!storage) |
1168 | 0 | diagnoseAndRemoveAttr(attr, diag::access_control_setter, attr->getAccess()); |
1169 | | |
1170 | 990 | if (visitAbstractAccessControlAttr(attr)) |
1171 | 0 | return; |
1172 | | |
1173 | 990 | if (!storage->isSettable(storage->getDeclContext())) { |
1174 | | // This must stay in sync with diag::access_control_setter_read_only. |
1175 | 27 | enum { |
1176 | 27 | SK_Constant = 0, |
1177 | 27 | SK_Variable, |
1178 | 27 | SK_Property, |
1179 | 27 | SK_Subscript |
1180 | 27 | } storageKind; |
1181 | 27 | if (isa<SubscriptDecl>(storage)) |
1182 | 3 | storageKind = SK_Subscript; |
1183 | 24 | else if (storage->getDeclContext()->isTypeContext()) |
1184 | 12 | storageKind = SK_Property; |
1185 | 12 | else if (cast<VarDecl>(storage)->isLet()) |
1186 | 6 | storageKind = SK_Constant; |
1187 | 6 | else |
1188 | 6 | storageKind = SK_Variable; |
1189 | 27 | diagnoseAndRemoveAttr(attr, diag::access_control_setter_read_only, |
1190 | 27 | attr->getAccess(), storageKind); |
1191 | 27 | } |
1192 | | |
1193 | 990 | auto getterAccess = cast<ValueDecl>(D)->getFormalAccess(); |
1194 | 990 | if (attr->getAccess() > getterAccess) { |
1195 | | // This must stay in sync with diag::access_control_setter_more. |
1196 | 36 | enum { |
1197 | 36 | SK_Variable = 0, |
1198 | 36 | SK_Property, |
1199 | 36 | SK_Subscript |
1200 | 36 | } storageKind; |
1201 | 36 | if (isa<SubscriptDecl>(D)) |
1202 | 9 | storageKind = SK_Subscript; |
1203 | 27 | else if (D->getDeclContext()->isTypeContext()) |
1204 | 18 | storageKind = SK_Property; |
1205 | 9 | else |
1206 | 9 | storageKind = SK_Variable; |
1207 | 36 | diagnose(attr->getLocation(), diag::access_control_setter_more, |
1208 | 36 | getterAccess, storageKind, attr->getAccess()); |
1209 | 36 | attr->setInvalid(); |
1210 | 36 | return; |
1211 | | |
1212 | 954 | } else if (attr->getAccess() == getterAccess) { |
1213 | 174 | diagnose(attr->getLocation(), |
1214 | 174 | diag::access_control_setter_redundant, |
1215 | 174 | attr->getAccess(), |
1216 | 174 | D->getDescriptiveKind(), |
1217 | 174 | getterAccess) |
1218 | 174 | .fixItRemove(attr->getRange()); |
1219 | 174 | return; |
1220 | 174 | } |
1221 | 990 | } |
1222 | | |
1223 | 29.9k | void AttributeChecker::visitSPIAccessControlAttr(SPIAccessControlAttr *attr) { |
1224 | 29.9k | if (auto VD = dyn_cast<ValueDecl>(D)) { |
1225 | | // VD must be public or open to use an @_spi attribute. |
1226 | 28.5k | auto declAccess = VD->getFormalAccess(); |
1227 | 28.5k | auto DC = VD->getDeclContext()->getAsDecl(); |
1228 | 28.5k | if (declAccess < AccessLevel::Public && |
1229 | 28.5k | !VD->getAttrs().hasAttribute<UsableFromInlineAttr>() && |
1230 | 28.5k | !(DC && DC->isSPI())) { |
1231 | 24 | diagnoseAndRemoveAttr(attr, |
1232 | 24 | diag::spi_attribute_on_non_public, |
1233 | 24 | declAccess, |
1234 | 24 | D->getDescriptiveKind()); |
1235 | 24 | } |
1236 | | |
1237 | | // Forbid stored properties marked SPI in frozen types. |
1238 | 28.5k | if (auto property = dyn_cast<VarDecl>(VD)) { |
1239 | 9.20k | if (auto NTD = dyn_cast<NominalTypeDecl>(D->getDeclContext())) { |
1240 | 8.99k | if (property->isLayoutExposedToClients() && !NTD->isSPI()) { |
1241 | 24 | diagnoseAndRemoveAttr(attr, |
1242 | 24 | diag::spi_attribute_on_frozen_stored_properties, |
1243 | 24 | VD); |
1244 | 24 | } |
1245 | 8.99k | } |
1246 | 9.20k | } |
1247 | | |
1248 | | // Forbid enum elements marked SPI in frozen types. |
1249 | 28.5k | if (auto elt = dyn_cast<EnumElementDecl>(VD)) { |
1250 | 2.95k | if (auto ED = dyn_cast<EnumDecl>(D->getDeclContext())) { |
1251 | 2.95k | if (ED->getAttrs().hasAttribute<FrozenAttr>(/*allowInvalid*/ true) && |
1252 | 2.95k | !ED->isSPI()) { |
1253 | 6 | diagnoseAndRemoveAttr(attr, diag::spi_attribute_on_frozen_enum_case, |
1254 | 6 | VD); |
1255 | 6 | } |
1256 | 2.95k | } |
1257 | 2.95k | } |
1258 | 28.5k | } |
1259 | | |
1260 | 29.9k | if (auto ID = dyn_cast<ImportDecl>(D)) { |
1261 | 291 | auto importedModule = ID->getModule(); |
1262 | 291 | if (importedModule) { |
1263 | 291 | auto path = importedModule->getModuleFilename(); |
1264 | 291 | if (llvm::sys::path::extension(path) == ".swiftinterface" && |
1265 | 291 | !(path.endswith(".private.swiftinterface") || path.endswith(".package.swiftinterface"))) { |
1266 | | // If the module was built from the public swiftinterface, it can't |
1267 | | // have any SPI. |
1268 | 12 | diagnose(attr->getLocation(), |
1269 | 12 | diag::spi_attribute_on_import_of_public_module, |
1270 | 12 | importedModule->getName(), path); |
1271 | 12 | } |
1272 | 291 | } |
1273 | 291 | } |
1274 | 29.9k | } |
1275 | | |
1276 | 23.7k | static bool checkObjCDeclContext(Decl *D) { |
1277 | 23.7k | DeclContext *DC = D->getDeclContext(); |
1278 | 23.7k | if (DC->getSelfClassDecl()) |
1279 | 22.1k | return true; |
1280 | 1.65k | if (auto *PD = dyn_cast<ProtocolDecl>(DC)) |
1281 | 975 | if (PD->isObjC()) |
1282 | 867 | return true; |
1283 | 792 | return false; |
1284 | 1.65k | } |
1285 | | |
1286 | | static void diagnoseObjCAttrWithoutFoundation(DeclAttribute *attr, Decl *decl, |
1287 | | ObjCReason reason, |
1288 | 27.3k | DiagnosticBehavior behavior) { |
1289 | 27.3k | assert(attr->getKind() == DeclAttrKind::DAK_ObjC || |
1290 | 27.3k | attr->getKind() == DeclAttrKind::DAK_ObjCMembers); |
1291 | 0 | auto *SF = decl->getDeclContext()->getParentSourceFile(); |
1292 | 27.3k | assert(SF); |
1293 | | |
1294 | | // We only care about explicitly written @objc attributes. |
1295 | 27.3k | if (attr->isImplicit()) |
1296 | 2.93k | return; |
1297 | | |
1298 | | // @objc enums do not require -enable-objc-interop or Foundation be have been |
1299 | | // imported. |
1300 | 24.4k | if (isa<EnumDecl>(decl)) |
1301 | 300 | return; |
1302 | | |
1303 | 24.1k | auto &ctx = SF->getASTContext(); |
1304 | | |
1305 | 24.1k | if (!ctx.LangOpts.EnableObjCInterop) { |
1306 | 0 | diagnoseAndRemoveAttr(decl, attr, diag::objc_interop_disabled) |
1307 | 0 | .limitBehavior(behavior); |
1308 | 0 | return; |
1309 | 0 | } |
1310 | | |
1311 | | // Don't diagnose in a SIL file. |
1312 | 24.1k | if (SF->Kind == SourceFileKind::SIL) |
1313 | 499 | return; |
1314 | | |
1315 | | // Don't diagnose for -disable-objc-attr-requires-foundation-module. |
1316 | 23.6k | if (!ctx.LangOpts.EnableObjCAttrRequiresFoundation) |
1317 | 18.6k | return; |
1318 | | |
1319 | | // If we have the Foundation module, @objc is okay. |
1320 | 4.93k | auto *foundation = ctx.getLoadedModule(ctx.Id_Foundation); |
1321 | 4.93k | if (foundation && ctx.getImportCache().isImportedBy(foundation, SF)) |
1322 | 4.86k | return; |
1323 | | |
1324 | 69 | ctx.Diags.diagnose(attr->getLocation(), |
1325 | 69 | diag::attr_used_without_required_module, attr, |
1326 | 69 | ctx.Id_Foundation) |
1327 | 69 | .highlight(attr->getRangeWithAt()) |
1328 | 69 | .limitBehavior(behavior); |
1329 | 69 | reason.describe(decl); |
1330 | 69 | } |
1331 | | |
1332 | 27.9k | void AttributeChecker::visitObjCAttr(ObjCAttr *attr) { |
1333 | 27.9k | auto reason = objCReasonForObjCAttr(attr); |
1334 | 27.9k | auto behavior = behaviorLimitForObjCReason(reason, Ctx); |
1335 | | |
1336 | | // Only certain decls can be ObjC. |
1337 | 27.9k | llvm::Optional<Diag<>> error; |
1338 | 27.9k | if (isa<ClassDecl>(D)) { |
1339 | | /* ok */ |
1340 | 24.4k | } else if (auto *P = dyn_cast<ProtocolDecl>(D)) { |
1341 | 1.99k | if (P->isMarkerProtocol()) |
1342 | 3 | error = diag::invalid_objc_decl; |
1343 | | /* ok on non-marker protocols */ |
1344 | 22.4k | } else if (auto Ext = dyn_cast<ExtensionDecl>(D)) { |
1345 | 183 | if (!Ext->getSelfClassDecl()) |
1346 | 27 | error = diag::objc_extension_not_class; |
1347 | 22.2k | } else if (auto ED = dyn_cast<EnumDecl>(D)) { |
1348 | 330 | if (ED->isGenericContext()) |
1349 | 3 | error = diag::objc_enum_generic; |
1350 | 21.9k | } else if (auto EED = dyn_cast<EnumElementDecl>(D)) { |
1351 | 210 | auto ED = EED->getParentEnum(); |
1352 | 210 | if (!ED->getAttrs().hasAttribute<ObjCAttr>()) |
1353 | 27 | error = diag::objc_enum_case_req_objc_enum; |
1354 | 183 | else if (attr->hasName() && EED->getParentCase()->getElements().size() > 1) |
1355 | 45 | error = diag::objc_enum_case_multi; |
1356 | 21.7k | } else if (auto *func = dyn_cast<FuncDecl>(D)) { |
1357 | 11.1k | if (!checkObjCDeclContext(D)) |
1358 | 432 | error = diag::invalid_objc_decl_context; |
1359 | 10.6k | else if (auto accessor = dyn_cast<AccessorDecl>(func)) |
1360 | 1.05k | if (!accessor->isGetterOrSetter()) |
1361 | 27 | error = diag::objc_observing_accessor; |
1362 | 11.1k | } else if (isa<ConstructorDecl>(D) || |
1363 | 10.5k | isa<DestructorDecl>(D) || |
1364 | 10.5k | isa<SubscriptDecl>(D) || |
1365 | 10.5k | isa<VarDecl>(D)) { |
1366 | 10.5k | if (!checkObjCDeclContext(D)) |
1367 | 354 | error = diag::invalid_objc_decl_context; |
1368 | | /* ok */ |
1369 | 10.5k | } else { |
1370 | 0 | error = diag::invalid_objc_decl; |
1371 | 0 | } |
1372 | | |
1373 | 27.9k | if (error) { |
1374 | 918 | diagnoseAndRemoveAttr(attr, *error).limitBehavior(behavior); |
1375 | 918 | reason.describe(D); |
1376 | 918 | return; |
1377 | 918 | } |
1378 | | |
1379 | 27.0k | auto correctNameUsingNewAttr = [&](ObjCAttr *newAttr) { |
1380 | 408 | if (attr->isInvalid()) newAttr->setInvalid(); |
1381 | 408 | newAttr->setImplicit(attr->isImplicit()); |
1382 | 408 | newAttr->setNameImplicit(attr->isNameImplicit()); |
1383 | 408 | newAttr->setAddedByAccessNote(attr->getAddedByAccessNote()); |
1384 | 408 | D->getAttrs().add(newAttr); |
1385 | | |
1386 | 408 | D->getAttrs().removeAttribute(attr); |
1387 | 408 | attr->setInvalid(); |
1388 | 408 | }; |
1389 | | |
1390 | | // If there is a name, check whether the kind of name is |
1391 | | // appropriate. |
1392 | 27.0k | if (auto objcName = attr->getName()) { |
1393 | 3.35k | if (isa<ClassDecl>(D) || isa<ProtocolDecl>(D) || isa<VarDecl>(D) |
1394 | 3.35k | || isa<EnumDecl>(D) || isa<EnumElementDecl>(D) |
1395 | 3.35k | || isa<ExtensionDecl>(D)) { |
1396 | | // Types and properties can only have nullary |
1397 | | // names. Complain and recover by chopping off everything |
1398 | | // after the first name. |
1399 | 870 | if (objcName->getNumArgs() > 0) { |
1400 | 135 | SourceLoc firstNameLoc, afterFirstNameLoc; |
1401 | 135 | if (!attr->getNameLocs().empty()) { |
1402 | 90 | firstNameLoc = attr->getNameLocs().front(); |
1403 | 90 | afterFirstNameLoc = |
1404 | 90 | Lexer::getLocForEndOfToken(Ctx.SourceMgr, firstNameLoc); |
1405 | 90 | } |
1406 | 45 | else { |
1407 | 45 | firstNameLoc = D->getLoc(); |
1408 | 45 | } |
1409 | 135 | softenIfAccessNote(D, attr, |
1410 | 135 | diagnose(firstNameLoc, diag::objc_name_req_nullary, |
1411 | 135 | D->getDescriptiveKind()) |
1412 | 135 | .fixItRemoveChars(afterFirstNameLoc, attr->getRParenLoc()) |
1413 | 135 | .limitBehavior(behavior)); |
1414 | | |
1415 | 135 | correctNameUsingNewAttr( |
1416 | 135 | ObjCAttr::createNullary(Ctx, attr->AtLoc, attr->getLocation(), |
1417 | 135 | attr->getLParenLoc(), firstNameLoc, |
1418 | 135 | objcName->getSelectorPieces()[0], |
1419 | 135 | attr->getRParenLoc())); |
1420 | 135 | } |
1421 | 2.48k | } else if (isa<SubscriptDecl>(D) || isa<DestructorDecl>(D)) { |
1422 | 54 | SourceLoc diagLoc = attr->getLParenLoc(); |
1423 | 54 | if (diagLoc.isInvalid()) |
1424 | 9 | diagLoc = D->getLoc(); |
1425 | 54 | softenIfAccessNote(D, attr, |
1426 | 54 | diagnose(diagLoc, |
1427 | 54 | isa<SubscriptDecl>(D) |
1428 | 54 | ? diag::objc_name_subscript |
1429 | 54 | : diag::objc_name_deinit) |
1430 | 54 | .limitBehavior(behavior)); |
1431 | | |
1432 | 54 | correctNameUsingNewAttr( |
1433 | 54 | ObjCAttr::createUnnamed(Ctx, attr->AtLoc, attr->getLocation())); |
1434 | 2.43k | } else { |
1435 | 2.43k | auto func = cast<AbstractFunctionDecl>(D); |
1436 | | |
1437 | | // Trigger lazy loading of any imported members with the same selector. |
1438 | | // This ensures we correctly diagnose selector conflicts. |
1439 | 2.43k | if (auto *CD = D->getDeclContext()->getSelfClassDecl()) { |
1440 | 2.32k | (void) CD->lookupDirect(*objcName, !func->isStatic()); |
1441 | 2.32k | } |
1442 | | |
1443 | | // We have a function. Make sure that the number of parameters |
1444 | | // matches the "number of colons" in the name. |
1445 | 2.43k | auto params = func->getParameters(); |
1446 | 2.43k | unsigned numParameters = params->size(); |
1447 | 2.43k | if (auto CD = dyn_cast<ConstructorDecl>(func)) |
1448 | 249 | if (CD->isObjCZeroParameterWithLongSelector()) |
1449 | 57 | numParameters = 0; // Something like "init(foo: ())" |
1450 | | |
1451 | | // An async method, even if it is also 'throws', has |
1452 | | // one additional completion handler parameter in ObjC. |
1453 | 2.43k | if (func->hasAsync()) |
1454 | 24 | ++numParameters; |
1455 | 2.40k | else if (func->hasThrows()) // A throwing method has an error parameter. |
1456 | 174 | ++numParameters; |
1457 | | |
1458 | 2.43k | unsigned numArgumentNames = objcName->getNumArgs(); |
1459 | 2.43k | if (numArgumentNames != numParameters) { |
1460 | 219 | SourceLoc firstNameLoc = func->getLoc(); |
1461 | 219 | if (!attr->getNameLocs().empty()) |
1462 | 147 | firstNameLoc = attr->getNameLocs().front(); |
1463 | 219 | softenIfAccessNote(D, attr, |
1464 | 219 | diagnose(firstNameLoc, |
1465 | 219 | diag::objc_name_func_mismatch, |
1466 | 219 | isa<FuncDecl>(func), |
1467 | 219 | numArgumentNames, |
1468 | 219 | numArgumentNames != 1, |
1469 | 219 | numParameters, |
1470 | 219 | numParameters != 1, |
1471 | 219 | func->hasThrows()) |
1472 | 219 | .limitBehavior(behavior)); |
1473 | | |
1474 | 219 | correctNameUsingNewAttr( |
1475 | 219 | ObjCAttr::createUnnamed(Ctx, attr->AtLoc, attr->Range.Start)); |
1476 | 219 | } |
1477 | 2.43k | } |
1478 | 23.7k | } else if (isa<EnumElementDecl>(D)) { |
1479 | | // Enum elements require names. |
1480 | 72 | diagnoseAndRemoveAttr(attr, diag::objc_enum_case_req_name) |
1481 | 72 | .limitBehavior(behavior); |
1482 | 72 | reason.describe(D); |
1483 | 72 | } |
1484 | | |
1485 | | // Diagnose an @objc attribute used without importing Foundation. |
1486 | 27.0k | diagnoseObjCAttrWithoutFoundation(attr, D, reason, behavior); |
1487 | 27.0k | } |
1488 | | |
1489 | 3.54k | void AttributeChecker::visitNonObjCAttr(NonObjCAttr *attr) { |
1490 | | // Only extensions of classes; methods, properties, subscripts |
1491 | | // and constructors can be NonObjC. |
1492 | | // The last three are handled automatically by generic attribute |
1493 | | // validation -- for the first one, we have to check FuncDecls |
1494 | | // ourselves. |
1495 | 3.54k | auto func = dyn_cast<FuncDecl>(D); |
1496 | 3.54k | if (func && |
1497 | 3.54k | (isa<DestructorDecl>(func) || |
1498 | 2.07k | !checkObjCDeclContext(func) || |
1499 | 2.07k | (isa<AccessorDecl>(func) && |
1500 | 2.06k | !cast<AccessorDecl>(func)->isGetterOrSetter()))) { |
1501 | 6 | diagnoseAndRemoveAttr(attr, diag::invalid_nonobjc_decl); |
1502 | 6 | } |
1503 | | |
1504 | 3.54k | if (auto ext = dyn_cast<ExtensionDecl>(D)) { |
1505 | 6 | if (!ext->getSelfClassDecl()) |
1506 | 3 | diagnoseAndRemoveAttr(attr, diag::invalid_nonobjc_extension); |
1507 | 6 | } |
1508 | 3.54k | } |
1509 | | |
1510 | | void AttributeChecker:: |
1511 | 99 | visitObjCImplementationAttr(ObjCImplementationAttr *attr) { |
1512 | 99 | auto ED = cast<ExtensionDecl>(D); |
1513 | 99 | if (ED->isConstrainedExtension()) |
1514 | 0 | diagnoseAndRemoveAttr(attr, |
1515 | 0 | diag::attr_objc_implementation_must_be_unconditional); |
1516 | | |
1517 | 99 | auto CD = dyn_cast<ClassDecl>(ED->getExtendedNominal()); |
1518 | 99 | if (!CD) { |
1519 | 6 | diagnoseAndRemoveAttr(attr, |
1520 | 6 | diag::attr_objc_implementation_must_extend_class, |
1521 | 6 | ED->getExtendedNominal()); |
1522 | 6 | ED->getExtendedNominal()->diagnose(diag::decl_declared_here, |
1523 | 6 | ED->getExtendedNominal()); |
1524 | 6 | return; |
1525 | 6 | } |
1526 | | |
1527 | 93 | if (!CD->hasClangNode()) { |
1528 | 6 | diagnoseAndRemoveAttr(attr, diag::attr_objc_implementation_must_be_imported, |
1529 | 6 | CD); |
1530 | 6 | CD->diagnose(diag::decl_declared_here, CD); |
1531 | 6 | return; |
1532 | 6 | } |
1533 | | |
1534 | 87 | if (!CD->hasSuperclass()) { |
1535 | 3 | diagnoseAndRemoveAttr(attr, diag::attr_objc_implementation_must_have_super, |
1536 | 3 | CD); |
1537 | 3 | CD->diagnose(diag::decl_declared_here, CD); |
1538 | 3 | return; |
1539 | 3 | } |
1540 | | |
1541 | 84 | if (CD->isTypeErasedGenericClass()) { |
1542 | 3 | diagnoseAndRemoveAttr(attr, diag::objc_implementation_cannot_have_generics, |
1543 | 3 | CD); |
1544 | 3 | CD->diagnose(diag::decl_declared_here, CD); |
1545 | 3 | } |
1546 | | |
1547 | 84 | if (!attr->isCategoryNameInvalid() && !ED->getImplementedObjCDecl()) { |
1548 | 3 | diagnose(attr->getLocation(), |
1549 | 3 | diag::attr_objc_implementation_category_not_found, |
1550 | 3 | attr->CategoryName, CD); |
1551 | | |
1552 | | // attr->getRange() covers the attr name and argument list; adjust it to |
1553 | | // exclude the first token. |
1554 | 3 | auto newStart = Lexer::getLocForEndOfToken(Ctx.SourceMgr, |
1555 | 3 | attr->getRange().Start); |
1556 | 3 | if (attr->getRange().contains(newStart)) { |
1557 | 3 | auto argListRange = SourceRange(newStart, attr->getRange().End); |
1558 | 3 | diagnose(attr->getLocation(), |
1559 | 3 | diag::attr_objc_implementation_fixit_remove_category_name) |
1560 | 3 | .fixItRemove(argListRange); |
1561 | 3 | } |
1562 | | |
1563 | 3 | attr->setCategoryNameInvalid(); |
1564 | | |
1565 | 3 | return; |
1566 | 3 | } |
1567 | 84 | } |
1568 | | |
1569 | 267 | void AttributeChecker::visitObjCMembersAttr(ObjCMembersAttr *attr) { |
1570 | 267 | if (!isa<ClassDecl>(D)) |
1571 | 0 | diagnoseAndRemoveAttr(attr, diag::objcmembers_attribute_nonclass); |
1572 | | |
1573 | 267 | auto reason = ObjCReason(ObjCReason::ExplicitlyObjCMembers, attr); |
1574 | 267 | auto behavior = behaviorLimitForObjCReason(reason, Ctx); |
1575 | 267 | diagnoseObjCAttrWithoutFoundation(attr, D, reason, behavior); |
1576 | 267 | } |
1577 | | |
1578 | 537 | void AttributeChecker::visitOptionalAttr(OptionalAttr *attr) { |
1579 | 537 | if (!isa<ProtocolDecl>(D->getDeclContext())) { |
1580 | 18 | diagnoseAndRemoveAttr(attr, diag::optional_attribute_non_protocol); |
1581 | 519 | } else if (!cast<ProtocolDecl>(D->getDeclContext())->isObjC()) { |
1582 | 3 | diagnoseAndRemoveAttr(attr, diag::optional_attribute_non_objc_protocol); |
1583 | 516 | } else if (isa<ConstructorDecl>(D)) { |
1584 | 3 | diagnoseAndRemoveAttr(attr, diag::optional_attribute_initializer); |
1585 | 513 | } else { |
1586 | 513 | auto objcAttr = D->getAttrs().getAttribute<ObjCAttr>(); |
1587 | 513 | if (!objcAttr || objcAttr->isImplicit()) { |
1588 | 6 | auto diag = diagnose(attr->getLocation(), |
1589 | 6 | diag::optional_attribute_missing_explicit_objc); |
1590 | 6 | if (auto VD = dyn_cast<ValueDecl>(D)) |
1591 | 6 | diag.fixItInsert(VD->getAttributeInsertionLoc(false), "@objc "); |
1592 | 6 | } |
1593 | 513 | } |
1594 | 537 | } |
1595 | | |
1596 | 4.85M | void TypeChecker::checkDeclAttributes(Decl *D) { |
1597 | 4.85M | if (auto VD = dyn_cast<ValueDecl>(D)) |
1598 | 3.59M | TypeChecker::applyAccessNote(VD); |
1599 | | |
1600 | 4.85M | AttributeChecker Checker(D); |
1601 | | // We need to check all availableAttrs, OriginallyDefinedInAttr and |
1602 | | // BackDeployedAttr relative to each other, so collect them and check in |
1603 | | // batch later. |
1604 | 4.85M | llvm::SmallVector<AvailableAttr *, 4> availableAttrs; |
1605 | 4.85M | llvm::SmallVector<BackDeployedAttr *, 4> backDeployedAttrs; |
1606 | 4.85M | llvm::SmallVector<OriginallyDefinedInAttr*, 4> ODIAttrs; |
1607 | 4.85M | for (auto attr : D->getExpandedAttrs()) { |
1608 | 2.24M | if (!attr->isValid()) continue; |
1609 | | |
1610 | | // If Attr.def says that the attribute cannot appear on this kind of |
1611 | | // declaration, diagnose it and disable it. |
1612 | 2.24M | if (attr->canAppearOnDecl(D)) { |
1613 | 2.24M | if (auto *ODI = dyn_cast<OriginallyDefinedInAttr>(attr)) { |
1614 | 4.72k | ODIAttrs.push_back(ODI); |
1615 | 2.23M | } else if (auto *BD = dyn_cast<BackDeployedAttr>(attr)) { |
1616 | 1.78k | backDeployedAttrs.push_back(BD); |
1617 | 2.23M | } else { |
1618 | | // check @available attribute both collectively and individually. |
1619 | 2.23M | if (auto *AV = dyn_cast<AvailableAttr>(attr)) { |
1620 | 557k | availableAttrs.push_back(AV); |
1621 | 557k | } |
1622 | | // Otherwise, check it. |
1623 | 2.23M | Checker.visit(attr); |
1624 | 2.23M | } |
1625 | 2.24M | continue; |
1626 | 2.24M | } |
1627 | | |
1628 | | // Otherwise, this attribute cannot be applied to this declaration. If the |
1629 | | // attribute is only valid on one kind of declaration (which is pretty |
1630 | | // common) give a specific helpful error. |
1631 | 590 | auto PossibleDeclKinds = attr->getOptions() & DeclAttribute::OnAnyDecl; |
1632 | 590 | StringRef OnlyKind; |
1633 | 590 | switch (PossibleDeclKinds) { |
1634 | 0 | case DeclAttribute::OnAccessor: OnlyKind = "accessor"; break; |
1635 | 18 | case DeclAttribute::OnClass: OnlyKind = "class"; break; |
1636 | 9 | case DeclAttribute::OnConstructor: OnlyKind = "init"; break; |
1637 | 0 | case DeclAttribute::OnDestructor: OnlyKind = "deinit"; break; |
1638 | 0 | case DeclAttribute::OnEnum: OnlyKind = "enum"; break; |
1639 | 0 | case DeclAttribute::OnEnumCase: OnlyKind = "case"; break; |
1640 | 18 | case DeclAttribute::OnFunc | DeclAttribute::OnAccessor: // FIXME |
1641 | 66 | case DeclAttribute::OnFunc: OnlyKind = "func"; break; |
1642 | 15 | case DeclAttribute::OnImport: OnlyKind = "import"; break; |
1643 | 0 | case DeclAttribute::OnModule: OnlyKind = "module"; break; |
1644 | 3 | case DeclAttribute::OnParam: OnlyKind = "parameter"; break; |
1645 | 24 | case DeclAttribute::OnProtocol: OnlyKind = "protocol"; break; |
1646 | 12 | case DeclAttribute::OnStruct: OnlyKind = "struct"; break; |
1647 | 0 | case DeclAttribute::OnSubscript: OnlyKind = "subscript"; break; |
1648 | 0 | case DeclAttribute::OnTypeAlias: OnlyKind = "typealias"; break; |
1649 | 30 | case DeclAttribute::OnVar: OnlyKind = "var"; break; |
1650 | 413 | default: break; |
1651 | 590 | } |
1652 | | |
1653 | 590 | if (!OnlyKind.empty()) |
1654 | 177 | Checker.diagnoseAndRemoveAttr(attr, diag::attr_only_one_decl_kind, |
1655 | 177 | attr, OnlyKind); |
1656 | 413 | else if (attr->isDeclModifier()) |
1657 | 75 | Checker.diagnoseAndRemoveAttr(attr, diag::invalid_decl_modifier, attr); |
1658 | 338 | else |
1659 | 338 | Checker.diagnoseAndRemoveAttr(attr, diag::invalid_decl_attribute, attr); |
1660 | 590 | } |
1661 | 4.85M | Checker.checkAvailableAttrs(availableAttrs); |
1662 | 4.85M | Checker.checkBackDeployedAttrs(backDeployedAttrs); |
1663 | 4.85M | Checker.checkOriginalDefinedInAttrs(ODIAttrs); |
1664 | 4.85M | } |
1665 | | |
1666 | | /// Returns true if the given method is an valid implementation of a |
1667 | | /// @dynamicCallable attribute requirement. The method is given to be defined |
1668 | | /// as one of the following: `dynamicallyCall(withArguments:)` or |
1669 | | /// `dynamicallyCall(withKeywordArguments:)`. |
1670 | | bool swift::isValidDynamicCallableMethod(FuncDecl *decl, ModuleDecl *module, |
1671 | 477 | bool hasKeywordArguments) { |
1672 | 477 | auto &ctx = module->getASTContext(); |
1673 | | // There are two cases to check. |
1674 | | // 1. `dynamicallyCall(withArguments:)`. |
1675 | | // In this case, the method is valid if the argument has type `A` where |
1676 | | // `A` conforms to `ExpressibleByArrayLiteral`. |
1677 | | // `A.ArrayLiteralElement` and the return type can be arbitrary. |
1678 | | // 2. `dynamicallyCall(withKeywordArguments:)` |
1679 | | // In this case, the method is valid if the argument has type `D` where |
1680 | | // `D` conforms to `ExpressibleByDictionaryLiteral` and `D.Key` conforms to |
1681 | | // `ExpressibleByStringLiteral`. |
1682 | | // `D.Value` and the return type can be arbitrary. |
1683 | | |
1684 | 477 | auto paramList = decl->getParameters(); |
1685 | 477 | if (paramList->size() != 1 || paramList->get(0)->isVariadic()) return false; |
1686 | 474 | auto argType = paramList->get(0)->getTypeInContext(); |
1687 | | |
1688 | | // If non-keyword (positional) arguments, check that argument type conforms to |
1689 | | // `ExpressibleByArrayLiteral`. |
1690 | 474 | if (!hasKeywordArguments) { |
1691 | 309 | auto arrayLitProto = |
1692 | 309 | ctx.getProtocol(KnownProtocolKind::ExpressibleByArrayLiteral); |
1693 | 309 | return (bool)TypeChecker::conformsToProtocol(argType, arrayLitProto, module); |
1694 | 309 | } |
1695 | | // If keyword arguments, check that argument type conforms to |
1696 | | // `ExpressibleByDictionaryLiteral` and that the `Key` associated type |
1697 | | // conforms to `ExpressibleByStringLiteral`. |
1698 | 165 | auto stringLitProtocol = |
1699 | 165 | ctx.getProtocol(KnownProtocolKind::ExpressibleByStringLiteral); |
1700 | 165 | auto dictLitProto = |
1701 | 165 | ctx.getProtocol(KnownProtocolKind::ExpressibleByDictionaryLiteral); |
1702 | 165 | auto dictConf = TypeChecker::conformsToProtocol(argType, dictLitProto, module); |
1703 | 165 | if (dictConf.isInvalid()) |
1704 | 0 | return false; |
1705 | 165 | auto keyType = dictConf.getTypeWitnessByName(argType, ctx.Id_Key); |
1706 | 165 | return (bool)TypeChecker::conformsToProtocol(keyType, stringLitProtocol, module); |
1707 | 165 | } |
1708 | | |
1709 | | /// Returns true if the given nominal type has a valid implementation of a |
1710 | | /// @dynamicCallable attribute requirement with the given argument name. |
1711 | | static bool hasValidDynamicCallableMethod(NominalTypeDecl *decl, |
1712 | | Identifier argumentName, |
1713 | 228 | bool hasKeywordArgs) { |
1714 | 228 | auto &ctx = decl->getASTContext(); |
1715 | 228 | auto declType = decl->getDeclaredType(); |
1716 | 228 | DeclNameRef methodName({ ctx, ctx.Id_dynamicallyCall, { argumentName } }); |
1717 | 228 | auto candidates = TypeChecker::lookupMember(decl, declType, methodName); |
1718 | 228 | if (candidates.empty()) return false; |
1719 | | |
1720 | | // Filter valid candidates. |
1721 | 120 | auto *module = decl->getParentModule(); |
1722 | 123 | candidates.filter([&](LookupResultEntry entry, bool isOuter) { |
1723 | 123 | auto candidate = cast<FuncDecl>(entry.getValueDecl()); |
1724 | 123 | return isValidDynamicCallableMethod(candidate, module, hasKeywordArgs); |
1725 | 123 | }); |
1726 | | |
1727 | | // If there are no valid candidates, return false. |
1728 | 120 | if (candidates.size() == 0) return false; |
1729 | 114 | return true; |
1730 | 120 | } |
1731 | | |
1732 | | void AttributeChecker:: |
1733 | 114 | visitDynamicCallableAttr(DynamicCallableAttr *attr) { |
1734 | | // This attribute is only allowed on nominal types. |
1735 | 114 | auto decl = cast<NominalTypeDecl>(D); |
1736 | 114 | auto type = decl->getDeclaredType(); |
1737 | | |
1738 | 114 | bool hasValidMethod = false; |
1739 | 114 | hasValidMethod |= |
1740 | 114 | hasValidDynamicCallableMethod(decl, Ctx.Id_withArguments, |
1741 | 114 | /*hasKeywordArgs*/ false); |
1742 | 114 | hasValidMethod |= |
1743 | 114 | hasValidDynamicCallableMethod(decl, Ctx.Id_withKeywordArguments, |
1744 | 114 | /*hasKeywordArgs*/ true); |
1745 | 114 | if (!hasValidMethod) { |
1746 | 9 | diagnose(attr->getLocation(), diag::invalid_dynamic_callable_type, type); |
1747 | 9 | attr->setInvalid(); |
1748 | 9 | } |
1749 | 114 | } |
1750 | | |
1751 | | static bool hasSingleNonVariadicParam(SubscriptDecl *decl, |
1752 | | Identifier expectedLabel, |
1753 | 7.54k | bool ignoreLabel = false) { |
1754 | 7.54k | auto *indices = decl->getIndices(); |
1755 | 7.54k | if (decl->isInvalid() || indices->size() != 1) |
1756 | 24 | return false; |
1757 | | |
1758 | 7.51k | auto *index = indices->get(0); |
1759 | 7.51k | if (index->isVariadic() || !index->hasInterfaceType()) |
1760 | 6 | return false; |
1761 | | |
1762 | 7.51k | if (ignoreLabel) { |
1763 | 18 | return true; |
1764 | 18 | } |
1765 | | |
1766 | 7.49k | return index->getArgumentName() == expectedLabel; |
1767 | 7.51k | } |
1768 | | |
1769 | | /// Returns true if the given subscript method is an valid implementation of |
1770 | | /// the `subscript(dynamicMember:)` requirement for @dynamicMemberLookup. |
1771 | | /// The method is given to be defined as `subscript(dynamicMember:)`. |
1772 | | bool swift::isValidDynamicMemberLookupSubscript(SubscriptDecl *decl, |
1773 | | ModuleDecl *module, |
1774 | 1.14k | bool ignoreLabel) { |
1775 | | // It could be |
1776 | | // - `subscript(dynamicMember: {Writable}KeyPath<...>)`; or |
1777 | | // - `subscript(dynamicMember: String*)` |
1778 | 1.14k | return isValidKeyPathDynamicMemberLookup(decl, ignoreLabel) || |
1779 | 1.14k | isValidStringDynamicMemberLookup(decl, module, ignoreLabel); |
1780 | 1.14k | } |
1781 | | |
1782 | | bool swift::isValidStringDynamicMemberLookup(SubscriptDecl *decl, |
1783 | | ModuleDecl *module, |
1784 | 2.00k | bool ignoreLabel) { |
1785 | 2.00k | auto &ctx = decl->getASTContext(); |
1786 | | // There are two requirements: |
1787 | | // - The subscript method has exactly one, non-variadic parameter. |
1788 | | // - The parameter type conforms to `ExpressibleByStringLiteral`. |
1789 | 2.00k | if (!hasSingleNonVariadicParam(decl, ctx.Id_dynamicMember, |
1790 | 2.00k | ignoreLabel)) |
1791 | 117 | return false; |
1792 | | |
1793 | 1.89k | const auto *param = decl->getIndices()->get(0); |
1794 | 1.89k | auto paramType = param->getTypeInContext(); |
1795 | | |
1796 | | // If this is `subscript(dynamicMember: String*)` |
1797 | 1.89k | return TypeChecker::conformsToKnownProtocol( |
1798 | 1.89k | paramType, KnownProtocolKind::ExpressibleByStringLiteral, module); |
1799 | 2.00k | } |
1800 | | |
1801 | | bool swift::isValidKeyPathDynamicMemberLookup(SubscriptDecl *decl, |
1802 | 5.53k | bool ignoreLabel) { |
1803 | 5.53k | auto &ctx = decl->getASTContext(); |
1804 | 5.53k | if (!hasSingleNonVariadicParam(decl, ctx.Id_dynamicMember, |
1805 | 5.53k | ignoreLabel)) |
1806 | 237 | return false; |
1807 | | |
1808 | 5.29k | auto paramTy = decl->getIndices()->get(0)->getInterfaceType(); |
1809 | 5.29k | return paramTy->isKeyPath() || |
1810 | 5.29k | paramTy->isWritableKeyPath() || |
1811 | 5.29k | paramTy->isReferenceWritableKeyPath(); |
1812 | 5.53k | } |
1813 | | |
1814 | | /// The @dynamicMemberLookup attribute is only allowed on types that have at |
1815 | | /// least one subscript member declared like this: |
1816 | | /// |
1817 | | /// subscript<KeywordType: ExpressibleByStringLiteral, LookupValue> |
1818 | | /// (dynamicMember name: KeywordType) -> LookupValue { get } |
1819 | | /// |
1820 | | /// ... but doesn't care about the mutating'ness of the getter/setter. |
1821 | | /// We just manually check the requirements here. |
1822 | | void AttributeChecker:: |
1823 | 537 | visitDynamicMemberLookupAttr(DynamicMemberLookupAttr *attr) { |
1824 | | // This attribute is only allowed on nominal types. |
1825 | 537 | auto decl = cast<NominalTypeDecl>(D); |
1826 | 537 | auto type = decl->getDeclaredType(); |
1827 | 537 | auto &ctx = decl->getASTContext(); |
1828 | | |
1829 | 537 | auto *module = decl->getParentModule(); |
1830 | | |
1831 | 537 | auto emitInvalidTypeDiagnostic = [&](const SourceLoc loc) { |
1832 | 9 | diagnose(loc, diag::invalid_dynamic_member_lookup_type, type); |
1833 | 9 | attr->setInvalid(); |
1834 | 9 | }; |
1835 | | |
1836 | | // Look up `subscript(dynamicMember:)` candidates. |
1837 | 537 | DeclNameRef subscriptName( |
1838 | 537 | { ctx, DeclBaseName::createSubscript(), { ctx.Id_dynamicMember } }); |
1839 | 537 | auto candidates = TypeChecker::lookupMember(decl, type, subscriptName); |
1840 | | |
1841 | 537 | if (!candidates.empty()) { |
1842 | | // If no candidates are valid, then reject one. |
1843 | 528 | auto oneCandidate = candidates.front().getValueDecl(); |
1844 | 990 | candidates.filter([&](LookupResultEntry entry, bool isOuter) -> bool { |
1845 | 990 | auto cand = cast<SubscriptDecl>(entry.getValueDecl()); |
1846 | 990 | return isValidDynamicMemberLookupSubscript(cand, module); |
1847 | 990 | }); |
1848 | | |
1849 | 528 | if (candidates.empty()) { |
1850 | 6 | emitInvalidTypeDiagnostic(oneCandidate->getLoc()); |
1851 | 6 | } |
1852 | | |
1853 | 528 | return; |
1854 | 528 | } |
1855 | | |
1856 | | // If we couldn't find any candidates, it's likely because: |
1857 | | // |
1858 | | // 1. We don't have a subscript with `dynamicMember` label. |
1859 | | // 2. We have a subscript with `dynamicMember` label, but no argument label. |
1860 | | // |
1861 | | // Let's do another lookup using just the base name. |
1862 | 9 | auto newCandidates = |
1863 | 9 | TypeChecker::lookupMember(decl, type, DeclNameRef::createSubscript()); |
1864 | | |
1865 | | // Validate the candidates while ignoring the label. |
1866 | 9 | newCandidates.filter([&](const LookupResultEntry entry, bool isOuter) { |
1867 | 9 | auto cand = cast<SubscriptDecl>(entry.getValueDecl()); |
1868 | 9 | return isValidDynamicMemberLookupSubscript(cand, module, |
1869 | 9 | /*ignoreLabel*/ true); |
1870 | 9 | }); |
1871 | | |
1872 | | // If there were no potentially valid candidates, then throw an error. |
1873 | 9 | if (newCandidates.empty()) { |
1874 | 3 | emitInvalidTypeDiagnostic(attr->getLocation()); |
1875 | 3 | return; |
1876 | 3 | } |
1877 | | |
1878 | | // For each candidate, emit a diagnostic. If we don't have an explicit |
1879 | | // argument label, then emit a fix-it to suggest the user to add one. |
1880 | 9 | for (auto cand : newCandidates) { |
1881 | 9 | auto SD = cast<SubscriptDecl>(cand.getValueDecl()); |
1882 | 9 | auto index = SD->getIndices()->get(0); |
1883 | 9 | diagnose(SD, diag::invalid_dynamic_member_lookup_type, type); |
1884 | | |
1885 | | // If we have something like `subscript(foo:)` then we want to insert |
1886 | | // `dynamicMember` before `foo`. |
1887 | 9 | if (index->getParameterNameLoc().isValid() && |
1888 | 9 | index->getArgumentNameLoc().isInvalid()) { |
1889 | 6 | diagnose(SD, diag::invalid_dynamic_member_subscript) |
1890 | 6 | .highlight(index->getSourceRange()) |
1891 | 6 | .fixItInsert(index->getParameterNameLoc(), "dynamicMember "); |
1892 | 6 | } |
1893 | 9 | } |
1894 | | |
1895 | 6 | attr->setInvalid(); |
1896 | 6 | return; |
1897 | 9 | } |
1898 | | |
1899 | | /// Get the innermost enclosing declaration for a declaration. |
1900 | 10.0k | static Decl *getEnclosingDeclForDecl(Decl *D) { |
1901 | | // If the declaration is an accessor, treat its storage declaration |
1902 | | // as the enclosing declaration. |
1903 | 10.0k | if (auto *accessor = dyn_cast<AccessorDecl>(D)) { |
1904 | 2.03k | return accessor->getStorage(); |
1905 | 2.03k | } |
1906 | | |
1907 | 8.00k | return D->getDeclContext()->getInnermostDeclarationDeclContext(); |
1908 | 10.0k | } |
1909 | | |
1910 | 557k | void AttributeChecker::visitAvailableAttr(AvailableAttr *attr) { |
1911 | 557k | if (Ctx.LangOpts.DisableAvailabilityChecking) |
1912 | 100k | return; |
1913 | | |
1914 | | // FIXME: This seems like it could be diagnosed during parsing instead. |
1915 | 456k | while (attr->IsSPI) { |
1916 | 147 | if (attr->hasPlatform() && attr->Introduced.has_value()) |
1917 | 141 | break; |
1918 | 6 | diagnoseAndRemoveAttr(attr, diag::spi_available_malformed); |
1919 | 6 | break; |
1920 | 147 | } |
1921 | | |
1922 | 456k | if (attr->isNoAsync()) { |
1923 | 30 | const DeclContext * dctx = dyn_cast<DeclContext>(D); |
1924 | 30 | bool isAsyncDeclContext = dctx && dctx->isAsyncContext(); |
1925 | | |
1926 | 30 | if (const AbstractStorageDecl *decl = dyn_cast<AbstractStorageDecl>(D)) { |
1927 | 3 | const AccessorDecl * accessor = decl->getEffectfulGetAccessor(); |
1928 | 3 | isAsyncDeclContext |= accessor && accessor->isAsyncContext(); |
1929 | 3 | } |
1930 | | |
1931 | 30 | if (isAsyncDeclContext) { |
1932 | 9 | if (const ValueDecl *vd = dyn_cast<ValueDecl>(D)) { |
1933 | 9 | D->getASTContext().Diags.diagnose( |
1934 | 9 | D->getLoc(), diag::async_named_decl_must_be_available_from_async, |
1935 | 9 | vd); |
1936 | 9 | } else { |
1937 | 0 | D->getASTContext().Diags.diagnose( |
1938 | 0 | D->getLoc(), diag::async_decl_must_be_available_from_async, |
1939 | 0 | D->getDescriptiveKind()); |
1940 | 0 | } |
1941 | 9 | } |
1942 | | |
1943 | | // deinit's may not be unavailable from async contexts |
1944 | 30 | if (isa<DestructorDecl>(D)) { |
1945 | 3 | D->getASTContext().Diags.diagnose( |
1946 | 3 | D->getLoc(), diag::invalid_decl_attribute, attr); |
1947 | 3 | } |
1948 | 30 | } |
1949 | | |
1950 | | // Skip the remaining diagnostics in swiftinterfaces. |
1951 | 456k | auto *DC = D->getDeclContext(); |
1952 | 456k | auto *SF = DC->getParentSourceFile(); |
1953 | 456k | if (SF && SF->Kind == SourceFileKind::Interface) |
1954 | 425k | return; |
1955 | | |
1956 | | // The remaining diagnostics are only for attributes that are active for the |
1957 | | // current target triple. |
1958 | 30.9k | if (!attr->isActivePlatform(Ctx) && !attr->isLanguageVersionSpecific() && |
1959 | 30.9k | !attr->isPackageDescriptionVersionSpecific()) |
1960 | 14.3k | return; |
1961 | | |
1962 | | // Make sure there isn't a more specific attribute we should be using instead. |
1963 | | // findMostSpecificActivePlatform() is O(N), so only do this if we're checking |
1964 | | // an iOS attribute while building for macCatalyst. |
1965 | 16.6k | if (attr->Platform == PlatformKind::iOS && |
1966 | 16.6k | isPlatformActive(PlatformKind::macCatalyst, Ctx.LangOpts)) { |
1967 | 12 | if (attr != D->getAttrs().findMostSpecificActivePlatform(Ctx)) { |
1968 | 12 | return; |
1969 | 12 | } |
1970 | 12 | } |
1971 | | |
1972 | 16.6k | SourceLoc attrLoc = attr->getLocation(); |
1973 | 16.6k | auto versionAvailability = attr->getVersionAvailability(Ctx); |
1974 | 16.6k | if (versionAvailability == AvailableVersionComparison::Obsoleted || |
1975 | 16.6k | versionAvailability == AvailableVersionComparison::Unavailable) { |
1976 | 4.76k | if (auto cannotBeUnavailable = |
1977 | 4.76k | TypeChecker::diagnosticIfDeclCannotBeUnavailable(D)) { |
1978 | 33 | diagnose(attrLoc, cannotBeUnavailable.value()); |
1979 | 33 | return; |
1980 | 33 | } |
1981 | | |
1982 | 4.72k | if (auto *PD = dyn_cast<ProtocolDecl>(DC)) { |
1983 | 117 | if (auto *VD = dyn_cast<ValueDecl>(D)) { |
1984 | 117 | if (VD->isProtocolRequirement() && !PD->isObjC()) { |
1985 | 3 | diagnoseAndRemoveAttr(attr, |
1986 | 3 | diag::unavailable_method_non_objc_protocol); |
1987 | 3 | return; |
1988 | 3 | } |
1989 | 117 | } |
1990 | 117 | } |
1991 | 4.72k | } |
1992 | | |
1993 | | // The remaining diagnostics are only for attributes with introduced versions |
1994 | | // for specific platforms. |
1995 | 16.6k | if (!attr->hasPlatform() || !attr->Introduced.has_value()) |
1996 | 6.60k | return; |
1997 | | |
1998 | | // Find the innermost enclosing declaration with an availability |
1999 | | // range annotation and ensure that this attribute's available version range |
2000 | | // is fully contained within that declaration's range. If there is no such |
2001 | | // enclosing declaration, then there is nothing to check. |
2002 | 10.0k | llvm::Optional<AvailabilityContext> EnclosingAnnotatedRange; |
2003 | 10.0k | AvailabilityContext AttrRange = |
2004 | 10.0k | AvailabilityInference::availableRange(attr, Ctx); |
2005 | | |
2006 | 10.0k | if (auto *parent = getEnclosingDeclForDecl(D)) { |
2007 | 4.34k | if (auto enclosingAvailable = |
2008 | 4.34k | parent->getSemanticAvailableRangeAttr()) { |
2009 | 2.58k | const AvailableAttr *enclosingAttr = enclosingAvailable.value().first; |
2010 | 2.58k | const Decl *enclosingDecl = enclosingAvailable.value().second; |
2011 | 2.58k | EnclosingAnnotatedRange.emplace( |
2012 | 2.58k | AvailabilityInference::availableRange(enclosingAttr, Ctx)); |
2013 | 2.58k | if (!AttrRange.isContainedIn(*EnclosingAnnotatedRange)) { |
2014 | 42 | auto limit = DiagnosticBehavior::Unspecified; |
2015 | 42 | if (D->isImplicit()) { |
2016 | | // Incorrect availability for an implicit declaration is likely a |
2017 | | // compiler bug so make the diagnostic a warning. |
2018 | 0 | limit = DiagnosticBehavior::Warning; |
2019 | 42 | } else if (enclosingDecl != parent) { |
2020 | | // Members of extensions of nominal types with available ranges were |
2021 | | // not diagnosed previously, so only emit a warning in that case. |
2022 | 21 | if (isa<ExtensionDecl>(DC->getTopmostDeclarationDeclContext())) |
2023 | 21 | limit = DiagnosticBehavior::Warning; |
2024 | 21 | } |
2025 | 42 | diagnose(D->isImplicit() ? enclosingDecl->getLoc() |
2026 | 42 | : attr->getLocation(), |
2027 | 42 | diag::availability_decl_more_than_enclosing, |
2028 | 42 | D->getDescriptiveKind()) |
2029 | 42 | .limitBehavior(limit); |
2030 | 42 | if (D->isImplicit()) |
2031 | 0 | diagnose(enclosingDecl->getLoc(), |
2032 | 0 | diag::availability_implicit_decl_here, |
2033 | 0 | D->getDescriptiveKind(), |
2034 | 0 | prettyPlatformString(targetPlatform(Ctx.LangOpts)), |
2035 | 0 | AttrRange.getOSVersion().getLowerEndpoint()); |
2036 | 42 | diagnose(enclosingDecl->getLoc(), |
2037 | 42 | diag::availability_decl_more_than_enclosing_here, |
2038 | 42 | prettyPlatformString(targetPlatform(Ctx.LangOpts)), |
2039 | 42 | EnclosingAnnotatedRange->getOSVersion().getLowerEndpoint()); |
2040 | 42 | } |
2041 | 2.58k | } |
2042 | 4.34k | } |
2043 | | |
2044 | 10.0k | llvm::Optional<Diag<>> MaybeNotAllowed = |
2045 | 10.0k | TypeChecker::diagnosticIfDeclCannotBePotentiallyUnavailable(D); |
2046 | 10.0k | if (MaybeNotAllowed.has_value()) { |
2047 | 552 | AvailabilityContext DeploymentRange |
2048 | 552 | = AvailabilityContext::forDeploymentTarget(Ctx); |
2049 | 552 | if (EnclosingAnnotatedRange.has_value()) |
2050 | 93 | DeploymentRange.intersectWith(*EnclosingAnnotatedRange); |
2051 | | |
2052 | 552 | if (!DeploymentRange.isContainedIn(AttrRange)) |
2053 | 78 | diagnose(attrLoc, MaybeNotAllowed.value()); |
2054 | 552 | } |
2055 | 10.0k | } |
2056 | | |
2057 | 414 | void AttributeChecker::visitCDeclAttr(CDeclAttr *attr) { |
2058 | | // Only top-level func decls are currently supported. |
2059 | 414 | if (D->getDeclContext()->isTypeContext()) |
2060 | 6 | diagnose(attr->getLocation(), diag::cdecl_not_at_top_level); |
2061 | | |
2062 | | // The name must not be empty. |
2063 | 414 | if (attr->Name.empty()) |
2064 | 3 | diagnose(attr->getLocation(), diag::cdecl_empty_name); |
2065 | 414 | } |
2066 | | |
2067 | 963 | void AttributeChecker::visitExposeAttr(ExposeAttr *attr) { |
2068 | 963 | switch (attr->getExposureKind()) { |
2069 | 48 | case ExposureKind::Wasm: { |
2070 | | // Only top-level func decls are currently supported. |
2071 | 48 | if (!isa<FuncDecl>(D) || D->getDeclContext()->isTypeContext()) |
2072 | 6 | diagnose(attr->getLocation(), diag::expose_wasm_not_at_top_level_func); |
2073 | 48 | break; |
2074 | 0 | } |
2075 | 915 | case ExposureKind::Cxx: { |
2076 | 915 | auto *VD = cast<ValueDecl>(D); |
2077 | | // Expose cannot be mixed with '@_cdecl' declarations. |
2078 | 915 | if (VD->getAttrs().hasAttribute<CDeclAttr>()) |
2079 | 3 | diagnose(attr->getLocation(), diag::expose_only_non_other_attr, "@_cdecl"); |
2080 | | |
2081 | | // Nested exposed declarations are expected to be inside |
2082 | | // of other exposed declarations. |
2083 | 915 | bool hasExpose = true; |
2084 | 915 | const ValueDecl *decl = VD; |
2085 | 1.06k | while (const NominalTypeDecl *NMT = |
2086 | 915 | dyn_cast<NominalTypeDecl>(decl->getDeclContext())) { |
2087 | 150 | decl = NMT; |
2088 | 150 | hasExpose = NMT->getAttrs().hasAttribute<ExposeAttr>(); |
2089 | 150 | } |
2090 | 915 | if (!hasExpose) { |
2091 | 3 | diagnose(attr->getLocation(), diag::expose_inside_unexposed_decl, decl); |
2092 | 3 | } |
2093 | | |
2094 | | // Verify that the declaration is exposable. |
2095 | 915 | auto repr = cxx_translation::getDeclRepresentation(VD); |
2096 | 915 | if (repr.isUnsupported()) |
2097 | 66 | diagnose(attr->getLocation(), |
2098 | 66 | cxx_translation::diagnoseRepresenationError(*repr.error, VD)); |
2099 | | |
2100 | | // Verify that the name mentioned in the expose |
2101 | | // attribute matches the supported name pattern. |
2102 | 915 | if (!attr->Name.empty()) { |
2103 | 120 | if (isa<ConstructorDecl>(VD) && !attr->Name.startswith("init")) |
2104 | 3 | diagnose(attr->getLocation(), diag::expose_invalid_name_pattern_init, |
2105 | 3 | attr->Name); |
2106 | 120 | } |
2107 | 915 | break; |
2108 | 0 | } |
2109 | 963 | } |
2110 | 963 | } |
2111 | | |
2112 | | bool IsCCompatibleFuncDeclRequest::evaluate(Evaluator &evaluator, |
2113 | 165 | FuncDecl *FD) const { |
2114 | 165 | if (FD->isInvalid()) |
2115 | 0 | return false; |
2116 | | |
2117 | 165 | bool foundError = false; |
2118 | | |
2119 | 165 | if (FD->hasAsync()) { |
2120 | 3 | FD->diagnose(diag::c_func_async); |
2121 | 3 | foundError = true; |
2122 | 3 | } |
2123 | | |
2124 | 165 | if (FD->hasThrows()) { |
2125 | 3 | FD->diagnose(diag::c_func_throws); |
2126 | 3 | foundError = true; |
2127 | 3 | } |
2128 | | |
2129 | | // --- Check for unsupported result types. |
2130 | 165 | Type resultTy = FD->getResultInterfaceType(); |
2131 | 165 | if (!resultTy->isVoid() && !resultTy->isRepresentableIn(ForeignLanguage::C, FD)) { |
2132 | 6 | FD->diagnose(diag::c_func_unsupported_type, resultTy); |
2133 | 6 | foundError = true; |
2134 | 6 | } |
2135 | | |
2136 | 165 | for (auto *param : *FD->getParameters()) { |
2137 | | // --- Check for unsupported specifiers. |
2138 | 93 | if (param->isVariadic()) { |
2139 | 0 | FD->diagnose(diag::c_func_variadic, param->getName(), FD); |
2140 | 0 | foundError = true; |
2141 | 0 | } |
2142 | 93 | if (param->getSpecifier() != ParamSpecifier::Default) { |
2143 | 0 | param |
2144 | 0 | ->diagnose(diag::c_func_unsupported_specifier, |
2145 | 0 | ParamDecl::getSpecifierSpelling(param->getSpecifier()), |
2146 | 0 | param->getName(), FD) |
2147 | 0 | .fixItRemove(param->getSpecifierLoc()); |
2148 | 0 | foundError = true; |
2149 | 0 | } |
2150 | | |
2151 | | // --- Check for unsupported parameter types. |
2152 | 93 | auto paramTy = param->getTypeInContext(); |
2153 | 93 | if (!paramTy->isRepresentableIn(ForeignLanguage::C, FD)) { |
2154 | 9 | param->diagnose(diag::c_func_unsupported_type, paramTy); |
2155 | 9 | foundError = true; |
2156 | 9 | } |
2157 | 93 | } |
2158 | 165 | return !foundError; |
2159 | 165 | } |
2160 | | |
2161 | 165 | static bool isCCompatibleFuncDecl(FuncDecl *FD) { |
2162 | 165 | return evaluateOrDefault(FD->getASTContext().evaluator, |
2163 | 165 | IsCCompatibleFuncDeclRequest{FD}, {}); |
2164 | 165 | } |
2165 | | |
2166 | 237 | void AttributeChecker::visitExternAttr(ExternAttr *attr) { |
2167 | 237 | if (!Ctx.LangOpts.hasFeature(Feature::Extern)) { |
2168 | 0 | diagnoseAndRemoveAttr(attr, diag::attr_extern_experimental); |
2169 | 0 | return; |
2170 | 0 | } |
2171 | | // Only top-level func or static func decls are currently supported. |
2172 | 237 | auto *FD = dyn_cast<FuncDecl>(D); |
2173 | 237 | if (!FD || (FD->getDeclContext()->isTypeContext() && !FD->isStatic())) { |
2174 | 6 | diagnose(attr->getLocation(), diag::extern_not_at_top_level_func); |
2175 | 6 | } |
2176 | | |
2177 | | // C name must not be empty. |
2178 | 237 | if (attr->getExternKind() == ExternKind::C) { |
2179 | 165 | StringRef cName = attr->getCName(FD); |
2180 | 165 | if (cName.empty()) { |
2181 | 3 | diagnose(attr->getLocation(), diag::extern_empty_c_name); |
2182 | 162 | } else if (!attr->Name.has_value() && !clang::isValidAsciiIdentifier(cName)) { |
2183 | | // Warn non ASCII identifiers if it's *implicitly* specified. The C standard allows |
2184 | | // Universal Character Names in identifiers, but clang doesn't provide |
2185 | | // an easy way to validate them, so we warn identifers that is potentially |
2186 | | // invalid. If it's explicitly specified, we assume the user knows what |
2187 | | // they are doing, and don't warn. |
2188 | 9 | diagnose(attr->getLocation(), diag::extern_c_maybe_invalid_name, cName) |
2189 | 9 | .fixItInsert(attr->getRParenLoc(), (", \"" + cName + "\"").str()); |
2190 | 9 | } |
2191 | | |
2192 | | // Ensure the decl has C compatible interface. Otherwise it produces diagnostics. |
2193 | 165 | if (!isCCompatibleFuncDecl(FD)) { |
2194 | 21 | attr->setInvalid(); |
2195 | | // Mark the decl itself invalid not to require body even with invalid ExternAttr. |
2196 | 21 | FD->setInvalid(); |
2197 | 21 | } |
2198 | 165 | } |
2199 | | |
2200 | 330 | for (auto *otherAttr : D->getAttrs()) { |
2201 | | // @_cdecl cannot be mixed with @_extern since @_cdecl is for definitions |
2202 | | // @_silgen_name cannot be mixed to avoid SIL-level name ambiguity |
2203 | 330 | if (isa<CDeclAttr>(otherAttr) || isa<SILGenNameAttr>(otherAttr)) { |
2204 | 18 | diagnose(attr->getLocation(), diag::extern_only_non_other_attr, |
2205 | 18 | otherAttr->getAttrName()); |
2206 | 18 | } |
2207 | 330 | } |
2208 | 237 | } |
2209 | | |
2210 | 117 | void AttributeChecker::visitUsedAttr(UsedAttr *attr) { |
2211 | 117 | if (!Ctx.LangOpts.hasFeature(Feature::SymbolLinkageMarkers)) { |
2212 | 0 | diagnoseAndRemoveAttr(attr, diag::section_linkage_markers_disabled); |
2213 | 0 | return; |
2214 | 0 | } |
2215 | | |
2216 | 117 | if (D->getDeclContext()->isLocalContext()) |
2217 | 3 | diagnose(attr->getLocation(), diag::attr_only_at_non_local_scope, |
2218 | 3 | attr->getAttrName()); |
2219 | 114 | else if (D->getDeclContext()->isGenericContext()) |
2220 | 0 | diagnose(attr->getLocation(), diag::attr_only_at_non_generic_scope, |
2221 | 0 | attr->getAttrName()); |
2222 | 114 | else if (auto *VarD = dyn_cast<VarDecl>(D)) { |
2223 | 90 | if (!VarD->isStatic() && !D->getDeclContext()->isModuleScopeContext()) { |
2224 | 0 | diagnose(attr->getLocation(), diag::attr_only_on_static_properties, |
2225 | 0 | attr->getAttrName()); |
2226 | 90 | } else if (!VarD->hasStorageOrWrapsStorage()) { |
2227 | 0 | diagnose(attr->getLocation(), diag::attr_not_on_computed_properties, |
2228 | 0 | attr); |
2229 | 0 | } |
2230 | 90 | } |
2231 | 117 | } |
2232 | | |
2233 | 228 | void AttributeChecker::visitSectionAttr(SectionAttr *attr) { |
2234 | 228 | if (!Ctx.LangOpts.hasFeature(Feature::SymbolLinkageMarkers)) { |
2235 | 0 | diagnoseAndRemoveAttr(attr, diag::section_linkage_markers_disabled); |
2236 | 0 | return; |
2237 | 0 | } |
2238 | | |
2239 | | // The name must not be empty. |
2240 | 228 | if (attr->Name.empty()) |
2241 | 3 | diagnose(attr->getLocation(), diag::section_empty_name); |
2242 | | |
2243 | 228 | if (D->getDeclContext()->isLocalContext()) |
2244 | 3 | return; // already diagnosed |
2245 | | |
2246 | 225 | if (D->getDeclContext()->isGenericContext()) |
2247 | 12 | diagnose(attr->getLocation(), diag::attr_only_at_non_generic_scope, |
2248 | 12 | attr->getAttrName()); |
2249 | 213 | else if (auto *VarD = dyn_cast<VarDecl>(D)) { |
2250 | 195 | if (!VarD->isStatic() && !D->getDeclContext()->isModuleScopeContext()) { |
2251 | 3 | diagnose(attr->getLocation(), diag::attr_only_on_static_properties, |
2252 | 3 | attr->getAttrName()); |
2253 | 192 | } else if (!VarD->hasStorageOrWrapsStorage()) { |
2254 | 3 | diagnose(attr->getLocation(), diag::attr_not_on_computed_properties, |
2255 | 3 | attr); |
2256 | 3 | } |
2257 | 195 | } |
2258 | 225 | } |
2259 | | |
2260 | | void AttributeChecker::visitUnsafeNoObjCTaggedPointerAttr( |
2261 | 0 | UnsafeNoObjCTaggedPointerAttr *attr) { |
2262 | | // Only class protocols can have the attribute. |
2263 | 0 | auto proto = dyn_cast<ProtocolDecl>(D); |
2264 | 0 | if (!proto) { |
2265 | 0 | diagnose(attr->getLocation(), |
2266 | 0 | diag::no_objc_tagged_pointer_not_class_protocol); |
2267 | 0 | attr->setInvalid(); |
2268 | 0 | } |
2269 | | |
2270 | 0 | if (!proto->requiresClass() |
2271 | 0 | && !proto->getAttrs().hasAttribute<ObjCAttr>()) { |
2272 | 0 | diagnose(attr->getLocation(), |
2273 | 0 | diag::no_objc_tagged_pointer_not_class_protocol); |
2274 | 0 | attr->setInvalid(); |
2275 | 0 | } |
2276 | 0 | } |
2277 | | |
2278 | | void AttributeChecker::visitSwiftNativeObjCRuntimeBaseAttr( |
2279 | 66 | SwiftNativeObjCRuntimeBaseAttr *attr) { |
2280 | | // Only root classes can have the attribute. |
2281 | 66 | auto theClass = dyn_cast<ClassDecl>(D); |
2282 | 66 | if (!theClass) { |
2283 | 0 | diagnose(attr->getLocation(), |
2284 | 0 | diag::swift_native_objc_runtime_base_not_on_root_class); |
2285 | 0 | attr->setInvalid(); |
2286 | 0 | return; |
2287 | 0 | } |
2288 | | |
2289 | 66 | if (theClass->hasSuperclass()) { |
2290 | 0 | diagnose(attr->getLocation(), |
2291 | 0 | diag::swift_native_objc_runtime_base_not_on_root_class); |
2292 | 0 | attr->setInvalid(); |
2293 | 0 | return; |
2294 | 0 | } |
2295 | 66 | } |
2296 | | |
2297 | 18.7k | void AttributeChecker::visitFinalAttr(FinalAttr *attr) { |
2298 | | // Reject combining 'final' with 'open'. |
2299 | 18.7k | if (auto accessAttr = D->getAttrs().getAttribute<AccessControlAttr>()) { |
2300 | 13.0k | if (accessAttr->getAccess() == AccessLevel::Open) { |
2301 | 3 | diagnose(attr->getLocation(), diag::open_decl_cannot_be_final, |
2302 | 3 | D->getDescriptiveKind()); |
2303 | 3 | return; |
2304 | 3 | } |
2305 | 13.0k | } |
2306 | | |
2307 | 18.7k | if (isa<ClassDecl>(D)) |
2308 | 4.51k | return; |
2309 | | |
2310 | | // 'final' only makes sense in the context of a class declaration. |
2311 | | // Reject it on global functions, protocols, structs, enums, etc. |
2312 | 14.2k | if (!D->getDeclContext()->getSelfClassDecl()) { |
2313 | 66 | diagnose(attr->getLocation(), diag::member_cannot_be_final) |
2314 | 66 | .fixItRemove(attr->getRange()); |
2315 | | |
2316 | | // Remove the attribute so child declarations are not flagged as final |
2317 | | // and duplicate the error message. |
2318 | 66 | D->getAttrs().removeAttribute(attr); |
2319 | 66 | return; |
2320 | 66 | } |
2321 | | |
2322 | | // We currently only support final on var/let, func and subscript |
2323 | | // declarations. |
2324 | 14.1k | if (!isa<VarDecl>(D) && !isa<FuncDecl>(D) && !isa<SubscriptDecl>(D)) { |
2325 | 0 | diagnose(attr->getLocation(), diag::final_not_allowed_here) |
2326 | 0 | .fixItRemove(attr->getRange()); |
2327 | 0 | return; |
2328 | 0 | } |
2329 | | |
2330 | 14.1k | if (auto *accessor = dyn_cast<AccessorDecl>(D)) { |
2331 | 6 | if (!attr->isImplicit()) { |
2332 | 0 | unsigned Kind = 2; |
2333 | 0 | if (auto *VD = dyn_cast<VarDecl>(accessor->getStorage())) |
2334 | 0 | Kind = VD->isLet() ? 1 : 0; |
2335 | 0 | diagnose(attr->getLocation(), diag::final_not_on_accessors, Kind) |
2336 | 0 | .fixItRemove(attr->getRange()); |
2337 | 0 | return; |
2338 | 0 | } |
2339 | 6 | } |
2340 | 14.1k | } |
2341 | | |
2342 | 1.92k | void AttributeChecker::visitMoveOnlyAttr(MoveOnlyAttr *attr) { |
2343 | 1.92k | if (!D->getASTContext().supportsMoveOnlyTypes()) |
2344 | 3 | D->diagnose(diag::moveOnly_requires_lexical_lifetimes); |
2345 | | |
2346 | 1.92k | if (isa<StructDecl>(D) || isa<EnumDecl>(D)) |
2347 | 1.83k | return; |
2348 | | |
2349 | | // for development purposes, allow it if specifically requested for classes. |
2350 | 81 | if (D->getASTContext().LangOpts.hasFeature(Feature::MoveOnlyClasses)) { |
2351 | 69 | if (isa<ClassDecl>(D)) |
2352 | 69 | return; |
2353 | 69 | } |
2354 | | |
2355 | 12 | diagnose(attr->getLocation(), diag::moveOnly_not_allowed_here) |
2356 | 12 | .fixItRemove(attr->getRange()); |
2357 | 12 | } |
2358 | | |
2359 | | /// Return true if this is a builtin operator that cannot be defined in user |
2360 | | /// code. |
2361 | 3.94k | static bool isBuiltinOperator(StringRef name, DeclAttribute *attr) { |
2362 | 3.94k | return ((isa<PrefixAttr>(attr) && name == "&") || // lvalue to inout |
2363 | 3.94k | (isa<PostfixAttr>(attr) && name == "!") || // optional unwrapping |
2364 | | // FIXME: Not actually a builtin operator, but should probably |
2365 | | // be allowed and accounted for in Sema? |
2366 | 3.94k | (isa<PrefixAttr>(attr) && name == "?") || |
2367 | 3.94k | (isa<PostfixAttr>(attr) && name == "?") || // optional chaining |
2368 | 3.94k | (isa<InfixAttr>(attr) && name == "?") || // ternary operator |
2369 | 3.94k | (isa<PostfixAttr>(attr) && name == ">") || // generic argument list |
2370 | 3.94k | (isa<PrefixAttr>(attr) && name == "<") || // generic argument list |
2371 | 3.94k | name == "=" || // Assignment |
2372 | | // FIXME: Should probably be allowed in expression position? |
2373 | 3.94k | name == "->"); |
2374 | 3.94k | } |
2375 | | |
2376 | 3.94k | void AttributeChecker::checkOperatorAttribute(DeclAttribute *attr) { |
2377 | | // Check out the operator attributes. They may be attached to an operator |
2378 | | // declaration or a function. |
2379 | 3.94k | if (auto *OD = dyn_cast<OperatorDecl>(D)) { |
2380 | | // Reject attempts to define builtin operators. |
2381 | 2.42k | if (isBuiltinOperator(OD->getName().str(), attr)) { |
2382 | 24 | diagnose(D->getStartLoc(), diag::redefining_builtin_operator, |
2383 | 24 | attr->getAttrName(), OD->getName().str()); |
2384 | 24 | attr->setInvalid(); |
2385 | 24 | return; |
2386 | 24 | } |
2387 | | |
2388 | | // Otherwise, the attribute is always ok on an operator. |
2389 | 2.39k | return; |
2390 | 2.42k | } |
2391 | | |
2392 | | // Operators implementations may only be defined as functions. |
2393 | 1.52k | auto *FD = dyn_cast<FuncDecl>(D); |
2394 | 1.52k | if (!FD) { |
2395 | 0 | diagnose(D->getLoc(), diag::operator_not_func); |
2396 | 0 | attr->setInvalid(); |
2397 | 0 | return; |
2398 | 0 | } |
2399 | | |
2400 | | // Only functions with an operator identifier can be declared with as an |
2401 | | // operator. |
2402 | 1.52k | if (!FD->isOperator()) { |
2403 | 3 | diagnose(D->getStartLoc(), diag::attribute_requires_operator_identifier, |
2404 | 3 | attr->getAttrName()); |
2405 | 3 | attr->setInvalid(); |
2406 | 3 | return; |
2407 | 3 | } |
2408 | | |
2409 | | // Reject attempts to define builtin operators. |
2410 | 1.52k | if (isBuiltinOperator(FD->getBaseIdentifier().str(), attr)) { |
2411 | 9 | diagnose(D->getStartLoc(), diag::redefining_builtin_operator, |
2412 | 9 | attr->getAttrName(), FD->getBaseIdentifier().str()); |
2413 | 9 | attr->setInvalid(); |
2414 | 9 | return; |
2415 | 9 | } |
2416 | | |
2417 | | // Otherwise, must be unary. |
2418 | 1.51k | if (!FD->isUnaryOperator()) { |
2419 | 3 | diagnose(attr->getLocation(), diag::attribute_requires_single_argument, |
2420 | 3 | attr->getAttrName()); |
2421 | 3 | attr->setInvalid(); |
2422 | 3 | return; |
2423 | 3 | } |
2424 | 1.51k | } |
2425 | | |
2426 | 42 | void AttributeChecker::visitNSCopyingAttr(NSCopyingAttr *attr) { |
2427 | | // The @NSCopying attribute is only allowed on stored properties. |
2428 | 42 | auto *VD = cast<VarDecl>(D); |
2429 | | |
2430 | | // It may only be used on class members. |
2431 | 42 | auto classDecl = D->getDeclContext()->getSelfClassDecl(); |
2432 | 42 | if (!classDecl) { |
2433 | 3 | diagnose(attr->getLocation(), diag::nscopying_only_on_class_properties); |
2434 | 3 | attr->setInvalid(); |
2435 | 3 | return; |
2436 | 3 | } |
2437 | | |
2438 | 39 | if (!VD->isSettable(VD->getDeclContext())) { |
2439 | 3 | diagnose(attr->getLocation(), diag::nscopying_only_mutable); |
2440 | 3 | attr->setInvalid(); |
2441 | 3 | return; |
2442 | 3 | } |
2443 | | |
2444 | 36 | if (!VD->hasStorage()) { |
2445 | 3 | diagnose(attr->getLocation(), diag::nscopying_only_stored_property); |
2446 | 3 | attr->setInvalid(); |
2447 | 3 | return; |
2448 | 3 | } |
2449 | | |
2450 | 33 | if (VD->hasInterfaceType()) { |
2451 | 33 | if (TypeChecker::checkConformanceToNSCopying(VD).isInvalid()) { |
2452 | 6 | attr->setInvalid(); |
2453 | 6 | return; |
2454 | 6 | } |
2455 | 33 | } |
2456 | | |
2457 | 27 | assert(VD->getOverriddenDecl() == nullptr && |
2458 | 27 | "Can't have value with storage that is an override"); |
2459 | | |
2460 | | // Check the type. It must be an [unchecked]optional, weak, a normal |
2461 | | // class, AnyObject, or classbound protocol. |
2462 | | // It must conform to the NSCopying protocol. |
2463 | | |
2464 | 27 | } |
2465 | | |
2466 | | void AttributeChecker::checkApplicationMainAttribute(DeclAttribute *attr, |
2467 | | Identifier Id_ApplicationDelegate, |
2468 | | Identifier Id_Kit, |
2469 | 99 | Identifier Id_ApplicationMain) { |
2470 | | // %select indexes for ApplicationMain diagnostics. |
2471 | 99 | enum : unsigned { |
2472 | 99 | UIApplicationMainClass, |
2473 | 99 | NSApplicationMainClass, |
2474 | 99 | }; |
2475 | | |
2476 | 99 | unsigned applicationMainKind; |
2477 | 99 | if (isa<UIApplicationMainAttr>(attr)) |
2478 | 30 | applicationMainKind = UIApplicationMainClass; |
2479 | 69 | else if (isa<NSApplicationMainAttr>(attr)) |
2480 | 69 | applicationMainKind = NSApplicationMainClass; |
2481 | 0 | else |
2482 | 0 | llvm_unreachable("not an ApplicationMain attr"); |
2483 | | |
2484 | 99 | auto *CD = dyn_cast<ClassDecl>(D); |
2485 | | |
2486 | | // The applicant not being a class should have been diagnosed by the early |
2487 | | // checker. |
2488 | 99 | if (!CD) return; |
2489 | | |
2490 | | // The class cannot be generic. |
2491 | 99 | if (CD->isGenericContext()) { |
2492 | 6 | diagnose(attr->getLocation(), |
2493 | 6 | diag::attr_generic_ApplicationMain_not_supported, |
2494 | 6 | applicationMainKind); |
2495 | 6 | attr->setInvalid(); |
2496 | 6 | return; |
2497 | 6 | } |
2498 | | |
2499 | | // @XXApplicationMain classes must conform to the XXApplicationDelegate |
2500 | | // protocol. |
2501 | 93 | auto *SF = cast<SourceFile>(CD->getModuleScopeContext()); |
2502 | 93 | auto &C = SF->getASTContext(); |
2503 | | |
2504 | 93 | auto KitModule = C.getLoadedModule(Id_Kit); |
2505 | 93 | ProtocolDecl *ApplicationDelegateProto = nullptr; |
2506 | 93 | if (KitModule) { |
2507 | 93 | SmallVector<ValueDecl *, 1> decls; |
2508 | 93 | namelookup::lookupInModule(KitModule, Id_ApplicationDelegate, |
2509 | 93 | decls, NLKind::QualifiedLookup, |
2510 | 93 | namelookup::ResolutionKind::TypesOnly, |
2511 | 93 | SF, attr->getLocation(), |
2512 | 93 | NL_QualifiedDefault); |
2513 | 93 | if (decls.size() == 1) |
2514 | 93 | ApplicationDelegateProto = dyn_cast<ProtocolDecl>(decls[0]); |
2515 | 93 | } |
2516 | | |
2517 | 93 | if (!ApplicationDelegateProto || |
2518 | 93 | !TypeChecker::conformsToProtocol(CD->getDeclaredInterfaceType(), |
2519 | 93 | ApplicationDelegateProto, |
2520 | 93 | CD->getParentModule())) { |
2521 | 6 | diagnose(attr->getLocation(), |
2522 | 6 | diag::attr_ApplicationMain_not_ApplicationDelegate, |
2523 | 6 | applicationMainKind); |
2524 | 6 | attr->setInvalid(); |
2525 | 6 | } |
2526 | | |
2527 | 93 | diagnose(attr->getLocation(), |
2528 | 93 | diag::attr_ApplicationMain_deprecated, |
2529 | 93 | applicationMainKind) |
2530 | 93 | .warnUntilSwiftVersion(6); |
2531 | | |
2532 | 93 | diagnose(attr->getLocation(), |
2533 | 93 | diag::attr_ApplicationMain_deprecated_use_attr_main) |
2534 | 93 | .fixItReplace(attr->getRange(), "@main"); |
2535 | | |
2536 | | |
2537 | 93 | if (attr->isInvalid()) |
2538 | 6 | return; |
2539 | | |
2540 | | // Register the class as the main class in the module. If there are multiples |
2541 | | // they will be diagnosed. |
2542 | 87 | if (SF->registerMainDecl(CD, attr->getLocation())) |
2543 | 27 | attr->setInvalid(); |
2544 | 87 | } |
2545 | | |
2546 | 69 | void AttributeChecker::visitNSApplicationMainAttr(NSApplicationMainAttr *attr) { |
2547 | 69 | auto &C = D->getASTContext(); |
2548 | 69 | checkApplicationMainAttribute(attr, |
2549 | 69 | C.getIdentifier("NSApplicationDelegate"), |
2550 | 69 | C.getIdentifier("AppKit"), |
2551 | 69 | C.getIdentifier("NSApplicationMain")); |
2552 | 69 | } |
2553 | 30 | void AttributeChecker::visitUIApplicationMainAttr(UIApplicationMainAttr *attr) { |
2554 | 30 | auto &C = D->getASTContext(); |
2555 | 30 | checkApplicationMainAttribute(attr, |
2556 | 30 | C.getIdentifier("UIApplicationDelegate"), |
2557 | 30 | C.getIdentifier("UIKit"), |
2558 | 30 | C.getIdentifier("UIApplicationMain")); |
2559 | 30 | } |
2560 | | |
2561 | | namespace { |
2562 | | struct MainTypeAttrParams { |
2563 | | FuncDecl *mainFunction; |
2564 | | MainTypeAttr *attr; |
2565 | | }; |
2566 | | |
2567 | | } |
2568 | | static std::pair<BraceStmt *, bool> |
2569 | 864 | synthesizeMainBody(AbstractFunctionDecl *fn, void *arg) { |
2570 | 864 | ASTContext &context = fn->getASTContext(); |
2571 | 864 | MainTypeAttrParams *params = (MainTypeAttrParams *) arg; |
2572 | | |
2573 | 864 | FuncDecl *mainFunction = params->mainFunction; |
2574 | 864 | auto location = params->attr->getLocation(); |
2575 | 864 | NominalTypeDecl *nominal = fn->getDeclContext()->getSelfNominalTypeDecl(); |
2576 | | |
2577 | 864 | auto *typeExpr = TypeExpr::createImplicit(nominal->getDeclaredType(), context); |
2578 | | |
2579 | 864 | SubstitutionMap substitutionMap; |
2580 | 864 | if (auto *environment = mainFunction->getGenericEnvironment()) { |
2581 | 27 | substitutionMap = SubstitutionMap::get( |
2582 | 27 | environment->getGenericSignature(), |
2583 | 54 | [&](SubstitutableType *type) { return nominal->getDeclaredType(); }, |
2584 | 27 | LookUpConformanceInModule(nominal->getModuleContext())); |
2585 | 837 | } else { |
2586 | 837 | substitutionMap = SubstitutionMap(); |
2587 | 837 | } |
2588 | | |
2589 | 864 | auto funcDeclRef = ConcreteDeclRef(mainFunction, substitutionMap); |
2590 | | |
2591 | 864 | auto *memberRefExpr = new (context) MemberRefExpr( |
2592 | 864 | typeExpr, SourceLoc(), funcDeclRef, DeclNameLoc(location), |
2593 | 864 | /*Implicit*/ true); |
2594 | 864 | memberRefExpr->setImplicit(true); |
2595 | | |
2596 | 864 | auto *callExpr = CallExpr::createImplicitEmpty(context, memberRefExpr); |
2597 | 864 | callExpr->setImplicit(true); |
2598 | 864 | callExpr->setType(context.TheEmptyTupleType); |
2599 | | |
2600 | 864 | Expr *returnedExpr; |
2601 | | |
2602 | 864 | if (mainFunction->hasAsync()) { |
2603 | | // Ensure that the concurrency module is loaded |
2604 | 507 | auto *concurrencyModule = context.getLoadedModule(context.Id_Concurrency); |
2605 | 507 | if (!concurrencyModule) { |
2606 | 6 | context.Diags.diagnose(mainFunction->getAsyncLoc(), |
2607 | 6 | diag::async_main_no_concurrency); |
2608 | 6 | auto result = new (context) ErrorExpr(mainFunction->getSourceRange()); |
2609 | 6 | ASTNode stmts[] = {result}; |
2610 | 6 | auto body = BraceStmt::create(context, SourceLoc(), stmts, SourceLoc(), |
2611 | 6 | /*Implicit*/ true); |
2612 | 6 | return std::make_pair(body, /*typechecked*/true); |
2613 | 6 | } |
2614 | | |
2615 | | // $main() async { await main() } |
2616 | 501 | Expr *awaitExpr = |
2617 | 501 | new (context) AwaitExpr(callExpr->getLoc(), callExpr, |
2618 | 501 | context.TheEmptyTupleType, /*implicit*/ true); |
2619 | 501 | if (mainFunction->hasThrows()) { |
2620 | | // $main() async throws { try await main() } |
2621 | 24 | awaitExpr = |
2622 | 24 | new (context) TryExpr(callExpr->getLoc(), awaitExpr, |
2623 | 24 | context.TheEmptyTupleType, /*implicit*/ true); |
2624 | 24 | } |
2625 | 501 | returnedExpr = awaitExpr; |
2626 | 501 | } else if (mainFunction->hasThrows()) { |
2627 | 36 | auto *tryExpr = new (context) TryExpr( |
2628 | 36 | callExpr->getLoc(), callExpr, context.TheEmptyTupleType, /*implicit=*/true); |
2629 | 36 | returnedExpr = tryExpr; |
2630 | 321 | } else { |
2631 | 321 | returnedExpr = callExpr; |
2632 | 321 | } |
2633 | | |
2634 | 858 | auto *returnStmt = |
2635 | 858 | new (context) ReturnStmt(SourceLoc(), returnedExpr, /*Implicit=*/true); |
2636 | | |
2637 | 858 | SmallVector<ASTNode, 1> stmts; |
2638 | 858 | stmts.push_back(returnStmt); |
2639 | 858 | auto *body = BraceStmt::create(context, SourceLoc(), stmts, |
2640 | 858 | SourceLoc(), /*Implicit*/true); |
2641 | | |
2642 | 858 | return std::make_pair(body, /*typechecked=*/false); |
2643 | 864 | } |
2644 | | |
2645 | | FuncDecl * |
2646 | | SynthesizeMainFunctionRequest::evaluate(Evaluator &evaluator, |
2647 | 291k | Decl *D) const { |
2648 | 291k | auto &context = D->getASTContext(); |
2649 | | |
2650 | 291k | MainTypeAttr *attr = D->getAttrs().getAttribute<MainTypeAttr>(); |
2651 | 291k | if (attr == nullptr) |
2652 | 290k | return nullptr; |
2653 | | |
2654 | 906 | auto *extension = dyn_cast<ExtensionDecl>(D); |
2655 | | |
2656 | 906 | IterableDeclContext *iterableDeclContext; |
2657 | 906 | DeclContext *declContext; |
2658 | 906 | NominalTypeDecl *nominal; |
2659 | 906 | SourceRange braces; |
2660 | | |
2661 | 906 | if (extension) { |
2662 | 57 | nominal = extension->getExtendedNominal(); |
2663 | 57 | iterableDeclContext = extension; |
2664 | 57 | declContext = extension; |
2665 | 57 | braces = extension->getBraces(); |
2666 | 849 | } else { |
2667 | 849 | nominal = dyn_cast<NominalTypeDecl>(D); |
2668 | 849 | iterableDeclContext = nominal; |
2669 | 849 | declContext = nominal; |
2670 | 849 | braces = nominal->getBraces(); |
2671 | 849 | } |
2672 | | |
2673 | 906 | assert(nominal && "Should have already recognized that the MainType decl " |
2674 | 906 | "isn't applicable to decls other than NominalTypeDecls"); |
2675 | 0 | assert(iterableDeclContext); |
2676 | 0 | assert(declContext); |
2677 | | |
2678 | | // The type cannot be generic. |
2679 | 906 | if (nominal->isGenericContext()) { |
2680 | 3 | context.Diags.diagnose(attr->getLocation(), |
2681 | 3 | diag::attr_generic_ApplicationMain_not_supported, 2); |
2682 | 3 | attr->setInvalid(); |
2683 | 3 | return nullptr; |
2684 | 3 | } |
2685 | | |
2686 | | // Create a function |
2687 | | // |
2688 | | // func $main() { |
2689 | | // return MainType.main() |
2690 | | // } |
2691 | | // |
2692 | | // to be called as the entry point. The advantage of setting up such a |
2693 | | // function is that we get full type-checking for mainType.main() as part of |
2694 | | // usual type-checking. The alternative would be to directly call |
2695 | | // mainType.main() from the entry point, and that would require fully |
2696 | | // type-checking the call to mainType.main(). |
2697 | 903 | using namespace constraints; |
2698 | 903 | ConstraintSystem CS(declContext, |
2699 | 903 | ConstraintSystemFlags::IgnoreAsyncSyncMismatch); |
2700 | 903 | ConstraintLocator *locator = |
2701 | 903 | CS.getConstraintLocator({}, ConstraintLocator::Member); |
2702 | | // Allowed main function types |
2703 | | // `() -> Void` |
2704 | | // `() async -> Void` |
2705 | | // `() throws -> Void` |
2706 | | // `() async throws -> Void` |
2707 | | // `@MainActor () -> Void` |
2708 | | // `@MainActor () async -> Void` |
2709 | | // `@MainActor () throws -> Void` |
2710 | | // `@MainActor () async throws -> Void` |
2711 | 903 | { |
2712 | 903 | llvm::SmallVector<Type, 8> mainTypes = { |
2713 | | |
2714 | 903 | FunctionType::get(/*params*/ {}, context.TheEmptyTupleType, |
2715 | 903 | ASTExtInfo()), |
2716 | 903 | FunctionType::get( |
2717 | 903 | /*params*/ {}, context.TheEmptyTupleType, |
2718 | 903 | ASTExtInfoBuilder().withAsync().build()), |
2719 | | |
2720 | 903 | FunctionType::get(/*params*/ {}, context.TheEmptyTupleType, |
2721 | 903 | ASTExtInfoBuilder().withThrows().build()), |
2722 | | |
2723 | 903 | FunctionType::get( |
2724 | 903 | /*params*/ {}, context.TheEmptyTupleType, |
2725 | 903 | ASTExtInfoBuilder().withAsync().withThrows().build())}; |
2726 | | |
2727 | 903 | Type mainActor = context.getMainActorType(); |
2728 | 903 | if (mainActor) { |
2729 | 780 | mainTypes.push_back(FunctionType::get( |
2730 | 780 | /*params*/ {}, context.TheEmptyTupleType, |
2731 | 780 | ASTExtInfoBuilder().withGlobalActor(mainActor).build())); |
2732 | 780 | mainTypes.push_back(FunctionType::get( |
2733 | 780 | /*params*/ {}, context.TheEmptyTupleType, |
2734 | 780 | ASTExtInfoBuilder().withAsync().withGlobalActor(mainActor).build())); |
2735 | 780 | mainTypes.push_back(FunctionType::get( |
2736 | 780 | /*params*/ {}, context.TheEmptyTupleType, |
2737 | 780 | ASTExtInfoBuilder().withThrows().withGlobalActor(mainActor).build())); |
2738 | 780 | mainTypes.push_back(FunctionType::get(/*params*/ {}, |
2739 | 780 | context.TheEmptyTupleType, |
2740 | 780 | ASTExtInfoBuilder() |
2741 | 780 | .withAsync() |
2742 | 780 | .withThrows() |
2743 | 780 | .withGlobalActor(mainActor) |
2744 | 780 | .build())); |
2745 | 780 | } |
2746 | 903 | TypeVariableType *mainType = |
2747 | 903 | CS.createTypeVariable(locator, /*options=*/0); |
2748 | 903 | llvm::SmallVector<Constraint *, 4> typeEqualityConstraints; |
2749 | 903 | typeEqualityConstraints.reserve(mainTypes.size()); |
2750 | 6.73k | for (const Type &candidateMainType : mainTypes) { |
2751 | 6.73k | typeEqualityConstraints.push_back( |
2752 | 6.73k | Constraint::create(CS, ConstraintKind::Equal, Type(mainType), |
2753 | 6.73k | candidateMainType, locator)); |
2754 | 6.73k | } |
2755 | | |
2756 | 903 | CS.addDisjunctionConstraint(typeEqualityConstraints, locator); |
2757 | 903 | CS.addValueMemberConstraint( |
2758 | 903 | nominal->getInterfaceType(), DeclNameRef(context.Id_main), |
2759 | 903 | Type(mainType), declContext, FunctionRefKind::SingleApply, {}, locator); |
2760 | 903 | } |
2761 | | |
2762 | 903 | FuncDecl *mainFunction = nullptr; |
2763 | 903 | llvm::SmallVector<Solution, 4> candidates; |
2764 | | |
2765 | 903 | if (!CS.solve(candidates, FreeTypeVariableBinding::Disallow)) { |
2766 | | // We can't use CS.diagnoseAmbiguity directly since the locator is empty |
2767 | | // Sticking the main type decl `D` in results in an assert due to a |
2768 | | // unsimplifiable locator anchor since it appears to be looking for an |
2769 | | // expression, which we don't have. |
2770 | | // (locator could not be simplified to anchor) |
2771 | | // TODO: emit notes for each of the ambiguous candidates |
2772 | 876 | if (candidates.size() != 1) { |
2773 | 6 | context.Diags.diagnose(nominal->getLoc(), diag::ambiguous_decl_ref, |
2774 | 6 | DeclNameRef(context.Id_main)); |
2775 | 6 | attr->setInvalid(); |
2776 | 6 | return nullptr; |
2777 | 6 | } |
2778 | 870 | mainFunction = dyn_cast<FuncDecl>( |
2779 | 870 | candidates[0].overloadChoices[locator].choice.getDecl()); |
2780 | 870 | } |
2781 | | |
2782 | 897 | if (!mainFunction) { |
2783 | 30 | const bool hasAsyncSupport = |
2784 | 30 | AvailabilityContext::forDeploymentTarget(context).isContainedIn( |
2785 | 30 | context.getBackDeployedConcurrencyAvailability()); |
2786 | 30 | context.Diags.diagnose(attr->getLocation(), |
2787 | 30 | diag::attr_MainType_without_main, |
2788 | 30 | nominal, hasAsyncSupport); |
2789 | 30 | attr->setInvalid(); |
2790 | 30 | return nullptr; |
2791 | 30 | } |
2792 | | |
2793 | 867 | auto where = ExportContext::forDeclSignature(D); |
2794 | 867 | diagnoseDeclAvailability(mainFunction, attr->getRange(), nullptr, where, |
2795 | 867 | llvm::None); |
2796 | | |
2797 | 867 | if (mainFunction->hasAsync() && |
2798 | 867 | context.LangOpts.isConcurrencyModelTaskToThread() && |
2799 | 867 | !AvailableAttr::isUnavailable(mainFunction)) { |
2800 | 0 | mainFunction->diagnose(diag::concurrency_task_to_thread_model_async_main, |
2801 | 0 | "task-to-thread concurrency model"); |
2802 | 0 | return nullptr; |
2803 | 0 | } |
2804 | | |
2805 | 867 | auto *const func = FuncDecl::createImplicit( |
2806 | 867 | context, StaticSpellingKind::KeywordStatic, |
2807 | 867 | DeclName(context, DeclBaseName(context.Id_MainEntryPoint), |
2808 | 867 | ParameterList::createEmpty(context)), |
2809 | 867 | /*NameLoc=*/SourceLoc(), |
2810 | 867 | /*Async=*/mainFunction->hasAsync(), |
2811 | 867 | /*Throws=*/mainFunction->hasThrows(), |
2812 | 867 | mainFunction->getThrownInterfaceType(), |
2813 | 867 | /*GenericParams=*/nullptr, ParameterList::createEmpty(context), |
2814 | 867 | /*FnRetType=*/TupleType::getEmpty(context), declContext); |
2815 | 867 | func->setSynthesized(true); |
2816 | | // It's never useful to provide a dynamic replacement of this function--it is |
2817 | | // just a pass-through to MainType.main. |
2818 | 867 | func->setIsDynamic(false); |
2819 | | |
2820 | 867 | auto *params = context.Allocate<MainTypeAttrParams>(); |
2821 | 867 | params->mainFunction = mainFunction; |
2822 | 867 | params->attr = attr; |
2823 | 867 | func->setBodySynthesizer(synthesizeMainBody, params); |
2824 | | |
2825 | 867 | iterableDeclContext->addMember(func); |
2826 | | |
2827 | 867 | return func; |
2828 | 867 | } |
2829 | | |
2830 | 906 | void AttributeChecker::visitMainTypeAttr(MainTypeAttr *attr) { |
2831 | 906 | auto &context = D->getASTContext(); |
2832 | | |
2833 | 906 | SourceFile *file = D->getDeclContext()->getParentSourceFile(); |
2834 | 906 | assert(file); |
2835 | | |
2836 | 0 | auto *func = evaluateOrDefault(context.evaluator, |
2837 | 906 | SynthesizeMainFunctionRequest{D}, |
2838 | 906 | nullptr); |
2839 | | |
2840 | 906 | if (!func) |
2841 | 39 | return; |
2842 | | |
2843 | | // Register the func as the main decl in the module. If there are multiples |
2844 | | // they will be diagnosed. |
2845 | 867 | if (file->registerMainDecl(func, attr->getLocation())) |
2846 | 15 | attr->setInvalid(); |
2847 | 867 | } |
2848 | | |
2849 | | /// Determine whether the given context is an extension to an Objective-C class |
2850 | | /// where the class is defined in the Objective-C module and the extension is |
2851 | | /// defined within its module. |
2852 | 324 | static bool isObjCClassExtensionInOverlay(DeclContext *dc) { |
2853 | | // Check whether we have an extension. |
2854 | 324 | auto ext = dyn_cast<ExtensionDecl>(dc); |
2855 | 324 | if (!ext) |
2856 | 0 | return false; |
2857 | | |
2858 | | // Find the extended class. |
2859 | 324 | auto classDecl = ext->getSelfClassDecl(); |
2860 | 324 | if (!classDecl) |
2861 | 0 | return false; |
2862 | | |
2863 | 324 | auto clangLoader = dc->getASTContext().getClangModuleLoader(); |
2864 | 324 | if (!clangLoader) return false; |
2865 | 324 | return clangLoader->isInOverlayModuleForImportedModule(ext, classDecl); |
2866 | 324 | } |
2867 | | |
2868 | 2.85k | void AttributeChecker::visitRequiredAttr(RequiredAttr *attr) { |
2869 | | // The required attribute only applies to constructors. |
2870 | 2.85k | auto ctor = cast<ConstructorDecl>(D); |
2871 | 2.85k | auto parentTy = ctor->getDeclContext()->getDeclaredInterfaceType(); |
2872 | 2.85k | if (!parentTy) { |
2873 | | // Constructor outside of nominal type context; we've already complained |
2874 | | // elsewhere. |
2875 | 0 | attr->setInvalid(); |
2876 | 0 | return; |
2877 | 0 | } |
2878 | | // Only classes can have required constructors. |
2879 | 2.85k | if (parentTy->getClassOrBoundGenericClass() && |
2880 | 2.85k | !parentTy->getClassOrBoundGenericClass()->isActor()) { |
2881 | | // The constructor must be declared within the class itself. |
2882 | | // FIXME: Allow an SDK overlay to add a required initializer to a class |
2883 | | // defined in Objective-C |
2884 | 2.84k | if (!isa<ClassDecl>(ctor->getDeclContext()->getImplementedObjCContext()) && |
2885 | 2.84k | !isObjCClassExtensionInOverlay(ctor->getDeclContext())) { |
2886 | 3 | diagnose(ctor, diag::required_initializer_in_extension, parentTy) |
2887 | 3 | .highlight(attr->getLocation()); |
2888 | 3 | attr->setInvalid(); |
2889 | 3 | return; |
2890 | 3 | } |
2891 | 2.84k | } else { |
2892 | 9 | if (!parentTy->hasError()) { |
2893 | 9 | diagnose(ctor, diag::required_initializer_nonclass, parentTy) |
2894 | 9 | .highlight(attr->getLocation()); |
2895 | 9 | } |
2896 | 9 | attr->setInvalid(); |
2897 | 9 | return; |
2898 | 9 | } |
2899 | 2.85k | } |
2900 | | |
2901 | 8.58k | void AttributeChecker::visitRethrowsAttr(RethrowsAttr *attr) { |
2902 | | // Make sure the function takes a 'throws' function argument or a |
2903 | | // conformance to a '@rethrows' protocol. |
2904 | 8.58k | auto fn = dyn_cast<AbstractFunctionDecl>(D); |
2905 | 8.58k | if (fn->getPolymorphicEffectKind(EffectKind::Throws) |
2906 | 8.58k | != PolymorphicEffectKind::Invalid) { |
2907 | 8.56k | return; |
2908 | 8.56k | } |
2909 | | |
2910 | 15 | diagnose(attr->getLocation(), diag::rethrows_without_throwing_parameter); |
2911 | 15 | attr->setInvalid(); |
2912 | 15 | } |
2913 | | |
2914 | | /// Ensure that the requirements provided by the @_specialize attribute |
2915 | | /// can be supported by the SIL EagerSpecializer pass. |
2916 | | static void checkSpecializeAttrRequirements(SpecializeAttr *attr, |
2917 | | GenericSignature originalSig, |
2918 | | GenericSignature specializedSig, |
2919 | 6.51k | ASTContext &ctx) { |
2920 | 6.51k | bool hadError = false; |
2921 | | |
2922 | 6.51k | auto specializedReqs = specializedSig.requirementsNotSatisfiedBy(originalSig); |
2923 | 7.21k | for (auto specializedReq : specializedReqs) { |
2924 | 7.21k | if (!specializedReq.getFirstType()->is<GenericTypeParamType>()) { |
2925 | 6 | ctx.Diags.diagnose(attr->getLocation(), |
2926 | 6 | diag::specialize_attr_only_generic_param_req); |
2927 | 6 | hadError = true; |
2928 | 6 | continue; |
2929 | 6 | } |
2930 | | |
2931 | 7.21k | switch (specializedReq.getKind()) { |
2932 | 0 | case RequirementKind::SameShape: |
2933 | 0 | llvm_unreachable("Same-shape requirement not supported here"); |
2934 | |
|
2935 | 12 | case RequirementKind::Conformance: |
2936 | 18 | case RequirementKind::Superclass: |
2937 | 18 | ctx.Diags.diagnose(attr->getLocation(), |
2938 | 18 | diag::specialize_attr_unsupported_kind_of_req); |
2939 | 18 | hadError = true; |
2940 | 18 | break; |
2941 | | |
2942 | 6.55k | case RequirementKind::SameType: |
2943 | 6.55k | if (specializedReq.getSecondType()->isTypeParameter()) { |
2944 | 0 | ctx.Diags.diagnose(attr->getLocation(), |
2945 | 0 | diag::specialize_attr_non_concrete_same_type_req); |
2946 | 0 | hadError = true; |
2947 | 0 | } |
2948 | 6.55k | break; |
2949 | | |
2950 | 642 | case RequirementKind::Layout: |
2951 | 642 | break; |
2952 | 7.21k | } |
2953 | 7.21k | } |
2954 | | |
2955 | 6.51k | if (hadError) |
2956 | 24 | return; |
2957 | | |
2958 | 6.48k | if (!attr->isFullSpecialization()) |
2959 | 42 | return; |
2960 | | |
2961 | 6.44k | if (specializedSig->areAllParamsConcrete()) |
2962 | 5.71k | return; |
2963 | | |
2964 | 729 | SmallVector<GenericTypeParamType *, 2> unspecializedParams; |
2965 | | |
2966 | 828 | for (auto *paramTy : specializedSig.getGenericParams()) { |
2967 | 828 | auto canTy = paramTy->getCanonicalType(); |
2968 | 828 | if (specializedSig->isReducedType(canTy) && |
2969 | 828 | (!specializedSig->getLayoutConstraint(canTy) || |
2970 | 774 | originalSig->getLayoutConstraint(canTy))) { |
2971 | 132 | unspecializedParams.push_back(paramTy); |
2972 | 132 | } |
2973 | 828 | } |
2974 | | |
2975 | 729 | unsigned expectedCount = specializedSig.getGenericParams().size(); |
2976 | 729 | unsigned gotCount = expectedCount - unspecializedParams.size(); |
2977 | | |
2978 | 729 | if (expectedCount == gotCount) |
2979 | 609 | return; |
2980 | | |
2981 | 120 | ctx.Diags.diagnose( |
2982 | 120 | attr->getLocation(), diag::specialize_attr_type_parameter_count_mismatch, |
2983 | 120 | gotCount, expectedCount); |
2984 | | |
2985 | 132 | for (auto paramTy : unspecializedParams) { |
2986 | 132 | ctx.Diags.diagnose(attr->getLocation(), |
2987 | 132 | diag::specialize_attr_missing_constraint, |
2988 | 132 | paramTy->getName()); |
2989 | 132 | } |
2990 | 120 | } |
2991 | | |
2992 | | /// Type check that a set of requirements provided by @_specialize. |
2993 | | /// Store the set of requirements in the attribute. |
2994 | 6.50k | void AttributeChecker::visitSpecializeAttr(SpecializeAttr *attr) { |
2995 | 6.50k | auto *FD = cast<AbstractFunctionDecl>(D); |
2996 | 6.50k | auto genericSig = FD->getGenericSignature(); |
2997 | 6.50k | auto *trailingWhereClause = attr->getTrailingWhereClause(); |
2998 | | |
2999 | 6.50k | if (!trailingWhereClause) { |
3000 | | // Report a missing "where" clause. |
3001 | 0 | diagnose(attr->getLocation(), diag::specialize_missing_where_clause); |
3002 | 0 | return; |
3003 | 0 | } |
3004 | | |
3005 | 6.50k | if (trailingWhereClause->getRequirements().empty()) { |
3006 | | // Report an empty "where" clause. |
3007 | 0 | diagnose(attr->getLocation(), diag::specialize_empty_where_clause); |
3008 | 0 | return; |
3009 | 0 | } |
3010 | | |
3011 | 6.50k | if (!genericSig) { |
3012 | | // Only generic functions are permitted to have trailing where clauses. |
3013 | 12 | diagnose(attr->getLocation(), |
3014 | 12 | diag::specialize_attr_nongeneric_trailing_where, FD->getName()) |
3015 | 12 | .highlight(trailingWhereClause->getSourceRange()); |
3016 | 12 | return; |
3017 | 12 | } |
3018 | | |
3019 | 6.49k | (void)attr->getSpecializedSignature(FD); |
3020 | 6.49k | } |
3021 | | |
3022 | | GenericSignature |
3023 | | SerializeAttrGenericSignatureRequest::evaluate(Evaluator &evaluator, |
3024 | | const AbstractFunctionDecl *FD, |
3025 | 6.51k | SpecializeAttr *attr) const { |
3026 | 6.51k | if (attr->specializedSignature) |
3027 | 0 | return attr->specializedSignature; |
3028 | | |
3029 | 6.51k | auto &Ctx = FD->getASTContext(); |
3030 | 6.51k | auto genericSig = FD->getGenericSignature(); |
3031 | 6.51k | if (!genericSig) |
3032 | 6 | return nullptr; |
3033 | | |
3034 | 6.51k | InferredGenericSignatureRequest request{ |
3035 | 6.51k | genericSig.getPointer(), |
3036 | 6.51k | /*genericParams=*/nullptr, |
3037 | 6.51k | WhereClauseOwner(const_cast<AbstractFunctionDecl *>(FD), attr), |
3038 | 6.51k | /*addedRequirements=*/{}, |
3039 | 6.51k | /*inferenceSources=*/{}, |
3040 | 6.51k | /*allowConcreteGenericParams=*/true}; |
3041 | | |
3042 | 6.51k | auto specializedSig = evaluateOrDefault(Ctx.evaluator, request, |
3043 | 6.51k | GenericSignatureWithError()) |
3044 | 6.51k | .getPointer(); |
3045 | | |
3046 | | // Check the validity of provided requirements. |
3047 | 6.51k | checkSpecializeAttrRequirements(attr, genericSig, specializedSig, Ctx); |
3048 | | |
3049 | 6.51k | if (Ctx.LangOpts.hasFeature(Feature::LayoutPrespecialization)) { |
3050 | 6.23k | llvm::SmallVector<Type, 4> typeErasedParams; |
3051 | 6.91k | for (const auto &pair : llvm::zip(attr->getTrailingWhereClause()->getRequirements(), specializedSig.getRequirements())) { |
3052 | 6.91k | auto &reqRepr = std::get<0>(pair); |
3053 | 6.91k | auto &req = std::get<1>(pair); |
3054 | 6.91k | if (reqRepr.getKind() == RequirementReprKind::LayoutConstraint) { |
3055 | 591 | if (auto *attributedTy = dyn_cast<AttributedTypeRepr>(reqRepr.getSubjectRepr())) { |
3056 | 504 | if (attributedTy->getAttrs().has(TAK__noMetadata)) { |
3057 | 504 | typeErasedParams.push_back(req.getFirstType()); |
3058 | 504 | } |
3059 | 504 | } |
3060 | 591 | } |
3061 | 6.91k | } |
3062 | 6.23k | attr->setTypeErasedParams(typeErasedParams); |
3063 | 6.23k | } |
3064 | | |
3065 | | // Check the target function if there is one. |
3066 | 6.51k | attr->getTargetFunctionDecl(FD); |
3067 | | |
3068 | 6.51k | return specializedSig; |
3069 | 6.51k | } |
3070 | | |
3071 | | llvm::Optional<GenericSignature> |
3072 | 58.8k | SerializeAttrGenericSignatureRequest::getCachedResult() const { |
3073 | 58.8k | const auto &storage = getStorage(); |
3074 | 58.8k | SpecializeAttr *attr = std::get<1>(storage); |
3075 | 58.8k | if (auto signature = attr->specializedSignature) |
3076 | 52.3k | return signature; |
3077 | 6.51k | return llvm::None; |
3078 | 58.8k | } |
3079 | | |
3080 | | void SerializeAttrGenericSignatureRequest::cacheResult( |
3081 | 6.51k | GenericSignature signature) const { |
3082 | 6.51k | const auto &storage = getStorage(); |
3083 | 6.51k | SpecializeAttr *attr = std::get<1>(storage); |
3084 | 6.51k | attr->specializedSignature = signature; |
3085 | 6.51k | } |
3086 | | |
3087 | 1.50k | void AttributeChecker::visitFixedLayoutAttr(FixedLayoutAttr *attr) { |
3088 | 1.50k | if (isa<StructDecl>(D)) { |
3089 | 207 | diagnose(attr->getLocation(), diag::fixed_layout_struct) |
3090 | 207 | .fixItReplace(attr->getRange(), "@frozen"); |
3091 | 207 | } |
3092 | | |
3093 | 1.50k | auto *VD = cast<ValueDecl>(D); |
3094 | | |
3095 | 1.50k | if (VD->getFormalAccess() < AccessLevel::Public && |
3096 | 1.50k | !VD->getAttrs().hasAttribute<UsableFromInlineAttr>()) { |
3097 | 36 | diagnoseAndRemoveAttr(attr, diag::fixed_layout_attr_on_internal_type, |
3098 | 36 | VD->getName(), VD->getFormalAccess()); |
3099 | 36 | } |
3100 | 1.50k | } |
3101 | | |
3102 | 24.4k | void AttributeChecker::visitUsableFromInlineAttr(UsableFromInlineAttr *attr) { |
3103 | 24.4k | auto *VD = cast<ValueDecl>(D); |
3104 | | |
3105 | | // FIXME: Once protocols can contain nominal types, do we want to allow |
3106 | | // these nominal types to have access control (and also @usableFromInline)? |
3107 | 24.4k | if (isa<ProtocolDecl>(VD->getDeclContext())) { |
3108 | 24 | diagnoseAndRemoveAttr(attr, diag::usable_from_inline_attr_in_protocol); |
3109 | 24 | return; |
3110 | 24 | } |
3111 | | |
3112 | | // @usableFromInline can only be applied to internal or package declarations. |
3113 | 24.4k | if (VD->getFormalAccess() != AccessLevel::Internal && |
3114 | 24.4k | VD->getFormalAccess() != AccessLevel::Package) { |
3115 | 78 | diagnoseAndRemoveAttr(attr, |
3116 | 78 | diag::usable_from_inline_attr_with_explicit_access, |
3117 | 78 | VD->getName(), VD->getFormalAccess()); |
3118 | 78 | return; |
3119 | 78 | } |
3120 | | |
3121 | | // On internal declarations, @inlinable implies @usableFromInline. |
3122 | 24.3k | if (VD->getAttrs().hasAttribute<InlinableAttr>()) { |
3123 | 147 | if (Ctx.isSwiftVersionAtLeast(4,2)) |
3124 | 15 | diagnoseAndRemoveAttr(attr, diag::inlinable_implies_usable_from_inline, |
3125 | 15 | VD); |
3126 | 147 | return; |
3127 | 147 | } |
3128 | 24.3k | } |
3129 | | |
3130 | 64.8k | void AttributeChecker::visitInlinableAttr(InlinableAttr *attr) { |
3131 | | // @inlinable cannot be applied to stored properties. |
3132 | | // |
3133 | | // If the type is fixed-layout, the accessors are inlinable anyway; |
3134 | | // if the type is resilient, the accessors cannot be inlinable |
3135 | | // because clients cannot directly access storage. |
3136 | 64.8k | if (auto *VD = dyn_cast<VarDecl>(D)) { |
3137 | 11.5k | if (VD->hasStorage() || VD->getAttrs().hasAttribute<LazyAttr>()) { |
3138 | 36 | diagnoseAndRemoveAttr(attr, |
3139 | 36 | diag::attribute_invalid_on_stored_property, |
3140 | 36 | attr); |
3141 | 36 | return; |
3142 | 36 | } |
3143 | 11.5k | } |
3144 | | |
3145 | 64.8k | auto *VD = cast<ValueDecl>(D); |
3146 | | |
3147 | | // Calls to dynamically-dispatched declarations are never devirtualized, |
3148 | | // so marking them as @inlinable does not make sense. |
3149 | 64.8k | if (VD->isDynamic()) { |
3150 | 27 | diagnoseAndRemoveAttr(attr, diag::inlinable_dynamic_not_supported); |
3151 | 27 | return; |
3152 | 27 | } |
3153 | | |
3154 | | // @inlinable can only be applied to public or internal declarations. |
3155 | 64.7k | auto access = VD->getFormalAccess(); |
3156 | 64.7k | if (access < AccessLevel::Internal) { |
3157 | 24 | diagnoseAndRemoveAttr(attr, diag::inlinable_decl_not_public, |
3158 | 24 | VD->getBaseName(), |
3159 | 24 | access); |
3160 | 24 | return; |
3161 | 24 | } |
3162 | | |
3163 | | // @inlinable cannot be applied to deinitializers in resilient classes. |
3164 | 64.7k | if (auto *DD = dyn_cast<DestructorDecl>(D)) { |
3165 | 490 | if (auto *CD = dyn_cast<ClassDecl>(DD->getDeclContext())) { |
3166 | 490 | if (CD->isResilient()) { |
3167 | 3 | diagnoseAndRemoveAttr(attr, diag::inlinable_resilient_deinit); |
3168 | 3 | return; |
3169 | 3 | } |
3170 | 490 | } |
3171 | 490 | } |
3172 | 64.7k | } |
3173 | | |
3174 | 858 | void AttributeChecker::visitOptimizeAttr(OptimizeAttr *attr) { |
3175 | 858 | if (auto *VD = dyn_cast<VarDecl>(D)) { |
3176 | 66 | if (VD->hasStorage()) { |
3177 | 6 | diagnoseAndRemoveAttr(attr, |
3178 | 6 | diag::attribute_invalid_on_stored_property, |
3179 | 6 | attr); |
3180 | 6 | return; |
3181 | 6 | } |
3182 | 66 | } |
3183 | 858 | } |
3184 | | |
3185 | 111 | void AttributeChecker::visitExclusivityAttr(ExclusivityAttr *attr) { |
3186 | 111 | if (auto *varDecl = dyn_cast<VarDecl>(D)) { |
3187 | 111 | auto *DC = D->getDeclContext(); |
3188 | 111 | auto *parentSF = DC->getParentSourceFile(); |
3189 | | |
3190 | 111 | if (parentSF && parentSF->Kind != SourceFileKind::Interface) { |
3191 | 87 | if (!varDecl->hasStorage()) { |
3192 | 6 | diagnose(attr->getLocation(), diag::exclusivity_on_computed_property); |
3193 | 6 | attr->setInvalid(); |
3194 | 6 | return; |
3195 | 6 | } |
3196 | 87 | } |
3197 | | |
3198 | 105 | if (isa<ClassDecl>(DC)) |
3199 | 51 | return; |
3200 | | |
3201 | 54 | if (DC->isTypeContext() && !varDecl->isInstanceMember()) |
3202 | 21 | return; |
3203 | | |
3204 | 33 | if (DC->isModuleScopeContext()) |
3205 | 30 | return; |
3206 | 33 | } |
3207 | 3 | diagnoseAndRemoveAttr(attr, diag::exclusivity_on_wrong_decl); |
3208 | 3 | attr->setInvalid(); |
3209 | 3 | } |
3210 | | |
3211 | 3.34k | void AttributeChecker::visitDiscardableResultAttr(DiscardableResultAttr *attr) { |
3212 | 3.34k | if (auto *FD = dyn_cast<FuncDecl>(D)) { |
3213 | 3.23k | if (auto result = FD->getResultInterfaceType()) { |
3214 | 3.23k | auto resultIsVoid = result->isVoid(); |
3215 | 3.23k | if (resultIsVoid || result->isUninhabited()) { |
3216 | 6 | diagnoseAndRemoveAttr(attr, |
3217 | 6 | diag::discardable_result_on_void_never_function, |
3218 | 6 | resultIsVoid); |
3219 | 6 | } |
3220 | 3.23k | } |
3221 | 3.23k | } |
3222 | 3.34k | } |
3223 | | |
3224 | | /// Lookup the replaced decl in the replacements scope. |
3225 | | static void lookupReplacedDecl(DeclNameRef replacedDeclName, |
3226 | | const DeclAttribute *attr, |
3227 | | const ValueDecl *replacement, |
3228 | 4.06k | SmallVectorImpl<ValueDecl *> &results) { |
3229 | 4.06k | auto *declCtxt = replacement->getDeclContext(); |
3230 | | |
3231 | | // Hop up to the FileUnit if we're in top-level code |
3232 | 4.06k | if (auto *toplevel = dyn_cast<TopLevelCodeDecl>(declCtxt)) |
3233 | 3 | declCtxt = toplevel->getDeclContext(); |
3234 | | |
3235 | | // Look at the accessors' storage's context. |
3236 | 4.06k | if (auto *accessor = dyn_cast<AccessorDecl>(replacement)) { |
3237 | 1.22k | auto *storage = accessor->getStorage(); |
3238 | 1.22k | declCtxt = storage->getDeclContext(); |
3239 | 1.22k | } |
3240 | | |
3241 | 4.06k | auto *moduleScopeCtxt = declCtxt->getModuleScopeContext(); |
3242 | 4.06k | if (isa<FileUnit>(declCtxt)) { |
3243 | 630 | auto &ctx = declCtxt->getASTContext(); |
3244 | 630 | auto descriptor = UnqualifiedLookupDescriptor( |
3245 | 630 | replacedDeclName, moduleScopeCtxt, attr->getLocation()); |
3246 | 630 | auto lookup = evaluateOrDefault(ctx.evaluator, |
3247 | 630 | UnqualifiedLookupRequest{descriptor}, {}); |
3248 | 630 | for (auto entry : lookup) { |
3249 | 612 | results.push_back(entry.getValueDecl()); |
3250 | 612 | } |
3251 | 630 | return; |
3252 | 630 | } |
3253 | | |
3254 | 3.43k | assert(declCtxt->isTypeContext()); |
3255 | 0 | auto typeCtx = dyn_cast<NominalTypeDecl>(declCtxt->getAsDecl()); |
3256 | 3.43k | if (!typeCtx) |
3257 | 3.07k | typeCtx = cast<ExtensionDecl>(declCtxt->getAsDecl())->getExtendedNominal(); |
3258 | | |
3259 | 3.43k | auto options = NL_QualifiedDefault; |
3260 | 3.43k | if (declCtxt->isInSpecializeExtensionContext()) |
3261 | 1.36k | options |= NL_IncludeUsableFromInline; |
3262 | | |
3263 | 3.43k | if (typeCtx) |
3264 | 3.43k | moduleScopeCtxt->lookupQualified({typeCtx}, replacedDeclName, |
3265 | 3.43k | attr->getLocation(), options, |
3266 | 3.43k | results); |
3267 | 3.43k | } |
3268 | | |
3269 | | /// Remove any argument labels from the interface type of the given value that |
3270 | | /// are extraneous from the type system's point of view, producing the |
3271 | | /// type to compare against for the purposes of dynamic replacement. |
3272 | 2.49k | static Type getDynamicComparisonType(ValueDecl *value) { |
3273 | 2.49k | unsigned numArgumentLabels = 0; |
3274 | | |
3275 | 2.49k | if (isa<AbstractFunctionDecl>(value)) { |
3276 | 0 | ++numArgumentLabels; |
3277 | |
|
3278 | 0 | if (value->getDeclContext()->isTypeContext()) |
3279 | 0 | ++numArgumentLabels; |
3280 | 2.49k | } else if (isa<SubscriptDecl>(value)) { |
3281 | 1.16k | ++numArgumentLabels; |
3282 | 1.16k | } |
3283 | | |
3284 | 2.49k | auto interfaceType = value->getInterfaceType(); |
3285 | 2.49k | return interfaceType->removeArgumentLabels(numArgumentLabels); |
3286 | 2.49k | } |
3287 | | |
3288 | | static FuncDecl *findSimilarAccessor(DeclNameRef replacedVarName, |
3289 | | const AccessorDecl *replacement, |
3290 | | DeclAttribute *attr, ASTContext &ctx, |
3291 | 1.22k | bool forDynamicReplacement) { |
3292 | | |
3293 | | // Retrieve the replaced abstract storage decl. |
3294 | 1.22k | SmallVector<ValueDecl *, 4> results; |
3295 | 1.22k | lookupReplacedDecl(replacedVarName, attr, replacement, results); |
3296 | | |
3297 | | // Filter out any accessors that won't work. |
3298 | 1.22k | if (!results.empty()) { |
3299 | 1.22k | auto replacementStorage = replacement->getStorage(); |
3300 | 1.22k | Type replacementStorageType = getDynamicComparisonType(replacementStorage); |
3301 | 1.22k | results.erase(std::remove_if(results.begin(), results.end(), |
3302 | 1.27k | [&](ValueDecl *result) { |
3303 | | // Protocol requirements are not replaceable. |
3304 | 1.27k | if (isa<ProtocolDecl>(result->getDeclContext())) |
3305 | 6 | return true; |
3306 | | // Check for static/instance mismatch. |
3307 | 1.26k | if (result->isStatic() != replacementStorage->isStatic()) |
3308 | 3 | return true; |
3309 | | |
3310 | | // Check for type mismatch. |
3311 | 1.26k | auto resultType = getDynamicComparisonType(result); |
3312 | 1.26k | if (!resultType->isEqual(replacementStorageType) && |
3313 | 1.26k | !resultType->matches( |
3314 | 45 | replacementStorageType, |
3315 | 45 | TypeMatchFlags::AllowCompatibleOpaqueTypeArchetypes)) { |
3316 | 30 | return true; |
3317 | 30 | } |
3318 | | |
3319 | 1.23k | return false; |
3320 | 1.26k | }), |
3321 | 1.22k | results.end()); |
3322 | 1.22k | } |
3323 | | |
3324 | 1.22k | auto &Diags = ctx.Diags; |
3325 | 1.22k | if (results.empty()) { |
3326 | 0 | Diags.diagnose(attr->getLocation(), |
3327 | 0 | diag::dynamic_replacement_accessor_not_found, |
3328 | 0 | replacedVarName); |
3329 | 0 | attr->setInvalid(); |
3330 | 0 | return nullptr; |
3331 | 0 | } |
3332 | | |
3333 | 1.22k | if (results.size() > 1) { |
3334 | 6 | Diags.diagnose(attr->getLocation(), |
3335 | 6 | diag::dynamic_replacement_accessor_ambiguous, |
3336 | 6 | replacedVarName); |
3337 | 12 | for (auto result : results) { |
3338 | 12 | Diags.diagnose(result, |
3339 | 12 | diag::dynamic_replacement_accessor_ambiguous_candidate, |
3340 | 12 | result->getModuleContext()->getName()); |
3341 | 12 | } |
3342 | 6 | attr->setInvalid(); |
3343 | 6 | return nullptr; |
3344 | 6 | } |
3345 | | |
3346 | 1.22k | assert(!isa<FuncDecl>(results[0])); |
3347 | | |
3348 | 0 | auto *origStorage = cast<AbstractStorageDecl>(results[0]); |
3349 | 1.22k | if (forDynamicReplacement && !origStorage->isDynamic()) { |
3350 | 0 | Diags.diagnose(attr->getLocation(), |
3351 | 0 | diag::dynamic_replacement_accessor_not_dynamic, |
3352 | 0 | origStorage->getName()); |
3353 | 0 | attr->setInvalid(); |
3354 | 0 | return nullptr; |
3355 | 0 | } |
3356 | | |
3357 | | // Find the accessor in the replaced storage decl. |
3358 | 1.22k | auto *origAccessor = origStorage->getOpaqueAccessor( |
3359 | 1.22k | replacement->getAccessorKind()); |
3360 | 1.22k | if (!origAccessor) |
3361 | 0 | return nullptr; |
3362 | | |
3363 | 1.22k | if (origAccessor->isImplicit() && |
3364 | 1.22k | !(origStorage->getReadImpl() == ReadImplKind::Stored && |
3365 | 90 | origStorage->getWriteImpl() == WriteImplKind::Stored)) { |
3366 | 0 | Diags.diagnose(attr->getLocation(), |
3367 | 0 | diag::dynamic_replacement_accessor_not_explicit, |
3368 | 0 | (unsigned)origAccessor->getAccessorKind(), |
3369 | 0 | origStorage->getName()); |
3370 | 0 | attr->setInvalid(); |
3371 | 0 | return nullptr; |
3372 | 0 | } |
3373 | | |
3374 | 1.22k | return origAccessor; |
3375 | 1.22k | } |
3376 | | |
3377 | | static FuncDecl *findReplacedAccessor(DeclNameRef replacedVarName, |
3378 | | const AccessorDecl *replacement, |
3379 | | DeclAttribute *attr, |
3380 | 453 | ASTContext &ctx) { |
3381 | 453 | return findSimilarAccessor(replacedVarName, replacement, attr, ctx, |
3382 | 453 | /*forDynamicReplacement*/ true); |
3383 | 453 | } |
3384 | | |
3385 | | static FuncDecl *findTargetAccessor(DeclNameRef replacedVarName, |
3386 | | const AccessorDecl *replacement, |
3387 | | DeclAttribute *attr, |
3388 | 774 | ASTContext &ctx) { |
3389 | 774 | return findSimilarAccessor(replacedVarName, replacement, attr, ctx, |
3390 | 774 | /*forDynamicReplacement*/ false); |
3391 | 774 | } |
3392 | | |
3393 | | static AbstractFunctionDecl * |
3394 | | findSimilarFunction(DeclNameRef replacedFunctionName, |
3395 | | const AbstractFunctionDecl *base, DeclAttribute *attr, |
3396 | 1.65k | DiagnosticEngine *Diags, bool forDynamicReplacement) { |
3397 | | |
3398 | | // Note: we might pass a constant attribute when typechecker is nullptr. |
3399 | | // Any modification to attr must be guarded by a null check on TC. |
3400 | | // |
3401 | 1.65k | SmallVector<ValueDecl *, 4> results; |
3402 | 1.65k | lookupReplacedDecl(replacedFunctionName, attr, base, results); |
3403 | | |
3404 | 1.65k | for (auto *result : results) { |
3405 | | // Protocol requirements are not replaceable. |
3406 | 1.65k | if (isa<ProtocolDecl>(result->getDeclContext())) |
3407 | 3 | continue; |
3408 | | // Check for static/instance mismatch. |
3409 | 1.65k | if (result->isStatic() != base->isStatic()) |
3410 | 0 | continue; |
3411 | | |
3412 | 1.65k | auto resultTy = result->getInterfaceType(); |
3413 | 1.65k | auto replaceTy = base->getInterfaceType(); |
3414 | 1.65k | TypeMatchOptions matchMode = TypeMatchFlags::AllowABICompatible; |
3415 | 1.65k | matchMode |= TypeMatchFlags::AllowCompatibleOpaqueTypeArchetypes; |
3416 | 1.65k | if (resultTy->matches(replaceTy, matchMode)) { |
3417 | 1.64k | if (forDynamicReplacement && !result->isDynamic()) { |
3418 | 0 | if (Diags) { |
3419 | 0 | Diags->diagnose(attr->getLocation(), |
3420 | 0 | diag::dynamic_replacement_function_not_dynamic, |
3421 | 0 | result->getName()); |
3422 | 0 | attr->setInvalid(); |
3423 | 0 | } |
3424 | 0 | return nullptr; |
3425 | 0 | } |
3426 | 1.64k | return cast<AbstractFunctionDecl>(result); |
3427 | 1.64k | } |
3428 | 1.65k | } |
3429 | | |
3430 | 6 | if (!Diags) |
3431 | 0 | return nullptr; |
3432 | | |
3433 | 6 | if (results.empty()) { |
3434 | 6 | Diags->diagnose(attr->getLocation(), |
3435 | 6 | forDynamicReplacement |
3436 | 6 | ? diag::dynamic_replacement_function_not_found |
3437 | 6 | : diag::specialize_target_function_not_found, |
3438 | 6 | replacedFunctionName); |
3439 | 6 | } else { |
3440 | 0 | Diags->diagnose(attr->getLocation(), |
3441 | 0 | forDynamicReplacement |
3442 | 0 | ? diag::dynamic_replacement_function_of_type_not_found |
3443 | 0 | : diag::specialize_target_function_of_type_not_found, |
3444 | 0 | replacedFunctionName, |
3445 | 0 | base->getInterfaceType()->getCanonicalType()); |
3446 | |
|
3447 | 0 | for (auto *result : results) { |
3448 | 0 | Diags->diagnose(SourceLoc(), |
3449 | 0 | forDynamicReplacement |
3450 | 0 | ? diag::dynamic_replacement_found_function_of_type |
3451 | 0 | : diag::specialize_found_function_of_type, |
3452 | 0 | result->getName(), |
3453 | 0 | result->getInterfaceType()->getCanonicalType()); |
3454 | 0 | } |
3455 | 0 | } |
3456 | 6 | attr->setInvalid(); |
3457 | 6 | return nullptr; |
3458 | 6 | } |
3459 | | |
3460 | | static AbstractFunctionDecl * |
3461 | | findReplacedFunction(DeclNameRef replacedFunctionName, |
3462 | | const AbstractFunctionDecl *replacement, |
3463 | 903 | DynamicReplacementAttr *attr, DiagnosticEngine *Diags) { |
3464 | 903 | return findSimilarFunction(replacedFunctionName, replacement, attr, Diags, |
3465 | 903 | true /*forDynamicReplacement*/); |
3466 | 903 | } |
3467 | | |
3468 | | static AbstractFunctionDecl * |
3469 | | findTargetFunction(DeclNameRef targetFunctionName, |
3470 | | const AbstractFunctionDecl *base, |
3471 | 750 | SpecializeAttr * attr, DiagnosticEngine *diags) { |
3472 | 750 | return findSimilarFunction(targetFunctionName, base, attr, diags, |
3473 | 750 | false /*forDynamicReplacement*/); |
3474 | 750 | } |
3475 | | |
3476 | | static AbstractStorageDecl * |
3477 | | findReplacedStorageDecl(DeclNameRef replacedFunctionName, |
3478 | | const AbstractStorageDecl *replacement, |
3479 | 312 | const DynamicReplacementAttr *attr) { |
3480 | | |
3481 | 312 | SmallVector<ValueDecl *, 4> results; |
3482 | 312 | lookupReplacedDecl(replacedFunctionName, attr, replacement, results); |
3483 | | |
3484 | 327 | for (auto *result : results) { |
3485 | | // Check for static/instance mismatch. |
3486 | 327 | if (result->isStatic() != replacement->isStatic()) |
3487 | 0 | continue; |
3488 | 327 | auto resultTy = result->getInterfaceType(); |
3489 | 327 | auto replaceTy = replacement->getInterfaceType(); |
3490 | 327 | TypeMatchOptions matchMode = TypeMatchFlags::AllowABICompatible; |
3491 | 327 | matchMode |= TypeMatchFlags::AllowCompatibleOpaqueTypeArchetypes; |
3492 | 327 | if (resultTy->matches(replaceTy, matchMode)) { |
3493 | 312 | if (!result->isDynamic()) { |
3494 | 0 | return nullptr; |
3495 | 0 | } |
3496 | 312 | return cast<AbstractStorageDecl>(result); |
3497 | 312 | } |
3498 | 327 | } |
3499 | 0 | return nullptr; |
3500 | 312 | } |
3501 | | |
3502 | 1.21k | void AttributeChecker::visitDynamicReplacementAttr(DynamicReplacementAttr *attr) { |
3503 | 1.21k | assert(isa<AbstractFunctionDecl>(D) || isa<AbstractStorageDecl>(D)); |
3504 | 0 | auto *replacement = cast<ValueDecl>(D); |
3505 | | |
3506 | 1.21k | if (!isa<ExtensionDecl>(replacement->getDeclContext()) && |
3507 | 1.21k | !replacement->getDeclContext()->isModuleScopeContext()) { |
3508 | 0 | diagnose(attr->getLocation(), diag::dynamic_replacement_not_in_extension, |
3509 | 0 | replacement->getBaseName()); |
3510 | 0 | attr->setInvalid(); |
3511 | 0 | return; |
3512 | 0 | } |
3513 | | |
3514 | 1.21k | if (replacement->shouldUseNativeDynamicDispatch()) { |
3515 | 0 | diagnose(attr->getLocation(), diag::dynamic_replacement_must_not_be_dynamic, |
3516 | 0 | replacement->getBaseName()); |
3517 | 0 | attr->setInvalid(); |
3518 | 0 | return; |
3519 | 0 | } |
3520 | | |
3521 | 1.21k | auto *original = replacement->getDynamicallyReplacedDecl(); |
3522 | 1.21k | if (!original) { |
3523 | 0 | attr->setInvalid(); |
3524 | 0 | return; |
3525 | 0 | } |
3526 | | |
3527 | 1.21k | if (original->isObjC() && !replacement->isObjC()) { |
3528 | 0 | diagnose(attr->getLocation(), |
3529 | 0 | diag::dynamic_replacement_replacement_not_objc_dynamic, |
3530 | 0 | replacement->getName()); |
3531 | 0 | attr->setInvalid(); |
3532 | 0 | } |
3533 | 1.21k | if (!original->isObjC() && replacement->isObjC()) { |
3534 | 0 | diagnose(attr->getLocation(), |
3535 | 0 | diag::dynamic_replacement_replaced_not_objc_dynamic, |
3536 | 0 | original->getName()); |
3537 | 0 | attr->setInvalid(); |
3538 | 0 | } |
3539 | | |
3540 | 1.21k | if (auto *CD = dyn_cast<ConstructorDecl>(replacement)) { |
3541 | 207 | auto *attr = CD->getAttrs().getAttribute<DynamicReplacementAttr>(); |
3542 | 207 | auto replacedIsConvenienceInit = |
3543 | 207 | cast<ConstructorDecl>(original)->isConvenienceInit(); |
3544 | 207 | if (replacedIsConvenienceInit &&!CD->isConvenienceInit()) { |
3545 | 3 | diagnose(attr->getLocation(), |
3546 | 3 | diag::dynamic_replacement_replaced_constructor_is_convenience, |
3547 | 3 | attr->getReplacedFunctionName()); |
3548 | 204 | } else if (!replacedIsConvenienceInit && CD->isConvenienceInit()) { |
3549 | 3 | diagnose( |
3550 | 3 | attr->getLocation(), |
3551 | 3 | diag::dynamic_replacement_replaced_constructor_is_not_convenience, |
3552 | 3 | attr->getReplacedFunctionName()); |
3553 | 3 | } |
3554 | 207 | } |
3555 | 1.21k | } |
3556 | | |
3557 | | Type |
3558 | | ResolveTypeEraserTypeRequest::evaluate(Evaluator &evaluator, |
3559 | | ProtocolDecl *PD, |
3560 | 102 | TypeEraserAttr *attr) const { |
3561 | 102 | if (auto *typeEraserRepr = attr->getParsedTypeEraserTypeRepr()) { |
3562 | 96 | return TypeResolution::resolveContextualType(typeEraserRepr, PD, llvm::None, |
3563 | | // Unbound generics and |
3564 | | // placeholders are not allowed |
3565 | | // within this attribute. |
3566 | 96 | /*unboundTyOpener*/ nullptr, |
3567 | 96 | /*placeholderHandler*/ nullptr, |
3568 | 96 | /*packElementOpener*/ nullptr); |
3569 | 96 | } else { |
3570 | 6 | auto *LazyResolver = attr->Resolver; |
3571 | 6 | assert(LazyResolver && "type eraser was neither parsed nor deserialized?"); |
3572 | 0 | auto ty = LazyResolver->loadTypeEraserType(attr, attr->ResolverContextData); |
3573 | 6 | attr->Resolver = nullptr; |
3574 | 6 | if (!ty) { |
3575 | 0 | return ErrorType::get(PD->getASTContext()); |
3576 | 0 | } |
3577 | 6 | return ty; |
3578 | 6 | } |
3579 | 102 | } |
3580 | | |
3581 | | Type |
3582 | | ResolveRawLayoutLikeTypeRequest::evaluate(Evaluator &evaluator, |
3583 | | StructDecl *sd, |
3584 | 72 | RawLayoutAttr *attr) const { |
3585 | 72 | assert(attr->LikeType); |
3586 | | |
3587 | | // If the attribute has a fixed type representation, then it was likely |
3588 | | // deserialized and the type has already been computed. |
3589 | 72 | if (auto fixedTy = dyn_cast<FixedTypeRepr>(attr->LikeType)) { |
3590 | 3 | return fixedTy->getType(); |
3591 | 3 | } |
3592 | | |
3593 | | // Resolve the like type in the struct's context. |
3594 | 69 | return TypeResolution::resolveContextualType( |
3595 | 69 | attr->LikeType, sd, llvm::None, |
3596 | | // Unbound generics and placeholders |
3597 | | // are not allowed within this |
3598 | | // attribute. |
3599 | 69 | /*unboundTyOpener*/ nullptr, |
3600 | 69 | /*placeholderHandler*/ nullptr, |
3601 | 69 | /*packElementOpener*/ nullptr); |
3602 | 72 | } |
3603 | | |
3604 | | bool |
3605 | | TypeEraserHasViableInitRequest::evaluate(Evaluator &evaluator, |
3606 | | TypeEraserAttr *attr, |
3607 | 96 | ProtocolDecl *protocol) const { |
3608 | 96 | DeclContext *dc = protocol->getDeclContext(); |
3609 | 96 | ModuleDecl *module = dc->getParentModule(); |
3610 | 96 | auto &ctx = module->getASTContext(); |
3611 | 96 | auto &diags = ctx.Diags; |
3612 | 96 | Type protocolType = protocol->getDeclaredInterfaceType(); |
3613 | | |
3614 | | // Get the NominalTypeDecl for the type eraser. |
3615 | 96 | Type typeEraser = attr->getResolvedType(protocol); |
3616 | 96 | if (typeEraser->hasError()) |
3617 | 6 | return false; |
3618 | | |
3619 | | // The type eraser must be a concrete nominal type |
3620 | 90 | auto nominalTypeDecl = typeEraser->getAnyNominal(); |
3621 | 90 | if (auto typeAliasDecl = dyn_cast_or_null<TypeAliasDecl>(nominalTypeDecl)) |
3622 | 0 | nominalTypeDecl = typeAliasDecl->getUnderlyingType()->getAnyNominal(); |
3623 | | |
3624 | 90 | if (!nominalTypeDecl || isa<ProtocolDecl>(nominalTypeDecl)) { |
3625 | 9 | diags.diagnose(attr->getLoc(), diag::non_nominal_type_eraser); |
3626 | 9 | return false; |
3627 | 9 | } |
3628 | | |
3629 | | // The nominal type must be accessible wherever the protocol is accessible |
3630 | 81 | if (nominalTypeDecl->getFormalAccess() < protocol->getFormalAccess()) { |
3631 | 9 | diags.diagnose(attr->getLoc(), diag::type_eraser_not_accessible, |
3632 | 9 | nominalTypeDecl->getFormalAccess(), nominalTypeDecl->getName(), |
3633 | 9 | protocolType, protocol->getFormalAccess()); |
3634 | 9 | diags.diagnose(nominalTypeDecl->getLoc(), diag::type_eraser_declared_here); |
3635 | 9 | return false; |
3636 | 9 | } |
3637 | | |
3638 | | // The type eraser must conform to the annotated protocol |
3639 | 72 | if (!TypeChecker::conformsToProtocol(typeEraser, protocol, module)) { |
3640 | 3 | diags.diagnose(attr->getLoc(), diag::type_eraser_does_not_conform, |
3641 | 3 | typeEraser, protocolType); |
3642 | 3 | diags.diagnose(nominalTypeDecl->getLoc(), diag::type_eraser_declared_here); |
3643 | 3 | return false; |
3644 | 3 | } |
3645 | | |
3646 | | // The type eraser must have an init of the form init<T: Protocol>(erasing: T) |
3647 | 69 | auto lookupResult = TypeChecker::lookupMember(dc, typeEraser, |
3648 | 69 | DeclNameRef::createConstructor()); |
3649 | | |
3650 | | // Keep track of unviable init candidates for diagnostics |
3651 | 69 | enum class UnviableReason { |
3652 | 69 | Failable, |
3653 | 69 | UnsatisfiedRequirements, |
3654 | 69 | Inaccessible, |
3655 | 69 | SPI, |
3656 | 69 | }; |
3657 | 69 | SmallVector<std::tuple<ConstructorDecl *, UnviableReason, Type>, 2> unviable; |
3658 | | |
3659 | 78 | bool foundMatch = llvm::any_of(lookupResult, [&](const LookupResultEntry &entry) { |
3660 | 78 | auto *init = cast<ConstructorDecl>(entry.getValueDecl()); |
3661 | 78 | if (!init->isGeneric() || init->getGenericParams()->size() != 1) |
3662 | 6 | return false; |
3663 | | |
3664 | 72 | auto genericSignature = init->getGenericSignature(); |
3665 | 72 | auto genericParamType = genericSignature.getInnermostGenericParams().front(); |
3666 | | |
3667 | | // Fow now, only allow one parameter. |
3668 | 72 | auto params = init->getParameters(); |
3669 | 72 | if (params->size() != 1) |
3670 | 3 | return false; |
3671 | | |
3672 | | // The parameter must have the form `erasing: T` where T conforms to the protocol. |
3673 | 69 | ParamDecl *param = *init->getParameters()->begin(); |
3674 | 69 | if (param->getArgumentName() != ctx.Id_erasing || |
3675 | 69 | !param->getInterfaceType()->isEqual(genericParamType) || |
3676 | 69 | !genericSignature->requiresProtocol(genericParamType, protocol)) |
3677 | 9 | return false; |
3678 | | |
3679 | | // Allow other constraints as long as the init can be called with any |
3680 | | // type conforming to the annotated protocol. We will check this by |
3681 | | // substituting the protocol's Self type for the generic arg and check that |
3682 | | // the requirements in the generic signature are satisfied. |
3683 | 60 | auto *module = nominalTypeDecl->getParentModule(); |
3684 | 60 | auto baseMap = |
3685 | 60 | typeEraser->getContextSubstitutionMap(module, |
3686 | 60 | nominalTypeDecl); |
3687 | 60 | QuerySubstitutionMap getSubstitution{baseMap}; |
3688 | | |
3689 | | // Use invalid 'SourceLoc's to suppress diagnostics. |
3690 | 60 | auto result = TypeChecker::checkGenericArguments( |
3691 | 60 | module, genericSignature.getRequirements(), |
3692 | 75 | [&](SubstitutableType *type) -> Type { |
3693 | 75 | if (type->isEqual(genericParamType)) |
3694 | 72 | return protocol->getSelfTypeInContext(); |
3695 | | |
3696 | 3 | return getSubstitution(type); |
3697 | 75 | }); |
3698 | | |
3699 | 60 | if (result != CheckGenericArgumentsResult::Success) { |
3700 | 9 | unviable.push_back( |
3701 | 9 | std::make_tuple(init, UnviableReason::UnsatisfiedRequirements, |
3702 | 9 | genericParamType)); |
3703 | 9 | return false; |
3704 | 9 | } |
3705 | | |
3706 | 51 | if (init->isFailable()) { |
3707 | 3 | unviable.push_back( |
3708 | 3 | std::make_tuple(init, UnviableReason::Failable, genericParamType)); |
3709 | 3 | return false; |
3710 | 3 | } |
3711 | | |
3712 | 48 | if (init->getFormalAccess() < protocol->getFormalAccess()) { |
3713 | 9 | unviable.push_back( |
3714 | 9 | std::make_tuple(init, UnviableReason::Inaccessible, genericParamType)); |
3715 | 9 | return false; |
3716 | 9 | } |
3717 | | |
3718 | 39 | if (init->isSPI()) { |
3719 | 9 | if (!protocol->isSPI()) { |
3720 | 3 | unviable.push_back( |
3721 | 3 | std::make_tuple(init, UnviableReason::SPI, genericParamType)); |
3722 | 3 | return false; |
3723 | 3 | } |
3724 | 6 | auto protocolSPIGroups = protocol->getSPIGroups(); |
3725 | 6 | auto initSPIGroups = init->getSPIGroups(); |
3726 | | // If both are SPI, `init(erasing:)` must be available in all of the |
3727 | | // protocol's SPI groups. |
3728 | | // TODO: Do this more efficiently? |
3729 | 12 | for (auto protocolGroup : protocolSPIGroups) { |
3730 | 12 | auto foundIt = std::find( |
3731 | 12 | initSPIGroups.begin(), initSPIGroups.end(), protocolGroup); |
3732 | 12 | if (foundIt == initSPIGroups.end()) { |
3733 | 3 | unviable.push_back( |
3734 | 3 | std::make_tuple(init, UnviableReason::SPI, genericParamType)); |
3735 | 3 | return false; |
3736 | 3 | } |
3737 | 12 | } |
3738 | 6 | } |
3739 | | |
3740 | 33 | return true; |
3741 | 39 | }); |
3742 | | |
3743 | 69 | if (!foundMatch) { |
3744 | 36 | if (unviable.empty()) { |
3745 | 18 | diags.diagnose(attr->getLocation(), diag::type_eraser_missing_init, |
3746 | 18 | typeEraser, protocol->getName().str()); |
3747 | 18 | diags.diagnose(nominalTypeDecl->getLoc(), diag::type_eraser_declared_here); |
3748 | 18 | return false; |
3749 | 18 | } |
3750 | | |
3751 | 18 | diags.diagnose(attr->getLocation(), diag::type_eraser_unviable_init, |
3752 | 18 | typeEraser, protocol->getName().str()); |
3753 | 27 | for (auto &candidate: unviable) { |
3754 | 27 | auto init = std::get<0>(candidate); |
3755 | 27 | auto reason = std::get<1>(candidate); |
3756 | 27 | auto genericParamType = std::get<2>(candidate); |
3757 | | |
3758 | 27 | switch (reason) { |
3759 | 3 | case UnviableReason::Failable: |
3760 | 3 | diags.diagnose(init->getLoc(), diag::type_eraser_failable_init); |
3761 | 3 | break; |
3762 | 9 | case UnviableReason::UnsatisfiedRequirements: |
3763 | 9 | diags.diagnose(init->getLoc(), |
3764 | 9 | diag::type_eraser_init_unsatisfied_requirements, |
3765 | 9 | genericParamType, protocol->getName().str()); |
3766 | 9 | break; |
3767 | 9 | case UnviableReason::Inaccessible: |
3768 | 9 | diags.diagnose( |
3769 | 9 | init->getLoc(), diag::type_eraser_init_not_accessible, |
3770 | 9 | init->getFormalAccessScope().requiredAccessForDiagnostics(), |
3771 | 9 | protocolType, |
3772 | 9 | protocol->getFormalAccessScope().requiredAccessForDiagnostics()); |
3773 | 9 | break; |
3774 | 6 | case UnviableReason::SPI: |
3775 | 6 | diags.diagnose(init->getLoc(), diag::type_eraser_init_spi, |
3776 | 6 | protocolType, protocol->isSPI()); |
3777 | 6 | break; |
3778 | 27 | } |
3779 | 27 | } |
3780 | 18 | return false; |
3781 | 18 | } |
3782 | | |
3783 | 33 | return true; |
3784 | 69 | } |
3785 | | |
3786 | 96 | void AttributeChecker::visitTypeEraserAttr(TypeEraserAttr *attr) { |
3787 | 96 | assert(isa<ProtocolDecl>(D)); |
3788 | | // Invoke the request. |
3789 | 0 | (void)attr->hasViableTypeEraserInit(cast<ProtocolDecl>(D)); |
3790 | 96 | } |
3791 | | |
3792 | 630 | void AttributeChecker::visitStorageRestrictionsAttr(StorageRestrictionsAttr *attr) { |
3793 | 630 | auto *accessor = dyn_cast<AccessorDecl>(D); |
3794 | 630 | if (!accessor || accessor->getAccessorKind() != AccessorKind::Init) { |
3795 | 9 | diagnose(attr->getLocation(), |
3796 | 9 | diag::storage_restrictions_attribute_not_on_init_accessor); |
3797 | 9 | return; |
3798 | 9 | } |
3799 | | |
3800 | 621 | auto initializesProperties = attr->getInitializesProperties(accessor); |
3801 | 621 | for (auto *property : attr->getAccessesProperties(accessor)) { |
3802 | 150 | if (llvm::is_contained(initializesProperties, property)) { |
3803 | 6 | diagnose(attr->getLocation(), |
3804 | 6 | diag::init_accessor_property_both_init_and_accessed, |
3805 | 6 | property->getName()); |
3806 | 6 | } |
3807 | 150 | } |
3808 | 621 | } |
3809 | | |
3810 | 1.05k | void AttributeChecker::visitImplementsAttr(ImplementsAttr *attr) { |
3811 | 1.05k | DeclContext *DC = D->getDeclContext(); |
3812 | | |
3813 | 1.05k | ProtocolDecl *PD = attr->getProtocol(DC); |
3814 | | |
3815 | 1.05k | if (!PD) { |
3816 | 3 | diagnose(attr->getLocation(), diag::implements_attr_non_protocol_type) |
3817 | 3 | .highlight(attr->getProtocolTypeRepr()->getSourceRange()); |
3818 | 3 | return; |
3819 | 3 | } |
3820 | | |
3821 | | // Check that the ProtocolType has the specified member. |
3822 | 1.04k | LookupResult R = |
3823 | 1.04k | TypeChecker::lookupMember(PD->getDeclContext(), |
3824 | 1.04k | PD->getDeclaredInterfaceType(), |
3825 | 1.04k | DeclNameRef(attr->getMemberName())); |
3826 | 1.04k | if (!R) { |
3827 | 3 | diagnose(attr->getLocation(), |
3828 | 3 | diag::implements_attr_protocol_lacks_member, |
3829 | 3 | PD, attr->getMemberName()) |
3830 | 3 | .highlight(attr->getMemberNameLoc().getSourceRange()); |
3831 | 3 | return; |
3832 | 3 | } |
3833 | | |
3834 | | // Check that the decl we're decorating is a member of a type that actually |
3835 | | // conforms to the specified protocol. |
3836 | 1.04k | NominalTypeDecl *NTD = DC->getSelfNominalTypeDecl(); |
3837 | 1.04k | if (auto *OtherPD = dyn_cast<ProtocolDecl>(NTD)) { |
3838 | 24 | if (!OtherPD->inheritsFrom(PD)) { |
3839 | 0 | diagnose(attr->getLocation(), |
3840 | 0 | diag::implements_attr_protocol_not_conformed_to, NTD, PD) |
3841 | 0 | .highlight(attr->getProtocolTypeRepr()->getSourceRange()); |
3842 | 0 | } |
3843 | 1.02k | } else { |
3844 | 1.02k | SmallVector<ProtocolConformance *, 2> conformances; |
3845 | 1.02k | if (!NTD->lookupConformance(PD, conformances)) { |
3846 | 3 | diagnose(attr->getLocation(), |
3847 | 3 | diag::implements_attr_protocol_not_conformed_to, NTD, PD) |
3848 | 3 | .highlight(attr->getProtocolTypeRepr()->getSourceRange()); |
3849 | 3 | } |
3850 | 1.02k | } |
3851 | 1.04k | } |
3852 | | |
3853 | 9.20k | void AttributeChecker::visitFrozenAttr(FrozenAttr *attr) { |
3854 | 9.20k | if (auto *ED = dyn_cast<EnumDecl>(D)) { |
3855 | 2.26k | if (!ED->getModuleContext()->isResilient()) { |
3856 | 54 | attr->setInvalid(); |
3857 | 54 | return; |
3858 | 54 | } |
3859 | | |
3860 | 2.21k | if (ED->getFormalAccess() < AccessLevel::Public && |
3861 | 2.21k | !ED->getAttrs().hasAttribute<UsableFromInlineAttr>()) { |
3862 | 6 | diagnoseAndRemoveAttr(attr, diag::enum_frozen_nonpublic, attr); |
3863 | 6 | return; |
3864 | 6 | } |
3865 | 2.21k | } |
3866 | | |
3867 | 9.14k | auto *VD = cast<ValueDecl>(D); |
3868 | | |
3869 | 9.14k | if (VD->getFormalAccess() < AccessLevel::Public && |
3870 | 9.14k | !VD->getAttrs().hasAttribute<UsableFromInlineAttr>()) { |
3871 | 36 | diagnoseAndRemoveAttr(attr, diag::frozen_attr_on_internal_type, |
3872 | 36 | VD->getName(), VD->getFormalAccess()); |
3873 | 36 | } |
3874 | 9.14k | } |
3875 | | |
3876 | 10.7k | void AttributeChecker::visitCustomAttr(CustomAttr *attr) { |
3877 | 10.7k | auto dc = D->getDeclContext(); |
3878 | | |
3879 | | // Figure out which nominal declaration this custom attribute refers to. |
3880 | 10.7k | auto *nominal = evaluateOrDefault( |
3881 | 10.7k | Ctx.evaluator, CustomAttrNominalRequest{attr, dc}, nullptr); |
3882 | | |
3883 | 10.7k | if (!nominal) { |
3884 | 1.70k | if (attr->isInvalid()) |
3885 | 0 | return; |
3886 | | |
3887 | | // Try resolving an attached macro attribute. |
3888 | 1.70k | if (auto *macro = D->getResolvedMacro(attr)) { |
3889 | 2.09k | for (auto *roleAttr : macro->getAttrs().getAttributes<MacroRoleAttr>()) { |
3890 | 2.09k | auto role = roleAttr->getMacroRole(); |
3891 | 2.09k | if (isInvalidAttachedMacro(role, D)) { |
3892 | 33 | diagnoseAndRemoveAttr(attr, diag::macro_attached_to_invalid_decl, |
3893 | 33 | getMacroRoleString(role), |
3894 | 33 | D->getDescriptiveKind(), D); |
3895 | 33 | } |
3896 | 2.09k | } |
3897 | | |
3898 | 1.59k | return; |
3899 | 1.59k | } |
3900 | | |
3901 | | // Diagnose errors. |
3902 | | |
3903 | 105 | auto typeRepr = attr->getTypeRepr(); |
3904 | | |
3905 | 105 | auto type = TypeResolution::forInterface(dc, TypeResolverContext::CustomAttr, |
3906 | | // Unbound generics and placeholders |
3907 | | // are not allowed within this |
3908 | | // attribute. |
3909 | 105 | /*unboundTyOpener*/ nullptr, |
3910 | 105 | /*placeholderHandler*/ nullptr, |
3911 | 105 | /*packElementOpener*/ nullptr) |
3912 | 105 | .resolveType(typeRepr); |
3913 | | |
3914 | 105 | if (type->is<ErrorType>()) { |
3915 | | // Type resolution has failed, and we should have diagnosed something already. |
3916 | 99 | assert(Ctx.hadError()); |
3917 | 99 | } else { |
3918 | | // Otherwise, something odd happened. |
3919 | 6 | std::string typeName; |
3920 | 6 | llvm::raw_string_ostream out(typeName); |
3921 | 6 | typeRepr->print(out); |
3922 | | |
3923 | 6 | Ctx.Diags.diagnose(attr->getLocation(), diag::unknown_attribute, typeName); |
3924 | 6 | } |
3925 | | |
3926 | 0 | attr->setInvalid(); |
3927 | 105 | return; |
3928 | 1.70k | } |
3929 | | |
3930 | 9.04k | if (nominal->isMainActor() && Ctx.LangOpts.isConcurrencyModelTaskToThread() && |
3931 | 9.04k | !AvailableAttr::isUnavailable(D)) { |
3932 | 0 | Ctx.Diags.diagnose(attr->getLocation(), |
3933 | 0 | diag::concurrency_task_to_thread_model_main_actor, |
3934 | 0 | "task-to-thread concurrency model"); |
3935 | 0 | return; |
3936 | 0 | } |
3937 | | |
3938 | | // If the nominal type is a property wrapper type, we can be delegating |
3939 | | // through a property. |
3940 | 9.04k | if (nominal->getAttrs().hasAttribute<PropertyWrapperAttr>()) { |
3941 | | // FIXME: We shouldn't be type checking missing decls. |
3942 | 4.13k | if (isa<MissingDecl>(D)) |
3943 | 0 | return; |
3944 | | |
3945 | | // property wrappers can only be applied to variables |
3946 | 4.13k | if (!isa<VarDecl>(D)) { |
3947 | 0 | diagnose(attr->getLocation(), |
3948 | 0 | diag::property_wrapper_attribute_not_on_property, |
3949 | 0 | nominal->getName()); |
3950 | 0 | attr->setInvalid(); |
3951 | 0 | return; |
3952 | 0 | } |
3953 | | |
3954 | 4.13k | if (isa<ParamDecl>(D)) { |
3955 | | // Check for unsupported declarations. |
3956 | 306 | auto *context = D->getDeclContext()->getAsDecl(); |
3957 | 306 | if (isa_and_nonnull<SubscriptDecl>(context)) { |
3958 | 3 | diagnose(attr->getLocation(), |
3959 | 3 | diag::property_wrapper_param_not_supported, |
3960 | 3 | context->getDescriptiveKind()); |
3961 | 3 | attr->setInvalid(); |
3962 | 3 | return; |
3963 | 3 | } |
3964 | 306 | } |
3965 | | |
3966 | 4.13k | return; |
3967 | 4.13k | } |
3968 | | |
3969 | | // If the nominal type is a result builder type, verify that D is a |
3970 | | // function, storage with an explicit getter, or parameter of function type. |
3971 | 4.90k | if (nominal->getAttrs().hasAttribute<ResultBuilderAttr>()) { |
3972 | 1.06k | ValueDecl *decl; |
3973 | 1.06k | if (auto param = dyn_cast<ParamDecl>(D)) { |
3974 | 675 | decl = param; |
3975 | 675 | } else if (auto func = dyn_cast<FuncDecl>(D)) { |
3976 | 132 | decl = func; |
3977 | 255 | } else if (auto storage = dyn_cast<AbstractStorageDecl>(D)) { |
3978 | 252 | decl = storage; |
3979 | | |
3980 | | // Check whether this is a storage declaration that is not permitted |
3981 | | // to have a result builder attached. |
3982 | 252 | auto shouldDiagnose = [&]() -> bool { |
3983 | | // An uninitialized stored property in a struct can have a function |
3984 | | // builder attached. |
3985 | 252 | if (auto var = dyn_cast<VarDecl>(decl)) { |
3986 | 252 | if (var->isInstanceMember() && |
3987 | 252 | isa<StructDecl>(var->getDeclContext()) && |
3988 | 252 | !var->getParentInitializer()) { |
3989 | 159 | return false; |
3990 | 159 | } |
3991 | 252 | } |
3992 | | |
3993 | 93 | auto getter = storage->getParsedAccessor(AccessorKind::Get); |
3994 | 93 | if (!getter) |
3995 | 6 | return true; |
3996 | | |
3997 | | // Module interfaces don't print bodies for all getters, so allow getters |
3998 | | // that don't have a body if we're compiling a module interface. |
3999 | | // Within a protocol definition, there will never be a body. |
4000 | 87 | SourceFile *parent = storage->getDeclContext()->getParentSourceFile(); |
4001 | 87 | bool isInInterface = parent && parent->Kind == SourceFileKind::Interface; |
4002 | 87 | if (!isInInterface && !getter->hasBody() && |
4003 | 87 | !isa<ProtocolDecl>(storage->getDeclContext())) |
4004 | 0 | return true; |
4005 | | |
4006 | 87 | return false; |
4007 | 87 | }; |
4008 | | |
4009 | 252 | if (shouldDiagnose()) { |
4010 | 6 | diagnose(attr->getLocation(), |
4011 | 6 | diag::result_builder_attribute_on_storage_without_getter, |
4012 | 6 | nominal->getName(), |
4013 | 6 | isa<SubscriptDecl>(storage) ? 0 |
4014 | 6 | : storage->getDeclContext()->isTypeContext() ? 1 |
4015 | 6 | : cast<VarDecl>(storage)->isLet() ? 2 : 3); |
4016 | 6 | attr->setInvalid(); |
4017 | 6 | return; |
4018 | 6 | } |
4019 | 252 | } else { |
4020 | 3 | diagnose(attr->getLocation(), |
4021 | 3 | diag::result_builder_attribute_not_allowed_here, |
4022 | 3 | nominal->getName()); |
4023 | 3 | attr->setInvalid(); |
4024 | 3 | return; |
4025 | 3 | } |
4026 | | |
4027 | | // Diagnose and ignore arguments. |
4028 | 1.05k | if (attr->hasArgs()) { |
4029 | 3 | diagnose(attr->getLocation(), diag::result_builder_arguments) |
4030 | 3 | .highlight(attr->getArgs()->getSourceRange()); |
4031 | 3 | } |
4032 | | |
4033 | | // Complain if this isn't the primary result-builder attribute. |
4034 | 1.05k | auto attached = decl->getAttachedResultBuilder(); |
4035 | 1.05k | if (attached != attr) { |
4036 | 6 | diagnose(attr->getLocation(), diag::result_builder_multiple, |
4037 | 6 | isa<ParamDecl>(decl)); |
4038 | 6 | diagnose(attached->getLocation(), diag::previous_result_builder_here); |
4039 | 6 | attr->setInvalid(); |
4040 | 6 | return; |
4041 | 1.04k | } else { |
4042 | | // Force any diagnostics associated with computing the result-builder |
4043 | | // type. |
4044 | 1.04k | (void) decl->getResultBuilderType(); |
4045 | 1.04k | } |
4046 | | |
4047 | 1.04k | return; |
4048 | 1.05k | } |
4049 | | |
4050 | | // If the nominal type is a global actor, let the global actor attribute |
4051 | | // retrieval request perform checking for us. |
4052 | 3.84k | if (nominal->isGlobalActor()) { |
4053 | 3.84k | (void)D->getGlobalActorAttr(); |
4054 | 3.84k | if (auto value = dyn_cast<ValueDecl>(D)) { |
4055 | 3.81k | (void)getActorIsolation(value); |
4056 | 3.81k | } else { |
4057 | | // Make sure we evaluate the global actor type. |
4058 | 33 | auto dc = D->getInnermostDeclContext(); |
4059 | 33 | (void)evaluateOrDefault( |
4060 | 33 | Ctx.evaluator, |
4061 | 33 | CustomAttrTypeRequest{ |
4062 | 33 | attr, dc, CustomAttrTypeKind::GlobalActor}, |
4063 | 33 | Type()); |
4064 | 33 | } |
4065 | | |
4066 | 3.84k | return; |
4067 | 3.84k | } |
4068 | | |
4069 | 0 | diagnose(attr->getLocation(), diag::nominal_type_not_attribute, nominal); |
4070 | 0 | nominal->diagnose(diag::decl_declared_here, nominal); |
4071 | 0 | attr->setInvalid(); |
4072 | 0 | } |
4073 | | |
4074 | | static bool isMemberLessAccessibleThanType(NominalTypeDecl *typeDecl, |
4075 | 573 | ValueDecl *member) { |
4076 | 573 | return member->getFormalAccess() < |
4077 | 573 | std::min(typeDecl->getFormalAccess(), AccessLevel::Public); |
4078 | 573 | } |
4079 | | |
4080 | 1.80k | void AttributeChecker::visitPropertyWrapperAttr(PropertyWrapperAttr *attr) { |
4081 | 1.80k | auto nominal = dyn_cast<NominalTypeDecl>(D); |
4082 | 1.80k | if (!nominal) |
4083 | 0 | return; |
4084 | | |
4085 | | // Force checking of the property wrapper type. |
4086 | 1.80k | (void)nominal->getPropertyWrapperTypeInfo(); |
4087 | 1.80k | } |
4088 | | |
4089 | 537 | void AttributeChecker::visitResultBuilderAttr(ResultBuilderAttr *attr) { |
4090 | 537 | auto *nominal = dyn_cast<NominalTypeDecl>(D); |
4091 | 537 | auto &ctx = D->getASTContext(); |
4092 | 537 | SmallVector<ValueDecl *, 4> buildBlockMatches; |
4093 | 537 | SmallVector<ValueDecl *, 4> buildPartialBlockFirstMatches; |
4094 | 537 | SmallVector<ValueDecl *, 4> buildPartialBlockAccumulatedMatches; |
4095 | | |
4096 | 537 | bool supportsBuildBlock = TypeChecker::typeSupportsBuilderOp( |
4097 | 537 | nominal->getDeclaredType(), nominal, ctx.Id_buildBlock, |
4098 | 537 | /*argLabels=*/{}, &buildBlockMatches); |
4099 | | |
4100 | 537 | bool supportsBuildPartialBlock = |
4101 | 537 | TypeChecker::typeSupportsBuilderOp( |
4102 | 537 | nominal->getDeclaredType(), nominal, ctx.Id_buildPartialBlock, |
4103 | 537 | /*argLabels=*/{ctx.Id_first}, &buildPartialBlockFirstMatches) && |
4104 | 537 | TypeChecker::typeSupportsBuilderOp( |
4105 | 63 | nominal->getDeclaredType(), nominal, ctx.Id_buildPartialBlock, |
4106 | 63 | /*argLabels=*/{ctx.Id_accumulated, ctx.Id_next}, |
4107 | 63 | &buildPartialBlockAccumulatedMatches); |
4108 | | |
4109 | 537 | if (!supportsBuildBlock && !supportsBuildPartialBlock) { |
4110 | 60 | { |
4111 | 60 | auto diag = diagnose( |
4112 | 60 | nominal->getLoc(), |
4113 | 60 | diag::result_builder_static_buildblock_or_buildpartialblock); |
4114 | | |
4115 | | // If there were no close matches, propose adding a stub. |
4116 | 60 | SourceLoc buildInsertionLoc; |
4117 | 60 | std::string stubIndent; |
4118 | 60 | Type componentType; |
4119 | 60 | std::tie(buildInsertionLoc, stubIndent, componentType) = |
4120 | 60 | determineResultBuilderBuildFixItInfo(nominal); |
4121 | 60 | if (buildInsertionLoc.isValid() && buildBlockMatches.empty()) { |
4122 | 30 | std::string fixItString; |
4123 | 30 | { |
4124 | 30 | llvm::raw_string_ostream out(fixItString); |
4125 | 30 | printResultBuilderBuildFunction( |
4126 | 30 | nominal, componentType, |
4127 | 30 | ResultBuilderBuildFunction::BuildBlock, |
4128 | 30 | stubIndent, out); |
4129 | 30 | } |
4130 | | |
4131 | 30 | diag.fixItInsert(buildInsertionLoc, fixItString); |
4132 | 30 | } |
4133 | 60 | } |
4134 | | |
4135 | | // For any close matches, attempt to explain to the user why they aren't |
4136 | | // valid. |
4137 | 60 | for (auto *member : buildBlockMatches) { |
4138 | 30 | if (member->isStatic() && isa<FuncDecl>(member)) |
4139 | 0 | continue; |
4140 | | |
4141 | 30 | if (isa<FuncDecl>(member) && |
4142 | 30 | member->getDeclContext()->getSelfNominalTypeDecl() == nominal) |
4143 | 6 | diagnose(member->getLoc(), diag::result_builder_non_static_buildblock) |
4144 | 6 | .fixItInsert(member->getAttributeInsertionLoc(true), "static "); |
4145 | 24 | else if (isa<EnumElementDecl>(member)) |
4146 | 3 | diagnose(member->getLoc(), diag::result_builder_buildblock_enum_case); |
4147 | 21 | else |
4148 | 21 | diagnose(member->getLoc(), |
4149 | 21 | diag::result_builder_buildblock_not_static_method); |
4150 | 30 | } |
4151 | | |
4152 | 60 | return; |
4153 | 60 | } |
4154 | | |
4155 | | // Let's check whether one or more overloads of buildBlock or |
4156 | | // buildPartialBlock are as accessible as the builder type itself. |
4157 | 477 | { |
4158 | 573 | auto isBuildMethodAsAccessibleAsType = [&](ValueDecl *member) { |
4159 | 573 | return !isMemberLessAccessibleThanType(nominal, member); |
4160 | 573 | }; |
4161 | | |
4162 | 477 | bool hasAccessibleBuildBlock = |
4163 | 477 | llvm::any_of(buildBlockMatches, isBuildMethodAsAccessibleAsType); |
4164 | | |
4165 | 477 | bool hasAccessibleBuildPartialBlockFirst = false; |
4166 | 477 | bool hasAccessibleBuildPartialBlockAccumulated = false; |
4167 | | |
4168 | 477 | if (supportsBuildPartialBlock) { |
4169 | 60 | DeclName buildPartialBlockFirst(ctx, ctx.Id_buildPartialBlock, |
4170 | 60 | /*argLabels=*/{ctx.Id_first}); |
4171 | 60 | DeclName buildPartialBlockAccumulated( |
4172 | 60 | ctx, ctx.Id_buildPartialBlock, |
4173 | 60 | /*argLabels=*/{ctx.Id_accumulated, ctx.Id_next}); |
4174 | | |
4175 | 60 | buildPartialBlockFirstMatches.clear(); |
4176 | 60 | buildPartialBlockAccumulatedMatches.clear(); |
4177 | | |
4178 | 60 | auto builderType = nominal->getDeclaredType(); |
4179 | 60 | nominal->lookupQualified(builderType, DeclNameRef(buildPartialBlockFirst), |
4180 | 60 | attr->getLocation(), NL_QualifiedDefault, |
4181 | 60 | buildPartialBlockFirstMatches); |
4182 | 60 | nominal->lookupQualified( |
4183 | 60 | builderType, DeclNameRef(buildPartialBlockAccumulated), |
4184 | 60 | attr->getLocation(), NL_QualifiedDefault, |
4185 | 60 | buildPartialBlockAccumulatedMatches); |
4186 | | |
4187 | 60 | hasAccessibleBuildPartialBlockFirst = llvm::any_of( |
4188 | 60 | buildPartialBlockFirstMatches, isBuildMethodAsAccessibleAsType); |
4189 | 60 | hasAccessibleBuildPartialBlockAccumulated = llvm::any_of( |
4190 | 60 | buildPartialBlockAccumulatedMatches, isBuildMethodAsAccessibleAsType); |
4191 | 60 | } |
4192 | | |
4193 | 477 | if (!hasAccessibleBuildBlock) { |
4194 | | // No or incomplete `buildPartialBlock` and all overloads of |
4195 | | // `buildBlock(_:)` are less accessible than the type. |
4196 | 36 | if (!supportsBuildPartialBlock) { |
4197 | 3 | diagnose(nominal->getLoc(), |
4198 | 3 | diag::result_builder_buildblock_not_accessible, |
4199 | 3 | nominal->getName(), nominal->getFormalAccess()); |
4200 | 33 | } else { |
4201 | 33 | if (!hasAccessibleBuildPartialBlockFirst) { |
4202 | 3 | diagnose(nominal->getLoc(), |
4203 | 3 | diag::result_builder_buildpartialblock_first_not_accessible, |
4204 | 3 | nominal->getName(), nominal->getFormalAccess()); |
4205 | 3 | } |
4206 | | |
4207 | 33 | if (!hasAccessibleBuildPartialBlockAccumulated) { |
4208 | 3 | diagnose( |
4209 | 3 | nominal->getLoc(), |
4210 | 3 | diag::result_builder_buildpartialblock_accumulated_not_accessible, |
4211 | 3 | nominal->getName(), nominal->getFormalAccess()); |
4212 | 3 | } |
4213 | 33 | } |
4214 | 36 | } |
4215 | 477 | } |
4216 | 477 | } |
4217 | | |
4218 | | void |
4219 | 627 | AttributeChecker::visitImplementationOnlyAttr(ImplementationOnlyAttr *attr) { |
4220 | 627 | if (isa<ImportDecl>(D)) { |
4221 | | // These are handled elsewhere. |
4222 | 435 | return; |
4223 | 435 | } |
4224 | | |
4225 | 192 | auto *VD = cast<ValueDecl>(D); |
4226 | 192 | auto *overridden = VD->getOverriddenDecl(); |
4227 | 192 | if (!overridden) { |
4228 | 6 | diagnoseAndRemoveAttr(attr, diag::implementation_only_decl_non_override); |
4229 | 6 | return; |
4230 | 6 | } |
4231 | | |
4232 | | // Check if VD has the exact same type as what it overrides. |
4233 | | // Note: This is specifically not using `swift::getMemberTypeForComparison` |
4234 | | // because that erases more information than we want, like `throws`-ness. |
4235 | 186 | auto baseInterfaceTy = overridden->getInterfaceType(); |
4236 | 186 | auto derivedInterfaceTy = VD->getInterfaceType(); |
4237 | | |
4238 | 186 | auto selfInterfaceTy = VD->getDeclContext()->getDeclaredInterfaceType(); |
4239 | | |
4240 | 186 | auto overrideInterfaceTy = |
4241 | 186 | selfInterfaceTy->adjustSuperclassMemberDeclType(overridden, VD, |
4242 | 186 | baseInterfaceTy); |
4243 | | |
4244 | 186 | if (isa<AbstractFunctionDecl>(VD)) { |
4245 | | // Drop the 'Self' parameter. |
4246 | | // FIXME: The real effect here, though, is dropping the generic signature. |
4247 | | // This should be okay because it should already be checked as part of |
4248 | | // making an override, but that isn't actually the case as of this writing, |
4249 | | // and it's kind of suspect anyway. |
4250 | 93 | derivedInterfaceTy = |
4251 | 93 | derivedInterfaceTy->castTo<AnyFunctionType>()->getResult(); |
4252 | 93 | overrideInterfaceTy = |
4253 | 93 | overrideInterfaceTy->castTo<AnyFunctionType>()->getResult(); |
4254 | 93 | } else if (isa<SubscriptDecl>(VD)) { |
4255 | | // For subscripts, we don't have a 'Self' type, but turn it |
4256 | | // into a monomorphic function type. |
4257 | | // FIXME: does this actually make sense, though? |
4258 | 33 | auto derivedInterfaceFuncTy = derivedInterfaceTy->castTo<AnyFunctionType>(); |
4259 | | // FIXME: Verify ExtInfo state is correct, not working by accident. |
4260 | 33 | FunctionType::ExtInfo derivedInterfaceInfo; |
4261 | 33 | derivedInterfaceTy = FunctionType::get(derivedInterfaceFuncTy->getParams(), |
4262 | 33 | derivedInterfaceFuncTy->getResult(), |
4263 | 33 | derivedInterfaceInfo); |
4264 | 33 | auto overrideInterfaceFuncTy = |
4265 | 33 | overrideInterfaceTy->castTo<AnyFunctionType>(); |
4266 | | // FIXME: Verify ExtInfo state is correct, not working by accident. |
4267 | 33 | FunctionType::ExtInfo overrideInterfaceInfo; |
4268 | 33 | overrideInterfaceTy = FunctionType::get( |
4269 | 33 | overrideInterfaceFuncTy->getParams(), |
4270 | 33 | overrideInterfaceFuncTy->getResult(), overrideInterfaceInfo); |
4271 | 33 | } |
4272 | | |
4273 | | // If @preconcurrency is involved, strip concurrency from the types before |
4274 | | // comparing them. |
4275 | 186 | if (overridden->preconcurrency() || VD->preconcurrency()) { |
4276 | 186 | derivedInterfaceTy = derivedInterfaceTy->stripConcurrency(true, false); |
4277 | 186 | overrideInterfaceTy = overrideInterfaceTy->stripConcurrency(true, false); |
4278 | 186 | } |
4279 | | |
4280 | 186 | if (!derivedInterfaceTy->isEqual(overrideInterfaceTy)) { |
4281 | 24 | diagnose(VD, diag::implementation_only_override_changed_type, |
4282 | 24 | overrideInterfaceTy); |
4283 | 24 | diagnose(overridden, diag::overridden_here); |
4284 | 24 | return; |
4285 | 24 | } |
4286 | | |
4287 | | // FIXME: When compiling without library evolution enabled, this should also |
4288 | | // check whether VD or any of its accessors need a new vtable entry, even if |
4289 | | // it won't necessarily be able to say why. |
4290 | 186 | } |
4291 | | |
4292 | | void |
4293 | 171 | AttributeChecker::visitSPIOnlyAttr(SPIOnlyAttr *attr) { |
4294 | 171 | auto *SF = D->getDeclContext()->getParentSourceFile(); |
4295 | 171 | if (!Ctx.LangOpts.EnableSPIOnlyImports && |
4296 | 171 | SF->Kind != SourceFileKind::Interface) { |
4297 | 3 | diagnoseAndRemoveAttr(attr, diag::spi_only_imports_not_enabled); |
4298 | 3 | } |
4299 | 171 | } |
4300 | | |
4301 | 0 | void AttributeChecker::visitNoMetadataAttr(NoMetadataAttr *attr) { |
4302 | 0 | if (!Ctx.LangOpts.hasFeature(Feature::LayoutPrespecialization)) { |
4303 | 0 | auto error = |
4304 | 0 | diag::experimental_no_metadata_feature_can_only_be_used_when_enabled; |
4305 | 0 | diagnoseAndRemoveAttr(attr, error); |
4306 | 0 | return; |
4307 | 0 | } |
4308 | | |
4309 | 0 | if (!isa<GenericTypeParamDecl>(D)) { |
4310 | 0 | attr->setInvalid(); |
4311 | 0 | diagnoseAndRemoveAttr(attr, diag::no_metadata_on_non_generic_param); |
4312 | 0 | } |
4313 | 0 | } |
4314 | | |
4315 | 987 | void AttributeChecker::visitNonEphemeralAttr(NonEphemeralAttr *attr) { |
4316 | 987 | auto *param = cast<ParamDecl>(D); |
4317 | 987 | auto type = param->getInterfaceType()->lookThroughSingleOptionalType(); |
4318 | | |
4319 | | // Can only be applied to Unsafe[...]Pointer types |
4320 | 987 | if (type->getAnyPointerElementType()) |
4321 | 897 | return; |
4322 | | |
4323 | | // ... or the protocol Self type. |
4324 | 90 | auto *outerDC = param->getDeclContext()->getParent(); |
4325 | 90 | if (outerDC->getSelfProtocolDecl() && |
4326 | 90 | type->isEqual(outerDC->getSelfInterfaceType())) { |
4327 | 81 | return; |
4328 | 81 | } |
4329 | | |
4330 | 9 | diagnose(attr->getLocation(), diag::non_ephemeral_non_pointer_type); |
4331 | 9 | attr->setInvalid(); |
4332 | 9 | } |
4333 | | |
4334 | | void AttributeChecker::checkOriginalDefinedInAttrs( |
4335 | 4.85M | ArrayRef<OriginallyDefinedInAttr *> Attrs) { |
4336 | 4.85M | if (Attrs.empty()) |
4337 | 4.85M | return; |
4338 | 1.09k | auto &Ctx = D->getASTContext(); |
4339 | 1.09k | std::map<PlatformKind, SourceLoc> seenPlatforms; |
4340 | | |
4341 | | // Attrs are in the reverse order of the source order. We need to visit them |
4342 | | // in source order to diagnose the later attribute. |
4343 | 4.72k | for (auto *Attr: Attrs) { |
4344 | 4.72k | if (!Attr->isActivePlatform(Ctx)) |
4345 | 3.61k | continue; |
4346 | | |
4347 | 1.10k | if (diagnoseAndRemoveAttrIfDeclIsNonPublic(Attr, /*isError=*/false)) |
4348 | 21 | continue; |
4349 | | |
4350 | 1.08k | auto AtLoc = Attr->AtLoc; |
4351 | 1.08k | auto Platform = Attr->Platform; |
4352 | 1.08k | if (!seenPlatforms.insert({Platform, AtLoc}).second) { |
4353 | | // We've seen the platform before, emit error to the previous one which |
4354 | | // comes later in the source order. |
4355 | 3 | diagnose(seenPlatforms[Platform], |
4356 | 3 | diag::attr_contains_multiple_versions_for_platform, Attr, |
4357 | 3 | platformString(Platform)); |
4358 | 3 | return; |
4359 | 3 | } |
4360 | 1.08k | if (!D->getDeclContext()->isModuleScopeContext()) { |
4361 | 3 | diagnose(AtLoc, diag::originally_definedin_topleve_decl, Attr); |
4362 | 3 | return; |
4363 | 3 | } |
4364 | | |
4365 | 1.08k | if (diagnoseMissingAvailability(Attr, Platform)) |
4366 | 9 | return; |
4367 | | |
4368 | 1.07k | auto IntroVer = D->getIntroducedOSVersion(Platform); |
4369 | 1.07k | if (IntroVer.value() > Attr->MovedVersion) { |
4370 | 3 | diagnose(AtLoc, |
4371 | 3 | diag::originally_definedin_must_not_before_available_version); |
4372 | 3 | return; |
4373 | 3 | } |
4374 | 1.07k | } |
4375 | 1.09k | } |
4376 | | |
4377 | 4.85M | void AttributeChecker::checkAvailableAttrs(ArrayRef<AvailableAttr *> Attrs) { |
4378 | 4.85M | if (Attrs.empty()) |
4379 | 4.68M | return; |
4380 | | |
4381 | | // Only diagnose top level decls since nested ones may have inherited availability. |
4382 | 166k | if (!D->getDeclContext()->getInnermostDeclarationDeclContext()) { |
4383 | | // If all available are spi available, we should use @_spi instead. |
4384 | 91.3k | if (std::all_of(Attrs.begin(), Attrs.end(), [](AvailableAttr *AV) { |
4385 | 91.3k | return AV->IsSPI; |
4386 | 91.3k | })) { |
4387 | 15 | diagnose(D->getLoc(), diag::spi_preferred_over_spi_available); |
4388 | 15 | } |
4389 | 91.2k | } |
4390 | 166k | } |
4391 | | |
4392 | | void AttributeChecker::checkBackDeployedAttrs( |
4393 | 4.85M | ArrayRef<BackDeployedAttr *> Attrs) { |
4394 | 4.85M | if (Attrs.empty()) |
4395 | 4.85M | return; |
4396 | | |
4397 | | // Diagnose conflicting attributes. @_alwaysEmitIntoClient and @_transparent |
4398 | | // conflict with back deployment because they each cause the body of a |
4399 | | // function to always be copied into the client and would defeat the goal of |
4400 | | // back deployment, which is to use the ABI version of the declaration when it |
4401 | | // is available. |
4402 | 930 | if (auto *AEICA = D->getAttrs().getAttribute<AlwaysEmitIntoClientAttr>()) { |
4403 | 3 | diagnoseAndRemoveAttr(AEICA, diag::attr_incompatible_with_back_deploy, |
4404 | 3 | AEICA, D->getDescriptiveKind()); |
4405 | 3 | } |
4406 | | |
4407 | 930 | if (auto *TA = D->getAttrs().getAttribute<TransparentAttr>()) { |
4408 | 3 | diagnoseAndRemoveAttr(TA, diag::attr_incompatible_with_back_deploy, TA, |
4409 | 3 | D->getDescriptiveKind()); |
4410 | 3 | } |
4411 | | |
4412 | | // Only functions, methods, computed properties, and subscripts are |
4413 | | // back-deployable, so D should be ValueDecl. |
4414 | 930 | auto *VD = cast<ValueDecl>(D); |
4415 | 930 | std::map<PlatformKind, SourceLoc> seenPlatforms; |
4416 | | |
4417 | 930 | auto *ActiveAttr = D->getAttrs().getBackDeployed(Ctx); |
4418 | | |
4419 | 1.78k | for (auto *Attr : Attrs) { |
4420 | | // Back deployment only makes sense for public declarations. |
4421 | 1.78k | if (diagnoseAndRemoveAttrIfDeclIsNonPublic(Attr, /*isError=*/true)) |
4422 | 12 | continue; |
4423 | | |
4424 | 1.77k | if (isa<DestructorDecl>(D)) { |
4425 | 3 | diagnoseAndRemoveAttr(Attr, diag::attr_invalid_on_decl_kind, Attr, |
4426 | 3 | D->getDescriptiveKind()); |
4427 | 3 | continue; |
4428 | 3 | } |
4429 | | |
4430 | 1.76k | if (VD->isObjC()) { |
4431 | 27 | diagnoseAndRemoveAttr(Attr, diag::attr_incompatible_with_objc, Attr, |
4432 | 27 | D->getDescriptiveKind()); |
4433 | 27 | continue; |
4434 | 27 | } |
4435 | | |
4436 | | // If the decl isn't effectively final then it could be invoked via dynamic |
4437 | | // dispatch. |
4438 | 1.74k | if (D->isSyntacticallyOverridable()) { |
4439 | 6 | diagnose(Attr->getLocation(), diag::attr_incompatible_with_non_final, |
4440 | 6 | Attr, D->getDescriptiveKind()); |
4441 | 6 | continue; |
4442 | 6 | } |
4443 | | |
4444 | | // Some methods declared in classes aren't syntactically overridable but |
4445 | | // still may have vtable entries, implying dynamic dispatch. |
4446 | 1.73k | if (auto *AFD = dyn_cast<AbstractFunctionDecl>(D)) { |
4447 | 1.59k | if (isa<ClassDecl>(D->getDeclContext()) && AFD->needsNewVTableEntry()) { |
4448 | 6 | diagnose(Attr->getLocation(), diag::attr_incompatible_with_non_final, |
4449 | 6 | Attr, D->getDescriptiveKind()); |
4450 | 6 | continue; |
4451 | 6 | } |
4452 | 1.59k | } |
4453 | | |
4454 | | // If the decl is final but overrides another decl, that also indicates it |
4455 | | // could be invoked via dynamic dispatch. |
4456 | 1.72k | if (VD->getOverriddenDecl()) { |
4457 | 3 | diagnoseAndRemoveAttr(Attr, diag::attr_incompatible_with_override, Attr); |
4458 | 3 | continue; |
4459 | 3 | } |
4460 | | |
4461 | 1.72k | if (auto *VarD = dyn_cast<VarDecl>(D)) { |
4462 | | // There must be a function body to back deploy so for vars we require |
4463 | | // that they be computed in order to allow back deployment. |
4464 | 114 | if (VarD->hasStorageOrWrapsStorage()) { |
4465 | 9 | diagnoseAndRemoveAttr(Attr, diag::attr_not_on_stored_properties, Attr); |
4466 | 9 | continue; |
4467 | 9 | } |
4468 | 114 | } |
4469 | | |
4470 | 1.71k | if (VD->getOpaqueResultTypeDecl()) { |
4471 | 42 | diagnoseAndRemoveAttr(Attr, |
4472 | 42 | diag::backdeployed_opaque_result_not_supported, |
4473 | 42 | Attr, D->getDescriptiveKind()) |
4474 | 42 | .warnInSwiftInterface(D->getDeclContext()); |
4475 | 42 | continue; |
4476 | 42 | } |
4477 | | |
4478 | 1.67k | auto AtLoc = Attr->AtLoc; |
4479 | 1.67k | auto Platform = Attr->Platform; |
4480 | | |
4481 | 1.67k | if (!seenPlatforms.insert({Platform, AtLoc}).second) { |
4482 | | // We've seen the platform before, emit error to the previous one which |
4483 | | // comes later in the source order. |
4484 | 6 | diagnose(seenPlatforms[Platform], |
4485 | 6 | diag::attr_contains_multiple_versions_for_platform, Attr, |
4486 | 6 | platformString(Platform)); |
4487 | 6 | continue; |
4488 | 6 | } |
4489 | | |
4490 | 1.66k | if (Ctx.LangOpts.DisableAvailabilityChecking) |
4491 | 732 | continue; |
4492 | | |
4493 | | // Availability conflicts can only be diagnosed for attributes that apply |
4494 | | // to the active platform. |
4495 | 936 | if (Attr != ActiveAttr) |
4496 | 306 | continue; |
4497 | | |
4498 | | // Unavailable decls cannot be back deployed. |
4499 | 630 | if (auto unavailableAttrPair = VD->getSemanticUnavailableAttr()) { |
4500 | 18 | auto unavailableAttr = unavailableAttrPair.value().first; |
4501 | | |
4502 | 18 | if (unavailableAttr->Platform == PlatformKind::none || |
4503 | 18 | unavailableAttr->Platform == Attr->Platform) { |
4504 | 15 | diagnose(AtLoc, diag::attr_has_no_effect_on_unavailable_decl, Attr, |
4505 | 15 | VD, prettyPlatformString(Platform)); |
4506 | 15 | diagnose(unavailableAttr->AtLoc, diag::availability_marked_unavailable, |
4507 | 15 | VD) |
4508 | 15 | .highlight(unavailableAttr->getRange()); |
4509 | 15 | continue; |
4510 | 15 | } |
4511 | 18 | } |
4512 | | |
4513 | | // Verify that the decl is available before the back deployment boundary. |
4514 | | // If it's not, the attribute doesn't make sense since the back deployment |
4515 | | // fallback could never be executed at runtime. |
4516 | 615 | if (auto availableRangeAttrPair = VD->getSemanticAvailableRangeAttr()) { |
4517 | 270 | auto availableAttr = availableRangeAttrPair.value().first; |
4518 | 270 | if (Attr->Version <= availableAttr->Introduced.value()) { |
4519 | 15 | diagnose(AtLoc, diag::attr_has_no_effect_decl_not_available_before, |
4520 | 15 | Attr, VD, prettyPlatformString(Platform), |
4521 | 15 | Attr->Version); |
4522 | 15 | diagnose(availableAttr->AtLoc, diag::availability_introduced_in_version, |
4523 | 15 | VD, prettyPlatformString(availableAttr->Platform), |
4524 | 15 | *availableAttr->Introduced) |
4525 | 15 | .highlight(availableAttr->getRange()); |
4526 | 15 | continue; |
4527 | 15 | } |
4528 | 270 | } |
4529 | 615 | } |
4530 | 930 | } |
4531 | | |
4532 | | Type TypeChecker::checkReferenceOwnershipAttr(VarDecl *var, Type type, |
4533 | 3.80k | ReferenceOwnershipAttr *attr) { |
4534 | 3.80k | auto &Diags = var->getASTContext().Diags; |
4535 | 3.80k | auto *dc = var->getDeclContext(); |
4536 | | |
4537 | | // Don't check ownership attribute if the type is invalid. |
4538 | 3.80k | if (attr->isInvalid() || type->is<ErrorType>()) |
4539 | 0 | return type; |
4540 | | |
4541 | 3.80k | auto ownershipKind = attr->get(); |
4542 | | |
4543 | | // A weak variable must have type R? or R! for some ownership-capable type R. |
4544 | 3.80k | auto underlyingType = type->getOptionalObjectType(); |
4545 | 3.80k | auto isOptional = bool(underlyingType); |
4546 | | |
4547 | 3.80k | switch (optionalityOf(ownershipKind)) { |
4548 | 0 | case ReferenceOwnershipOptionality::Disallowed: |
4549 | 0 | if (isOptional) { |
4550 | 0 | var->diagnose(diag::invalid_ownership_with_optional, ownershipKind) |
4551 | 0 | .fixItReplace(attr->getRange(), "weak"); |
4552 | 0 | attr->setInvalid(); |
4553 | 0 | } |
4554 | 0 | break; |
4555 | 1.84k | case ReferenceOwnershipOptionality::Allowed: |
4556 | 1.84k | break; |
4557 | 1.95k | case ReferenceOwnershipOptionality::Required: |
4558 | 1.95k | if (var->isLet()) { |
4559 | 6 | var->diagnose(diag::invalid_ownership_is_let, ownershipKind); |
4560 | 6 | attr->setInvalid(); |
4561 | 6 | } |
4562 | | |
4563 | 1.95k | if (!isOptional) { |
4564 | 21 | attr->setInvalid(); |
4565 | | |
4566 | | // @IBOutlet has its own diagnostic when the property type is |
4567 | | // non-optional. |
4568 | 21 | if (var->getAttrs().hasAttribute<IBOutletAttr>()) |
4569 | 3 | break; |
4570 | | |
4571 | 18 | auto diag = var->diagnose(diag::invalid_ownership_not_optional, |
4572 | 18 | ownershipKind, OptionalType::get(type)); |
4573 | 18 | auto typeRange = var->getTypeSourceRangeForDiagnostics(); |
4574 | 18 | if (type->hasSimpleTypeRepr()) { |
4575 | 9 | diag.fixItInsertAfter(typeRange.End, "?"); |
4576 | 9 | } else { |
4577 | 9 | diag.fixItInsert(typeRange.Start, "(") |
4578 | 9 | .fixItInsertAfter(typeRange.End, ")?"); |
4579 | 9 | } |
4580 | 18 | } |
4581 | 1.95k | break; |
4582 | 3.80k | } |
4583 | | |
4584 | 3.80k | if (!underlyingType) |
4585 | 1.79k | underlyingType = type; |
4586 | | |
4587 | 3.80k | auto sig = var->getDeclContext()->getGenericSignatureOfContext(); |
4588 | 3.80k | if (!underlyingType->allowsOwnership(sig.getPointer())) { |
4589 | 201 | auto D = diag::invalid_ownership_type; |
4590 | | |
4591 | 201 | if (underlyingType->isExistentialType() || |
4592 | 201 | underlyingType->isTypeParameter()) { |
4593 | | // Suggest the possibility of adding a class bound. |
4594 | 18 | D = diag::invalid_ownership_protocol_type; |
4595 | 18 | } |
4596 | | |
4597 | 201 | var->diagnose(D, ownershipKind, underlyingType); |
4598 | 201 | attr->setInvalid(); |
4599 | 201 | } |
4600 | | |
4601 | 3.80k | ClassDecl *underlyingClass = underlyingType->getClassOrBoundGenericClass(); |
4602 | 3.80k | if (underlyingClass && underlyingClass->isIncompatibleWithWeakReferences()) { |
4603 | 24 | Diags |
4604 | 24 | .diagnose(attr->getLocation(), |
4605 | 24 | diag::invalid_ownership_incompatible_class, underlyingType, |
4606 | 24 | ownershipKind) |
4607 | 24 | .fixItRemove(attr->getRange()); |
4608 | 24 | attr->setInvalid(); |
4609 | 24 | } |
4610 | | |
4611 | 3.80k | auto PDC = dyn_cast<ProtocolDecl>(dc); |
4612 | 3.80k | if (PDC && !PDC->isObjC()) { |
4613 | | // Ownership does not make sense in protocols, except for "weak" on |
4614 | | // properties of Objective-C protocols. |
4615 | 27 | auto D = diag::ownership_invalid_in_protocols; |
4616 | 27 | Diags.diagnose(attr->getLocation(), D, ownershipKind) |
4617 | 27 | .warnUntilSwiftVersion(5) |
4618 | 27 | .fixItRemove(attr->getRange()); |
4619 | 27 | attr->setInvalid(); |
4620 | 27 | } |
4621 | | |
4622 | 3.80k | if (attr->isInvalid()) |
4623 | 258 | return type; |
4624 | | |
4625 | | // Change the type to the appropriate reference storage type. |
4626 | 3.54k | return ReferenceStorageType::get(type, ownershipKind, var->getASTContext()); |
4627 | 3.80k | } |
4628 | | |
4629 | | llvm::Optional<Diag<>> |
4630 | 14.3k | TypeChecker::diagnosticIfDeclCannotBePotentiallyUnavailable(const Decl *D) { |
4631 | 14.3k | auto *DC = D->getDeclContext(); |
4632 | | |
4633 | | // A destructor is always called if declared. |
4634 | 14.3k | if (auto *DD = dyn_cast<DestructorDecl>(D)) |
4635 | 9 | return diag::availability_deinit_no_potential; |
4636 | | |
4637 | 14.3k | if (auto *VD = dyn_cast<VarDecl>(D)) { |
4638 | 1.88k | if (!VD->hasStorageOrWrapsStorage()) |
4639 | 930 | return llvm::None; |
4640 | | |
4641 | | // Do not permit potential availability of script-mode global variables; |
4642 | | // their initializer expression is not lazily evaluated, so this would |
4643 | | // not be safe. |
4644 | 954 | if (VD->isTopLevelGlobal()) |
4645 | 15 | return diag::availability_global_script_no_potential; |
4646 | | |
4647 | | // Globals and statics are lazily initialized, so they are safe |
4648 | | // for potential unavailability. |
4649 | 939 | if (!VD->isStatic() && !DC->isModuleScopeContext()) |
4650 | 810 | return diag::availability_stored_property_no_potential; |
4651 | | |
4652 | 12.4k | } else if (auto *EED = dyn_cast<EnumElementDecl>(D)) { |
4653 | | // An enum element with an associated value cannot be potentially |
4654 | | // unavailable. |
4655 | 273 | if (EED->hasAssociatedValues()) { |
4656 | 225 | auto *SF = DC->getParentSourceFile(); |
4657 | | |
4658 | 225 | if (SF->Kind == SourceFileKind::Interface) { |
4659 | 0 | return diag::availability_enum_element_no_potential_warn; |
4660 | 225 | } else { |
4661 | 225 | return diag::availability_enum_element_no_potential; |
4662 | 225 | } |
4663 | 225 | } |
4664 | 273 | } |
4665 | | |
4666 | 12.3k | return llvm::None; |
4667 | 14.3k | } |
4668 | | |
4669 | | llvm::Optional<Diag<>> |
4670 | 4.76k | TypeChecker::diagnosticIfDeclCannotBeUnavailable(const Decl *D) { |
4671 | 4.76k | auto parentIsUnavailable = [](const Decl *D) -> bool { |
4672 | 186 | if (auto *parent = |
4673 | 186 | AvailabilityInference::parentDeclForInferredAvailability(D)) { |
4674 | 72 | return parent->getSemanticUnavailableAttr() != llvm::None; |
4675 | 72 | } |
4676 | 114 | return false; |
4677 | 186 | }; |
4678 | | |
4679 | | // A destructor is always called if declared. |
4680 | 4.76k | if (auto *DD = dyn_cast<DestructorDecl>(D)) { |
4681 | 12 | if (parentIsUnavailable(D)) |
4682 | 6 | return llvm::None; |
4683 | | |
4684 | 6 | return diag::availability_deinit_no_unavailable; |
4685 | 12 | } |
4686 | | |
4687 | 4.74k | if (auto *VD = dyn_cast<VarDecl>(D)) { |
4688 | 552 | if (!VD->hasStorageOrWrapsStorage()) |
4689 | 378 | return llvm::None; |
4690 | | |
4691 | 174 | if (parentIsUnavailable(D)) |
4692 | 9 | return llvm::None; |
4693 | | |
4694 | | // Do not permit unavailable script-mode global variables; their initializer |
4695 | | // expression is not lazily evaluated, so this would not be safe. |
4696 | 165 | if (VD->isTopLevelGlobal()) |
4697 | 9 | return diag::availability_global_script_no_unavailable; |
4698 | | |
4699 | | // Globals and statics are lazily initialized, so they are safe for |
4700 | | // unavailability. |
4701 | 156 | if (!VD->isStatic() && !D->getDeclContext()->isModuleScopeContext()) |
4702 | 18 | return diag::availability_stored_property_no_unavailable; |
4703 | 156 | } |
4704 | | |
4705 | 4.33k | return llvm::None; |
4706 | 4.74k | } |
4707 | | |
4708 | 2.76k | static bool shouldBlockImplicitDynamic(Decl *D) { |
4709 | 2.76k | if (D->getAttrs().hasAttribute<SILGenNameAttr>() || |
4710 | 2.76k | D->getAttrs().hasAttribute<TransparentAttr>() || |
4711 | 2.76k | D->getAttrs().hasAttribute<InlinableAttr>()) |
4712 | 18 | return true; |
4713 | 2.75k | return false; |
4714 | 2.76k | } |
4715 | 6.20M | void TypeChecker::addImplicitDynamicAttribute(Decl *D) { |
4716 | 6.20M | if (!D->getModuleContext()->isImplicitDynamicEnabled()) |
4717 | 6.19M | return; |
4718 | | |
4719 | | // Add the attribute if the decl kind allows it and it is not an accessor |
4720 | | // decl. Accessor decls should always infer the var/subscript's attribute. |
4721 | 3.72k | if (!DeclAttribute::canAttributeAppearOnDecl(DAK_Dynamic, D) || |
4722 | 3.72k | isa<AccessorDecl>(D)) |
4723 | 1.69k | return; |
4724 | | |
4725 | | // Don't add dynamic if decl is inlinable or transparent. |
4726 | 2.02k | if (shouldBlockImplicitDynamic(D)) |
4727 | 12 | return; |
4728 | | |
4729 | 2.01k | if (auto *FD = dyn_cast<FuncDecl>(D)) { |
4730 | | // Don't add dynamic to defer bodies. |
4731 | 654 | if (FD->isDeferBody()) |
4732 | 3 | return; |
4733 | | // Don't add dynamic to functions with a cdecl. |
4734 | 651 | if (FD->getAttrs().hasAttribute<CDeclAttr>()) |
4735 | 3 | return; |
4736 | | // Don't add dynamic to local function definitions. |
4737 | 648 | if (!FD->getDeclContext()->isTypeContext() && |
4738 | 648 | FD->getDeclContext()->isLocalContext()) |
4739 | 9 | return; |
4740 | 648 | } |
4741 | | |
4742 | | // Don't add dynamic if accessor is inlinable or transparent. |
4743 | 2.00k | if (auto *asd = dyn_cast<AbstractStorageDecl>(D)) { |
4744 | 969 | bool blocked = false; |
4745 | 969 | asd->visitParsedAccessors([&](AccessorDecl *accessor) { |
4746 | 741 | blocked |= shouldBlockImplicitDynamic(accessor); |
4747 | 741 | }); |
4748 | 969 | if (blocked) |
4749 | 6 | return; |
4750 | 969 | } |
4751 | | |
4752 | 1.99k | if (auto *VD = dyn_cast<VarDecl>(D)) { |
4753 | | // Don't turn stored into computed properties. This could conflict with |
4754 | | // exclusivity checking. |
4755 | | // If there is a didSet or willSet function we allow dynamic replacement. |
4756 | 795 | if (VD->hasStorage() && |
4757 | 795 | !VD->getParsedAccessor(AccessorKind::DidSet) && |
4758 | 795 | !VD->getParsedAccessor(AccessorKind::WillSet)) |
4759 | 354 | return; |
4760 | | // Don't add dynamic to local variables. |
4761 | 441 | if (VD->getDeclContext()->isLocalContext()) |
4762 | 0 | return; |
4763 | | // Don't add to implicit variables. |
4764 | 441 | if (VD->isImplicit()) |
4765 | 66 | return; |
4766 | 441 | } |
4767 | | |
4768 | 1.57k | if (!D->getAttrs().hasAttribute<DynamicAttr>() && |
4769 | 1.57k | !D->getAttrs().hasAttribute<DynamicReplacementAttr>()) { |
4770 | 714 | auto attr = new (D->getASTContext()) DynamicAttr(/*implicit=*/true); |
4771 | 714 | D->getAttrs().add(attr); |
4772 | 714 | } |
4773 | 1.57k | } |
4774 | | |
4775 | | ValueDecl * |
4776 | | DynamicallyReplacedDeclRequest::evaluate(Evaluator &evaluator, |
4777 | 6.25M | ValueDecl *VD) const { |
4778 | | // Dynamic replacements must be explicit. |
4779 | 6.25M | if (VD->isImplicit()) |
4780 | 747k | return nullptr; |
4781 | | |
4782 | 5.50M | auto *attr = VD->getAttrs().getAttribute<DynamicReplacementAttr>(); |
4783 | 5.50M | if (!attr) { |
4784 | | // It's likely that the accessor isn't annotated but its storage is. |
4785 | 5.50M | if (auto *AD = dyn_cast<AccessorDecl>(VD)) { |
4786 | | // Try to grab the attribute from the storage. |
4787 | 265k | attr = AD->getStorage()->getAttrs().getAttribute<DynamicReplacementAttr>(); |
4788 | 265k | } |
4789 | | |
4790 | 5.50M | if (!attr) { |
4791 | | // Otherwise, it's not dynamically replacing anything. |
4792 | 5.50M | return nullptr; |
4793 | 5.50M | } |
4794 | 5.50M | } |
4795 | | |
4796 | | // If the attribute is invalid, bail. |
4797 | 2.08k | if (attr->isInvalid()) |
4798 | 0 | return nullptr; |
4799 | | |
4800 | | // If we can lazily resolve the function, do so now. |
4801 | 2.08k | if (auto *LazyResolver = attr->Resolver) { |
4802 | 417 | auto decl = LazyResolver->loadDynamicallyReplacedFunctionDecl( |
4803 | 417 | attr, attr->ResolverContextData); |
4804 | 417 | attr->Resolver = nullptr; |
4805 | 417 | return decl; |
4806 | 417 | } |
4807 | | |
4808 | 1.66k | auto &Ctx = VD->getASTContext(); |
4809 | 1.66k | if (auto *AD = dyn_cast<AccessorDecl>(VD)) { |
4810 | 453 | return findReplacedAccessor(attr->getReplacedFunctionName(), AD, attr, Ctx); |
4811 | 453 | } |
4812 | | |
4813 | 1.21k | if (auto *AFD = dyn_cast<AbstractFunctionDecl>(VD)) { |
4814 | 903 | return findReplacedFunction(attr->getReplacedFunctionName(), AFD, |
4815 | 903 | attr, &Ctx.Diags); |
4816 | 903 | } |
4817 | | |
4818 | 312 | if (auto *SD = dyn_cast<AbstractStorageDecl>(VD)) { |
4819 | 312 | return findReplacedStorageDecl(attr->getReplacedFunctionName(), SD, attr); |
4820 | 312 | } |
4821 | | |
4822 | 0 | return nullptr; |
4823 | 312 | } |
4824 | | |
4825 | | ValueDecl * |
4826 | | SpecializeAttrTargetDeclRequest::evaluate(Evaluator &evaluator, |
4827 | | const ValueDecl *vd, |
4828 | 39.7k | SpecializeAttr *attr) const { |
4829 | 39.7k | if (auto *lazyResolver = attr->resolver) { |
4830 | 33.2k | auto *decl = |
4831 | 33.2k | lazyResolver->loadTargetFunctionDecl(attr, attr->resolverContextData); |
4832 | 33.2k | attr->resolver = nullptr; |
4833 | 33.2k | return decl; |
4834 | 33.2k | } |
4835 | | |
4836 | 6.51k | auto &ctx = vd->getASTContext(); |
4837 | | |
4838 | 6.51k | auto targetFunctionName = attr->getTargetFunctionName(); |
4839 | 6.51k | if (!targetFunctionName) |
4840 | 4.98k | return nullptr; |
4841 | | |
4842 | 1.52k | if (auto *ad = dyn_cast<AccessorDecl>(vd)) { |
4843 | 774 | return findTargetAccessor(targetFunctionName, ad, attr, ctx); |
4844 | 774 | } |
4845 | | |
4846 | 750 | if (auto *afd = dyn_cast<AbstractFunctionDecl>(vd)) { |
4847 | 750 | return findTargetFunction(targetFunctionName, afd, attr, &ctx.Diags); |
4848 | 750 | } |
4849 | | |
4850 | 0 | return nullptr; |
4851 | | |
4852 | 750 | } |
4853 | | /// Returns true if the given type conforms to `Differentiable` in the given |
4854 | | /// context. If `tangentVectorEqualsSelf` is true, also check whether the given |
4855 | | /// type satisfies `TangentVector == Self`. |
4856 | | static bool conformsToDifferentiable(Type type, ModuleDecl *module, |
4857 | 7.58k | bool tangentVectorEqualsSelf = false) { |
4858 | 7.58k | auto &ctx = module->getASTContext(); |
4859 | 7.58k | auto *differentiableProto = |
4860 | 7.58k | ctx.getProtocol(KnownProtocolKind::Differentiable); |
4861 | 7.58k | auto conf = TypeChecker::conformsToProtocol(type, differentiableProto, module); |
4862 | 7.58k | if (conf.isInvalid()) |
4863 | 896 | return false; |
4864 | 6.68k | if (!tangentVectorEqualsSelf) |
4865 | 5.39k | return true; |
4866 | 1.29k | auto tanType = conf.getTypeWitnessByName(type, ctx.Id_TangentVector); |
4867 | 1.29k | return type->isEqual(tanType); |
4868 | 6.68k | } |
4869 | | |
4870 | | IndexSubset *TypeChecker::inferDifferentiabilityParameters( |
4871 | 3.31k | AbstractFunctionDecl *AFD, GenericEnvironment *derivativeGenEnv) { |
4872 | 3.31k | auto *module = AFD->getParentModule(); |
4873 | 3.31k | auto &ctx = module->getASTContext(); |
4874 | 3.31k | auto *functionType = AFD->getInterfaceType()->castTo<AnyFunctionType>(); |
4875 | 3.31k | auto numUncurriedParams = functionType->getNumParams(); |
4876 | 3.31k | if (auto *resultFnType = |
4877 | 3.31k | functionType->getResult()->getAs<AnyFunctionType>()) { |
4878 | 1.93k | numUncurriedParams += resultFnType->getNumParams(); |
4879 | 1.93k | } |
4880 | 3.31k | llvm::SmallBitVector parameterBits(numUncurriedParams); |
4881 | 3.31k | SmallVector<Type, 4> allParamTypes; |
4882 | | |
4883 | | // Returns true if the i-th parameter type is differentiable. |
4884 | 5.52k | auto isDifferentiableParam = [&](unsigned i) -> bool { |
4885 | 5.52k | if (i >= allParamTypes.size()) |
4886 | 0 | return false; |
4887 | 5.52k | auto paramType = allParamTypes[i]; |
4888 | 5.52k | if (derivativeGenEnv) |
4889 | 2.06k | paramType = derivativeGenEnv->mapTypeIntoContext(paramType); |
4890 | 3.46k | else |
4891 | 3.46k | paramType = AFD->mapTypeIntoContext(paramType); |
4892 | | // Return false for existential types. |
4893 | 5.52k | if (paramType->isExistentialType()) |
4894 | 0 | return false; |
4895 | | // Return true if the type conforms to `Differentiable`. |
4896 | 5.52k | return conformsToDifferentiable(paramType, module); |
4897 | 5.52k | }; |
4898 | | |
4899 | | // Get all parameter types. |
4900 | | // NOTE: To be robust, result function type parameters should be added only if |
4901 | | // `functionType` comes from a static/instance method, and not a free function |
4902 | | // returning a function type. In practice, this code path should not be |
4903 | | // reachable for free functions returning a function type. |
4904 | 3.31k | if (auto resultFnType = functionType->getResult()->getAs<AnyFunctionType>()) |
4905 | 1.93k | for (auto ¶m : resultFnType->getParams()) |
4906 | 1.75k | allParamTypes.push_back(param.getPlainType()); |
4907 | 3.31k | for (auto ¶m : functionType->getParams()) |
4908 | 3.77k | allParamTypes.push_back(param.getPlainType()); |
4909 | | |
4910 | | // Set differentiability parameters. |
4911 | 3.31k | for (unsigned i : range(parameterBits.size())) |
4912 | 5.52k | if (isDifferentiableParam(i)) |
4913 | 4.67k | parameterBits.set(i); |
4914 | | |
4915 | 3.31k | return IndexSubset::get(ctx, parameterBits); |
4916 | 3.31k | } |
4917 | | |
4918 | | /// Computes the differentiability parameter indices from the given parsed |
4919 | | /// differentiability parameters for the given original or derivative |
4920 | | /// `AbstractFunctionDecl` and derivative generic environment. On error, emits |
4921 | | /// diagnostics and returns `nullptr`. |
4922 | | /// - If parsed parameters are empty, infer parameter indices. |
4923 | | /// - Otherwise, build parameter indices from parsed parameters. |
4924 | | /// The attribute name/location are used in diagnostics. |
4925 | | static IndexSubset *computeDifferentiabilityParameters( |
4926 | | ArrayRef<ParsedAutoDiffParameter> parsedDiffParams, |
4927 | | AbstractFunctionDecl *function, GenericEnvironment *derivativeGenEnv, |
4928 | 4.84k | StringRef attrName, SourceLoc attrLoc) { |
4929 | 4.84k | auto *module = function->getParentModule(); |
4930 | 4.84k | auto &ctx = module->getASTContext(); |
4931 | 4.84k | auto &diags = ctx.Diags; |
4932 | | |
4933 | | // Get function type and parameters. |
4934 | 4.84k | auto *functionType = function->getInterfaceType()->castTo<AnyFunctionType>(); |
4935 | 4.84k | auto ¶ms = *function->getParameters(); |
4936 | 4.84k | auto numParams = function->getParameters()->size(); |
4937 | 4.84k | auto isInstanceMethod = function->isInstanceMember(); |
4938 | | |
4939 | | // Diagnose if function has no parameters. |
4940 | 4.84k | if (params.size() == 0) { |
4941 | | // If function is not an instance method, diagnose immediately. |
4942 | 772 | if (!isInstanceMethod) { |
4943 | 40 | diags |
4944 | 40 | .diagnose(attrLoc, diag::diff_function_no_parameters, function) |
4945 | 40 | .highlight(function->getSignatureSourceRange()); |
4946 | 40 | return nullptr; |
4947 | 40 | } |
4948 | | // If function is an instance method, diagnose only if `self` does not |
4949 | | // conform to `Differentiable`. |
4950 | 732 | else { |
4951 | 732 | auto selfType = function->getImplicitSelfDecl()->getInterfaceType(); |
4952 | 732 | if (derivativeGenEnv) |
4953 | 384 | selfType = derivativeGenEnv->mapTypeIntoContext(selfType); |
4954 | 348 | else |
4955 | 348 | selfType = function->mapTypeIntoContext(selfType); |
4956 | 732 | if (!conformsToDifferentiable(selfType, module)) { |
4957 | 8 | diags |
4958 | 8 | .diagnose(attrLoc, diag::diff_function_no_parameters, function) |
4959 | 8 | .highlight(function->getSignatureSourceRange()); |
4960 | 8 | return nullptr; |
4961 | 8 | } |
4962 | 732 | } |
4963 | 772 | } |
4964 | | |
4965 | | // If parsed differentiability parameters are empty, infer parameter indices |
4966 | | // from the function type. |
4967 | 4.79k | if (parsedDiffParams.empty()) |
4968 | 3.20k | return TypeChecker::inferDifferentiabilityParameters(function, |
4969 | 3.20k | derivativeGenEnv); |
4970 | | |
4971 | | // Otherwise, build parameter indices from parsed differentiability |
4972 | | // parameters. |
4973 | 1.59k | auto numUncurriedParams = functionType->getNumParams(); |
4974 | 1.59k | if (auto *resultFnType = |
4975 | 1.59k | functionType->getResult()->getAs<AnyFunctionType>()) { |
4976 | 1.11k | numUncurriedParams += resultFnType->getNumParams(); |
4977 | 1.11k | } |
4978 | 1.59k | llvm::SmallBitVector parameterBits(numUncurriedParams); |
4979 | 1.59k | int lastIndex = -1; |
4980 | 2.19k | for (unsigned i : indices(parsedDiffParams)) { |
4981 | 2.19k | auto paramLoc = parsedDiffParams[i].getLoc(); |
4982 | 2.19k | switch (parsedDiffParams[i].getKind()) { |
4983 | 1.40k | case ParsedAutoDiffParameter::Kind::Named: { |
4984 | 1.90k | auto nameIter = llvm::find_if(params.getArray(), [&](ParamDecl *param) { |
4985 | 1.90k | return param->getName() == parsedDiffParams[i].getName(); |
4986 | 1.90k | }); |
4987 | | // Parameter name must exist. |
4988 | 1.40k | if (nameIter == params.end()) { |
4989 | 8 | diags.diagnose(paramLoc, diag::diff_params_clause_param_name_unknown, |
4990 | 8 | parsedDiffParams[i].getName()); |
4991 | 8 | return nullptr; |
4992 | 8 | } |
4993 | | // Parameter names must be specified in the original order. |
4994 | 1.39k | unsigned index = std::distance(params.begin(), nameIter); |
4995 | 1.39k | if ((int)index <= lastIndex) { |
4996 | 32 | diags.diagnose(paramLoc, |
4997 | 32 | diag::diff_params_clause_params_not_original_order); |
4998 | 32 | return nullptr; |
4999 | 32 | } |
5000 | 1.36k | parameterBits.set(index); |
5001 | 1.36k | lastIndex = index; |
5002 | 1.36k | break; |
5003 | 1.39k | } |
5004 | 604 | case ParsedAutoDiffParameter::Kind::Self: { |
5005 | | // 'self' is only applicable to instance methods. |
5006 | 604 | if (!isInstanceMethod) { |
5007 | 16 | diags.diagnose(paramLoc, |
5008 | 16 | diag::diff_params_clause_self_instance_method_only); |
5009 | 16 | return nullptr; |
5010 | 16 | } |
5011 | | // 'self' can only be the first in the list. |
5012 | 588 | if (i > 0) { |
5013 | 8 | diags.diagnose(paramLoc, diag::diff_params_clause_self_must_be_first); |
5014 | 8 | return nullptr; |
5015 | 8 | } |
5016 | 580 | parameterBits.set(parameterBits.size() - 1); |
5017 | 580 | break; |
5018 | 588 | } |
5019 | 184 | case ParsedAutoDiffParameter::Kind::Ordered: { |
5020 | 184 | auto index = parsedDiffParams[i].getIndex(); |
5021 | 184 | if (index >= numParams) { |
5022 | 24 | diags.diagnose(paramLoc, |
5023 | 24 | diag::diff_params_clause_param_index_out_of_range); |
5024 | 24 | return nullptr; |
5025 | 24 | } |
5026 | | // Parameter names must be specified in the original order. |
5027 | 160 | if ((int)index <= lastIndex) { |
5028 | 32 | diags.diagnose(paramLoc, |
5029 | 32 | diag::diff_params_clause_params_not_original_order); |
5030 | 32 | return nullptr; |
5031 | 32 | } |
5032 | 128 | parameterBits.set(index); |
5033 | 128 | lastIndex = index; |
5034 | 128 | break; |
5035 | 160 | } |
5036 | 2.19k | } |
5037 | 2.19k | } |
5038 | 1.47k | return IndexSubset::get(ctx, parameterBits); |
5039 | 1.59k | } |
5040 | | |
5041 | | /// Returns the `DescriptiveDeclKind` corresponding to the given `AccessorKind`. |
5042 | | /// Used for diagnostics. |
5043 | 32 | static DescriptiveDeclKind getAccessorDescriptiveDeclKind(AccessorKind kind) { |
5044 | 32 | switch (kind) { |
5045 | 16 | case AccessorKind::Get: |
5046 | 16 | return DescriptiveDeclKind::Getter; |
5047 | 8 | case AccessorKind::Set: |
5048 | 8 | return DescriptiveDeclKind::Setter; |
5049 | 0 | case AccessorKind::Read: |
5050 | 0 | return DescriptiveDeclKind::ReadAccessor; |
5051 | 8 | case AccessorKind::Modify: |
5052 | 8 | return DescriptiveDeclKind::ModifyAccessor; |
5053 | 0 | case AccessorKind::WillSet: |
5054 | 0 | return DescriptiveDeclKind::WillSet; |
5055 | 0 | case AccessorKind::DidSet: |
5056 | 0 | return DescriptiveDeclKind::DidSet; |
5057 | 0 | case AccessorKind::Address: |
5058 | 0 | return DescriptiveDeclKind::Addressor; |
5059 | 0 | case AccessorKind::MutableAddress: |
5060 | 0 | return DescriptiveDeclKind::MutableAddressor; |
5061 | 0 | case AccessorKind::Init: |
5062 | 0 | return DescriptiveDeclKind::InitAccessor; |
5063 | 32 | } |
5064 | 32 | } |
5065 | | |
5066 | | /// An abstract function declaration lookup error. |
5067 | | enum class AbstractFunctionDeclLookupErrorKind { |
5068 | | /// No lookup candidates could be found. |
5069 | | NoCandidatesFound, |
5070 | | /// There are multiple valid lookup candidates. |
5071 | | CandidatesAmbiguous, |
5072 | | /// Lookup candidate does not have the expected type. |
5073 | | CandidateTypeMismatch, |
5074 | | /// Lookup candidate is in the wrong type context. |
5075 | | CandidateWrongTypeContext, |
5076 | | /// Lookup candidate does not have the requested accessor. |
5077 | | CandidateMissingAccessor, |
5078 | | /// Lookup candidate is a protocol requirement. |
5079 | | CandidateProtocolRequirement, |
5080 | | /// Lookup candidate could be resolved to an `AbstractFunctionDecl`. |
5081 | | CandidateNotFunctionDeclaration |
5082 | | }; |
5083 | | |
5084 | | /// Returns the original function (in the context of a derivative or transpose |
5085 | | /// function) declaration corresponding to the given base type (optional), |
5086 | | /// function name, lookup context, and the expected original function type. |
5087 | | /// |
5088 | | /// If the base type of the function is specified, member lookup is performed. |
5089 | | /// Otherwise, unqualified lookup is performed. |
5090 | | /// |
5091 | | /// If the expected original function type has a generic signature, any |
5092 | | /// candidate with a less constrained type signature than the expected original |
5093 | | /// function type will be treated as a viable candidate. |
5094 | | /// |
5095 | | /// If the function declaration cannot be resolved, emits a diagnostic and |
5096 | | /// returns nullptr. |
5097 | | /// |
5098 | | /// Used for resolving the referenced declaration in `@derivative` and |
5099 | | /// `@transpose` attributes. |
5100 | | static AbstractFunctionDecl *findAutoDiffOriginalFunctionDecl( |
5101 | | DeclAttribute *attr, Type baseType, DeclNameRefWithLoc funcNameWithLoc, |
5102 | | DeclContext *lookupContext, NameLookupOptions lookupOptions, |
5103 | | const llvm::function_ref< |
5104 | | llvm::Optional<AbstractFunctionDeclLookupErrorKind>( |
5105 | | AbstractFunctionDecl *)> &isValidCandidate, |
5106 | 2.26k | AnyFunctionType *expectedOriginalFnType) { |
5107 | 2.26k | assert(lookupContext); |
5108 | 0 | auto &ctx = lookupContext->getASTContext(); |
5109 | 2.26k | auto &diags = ctx.Diags; |
5110 | | |
5111 | 2.26k | auto funcName = funcNameWithLoc.Name; |
5112 | 2.26k | auto funcNameLoc = funcNameWithLoc.Loc; |
5113 | 2.26k | auto maybeAccessorKind = funcNameWithLoc.AccessorKind; |
5114 | | |
5115 | | // Perform lookup. |
5116 | 2.26k | LookupResult results; |
5117 | | // If `baseType` is not null but `lookupContext` is a type context, set |
5118 | | // `baseType` to the `self` type of `lookupContext` to perform member lookup. |
5119 | 2.26k | if (!baseType && lookupContext->isTypeContext()) |
5120 | 1.10k | baseType = lookupContext->getSelfTypeInContext(); |
5121 | 2.26k | if (baseType) { |
5122 | 1.38k | results = TypeChecker::lookupMember(lookupContext, baseType, funcName); |
5123 | 1.38k | } else { |
5124 | 884 | results = TypeChecker::lookupUnqualified( |
5125 | 884 | lookupContext, funcName, funcNameLoc.getBaseNameLoc(), lookupOptions); |
5126 | 884 | } |
5127 | | |
5128 | | // Error if no candidates were found. |
5129 | 2.26k | if (results.empty()) { |
5130 | 32 | diags.diagnose(funcNameLoc, diag::cannot_find_in_scope, funcName, |
5131 | 32 | funcName.isOperator()); |
5132 | 32 | return nullptr; |
5133 | 32 | } |
5134 | | |
5135 | | // Track invalid and valid candidates. |
5136 | 2.23k | using LookupErrorKind = AbstractFunctionDeclLookupErrorKind; |
5137 | 2.23k | SmallVector<std::pair<ValueDecl *, LookupErrorKind>, 2> invalidCandidates; |
5138 | 2.23k | SmallVector<AbstractFunctionDecl *, 2> validCandidates; |
5139 | | |
5140 | | // Filter lookup results. |
5141 | 2.60k | for (auto choice : results) { |
5142 | 2.60k | auto *decl = choice.getValueDecl(); |
5143 | | // Cast the candidate to an `AbstractFunctionDecl`. |
5144 | 2.60k | auto *candidate = dyn_cast<AbstractFunctionDecl>(decl); |
5145 | | // If the candidate is an `AbstractStorageDecl`, use one of its accessors as |
5146 | | // the candidate. |
5147 | 2.60k | if (auto *asd = dyn_cast<AbstractStorageDecl>(decl)) { |
5148 | | // If accessor kind is specified, use corresponding accessor from the |
5149 | | // candidate. Otherwise, use the getter by default. |
5150 | 440 | auto accessorKind = maybeAccessorKind.value_or(AccessorKind::Get); |
5151 | 440 | candidate = asd->getOpaqueAccessor(accessorKind); |
5152 | | // Error if candidate is missing the requested accessor. |
5153 | 440 | if (!candidate) { |
5154 | 28 | invalidCandidates.push_back( |
5155 | 28 | {decl, LookupErrorKind::CandidateMissingAccessor}); |
5156 | 28 | continue; |
5157 | 28 | } |
5158 | 440 | } |
5159 | | // Error if the candidate is not an `AbstractStorageDecl` but an accessor is |
5160 | | // requested. |
5161 | 2.16k | else if (maybeAccessorKind.has_value()) { |
5162 | 8 | invalidCandidates.push_back( |
5163 | 8 | {decl, LookupErrorKind::CandidateMissingAccessor}); |
5164 | 8 | continue; |
5165 | 8 | } |
5166 | | // Error if candidate is not a `AbstractFunctionDecl`. |
5167 | 2.56k | if (!candidate) { |
5168 | 0 | invalidCandidates.push_back( |
5169 | 0 | {decl, LookupErrorKind::CandidateNotFunctionDeclaration}); |
5170 | 0 | continue; |
5171 | 0 | } |
5172 | | // Error if candidate is not valid. |
5173 | 2.56k | auto invalidCandidateKind = isValidCandidate(candidate); |
5174 | 2.56k | if (invalidCandidateKind.has_value()) { |
5175 | 452 | invalidCandidates.push_back({candidate, *invalidCandidateKind}); |
5176 | 452 | continue; |
5177 | 452 | } |
5178 | | // Otherwise, record valid candidate. |
5179 | 2.11k | validCandidates.push_back(candidate); |
5180 | 2.11k | } |
5181 | | // If there are no valid candidates, emit diagnostics for invalid candidates. |
5182 | 2.23k | if (validCandidates.empty()) { |
5183 | 128 | assert(!invalidCandidates.empty()); |
5184 | 0 | diags.diagnose(funcNameLoc, diag::autodiff_attr_original_decl_none_valid, |
5185 | 128 | funcName); |
5186 | 160 | for (auto invalidCandidatePair : invalidCandidates) { |
5187 | 160 | auto *invalidCandidate = invalidCandidatePair.first; |
5188 | 160 | auto invalidCandidateKind = invalidCandidatePair.second; |
5189 | 160 | auto declKind = invalidCandidate->getDescriptiveKind(); |
5190 | 160 | switch (invalidCandidateKind) { |
5191 | 0 | case AbstractFunctionDeclLookupErrorKind::NoCandidatesFound: |
5192 | 0 | diags.diagnose(invalidCandidate, diag::cannot_find_in_scope, funcName, |
5193 | 0 | funcName.isOperator()); |
5194 | 0 | break; |
5195 | 0 | case AbstractFunctionDeclLookupErrorKind::CandidatesAmbiguous: |
5196 | 0 | diags.diagnose(invalidCandidate, diag::attr_ambiguous_reference_to_decl, |
5197 | 0 | funcName, attr->getAttrName()); |
5198 | 0 | break; |
5199 | 88 | case AbstractFunctionDeclLookupErrorKind::CandidateTypeMismatch: { |
5200 | | // If the expected original function type has a generic signature, emit |
5201 | | // "candidate does not have type equal to or less constrained than ..." |
5202 | | // diagnostic. |
5203 | | // |
5204 | | // This is significant because derivative/transpose functions may have |
5205 | | // more constrained generic signatures than their referenced original |
5206 | | // declarations. |
5207 | 88 | if (auto genSig = expectedOriginalFnType->getOptGenericSignature()) { |
5208 | 48 | diags.diagnose(invalidCandidate, |
5209 | 48 | diag::autodiff_attr_original_decl_type_mismatch, |
5210 | 48 | declKind, expectedOriginalFnType, |
5211 | 48 | /*hasGenericSignature*/ true); |
5212 | 48 | break; |
5213 | 48 | } |
5214 | | // Otherwise, emit a "candidate does not have expected type ..." error. |
5215 | 40 | diags.diagnose(invalidCandidate, |
5216 | 40 | diag::autodiff_attr_original_decl_type_mismatch, |
5217 | 40 | declKind, expectedOriginalFnType, |
5218 | 40 | /*hasGenericSignature*/ false); |
5219 | 40 | break; |
5220 | 88 | } |
5221 | 16 | case AbstractFunctionDeclLookupErrorKind::CandidateWrongTypeContext: |
5222 | 16 | diags.diagnose(invalidCandidate, |
5223 | 16 | diag::autodiff_attr_original_decl_not_same_type_context, |
5224 | 16 | declKind); |
5225 | 16 | break; |
5226 | 24 | case AbstractFunctionDeclLookupErrorKind::CandidateMissingAccessor: { |
5227 | 24 | auto accessorKind = maybeAccessorKind.value_or(AccessorKind::Get); |
5228 | 24 | auto accessorDeclKind = getAccessorDescriptiveDeclKind(accessorKind); |
5229 | 24 | diags.diagnose(invalidCandidate, |
5230 | 24 | diag::autodiff_attr_original_decl_missing_accessor, |
5231 | 24 | declKind, accessorDeclKind); |
5232 | 24 | break; |
5233 | 88 | } |
5234 | 32 | case AbstractFunctionDeclLookupErrorKind::CandidateProtocolRequirement: |
5235 | 32 | diags.diagnose(invalidCandidate, |
5236 | 32 | diag::derivative_attr_protocol_requirement_unsupported); |
5237 | 32 | break; |
5238 | 0 | case AbstractFunctionDeclLookupErrorKind::CandidateNotFunctionDeclaration: |
5239 | 0 | diags.diagnose(invalidCandidate, |
5240 | 0 | diag::autodiff_attr_original_decl_invalid_kind, |
5241 | 0 | declKind); |
5242 | 0 | break; |
5243 | 160 | } |
5244 | 160 | } |
5245 | 128 | return nullptr; |
5246 | 128 | } |
5247 | | // Error if there are multiple valid candidates. |
5248 | 2.10k | if (validCandidates.size() > 1) { |
5249 | 8 | diags.diagnose(funcNameLoc, diag::autodiff_attr_original_decl_ambiguous, |
5250 | 8 | funcName); |
5251 | 16 | for (auto *validCandidate : validCandidates) { |
5252 | 16 | auto declKind = validCandidate->getDescriptiveKind(); |
5253 | 16 | diags.diagnose(validCandidate, |
5254 | 16 | diag::autodiff_attr_original_decl_ambiguous_candidate, |
5255 | 16 | declKind); |
5256 | 16 | } |
5257 | 8 | return nullptr; |
5258 | 8 | } |
5259 | | // Success if there is one unambiguous valid candidate. |
5260 | 2.09k | return validCandidates.front(); |
5261 | 2.10k | } |
5262 | | |
5263 | | /// Checks that the `candidate` function type equals the `required` function |
5264 | | /// type, disregarding parameter labels and tuple result labels. |
5265 | | /// `checkGenericSignature` is used to check generic signatures, if specified. |
5266 | | /// Otherwise, generic signatures are checked for equality. |
5267 | | static bool checkFunctionSignature( |
5268 | 3.84k | CanAnyFunctionType required, CanType candidate) { |
5269 | | // Check that candidate is actually a function. |
5270 | 3.84k | auto candidateFnTy = dyn_cast<AnyFunctionType>(candidate); |
5271 | 3.84k | if (!candidateFnTy) |
5272 | 0 | return false; |
5273 | | |
5274 | | // Erase dynamic self types. |
5275 | 3.84k | required = dyn_cast<AnyFunctionType>(required->getCanonicalType()); |
5276 | 3.84k | candidateFnTy = dyn_cast<AnyFunctionType>(candidateFnTy->getCanonicalType()); |
5277 | | |
5278 | | // Check that generic signatures match. |
5279 | 3.84k | auto requiredGenSig = required.getOptGenericSignature(); |
5280 | 3.84k | auto candidateGenSig = candidateFnTy.getOptGenericSignature(); |
5281 | | // Check that the candidate signature's generic parameters are a subset of |
5282 | | // those of the required signature. |
5283 | 3.84k | if (requiredGenSig && candidateGenSig && |
5284 | 3.84k | candidateGenSig.getGenericParams().size() |
5285 | 936 | > requiredGenSig.getGenericParams().size()) |
5286 | 32 | return false; |
5287 | | // Check that the requirements are satisfied. |
5288 | 3.80k | if (!candidateGenSig.requirementsNotSatisfiedBy(requiredGenSig).empty()) |
5289 | 60 | return false; |
5290 | | |
5291 | | // Check that parameter types match, disregarding labels. |
5292 | 3.74k | if (required->getNumParams() != candidateFnTy->getNumParams()) |
5293 | 116 | return false; |
5294 | 3.63k | if (!std::equal(required->getParams().begin(), required->getParams().end(), |
5295 | 3.63k | candidateFnTy->getParams().begin(), |
5296 | 4.39k | [&](AnyFunctionType::Param x, AnyFunctionType::Param y) { |
5297 | 4.39k | auto xInstanceTy = x.getOldType()->getMetatypeInstanceType(); |
5298 | 4.39k | auto yInstanceTy = y.getOldType()->getMetatypeInstanceType(); |
5299 | 4.39k | return xInstanceTy->isEqual( |
5300 | 4.39k | requiredGenSig.getReducedType(yInstanceTy)); |
5301 | 4.39k | })) |
5302 | 36 | return false; |
5303 | | |
5304 | | // If required result type is not a function type, check that result types |
5305 | | // match exactly. |
5306 | 3.59k | auto requiredResultFnTy = dyn_cast<AnyFunctionType>(required.getResult()); |
5307 | 3.59k | auto candidateResultTy = |
5308 | 3.59k | requiredGenSig.getReducedType(candidateFnTy.getResult()); |
5309 | 3.59k | if (!requiredResultFnTy) { |
5310 | 2.14k | auto requiredResultTupleTy = dyn_cast<TupleType>(required.getResult()); |
5311 | 2.14k | auto candidateResultTupleTy = dyn_cast<TupleType>(candidateResultTy); |
5312 | 2.14k | if (!requiredResultTupleTy || !candidateResultTupleTy) |
5313 | 1.86k | return required.getResult()->isEqual(candidateResultTy); |
5314 | | // If result types are tuple types, check that element types match, |
5315 | | // ignoring labels. |
5316 | 280 | if (requiredResultTupleTy->getNumElements() != |
5317 | 280 | candidateResultTupleTy->getNumElements()) |
5318 | 0 | return false; |
5319 | 280 | return std::equal(requiredResultTupleTy.getElementTypes().begin(), |
5320 | 280 | requiredResultTupleTy.getElementTypes().end(), |
5321 | 280 | candidateResultTupleTy.getElementTypes().begin(), |
5322 | 280 | [](CanType x, CanType y) { return x->isEqual(y); }); |
5323 | 280 | } |
5324 | | |
5325 | | // Required result type is a function. Recurse. |
5326 | 1.44k | return checkFunctionSignature(requiredResultFnTy, candidateResultTy); |
5327 | 3.59k | } |
5328 | | |
5329 | | /// Returns an `AnyFunctionType` from the given parameters, result type, and |
5330 | | /// generic signature. |
5331 | | static AnyFunctionType * |
5332 | | makeFunctionType(ArrayRef<AnyFunctionType::Param> parameters, Type resultType, |
5333 | 3.67k | GenericSignature genericSignature) { |
5334 | | // FIXME: Verify ExtInfo state is correct, not working by accident. |
5335 | 3.67k | if (genericSignature) { |
5336 | 832 | GenericFunctionType::ExtInfo info; |
5337 | 832 | return GenericFunctionType::get(genericSignature, parameters, resultType, |
5338 | 832 | info); |
5339 | 832 | } |
5340 | 2.84k | FunctionType::ExtInfo info; |
5341 | 2.84k | return FunctionType::get(parameters, resultType, info); |
5342 | 3.67k | } |
5343 | | |
5344 | | /// Computes the original function type corresponding to the given derivative |
5345 | | /// function type. Used for `@derivative` attribute type-checking. |
5346 | | static AnyFunctionType * |
5347 | 1.74k | getDerivativeOriginalFunctionType(AnyFunctionType *derivativeFnTy) { |
5348 | | // Unwrap curry levels. At most, two parameter lists are necessary, for |
5349 | | // curried method types with a `(Self)` parameter list. |
5350 | 1.74k | SmallVector<AnyFunctionType *, 2> curryLevels; |
5351 | 1.74k | auto *currentLevel = derivativeFnTy; |
5352 | 3.49k | for (unsigned i : range(2)) { |
5353 | 3.49k | (void)i; |
5354 | 3.49k | if (currentLevel == nullptr) |
5355 | 716 | break; |
5356 | 2.78k | curryLevels.push_back(currentLevel); |
5357 | 2.78k | currentLevel = currentLevel->getResult()->getAs<AnyFunctionType>(); |
5358 | 2.78k | } |
5359 | | |
5360 | 1.74k | auto derivativeResult = curryLevels.back()->getResult()->getAs<TupleType>(); |
5361 | 1.74k | assert(derivativeResult && derivativeResult->getNumElements() == 2 && |
5362 | 1.74k | "Expected derivative result to be a two-element tuple"); |
5363 | 0 | auto originalResult = derivativeResult->getElement(0).getType(); |
5364 | 1.74k | auto *originalType = makeFunctionType( |
5365 | 1.74k | curryLevels.back()->getParams(), originalResult, |
5366 | 1.74k | curryLevels.size() == 1 ? derivativeFnTy->getOptGenericSignature() |
5367 | 1.74k | : nullptr); |
5368 | | |
5369 | | // Wrap the derivative function type in additional curry levels. |
5370 | 1.74k | auto curryLevelsWithoutLast = |
5371 | 1.74k | ArrayRef<AnyFunctionType *>(curryLevels).drop_back(1); |
5372 | 1.74k | for (auto pair : enumerate(llvm::reverse(curryLevelsWithoutLast))) { |
5373 | 1.03k | unsigned i = pair.index(); |
5374 | 1.03k | AnyFunctionType *curryLevel = pair.value(); |
5375 | 1.03k | originalType = |
5376 | 1.03k | makeFunctionType(curryLevel->getParams(), originalType, |
5377 | 1.03k | i == curryLevelsWithoutLast.size() - 1 |
5378 | 1.03k | ? derivativeFnTy->getOptGenericSignature() |
5379 | 1.03k | : nullptr); |
5380 | 1.03k | } |
5381 | 1.74k | return originalType; |
5382 | 1.74k | } |
5383 | | |
5384 | | /// Computes the original function type corresponding to the given transpose |
5385 | | /// function type. Used for `@transpose` attribute type-checking. |
5386 | | static AnyFunctionType * |
5387 | | getTransposeOriginalFunctionType(AnyFunctionType *transposeFnType, |
5388 | | IndexSubset *linearParamIndices, |
5389 | 540 | bool wrtSelf) { |
5390 | 540 | unsigned transposeParamsIndex = 0; |
5391 | | |
5392 | | // Get the transpose function's parameters and result type. |
5393 | 540 | auto transposeParams = transposeFnType->getParams(); |
5394 | 540 | auto transposeResult = transposeFnType->getResult(); |
5395 | 540 | bool isCurried = transposeResult->is<AnyFunctionType>(); |
5396 | 540 | if (isCurried) { |
5397 | 356 | auto methodType = transposeResult->castTo<AnyFunctionType>(); |
5398 | 356 | transposeParams = methodType->getParams(); |
5399 | 356 | transposeResult = methodType->getResult(); |
5400 | 356 | } |
5401 | | |
5402 | | // Get the original function's result type. |
5403 | | // The original result type is always equal to the type of the last |
5404 | | // parameter of the transpose function type. |
5405 | 540 | auto originalResult = transposeParams.back().getPlainType(); |
5406 | | |
5407 | | // Get transposed result types. |
5408 | | // The transpose function result type may be a singular type or a tuple type. |
5409 | 540 | SmallVector<TupleTypeElt, 4> transposeResultTypes; |
5410 | 540 | if (auto transposeResultTupleType = transposeResult->getAs<TupleType>()) { |
5411 | 204 | transposeResultTypes.append(transposeResultTupleType->getElements().begin(), |
5412 | 204 | transposeResultTupleType->getElements().end()); |
5413 | 336 | } else { |
5414 | 336 | transposeResultTypes.push_back(transposeResult); |
5415 | 336 | } |
5416 | | |
5417 | | // Get the `Self` type, if the transpose function type is curried. |
5418 | | // - If `self` is a linearity parameter, use the first transpose result type. |
5419 | | // - Otherwise, use the first transpose parameter type. |
5420 | 540 | unsigned transposeResultTypesIndex = 0; |
5421 | 540 | Type selfType; |
5422 | 540 | if (isCurried && wrtSelf) { |
5423 | 180 | selfType = transposeResultTypes.front().getType(); |
5424 | 180 | ++transposeResultTypesIndex; |
5425 | 360 | } else if (isCurried) { |
5426 | 176 | selfType = transposeFnType->getParams().front().getPlainType(); |
5427 | 176 | } |
5428 | | |
5429 | | // Get the original function's parameters. |
5430 | 540 | SmallVector<AnyFunctionType::Param, 8> originalParams; |
5431 | | // The number of original parameters is equal to the sum of: |
5432 | | // - The number of original non-transposed parameters. |
5433 | | // - This is the number of transpose parameters minus one. All transpose |
5434 | | // parameters come from the original function, except the last parameter |
5435 | | // (the transposed original result). |
5436 | | // - The number of original transposed parameters. |
5437 | | // - This is the number of linearity parameters. |
5438 | 540 | unsigned originalParameterCount = |
5439 | 540 | transposeParams.size() - 1 + linearParamIndices->getNumIndices(); |
5440 | | // Iterate over all original parameter indices. |
5441 | 1.19k | for (auto i : range(originalParameterCount)) { |
5442 | | // Skip `self` parameter if `self` is a linearity parameter. |
5443 | | // The `self` is handled specially later to form a curried function type. |
5444 | 1.19k | bool isSelfParameterAndWrtSelf = |
5445 | 1.19k | wrtSelf && i == linearParamIndices->getCapacity() - 1; |
5446 | 1.19k | if (isSelfParameterAndWrtSelf) |
5447 | 180 | continue; |
5448 | | // If `i` is a linearity parameter index, the next original parameter is |
5449 | | // the next transpose result. |
5450 | 1.01k | if (linearParamIndices->contains(i)) { |
5451 | 636 | auto resultType = |
5452 | 636 | transposeResultTypes[transposeResultTypesIndex++].getType(); |
5453 | 636 | originalParams.push_back(AnyFunctionType::Param(resultType)); |
5454 | 636 | } |
5455 | | // Otherwise, the next original parameter is the next transpose parameter. |
5456 | 380 | else { |
5457 | 380 | originalParams.push_back(transposeParams[transposeParamsIndex++]); |
5458 | 380 | } |
5459 | 1.01k | } |
5460 | | |
5461 | | // Compute the original function type. |
5462 | 540 | AnyFunctionType *originalType; |
5463 | | // If the transpose type is curried, the original function type is: |
5464 | | // `(Self) -> (<original parameters>) -> <original result>`. |
5465 | 540 | if (isCurried) { |
5466 | 356 | assert(selfType && "`Self` type should be resolved"); |
5467 | 0 | originalType = makeFunctionType(originalParams, originalResult, nullptr); |
5468 | 356 | originalType = |
5469 | 356 | makeFunctionType(AnyFunctionType::Param(selfType), originalType, |
5470 | 356 | transposeFnType->getOptGenericSignature()); |
5471 | 356 | } |
5472 | | // Otherwise, the original function type is simply: |
5473 | | // `(<original parameters>) -> <original result>`. |
5474 | 184 | else { |
5475 | 184 | originalType = makeFunctionType(originalParams, originalResult, |
5476 | 184 | transposeFnType->getOptGenericSignature()); |
5477 | 184 | } |
5478 | 0 | return originalType; |
5479 | 540 | } |
5480 | | |
5481 | | /// Given a `@differentiable` attribute, attempts to resolve the derivative |
5482 | | /// generic signature. The derivative generic signature is returned as |
5483 | | /// `derivativeGenSig`. On error, emits diagnostic, assigns `nullptr` to |
5484 | | /// `derivativeGenSig`, and returns true. |
5485 | | bool resolveDifferentiableAttrDerivativeGenericSignature( |
5486 | | DifferentiableAttr *attr, AbstractFunctionDecl *original, |
5487 | 3.67k | GenericSignature &derivativeGenSig) { |
5488 | 3.67k | derivativeGenSig = nullptr; |
5489 | | |
5490 | 3.67k | auto &ctx = original->getASTContext(); |
5491 | 3.67k | auto &diags = ctx.Diags; |
5492 | | |
5493 | 3.67k | bool isOriginalProtocolRequirement = |
5494 | 3.67k | isa<ProtocolDecl>(original->getDeclContext()) && |
5495 | 3.67k | original->isProtocolRequirement(); |
5496 | | |
5497 | | // Compute the derivative generic signature for the `@differentiable` |
5498 | | // attribute: |
5499 | | // - If the `@differentiable` attribute has a `where` clause, use it to |
5500 | | // compute the derivative generic signature. |
5501 | | // - Otherwise, use the original function's generic signature by default. |
5502 | 3.67k | auto originalGenSig = original->getGenericSignature(); |
5503 | 3.67k | derivativeGenSig = originalGenSig; |
5504 | | |
5505 | | // Handle the `where` clause, if it exists. |
5506 | | // - Resolve attribute where clause requirements and store in the attribute |
5507 | | // for serialization. |
5508 | | // - Compute generic signature for autodiff derivative functions based on |
5509 | | // the original function's generate signature and the attribute's where |
5510 | | // clause requirements. |
5511 | 3.67k | if (auto *whereClause = attr->getWhereClause()) { |
5512 | | // `@differentiable` attributes on protocol requirements do not support |
5513 | | // `where` clauses. |
5514 | 236 | if (isOriginalProtocolRequirement) { |
5515 | 8 | diags.diagnose(attr->getLocation(), |
5516 | 8 | diag::differentiable_attr_protocol_req_where_clause); |
5517 | 8 | attr->setInvalid(); |
5518 | 8 | return true; |
5519 | 8 | } |
5520 | 228 | if (whereClause->getRequirements().empty()) { |
5521 | | // `where` clause must not be empty. |
5522 | 0 | diags.diagnose(attr->getLocation(), |
5523 | 0 | diag::differentiable_attr_empty_where_clause); |
5524 | 0 | attr->setInvalid(); |
5525 | 0 | return true; |
5526 | 0 | } |
5527 | | |
5528 | 228 | if (!originalGenSig) { |
5529 | | // `where` clauses are valid only when the original function is generic. |
5530 | 0 | diags |
5531 | 0 | .diagnose( |
5532 | 0 | attr->getLocation(), |
5533 | 0 | diag::differentiable_attr_where_clause_for_nongeneric_original, |
5534 | 0 | original) |
5535 | 0 | .highlight(whereClause->getSourceRange()); |
5536 | 0 | attr->setInvalid(); |
5537 | 0 | return true; |
5538 | 0 | } |
5539 | | |
5540 | 228 | InferredGenericSignatureRequest request{ |
5541 | 228 | originalGenSig.getPointer(), |
5542 | 228 | /*genericParams=*/nullptr, |
5543 | 228 | WhereClauseOwner(original, attr), |
5544 | 228 | /*addedRequirements=*/{}, |
5545 | 228 | /*inferenceSources=*/{}, |
5546 | 228 | /*allowConcreteParams=*/true}; |
5547 | | |
5548 | | // Compute generic signature for derivative functions. |
5549 | 228 | derivativeGenSig = evaluateOrDefault(ctx.evaluator, request, |
5550 | 228 | GenericSignatureWithError()) |
5551 | 228 | .getPointer(); |
5552 | | |
5553 | 228 | bool hadInvalidRequirements = false; |
5554 | 256 | for (auto req : derivativeGenSig.requirementsNotSatisfiedBy(originalGenSig)) { |
5555 | 256 | if (req.getKind() == RequirementKind::Layout) { |
5556 | | // Layout requirements are not supported. |
5557 | 16 | diags |
5558 | 16 | .diagnose(attr->getLocation(), |
5559 | 16 | diag::differentiable_attr_layout_req_unsupported); |
5560 | 16 | hadInvalidRequirements = true; |
5561 | 16 | } |
5562 | 256 | } |
5563 | | |
5564 | 228 | if (hadInvalidRequirements) { |
5565 | 16 | attr->setInvalid(); |
5566 | 16 | return true; |
5567 | 16 | } |
5568 | 228 | } |
5569 | | |
5570 | 3.65k | attr->setDerivativeGenericSignature(derivativeGenSig); |
5571 | 3.65k | return false; |
5572 | 3.67k | } |
5573 | | |
5574 | | /// Given a `@differentiable` attribute, attempts to resolve and validate the |
5575 | | /// differentiability parameter indices. The parameter indices are returned as |
5576 | | /// `diffParamIndices`. On error, emits diagnostic, assigns `nullptr` to |
5577 | | /// `diffParamIndices`, and returns true. |
5578 | | bool resolveDifferentiableAttrDifferentiabilityParameters( |
5579 | | DifferentiableAttr *attr, AbstractFunctionDecl *original, |
5580 | | AnyFunctionType *originalFnRemappedTy, GenericEnvironment *derivativeGenEnv, |
5581 | 3.42k | IndexSubset *&diffParamIndices) { |
5582 | 3.42k | diffParamIndices = nullptr; |
5583 | 3.42k | auto &ctx = original->getASTContext(); |
5584 | 3.42k | auto &diags = ctx.Diags; |
5585 | | |
5586 | | // Get the parsed differentiability parameter indices, which have not yet been |
5587 | | // resolved. Parsed differentiability parameter indices are defined only for |
5588 | | // parsed attributes. |
5589 | 3.42k | auto parsedDiffParams = attr->getParsedParameters(); |
5590 | | |
5591 | 3.42k | diffParamIndices = computeDifferentiabilityParameters( |
5592 | 3.42k | parsedDiffParams, original, derivativeGenEnv, attr->getAttrName(), |
5593 | 3.42k | attr->getLocation()); |
5594 | 3.42k | if (!diffParamIndices) { |
5595 | 96 | attr->setInvalid(); |
5596 | 96 | return true; |
5597 | 96 | } |
5598 | | |
5599 | | // Check if differentiability parameter indices are valid. |
5600 | | // Do this by compute the expected differential type and checking whether |
5601 | | // there is an error. |
5602 | 3.32k | auto expectedLinearMapTypeOrError = |
5603 | 3.32k | originalFnRemappedTy->getAutoDiffDerivativeFunctionLinearMapType( |
5604 | 3.32k | diffParamIndices, AutoDiffLinearMapKind::Differential, |
5605 | 3.32k | LookUpConformanceInModule(original->getModuleContext()), |
5606 | 3.32k | /*makeSelfParamFirst*/ true); |
5607 | | |
5608 | | // Helper for diagnosing derivative function type errors. |
5609 | 3.32k | auto errorHandler = [&](const DerivativeFunctionTypeError &error) { |
5610 | 96 | attr->setInvalid(); |
5611 | 96 | switch (error.kind) { |
5612 | 32 | case DerivativeFunctionTypeError::Kind::NoSemanticResults: |
5613 | 32 | diags |
5614 | 32 | .diagnose(attr->getLocation(), |
5615 | 32 | diag::autodiff_attr_original_void_result, |
5616 | 32 | original->getName()) |
5617 | 32 | .highlight(original->getSourceRange()); |
5618 | 32 | return; |
5619 | 16 | case DerivativeFunctionTypeError::Kind::NoDifferentiabilityParameters: |
5620 | 16 | diags.diagnose(attr->getLocation(), |
5621 | 16 | diag::diff_params_clause_no_inferred_parameters); |
5622 | 16 | return; |
5623 | 8 | case DerivativeFunctionTypeError::Kind:: |
5624 | 8 | NonDifferentiableDifferentiabilityParameter: { |
5625 | 8 | auto nonDiffParam = error.getNonDifferentiableTypeAndIndex(); |
5626 | 8 | SourceLoc loc = parsedDiffParams.empty() |
5627 | 8 | ? attr->getLocation() |
5628 | 8 | : parsedDiffParams[nonDiffParam.second].getLoc(); |
5629 | 8 | diags.diagnose(loc, diag::diff_params_clause_param_not_differentiable, |
5630 | 8 | nonDiffParam.first); |
5631 | 8 | return; |
5632 | 0 | } |
5633 | 40 | case DerivativeFunctionTypeError::Kind::NonDifferentiableResult: |
5634 | 40 | auto nonDiffResult = error.getNonDifferentiableTypeAndIndex(); |
5635 | 40 | diags.diagnose(attr->getLocation(), |
5636 | 40 | diag::autodiff_attr_result_not_differentiable, |
5637 | 40 | nonDiffResult.first); |
5638 | 40 | return; |
5639 | 96 | } |
5640 | 96 | }; |
5641 | | // Diagnose any derivative function type errors. |
5642 | 3.32k | if (!expectedLinearMapTypeOrError) { |
5643 | 96 | auto error = expectedLinearMapTypeOrError.takeError(); |
5644 | 96 | handleAllErrors(std::move(error), errorHandler); |
5645 | 96 | return true; |
5646 | 96 | } |
5647 | | |
5648 | 3.23k | return false; |
5649 | 3.32k | } |
5650 | | |
5651 | | /// Checks whether differentiable programming is enabled for the given |
5652 | | /// differentiation-related attribute. Returns true on error. |
5653 | | static bool checkIfDifferentiableProgrammingEnabled(DeclAttribute *attr, |
5654 | 5.16k | Decl *D) { |
5655 | 5.16k | auto &ctx = D->getASTContext(); |
5656 | 5.16k | auto &diags = ctx.Diags; |
5657 | 5.16k | auto *SF = D->getDeclContext()->getParentSourceFile(); |
5658 | 5.16k | assert(SF && "Source file not found"); |
5659 | | // The `Differentiable` protocol must be available. |
5660 | | // If unavailable, the `_Differentiation` module should be imported. |
5661 | 5.16k | if (isDifferentiableProgrammingEnabled(*SF)) |
5662 | 5.15k | return false; |
5663 | 8 | diags |
5664 | 8 | .diagnose(attr->getLocation(), diag::attr_used_without_required_module, |
5665 | 8 | attr, ctx.Id_Differentiation) |
5666 | 8 | .highlight(attr->getRangeWithAt()); |
5667 | 8 | return true; |
5668 | 5.16k | } |
5669 | | |
5670 | | static IndexSubset * |
5671 | | resolveDiffParamIndices(AbstractFunctionDecl *original, |
5672 | | DifferentiableAttr *attr, |
5673 | 3.42k | GenericSignature derivativeGenSig) { |
5674 | 3.42k | auto *derivativeGenEnv = derivativeGenSig.getGenericEnvironment(); |
5675 | | |
5676 | | // Compute the derivative function type. |
5677 | 3.42k | auto originalFnRemappedTy = original->getInterfaceType()->castTo<AnyFunctionType>(); |
5678 | 3.42k | if (derivativeGenEnv) |
5679 | 1.16k | originalFnRemappedTy = |
5680 | 1.16k | derivativeGenEnv->mapTypeIntoContext(originalFnRemappedTy) |
5681 | 1.16k | ->castTo<AnyFunctionType>(); |
5682 | | |
5683 | | // Resolve and validate the differentiability parameters. |
5684 | 3.42k | IndexSubset *resolvedDiffParamIndices = nullptr; |
5685 | 3.42k | if (resolveDifferentiableAttrDifferentiabilityParameters( |
5686 | 3.42k | attr, original, originalFnRemappedTy, derivativeGenEnv, |
5687 | 3.42k | resolvedDiffParamIndices)) |
5688 | 192 | return nullptr; |
5689 | | |
5690 | 3.23k | return resolvedDiffParamIndices; |
5691 | 3.42k | } |
5692 | | |
5693 | | |
5694 | | static IndexSubset * |
5695 | | typecheckDifferentiableAttrforDecl(AbstractFunctionDecl *original, |
5696 | | DifferentiableAttr *attr, |
5697 | 3.45k | IndexSubset *resolvedDiffParamIndices = nullptr) { |
5698 | 3.45k | auto &ctx = original->getASTContext(); |
5699 | 3.45k | auto &diags = ctx.Diags; |
5700 | | |
5701 | | // Diagnose if original function has opaque result types. |
5702 | 3.45k | if (auto *opaqueResultTypeDecl = original->getOpaqueResultTypeDecl()) { |
5703 | 8 | diags.diagnose( |
5704 | 8 | attr->getLocation(), |
5705 | 8 | diag::autodiff_attr_opaque_result_type_unsupported); |
5706 | 8 | attr->setInvalid(); |
5707 | 8 | return nullptr; |
5708 | 8 | } |
5709 | | |
5710 | | // Diagnose if original function is an invalid class member. |
5711 | 3.44k | bool isOriginalClassMember = original->getDeclContext() && |
5712 | 3.44k | original->getDeclContext()->getSelfClassDecl(); |
5713 | 3.44k | if (isOriginalClassMember) { |
5714 | 448 | auto *classDecl = original->getDeclContext()->getSelfClassDecl(); |
5715 | 448 | assert(classDecl); |
5716 | | // Class members returning dynamic `Self` are not supported. |
5717 | | // Dynamic `Self` is supported only as a single top-level result for class |
5718 | | // members. JVP/VJP functions returning `(Self, ...)` tuples would not |
5719 | | // type-check. |
5720 | 0 | bool diagnoseDynamicSelfResult = original->hasDynamicSelfResult(); |
5721 | 448 | if (diagnoseDynamicSelfResult) { |
5722 | | // Diagnose class initializers in non-final classes. |
5723 | 68 | if (isa<ConstructorDecl>(original)) { |
5724 | 52 | if (!classDecl->isSemanticallyFinal()) { |
5725 | 8 | diags.diagnose( |
5726 | 8 | attr->getLocation(), |
5727 | 8 | diag::differentiable_attr_nonfinal_class_init_unsupported, |
5728 | 8 | classDecl->getDeclaredInterfaceType()); |
5729 | 8 | attr->setInvalid(); |
5730 | 8 | return nullptr; |
5731 | 8 | } |
5732 | 52 | } |
5733 | | // Diagnose all other declarations returning dynamic `Self`. |
5734 | 16 | else { |
5735 | 16 | diags.diagnose( |
5736 | 16 | attr->getLocation(), |
5737 | 16 | diag:: |
5738 | 16 | differentiable_attr_class_member_dynamic_self_result_unsupported); |
5739 | 16 | attr->setInvalid(); |
5740 | 16 | return nullptr; |
5741 | 16 | } |
5742 | 68 | } |
5743 | 448 | } |
5744 | | |
5745 | | // Resolve the derivative generic signature. |
5746 | 3.42k | GenericSignature derivativeGenSig = attr->getDerivativeGenericSignature(); |
5747 | 3.42k | if (!derivativeGenSig && |
5748 | 3.42k | resolveDifferentiableAttrDerivativeGenericSignature(attr, original, |
5749 | 3.20k | derivativeGenSig)) |
5750 | 24 | return nullptr; |
5751 | | |
5752 | | // Resolve and validate the differentiability parameters. |
5753 | 3.40k | if (!resolvedDiffParamIndices) |
5754 | 2.94k | resolvedDiffParamIndices = resolveDiffParamIndices(original, attr, |
5755 | 2.94k | derivativeGenSig); |
5756 | 3.40k | if (!resolvedDiffParamIndices) |
5757 | 176 | return nullptr; |
5758 | | |
5759 | | // Reject duplicate `@differentiable` attributes. |
5760 | 3.22k | auto insertion = |
5761 | 3.22k | ctx.DifferentiableAttrs.try_emplace({original, resolvedDiffParamIndices}, attr); |
5762 | 3.22k | if (!insertion.second && insertion.first->getSecond() != attr) { |
5763 | 40 | diagnoseAndRemoveAttr(original, attr, diag::differentiable_attr_duplicate); |
5764 | 40 | diags.diagnose(insertion.first->getSecond()->getLocation(), |
5765 | 40 | diag::differentiable_attr_duplicate_note); |
5766 | 40 | return nullptr; |
5767 | 40 | } |
5768 | | |
5769 | | // Register derivative function configuration. |
5770 | 3.18k | SmallVector<AutoDiffSemanticFunctionResultType, 1> semanticResults; |
5771 | | |
5772 | | // Compute the derivative function type. |
5773 | 3.18k | auto originalFnRemappedTy = original->getInterfaceType()->castTo<AnyFunctionType>(); |
5774 | 3.18k | if (auto *derivativeGenEnv = derivativeGenSig.getGenericEnvironment()) |
5775 | 1.11k | originalFnRemappedTy = |
5776 | 1.11k | derivativeGenEnv->mapTypeIntoContext(originalFnRemappedTy) |
5777 | 1.11k | ->castTo<AnyFunctionType>(); |
5778 | | |
5779 | 3.18k | auto *resultIndices = |
5780 | 3.18k | autodiff::getFunctionSemanticResultIndices(originalFnRemappedTy, |
5781 | 3.18k | resolvedDiffParamIndices); |
5782 | | |
5783 | 3.18k | original->addDerivativeFunctionConfiguration( |
5784 | 3.18k | {resolvedDiffParamIndices, resultIndices, derivativeGenSig}); |
5785 | 3.18k | return resolvedDiffParamIndices; |
5786 | 3.22k | } |
5787 | | |
5788 | | /// Given a `@differentiable` attribute, attempts to resolve the original |
5789 | | /// `AbstractFunctionDecl` for which it is registered, using the declaration |
5790 | | /// on which it is actually declared. On error, emits diagnostic and returns |
5791 | | /// `nullptr`. |
5792 | | static AbstractFunctionDecl * |
5793 | 3.01k | resolveDifferentiableAttrOriginalFunction(DifferentiableAttr *attr) { |
5794 | 3.01k | auto *D = attr->getOriginalDeclaration(); |
5795 | 3.01k | auto *original = dyn_cast<AbstractFunctionDecl>(D); |
5796 | | |
5797 | | // Non-`get`/`set` accessors are not yet supported: `read`, and `modify`. |
5798 | | // TODO(TF-1080): Enable `read` and `modify` when differentiation supports |
5799 | | // coroutines. |
5800 | 3.01k | if (auto *accessor = dyn_cast_or_null<AccessorDecl>(original)) |
5801 | 180 | if (!accessor->isGetter() && !accessor->isSetter()) |
5802 | 16 | original = nullptr; |
5803 | | |
5804 | | // Diagnose if original `AbstractFunctionDecl` could not be resolved. |
5805 | 3.01k | if (!original) { |
5806 | 16 | diagnoseAndRemoveAttr(D, attr, diag::invalid_decl_attribute, attr); |
5807 | 16 | attr->setInvalid(); |
5808 | 16 | return nullptr; |
5809 | 16 | } |
5810 | | |
5811 | | // If the original function has an error interface type, return. |
5812 | | // A diagnostic should have already been emitted. |
5813 | 2.99k | if (original->getInterfaceType()->hasError()) |
5814 | 0 | return nullptr; |
5815 | | |
5816 | 2.99k | return original; |
5817 | 2.99k | } |
5818 | | |
5819 | | static IndexSubset * |
5820 | | resolveDifferentiableAccessors(DifferentiableAttr *attr, |
5821 | 368 | AbstractStorageDecl *asd) { |
5822 | 476 | auto typecheckAccessor = [&](AccessorDecl *ad) -> IndexSubset* { |
5823 | 476 | GenericSignature derivativeGenSig = nullptr; |
5824 | 476 | if (resolveDifferentiableAttrDerivativeGenericSignature(attr, ad, |
5825 | 476 | derivativeGenSig)) |
5826 | 0 | return nullptr; |
5827 | | |
5828 | 476 | IndexSubset *resolvedDiffParamIndices = resolveDiffParamIndices(ad, attr, |
5829 | 476 | derivativeGenSig); |
5830 | 476 | if (!resolvedDiffParamIndices) |
5831 | 16 | return nullptr; |
5832 | | |
5833 | 460 | auto *newAttr = DifferentiableAttr::create( |
5834 | 460 | ad, /*implicit*/ true, attr->AtLoc, attr->getRange(), |
5835 | 460 | attr->getDifferentiabilityKind(), resolvedDiffParamIndices, |
5836 | 460 | attr->getDerivativeGenericSignature()); |
5837 | 460 | ad->getAttrs().add(newAttr); |
5838 | | |
5839 | 460 | if (!typecheckDifferentiableAttrforDecl(ad, attr, |
5840 | 460 | resolvedDiffParamIndices)) |
5841 | 16 | return nullptr; |
5842 | | |
5843 | 444 | return resolvedDiffParamIndices; |
5844 | 460 | }; |
5845 | | |
5846 | | // No getters / setters for global variables |
5847 | 368 | if (asd->getDeclContext()->isModuleScopeContext()) { |
5848 | 16 | diagnoseAndRemoveAttr(asd, attr, diag::invalid_decl_attribute, attr); |
5849 | 16 | attr->setInvalid(); |
5850 | 16 | return nullptr; |
5851 | 16 | } |
5852 | | |
5853 | 352 | if (!typecheckAccessor(asd->getSynthesizedAccessor(AccessorKind::Get))) |
5854 | 32 | return nullptr; |
5855 | | |
5856 | 320 | if (asd->supportsMutation()) { |
5857 | | // FIXME: Class-typed values have reference semantics and can be freely |
5858 | | // mutated. Thus, they should be treated like inout parameters for the |
5859 | | // purposes of @differentiable and @derivative type-checking. Until |
5860 | | // https://github.com/apple/swift/issues/55542 is fixed, check if setter has |
5861 | | // computed semantic results and do not typecheck if they are none |
5862 | | // (class-typed `self' parameter is not treated as a "semantic result" |
5863 | | // currently) |
5864 | 196 | if (!asd->getDeclContext()->getSelfClassDecl()) |
5865 | 124 | if (!typecheckAccessor(asd->getSynthesizedAccessor(AccessorKind::Set))) |
5866 | 0 | return nullptr; |
5867 | 196 | } |
5868 | | |
5869 | | // Remove `@differentiable` attribute from storage declaration to prevent |
5870 | | // duplicate attribute registration during SILGen. |
5871 | 320 | asd->getAttrs().removeAttribute(attr); |
5872 | | |
5873 | | // Here we are effectively removing attribute from original decl, therefore no |
5874 | | // index subset for us |
5875 | 320 | return nullptr; |
5876 | 320 | } |
5877 | | |
5878 | | |
5879 | | IndexSubset *DifferentiableAttributeTypeCheckRequest::evaluate( |
5880 | 3.38k | Evaluator &evaluator, DifferentiableAttr *attr) const { |
5881 | | // Skip type-checking for implicit `@differentiable` attributes. We currently |
5882 | | // assume that all implicit `@differentiable` attributes are valid. |
5883 | | // |
5884 | | // Motivation: some implicit attributes do not have a `where` clause, and this |
5885 | | // function assumes that the `where` clauses exist. Propagating `where` |
5886 | | // clauses and requirements consistently is a larger problem, to be revisited. |
5887 | 3.38k | if (attr->isImplicit()) |
5888 | 0 | return nullptr; |
5889 | | |
5890 | 3.38k | auto *D = attr->getOriginalDeclaration(); |
5891 | 3.38k | assert(D && |
5892 | 3.38k | "Original declaration should be resolved by parsing/deserialization"); |
5893 | | |
5894 | | // `@differentiable` attribute requires experimental differentiable |
5895 | | // programming to be enabled. |
5896 | 3.38k | if (checkIfDifferentiableProgrammingEnabled(attr, D)) { |
5897 | 4 | attr->setInvalid(); |
5898 | 4 | return nullptr; |
5899 | 4 | } |
5900 | | |
5901 | | // If `@differentiable` attribute is declared directly on a |
5902 | | // `AbstractStorageDecl` (a stored/computed property or subscript), |
5903 | | // forward the attribute to the storage's getter / setter |
5904 | 3.38k | if (auto *asd = dyn_cast<AbstractStorageDecl>(D)) |
5905 | 368 | return resolveDifferentiableAccessors(attr, asd); |
5906 | | |
5907 | | // Resolve the original `AbstractFunctionDecl`. |
5908 | 3.01k | auto *original = resolveDifferentiableAttrOriginalFunction(attr); |
5909 | 3.01k | if (!original) { |
5910 | 16 | attr->setInvalid(); |
5911 | 16 | return nullptr; |
5912 | 16 | } |
5913 | | |
5914 | 2.99k | return typecheckDifferentiableAttrforDecl(original, attr); |
5915 | 3.01k | } |
5916 | | |
5917 | 3.74k | void AttributeChecker::visitDifferentiableAttr(DifferentiableAttr *attr) { |
5918 | | // Call `getParameterIndices` to trigger |
5919 | | // `DifferentiableAttributeTypeCheckRequest`. |
5920 | 3.74k | (void)attr->getParameterIndices(); |
5921 | 3.74k | } |
5922 | | |
5923 | | /// Type-checks the given `@derivative` attribute `attr` on declaration `D`. |
5924 | | /// |
5925 | | /// Effects are: |
5926 | | /// - Sets the original function and parameter indices on `attr`. |
5927 | | /// - Diagnoses errors. |
5928 | | /// - Stores the attribute in `ASTContext::DerivativeAttrs`. |
5929 | | /// |
5930 | | /// \returns true on error, false on success. |
5931 | 1.77k | static bool typeCheckDerivativeAttr(DerivativeAttr *attr) { |
5932 | | // Note: Implementation must be idempotent because it may be called multiple |
5933 | | // times for the same attribute. |
5934 | 1.77k | Decl *D = attr->getOriginalDeclaration(); |
5935 | 1.77k | auto &Ctx = D->getASTContext(); |
5936 | 1.77k | auto &diags = Ctx.Diags; |
5937 | | // `@derivative` attribute requires experimental differentiable programming |
5938 | | // to be enabled. |
5939 | 1.77k | if (checkIfDifferentiableProgrammingEnabled(attr, D)) |
5940 | 4 | return true; |
5941 | 1.77k | auto *derivative = cast<FuncDecl>(D); |
5942 | 1.77k | auto originalName = attr->getOriginalFunctionName(); |
5943 | | |
5944 | 1.77k | auto *derivativeInterfaceType = |
5945 | 1.77k | derivative->getInterfaceType()->castTo<AnyFunctionType>(); |
5946 | | |
5947 | | // Perform preliminary `@derivative` declaration checks. |
5948 | | // The result type should be a two-element tuple. |
5949 | | // Either a value and pullback: |
5950 | | // (value: R, pullback: (R.TangentVector) -> (T.TangentVector...) |
5951 | | // Or a value and differential: |
5952 | | // (value: R, differential: (T.TangentVector...) -> (R.TangentVector) |
5953 | 1.77k | auto derivativeResultType = derivative->getResultInterfaceType(); |
5954 | 1.77k | auto derivativeResultTupleType = derivativeResultType->getAs<TupleType>(); |
5955 | 1.77k | if (!derivativeResultTupleType || |
5956 | 1.77k | derivativeResultTupleType->getNumElements() != 2) { |
5957 | 8 | diags.diagnose(attr->getLocation(), |
5958 | 8 | diag::derivative_attr_expected_result_tuple); |
5959 | 8 | return true; |
5960 | 8 | } |
5961 | 1.76k | auto valueResultElt = derivativeResultTupleType->getElement(0); |
5962 | 1.76k | auto funcResultElt = derivativeResultTupleType->getElement(1); |
5963 | | // Get derivative kind and derivative function identifier. |
5964 | 1.76k | AutoDiffDerivativeFunctionKind kind; |
5965 | 1.76k | if (valueResultElt.getName().str() != "value") { |
5966 | 8 | diags.diagnose(attr->getLocation(), |
5967 | 8 | diag::derivative_attr_invalid_result_tuple_value_label); |
5968 | 8 | return true; |
5969 | 8 | } |
5970 | 1.75k | if (funcResultElt.getName().str() == "differential") { |
5971 | 448 | kind = AutoDiffDerivativeFunctionKind::JVP; |
5972 | 1.30k | } else if (funcResultElt.getName().str() == "pullback") { |
5973 | 1.30k | kind = AutoDiffDerivativeFunctionKind::VJP; |
5974 | 1.30k | } else { |
5975 | 8 | diags.diagnose(attr->getLocation(), |
5976 | 8 | diag::derivative_attr_invalid_result_tuple_func_label); |
5977 | 8 | return true; |
5978 | 8 | } |
5979 | 1.74k | attr->setDerivativeKind(kind); |
5980 | | |
5981 | | // Compute expected original function type and look up original function. |
5982 | 1.74k | auto *originalFnType = |
5983 | 1.74k | getDerivativeOriginalFunctionType(derivativeInterfaceType); |
5984 | | |
5985 | | // Returns true if the derivative function and original function candidate are |
5986 | | // defined in compatible type contexts. If the derivative function and the |
5987 | | // original function candidate have different parents, return false. |
5988 | 1.82k | auto hasValidTypeContext = [&](AbstractFunctionDecl *originalCandidate) { |
5989 | | // Check if both functions are top-level. |
5990 | 1.82k | if (!derivative->getInnermostTypeContext() && |
5991 | 1.82k | !originalCandidate->getInnermostTypeContext()) |
5992 | 708 | return true; |
5993 | | // Check if both functions are defined in the same type context. |
5994 | 1.12k | if (auto typeCtx1 = derivative->getInnermostTypeContext()) |
5995 | 1.12k | if (auto typeCtx2 = originalCandidate->getInnermostTypeContext()) { |
5996 | 1.12k | return typeCtx1->getSelfNominalTypeDecl() == |
5997 | 1.12k | typeCtx2->getSelfNominalTypeDecl(); |
5998 | 1.12k | } |
5999 | 0 | return derivative->getParent() == originalCandidate->getParent(); |
6000 | 1.12k | }; |
6001 | | |
6002 | 1.74k | auto isValidOriginalCandidate = [&](AbstractFunctionDecl *originalCandidate) |
6003 | 1.96k | -> llvm::Optional<AbstractFunctionDeclLookupErrorKind> { |
6004 | | // Error if the original candidate is a protocol requirement. Derivative |
6005 | | // registration does not yet support protocol requirements. |
6006 | | // TODO(TF-982): Allow default derivative implementations for protocol |
6007 | | // requirements. |
6008 | 1.96k | if (isa<ProtocolDecl>(originalCandidate->getDeclContext())) |
6009 | 140 | return AbstractFunctionDeclLookupErrorKind::CandidateProtocolRequirement; |
6010 | | // Error if the original candidate is not defined in a type context |
6011 | | // compatible with the derivative function. |
6012 | 1.82k | if (!hasValidTypeContext(originalCandidate)) |
6013 | 32 | return AbstractFunctionDeclLookupErrorKind::CandidateWrongTypeContext; |
6014 | | // Error if the original candidate does not have the expected type. |
6015 | 1.79k | if (!checkFunctionSignature( |
6016 | 1.79k | cast<AnyFunctionType>(originalFnType->getCanonicalType()), |
6017 | 1.79k | originalCandidate->getInterfaceType()->getCanonicalType())) |
6018 | 192 | return AbstractFunctionDeclLookupErrorKind::CandidateTypeMismatch; |
6019 | 1.60k | return llvm::None; |
6020 | 1.79k | }; |
6021 | | |
6022 | 1.74k | Type baseType; |
6023 | 1.74k | if (auto *baseTypeRepr = attr->getBaseTypeRepr()) { |
6024 | 28 | const auto options = |
6025 | 28 | TypeResolutionOptions(llvm::None) | TypeResolutionFlags::AllowModule; |
6026 | 28 | baseType = TypeResolution::resolveContextualType( |
6027 | 28 | baseTypeRepr, derivative->getDeclContext(), options, |
6028 | 28 | /*unboundTyOpener*/ nullptr, |
6029 | 28 | /*placeholderHandler*/ nullptr, |
6030 | 28 | /*packElementOpener*/ nullptr); |
6031 | 28 | } |
6032 | 1.74k | if (baseType && baseType->hasError()) |
6033 | 0 | return true; |
6034 | 1.74k | auto lookupOptions = attr->getBaseTypeRepr() |
6035 | 1.74k | ? defaultMemberLookupOptions |
6036 | 1.74k | : defaultUnqualifiedLookupOptions; |
6037 | 1.74k | auto derivativeTypeCtx = derivative->getInnermostTypeContext(); |
6038 | 1.74k | if (!derivativeTypeCtx) |
6039 | 716 | derivativeTypeCtx = derivative->getParent(); |
6040 | 1.74k | assert(derivativeTypeCtx); |
6041 | | |
6042 | | // Diagnose unsupported original accessor kinds. |
6043 | | // Currently, only getters and setters are supported. |
6044 | 1.74k | if (originalName.AccessorKind.has_value()) { |
6045 | 176 | if (*originalName.AccessorKind != AccessorKind::Get && |
6046 | 176 | *originalName.AccessorKind != AccessorKind::Set) { |
6047 | 8 | attr->setInvalid(); |
6048 | 8 | diags.diagnose( |
6049 | 8 | originalName.Loc, diag::derivative_attr_unsupported_accessor_kind, |
6050 | 8 | getAccessorDescriptiveDeclKind(*originalName.AccessorKind)); |
6051 | 8 | return true; |
6052 | 8 | } |
6053 | 176 | } |
6054 | | |
6055 | | // Look up original function. |
6056 | 1.74k | auto *originalAFD = findAutoDiffOriginalFunctionDecl( |
6057 | 1.74k | attr, baseType, originalName, derivativeTypeCtx, lookupOptions, |
6058 | 1.74k | isValidOriginalCandidate, originalFnType); |
6059 | 1.74k | if (!originalAFD) { |
6060 | 152 | attr->setInvalid(); |
6061 | 152 | return true; |
6062 | 152 | } |
6063 | | |
6064 | | // Diagnose original stored properties. Stored properties cannot have custom |
6065 | | // registered derivatives. |
6066 | 1.58k | if (auto *accessorDecl = dyn_cast<AccessorDecl>(originalAFD)) { |
6067 | | // Diagnose original stored properties. Stored properties cannot have custom |
6068 | | // registered derivatives. |
6069 | 280 | auto *asd = accessorDecl->getStorage(); |
6070 | 280 | if (asd->hasStorage()) { |
6071 | 8 | diags.diagnose(originalName.Loc, |
6072 | 8 | diag::derivative_attr_original_stored_property_unsupported, |
6073 | 8 | originalName.Name); |
6074 | 8 | diags.diagnose(originalAFD->getLoc(), diag::decl_declared_here, asd); |
6075 | 8 | return true; |
6076 | 8 | } |
6077 | | // Diagnose original class property and subscript setters. |
6078 | | // TODO(https://github.com/apple/swift/issues/55542): Fix derivative function typing results regarding class-typed function parameters. |
6079 | 272 | if (asd->getDeclContext()->getSelfClassDecl() && |
6080 | 272 | accessorDecl->getAccessorKind() == AccessorKind::Set) { |
6081 | 8 | diags.diagnose(originalName.Loc, |
6082 | 8 | diag::derivative_attr_class_setter_unsupported); |
6083 | 8 | diags.diagnose(originalAFD->getLoc(), diag::decl_declared_here, asd); |
6084 | 8 | return true; |
6085 | 8 | } |
6086 | 272 | } |
6087 | | |
6088 | | // Diagnose if original function has opaque result types. |
6089 | 1.57k | if (auto *opaqueResultTypeDecl = originalAFD->getOpaqueResultTypeDecl()) { |
6090 | 0 | diags.diagnose( |
6091 | 0 | attr->getLocation(), |
6092 | 0 | diag::autodiff_attr_opaque_result_type_unsupported); |
6093 | 0 | attr->setInvalid(); |
6094 | 0 | return true; |
6095 | 0 | } |
6096 | | |
6097 | | // Diagnose if original function is an invalid class member. |
6098 | 1.57k | bool isOriginalClassMember = |
6099 | 1.57k | originalAFD->getDeclContext() && |
6100 | 1.57k | originalAFD->getDeclContext()->getSelfClassDecl(); |
6101 | 1.57k | if (isOriginalClassMember) { |
6102 | 180 | auto *classDecl = originalAFD->getDeclContext()->getSelfClassDecl(); |
6103 | 180 | assert(classDecl); |
6104 | | // Class members returning dynamic `Self` are not supported. |
6105 | | // Dynamic `Self` is supported only as a single top-level result for class |
6106 | | // members. JVP/VJP functions returning `(Self, ...)` tuples would not |
6107 | | // type-check. |
6108 | 0 | bool diagnoseDynamicSelfResult = originalAFD->hasDynamicSelfResult(); |
6109 | 180 | if (diagnoseDynamicSelfResult) { |
6110 | | // Diagnose class initializers in non-final classes. |
6111 | 4 | if (isa<ConstructorDecl>(originalAFD)) { |
6112 | 4 | if (!classDecl->isSemanticallyFinal()) { |
6113 | 0 | diags.diagnose(attr->getLocation(), |
6114 | 0 | diag::derivative_attr_nonfinal_class_init_unsupported, |
6115 | 0 | classDecl->getDeclaredInterfaceType()); |
6116 | 0 | return true; |
6117 | 0 | } |
6118 | 4 | } |
6119 | | // Diagnose all other declarations returning dynamic `Self`. |
6120 | 0 | else { |
6121 | 0 | diags.diagnose( |
6122 | 0 | attr->getLocation(), |
6123 | 0 | diag::derivative_attr_class_member_dynamic_self_result_unsupported, |
6124 | 0 | DeclNameRef(originalAFD->getName())); |
6125 | 0 | return true; |
6126 | 0 | } |
6127 | 4 | } |
6128 | 180 | } |
6129 | | |
6130 | 1.57k | attr->setOriginalFunction(originalAFD); |
6131 | | |
6132 | | // Returns true if: |
6133 | | // - Original function and derivative function are static methods. |
6134 | | // - Original function and derivative function are non-static methods. |
6135 | | // - Original function is a Constructor declaration and derivative function is |
6136 | | // a static method. |
6137 | 1.57k | auto compatibleStaticDecls = [&]() { |
6138 | 1.57k | return (isa<ConstructorDecl>(originalAFD) || originalAFD->isStatic()) == |
6139 | 1.57k | derivative->isStatic(); |
6140 | 1.57k | }; |
6141 | | |
6142 | | // Diagnose if original function and derivative differ in terms of static declaration. |
6143 | 1.57k | if (!compatibleStaticDecls()) { |
6144 | 24 | bool derivativeMustBeStatic = !derivative->isStatic(); |
6145 | 24 | diags |
6146 | 24 | .diagnose(attr->getOriginalFunctionName().Loc.getBaseNameLoc(), |
6147 | 24 | diag::derivative_attr_static_method_mismatch_original, |
6148 | 24 | originalAFD, derivative, derivativeMustBeStatic) |
6149 | 24 | .highlight(attr->getOriginalFunctionName().Loc.getSourceRange()); |
6150 | 24 | diags.diagnose(originalAFD->getNameLoc(), |
6151 | 24 | diag::derivative_attr_static_method_mismatch_original_note, |
6152 | 24 | originalAFD, derivativeMustBeStatic); |
6153 | 24 | auto fixItDiag = |
6154 | 24 | diags.diagnose(derivative->getStartLoc(), |
6155 | 24 | diag::derivative_attr_static_method_mismatch_fix, |
6156 | 24 | derivative, derivativeMustBeStatic); |
6157 | 24 | if (derivativeMustBeStatic) { |
6158 | 16 | fixItDiag.fixItInsert(derivative->getStartLoc(), "static "); |
6159 | 16 | } else { |
6160 | 8 | fixItDiag.fixItRemove(derivative->getStaticLoc()); |
6161 | 8 | } |
6162 | 24 | return true; |
6163 | 24 | } |
6164 | | |
6165 | | // Returns true if: |
6166 | | // - Original function and derivative function have the same access level. |
6167 | | // - Original function is public and derivative function is internal |
6168 | | // `@usableFromInline`. This is the only special case. |
6169 | 1.54k | auto compatibleAccessLevels = [&]() { |
6170 | 1.54k | if (originalAFD->getFormalAccess() == derivative->getFormalAccess()) |
6171 | 1.38k | return true; |
6172 | 160 | return originalAFD->getFormalAccess() == AccessLevel::Public && |
6173 | 160 | (derivative->getFormalAccess() == AccessLevel::Public || |
6174 | 56 | derivative->isUsableFromInline()); |
6175 | 1.54k | }; |
6176 | | |
6177 | | // Check access level compatibility for original and derivative functions. |
6178 | 1.54k | if (!compatibleAccessLevels()) { |
6179 | 128 | auto originalAccess = originalAFD->getFormalAccess(); |
6180 | 128 | auto derivativeAccess = |
6181 | 128 | derivative->getFormalAccessScope().accessLevelForDiagnostics(); |
6182 | 128 | diags.diagnose(originalName.Loc, |
6183 | 128 | diag::derivative_attr_access_level_mismatch, |
6184 | 128 | originalAFD, originalAccess, |
6185 | 128 | derivative, derivativeAccess); |
6186 | 128 | auto fixItDiag = |
6187 | 128 | derivative->diagnose(diag::derivative_attr_fix_access, originalAccess); |
6188 | | // If original access is public, suggest adding `@usableFromInline` to |
6189 | | // derivative. |
6190 | 128 | if (originalAccess == AccessLevel::Public) { |
6191 | 24 | fixItDiag.fixItInsert( |
6192 | 24 | derivative->getAttributeInsertionLoc(/*forModifier*/ false), |
6193 | 24 | "@usableFromInline "); |
6194 | 24 | } |
6195 | | // Otherwise, suggest changing derivative access level. |
6196 | 104 | else { |
6197 | 104 | fixItAccess(fixItDiag, derivative, originalAccess); |
6198 | 104 | } |
6199 | 128 | return true; |
6200 | 128 | } |
6201 | | |
6202 | | // Get the resolved differentiability parameter indices. |
6203 | 1.42k | auto *resolvedDiffParamIndices = attr->getParameterIndices(); |
6204 | | |
6205 | | // Get the parsed differentiability parameter indices, which have not yet been |
6206 | | // resolved. Parsed differentiability parameter indices are defined only for |
6207 | | // parsed attributes. |
6208 | 1.42k | auto parsedDiffParams = attr->getParsedParameters(); |
6209 | | |
6210 | | // If differentiability parameter indices are not resolved, compute them. |
6211 | 1.42k | if (!resolvedDiffParamIndices) |
6212 | 1.42k | resolvedDiffParamIndices = computeDifferentiabilityParameters( |
6213 | 1.42k | parsedDiffParams, derivative, derivative->getGenericEnvironment(), |
6214 | 1.42k | attr->getAttrName(), attr->getLocation()); |
6215 | 1.42k | if (!resolvedDiffParamIndices) |
6216 | 72 | return true; |
6217 | | |
6218 | | // Set the resolved differentiability parameter indices in the attribute. |
6219 | | // Differentiability parameter indices verification is done by |
6220 | | // `AnyFunctionType::getAutoDiffDerivativeFunctionLinearMapType` below. |
6221 | 1.34k | attr->setParameterIndices(resolvedDiffParamIndices); |
6222 | | |
6223 | | // Compute the expected differential/pullback type. |
6224 | 1.34k | auto expectedLinearMapTypeOrError = |
6225 | 1.34k | originalFnType->getAutoDiffDerivativeFunctionLinearMapType( |
6226 | 1.34k | resolvedDiffParamIndices, kind.getLinearMapKind(), |
6227 | 1.34k | LookUpConformanceInModule(derivative->getModuleContext()), |
6228 | 1.34k | /*makeSelfParamFirst*/ true); |
6229 | | |
6230 | | // Helper for diagnosing derivative function type errors. |
6231 | 1.34k | auto errorHandler = [&](const DerivativeFunctionTypeError &error) { |
6232 | 104 | attr->setInvalid(); |
6233 | 104 | switch (error.kind) { |
6234 | 72 | case DerivativeFunctionTypeError::Kind::NoSemanticResults: |
6235 | 72 | diags |
6236 | 72 | .diagnose(attr->getLocation(), |
6237 | 72 | diag::autodiff_attr_original_void_result, |
6238 | 72 | originalAFD->getName()) |
6239 | 72 | .highlight(attr->getOriginalFunctionName().Loc.getSourceRange()); |
6240 | 72 | return; |
6241 | 8 | case DerivativeFunctionTypeError::Kind::NoDifferentiabilityParameters: |
6242 | 8 | diags.diagnose(attr->getLocation(), |
6243 | 8 | diag::diff_params_clause_no_inferred_parameters); |
6244 | 8 | return; |
6245 | 8 | case DerivativeFunctionTypeError::Kind:: |
6246 | 8 | NonDifferentiableDifferentiabilityParameter: { |
6247 | 8 | auto nonDiffParam = error.getNonDifferentiableTypeAndIndex(); |
6248 | 8 | SourceLoc loc = parsedDiffParams.empty() |
6249 | 8 | ? attr->getLocation() |
6250 | 8 | : parsedDiffParams[nonDiffParam.second].getLoc(); |
6251 | 8 | diags.diagnose(loc, diag::diff_params_clause_param_not_differentiable, |
6252 | 8 | nonDiffParam.first); |
6253 | 8 | return; |
6254 | 0 | } |
6255 | 16 | case DerivativeFunctionTypeError::Kind::NonDifferentiableResult: |
6256 | 16 | auto nonDiffResult = error.getNonDifferentiableTypeAndIndex(); |
6257 | 16 | diags.diagnose(attr->getLocation(), |
6258 | 16 | diag::autodiff_attr_result_not_differentiable, |
6259 | 16 | nonDiffResult.first); |
6260 | 16 | return; |
6261 | 104 | } |
6262 | 104 | }; |
6263 | | // Diagnose any derivative function type errors. |
6264 | 1.34k | if (!expectedLinearMapTypeOrError) { |
6265 | 104 | auto error = expectedLinearMapTypeOrError.takeError(); |
6266 | 104 | handleAllErrors(std::move(error), errorHandler); |
6267 | 104 | return true; |
6268 | 104 | } |
6269 | 1.24k | Type expectedLinearMapType = expectedLinearMapTypeOrError.get(); |
6270 | 1.24k | if (expectedLinearMapType->hasTypeParameter()) |
6271 | 492 | expectedLinearMapType = |
6272 | 492 | derivative->mapTypeIntoContext(expectedLinearMapType); |
6273 | 1.24k | if (expectedLinearMapType->hasArchetype()) |
6274 | 448 | expectedLinearMapType = expectedLinearMapType->mapTypeOutOfContext(); |
6275 | | |
6276 | | // Compute the actual differential/pullback type for comparison with the |
6277 | | // expected type. We must canonicalize the derivative interface type before |
6278 | | // extracting the differential/pullback type from it so that types are |
6279 | | // simplified via the canonical generic signature. |
6280 | 1.24k | CanType canActualResultType = derivativeInterfaceType->getCanonicalType(); |
6281 | 3.30k | while (isa<AnyFunctionType>(canActualResultType)) { |
6282 | 2.06k | canActualResultType = |
6283 | 2.06k | cast<AnyFunctionType>(canActualResultType).getResult(); |
6284 | 2.06k | } |
6285 | 1.24k | CanType actualLinearMapType = |
6286 | 1.24k | cast<TupleType>(canActualResultType).getElementType(1); |
6287 | | |
6288 | | // Check if differential/pullback type matches expected type. |
6289 | 1.24k | if (!actualLinearMapType->isEqual(expectedLinearMapType)) { |
6290 | | // Emit differential/pullback type mismatch error on attribute. |
6291 | 56 | diags.diagnose(attr->getLocation(), |
6292 | 56 | diag::derivative_attr_result_func_type_mismatch, |
6293 | 56 | funcResultElt.getName(), originalAFD); |
6294 | | // Emit note with expected differential/pullback type on actual type |
6295 | | // location. |
6296 | 56 | auto *tupleReturnTypeRepr = |
6297 | 56 | cast<TupleTypeRepr>(derivative->getResultTypeRepr()); |
6298 | 56 | auto *funcEltTypeRepr = tupleReturnTypeRepr->getElementType(1); |
6299 | 56 | diags |
6300 | 56 | .diagnose(funcEltTypeRepr->getStartLoc(), |
6301 | 56 | diag::derivative_attr_result_func_type_mismatch_note, |
6302 | 56 | funcResultElt.getName(), expectedLinearMapType) |
6303 | 56 | .highlight(funcEltTypeRepr->getSourceRange()); |
6304 | | // Emit note showing original function location, if possible. |
6305 | 56 | if (originalAFD->getLoc().isValid()) |
6306 | 56 | diags.diagnose(originalAFD->getLoc(), |
6307 | 56 | diag::derivative_attr_result_func_original_note, |
6308 | 56 | originalAFD); |
6309 | 56 | return true; |
6310 | 56 | } |
6311 | | |
6312 | | // Reject duplicate `@derivative` attributes. |
6313 | 1.18k | auto &derivativeAttrs = Ctx.DerivativeAttrs[std::make_tuple( |
6314 | 1.18k | originalAFD, resolvedDiffParamIndices, kind)]; |
6315 | 1.18k | derivativeAttrs.insert(attr); |
6316 | 1.18k | if (derivativeAttrs.size() > 1) { |
6317 | 40 | diags.diagnose(attr->getLocation(), |
6318 | 40 | diag::derivative_attr_original_already_has_derivative, |
6319 | 40 | originalAFD); |
6320 | 80 | for (auto *duplicateAttr : derivativeAttrs) { |
6321 | 80 | if (duplicateAttr == attr) |
6322 | 40 | continue; |
6323 | 40 | diags.diagnose(duplicateAttr->getLocation(), |
6324 | 40 | diag::derivative_attr_duplicate_note); |
6325 | 40 | } |
6326 | 40 | return true; |
6327 | 40 | } |
6328 | | |
6329 | | // Register derivative function configuration. |
6330 | 1.14k | auto *resultIndices = |
6331 | 1.14k | autodiff::getFunctionSemanticResultIndices(originalAFD, |
6332 | 1.14k | resolvedDiffParamIndices); |
6333 | 1.14k | originalAFD->addDerivativeFunctionConfiguration( |
6334 | 1.14k | {resolvedDiffParamIndices, resultIndices, |
6335 | 1.14k | derivative->getGenericSignature()}); |
6336 | | |
6337 | 1.14k | return false; |
6338 | 1.18k | } |
6339 | | |
6340 | 1.76k | void AttributeChecker::visitDerivativeAttr(DerivativeAttr *attr) { |
6341 | 1.76k | if (typeCheckDerivativeAttr(attr)) |
6342 | 628 | attr->setInvalid(); |
6343 | 1.76k | } |
6344 | | |
6345 | | AbstractFunctionDecl * |
6346 | | DerivativeAttrOriginalDeclRequest::evaluate(Evaluator &evaluator, |
6347 | 1.10k | DerivativeAttr *attr) const { |
6348 | | // Try to resolve the original function. |
6349 | 1.10k | if (attr->isValid() && attr->OriginalFunction.isNull()) |
6350 | 16 | if (typeCheckDerivativeAttr(attr)) |
6351 | 0 | attr->setInvalid(); |
6352 | | |
6353 | | // If the typechecker has resolved the original function, return it. |
6354 | 1.10k | if (auto *FD = attr->OriginalFunction.dyn_cast<AbstractFunctionDecl *>()) |
6355 | 1.09k | return FD; |
6356 | | |
6357 | | // If the function can be lazily resolved, do so now. |
6358 | 8 | if (auto *Resolver = attr->OriginalFunction.dyn_cast<LazyMemberLoader *>()) |
6359 | 8 | return Resolver->loadReferencedFunctionDecl(attr, |
6360 | 8 | attr->ResolverContextData); |
6361 | | |
6362 | 0 | return nullptr; |
6363 | 8 | } |
6364 | | |
6365 | | /// Computes the linearity parameter indices from the given parsed linearity |
6366 | | /// parameters for the given transpose function. On error, emits diagnostics and |
6367 | | /// returns `nullptr`. |
6368 | | /// |
6369 | | /// The attribute location is used in diagnostics. |
6370 | | static IndexSubset * |
6371 | | computeLinearityParameters(ArrayRef<ParsedAutoDiffParameter> parsedLinearParams, |
6372 | | AbstractFunctionDecl *transposeFunction, |
6373 | 548 | SourceLoc attrLoc) { |
6374 | 548 | auto &ctx = transposeFunction->getASTContext(); |
6375 | 548 | auto &diags = ctx.Diags; |
6376 | | |
6377 | | // Get the transpose function type. |
6378 | 548 | auto *transposeFunctionType = |
6379 | 548 | transposeFunction->getInterfaceType()->castTo<AnyFunctionType>(); |
6380 | 548 | bool isCurried = transposeFunctionType->getResult()->is<AnyFunctionType>(); |
6381 | | |
6382 | | // Get transposed result types. |
6383 | | // The transpose function result type may be a singular type or a tuple type. |
6384 | 548 | ArrayRef<TupleTypeElt> transposeResultTypes; |
6385 | 548 | auto transposeResultType = transposeFunctionType->getResult(); |
6386 | 548 | if (isCurried) |
6387 | 364 | transposeResultType = |
6388 | 364 | transposeResultType->castTo<AnyFunctionType>()->getResult(); |
6389 | 548 | if (auto resultTupleType = transposeResultType->getAs<TupleType>()) { |
6390 | 204 | transposeResultTypes = resultTupleType->getElements(); |
6391 | 344 | } else { |
6392 | 344 | transposeResultTypes = ArrayRef<TupleTypeElt>(transposeResultType); |
6393 | 344 | } |
6394 | | |
6395 | | // If `self` is a linearity parameter, the transpose function must be static. |
6396 | 548 | auto isStaticMethod = transposeFunction->isStatic(); |
6397 | 548 | bool wrtSelf = false; |
6398 | 548 | if (!parsedLinearParams.empty()) |
6399 | 548 | wrtSelf = parsedLinearParams.front().getKind() == |
6400 | 548 | ParsedAutoDiffParameter::Kind::Self; |
6401 | 548 | if (wrtSelf && !isStaticMethod) { |
6402 | 0 | diags.diagnose(attrLoc, diag::transpose_attr_wrt_self_must_be_static); |
6403 | 0 | return nullptr; |
6404 | 0 | } |
6405 | | |
6406 | | // Build linearity parameter indices from parsed linearity parameters. |
6407 | 548 | auto numUncurriedParams = transposeFunctionType->getNumParams(); |
6408 | 548 | if (isCurried) { |
6409 | 364 | auto *resultFnType = |
6410 | 364 | transposeFunctionType->getResult()->castTo<AnyFunctionType>(); |
6411 | 364 | numUncurriedParams += resultFnType->getNumParams(); |
6412 | 364 | } |
6413 | 548 | auto numParams = |
6414 | 548 | numUncurriedParams + parsedLinearParams.size() - 1 - (unsigned)wrtSelf; |
6415 | 548 | SmallBitVector parameterBits(numParams); |
6416 | 548 | int lastIndex = -1; |
6417 | 824 | for (unsigned i : indices(parsedLinearParams)) { |
6418 | 824 | auto paramLoc = parsedLinearParams[i].getLoc(); |
6419 | 824 | switch (parsedLinearParams[i].getKind()) { |
6420 | 0 | case ParsedAutoDiffParameter::Kind::Named: { |
6421 | 0 | diags.diagnose(paramLoc, diag::transpose_attr_cannot_use_named_wrt_params, |
6422 | 0 | parsedLinearParams[i].getName()); |
6423 | 0 | return nullptr; |
6424 | 0 | } |
6425 | 188 | case ParsedAutoDiffParameter::Kind::Self: { |
6426 | | // 'self' can only be the first in the list. |
6427 | 188 | if (i > 0) { |
6428 | 0 | diags.diagnose(paramLoc, diag::diff_params_clause_self_must_be_first); |
6429 | 0 | return nullptr; |
6430 | 0 | } |
6431 | 188 | parameterBits.set(parameterBits.size() - 1); |
6432 | 188 | break; |
6433 | 188 | } |
6434 | 636 | case ParsedAutoDiffParameter::Kind::Ordered: { |
6435 | 636 | auto index = parsedLinearParams[i].getIndex(); |
6436 | 636 | if (index >= numParams) { |
6437 | 0 | diags.diagnose(paramLoc, |
6438 | 0 | diag::diff_params_clause_param_index_out_of_range); |
6439 | 0 | return nullptr; |
6440 | 0 | } |
6441 | | // Parameter names must be specified in the original order. |
6442 | 636 | if ((int)index <= lastIndex) { |
6443 | 0 | diags.diagnose(paramLoc, |
6444 | 0 | diag::diff_params_clause_params_not_original_order); |
6445 | 0 | return nullptr; |
6446 | 0 | } |
6447 | 636 | parameterBits.set(index); |
6448 | 636 | lastIndex = index; |
6449 | 636 | break; |
6450 | 636 | } |
6451 | 824 | } |
6452 | 824 | } |
6453 | 548 | return IndexSubset::get(ctx, parameterBits); |
6454 | 548 | } |
6455 | | |
6456 | | /// Checks if the given linearity parameter types are valid for the given |
6457 | | /// original function in the given derivative generic environment and module |
6458 | | /// context. Returns true on error. |
6459 | | /// |
6460 | | /// The parsed differentiability parameters and attribute location are used in |
6461 | | /// diagnostics. |
6462 | | static bool checkLinearityParameters( |
6463 | | AbstractFunctionDecl *originalAFD, |
6464 | | SmallVector<AnyFunctionType::Param, 4> linearParams, |
6465 | | GenericEnvironment *derivativeGenEnv, ModuleDecl *module, |
6466 | 508 | ArrayRef<ParsedAutoDiffParameter> parsedLinearParams, SourceLoc attrLoc) { |
6467 | 508 | auto &ctx = module->getASTContext(); |
6468 | 508 | auto &diags = ctx.Diags; |
6469 | | |
6470 | | // Check that linearity parameters have allowed types. |
6471 | 784 | for (unsigned i : range(linearParams.size())) { |
6472 | 784 | auto linearParamType = linearParams[i].getPlainType(); |
6473 | 784 | if (!linearParamType->hasTypeParameter()) |
6474 | 656 | linearParamType = linearParamType->mapTypeOutOfContext(); |
6475 | 784 | if (derivativeGenEnv) |
6476 | 212 | linearParamType = derivativeGenEnv->mapTypeIntoContext(linearParamType); |
6477 | 572 | else |
6478 | 572 | linearParamType = originalAFD->mapTypeIntoContext(linearParamType); |
6479 | 784 | SourceLoc loc = |
6480 | 784 | parsedLinearParams.empty() ? attrLoc : parsedLinearParams[i].getLoc(); |
6481 | | // Parameter must conform to `Differentiable` and satisfy |
6482 | | // `Self == Self.TangentVector`. |
6483 | 784 | if (!conformsToDifferentiable(linearParamType, module, |
6484 | 784 | /*tangentVectorEqualsSelf*/ true)) { |
6485 | 24 | diags.diagnose(loc, |
6486 | 24 | diag::transpose_attr_invalid_linearity_parameter_or_result, |
6487 | 24 | linearParamType.getString(), /*isParameter*/ true); |
6488 | 24 | return true; |
6489 | 24 | } |
6490 | 784 | } |
6491 | 484 | return false; |
6492 | 508 | } |
6493 | | |
6494 | | /// Given a transpose function type where `self` is a linearity parameter, |
6495 | | /// sets `staticSelfType` and `instanceSelfType` and returns true if they are |
6496 | | /// equals. Otherwise, returns false. |
6497 | | static bool |
6498 | | doTransposeStaticAndInstanceSelfTypesMatch(AnyFunctionType *transposeType, |
6499 | | Type &staticSelfType, |
6500 | 188 | Type &instanceSelfType) { |
6501 | | // Transpose type should have the form: |
6502 | | // `(StaticSelf) -> (...) -> (InstanceSelf, ...)`. |
6503 | 188 | auto methodType = transposeType->getResult()->castTo<AnyFunctionType>(); |
6504 | 188 | auto transposeResult = methodType->getResult(); |
6505 | | |
6506 | | // Get transposed result types. |
6507 | | // The transpose function result type may be a singular type or a tuple type. |
6508 | 188 | SmallVector<TupleTypeElt, 4> transposeResultTypes; |
6509 | 188 | if (auto transposeResultTupleType = transposeResult->getAs<TupleType>()) { |
6510 | 96 | transposeResultTypes.append(transposeResultTupleType->getElements().begin(), |
6511 | 96 | transposeResultTupleType->getElements().end()); |
6512 | 96 | } else { |
6513 | 92 | transposeResultTypes.push_back(transposeResult); |
6514 | 92 | } |
6515 | 188 | assert(!transposeResultTypes.empty()); |
6516 | | |
6517 | | // Get the static and instance `Self` types. |
6518 | 0 | staticSelfType = transposeType->getParams() |
6519 | 188 | .front() |
6520 | 188 | .getPlainType() |
6521 | 188 | ->getMetatypeInstanceType(); |
6522 | 188 | instanceSelfType = transposeResultTypes.front().getType(); |
6523 | | |
6524 | | // Return true if static and instance `Self` types are equal. |
6525 | 188 | return staticSelfType->isEqual(instanceSelfType); |
6526 | 188 | } |
6527 | | |
6528 | 548 | void AttributeChecker::visitTransposeAttr(TransposeAttr *attr) { |
6529 | 548 | auto *transpose = cast<FuncDecl>(D); |
6530 | 548 | auto *module = transpose->getParentModule(); |
6531 | 548 | auto originalName = attr->getOriginalFunctionName(); |
6532 | 548 | auto *transposeInterfaceType = |
6533 | 548 | transpose->getInterfaceType()->castTo<AnyFunctionType>(); |
6534 | 548 | bool isCurried = transposeInterfaceType->getResult()->is<AnyFunctionType>(); |
6535 | | |
6536 | | // Get the linearity parameter indices. |
6537 | 548 | auto *linearParamIndices = attr->getParameterIndices(); |
6538 | | |
6539 | | // Get the parsed linearity parameter indices, which have not yet been |
6540 | | // resolved. Parsed linearity parameter indices are defined only for parsed |
6541 | | // attributes. |
6542 | 548 | auto parsedLinearParams = attr->getParsedParameters(); |
6543 | | |
6544 | | // If linearity parameter indices are not resolved, compute them. |
6545 | 548 | if (!linearParamIndices) |
6546 | 548 | linearParamIndices = computeLinearityParameters( |
6547 | 548 | parsedLinearParams, transpose, attr->getLocation()); |
6548 | 548 | if (!linearParamIndices) { |
6549 | 0 | attr->setInvalid(); |
6550 | 0 | return; |
6551 | 0 | } |
6552 | | |
6553 | | // Diagnose empty linearity parameter indices. This occurs when no `wrt:` |
6554 | | // clause is declared and no linearity parameters can be inferred. |
6555 | 548 | if (linearParamIndices->isEmpty()) { |
6556 | 0 | diagnoseAndRemoveAttr(attr, |
6557 | 0 | diag::diff_params_clause_no_inferred_parameters); |
6558 | 0 | return; |
6559 | 0 | } |
6560 | | |
6561 | 548 | bool wrtSelf = false; |
6562 | 548 | if (!parsedLinearParams.empty()) |
6563 | 548 | wrtSelf = parsedLinearParams.front().getKind() == |
6564 | 548 | ParsedAutoDiffParameter::Kind::Self; |
6565 | | |
6566 | | // If the transpose function is curried and `self` is a linearity parameter, |
6567 | | // check that the instance and static `Self` types are equal. |
6568 | 548 | Type staticSelfType, instanceSelfType; |
6569 | 548 | bool doSelfTypesMatch = false; |
6570 | 548 | if (isCurried && wrtSelf) { |
6571 | 188 | doSelfTypesMatch = doTransposeStaticAndInstanceSelfTypesMatch( |
6572 | 188 | transposeInterfaceType, staticSelfType, instanceSelfType); |
6573 | 188 | if (!doSelfTypesMatch) { |
6574 | 8 | diagnose(attr->getLocation(), |
6575 | 8 | diag::transpose_attr_wrt_self_must_be_static); |
6576 | 8 | diagnose(attr->getLocation(), |
6577 | 8 | diag::transpose_attr_wrt_self_self_type_mismatch_note, |
6578 | 8 | staticSelfType, instanceSelfType); |
6579 | 8 | attr->setInvalid(); |
6580 | 8 | return; |
6581 | 8 | } |
6582 | 188 | } |
6583 | | |
6584 | 540 | auto *expectedOriginalFnType = getTransposeOriginalFunctionType( |
6585 | 540 | transposeInterfaceType, linearParamIndices, wrtSelf); |
6586 | | |
6587 | | // `R` result type must conform to `Differentiable` and satisfy |
6588 | | // `Self == Self.TangentVector`. |
6589 | 540 | auto expectedOriginalResultType = expectedOriginalFnType->getResult(); |
6590 | 540 | if (isCurried) |
6591 | 356 | expectedOriginalResultType = |
6592 | 356 | expectedOriginalResultType->castTo<AnyFunctionType>()->getResult(); |
6593 | 540 | if (expectedOriginalResultType->hasTypeParameter()) |
6594 | 132 | expectedOriginalResultType = transpose->mapTypeIntoContext( |
6595 | 132 | expectedOriginalResultType); |
6596 | 540 | if (!conformsToDifferentiable(expectedOriginalResultType, module, |
6597 | 540 | /*tangentVectorEqualsSelf*/ true)) { |
6598 | 16 | diagnoseAndRemoveAttr( |
6599 | 16 | attr, diag::transpose_attr_invalid_linearity_parameter_or_result, |
6600 | 16 | expectedOriginalResultType.getString(), /*isParameter*/ false); |
6601 | 16 | return; |
6602 | 16 | } |
6603 | | |
6604 | 524 | auto isValidOriginalCandidate = [&](AbstractFunctionDecl *originalCandidate) |
6605 | 596 | -> llvm::Optional<AbstractFunctionDeclLookupErrorKind> { |
6606 | | // Error if the original candidate does not have the expected type. |
6607 | 596 | if (!checkFunctionSignature( |
6608 | 596 | cast<AnyFunctionType>(expectedOriginalFnType->getCanonicalType()), |
6609 | 596 | originalCandidate->getInterfaceType()->getCanonicalType())) |
6610 | 88 | return AbstractFunctionDeclLookupErrorKind::CandidateTypeMismatch; |
6611 | 508 | return llvm::None; |
6612 | 596 | }; |
6613 | | |
6614 | 524 | Type baseType; |
6615 | 524 | if (attr->getBaseTypeRepr()) { |
6616 | 244 | baseType = TypeResolution::resolveContextualType( |
6617 | 244 | attr->getBaseTypeRepr(), transpose->getDeclContext(), llvm::None, |
6618 | 244 | /*unboundTyOpener*/ nullptr, |
6619 | 244 | /*placeholderHandler*/ nullptr, |
6620 | 244 | /*packElementOpener*/ nullptr); |
6621 | 244 | } |
6622 | 524 | auto lookupOptions = |
6623 | 524 | (attr->getBaseTypeRepr() ? defaultMemberLookupOptions |
6624 | 524 | : defaultUnqualifiedLookupOptions) | |
6625 | 524 | NameLookupFlags::IgnoreAccessControl; |
6626 | 524 | auto transposeTypeCtx = transpose->getInnermostTypeContext(); |
6627 | 524 | if (!transposeTypeCtx) transposeTypeCtx = transpose->getParent(); |
6628 | 524 | assert(transposeTypeCtx); |
6629 | | |
6630 | | // Look up original function. |
6631 | 0 | auto funcLoc = originalName.Loc.getBaseNameLoc(); |
6632 | 524 | if (attr->getBaseTypeRepr()) |
6633 | 244 | funcLoc = attr->getBaseTypeRepr()->getLoc(); |
6634 | 524 | auto *originalAFD = findAutoDiffOriginalFunctionDecl( |
6635 | 524 | attr, baseType, originalName, transposeTypeCtx, lookupOptions, |
6636 | 524 | isValidOriginalCandidate, expectedOriginalFnType); |
6637 | 524 | if (!originalAFD) { |
6638 | 16 | attr->setInvalid(); |
6639 | 16 | return; |
6640 | 16 | } |
6641 | 508 | attr->setOriginalFunction(originalAFD); |
6642 | | |
6643 | | // Diagnose if original function has opaque result types. |
6644 | 508 | if (auto *opaqueResultTypeDecl = originalAFD->getOpaqueResultTypeDecl()) { |
6645 | 0 | diagnose(attr->getLocation(), |
6646 | 0 | diag::autodiff_attr_opaque_result_type_unsupported); |
6647 | 0 | attr->setInvalid(); |
6648 | 0 | return; |
6649 | 0 | } |
6650 | | |
6651 | | // Get the linearity parameter types. |
6652 | 508 | SmallVector<AnyFunctionType::Param, 4> linearParams; |
6653 | 508 | expectedOriginalFnType->getSubsetParameters(linearParamIndices, linearParams, |
6654 | 508 | /*reverseCurryLevels*/ true); |
6655 | | |
6656 | | // Check if linearity parameter indices are valid. |
6657 | 508 | if (checkLinearityParameters(originalAFD, linearParams, |
6658 | 508 | transpose->getGenericEnvironment(), |
6659 | 508 | transpose->getModuleContext(), |
6660 | 508 | parsedLinearParams, attr->getLocation())) { |
6661 | 24 | D->getAttrs().removeAttribute(attr); |
6662 | 24 | attr->setInvalid(); |
6663 | 24 | return; |
6664 | 24 | } |
6665 | | |
6666 | | // Returns true if: |
6667 | | // - Original function and transpose function are static methods. |
6668 | | // - Original function and transpose function are non-static methods. |
6669 | | // - Original function is a Constructor declaration and transpose function is |
6670 | | // a static method. |
6671 | 484 | auto compatibleStaticDecls = [&]() { |
6672 | 328 | return (isa<ConstructorDecl>(originalAFD) || originalAFD->isStatic()) == |
6673 | 328 | transpose->isStatic(); |
6674 | 328 | }; |
6675 | | |
6676 | | // Diagnose if original function and transpose differ in terms of static declaration. |
6677 | 484 | if (!doSelfTypesMatch && !compatibleStaticDecls()) { |
6678 | 8 | bool transposeMustBeStatic = !transpose->isStatic(); |
6679 | 8 | diagnose(attr->getOriginalFunctionName().Loc.getBaseNameLoc(), |
6680 | 8 | diag::transpose_attr_static_method_mismatch_original, |
6681 | 8 | originalAFD, transpose, transposeMustBeStatic) |
6682 | 8 | .highlight(attr->getOriginalFunctionName().Loc.getSourceRange()); |
6683 | 8 | diagnose(originalAFD->getNameLoc(), |
6684 | 8 | diag::transpose_attr_static_method_mismatch_original_note, |
6685 | 8 | originalAFD, transposeMustBeStatic); |
6686 | 8 | auto fixItDiag = diagnose(transpose->getStartLoc(), |
6687 | 8 | diag::transpose_attr_static_method_mismatch_fix, |
6688 | 8 | transpose, transposeMustBeStatic); |
6689 | 8 | if (transposeMustBeStatic) { |
6690 | 8 | fixItDiag.fixItInsert(transpose->getStartLoc(), "static "); |
6691 | 8 | } else { |
6692 | 0 | fixItDiag.fixItRemove(transpose->getStaticLoc()); |
6693 | 0 | } |
6694 | 8 | return; |
6695 | 8 | } |
6696 | | |
6697 | | // Set the resolved linearity parameter indices in the attribute. |
6698 | 476 | attr->setParameterIndices(linearParamIndices); |
6699 | 476 | } |
6700 | | |
6701 | 0 | void AttributeChecker::visitActorAttr(ActorAttr *attr) { |
6702 | 0 | auto classDecl = dyn_cast<ClassDecl>(D); |
6703 | 0 | if (!classDecl) |
6704 | 0 | return; // already diagnosed |
6705 | | |
6706 | 0 | (void)classDecl->isActor(); |
6707 | 0 | } |
6708 | | |
6709 | 1.33k | void AttributeChecker::visitDistributedActorAttr(DistributedActorAttr *attr) { |
6710 | 1.33k | auto dc = D->getDeclContext(); |
6711 | | |
6712 | | // distributed can be applied to actor definitions and their methods |
6713 | 1.33k | if (auto varDecl = dyn_cast<VarDecl>(D)) { |
6714 | 78 | if (varDecl->isDistributed()) { |
6715 | 78 | if (checkDistributedActorProperty(varDecl, /*diagnose=*/true)) |
6716 | 48 | return; |
6717 | 78 | } else { |
6718 | | // distributed can not be applied to stored properties |
6719 | 0 | diagnoseAndRemoveAttr(attr, diag::distributed_actor_property); |
6720 | 0 | return; |
6721 | 0 | } |
6722 | 78 | } |
6723 | | |
6724 | | // distributed can only be declared on an `actor` |
6725 | 1.28k | if (auto classDecl = dyn_cast<ClassDecl>(D)) { |
6726 | 474 | if (!classDecl->isActor()) { |
6727 | 6 | diagnoseAndRemoveAttr(attr, diag::distributed_actor_not_actor); |
6728 | 6 | return; |
6729 | 468 | } else { |
6730 | | // good: `distributed actor` |
6731 | 468 | return; |
6732 | 468 | } |
6733 | 810 | } else if (dyn_cast<StructDecl>(D) || dyn_cast<EnumDecl>(D)) { |
6734 | 0 | diagnoseAndRemoveAttr( |
6735 | 0 | attr, diag::distributed_actor_func_not_in_distributed_actor); |
6736 | 0 | return; |
6737 | 0 | } |
6738 | | |
6739 | 810 | if (auto funcDecl = dyn_cast<AbstractFunctionDecl>(D)) { |
6740 | | // distributed functions must not be static |
6741 | 780 | if (funcDecl->isStatic()) { |
6742 | 12 | diagnoseAndRemoveAttr(attr, diag::distributed_actor_func_static); |
6743 | 12 | return; |
6744 | 12 | } |
6745 | | |
6746 | | // distributed func cannot be simultaneously nonisolated |
6747 | 768 | if (auto nonisolated = |
6748 | 768 | funcDecl->getAttrs().getAttribute<NonisolatedAttr>()) { |
6749 | 6 | diagnoseAndRemoveAttr(nonisolated, |
6750 | 6 | diag::distributed_actor_func_nonisolated, |
6751 | 6 | funcDecl->getName()); |
6752 | 6 | return; |
6753 | 6 | } |
6754 | | |
6755 | | // distributed func must be declared inside an distributed actor |
6756 | 762 | auto selfTy = dc->getSelfTypeInContext(); |
6757 | 762 | if (!selfTy->isDistributedActor()) { |
6758 | 30 | auto diagnostic = diagnoseAndRemoveAttr( |
6759 | 30 | attr, diag::distributed_actor_func_not_in_distributed_actor); |
6760 | | |
6761 | 30 | if (auto *protoDecl = dc->getSelfProtocolDecl()) { |
6762 | 9 | diagnoseDistributedFunctionInNonDistributedActorProtocol(protoDecl, |
6763 | 9 | diagnostic); |
6764 | 9 | } |
6765 | 30 | return; |
6766 | 30 | } |
6767 | 762 | } |
6768 | 810 | } |
6769 | | |
6770 | 0 | void AttributeChecker::visitKnownToBeLocalAttr(KnownToBeLocalAttr *attr) { |
6771 | 0 | if (!D->isImplicit()) { |
6772 | 0 | diagnoseAndRemoveAttr(attr, diag::distributed_local_cannot_be_used); |
6773 | 0 | } |
6774 | 0 | } |
6775 | | |
6776 | 279 | void AttributeChecker::visitSendableAttr(SendableAttr *attr) { |
6777 | | |
6778 | 279 | auto dc = D->getDeclContext(); |
6779 | | |
6780 | 279 | if ((isa<AbstractFunctionDecl>(D) || isa<AbstractStorageDecl>(D)) && |
6781 | 279 | !isAsyncDecl(cast<ValueDecl>(D))) { |
6782 | 183 | auto value = cast<ValueDecl>(D); |
6783 | 183 | ActorIsolation isolation = getActorIsolation(value); |
6784 | 183 | if (isolation.isActorIsolated()) { |
6785 | 24 | diagnoseAndRemoveAttr( |
6786 | 24 | attr, diag::sendable_isolated_sync_function, |
6787 | 24 | isolation, value) |
6788 | 24 | .warnUntilSwiftVersion(6); |
6789 | 24 | } |
6790 | 183 | } |
6791 | | // Prevent Sendable Attr from being added to methods of non-sendable types |
6792 | 279 | if (auto *funcDecl = dyn_cast<AbstractFunctionDecl>(D)) { |
6793 | 279 | if (auto selfdecl = funcDecl->getImplicitSelfDecl()) { |
6794 | 81 | if (!isSendableType(dc->getParentModule(), selfdecl->getTypeInContext())) { |
6795 | 30 | diagnose(attr->getLocation(), diag::nonsendable_instance_method) |
6796 | 30 | .warnUntilSwiftVersion(6); |
6797 | 30 | } |
6798 | 81 | } |
6799 | 279 | } |
6800 | 279 | } |
6801 | | |
6802 | 6.28k | void AttributeChecker::visitNonisolatedAttr(NonisolatedAttr *attr) { |
6803 | | // 'nonisolated' can be applied to global and static/class variables |
6804 | | // that do not have storage. |
6805 | 6.28k | auto dc = D->getDeclContext(); |
6806 | | |
6807 | 6.28k | if (auto var = dyn_cast<VarDecl>(D)) { |
6808 | | // stored properties have limitations as to when they can be nonisolated. |
6809 | 4.91k | if (var->hasStorage()) { |
6810 | 1.03k | const bool isUnsafeGlobal = attr->isUnsafe() && var->isGlobalStorage(); |
6811 | | |
6812 | | // 'nonisolated' can not be applied to mutable stored properties. |
6813 | 1.03k | if (var->supportsMutation() && !isUnsafeGlobal) { |
6814 | 6 | diagnoseAndRemoveAttr(attr, diag::nonisolated_mutable_storage); |
6815 | 6 | return; |
6816 | 6 | } |
6817 | | |
6818 | 1.02k | if (auto nominal = dyn_cast<NominalTypeDecl>(dc)) { |
6819 | | // 'nonisolated' can not be applied to stored properties inside |
6820 | | // distributed actors. Attempts of nonisolated access would be |
6821 | | // cross-actor, which means they might be accessing on a remote actor, |
6822 | | // in which case the stored property storage does not exist. |
6823 | | // |
6824 | | // The synthesized "id" and "actorSystem" are the only exceptions, |
6825 | | // because the implementation mirrors them. |
6826 | 1.00k | if (nominal->isDistributedActor() && |
6827 | 1.00k | !(var->getName() == Ctx.Id_id || |
6828 | 906 | var->getName() == Ctx.Id_actorSystem)) { |
6829 | 3 | diagnoseAndRemoveAttr(attr, |
6830 | 3 | diag::nonisolated_distributed_actor_storage); |
6831 | 3 | return; |
6832 | 3 | } |
6833 | | |
6834 | | // 'nonisolated' is redundant for the stored properties of a struct. |
6835 | 1.00k | if (isa<StructDecl>(nominal) && |
6836 | 1.00k | !var->isStatic() && |
6837 | 1.00k | var->isOrdinaryStoredProperty() && |
6838 | 1.00k | !isWrappedValueOfPropWrapper(var)) { |
6839 | 12 | diagnoseAndRemoveAttr(attr, diag::nonisolated_storage_value_type, |
6840 | 12 | nominal->getDescriptiveKind()) |
6841 | 12 | .warnUntilSwiftVersion(6); |
6842 | 12 | return; |
6843 | 12 | } |
6844 | 1.00k | } |
6845 | 1.02k | } |
6846 | | |
6847 | | // Using 'nonisolated' with wrapped properties is unsupported, because |
6848 | | // backing storage is a stored 'var' that is part of the internal state |
6849 | | // of the actor which could only be accessed in actor's isolation context. |
6850 | 4.89k | if (var->hasAttachedPropertyWrapper()) { |
6851 | 12 | diagnoseAndRemoveAttr(attr, diag::nonisolated_wrapped_property); |
6852 | 12 | return; |
6853 | 12 | } |
6854 | | |
6855 | | // nonisolated can not be applied to local properties. |
6856 | 4.88k | if (dc->isLocalContext()) { |
6857 | 0 | diagnoseAndRemoveAttr(attr, diag::nonisolated_local_var); |
6858 | 0 | return; |
6859 | 0 | } |
6860 | | |
6861 | | // If this is a static or global variable, we're all set. |
6862 | 4.88k | if (dc->isModuleScopeContext() || |
6863 | 4.88k | (dc->isTypeContext() && var->isStatic())) { |
6864 | 42 | return; |
6865 | 42 | } |
6866 | 4.88k | } |
6867 | | |
6868 | | // `nonisolated` on non-async actor initializers is invalid. |
6869 | | // the reasoning is that there is a "little bit" of isolation, |
6870 | | // as afforded by flow-isolation. |
6871 | 6.21k | if (auto ctor = dyn_cast<ConstructorDecl>(D)) { |
6872 | 240 | if (auto nominal = dyn_cast<NominalTypeDecl>(dc)) { |
6873 | 240 | if (nominal->isAnyActor()) { |
6874 | 63 | if (!ctor->hasAsync()) { |
6875 | | // the isolation for a synchronous init cannot be `nonisolated`. |
6876 | 18 | diagnoseAndRemoveAttr(attr, diag::nonisolated_actor_sync_init) |
6877 | 18 | .warnUntilSwiftVersion(6); |
6878 | 18 | return; |
6879 | 18 | } |
6880 | 63 | } |
6881 | 240 | } |
6882 | 240 | } |
6883 | | |
6884 | 6.19k | if (auto VD = dyn_cast<ValueDecl>(D)) { |
6885 | 6.19k | (void)getActorIsolation(VD); |
6886 | 6.19k | } |
6887 | 6.19k | } |
6888 | | |
6889 | 432 | void AttributeChecker::visitGlobalActorAttr(GlobalActorAttr *attr) { |
6890 | 432 | auto nominal = dyn_cast<NominalTypeDecl>(D); |
6891 | 432 | if (!nominal) |
6892 | 0 | return; // already diagnosed |
6893 | | |
6894 | 432 | auto &context = nominal->getASTContext(); |
6895 | 432 | if (context.LangOpts.isConcurrencyModelTaskToThread() && |
6896 | 432 | !AvailableAttr::isUnavailable(nominal)) { |
6897 | 0 | context.Diags.diagnose(attr->getLocation(), |
6898 | 0 | diag::concurrency_task_to_thread_model_global_actor, |
6899 | 0 | "task-to-thread concurrency model"); |
6900 | 0 | return; |
6901 | 0 | } |
6902 | | |
6903 | 432 | (void)nominal->isGlobalActor(); |
6904 | 432 | } |
6905 | | |
6906 | 480 | void AttributeChecker::visitAsyncAttr(AsyncAttr *attr) { |
6907 | 480 | auto var = dyn_cast<VarDecl>(D); |
6908 | 480 | if (!var) |
6909 | 0 | return; |
6910 | | |
6911 | 480 | auto patternBinding = var->getParentPatternBinding(); |
6912 | 480 | if (!patternBinding) |
6913 | 0 | return; // already diagnosed |
6914 | | |
6915 | | // "Async" modifier can only be applied to local declarations. |
6916 | 480 | if (!patternBinding->getDeclContext()->isLocalContext()) { |
6917 | 3 | diagnoseAndRemoveAttr(attr, diag::async_let_not_local); |
6918 | 3 | return; |
6919 | 3 | } |
6920 | | |
6921 | | // Check each of the pattern binding entries. |
6922 | 477 | bool diagnosedVar = false; |
6923 | 483 | for (unsigned index : range(patternBinding->getNumPatternEntries())) { |
6924 | 483 | auto pattern = patternBinding->getPattern(index); |
6925 | | |
6926 | | // Look for variables bound by this pattern. |
6927 | 483 | bool foundAnyVariable = false; |
6928 | 483 | bool isLet = true; |
6929 | 492 | pattern->forEachVariable([&](VarDecl *var) { |
6930 | 492 | if (!var->isLet()) |
6931 | 3 | isLet = false; |
6932 | 492 | foundAnyVariable = true; |
6933 | 492 | }); |
6934 | | |
6935 | | // Each entry must bind at least one named variable, so that there is |
6936 | | // something to "await". |
6937 | 483 | if (!foundAnyVariable) { |
6938 | 3 | diagnose(pattern->getLoc(), diag::async_let_no_variables); |
6939 | 3 | attr->setInvalid(); |
6940 | 3 | return; |
6941 | 3 | } |
6942 | | |
6943 | | // Async can only be used on an "async let". |
6944 | 480 | if (!isLet && !diagnosedVar) { |
6945 | 3 | diagnose(patternBinding->getLoc(), diag::async_not_let) |
6946 | 3 | .fixItReplace(patternBinding->getLoc(), "let"); |
6947 | 3 | diagnosedVar = true; |
6948 | 3 | } |
6949 | | |
6950 | | // Each pattern entry must have an initializer expression. |
6951 | 480 | if (patternBinding->getEqualLoc(index).isInvalid()) { |
6952 | 3 | diagnose(pattern->getLoc(), diag::async_let_not_initialized); |
6953 | 3 | attr->setInvalid(); |
6954 | 3 | return; |
6955 | 3 | } |
6956 | 480 | } |
6957 | 477 | } |
6958 | | |
6959 | 294 | void AttributeChecker::visitMarkerAttr(MarkerAttr *attr) { |
6960 | 294 | auto proto = dyn_cast<ProtocolDecl>(D); |
6961 | 294 | if (!proto) |
6962 | 0 | return; |
6963 | | |
6964 | | // A marker protocol cannot inherit a non-marker protocol. |
6965 | 294 | for (auto inheritedProto : proto->getInheritedProtocols()) { |
6966 | 63 | if (!inheritedProto->isMarkerProtocol()) { |
6967 | 3 | proto->diagnose( |
6968 | 3 | diag::marker_protocol_inherit_nonmarker, |
6969 | 3 | proto->getName(), inheritedProto->getName()); |
6970 | 3 | inheritedProto->diagnose( diag::decl_declared_here, inheritedProto); |
6971 | 3 | } |
6972 | 63 | } |
6973 | | |
6974 | 294 | if (Type superclass = proto->getSuperclass()) { |
6975 | 3 | proto->diagnose( |
6976 | 3 | diag::marker_protocol_inherit_class, |
6977 | 3 | proto->getName(), superclass); |
6978 | 3 | } |
6979 | | |
6980 | | // A marker protocol cannot have any requirements. |
6981 | 294 | for (auto member : proto->getAllMembers()) { |
6982 | 9 | auto value = dyn_cast<ValueDecl>(member); |
6983 | 9 | if (!value) |
6984 | 0 | continue; |
6985 | | |
6986 | 9 | if (value->isProtocolRequirement()) { |
6987 | 6 | value->diagnose(diag::marker_protocol_requirement, proto->getName()); |
6988 | 6 | break; |
6989 | 6 | } |
6990 | 9 | } |
6991 | 294 | } |
6992 | | |
6993 | 189 | void AttributeChecker::visitReasyncAttr(ReasyncAttr *attr) { |
6994 | | // Make sure the function takes a 'throws' function argument or a |
6995 | | // conformance to a '@rethrows' protocol. |
6996 | 189 | auto fn = dyn_cast<AbstractFunctionDecl>(D); |
6997 | 189 | if (fn->getPolymorphicEffectKind(EffectKind::Async) |
6998 | 189 | != PolymorphicEffectKind::Invalid) { |
6999 | 177 | return; |
7000 | 177 | } |
7001 | | |
7002 | 12 | diagnose(attr->getLocation(), diag::reasync_without_async_parameter); |
7003 | 12 | attr->setInvalid(); |
7004 | 12 | } |
7005 | | |
7006 | | void AttributeChecker::visitUnavailableFromAsyncAttr( |
7007 | 636 | UnavailableFromAsyncAttr *attr) { |
7008 | 636 | if (DeclContext *dc = dyn_cast<DeclContext>(D)) { |
7009 | 636 | if (dc->isAsyncContext()) { |
7010 | 12 | if (ValueDecl *vd = dyn_cast<ValueDecl>(D)) { |
7011 | 12 | D->getASTContext().Diags.diagnose( |
7012 | 12 | D->getLoc(), diag::async_named_decl_must_be_available_from_async, |
7013 | 12 | vd); |
7014 | 12 | } else { |
7015 | 0 | D->getASTContext().Diags.diagnose( |
7016 | 0 | D->getLoc(), diag::async_decl_must_be_available_from_async, |
7017 | 0 | D->getDescriptiveKind()); |
7018 | 0 | } |
7019 | 12 | } |
7020 | 636 | } |
7021 | 636 | } |
7022 | | |
7023 | | void AttributeChecker::visitUnsafeInheritExecutorAttr( |
7024 | 474 | UnsafeInheritExecutorAttr *attr) { |
7025 | 474 | auto fn = cast<FuncDecl>(D); |
7026 | 474 | if (!fn->isAsyncContext()) { |
7027 | 24 | diagnose(attr->getLocation(), diag::inherits_executor_without_async); |
7028 | 24 | } |
7029 | 474 | } |
7030 | | |
7031 | 192 | bool AttributeChecker::visitLifetimeAttr(DeclAttribute *attr) { |
7032 | 192 | if (auto *funcDecl = dyn_cast<FuncDecl>(D)) { |
7033 | 51 | auto declContext = funcDecl->getDeclContext(); |
7034 | | // eagerMove attribute may only appear in type context |
7035 | 51 | if (!declContext->getDeclaredInterfaceType()) { |
7036 | 6 | diagnoseAndRemoveAttr(attr, diag::lifetime_invalid_global_scope, attr); |
7037 | 6 | return true; |
7038 | 6 | } |
7039 | 51 | } |
7040 | 186 | return false; |
7041 | 192 | } |
7042 | | |
7043 | 129 | void AttributeChecker::visitEagerMoveAttr(EagerMoveAttr *attr) { |
7044 | 129 | if (visitLifetimeAttr(attr)) |
7045 | 3 | return; |
7046 | 126 | if (auto *nominal = dyn_cast<NominalTypeDecl>(D)) { |
7047 | 45 | if (nominal->getDeclaredInterfaceType()->isNoncopyable()) { |
7048 | 3 | diagnoseAndRemoveAttr(attr, diag::eagermove_and_noncopyable_combined); |
7049 | 3 | return; |
7050 | 3 | } |
7051 | 45 | } |
7052 | 123 | if (auto *func = dyn_cast<FuncDecl>(D)) { |
7053 | 21 | auto *self = func->getImplicitSelfDecl(); |
7054 | 21 | if (self && self->getTypeInContext()->isNoncopyable()) { |
7055 | 3 | diagnoseAndRemoveAttr(attr, diag::eagermove_and_noncopyable_combined); |
7056 | 3 | return; |
7057 | 3 | } |
7058 | 21 | } |
7059 | 120 | if (auto *pd = dyn_cast<ParamDecl>(D)) { |
7060 | 33 | if (pd->getTypeInContext()->isNoncopyable()) { |
7061 | 3 | diagnoseAndRemoveAttr(attr, diag::eagermove_and_noncopyable_combined); |
7062 | 3 | return; |
7063 | 3 | } |
7064 | 33 | } |
7065 | 120 | } |
7066 | | |
7067 | 48 | void AttributeChecker::visitNoEagerMoveAttr(NoEagerMoveAttr *attr) { |
7068 | 48 | if (visitLifetimeAttr(attr)) |
7069 | 3 | return; |
7070 | | // @_noEagerMove and @_eagerMove are opposites and can't be combined. |
7071 | 45 | if (D->getAttrs().hasAttribute<EagerMoveAttr>()) { |
7072 | 6 | diagnoseAndRemoveAttr(attr, diag::eagermove_and_lexical_combined); |
7073 | 6 | return; |
7074 | 6 | } |
7075 | 45 | } |
7076 | | |
7077 | | void AttributeChecker::visitCompilerInitializedAttr( |
7078 | 489 | CompilerInitializedAttr *attr) { |
7079 | 489 | auto var = cast<VarDecl>(D); |
7080 | | |
7081 | | // For now, ban its use within protocols. I could imagine supporting it |
7082 | | // by saying that witnesses must also be compiler-initialized, but I can't |
7083 | | // think of a use case for that right now. |
7084 | 489 | if (auto ctx = var->getDeclContext()) { |
7085 | 489 | if (isa<ProtocolDecl>(ctx) && var->isProtocolRequirement()) { |
7086 | 3 | diagnose(attr->getLocation(), diag::protocol_compilerinitialized); |
7087 | 3 | return; |
7088 | 3 | } |
7089 | 489 | } |
7090 | | |
7091 | | // Must be a let-bound stored property without an initial value. |
7092 | | // The fact that it's let-bound generally simplifies the implementation |
7093 | | // of this attribute in definite initialization, since we don't need to |
7094 | | // reason about whether the compiler made the first assignment to the var, |
7095 | | // etc. |
7096 | 486 | if (var->hasInitialValue() |
7097 | 486 | || !var->isOrdinaryStoredProperty() |
7098 | 486 | || !var->isLet()) { |
7099 | 15 | diagnose(attr->getLocation(), diag::incompatible_compilerinitialized_var); |
7100 | 15 | return; |
7101 | 15 | } |
7102 | | |
7103 | | // Because optionals are implicitly initialized to nil according to the |
7104 | | // language, this attribute doesn't make sense on optionals. |
7105 | 471 | if (var->getTypeInContext()->isOptional()) { |
7106 | 3 | diagnose(attr->getLocation(), diag::optional_compilerinitialized); |
7107 | 3 | return; |
7108 | 3 | } |
7109 | | |
7110 | | // To keep things even more simple in definite initialization, restrict |
7111 | | // the attribute to class/actor instance members only. This means we can |
7112 | | // focus just on the initialization in the init. |
7113 | 468 | if (!(var->getDeclContext()->getSelfClassDecl() && var->isInstanceMember())) { |
7114 | 9 | diagnose(attr->getLocation(), diag::instancemember_compilerinitialized); |
7115 | 9 | return; |
7116 | 9 | } |
7117 | 468 | } |
7118 | | |
7119 | 2.37k | void AttributeChecker::visitMacroRoleAttr(MacroRoleAttr *attr) { |
7120 | 2.37k | switch (attr->getMacroSyntax()) { |
7121 | 1.56k | case MacroSyntax::Freestanding: { |
7122 | 1.56k | switch (attr->getMacroRole()) { |
7123 | 891 | case MacroRole::Expression: |
7124 | 891 | if (!attr->getNames().empty()) |
7125 | 0 | diagnoseAndRemoveAttr(attr, diag::macro_cannot_introduce_names, |
7126 | 0 | getMacroRoleString(attr->getMacroRole())); |
7127 | 891 | break; |
7128 | 642 | case MacroRole::Declaration: |
7129 | | // TODO: Check names |
7130 | 642 | break; |
7131 | 27 | case MacroRole::CodeItem: |
7132 | 27 | if (!attr->getNames().empty()) |
7133 | 3 | diagnoseAndRemoveAttr(attr, diag::macro_cannot_introduce_names, |
7134 | 3 | getMacroRoleString(attr->getMacroRole())); |
7135 | 27 | break; |
7136 | 0 | default: |
7137 | 0 | diagnoseAndRemoveAttr(attr, diag::invalid_macro_role_for_macro_syntax, |
7138 | 0 | /*freestanding*/0); |
7139 | 0 | break; |
7140 | 1.56k | } |
7141 | 1.56k | break; |
7142 | 1.56k | } |
7143 | 1.56k | case MacroSyntax::Attached: { |
7144 | 810 | switch (attr->getMacroRole()) { |
7145 | 147 | case MacroRole::Accessor: |
7146 | | // TODO: Check property observer names? |
7147 | 147 | break; |
7148 | 42 | case MacroRole::MemberAttribute: |
7149 | 42 | if (!attr->getNames().empty()) |
7150 | 0 | diagnoseAndRemoveAttr(attr, diag::macro_cannot_introduce_names, |
7151 | 0 | getMacroRoleString(attr->getMacroRole())); |
7152 | 42 | break; |
7153 | 198 | case MacroRole::Member: |
7154 | 198 | break; |
7155 | 198 | case MacroRole::Peer: |
7156 | 198 | break; |
7157 | 6 | case MacroRole::Conformance: { |
7158 | | // Suppress the conformance macro error in swiftinterfaces. |
7159 | 6 | SourceFile *file = D->getDeclContext()->getParentSourceFile(); |
7160 | 6 | if (file && file->Kind == SourceFileKind::Interface) |
7161 | 3 | break; |
7162 | | |
7163 | 3 | diagnoseAndRemoveAttr(attr, diag::conformance_macro) |
7164 | 3 | .fixItReplace(attr->getRange(), |
7165 | 3 | "@attached(extension, conformances: <#Protocol#>)"); |
7166 | 3 | break; |
7167 | 6 | } |
7168 | 219 | case MacroRole::Extension: |
7169 | 219 | break; |
7170 | 0 | default: |
7171 | 0 | diagnoseAndRemoveAttr(attr, diag::invalid_macro_role_for_macro_syntax, |
7172 | 0 | /*attached*/1); |
7173 | 0 | break; |
7174 | 810 | } |
7175 | 810 | break; |
7176 | 810 | } |
7177 | 2.37k | } |
7178 | | |
7179 | 2.37k | (void)evaluateOrDefault( |
7180 | 2.37k | Ctx.evaluator, |
7181 | 2.37k | ResolveMacroConformances{attr, D}, |
7182 | 2.37k | {}); |
7183 | 2.37k | } |
7184 | | |
7185 | 129 | void AttributeChecker::visitRawLayoutAttr(RawLayoutAttr *attr) { |
7186 | 129 | if (!Ctx.LangOpts.hasFeature(Feature::RawLayout)) { |
7187 | 0 | diagnoseAndRemoveAttr(attr, diag::attr_rawlayout_experimental); |
7188 | 0 | return; |
7189 | 0 | } |
7190 | | |
7191 | | // Can only apply to structs. |
7192 | 129 | auto sd = dyn_cast<StructDecl>(D); |
7193 | 129 | if (!sd) { |
7194 | 0 | diagnoseAndRemoveAttr(attr, diag::attr_only_one_decl_kind, |
7195 | 0 | attr, "struct"); |
7196 | 0 | return; |
7197 | 0 | } |
7198 | | |
7199 | 129 | if (!sd->canBeNoncopyable()) { |
7200 | 3 | diagnoseAndRemoveAttr(attr, diag::attr_rawlayout_cannot_be_copyable); |
7201 | 3 | } |
7202 | | |
7203 | 129 | if (!sd->getStoredProperties().empty()) { |
7204 | 12 | diagnoseAndRemoveAttr(attr, diag::attr_rawlayout_cannot_have_stored_properties); |
7205 | 12 | } |
7206 | | |
7207 | 129 | if (auto sizeAndAlign = attr->getSizeAndAlignment()) { |
7208 | | // Alignment must be a power of two. |
7209 | 60 | auto align = sizeAndAlign->second; |
7210 | 60 | if (align == 0 || (align & (align - 1)) != 0) { |
7211 | 3 | diagnoseAndRemoveAttr(attr, diag::alignment_not_power_of_two); |
7212 | 3 | return; |
7213 | 3 | } |
7214 | 69 | } else if (attr->getScalarLikeType()) { |
7215 | 36 | (void)attr->getResolvedLikeType(sd); |
7216 | 36 | } else if (attr->getArrayLikeTypeAndCount()) { |
7217 | 33 | (void)attr->getResolvedLikeType(sd); |
7218 | 33 | } else { |
7219 | 0 | llvm_unreachable("new unhandled rawLayout attribute form?"); |
7220 | 0 | } |
7221 | | |
7222 | | // If the type also specifies an `@_alignment`, that's an error. |
7223 | | // Maybe this is interesting to support to have a layout like another |
7224 | | // type but with different alignment in the future. |
7225 | 126 | if (D->getAttrs().hasAttribute<AlignmentAttr>()) { |
7226 | 3 | diagnoseAndRemoveAttr(attr, diag::attr_rawlayout_cannot_have_alignment_attr); |
7227 | 3 | return; |
7228 | 3 | } |
7229 | | |
7230 | | // The storage is not directly referenceable by stored properties. |
7231 | 123 | sd->setHasUnreferenceableStorage(true); |
7232 | 123 | } |
7233 | | |
7234 | 3 | void AttributeChecker::visitNonEscapableAttr(NonEscapableAttr *attr) { |
7235 | 3 | if (!Ctx.LangOpts.hasFeature(Feature::NonEscapableTypes)) { |
7236 | 0 | diagnoseAndRemoveAttr(attr, diag::nonescapable_types_attr_disabled); |
7237 | 0 | } |
7238 | 3 | } |
7239 | | |
7240 | | void AttributeChecker::visitUnsafeNonEscapableResultAttr( |
7241 | 6 | UnsafeNonEscapableResultAttr *attr) { |
7242 | 6 | if (!Ctx.LangOpts.hasFeature(Feature::NonEscapableTypes)) { |
7243 | 0 | diagnoseAndRemoveAttr(attr, diag::nonescapable_types_attr_disabled); |
7244 | 0 | } |
7245 | 6 | } |
7246 | | |
7247 | | namespace { |
7248 | | |
7249 | | class ClosureAttributeChecker |
7250 | | : public AttributeVisitor<ClosureAttributeChecker> { |
7251 | | ASTContext &ctx; |
7252 | | ClosureExpr *closure; |
7253 | | public: |
7254 | | ClosureAttributeChecker(ClosureExpr *closure) |
7255 | 136k | : ctx(closure->getASTContext()), closure(closure) { } |
7256 | | |
7257 | 6 | void visitDeclAttribute(DeclAttribute *attr) { |
7258 | 6 | ctx.Diags.diagnose( |
7259 | 6 | attr->getLocation(), diag::unsupported_closure_attr, |
7260 | 6 | attr->isDeclModifier(), attr->getAttrName()) |
7261 | 6 | .fixItRemove(attr->getRangeWithAt()); |
7262 | 6 | attr->setInvalid(); |
7263 | 6 | } |
7264 | | |
7265 | 42 | void visitSendableAttr(SendableAttr *attr) { |
7266 | | // Nothing else to check. |
7267 | 42 | } |
7268 | | |
7269 | 624 | void visitCustomAttr(CustomAttr *attr) { |
7270 | | // Check whether this custom attribute is the global actor attribute. |
7271 | 624 | auto globalActorAttr = evaluateOrDefault( |
7272 | 624 | ctx.evaluator, GlobalActorAttributeRequest{closure}, llvm::None); |
7273 | | |
7274 | 624 | if (globalActorAttr && globalActorAttr->first == attr) { |
7275 | | // if there is an `isolated` parameter, then this global-actor attribute |
7276 | | // is invalid. |
7277 | 624 | for (auto param : *closure->getParameters()) { |
7278 | 99 | if (param->isIsolated()) { |
7279 | 12 | param->diagnose( |
7280 | 12 | diag::isolated_parameter_closure_combined_global_actor_attr, |
7281 | 12 | param->getName()) |
7282 | 12 | .fixItRemove(attr->getRangeWithAt()) |
7283 | 12 | .warnUntilSwiftVersion(6); |
7284 | 12 | attr->setInvalid(); |
7285 | 12 | break; // don't need to complain about this more than once. |
7286 | 12 | } |
7287 | 99 | } |
7288 | | |
7289 | 624 | return; // it's OK |
7290 | 624 | } |
7291 | | |
7292 | | // Otherwise, it's an error. |
7293 | 0 | std::string typeName; |
7294 | 0 | if (auto typeRepr = attr->getTypeRepr()) { |
7295 | 0 | llvm::raw_string_ostream out(typeName); |
7296 | 0 | typeRepr->print(out); |
7297 | 0 | } else { |
7298 | 0 | typeName = attr->getType().getString(); |
7299 | 0 | } |
7300 | |
|
7301 | 0 | ctx.Diags.diagnose( |
7302 | 0 | attr->getLocation(), diag::unsupported_closure_attr, |
7303 | 0 | attr->isDeclModifier(), typeName) |
7304 | 0 | .fixItRemove(attr->getRangeWithAt()); |
7305 | 0 | attr->setInvalid(); |
7306 | 0 | } |
7307 | | }; |
7308 | | |
7309 | | } |
7310 | | |
7311 | 136k | void TypeChecker::checkClosureAttributes(ClosureExpr *closure) { |
7312 | 136k | ClosureAttributeChecker checker(closure); |
7313 | 136k | for (auto attr : closure->getAttrs()) { |
7314 | 672 | checker.visit(attr); |
7315 | 672 | } |
7316 | 136k | } |
7317 | | |
7318 | | static bool renameCouldMatch(const ValueDecl *original, |
7319 | | const ValueDecl *candidate, |
7320 | | bool originalIsObjCVisible, |
7321 | 789 | AccessLevel minAccess) { |
7322 | | // Can't match itself |
7323 | 789 | if (original == candidate) |
7324 | 12 | return false; |
7325 | | |
7326 | | // Kinds have to match, but we want to allow eg. an accessor to match |
7327 | | // a function |
7328 | 777 | if (candidate->getKind() != original->getKind() && |
7329 | 777 | !(isa<FuncDecl>(candidate) && isa<FuncDecl>(original))) |
7330 | 27 | return false; |
7331 | | |
7332 | | // Instance can't match static/class function |
7333 | 750 | if (candidate->isInstanceMember() != original->isInstanceMember()) |
7334 | 24 | return false; |
7335 | | |
7336 | | // If the original is ObjC visible then the rename must be as well |
7337 | 726 | if (originalIsObjCVisible && |
7338 | 726 | !objc_translation::isVisibleToObjC(candidate, minAccess)) |
7339 | 36 | return false; |
7340 | | |
7341 | | // @available is intended for public interfaces, so an implementation-only |
7342 | | // decl shouldn't match |
7343 | 690 | if (candidate->getAttrs().hasAttribute<ImplementationOnlyAttr>()) |
7344 | 0 | return false; |
7345 | | |
7346 | 690 | return true; |
7347 | 690 | } |
7348 | | |
7349 | | static bool parametersMatch(const AbstractFunctionDecl *a, |
7350 | 72 | const AbstractFunctionDecl *b) { |
7351 | 72 | auto aParams = a->getParameters(); |
7352 | 72 | auto bParams = b->getParameters(); |
7353 | | |
7354 | 72 | if (aParams->size() != bParams->size()) |
7355 | 6 | return false; |
7356 | | |
7357 | 105 | for (auto index : indices(*aParams)) { |
7358 | 105 | auto aParamType = aParams->get(index)->getTypeInContext(); |
7359 | 105 | auto bParamType = bParams->get(index)->getTypeInContext(); |
7360 | 105 | if (!aParamType->matchesParameter(bParamType, TypeMatchOptions())) |
7361 | 30 | return false; |
7362 | 105 | } |
7363 | 36 | return true; |
7364 | 66 | } |
7365 | | |
7366 | | ValueDecl *RenamedDeclRequest::evaluate(Evaluator &evaluator, |
7367 | | const ValueDecl *attached, |
7368 | 65.8k | const AvailableAttr *attr) const { |
7369 | 65.8k | if (!attached || !attr) |
7370 | 64.7k | return nullptr; |
7371 | | |
7372 | 1.08k | if (attr->RenameDecl) |
7373 | 204 | return attr->RenameDecl; |
7374 | | |
7375 | 882 | if (attr->Rename.empty()) |
7376 | 0 | return nullptr; |
7377 | | |
7378 | 882 | auto attachedContext = attached->getDeclContext(); |
7379 | 882 | auto parsedName = parseDeclName(attr->Rename); |
7380 | 882 | auto nameRef = parsedName.formDeclNameRef(attached->getASTContext()); |
7381 | | |
7382 | | // Handle types separately |
7383 | 882 | if (isa<NominalTypeDecl>(attached)) { |
7384 | 12 | if (!parsedName.ContextName.empty()) |
7385 | 0 | return nullptr; |
7386 | | |
7387 | 12 | SmallVector<ValueDecl *, 1> lookupResults; |
7388 | 12 | attachedContext->lookupQualified(attachedContext->getParentModule(), |
7389 | 12 | nameRef.withoutArgumentLabels(), |
7390 | 12 | attr->getLocation(), NL_OnlyTypes, |
7391 | 12 | lookupResults); |
7392 | 12 | if (lookupResults.size() == 1) |
7393 | 12 | return lookupResults[0]; |
7394 | 0 | return nullptr; |
7395 | 12 | } |
7396 | | |
7397 | 870 | auto minAccess = AccessLevel::Private; |
7398 | 870 | if (attached->getModuleContext()->isExternallyConsumed()) |
7399 | 399 | minAccess = AccessLevel::Public; |
7400 | 870 | bool attachedIsObjcVisible = |
7401 | 870 | objc_translation::isVisibleToObjC(attached, minAccess); |
7402 | | |
7403 | 870 | SmallVector<ValueDecl *, 4> lookupResults; |
7404 | 870 | SmallVector<AbstractFunctionDecl *, 4> asyncResults; |
7405 | 870 | lookupReplacedDecl(nameRef, attr, attached, lookupResults); |
7406 | | |
7407 | 870 | ValueDecl *renamedDecl = nullptr; |
7408 | 870 | auto attachedFunc = dyn_cast<AbstractFunctionDecl>(attached); |
7409 | 870 | for (auto candidate : lookupResults) { |
7410 | | // If the name is a getter or setter, grab the underlying accessor (if any) |
7411 | 789 | if (parsedName.IsGetter || parsedName.IsSetter) { |
7412 | 42 | auto *VD = dyn_cast<VarDecl>(candidate); |
7413 | 42 | if (!VD) |
7414 | 0 | continue; |
7415 | | |
7416 | 42 | candidate = VD->getAccessor(parsedName.IsGetter ? AccessorKind::Get : |
7417 | 42 | AccessorKind::Set); |
7418 | 42 | if (!candidate) |
7419 | 0 | continue; |
7420 | 42 | } |
7421 | | |
7422 | 789 | if (!renameCouldMatch(attached, candidate, attachedIsObjcVisible, |
7423 | 789 | minAccess)) |
7424 | 99 | continue; |
7425 | | |
7426 | 690 | if (auto *candidateFunc = dyn_cast<AbstractFunctionDecl>(candidate)) { |
7427 | | // Require both functions to be async/not. Async alternatives are handled |
7428 | | // below if there's no other matches |
7429 | 666 | if (attachedFunc->hasAsync() != candidateFunc->hasAsync()) { |
7430 | 273 | if (candidateFunc->hasAsync()) |
7431 | 273 | asyncResults.push_back(candidateFunc); |
7432 | 273 | continue; |
7433 | 273 | } |
7434 | | |
7435 | | // Require matching parameters for functions, unless there's only a single |
7436 | | // match |
7437 | 393 | if (lookupResults.size() > 1 && |
7438 | 393 | !parametersMatch(attachedFunc, candidateFunc)) |
7439 | 36 | continue; |
7440 | 393 | } |
7441 | | |
7442 | | // Do not match if there are any duplicates |
7443 | 381 | if (renamedDecl) { |
7444 | 0 | renamedDecl = nullptr; |
7445 | 0 | break; |
7446 | 0 | } |
7447 | 381 | renamedDecl = candidate; |
7448 | 381 | } |
7449 | | |
7450 | | // Try to match up an async alternative instead (ie. one where the |
7451 | | // completion handler has been removed). |
7452 | 870 | if (!renamedDecl && !asyncResults.empty()) { |
7453 | 273 | for (AbstractFunctionDecl *candidate : asyncResults) { |
7454 | 273 | llvm::Optional<unsigned> completionHandler = |
7455 | 273 | attachedFunc->findPotentialCompletionHandlerParam(candidate); |
7456 | 273 | if (!completionHandler) |
7457 | 69 | continue; |
7458 | | |
7459 | | // TODO: Check the result of the async function matches the parameters |
7460 | | // of the completion handler? |
7461 | | |
7462 | | // Do not match if there are any duplicates |
7463 | 204 | if (renamedDecl) { |
7464 | 6 | renamedDecl = nullptr; |
7465 | 6 | break; |
7466 | 6 | } |
7467 | 198 | renamedDecl = candidate; |
7468 | 198 | } |
7469 | 261 | } |
7470 | | |
7471 | 870 | return renamedDecl; |
7472 | 882 | } |
7473 | | |
7474 | | template <typename ATTR> |
7475 | | static void forEachCustomAttribute( |
7476 | | Decl *decl, |
7477 | | llvm::function_ref<void(CustomAttr *attr, NominalTypeDecl *)> fn) { |
7478 | | auto &ctx = decl->getASTContext(); |
7479 | | |
7480 | | for (auto *attr : decl->getAttrs().getAttributes<CustomAttr>()) { |
7481 | | auto *mutableAttr = const_cast<CustomAttr *>(attr); |
7482 | | |
7483 | | auto *nominal = evaluateOrDefault( |
7484 | | ctx.evaluator, |
7485 | | CustomAttrNominalRequest{mutableAttr, decl->getDeclContext()}, nullptr); |
7486 | | if (!nominal) |
7487 | | continue; |
7488 | | |
7489 | | if (nominal->getAttrs().hasAttribute<ATTR>()) |
7490 | | fn(mutableAttr, nominal); |
7491 | | } |
7492 | | } |
7493 | | |
7494 | | ArrayRef<VarDecl *> InitAccessorReferencedVariablesRequest::evaluate( |
7495 | | Evaluator &evaluator, DeclAttribute *attr, AccessorDecl *attachedTo, |
7496 | 1.26k | ArrayRef<Identifier> referencedVars) const { |
7497 | 1.26k | auto &ctx = attachedTo->getASTContext(); |
7498 | | |
7499 | 1.26k | auto *storage = attachedTo->getStorage(); |
7500 | | |
7501 | 1.26k | auto typeDC = storage->getDeclContext()->getSelfNominalTypeDecl(); |
7502 | 1.26k | if (!typeDC) |
7503 | 6 | return ctx.AllocateCopy(ArrayRef<VarDecl *>()); |
7504 | | |
7505 | 1.25k | SmallVector<VarDecl *> results; |
7506 | | |
7507 | 1.25k | bool failed = false; |
7508 | 1.25k | for (auto name : referencedVars) { |
7509 | 882 | auto propertyResults = typeDC->lookupDirect(DeclName(name)); |
7510 | 882 | switch (propertyResults.size()) { |
7511 | 30 | case 0: { |
7512 | 30 | ctx.Diags.diagnose(attr->getLocation(), diag::cannot_find_type_in_scope, |
7513 | 30 | DeclNameRef(name)); |
7514 | 30 | failed = true; |
7515 | 30 | break; |
7516 | 0 | } |
7517 | | |
7518 | 849 | case 1: { |
7519 | 849 | auto *member = propertyResults.front(); |
7520 | | |
7521 | | // Only stored properties are supported. |
7522 | 849 | if (auto *var = dyn_cast<VarDecl>(member)) { |
7523 | 849 | if (var->getImplInfo().hasStorage()) { |
7524 | 831 | results.push_back(var); |
7525 | 831 | break; |
7526 | 831 | } |
7527 | 849 | } |
7528 | | |
7529 | 18 | ctx.Diags.diagnose(attr->getLocation(), |
7530 | 18 | diag::init_accessor_can_refer_only_to_properties, |
7531 | 18 | member->getDescriptiveKind(), member->createNameRef()); |
7532 | 18 | failed = true; |
7533 | 18 | break; |
7534 | 849 | } |
7535 | | |
7536 | 3 | default: |
7537 | 3 | ctx.Diags.diagnose(attr->getLocation(), |
7538 | 3 | diag::ambiguous_member_overload_set, |
7539 | 3 | DeclNameRef(name)); |
7540 | | |
7541 | 6 | for (auto *choice : propertyResults) { |
7542 | 6 | ctx.Diags.diagnose(choice, diag::decl_declared_here, choice); |
7543 | 6 | } |
7544 | | |
7545 | 3 | failed = true; |
7546 | 3 | break; |
7547 | 882 | } |
7548 | 882 | } |
7549 | | |
7550 | 1.25k | if (failed) |
7551 | 39 | return ctx.AllocateCopy(ArrayRef<VarDecl *>()); |
7552 | | |
7553 | 1.21k | return ctx.AllocateCopy(results); |
7554 | 1.25k | } |