Commit Graph

135 Commits

Author SHA1 Message Date
Hamish Knight
fe68fab1e2 [AST] Simplify construction of EnumElementPattern
Add `EnumElementPattern::create` and
`EnumElementPattern::createImplicit`, and replace
existing constructions with them.
2024-07-06 22:56:30 +01:00
Tim Kientzle
1d961ba22d Add #include "swift/Basic/Assertions.h" to a lot of source files
Although I don't plan to bring over new assertions wholesale
into the current qualification branch, it's entirely possible
that various minor changes in main will use the new assertions;
having this basic support in the release branch will simplify that.
(This is why I'm adding the includes as a separate pass from
rewriting the individual assertions)
2024-06-05 19:37:30 -07:00
Joe Groff
ba3494802a Alternative noncopyable switch design based on expression kind.
If an expression refers to noncopyable storage, then default to performing
a borrowing switch, where `let` bindings in patterns borrow out of the
matched value. If an expression refers to a temporary value or explicitly
uses the `consume` keyword, then perform a consuming switch, where
`let` bindings take ownership of corresponding parts of the matched value.
Allow `_borrowing` to still be used to explicitly bind a pattern variable
as a borrow, with no-implicit-copy semantics for copyable values.
2024-03-28 08:32:48 -07:00
Ben Barham
ef8825bfe6 Migrate llvm::Optional to std::optional
LLVM has removed llvm::Optional, move over to std::optional. Also
clang-format to fix up all the renamed #includes.
2024-02-21 11:20:06 -08:00
Joe Groff
c28b352b4c Merge pull request #71431 from jckarter/borrowing-switch-6
SILGen: Improve handling of copyable subpatterns in borrowing switches.
2024-02-07 15:12:22 -08:00
Joe Groff
e46168c626 SILGen: Improve handling of copyable subpatterns in borrowing switches.
A `let` binding of a copyable subpattern can create an independent variable
which should be copyable and consumable without affecting a borrowed
move-only base. In the same way that `borrowing` parameters are
no-implicit-copy, though, explicitly `_borrowing` subpatterns of
copyable type should be no-implicit-copy as well.
2024-02-07 07:21:11 -08:00
Hamish Knight
16cfca4186 [ASTWalker] NFC: Rename SkipChildren -> SkipNode
This better describes what the action currently
does, and allows us to re-introduce `SkipChildren`
with the correct behavior.
2024-02-05 15:27:25 +00:00
Joe Groff
6706feaf5e Parse _borrowing x in patterns as a borrow binding.
Treat it as a contextual keyword when followed by an identifier, like our
other ownership-related declarations and operators.
2024-01-30 17:33:42 -08:00
Joe Groff
4011b2f53c Add methods to determine the ownership behavior of patterns.
When matching against a noncopyable value, whether the match operation can
borrow the value in-place or needs to take ownership of it is significant.
This can generally be determined from the kind of pattern being used, except
in the case of expr patterns, where it depends on type-checking the `~=`
operator that was used.
2024-01-08 18:21:33 -08:00
Rintaro Ishizaki
409b2760f9 [ASTGen] Statements 2023-12-18 16:09:25 -08:00
Evan Wilde
f3ff561c6f [NFC] add llvm namespace to Optional and None
This is phase-1 of switching from llvm::Optional to std::optional in the
next rebranch. llvm::Optional was removed from upstream LLVM, so we need
to migrate off rather soon. On Darwin, std::optional, and llvm::Optional
have the same layout, so we don't need to be as concerned about ABI
beyond the name mangling. `llvm::Optional` is only returned from one
function in
```
getStandardTypeSubst(StringRef TypeName,
                     bool allowConcurrencyManglings);
```
It's the return value, so it should not impact the mangling of the
function, and the layout is the same as `std::optional`, so it should be
mostly okay. This function doesn't appear to have users, and the ABI was
already broken 2 years ago for concurrency and no one seemed to notice
so this should be "okay".

I'm doing the migration incrementally so that folks working on main can
cherry-pick back to the release/5.9 branch. Once 5.9 is done and locked
away, then we can go through and finish the replacement. Since `None`
and `Optional` show up in contexts where they are not `llvm::None` and
`llvm::Optional`, I'm preparing the work now by going through and
removing the namespace unwrapping and making the `llvm` namespace
explicit. This should make it fairly mechanical to go through and
replace llvm::Optional with std::optional, and llvm::None with
std::nullopt. It's also a change that can be brought onto the
release/5.9 with minimal impact. This should be an NFC change.
2023-06-27 09:03:52 -07:00
Rajveer
c34f099c7d Improved out-of-place binding diagnostic and reflecting 'var' or 'let' binding pattern
Fixes Issue #63993
2023-03-19 19:26:58 +05:30
Hamish Knight
37b0a6074f [Sema] Introduce ExprPatternMatchRequest
This replaces `synthesizeTildeEqualsOperatorApplication`,
and synthesizes the match expression and var
on-demand.

Additionally, it pushes the lookup logic into
pre-checking.
2023-03-07 15:16:35 +00:00
Hamish Knight
9b8bc6033c [AST] NFC: Refactor ExprPattern construction
Introduce 3 separate factory constructors, and
remove the ability to specify the match expr and
var, as those should be synthesized on-demand.
2023-03-01 15:53:41 +00:00
Doug Gregor
200f2340d9 [Macros] Be deliberate about walking macro arguments vs. expansions
Provide ASTWalker with a customization point to specify whether to
check macro arguments (which are type checked but never emitted), the
macro expansion (which is the result of applying the macro and is
actually emitted into the source), or both. Provide answers for the
~115 different ASTWalker visitors throughout the code base.

Fixes rdar://104042945, which concerns checking of effects in
macro arguments---which we shouldn't do.
2023-02-28 17:48:23 -08:00
Hamish Knight
81b1358a12 [AST] Improve OptionalSomePattern a bit
Rather than having Sema set the same Optional
some decl, let's just store a pointer to the
ASTContext and retrieve it on demand.
Additionally, add `create` and `createImplicit`
factory methods.
2023-02-21 16:00:27 +00:00
Hamish Knight
4716f61fba [AST] Introduce explicit actions for ASTWalker
Replace the use of bool and pointer returns for
`walkToXXXPre`/`walkToXXXPost`, and instead use
explicit actions such as `Action::Continue(E)`,
`Action::SkipChildren(E)`, and `Action::Stop()`.
There are also conditional variants, e.g
`Action::SkipChildrenIf`, `Action::VisitChildrenIf`,
and `Action::StopIf`.

There is still more work that can be done here, in
particular:

- SourceEntityWalker still needs to be migrated.
- Some uses of `return false` in pre-visitation
methods can likely now be replaced by
`Action::Stop`.
- We still use bool and pointer returns internally
within the ASTWalker traversal, which could likely
be improved.

But I'm leaving those as future work for now as
this patch is already large enough.
2022-09-13 10:35:29 +01:00
Slava Pestov
7a16b0275b AST: Allow one-element tuple types to be constructed
These will never appear in the source language, but can arise
after substitution when the original type is a tuple type with
a pack expansion type.

Two examples:
- original type: (Int, T...), substitution T := {}
- original type: (T...), substitution T := {Int}

We need to model these correctly to maintain invariants.

Callers that previously used to rely on TupleType::get()
returning a ParenType now explicitly check for the one-element
case instead.
2022-08-23 11:12:00 -04:00
Becca Royal-Gordon
59bb325e4b [NFC] Factor out ASTContext operator news
Many, many, many types in the Swift compiler are intended to only be allocated in the ASTContext. We have previously implemented this by writing several `operator new` and `operator delete` implementations into these types. Factor those out into a new base class instead.
2021-08-19 11:19:52 -07:00
Hamish Knight
1b2a4ac365 [AST] Add Pattern::hasAnyMutableBindings 2021-06-09 10:43:25 +01:00
David Zarzycki
1e940c2c7e [NFC] Fix -Wsuggest-override warnings
LLVM, as of 77e0e9e17daf0865620abcd41f692ab0642367c4, now builds with
-Wsuggest-override. Let's clean up the swift sources rather than disable
the warning locally.
2020-08-13 16:17:46 -04:00
Anthony Latsis
17f12da381 [NFC] AST: Remove TypedPattern:getTypeLoc() 2020-08-04 18:46:21 +03:00
Anthony Latsis
b26310ee97 TypeLoc: Offload TypeLoc off the ASTWalker 2020-08-04 18:13:28 +03:00
Michael Gottesman
092edd6621 [ast] Rename VarPattern -> BindingPattern.
VarPattern is today used to implement both 'let' and 'var' pattern bindings, so
today is already misleading. The reason why the name Var was chosen was done b/c
it is meant to represent a pattern that performs 'variable binding'. Given that
I am going to add a new 'inout' pattern binding to this, it makes sense to
give it now a better fitting name before I make things more confusing.
2020-07-16 18:56:01 -07:00
Robert Widmann
2371e5c260 Strip TypeLoc from EnumElementPattern 2020-06-10 14:22:46 -07:00
Robert Widmann
fc9070c072 Strip TypeLoc from IsPattern 2020-06-10 13:29:39 -07:00
Robert Widmann
0342855e50 [NFC] Debride Pattern.h of Implicit Tri-State
Remove all of this in favor of explicit constructors to preserve the one-liners, or distribute the setImplicit() calls to the callsites if necessary.
2020-04-30 22:03:55 -07:00
Doug Gregor
5ac8d769fd [Property wrappers] Allow default initialization to infer a type.
Property wrappers are allowed to infer the type of a variable, but this
only worked when the property wrapper was provided with an explicit
initialization, e.g.,

    @WrapsAnInt() var x   // infers type Int from WrapsAnInt.wrappedValue

However, when default initialization is supported by the property wrapper,
dropping the parentheses would produce an error about the missing type
annotation

    @WrapsAnInt var x

Make this second case behave like the first, so that default initialization
works consistently with the explicitly-specified version.
Fixes rdar://problem/59471019.
2020-03-26 13:44:08 -07:00
Doug Gregor
033f9c7927 [Type checker] Introduce "contextual patterns".
Contextual pattern describes a particular pattern with enough
contextual information to determine its type. Use this to simplify
TypeChecker::typeCheckPattern()'s interface in a manner that will
admit request'ification.
2020-01-03 15:41:21 -08:00
Jordan Rose
8ff1dac381 [AST] Break some header dependencies for faster rebuilds (#27374)
DiagnosticEngine.h no longer depends on Attr.h.
Expr.h no longer depends on TypeRepr.h.

No functionality change.
2019-09-26 09:17:10 -07:00
Adrian Prantl
ff63eaea6f Remove \brief commands from doxygen comments.
We've been running doxygen with the autobrief option for a couple of
years now. This makes the \brief markers into our comments
redundant. Since they are a visual distraction and we don't want to
encourage more \brief markers in new code either, this patch removes
them all.

Patch produced by

      for i in $(git grep -l '\\brief'); do perl -pi -e 's/\\brief //g' $i & done
2018-12-04 15:45:04 -08:00
Jordan Rose
08d4a93896 [AST] More static_asserts for non-destroyed bump-allocated AST types (#19670)
Attributes, ParameterLists, GenericParamLists, Patterns, Types, and
TypeReprs. Thanks, Rintaro!
2018-10-02 14:58:18 -07:00
Harlan
eb75ad80dc [AST] Remove stored TypeLoc from TypedPattern (#19175)
* [AST] Remove stored TypeLoc from TypedPattern

TypedPattern was only using this TypeLoc as a means to a TypeRepr, which
caused it to store the pattern type twice (through the superclass and through
the TypeLoc itself.)

This also fixes a bug where deserializing a TypedPattern doesn't store
the type correctly and generally cleans up TypedPattern initialization.

Resolves rdar://44144435

* Address review comments
2018-09-07 21:14:04 -07:00
Graydon Hoare
ffa1bf1979 [Stats] Expand and improve traceable-entity vocabulary. 2018-09-01 00:05:58 -07:00
Huon Wilson
b6d44f31da [AST] std::function -> llvm::function_ref for some non-escaping params. 2018-05-01 08:29:06 +10:00
David Zarzycki
54ea315586 [Basic] NFC: Stop using transparent unions 2017-12-16 10:43:49 -05:00
David Zarzycki
97541e0d1e [Basic] NFC: Standardize and simplify inline bitfields
Inline bitfields are a common design pattern in LLVM and derived
projects, but the associated boilerplate can be demotivating and
brittle. This new header makes it easier to define and use inline
bitfields in Swift.

This also reorders some fields for better code generation.
2017-12-15 14:14:59 -05:00
Robert Widmann
72ee26a52f Resolve a crasher 2017-06-01 23:58:14 -07:00
Harlan Haskins
de7a1b5412 Fix compiler crash by restricting the WalkToVarDecls walker.
WalkToVarDecls should only walk within the current pattern, not into
any other nodes (especially not nodes that open a scope.)

Restricting this fixes the name lookup weirdness that caused the crash.
2017-06-01 23:23:29 -07:00
Slava Pestov
162b2d252e AST: Include gardening to minimize dependencies on Expr.h
A lot of files transitively include Expr.h, because it was
included from SILInstruction.h, SILLocation.h and SILDeclRef.h.

However in reality most of these files don't do anything
with Exprs, especially not anything in IRGen or the SILOptimizer.

Now we're down to 171 files in the frontend which depend on
Expr.h, which is still a lot but much better than before.
2017-03-12 22:26:56 -07:00
Slava Pestov
bd4f31025f AST: GenericEnvironment::mapTypeIntoContext() no longer needs to take a ModuleDecl
Now, use LookUpConformanceInSignature instead.
2017-02-07 19:25:34 -08:00
Joe Groff
c03371afc1 Sema: NSValue-to-value-type casts are failable and should be checked.
In Swift 4 mode, no longer consider e.g. 'nsNumber as Int' or 'nsValue as NSRange' to be valid coercions. This would break compatibility with Swift 3, so in Swift 3 mode, accept the coercion, but *also* accept a checked cast without a warning, and raise a migration warning about the unchecked coercion.
2017-01-13 13:51:27 -08:00
practicalswift
6d1ae2a39c [gardening] 2016 → 2017 2017-01-06 16:41:22 +01:00
Doug Gregor
e97ab635ea [Constraint solver] Separate bridging conversions from other conversions.
Previously, bridging conversions were handled as a form of "explicit
conversion" that was treated along the same path as normal
conversions in matchTypes(). Historically, this made some
sense---bridging was just another form of conversion---however, Swift
now separates out bridging into a different kind of conversion that is
available only via an explicit "as". This change accomplishes a few
things:

* Improves type inference around "as" coercions. We were incorrectly
  inferring type variables of the "x" in "x as T" in cases where a
  bridging conversion was expected, which cause some type inference
  failures (e.g., the SR-3319 regression).

* Detangles checking for bridging conversions from other conversions,
  so it's easier to isolate when we're applying a bridging
  conversion.

* Explicitly handle optionals when dealing with bridging conversions,
  addressing a number of problems with incorrect diagnostics, e.g.,
  complains about "unrelated type" cast failures that would succeed at
  runtime.

Addresses rdar://problem/29496775 / SR-3319 / SR-2365.
2016-12-21 13:46:14 -08:00
Slava Pestov
fb0f372e94 AST: Move mapType{In,OutOf}Context() out of ArchetypeBuilder and clean up headers
- The DeclContext versions of these methods have equivalents
  on the DeclContext class; use them instead.

- The GenericEnvironment versions of these methods are now
  static methods on the GenericEnvironment class. Note that
  these are not made redundant by the instance methods on
  GenericEnvironment, since the static methods can also be
  called with a null GenericEnvironment, in which case they
  just assert that the type is fully concrete.

- Remove some unnecessary #includes of ArchetypeBuilder.h
  and GenericEnvironment.h. Now changes to these files
  result in a lot less recompilation.
2016-12-18 19:55:41 -08:00
Doug Gregor
0d1e904623 [AST] Fix a potential iterator invalidation issue with lazy generic environments.
The ASTContext-level map of delayed pattern contexts is a DenseMap
that could get reallocated by lazy deserialization of generic
environments. Don't re-use an iterator across the potential lazy
deserialization.
2016-12-13 09:57:07 -08:00
Doug Gregor
d4fca2cc8b [Serialization] Lazily form context types for deserialized patterns.
When a pattern within a type context is serialized, serialize its
interface type (not its contextual type). When deserializing, record
the interface type and keep a side table of the associated
DeclContext, so that we can lazily map to the contextual type on first
access. This is designed to break recursion when we change the way
archetypes and generic environments are serialized.
2016-12-09 20:48:41 -08:00
Michael Gottesman
1af1cbfb76 [gardening] Add a bunch of end namespace comments found by clang-tidy. 2016-12-06 19:22:52 -08:00
practicalswift
797b80765f [gardening] Use the correct base URL (https://swift.org) in references to the Swift website
Remove all references to the old non-TLS enabled base URL (http://swift.org)
2016-11-20 17:36:03 +01:00
Doug Gregor
df724687cd [AST] Don’t include propagated type locations in the source range of a type pattern. 2016-09-02 16:30:09 -07:00