Skip to content

Commit 12883d0

Browse files
committed
Merge branch 'master' into semantics-def
2 parents a800c9e + f5f214d commit 12883d0

File tree

455 files changed

+11686
-6635
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

455 files changed

+11686
-6635
lines changed

CHANGELOG.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,39 @@ CHANGELOG
2626
Swift 5.2
2727
---------
2828

29+
* [SR-2790][]:
30+
31+
The compiler will now emit a warning when attempting to pass a temporary
32+
pointer argument produced from an array, string, or inout argument to a
33+
parameter which is known to escape it. This includes the various initializers
34+
for the `UnsafePointer`/`UnsafeBufferPointer` family of types, as well as
35+
memberwise initializers.
36+
37+
```swift
38+
struct S {
39+
var ptr: UnsafePointer<Int8>
40+
}
41+
42+
func foo() {
43+
var i: Int8 = 0
44+
let ptr = UnsafePointer(&i)
45+
// warning: initialization of 'UnsafePointer<Int8>' results in a
46+
// dangling pointer
47+
48+
let s1 = S(ptr: [1, 2, 3])
49+
// warning: passing '[Int8]' to parameter, but argument 'ptr' should be a
50+
// pointer that outlives the call to 'init(ptr:)'
51+
52+
let s2 = S(ptr: "hello")
53+
// warning: passing 'String' to parameter, but argument 'ptr' should be a
54+
// pointer that outlives the call to 'init(ptr:)'
55+
}
56+
```
57+
58+
All 3 of the above examples are unsound because each argument produces a
59+
temporary pointer only valid for the duration of the call they are passed to.
60+
Therefore the returned value in each case references a dangling pointer.
61+
2962
* [SR-2189][]:
3063

3164
The compiler now supports local functions whose default arguments capture
@@ -7824,6 +7857,7 @@ Swift 1.0
78247857
[SR-2608]: <https://bugs.swift.org/browse/SR-2608>
78257858
[SR-2672]: <https://bugs.swift.org/browse/SR-2672>
78267859
[SR-2688]: <https://bugs.swift.org/browse/SR-2688>
7860+
[SR-2790]: <https://bugs.swift.org/browse/SR-2790>
78277861
[SR-4206]: <https://bugs.swift.org/browse/SR-4206>
78287862
[SR-4248]: <https://bugs.swift.org/browse/SR-4248>
78297863
[SR-5581]: <https://bugs.swift.org/browse/SR-5581>

CMakeLists.txt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -455,7 +455,7 @@ if(MSVC OR "${CMAKE_SIMULATE_ID}" STREQUAL MSVC)
455455
include(ClangClCompileRules)
456456
endif()
457457

458-
if(CMAKE_C_COMPILER_ID STREQUAL Clang)
458+
if(CMAKE_C_COMPILER_ID MATCHES Clang)
459459
add_compile_options($<$<OR:$<COMPILE_LANGUAGE:C>,$<COMPILE_LANGUAGE:CXX>>:-Werror=gnu>)
460460
endif()
461461

@@ -1129,6 +1129,8 @@ endif()
11291129

11301130
add_subdirectory(utils)
11311131

1132+
add_subdirectory(userdocs)
1133+
11321134
if ("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin")
11331135
if(SWIFT_BUILD_PERF_TESTSUITE)
11341136
add_subdirectory(benchmark)

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ Please make sure you use Python 2.x. Python 3.x is not supported currently.
8686

8787
#### macOS
8888

89-
To build for macOS, you need [Xcode 11 beta 6](https://developer.apple.com/xcode/downloads/).
89+
To build for macOS, you need [Xcode 11.2](https://developer.apple.com/xcode/downloads/).
9090
The required version of Xcode changes frequently, and is often a beta release.
9191
Check this document or the host information on <https://ci.swift.org> for the
9292
current required version.

cmake/modules/AddSwift.cmake

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1991,7 +1991,7 @@ function(add_swift_target_library name)
19911991
DEPLOYMENT_VERSION_WATCHOS "${SWIFTLIB_DEPLOYMENT_VERSION_WATCHOS}"
19921992
GYB_SOURCES ${SWIFTLIB_GYB_SOURCES}
19931993
)
1994-
if(NOT SWIFT_BUILT_STANDALONE AND NOT CMAKE_C_COMPILER MATCHES Clang)
1994+
if(NOT SWIFT_BUILT_STANDALONE AND NOT "${CMAKE_C_COMPILER_ID}" MATCHES "Clang")
19951995
add_dependencies(${VARIANT_NAME} clang)
19961996
endif()
19971997

docs/Diagnostics.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,25 @@ The Swift compiler has a setting (under LangOptions) called `DiagnosticsEditorMo
9090

9191
Most diagnostics have no reason to change behavior under editor mode. An example of an exception is the "protocol requirements not satisfied diagnostic"; on the command line, it may be better to show all unsatisfied requirements, while in an IDE a single multi-line fix-it would be preferred.
9292

93+
### Educational Notes ###
94+
95+
**Note**: This feature is currently experimental. It can be enabled by passing the `-Xfrontend -enable-descriptive-diagnostics` flag.
96+
97+
Educational notes are small snippets of documentation attached to a diagnostic which explain relevant language concepts. They are intended to further Swift's goal of progressive disclosure by providing a learning resource at the point of use for users encountering a new error message for the first time. In very limited circumstances, they also allow the main diagnostic message to use more precise and correct terminology (e.g. nominal types) which would otherwise be too unfriendly for beginners.
98+
99+
When outputting diagnostics on the command line, educational notes will be printed after the main diagnostic body if descriptive diagnostics are enabled. When presented in an IDE, it's expected they will be collapsed under a disclosure arrow, info button, or similar to avoid cluttering output.
100+
101+
Generally speaking, a diagnostic should try to provide educational notes for any concepts/terminology which is difficult to understand from context or is especially subtle. Educational notes should:
102+
- Explain a single language concept. This makes them easy to reuse across diagnostics and helps keep them clear, concise, and easy to understand.
103+
- Be written in unabbreviated English. These are longer form messages compared to the main diagnostic, so there is no need to omit needless words and punctuation.
104+
- Not generally exceed 3-4 paragraphs. Educational notes should be clear and easily digestible. Messages which are too long also have the potential to create diagnostics UX issues in some contexts.
105+
- Be accessible. Educational notes should be beginner friendly and avoid assuming unnecesary prior knowledge. The goal is not only to help users understand what a diagnostic is telling them, but also to turn errors and warnings into "teachable moments".
106+
- Include references to relevant chapters of _The Swift Programming Language_ if applicable.
107+
- Be written in Markdown, but avoid excessive markup to avoid impacting the terminal UX.
108+
109+
To add a new educational note:
110+
1. Add a new Markdown file in the `userdocs/diagnostics/` directory containing the contents of the note.
111+
2. Associate the note with one or more diagnostics in EducationalNotes.def.
93112

94113
### Format Specifiers ###
95114

docs/WindowsBuild.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,10 @@ git clone https://github.com/compnerd/windows-swift windows-swift
5959
`${UniversalCRTSdkDir}/Include/${UCRTVersion}/ucrt` as `module.modulemap`, copying `visualc.modulemap` located at `swift/stdlib/public/Platform/visualc.modulemap` into `${VCToolsInstallDir}/include` as `module.modulemap`, and copying `winsdk.modulemap` located at `swift/stdlib/public/Platform/winsdk.modulemap` into `${UniversalCRTSdkDir}/Include/${UCRTVersion}/um` and setup the `visualc.apinotes` located at `swift/stdlib/public/Platform/visualc.apinotes` into `${VCToolsInstallDir}/include` as `visualc.apinotes`
6060

6161
```cmd
62-
mklink "%UniversalCRTSdkDir%\Include\%UCRTVersion%\ucrt\module.modulemap" S:\swift\stdlib\public\Platform\ucrt.modulemap
63-
mklink "%UniversalCRTSdkDir%\Include\%UCRTVersion%\um\module.modulemap" S:\swift\stdlib\public\Platform\winsdk.modulemap
64-
mklink "%VCToolsInstallDir%\include\module.modulemap" S:\swift\stdlib\public\Platform\visualc.modulemap
65-
mklink "%VCToolsInstallDir%\include\visualc.apinotes" S:\swift\stdlib\public\Platform\visualc.apinotes
62+
mklink "%UniversalCRTSdkDir%\Include\%UCRTVersion%\ucrt\module.modulemap" S:\toolchain\swift\stdlib\public\Platform\ucrt.modulemap
63+
mklink "%UniversalCRTSdkDir%\Include\%UCRTVersion%\um\module.modulemap" S:\toolchain\swift\stdlib\public\Platform\winsdk.modulemap
64+
mklink "%VCToolsInstallDir%\include\module.modulemap" S:\toolchain\swift\stdlib\public\Platform\visualc.modulemap
65+
mklink "%VCToolsInstallDir%\include\visualc.apinotes" S:\toolchain\swift\stdlib\public\Platform\visualc.apinotes
6666
```
6767

6868
Warning: Creating the above links usually requires administrator privileges. The quick and easy way to do this is to open a second developer prompt by right clicking whatever shortcut you used to open the first one, choosing Run As Administrator, and pasting the above commands into the resulting window. You can then close the privileged prompt; this is the only step which requires elevation.

docs/conf.py

Lines changed: 5 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
import sys
1515
from datetime import date
16+
from sphinx.highlighting import lexers
1617

1718
# If extensions (or modules to document with autodoc) are in another directory,
1819
# add these directories to sys.path here. If the directory is relative to the
@@ -263,9 +264,7 @@
263264
# Enable this if you want TODOs to show up in the generated documentation.
264265
todo_include_todos = True
265266

266-
#
267-
# Monkeypatch pygments so it will know about the Swift lexers
268-
#
267+
# -- Patch pygments so it will know about the Swift lexers ---------------
269268

270269
# Pull in the Swift lexers
271270
from os.path import abspath, dirname, join as join_paths # noqa (E402)
@@ -277,22 +276,6 @@
277276

278277
sys.path.pop(0)
279278

280-
# Monkeypatch pygments.lexers.get_lexer_by_name to return our lexers. The
281-
# ordering required to allow for monkeypatching causes the warning
282-
# "I100 Import statements are in the wrong order." when linting using
283-
# flake8-import-order. "noqa" is used to suppress this warning.
284-
from pygments.lexers import get_lexer_by_name as original_get_lexer_by_name # noqa (E402)
285-
286-
287-
def swift_get_lexer_by_name(_alias, *args, **kw):
288-
if _alias == 'swift':
289-
return swift_pygments_lexers.SwiftLexer()
290-
elif _alias == 'sil':
291-
return swift_pygments_lexers.SILLexer()
292-
elif _alias == 'swift-console':
293-
return swift_pygments_lexers.SwiftConsoleLexer()
294-
else:
295-
return original_get_lexer_by_name(_alias, *args, **kw)
296-
297-
import pygments.lexers # noqa (I100 Import statements are in the wrong order.)
298-
pygments.lexers.get_lexer_by_name = swift_get_lexer_by_name
279+
lexers['swift'] = swift_pygments_lexers.SwiftLexer()
280+
lexers['sil'] = swift_pygments_lexers.SILLexer()
281+
lexers['swift-console'] = swift_pygments_lexers.SwiftConsoleLexer()

include/swift/AST/ASTContext.h

Lines changed: 21 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,6 @@ namespace swift {
7070
class LazyContextData;
7171
class LazyIterableDeclContextData;
7272
class LazyMemberLoader;
73-
class LazyResolver;
7473
class PatternBindingDecl;
7574
class PatternBindingInitializer;
7675
class SourceFile;
@@ -102,6 +101,7 @@ namespace swift {
102101
class SourceManager;
103102
class ValueDecl;
104103
class DiagnosticEngine;
104+
class TypeChecker;
105105
class TypeCheckerDebugConsumer;
106106
struct RawComment;
107107
class DocComment;
@@ -271,6 +271,9 @@ class ASTContext final {
271271
/// Cache of remapped types (useful for diagnostics).
272272
llvm::StringMap<Type> RemappedTypes;
273273

274+
/// The # of times we have performed typo correction.
275+
unsigned NumTypoCorrections = 0;
276+
274277
private:
275278
/// The current generation number, which reflects the number of
276279
/// times that external modules have been loaded.
@@ -404,28 +407,14 @@ class ASTContext final {
404407
/// Set a new stats reporter.
405408
void setStatsReporter(UnifiedStatsReporter *stats);
406409

407-
/// Creates a new lazy resolver by passing the ASTContext and the other
408-
/// given arguments to a newly-allocated instance of \c ResolverType.
409-
///
410-
/// \returns true if a new lazy resolver was created, false if there was
411-
/// already a lazy resolver registered.
412-
template<typename ResolverType, typename ... Args>
413-
bool createLazyResolverIfMissing(Args && ...args) {
414-
if (getLazyResolver())
415-
return false;
416-
417-
setLazyResolver(new ResolverType(*this, std::forward<Args>(args)...));
418-
return true;
419-
}
420-
421-
/// Retrieve the lazy resolver for this context.
422-
LazyResolver *getLazyResolver() const;
423-
424410
private:
425-
/// Set the lazy resolver for this context.
426-
void setLazyResolver(LazyResolver *resolver);
411+
friend class TypeChecker;
427412

413+
void installGlobalTypeChecker(TypeChecker *TC);
428414
public:
415+
/// Retrieve the global \c TypeChecker instance associated with this context.
416+
TypeChecker *getLegacyGlobalTypeChecker() const;
417+
429418
/// getIdentifier - Return the uniqued and AST-Context-owned version of the
430419
/// specified string.
431420
Identifier getIdentifier(StringRef Str) const;
@@ -458,17 +447,13 @@ class ASTContext final {
458447
/// Retrieve the type Swift.Never.
459448
CanType getNeverType() const;
460449

461-
/// Retrieve the declaration of ObjectiveC.ObjCBool.
462-
StructDecl *getObjCBoolDecl() const;
463-
464-
/// Retrieve the declaration of Foundation.NSCopying.
465-
ProtocolDecl *getNSCopyingDecl() const;
466-
/// Retrieve the declaration of Foundation.NSError.
467-
ClassDecl *getNSErrorDecl() const;
468-
/// Retrieve the declaration of Foundation.NSNumber.
469-
ClassDecl *getNSNumberDecl() const;
470-
/// Retrieve the declaration of Foundation.NSValue.
471-
ClassDecl *getNSValueDecl() const;
450+
#define KNOWN_OBJC_TYPE_DECL(MODULE, NAME, DECL_CLASS) \
451+
/** Retrieve the declaration of MODULE.NAME. */ \
452+
DECL_CLASS *get##NAME##Decl() const; \
453+
\
454+
/** Retrieve the type of MODULE.NAME. */ \
455+
Type get##NAME##Type() const;
456+
#include "swift/AST/KnownObjCTypes.def"
472457

473458
// Declare accessors for the known declarations.
474459
#define FUNC_DECL(Name, Id) \
@@ -854,6 +839,11 @@ class ASTContext final {
854839
/// This guarantees that resulted \p names doesn't have duplicated names.
855840
void getVisibleTopLevelModuleNames(SmallVectorImpl<Identifier> &names) const;
856841

842+
/// Whether to perform typo correction given the pre-configured correction limit.
843+
/// Increments \c NumTypoCorrections then checks this against the limit in
844+
/// the language options.
845+
bool shouldPerformTypoCorrection();
846+
857847
private:
858848
/// Register the given generic signature builder to be used as the canonical
859849
/// generic signature builder for the given signature, if we don't already

include/swift/AST/ASTScope.h

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,10 @@ class ASTScopeImpl {
226226
#pragma mark - source range queries
227227

228228
public:
229+
/// Return signum of ranges. Centralize the invariant that ASTScopes use ends.
230+
static int compare(SourceRange, SourceRange, const SourceManager &,
231+
bool ensureDisjoint);
232+
229233
SourceRange getSourceRangeOfScope(bool omitAssertions = false) const;
230234

231235
/// InterpolatedStringLiteralExprs and EditorPlaceHolders respond to
@@ -427,12 +431,12 @@ class ASTScopeImpl {
427431

428432
protected:
429433
/// Not const because may reexpand some scopes.
430-
const ASTScopeImpl *findInnermostEnclosingScope(SourceLoc,
431-
NullablePtr<raw_ostream>);
432-
const ASTScopeImpl *findInnermostEnclosingScopeImpl(SourceLoc,
433-
NullablePtr<raw_ostream>,
434-
SourceManager &,
435-
ScopeCreator &);
434+
ASTScopeImpl *findInnermostEnclosingScope(SourceLoc,
435+
NullablePtr<raw_ostream>);
436+
ASTScopeImpl *findInnermostEnclosingScopeImpl(SourceLoc,
437+
NullablePtr<raw_ostream>,
438+
SourceManager &,
439+
ScopeCreator &);
436440

437441
private:
438442
NullablePtr<ASTScopeImpl> findChildContaining(SourceLoc loc,
@@ -563,6 +567,8 @@ class ASTSourceFileScope final : public ASTScopeImpl {
563567
void
564568
buildEnoughOfTreeForTopLevelExpressionsButDontRequestGenericsOrExtendedNominals();
565569

570+
void expandFunctionBody(AbstractFunctionDecl *AFD);
571+
566572
const SourceFile *getSourceFile() const override;
567573
NullablePtr<const void> addressForPrinting() const override { return SF; }
568574
bool crossCheckWithAST();

include/swift/AST/ASTTypeIDZone.def

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,16 @@
1818
SWIFT_TYPEID(AncestryFlags)
1919
SWIFT_TYPEID(CtorInitializerKind)
2020
SWIFT_TYPEID(GenericSignature)
21+
SWIFT_TYPEID(ImplicitMemberAction)
2122
SWIFT_TYPEID(ParamSpecifier)
2223
SWIFT_TYPEID(PropertyWrapperBackingPropertyInfo)
2324
SWIFT_TYPEID(PropertyWrapperTypeInfo)
2425
SWIFT_TYPEID(Requirement)
2526
SWIFT_TYPEID(ResilienceExpansion)
2627
SWIFT_TYPEID(Type)
2728
SWIFT_TYPEID(TypePair)
29+
SWIFT_TYPEID(TypeWitnessAndDecl)
30+
SWIFT_TYPEID(Witness)
2831
SWIFT_TYPEID_NAMED(ConstructorDecl *, ConstructorDecl)
2932
SWIFT_TYPEID_NAMED(CustomAttr *, CustomAttr)
3033
SWIFT_TYPEID_NAMED(Decl *, Decl)

include/swift/AST/ASTTypeIDs.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,13 @@ enum class ResilienceExpansion : unsigned;
5151
class Type;
5252
class ValueDecl;
5353
class VarDecl;
54+
class Witness;
5455
class TypeAliasDecl;
5556
class Type;
5657
struct TypePair;
58+
struct TypeWitnessAndDecl;
5759
enum class AncestryFlags : uint8_t;
60+
enum class ImplicitMemberAction : uint8_t;
5861

5962
// Define the AST type zone (zone 1)
6063
#define SWIFT_TYPEID_ZONE AST

include/swift/AST/Attr.def

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ TYPE_ATTR(autoclosure)
5151
TYPE_ATTR(convention)
5252
TYPE_ATTR(noescape)
5353
TYPE_ATTR(escaping)
54+
TYPE_ATTR(differentiable)
5455

5556
// SIL-specific attributes
5657
TYPE_ATTR(block_storage)
@@ -202,7 +203,7 @@ DECL_ATTR(inline, Inline,
202203
ABIStableToAdd | ABIStableToRemove | APIStableToAdd | APIStableToRemove,
203204
20)
204205
DECL_ATTR(_semantics, Semantics,
205-
OnAbstractFunction | OnSubscript | OnNominalType |
206+
OnAbstractFunction | OnSubscript | OnNominalType | OnVar |
206207
AllowMultipleAttributes | UserInaccessible |
207208
ABIStableToAdd | ABIStableToRemove | APIStableToAdd | APIStableToRemove,
208209
21)
@@ -496,6 +497,10 @@ DECL_ATTR(_projectedValueProperty, ProjectedValueProperty,
496497
OnVar | UserInaccessible |
497498
ABIStableToAdd | ABIStableToRemove | APIStableToAdd | APIStableToRemove,
498499
89)
500+
SIMPLE_DECL_ATTR(_nonEphemeral, NonEphemeral,
501+
OnParam | UserInaccessible |
502+
ABIStableToAdd | ABIStableToRemove | APIBreakingToAdd | APIStableToRemove,
503+
90)
499504

500505
SIMPLE_DECL_ATTR(IBSegueAction, IBSegueAction,
501506
OnFunc |

include/swift/AST/Attr.h

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,10 @@ class TypeAttributes {
6666
Optional<StringRef> convention = None;
6767
Optional<StringRef> conventionWitnessMethodProtocol = None;
6868

69+
// Indicates whether the type's '@differentiable' attribute has a 'linear'
70+
// argument.
71+
bool linear = false;
72+
6973
// For an opened existential type, the known ID.
7074
Optional<UUID> OpenedID;
7175

@@ -80,7 +84,15 @@ class TypeAttributes {
8084
TypeAttributes() {}
8185

8286
bool isValid() const { return AtLoc.isValid(); }
83-
87+
88+
bool isLinear() const {
89+
assert(
90+
!linear ||
91+
(linear && has(TAK_differentiable)) &&
92+
"Linear shouldn't have been true if there's no `@differentiable`");
93+
return linear;
94+
}
95+
8496
void clearAttribute(TypeAttrKind A) {
8597
AttrLocs[A] = SourceLoc();
8698
}

0 commit comments

Comments
 (0)