Commit Graph

121 Commits

Author SHA1 Message Date
Anthony Latsis
06a5670c8f Basic: Untie swift::SourceLoc from llvm::SMLoc
Storing a `llvm::SMLoc` is a superfluous indirection, and getting rid of
it enables us to unconditionally import `SourceLoc` into Swift.
2025-07-11 18:48:42 +01:00
John Hui
44aba1382d [SourceKit] Support location info for macro-expanded Clang imports
Currently, when we jump-to-definition for decls that are macro-expanded
from Clang imported decls (e.g., safe overloads generated by
@_SwiftifyImport), setLocationInfo() emits a bongus location pointing to
a generated buffer, leading the IDE to try to jump to a file that does
not exist.

The root cause here is that setLocationInfo() calls getOriginalRange()
(earlier, getOriginalLocation()), which was not written to account for
such cases where a macro is generated from another generated buffer
whose kind is 'AttributeFromClang'.

This patch fixes setLocationInfo() with some refactoring:

-   getOriginalRange() is inlined into setLocationInfo(), so that the
    generated buffer-handling logic is localized to that function. This
    includes how it handles buffers generated for ReplacedFunctionBody.

-   getOriginalLocation() is used in a couple of other places that only
    care about macros expanded from the same buffer (so other generated
    buffers not not relevant). This "macro-chasing" logic is simplified
    and moved from ModuleDecl::getOriginalRange() to a free-standing
    function, getMacroUnexpandedRange() (there is no reason for it to be
    a method of ModuleDecl).

-   GeneratedSourceInfo now carries an extra ClangNode field, which is
    populated by getClangSwiftAttrSourceFile() when constructing
    a generated buffer for an 'AttributeFromClang'. This could probably
    be union'ed with one or more of the other fields in the future.

rdar://151020332
2025-06-12 18:22:06 -07:00
Gabor Horvath
22e2276c4f [cxx-interop] Do not require the LifetimeDependence feature in _SwiftifyImport
We use experimental features to let people know that the construct is
subject to change and users should not rely on this unless they are
willing to rewrite the uses of this feature later. However, in compiler
generated code everything should be fair game, we will update the
compiler when these features change. This is a requirement to be able to
turn safe wrapper generation on by default.
2025-03-11 17:38:53 +00:00
Doug Gregor
24a12ebc34 Renable GeneratedSourceInfo::Attribute to GeneratedSourceInfo::AttributeFromClang 2024-11-15 09:02:49 -08:00
Doug Gregor
989c73d014 Ensure that buffers containing Clang swift_attr attributes are parsed as attributes
Previously, they were being parsed as top-level code, which would cause
errors because there are no definitions. Introduce a new
GeneratedSourceInfo kind to mark the purpose of these buffers so the
parser can handle them appropriately.
2024-11-13 21:19:37 -08:00
Allan Shortlidge
42ebee8dd1 AST: Improve TypeRefinementContext debug descriptions.
When printing the source ranges for nodes that represent an expansion within a
source file, print the range from the original source file and include a
description of the kind of expansion.
2024-10-08 09:55:28 -07:00
Doug Gregor
6f88c228df Maintain a buffer ID -> source file(s) mapping in the source manager
Now that every source file has a buffer ID, introduce the reverse mapping
so clients can find the source file(s) in their module that reference
that buffer ID.
2024-09-17 14:01:58 -07:00
Saleem Abdulrasool
8d9c5e178c Merge pull request #75406 from z2oh/fix-sourcekitd-file-locks-windows
Fix sourcekitd persistent file-locks on Windows
2024-08-01 09:51:17 -07:00
Jeremy Day
221c7039bd Add explicit OpenSourcesAsVolatile option 2024-07-26 17:02:04 -07:00
Jeremy Day
a22419f1d0 Fix sourcekitd persistent file-locks on Windows 2024-07-23 09:59:41 -07:00
Rintaro Ishizaki
fba8b10cda Merge pull request #75115 from rintaro/basic-ondiscbuffer-cache
[Basic] Don't rewrite source buffer copy multiple times
2024-07-09 18:54:56 -07:00
Rintaro Ishizaki
90c2975d66 [Basic] Don't rewrite source buffer copy multiple times
The on-disc buffer file name was not recorded correctly.

rdar://130478685
2024-07-09 15:09:30 -07:00
Steven Wu
30737eb396 [Caching] Support swift style diagnostics for swift caching
Add support for swift style diagnostics for swift caching. This includes
pre-populate the GeneratedSourceInfo with macro name so it doesn't need
to infer from an ASTNode, which the caching mechanism cannot preserve.

Still leave the default diagnostic style to LLVM style because replaying
swift style diagnostics is still very slow and including parsing source
file using swift-syntax.

rdar://128615572
2024-07-08 16:15:44 -07:00
Steven Wu
68c755e99c [Caching] Temporarily using llvm style diagnostics in caching
When caching is enabled, using swift style diagnotics can lead to
crashes due to some uninitialized variables. Even more, the swift style
diagnostics is not going to render the same when replay from the cache
since the currect caching diagnostics processor is not capture all
information that is needed to render diagnostis from SwiftSyntax.
Temprarily using llvm style for caching builds.

rdar://127530204
2024-05-22 13:15:08 -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
Apollo Zhu
b09a22a9a0 Somewhat working
Test shadowed variable of same type

Fully type check caller side macro expansion

Skip macro default arg caller side expr at decl primary

Test macro expand more complex expressions

Set synthesized expression as implicit

Add test case for with argument, not compiling currently

Test with swiftinterface

Always use the string representation of the default argument

Now works across module boundary

Check works for multiple files

Make default argument expression work in single file

Use expected-error

Disallow expression macro as default argument

Using as a sub expression in default argument still allowed as expression macros behave the same as built-in magic literals
2024-02-06 15:02:11 -08:00
Doug Gregor
79e31a87b3 Re-implement ASTScope's child-insertion assertions
ASTScope assertions that a new child node inserted into its parent list
is after all other child nodes in the source, which included some bespoke
code for dealing with macro expansions. Replace this bespoke code with
uses of the newer SourceManager operations that check ordering of
source locations in a manner that respects macro expansions.
2023-11-30 10:54:42 -08:00
Doug Gregor
37ed49e0bd Implement ordering of source locations that accounts for macro expansion
SourceManager's `isBeforeInBuffer` in buffer takes two source locations
that are assumed to be within the same source buffer and determines
whether the first precedes the second. However, due to macro
expansion, there can be source locations in different source buffers
that are nonetheless conceptually part of the same source file. For
such cases, `isBeforeInBuffer` will silently produce wrong results.

Extend `SourceManager` with a new `isBefore` operation that determines
whether one source location precedes another in the same conceptual
source file, even if they are in different source buffers that (e.g.)
represent macro expansions within that source file. Also introduce
`isAtOrBefore` to cover the case where the source locations might be
equivalent, which was previously handled via a separate equality check
on the source locations that won't work with macro expansions.

Add caching for the list of accessors of a buffer, so we aren't doing
a full walk up the source-buffer chain ever time we do a comparison of
source locations. LCA is still linear-time, but this eliminates
extraneous hash table lookups along the way.

Over time, we should both move more clients over to these new variants
and introduce more assertions into the old (in-buffer) versions to
catch improper uses of them.
2023-11-30 09:55:56 -08:00
Doug Gregor
b53026d8d4 [Macros] Macro-metaprogram macro roles
Introduce X-macros for the various macro roles, and use them to
macro-metaprogram a lot of boilerplate involved with introducing new
macro roles.
2023-11-13 22:37:54 -08:00
Doug Gregor
f36d2d3978 [Source manager] Improve the performance of findBufferContainingLocInternal()
This function was performing a linear scan through the set of known
buffers to find the buffer containing a given source location. This
linear scan can show up in hot loops, and the number of buffers in a
program is increasing due to macros, so this has become a performance
problem.

Replace the linear scan with a logarithmic lookup into a sorted vector
of the buffer IDs, with a one-element most-recently-used cache so that
repeated lookups in the same buffer require constant time.

This mirrors what we already do with source files in a module.
Unfortunately, we cannot reuse that code because there is no link from
buffers to source files. We should look to consolidate this in the
future.

Fixes rdar://116184248.
2023-10-04 14:37:34 -07:00
Doug Gregor
9bf512adf0 [Diagnostics] Remove the C++ formatter for the "Swift" diagnostic style
We'll be using the new swift-syntax diagnostic formatter in the near
future, as it is nearly available on all host platforms. So, remove
the C++ formatter that did source-line annotation, falling back to the
"LLVM" style when swift-syntax is not compiled in.
2023-09-04 22:22:17 -07:00
Holly Borla
725374e0d8 [Macros] Implement attached extension macros. 2023-06-27 21:22:12 -07:00
Evan Wilde
250082df25 [NFC] Reformat all the LLVMs
Reformatting everything now that we have `llvm` namespaces. I've
separated this from the main commit to help manage merge-conflicts and
for making it a bit easier to read the mega-patch.
2023-06-27 09:03:52 -07: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
Hamish Knight
a3848c62d5 [Profiler] Don't profile generated buffers
We may want to revisit this in the future, but for
now let's avoid profiling code in generated
buffers. To make this work we'll need to come up
with a scheme for writing out the generated buffers
such that tools like `llvm-cov` can reference them.

rdar://109562235
2023-05-20 00:32:20 +01:00
Holly Borla
a3caacd309 [Macros] Initial implementation of conformance macros. 2023-02-23 20:43:11 -08:00
Alex Hoppen
8bdf68d483 [IDE] Check whether an AST node contains the IDE inspection point based on CharSourceRange
This fixes an issue if the range ends with a string literal that contains the IDE inspection target. In that case the end of the range will point to the start of the string literal but the IDE inspection target is inside the string literal and thus after the range’s end.
2023-02-20 15:37:38 +01:00
Doug Gregor
7ea0e3f096 Switch GeneratedSourceInfo ranges over to CharSourceRange.
Macro expansion buffers, along with other generated source buffers,
need more precise "original source ranges" that can be had with the
token-based `SourceRange`. Switch over to `CharSourceRange` and provide
more thoughtfully-determined original source ranges.
2023-02-11 11:23:26 -08:00
Holly Borla
f04f512184 [Macros] Add a new macro role for attached peer macros. 2023-02-10 14:38:22 -08:00
Doug Gregor
c085f5afd9 Record original source range of generated source buffers into dumped files
This helps us establish where the code from a generated source buffer
would go, for external tools that don't understand serialized
diagnostics.
2023-02-08 18:08:33 -08:00
Alex Hoppen
a5f85ee10c [SourceKit] Make sure we reuse ASTContext in function bodies for solver-based cursor info
The main problem that prevented us from reusing the ASTContext was that we weren’t remapping the `LocToResolve` in the temporary buffer that only contains the re-parsed function back to the original buffer. Thus `NodeFinder` couldn’t find the node that we want to get cursor info for.

Getting AST reuse to work for top-level items is harder because it currently heavily relies on the `HasCodeCompletion` state being set on the parser result. I’ll try that in a follow-up PR.

rdar://103251263
2023-02-02 22:03:25 +01:00
Doug Gregor
8871129896 [Macros] Add frontend flag to dump macro expansions for diagnostics.
Add frontend flag `-emit-macro-expansion-files diagnostics` to emit any
macro expansion buffers referenced by diagnostics into files in a
temporary directory. This makes debugging type-checking failures in
macro expansions far easier, because you can see them after the
compiler process has exited.
2023-01-30 18:05:53 -08:00
Holly Borla
f6f57a8099 [Macros] Rename "synthesized member macros" to "member macros". 2023-01-26 21:52:36 -08:00
Holly Borla
8b9be30783 [Macros] Add a new macro role for synthesized member macros. 2023-01-22 21:19:21 -08:00
Doug Gregor
31a3d8e329 Introduce infrastructure to dump generated source buffers into temporary files 2023-01-19 21:30:22 -08:00
Holly Borla
1b74d6cfcc [SourceManager] Distinguish between the various macro roles in
GeneratedSourceInfo::Kind.
2023-01-15 10:11:00 -08:00
Doug Gregor
91ee109c2f [Macros] Start expanding accessor macros attached to a storage declaration.
Accessor macros are attached macros (written with attribute syntax)
that can generate accessors for a property or subscript. Recognize
custom attributes that are accessor macros when written on a storage
declaration, and expand those macros.

This is very much a work in progress, and the result of the expansion
isn't yet parsed or wired into the AST.
2023-01-13 10:12:25 -08:00
Doug Gregor
514a05297e Drop the original buffer ID from GeneratedSourceInfo.
Nobody is using it, and this information is recoverable from the original
source range.
2023-01-06 11:17:29 -08:00
Doug Gregor
5c217bd17c Add source buffers pretty-printed for diagnostics to serialized diagnostics
When emitting a diagnostic that references a declaration that does not
itself have a source location (e.g., because it was synthesized or
deserialized), the diagnostics engine pretty-prints the declaration
into a buffer so it can provide caret diagnostics pointing to that
declaration.

Start marking those buffers as "generated source buffers", so that we
emit their contents into serialized diagnostics files. This will allow
tools that make use of serialized diagnostics to also show caret
information.
2023-01-06 11:17:29 -08:00
Doug Gregor
0407610162 [Macros] Don't parse the macro expansion buffer twice.
Each macro expansion buffer was getting parsed twice: once by
ParseSourceFileRequest (which is used by unqualified name lookup) and
once to parse the expression when type-checking the expanded macro.
This meant that the same code had two ASTs. Hilarity ensures.

Stop directly invoking the parser on macro-expanded code. Instead, go
through ParseSourceFileRequest *as is always the right way*, and dig
out the expression we want.
2023-01-02 21:22:04 -08:00
Doug Gregor
f467ef4d37 [Source manager] Start tracking generated-source info in the source manager
Establish the relationship for generated sources, whether for macro
expansions or (via a small stretch) replacing function bodies with
other bodies, in the source manager itself. This makes the information
available for diagnostic rendering, and unifies a little bit of the
representation, although it isn't used for much yet.
2022-12-14 23:02:27 -08:00
Alex Hoppen
fe2ae72ad2 [IDE] Rename CodeCompletion to IDEInspection in cases where the code path no longer exclusively applies to code completion
The code completio infrastructure is also being used for cursor info now, so it should no longer be called code completion.

rdar://103251187
2022-12-13 11:41:05 +01:00
Erik Eckstein
ab1b343dad use new llvm::Optional API
`getValue` -> `value`
`getValueOr` -> `value_or`
`hasValue` -> `has_value`
`map` -> `transform`

The old API will be deprecated in the rebranch.
To avoid merge conflicts, use the new API already in the main branch.

rdar://102362022
2022-11-21 19:44:24 +01:00
Hamish Knight
e234f80f14 Track regex literal source locations in SourceManager
This is unfortunately needed to ensure we correctly
re-lex regex literal tokens correctly, which is
needed for diagnostic logic to correctly compute
source ranges.

rdar://92469692
2022-05-11 10:45:39 +01:00
Anthony Latsis
8e4ea9b01a [NFC] DiagnosticVerifier: Move 'getColumnNumber' into SourceManager 2022-01-31 05:04:09 +03:00
Rintaro Ishizaki
7c92a8e555 [SourceKit] Add a request to generate object files in SourceKit
Add 'request.compile'
2021-12-21 14:35:38 -08:00
Ben Barham
c763ab5d1e [Serialization] Store offset of decls in .swiftsourceinfo
The locations stored in .swiftsourceinfo included the presumed file,
line, and column. When a location is requested it would read these, open
the external file, create a line map, and find the offset corresponding
to that line/column.

The offset is known during serialization though, so output it as well to
avoid having to read the file and generate the line map.

Since the serialized location is returned from `Decl::getLoc()`, it
should not be the presumed location. Instead, also output the line
directives so that the presumed location can be built as per normal
locations.

Finally, move the cache out of `Decl` and into `ASTContext`, since very
few declarations will actually have their locations deserialized. Make
sure to actually write to that cache so it's used - the old cache was
never written to.
2021-04-29 12:33:05 +10:00
Becca Royal-Gordon
1f713074ac [NFC] Fix issues with -verify mode
This commit fixes two weird bugs in -verify mode:

1. SourceLocs from the wrong SourceManager could be passed through a ForwardingDiagnosticConsumer into the DiagnosticVerifier.

2. -verify-additional-file did not error out correctly when the file couldn’t be opened.

No tests, as we only have basic tests for the diagnostic verifier.
2021-03-25 16:02:29 -07:00
Becca Royal-Gordon
ccf244b89b Add ability to load access notes 2021-02-09 14:17:33 -08:00
Robert Widmann
cedef16f54 [NFC] Mark SourceManager::getIDForBufferIdentifier const 2020-09-11 13:54:39 -06:00