Import simple CPP macro aliases as aliases in Swift. Extend the macro
importer to import the following construct:
```
#define alias aliasee
```
as the following Swift construct:
```
@_transparent @inline(__always)
var alias: type(of: aliasee) {
aliasee
}
```
This improves the QoI for Windows where there is a universal define
(`UNICODE`) which normally is used for translating APIs between ANSI and
Unicode variants, e.g.:
```
#if defined(UNICODE)
#define MessageBox MessageBoxW
#else
#define MessageBox MessageBoxA
#endif
```
Global variables which are non-const also have a setter synthesized:
```
@_transparent @inline(__always)
var alias: type(of: aliasee) {
get { return aliasee }
set { aliasee = newValue }
}
```
Repeatedly lookup up a key from a dictionary can be justified whenever
the content of the dictionary might change between the lookups (so any
references into the dictionary might get invalidated). We had a couple
of instances where as far as I can tell no such modifications should
happen between two lookups with identical keys. This PR simplifies the
code to remove the extra lookups. It also removes a dictionary that was
completely unused.
This commit removes the guardrails in ImportDecl.cpp:SwiftDeclConverter
that prevent it from importing non-public C++ members. It also
accordingly adjusts all code that assumes generated Swift decls should
be public. This commit does not import non-public inherited members;
that needs its own follow-up patch.
Note that Swift enforces stricter invariants about access levels than C++.
For instance, public typealiases cannot be assigned private underlying types,
and public functions cannot take or return private types. Meanwhile,
both of these patterns are supported in C++, where exposing private types
from a class's public interface is considered feature. As far as I am aware,
Swift was already importing such private-containing public decls from C++
already, but I added a test suite, access inversion, that checks and
documents this scenario, to ensure that it doesn't trip any assertions.
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)
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.
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.
After adopting the stable/20221013 clang branch, ClangImporter started seeing out-of-date identifiers in macros where it previously never had. Force these identifiers to update themselves before we read the macro definition out of them.
Fixes rdar://104456939.
`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
`ImportDecl.cpp` contained 10k+ lines of code, which caused slowdowns in incremental compilation and while editing the code in the IDE.
This change extracts a chunk of largely self-contained decl synthesis logic into a separate file.
`ClangImporter::Implementation::importType()` and associated parts of the importer are now passed an `llvm::function_ref` they can use to emit import diagnostics on the declaration they’re importing, and the `ImportDiagnosticAdder` helper class provides a convenient way to construct such a function.
This capability is not actually *used* in this commit—we are simply threading this function through the importer—so there is no change in behavior.
Swift string literals are only permitted to contain well-formed UTF-8, but C does not share this restriction, and ClangImporter wasn't checking for that before it created `StringLiteralExpr`s for imported macros; this could cause crashes when importing a header. This commit makes us drop these macros instead.
Although invalid UTF-8 always *did* cause a segfault in my testing, I'm not convinced that there isn't a way to cause a miscompile with a bug like this. If we somehow did generate code that fed ill-formed UTF-8 to the builtin literal init for Swift.String, the resulting string could cause undefined behavior at runtime. So I have additionally added a defensive assertion to StringLiteralInst that any UTF-8 string represented in SIL is well-formed. Hopefully that will catch any non-crashing compiler bugs like this one.
Fixes rdar://67840900.
This patch introduces new diagnostics to the ClangImporter to help
explain why certain C, Objective-C or C++ declarations fail to import
into Swift. This patch includes new diagnostics for the following entities:
- C functions
- C struct fields
- Macros
- Objective-C properties
- Objective-C methods
In particular, notes are attached to indicate when any of the above
entities fail to import as a result of refering an incomplete (only
forward declared) type.
The new diangostics are hidden behind two new flags, -enable-experimental-clang-importer-diagnostics
and -enable-experimental-eager-clang-module-diagnostics. The first flag emits diagnostics lazily,
while the second eagerly imports all declarations visible from loaded Clang modules. The first
flag is intended for day to day swiftc use, the second for module linting or debugging the importer.
The importer handles these by first trying to look up the type by name
using Clang's Sema, but that lookup can cause diagnostics to be
emitted (usually availability diagnostics). We could try to figure out
how to propagate that to the macro when we import it, but for now just
drop the macro instead if there are any diagnostics emitted when
looking up the type.
This will be a small source compatibility break if anyone was using a
macro defined in terms of a type that's deprecated or that has partial
availability; the macro will now silently not be imported instead of
producing an unsilenceable warning.
rdar://problem/36528212
Update several functions to return a Type/bool pair with the bool
representing whether the type is one that should be implicitly
unwrapped. This bool is surfaced up to the decl importing functions,
allowing them to set the appropriate decl attribute so that the
expression type checker will consider selecting the underlying type of
the optional involved during solving if the expression doesn't type
check with the optional type.
When importing Decls, use the IUO information to set the
ImplicitlyUnwrappedOptionalAttr attribute when appropriate.
We're still generating IUO types at the moment, so this change doesn't
really have much of an affect other than the creation of those
attributes.
Rather than being smart about this, just record an import failure when
we start importing a particular macro and update it at the end. Also
add a PrettyStackTrace to make this a little easier to track down in
the future.
The old logic for importing macros that just aliased other macros
managed to handle this in a clever way, but that was never tested for
the newer logic that evaluates expressions (fa834e2f80). Macro
importing in general probably deserves some cleanup, but meanwhile we
should make sure not to crash!
rdar://problem/34986930
This has been showing up as nondeterministic failures on our Linux
bots in the clang_builtins.swift test, because that test used to
trigger typo correction! Which pulled in macros, which happened to
include some redefinitions, which resulted in this.
rdar://problem/34266952
...which didn't do the right thing in the presence of ModuleMacro,
depending on the order the macros were referenced. Already covered by
test/ClangImporter/macros.swift, but it actually seems to improve the
behavior of some of the SourceKit tests as well.
Continuing rdar://problem/32199805, which is just "get macros working
with clang::ModuleMacro".
Somehow the logic had slipped so that we were basing this decision purely
on the ImportTypeKind and not on whether the broader context is bridgeable.
This was allowing us to use bridged types when e.g. importing the results
and parameters of C function pointer types, which is really bad.
Also, when importing a reference to a typedef of block type, do not use
the typedef in a non-bridgeable context. We import typedefs of block type
as fully-bridged types, but this means that it is invalid to import a type
using the typedef in a context where the original C type must be used.
Similarly, make sure we use a properly-imported underlying type of the
typedef when the typedef itself is unavailable.
Also, extend the special behavior of block typedefs to abstract-function
typedefs, which seems to be consistent with the expected behavior of the
tests.
Finally, I changed importType to take a new Bridgeability enum instead of
a raw canFullyBridgeTypes bool. At the time, I was doing that because I
was going to make it tri-valued; that turned out to be unnecessary, but I
think it's an improvement anyway.
We don't have any way to import a macro into a different DeclContext
anyway, but even then this saves a bit of unnecessary work.
Groundwork for rdar://problem/32199805, which is that Clang has
removed a bunch of facilities for going from a SourceLocation or
MacroInfo to a Module in favor of things like clang::ModuleMacro.
...by using a null clang::QualType as a placeholder instead of a
'QualType *' that might be null.
The problematic case here was when importing builtin types, which
would use the address of a stack local in the later call to
importNumericLiteral. Rather than fix this case specifically I just
simplified the whole thing---the extra level of indirection isn't
buying us anything.
No functionality change, other than not using memory after its
lifetime has ended. Caught by ASan!
rdar://problem/31117311
integer constants, and to always look through macro definitions for them.
Also, logical comparisons now return a Boolean.
New operations: +, -, *, /, ^, >>, ==, >, >=, <, <=
Changes:
* Terminate all namespaces with the correct closing comment.
* Make sure argument names in comments match the corresponding parameter name.
* Remove redundant get() calls on smart pointers.
* Prefer using "override" or "final" instead of "virtual". Remove "virtual" where appropriate.
SwiftNameLookupExtension and ClangImporter::Implementation were
friends, but as time goes on they have drifted apart. As part of the
ImportName refactoring, these are being decoupled to facilitate
multiple-name importing, and fight the existing false encapsulation
present in the Impl.
SwiftNameLookupExtension is now spun off into its own entity, and can
evolve to have and use its own de-coupled NameImporter.
Change more methods on the Impl to be static, passing down an
ASTContext if necessary. While this does ugly up the functions
slightly with the extra parameter, it decouples them from the Impl,
which has been a false abstraction when building the lookup
tables. These can all be moved to a more appropriate place in the
future.
NFC