From b3d31c7d512c16bc266ee73444df000e0790dcca Mon Sep 17 00:00:00 2001 From: Daniil Kovalev Date: Mon, 6 Oct 2025 14:45:09 +0300 Subject: [PATCH 1/7] Bridging: Implement bridges required for ongoing AutoDiff changes In #83926, part of the changes resolving #68944 is submitted. The AutoDiff closure specialization optimizer pass relies on several bridges not implemented yet. This patch introduces these missing bridges. See the list of the changes below. **AST:** * Define `.asValueDecl` on each BridgedXXXDecl type that's also a ValueDecl. * Define `.asNominalTypeDecl` on each BridgedXXXDecl type that's also a NominalTypeDecl. * Define `.asGenericContext` on each BridgedXXXDecl type that's also a GenericContext. * `class BridgedSourceFile`: - Make nullable - `func addTopLevelDecl(_ decl: BridgedDecl)` * `class BridgedFileUnit`: - `func castToSourceFile() -> BridgedNullableSourceFile` * `class BridgedDecl`: - `func getDeclContext() -> BridgedDeclContext` * `class BridgedParamDecl`: - `func cloneWithoutType() -> BridgedParamDecl` - `func setInterfaceType(_ type : BridgedASTType)` * Define `BridgedDecl.setImplicit()` instead of `BridgedParamDecl.setImplicit()` * `class BridgedGenericContext`: - `setGenericSignature(_ genSig: BridgedGenericSignature)` * Change return type of `BridgedEnumDecl.createParsed(/*...*/)` from `BridgedNominalTypeDecl` to `BridgedEnumDecl` * `class BridgedValueDecl`: - `func setAccess(_ accessLevel: swift.AccessLevel)` * `class BridgedNominalTypeDecl`: - `func addMember(_ member: BridgedDecl)` * `class BridgedGenericTypeParamDecl`: - `func createImplicit(declContext: BridgedDeclContext, name: swift.Identifier, depth: UInt, index: UInt, paramKind: swift.GenericTypeParamKind)` * `class ValueDecl`: - `var baseIdentifier: swift.Identifier` * `class NominalTypeDecl`: - `var declaredInterfaceType: Type` * `class EnumElementDecl`: - `var parameterList: BridgedParameterList` - `var nameStr: StringRef` * `struct GenericSignature`: - `var canonicalSignature: CanGenericSignature` * `struct CanGenericSignature`: - `var isEmpty: Bool` - `var genericSignature: GenericSignature` * `struct Type`: - `func mapTypeOutOfContext() -> Type` - `func getReducedType(sig: GenericSignature) -> CanonicalType` - `func GenericTypeParam_getName() -> swift.Identifier` - `func GenericTypeParam_getDepth() -> UInt` - `func GenericTypeParam_getIndex() -> UInt` - `func GenericTypeParam_getParamKind() -> swift.GenericTypeParamKind` * `struct CanonicalType`: - `func SILFunctionType_getSubstGenericSignature() -> CanGenericSignature` - `func loweredType(in function: SIL.Function) -> SIL.Type` **SIL:** * `class Argument`: - `func replaceAllUsesWith(newArg: Argument)` * `class BasicBlock`: - `func insertPhiArgument(atPosition: Int, type: Type, ownership: Ownership, _ context: some MutatingContext) -> Argument` * `struct Builder`: - `func createTuple(elements: [Value]) -> TupleInst` * `protocol Context`: - `func getTupleType(elements: [AST.Type]) -> AST.Type` - `func getTupleTypeWithLabels(elements: [AST.Type], labels: [swift.Identifier]) -> AST.Type` * `class Function`: - `var sourceFile: BridgedNullableSourceFile` - `func mapTypeIntoContext(_ type: Type) -> Type` * `class PartialApplyInst`: - `var substitutionMap: SubstitutionMap` * `class SwitchEnumInst`: - `var numCases: Int` - `public func getSuccessorForDefault() -> BasicBlock?` * `Type`: - `var category: ValueCategory` - `func getEnumCasePayload(caseIdx: Int, function: Function) -> Type` - `func mapTypeOutOfContext() -> Type` - `static func getPrimitiveType(canType: CanonicalType, silValueCategory: ValueCategory) -> Type` * `struct EnumCase`: - `let enumElementDecl: EnumElementDecl` * `struct TupleElementArray`: - `func label(at index: Int) -> swift.Identifier` * Define `enum ValueCategory` with `address` and `object` elements --- .../Sources/AST/Declarations.swift | 7 + .../Sources/AST/GenericSignature.swift | 14 ++ SwiftCompilerSources/Sources/AST/Type.swift | 28 ++++ .../Sources/SIL/ASTExtensions.swift | 4 + .../Sources/SIL/Argument.swift | 4 + .../Sources/SIL/BasicBlock.swift | 5 + .../Sources/SIL/Builder.swift | 7 + .../Sources/SIL/Context.swift | 14 ++ .../Sources/SIL/Function.swift | 8 + .../Sources/SIL/Instruction.swift | 6 + SwiftCompilerSources/Sources/SIL/Type.swift | 19 ++- SwiftCompilerSources/Sources/SIL/Value.swift | 21 +++ include/swift/AST/ASTBridging.h | 100 ++++++++++++- include/swift/AST/ASTBridgingImpl.h | 101 ++++++++++++- include/swift/AST/ASTBridgingWrappers.def | 4 +- include/swift/SIL/SILBridging.h | 35 +++++ include/swift/SIL/SILBridgingImpl.h | 137 ++++++++++++++++++ lib/AST/Bridging/DeclBridging.cpp | 43 +++++- lib/AST/Bridging/GenericsBridging.cpp | 9 ++ lib/ASTGen/Sources/ASTGen/Decls.swift | 4 +- lib/ASTGen/Sources/ASTGen/Exprs.swift | 2 +- 21 files changed, 561 insertions(+), 11 deletions(-) diff --git a/SwiftCompilerSources/Sources/AST/Declarations.swift b/SwiftCompilerSources/Sources/AST/Declarations.swift index 2041d32fd22de..6724cf2f16448 100644 --- a/SwiftCompilerSources/Sources/AST/Declarations.swift +++ b/SwiftCompilerSources/Sources/AST/Declarations.swift @@ -39,6 +39,7 @@ public class Decl: CustomStringConvertible, Hashable { public class ValueDecl: Decl { final public var nameLoc: SourceLoc? { SourceLoc(bridged: bridged.Value_getNameLoc()) } final public var userFacingName: StringRef { StringRef(bridged: bridged.Value_getUserFacingName()) } + final public var baseIdentifier: swift.Identifier { bridged.Value_getBaseIdentifier() } final public var isObjC: Bool { bridged.Value_isObjC() } } @@ -56,6 +57,10 @@ public class NominalTypeDecl: GenericTypeDecl { final public var valueTypeDestructor: DestructorDecl? { bridged.NominalType_getValueTypeDestructor().getAs(DestructorDecl.self) } + + public var declaredInterfaceType : AST.`Type` { + AST.`Type`(bridged: bridged.NominalType_getDeclaredInterfaceType()) + } } final public class EnumDecl: NominalTypeDecl { @@ -118,6 +123,8 @@ final public class MacroDecl: ValueDecl {} final public class EnumElementDecl: ValueDecl { public var hasAssociatedValues: Bool { bridged.EnumElementDecl_hasAssociatedValues() } + public var parameterList: BridgedParameterList { bridged.EnumElementDecl_getParameterList() } + public var nameStr: StringRef { StringRef(bridged: bridged.EnumElementDecl_getNameStr()) } } final public class ExtensionDecl: Decl {} diff --git a/SwiftCompilerSources/Sources/AST/GenericSignature.swift b/SwiftCompilerSources/Sources/AST/GenericSignature.swift index 64b858e9b4bd2..f91ad0504ba00 100644 --- a/SwiftCompilerSources/Sources/AST/GenericSignature.swift +++ b/SwiftCompilerSources/Sources/AST/GenericSignature.swift @@ -35,4 +35,18 @@ public struct GenericSignature: CustomStringConvertible, NoReflectionChildren { } public var isEmpty: Bool { bridged.impl == nil } + + public var canonicalSignature: CanGenericSignature { CanGenericSignature(bridged: bridged.getCanonicalSignature()) } +} + +public struct CanGenericSignature { + public let bridged: BridgedCanGenericSignature + + public init(bridged: BridgedCanGenericSignature) { + self.bridged = bridged + } + + public var isEmpty: Bool { bridged.impl == nil } + + public var genericSignature: GenericSignature { GenericSignature(bridged: bridged.getGenericSignature()) } } diff --git a/SwiftCompilerSources/Sources/AST/Type.swift b/SwiftCompilerSources/Sources/AST/Type.swift index c193387800f1a..008fc55776bc0 100644 --- a/SwiftCompilerSources/Sources/AST/Type.swift +++ b/SwiftCompilerSources/Sources/AST/Type.swift @@ -66,6 +66,30 @@ public struct Type: TypeProperties, CustomStringConvertible, NoReflectionChildre public func subst(with substitutionMap: SubstitutionMap) -> Type { return Type(bridged: bridged.subst(substitutionMap.bridged)) } + + public func mapTypeOutOfContext() -> Type { + return Type(bridged: bridged.mapTypeOutOfContext()) + } + + public func getReducedType(sig: GenericSignature) -> CanonicalType { + CanonicalType(bridged: bridged.getReducedType(sig.bridged)) + } + + public func GenericTypeParam_getName() -> swift.Identifier { + return bridged.GenericTypeParam_getName() + } + + public func GenericTypeParam_getDepth() -> UInt { + return bridged.GenericTypeParam_getDepth() + } + + public func GenericTypeParam_getIndex() -> UInt { + return bridged.GenericTypeParam_getIndex() + } + + public func GenericTypeParam_getParamKind() -> swift.GenericTypeParamKind { + return bridged.GenericTypeParam_getParamKind() + } } /// A Type that is statically known to be canonical. @@ -86,6 +110,10 @@ public struct CanonicalType: TypeProperties, CustomStringConvertible, NoReflecti public func subst(with substitutionMap: SubstitutionMap) -> CanonicalType { return rawType.subst(with: substitutionMap).canonical } + + public func SILFunctionType_getSubstGenericSignature() -> CanGenericSignature { + CanGenericSignature(bridged: bridged.SILFunctionType_getSubstGenericSignature()) + } } /// Implements the common members of `AST.Type`, `AST.CanonicalType` and `SIL.Type`. diff --git a/SwiftCompilerSources/Sources/SIL/ASTExtensions.swift b/SwiftCompilerSources/Sources/SIL/ASTExtensions.swift index f02ab08bef4a8..76b47a4cda938 100644 --- a/SwiftCompilerSources/Sources/SIL/ASTExtensions.swift +++ b/SwiftCompilerSources/Sources/SIL/ASTExtensions.swift @@ -36,6 +36,10 @@ extension CanonicalType { precondition(isBox) return BoxFieldsArray(boxType: self, function: function) } + + public func loweredType(in function: Function) -> Type { + function.bridged.getLoweredType(bridged).type + } } extension Decl { diff --git a/SwiftCompilerSources/Sources/SIL/Argument.swift b/SwiftCompilerSources/Sources/SIL/Argument.swift index 8a9c861366501..88b3662761057 100644 --- a/SwiftCompilerSources/Sources/SIL/Argument.swift +++ b/SwiftCompilerSources/Sources/SIL/Argument.swift @@ -50,6 +50,10 @@ public class Argument : Value, Hashable { public var sourceLoc: SourceLoc? { findVarDecl()?.nameLoc } + public func replaceAllUsesWith(newArg: Argument) { + bridged.replaceAllUsesWith(newArg.bridged) + } + public static func ==(lhs: Argument, rhs: Argument) -> Bool { lhs === rhs } diff --git a/SwiftCompilerSources/Sources/SIL/BasicBlock.swift b/SwiftCompilerSources/Sources/SIL/BasicBlock.swift index c543559c24489..cdd548f5dc8fe 100644 --- a/SwiftCompilerSources/Sources/SIL/BasicBlock.swift +++ b/SwiftCompilerSources/Sources/SIL/BasicBlock.swift @@ -68,6 +68,11 @@ final public class BasicBlock : CustomStringConvertible, HasShortDescription, Ha (decl as Decl?).bridged).argument as! FunctionArgument } + public func insertPhiArgument(atPosition: Int, type: Type, ownership: Ownership, _ context: some MutatingContext) -> Argument { + context.notifyInstructionsChanged() + return bridged.insertPhiArgument(atPosition, type.bridged, ownership._bridged).argument + } + public func eraseArgument(at index: Int, _ context: some MutatingContext) { context.notifyInstructionsChanged() bridged.eraseArgument(index) diff --git a/SwiftCompilerSources/Sources/SIL/Builder.swift b/SwiftCompilerSources/Sources/SIL/Builder.swift index 5072bf4759393..43fcb73ce27a5 100644 --- a/SwiftCompilerSources/Sources/SIL/Builder.swift +++ b/SwiftCompilerSources/Sources/SIL/Builder.swift @@ -662,6 +662,13 @@ public struct Builder { return notifyNew(tuple.getAs(TupleInst.self)) } + public func createTuple(elements: [Value]) -> TupleInst { + let tuple = elements.withBridgedValues { valuesRef in + return bridged.createTuple(valuesRef) + } + return notifyNew(tuple.getAs(TupleInst.self)) + } + public func createTupleExtract(tuple: Value, elementIndex: Int) -> TupleExtractInst { return notifyNew(bridged.createTupleExtract(tuple.bridged, elementIndex).getAs(TupleExtractInst.self)) } diff --git a/SwiftCompilerSources/Sources/SIL/Context.swift b/SwiftCompilerSources/Sources/SIL/Context.swift index 1db07567efaeb..3384573b6a29d 100644 --- a/SwiftCompilerSources/Sources/SIL/Context.swift +++ b/SwiftCompilerSources/Sources/SIL/Context.swift @@ -55,6 +55,20 @@ extension Context { } } + public func getTupleType(elements: [AST.`Type`]) -> AST.`Type` { + let bridgedElements = elements.map { $0.bridged } + return bridgedElements.withBridgedArrayRef { + AST.`Type`(bridged: _bridged.getTupleType($0)) + } + } + + public func getTupleTypeWithLabels(elements: [AST.`Type`], labels: [swift.Identifier]) -> AST.`Type` { + assert(elements.count == labels.count) + return elements.withBridgedArrayRef{ + eltArr in labels.withBridgedArrayRef{labelsArr in + AST.`Type`(bridged: _bridged.getTupleTypeWithLabels(eltArr, labelsArr))}} + } + public var swiftArrayDecl: NominalTypeDecl { _bridged.getSwiftArrayDecl().getAs(NominalTypeDecl.self) } diff --git a/SwiftCompilerSources/Sources/SIL/Function.swift b/SwiftCompilerSources/Sources/SIL/Function.swift index a802984455223..548b08b69da9b 100644 --- a/SwiftCompilerSources/Sources/SIL/Function.swift +++ b/SwiftCompilerSources/Sources/SIL/Function.swift @@ -26,6 +26,10 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash return Location(bridged: bridged.getLocation()) } + public var sourceFile: BridgedNullableSourceFile { + return bridged.getSourceFile() + } + final public var description: String { return String(taking: bridged.getDebugDescription()) } @@ -88,6 +92,10 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash return AST.`Type`(bridged: bridged.mapTypeIntoContext(type.bridged)) } + public func mapTypeIntoContext(_ type: Type) -> Type { + return Type(bridged: bridged.mapTypeIntoContext(type.bridged)) + } + /// Returns true if the function is a definition and not only an external declaration. /// /// This is the case if the function contains a body, i.e. some basic blocks. diff --git a/SwiftCompilerSources/Sources/SIL/Instruction.swift b/SwiftCompilerSources/Sources/SIL/Instruction.swift index 6786cb516f2f2..c33ae1772f725 100644 --- a/SwiftCompilerSources/Sources/SIL/Instruction.swift +++ b/SwiftCompilerSources/Sources/SIL/Instruction.swift @@ -1351,6 +1351,7 @@ final public class PartialApplyInst : SingleValueInstruction, ApplySite { public var hasUnknownResultIsolation: Bool { bridged.PartialApplyInst_hasUnknownResultIsolation() } public var unappliedArgumentCount: Int { bridged.PartialApply_getCalleeArgIndexOfFirstAppliedArg() } public var calleeConvention: ArgumentConvention { type.bridged.getCalleeConvention().convention } + public var substitutionMap: SubstitutionMap { SubstitutionMap(bridged: bridged.PartialApplyInst_getSubstitutionMap()) } } final public class ApplyInst : SingleValueInstruction, FullApplySite { @@ -1929,6 +1930,7 @@ final public class SwitchValueInst : TermInst { final public class SwitchEnumInst : TermInst { public var enumOp: Value { operands[0].value } + public var numCases: Int { bridged.SwitchEnumInst_getNumCases() } public struct CaseIndexArray : RandomAccessCollection { fileprivate let switchEnum: SwitchEnumInst @@ -1953,6 +1955,10 @@ final public class SwitchEnumInst : TermInst { cases.first(where: { $0.0 == forCaseIndex })?.1 } + public func getSuccessorForDefault() -> BasicBlock? { + return self.bridged.SwitchEnumInst_getSuccessorForDefault().block + } + // This does not handle the special case where the default covers exactly // the "missing" case. public func getUniqueCase(forSuccessor: BasicBlock) -> Int? { diff --git a/SwiftCompilerSources/Sources/SIL/Type.swift b/SwiftCompilerSources/Sources/SIL/Type.swift index ea1767fccb7b7..397c4b4198e0d 100644 --- a/SwiftCompilerSources/Sources/SIL/Type.swift +++ b/SwiftCompilerSources/Sources/SIL/Type.swift @@ -27,6 +27,7 @@ public struct Type : TypeProperties, CustomStringConvertible, NoReflectionChildr public var isAddress: Bool { bridged.isAddress() } public var isObject: Bool { !isAddress } + public var category: ValueCategory { ValueCategory(bridged: bridged.getCategory()) } public var addressType: Type { bridged.getAddressType().type } public var objectType: Type { bridged.getObjectType().type } @@ -214,6 +215,16 @@ public struct Type : TypeProperties, CustomStringConvertible, NoReflectionChildr } return false } + + public func getEnumCasePayload(caseIdx: Int, function: Function) -> Type { + bridged.getEnumCasePayload(caseIdx, function.bridged).type + } + + public func mapTypeOutOfContext() -> Type { bridged.mapTypeOutOfContext().type } + + public static func getPrimitiveType(canType: CanonicalType, silValueCategory: ValueCategory) -> Type { + BridgedType.getPrimitiveType(canType: canType.bridged, silValueCategory: silValueCategory._bridged).type + } } extension Type: Equatable { @@ -266,6 +277,7 @@ public struct NominalFieldsArray : RandomAccessCollection, FormattedLikeArray { } public struct EnumCase { + public let enumElementDecl : EnumElementDecl public let payload: Type? public let index: Int } @@ -288,7 +300,8 @@ public struct EnumCases : CollectionLikeSequence, IteratorProtocol { caseIterator = caseIterator.getNext() caseIndex += 1 } - return EnumCase(payload: enumType.bridged.getEnumCasePayload(caseIterator, function.bridged).typeOrNil, + return EnumCase(enumElementDecl: enumType.bridged.getEnumElementDecl(caseIterator).getAs(EnumElementDecl.self), + payload: enumType.bridged.getEnumCasePayload(caseIterator, function.bridged).typeOrNil, index: caseIndex) } return nil @@ -304,6 +317,10 @@ public struct TupleElementArray : RandomAccessCollection, FormattedLikeArray { public subscript(_ index: Int) -> Type { type.bridged.getTupleElementType(index).type } + + public func label(at index: Int) -> swift.Identifier { + type.bridged.getTupleElementLabel(index) + } } public struct BoxFieldsArray : RandomAccessCollection, FormattedLikeArray { diff --git a/SwiftCompilerSources/Sources/SIL/Value.swift b/SwiftCompilerSources/Sources/SIL/Value.swift index a346cb621ba80..213a176d72832 100644 --- a/SwiftCompilerSources/Sources/SIL/Value.swift +++ b/SwiftCompilerSources/Sources/SIL/Value.swift @@ -41,6 +41,27 @@ public protocol Value : AnyObject, CustomStringConvertible { var isLexical: Bool { get } } +public enum ValueCategory { + case address + case object + + public init(bridged: BridgedValueCategory) { + switch bridged { + case .Address: self = .address + case .Object: self = .object + default: + fatalError("unsupported value category") + } + } + + public var _bridged: BridgedValueCategory { + switch self { + case .address: return BridgedValueCategory.Address + case .object: return BridgedValueCategory.Object + } + } +} + public enum Ownership { /// A Value with `unowned` ownership kind is an independent value that /// has a lifetime that is only guaranteed to last until the next program diff --git a/include/swift/AST/ASTBridging.h b/include/swift/AST/ASTBridging.h index ec88cb660a4f0..860ce0dfe5629 100644 --- a/include/swift/AST/ASTBridging.h +++ b/include/swift/AST/ASTBridging.h @@ -86,6 +86,7 @@ class BridgedASTContext; class BridgedLangOptions; struct BridgedSubstitutionMap; struct BridgedGenericSignature; +struct BridgedCanGenericSignature; struct BridgedConformance; class BridgedParameterList; @@ -315,11 +316,15 @@ struct BridgedDeclObj { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef Type_getName() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef Value_getUserFacingName() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE swift::SourceLoc Value_getNameLoc() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE swift::Identifier + Value_getBaseIdentifier() const; BRIDGED_INLINE bool hasClangNode() const; BRIDGED_INLINE bool Value_isObjC() const; BRIDGED_INLINE bool AbstractStorage_isConst() const; BRIDGED_INLINE bool GenericType_isGenericAtAnyLevel() const; BRIDGED_INLINE bool NominalType_isGlobalActor() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType + NominalType_getDeclaredInterfaceType() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedDeclObj NominalType_getValueTypeDestructor() const; BRIDGED_INLINE bool Enum_hasRawType() const; BRIDGED_INLINE bool Struct_hasUnreferenceableStorage() const; @@ -329,6 +334,10 @@ struct BridgedDeclObj { BRIDGED_INLINE bool AbstractFunction_isOverridden() const; BRIDGED_INLINE bool Destructor_isIsolated() const; BRIDGED_INLINE bool EnumElementDecl_hasAssociatedValues() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedParameterList + EnumElementDecl_getParameterList() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef + EnumElementDecl_getNameStr() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef AccessorDecl_getKindName() const; }; @@ -382,6 +391,23 @@ class BridgedASTNode { #define ABSTRACT_DECL(Id, Parent) DECL(Id, Parent) #include "swift/AST/DeclNodes.def" +// Declare `.asValueDecl` on each BridgedXXXDecl type that's also a +// ValueDecl. +#define DECL(Id, Parent) +#define VALUE_DECL(Id, Parent) \ + SWIFT_NAME("getter:Bridged" #Id "Decl.asValueDecl(self:)") \ + BridgedValueDecl Bridged##Id##Decl_asValueDecl(Bridged##Id##Decl decl); +#include "swift/AST/DeclNodes.def" + +// Declare `.asNominalTypeDecl` on each BridgedXXXDecl type that's also a +// NominalTypeDecl. +#define DECL(Id, Parent) +#define NOMINAL_TYPE_DECL(Id, Parent) \ + SWIFT_NAME("getter:Bridged" #Id "Decl.asNominalTypeDecl(self:)") \ + BridgedNominalTypeDecl Bridged##Id##Decl_asNominalTypeDecl( \ + Bridged##Id##Decl decl); +#include "swift/AST/DeclNodes.def" + // Declare `.asDeclContext` on each BridgedXXXDecl type that's also a // DeclContext. #define DECL(Id, Parent) @@ -391,6 +417,16 @@ class BridgedASTNode { #define ABSTRACT_CONTEXT_DECL(Id, Parent) CONTEXT_DECL(Id, Parent) #include "swift/AST/DeclNodes.def" +// Declare `.asGenericContext` on each BridgedXXXDecl type that's also a +// GenericContext. +#define DECL(Id, Parent) +#define GENERIC_DECL(Id, Parent) \ + SWIFT_NAME("getter:Bridged" #Id "Decl.asGenericContext(self:)") \ + BridgedGenericContext Bridged##Id##Decl_asGenericContext( \ + Bridged##Id##Decl decl); +#define ITERABLE_GENERIC_DECL(Id, Parent) GENERIC_DECL(Id, Parent) +#include "swift/AST/DeclNodes.def" + // Declare `.asStmt` on each BridgedXXXStmt type, which upcasts a wrapper for // a Stmt subclass to a BridgedStmt. #define STMT(Id, Parent) \ @@ -568,6 +604,14 @@ BridgedDeclContext_getParentSourceFile(BridgedDeclContext dc); SWIFT_NAME("getter:BridgedSourceFile.isScriptMode(self:)") BRIDGED_INLINE bool BridgedSourceFile_isScriptMode(BridgedSourceFile sf); +SWIFT_NAME("BridgedSourceFile.addTopLevelDecl(self:_:)") +BRIDGED_INLINE void BridgedSourceFile_addTopLevelDecl(BridgedSourceFile sf, + BridgedDecl decl); + +SWIFT_NAME("BridgedFileUnit.castToSourceFile(self:)") +BRIDGED_INLINE BridgedNullableSourceFile +BridgedFileUnit_castToSourceFile(BridgedFileUnit fileUnit); + SWIFT_NAME("BridgedPatternBindingInitializer.create(declContext:)") BridgedPatternBindingInitializer BridgedPatternBindingInitializer_create(BridgedDeclContext cDeclContext); @@ -1288,6 +1332,9 @@ SWIFT_NAME("BridgedDecl.forEachDeclToHoist(self:_:)") void BridgedDecl_forEachDeclToHoist(BridgedDecl decl, BridgedSwiftClosure closure); +SWIFT_NAME("BridgedDecl.getDeclContext(self:)") +BridgedDeclContext BridgedDecl_getDeclContext(BridgedDecl decl); + enum ENUM_EXTENSIBILITY_ATTR(closed) BridgedStaticSpelling { BridgedStaticSpellingNone, BridgedStaticSpellingStatic, @@ -1335,10 +1382,18 @@ BridgedParamDecl BridgedParamDecl_createParsed( swift::SourceLoc paramNameLoc, BridgedNullableExpr defaultValue, BridgedNullableDefaultArgumentInitializer cDefaultArgumentInitContext); +SWIFT_NAME("BridgedParamDecl.cloneWithoutType(self:)") +BRIDGED_INLINE BridgedParamDecl +BridgedParamDecl_cloneWithoutType(BridgedParamDecl cDecl); + SWIFT_NAME("BridgedParamDecl.setTypeRepr(self:_:)") BRIDGED_INLINE void BridgedParamDecl_setTypeRepr(BridgedParamDecl cDecl, BridgedTypeRepr cType); +SWIFT_NAME("BridgedParamDecl.setInterfaceType(self:_:)") +BRIDGED_INLINE void BridgedParamDecl_setInterfaceType(BridgedParamDecl cDecl, + BridgedASTType cType); + /// The various spellings of ownership modifier that can be used in source. enum ENUM_EXTENSIBILITY_ATTR(closed) BridgedParamSpecifier { BridgedParamSpecifierDefault, @@ -1357,8 +1412,13 @@ BRIDGED_INLINE void BridgedParamDecl_setSpecifier(BridgedParamDecl cDecl, BridgedParamSpecifier cSpecifier); -SWIFT_NAME("BridgedParamDecl.setImplicit(self:)") -BRIDGED_INLINE void BridgedParamDecl_setImplicit(BridgedParamDecl cDecl); +SWIFT_NAME("BridgedDecl.setImplicit(self:)") +BRIDGED_INLINE void BridgedDecl_setImplicit(BridgedDecl cDecl); + +SWIFT_NAME("BridgedGenericContext.setGenericSignature(self:_:)") +BRIDGED_INLINE void +BridgedGenericContext_setGenericSignature(BridgedGenericContext cDecl, + BridgedGenericSignature cGenSig); SWIFT_NAME("BridgedConstructorDecl.setParsedBody(self:_:)") void BridgedConstructorDecl_setParsedBody(BridgedConstructorDecl decl, @@ -1422,7 +1482,7 @@ void BridgedExtensionDecl_setParsedMembers(BridgedExtensionDecl decl, SWIFT_NAME( "BridgedEnumDecl.createParsed(_:declContext:enumKeywordLoc:name:nameLoc:" "genericParamList:inheritedTypes:genericWhereClause:braceRange:)") -BridgedNominalTypeDecl BridgedEnumDecl_createParsed( +BridgedEnumDecl BridgedEnumDecl_createParsed( BridgedASTContext cContext, BridgedDeclContext cDeclContext, swift::SourceLoc enumKeywordLoc, swift::Identifier name, swift::SourceLoc nameLoc, BridgedNullableGenericParamList genericParamList, @@ -1613,6 +1673,10 @@ void BridgedTopLevelCodeDecl_dump(BridgedTopLevelCodeDecl decl); SWIFT_NAME("BridgedDecl.dump(self:)") void BridgedDecl_dump(BridgedDecl decl); +SWIFT_NAME("BridgedValueDecl.setAccess(self:_:)") +void BridgedValueDecl_setAccess(BridgedValueDecl decl, + swift::AccessLevel accessLevel); + //===----------------------------------------------------------------------===// // MARK: AbstractStorageDecl //===----------------------------------------------------------------------===// @@ -1662,6 +1726,11 @@ SWIFT_NAME("BridgedNominalTypeDecl.getSourceLocation(self:)") BRIDGED_INLINE swift::SourceLoc BridgedNominalTypeDecl_getSourceLocation(BridgedNominalTypeDecl decl); +SWIFT_NAME("BridgedNominalTypeDecl.addMember(self:_:)") +BRIDGED_INLINE void +BridgedNominalTypeDecl_addMember(BridgedNominalTypeDecl cDecl, + BridgedDecl member); + //===----------------------------------------------------------------------===// // MARK: SubscriptDecl //===----------------------------------------------------------------------===// @@ -2851,6 +2920,12 @@ BridgedGenericTypeParamDecl BridgedGenericTypeParamDecl_createParsed( swift::SourceLoc nameLoc, BridgedNullableTypeRepr opaqueInheritedType, size_t index, swift::GenericTypeParamKind paramKind); +SWIFT_NAME("BridgedGenericTypeParamDecl.createImplicit(declContext:" + "name:depth:index:paramKind:)") +BridgedGenericTypeParamDecl BridgedGenericTypeParamDecl_createImplicit( + BridgedDeclContext cDeclContext, swift::Identifier name, SwiftUInt depth, + SwiftUInt index, swift::GenericTypeParamKind paramKind); + SWIFT_NAME( "BridgedTrailingWhereClause.createParsed(_:whereKeywordLoc:requirements:)") BridgedTrailingWhereClause @@ -2968,6 +3043,15 @@ struct BridgedASTType { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGenericSignature getInvocationGenericSignatureOfFunctionType() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType subst(BridgedSubstitutionMap substMap) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedConformance checkConformance(BridgedDeclObj proto) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType mapTypeOutOfContext() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedCanType + getReducedType(BridgedGenericSignature sig) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE swift::Identifier + GenericTypeParam_getName() const; + BRIDGED_INLINE SwiftUInt GenericTypeParam_getDepth() const; + BRIDGED_INLINE SwiftUInt GenericTypeParam_getIndex() const; + BRIDGED_INLINE swift::GenericTypeParamKind + GenericTypeParam_getParamKind() const; }; class BridgedCanType { @@ -2978,6 +3062,8 @@ class BridgedCanType { BRIDGED_INLINE BridgedCanType(swift::CanType ty); BRIDGED_INLINE swift::CanType unbridged() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType getRawType() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedCanGenericSignature + SILFunctionType_getSubstGenericSignature() const; }; struct BridgedASTTypeArray { @@ -3042,6 +3128,14 @@ struct BridgedGenericSignature { BridgedOwnedString getDebugDescription() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTTypeArray getGenericParams() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType mapTypeIntoContext(BridgedASTType type) const; + BRIDGED_INLINE BridgedCanGenericSignature getCanonicalSignature() const; +}; + +struct BridgedCanGenericSignature { + const swift::GenericSignatureImpl *_Nullable impl; + + BRIDGED_INLINE swift::CanGenericSignature unbridged() const; + BRIDGED_INLINE BridgedGenericSignature getGenericSignature() const; }; struct BridgedFingerprint { diff --git a/include/swift/AST/ASTBridgingImpl.h b/include/swift/AST/ASTBridgingImpl.h index b71a98e3b140d..e3b4c4a78e69c 100644 --- a/include/swift/AST/ASTBridgingImpl.h +++ b/include/swift/AST/ASTBridgingImpl.h @@ -148,6 +148,17 @@ bool BridgedSourceFile_isScriptMode(BridgedSourceFile sf) { return sf.unbridged()->isScriptMode(); } +void BridgedSourceFile_addTopLevelDecl(BridgedSourceFile sf, BridgedDecl decl) { + auto &file = sf.unbridged()->getOrCreateSynthesizedFile(); + file.addTopLevelDecl(decl.unbridged()); + file.getParentModule()->clearLookupCache(); +} + +BridgedNullableSourceFile +BridgedFileUnit_castToSourceFile(BridgedFileUnit fileUnit) { + return llvm::dyn_cast(fileUnit.unbridged()); +} + //===----------------------------------------------------------------------===// // MARK: BridgedDeclObj //===----------------------------------------------------------------------===// @@ -176,6 +187,10 @@ swift::SourceLoc BridgedDeclObj::Value_getNameLoc() const { return getAs()->getNameLoc(); } +swift::Identifier BridgedDeclObj::Value_getBaseIdentifier() const { + return getAs()->getBaseIdentifier(); +} + bool BridgedDeclObj::hasClangNode() const { return unbridged()->hasClangNode(); } @@ -234,6 +249,19 @@ bool BridgedDeclObj::EnumElementDecl_hasAssociatedValues() const { return getAs()->hasAssociatedValues(); } +BridgedParameterList BridgedDeclObj::EnumElementDecl_getParameterList() const { + return getAs()->getParameterList(); +} + +BridgedStringRef BridgedDeclObj::EnumElementDecl_getNameStr() const { + return getAs()->getNameStr(); +} + +BridgedASTType BridgedDeclObj::NominalType_getDeclaredInterfaceType() const { + return { + getAs()->getDeclaredInterfaceType().getPointer()}; +} + //===----------------------------------------------------------------------===// // MARK: BridgedASTNode //===----------------------------------------------------------------------===// @@ -337,20 +365,44 @@ swift::ParamSpecifier unbridge(BridgedParamSpecifier specifier) { } } +BridgedParamDecl BridgedParamDecl_cloneWithoutType(BridgedParamDecl cDecl) { + return swift::ParamDecl::cloneWithoutType(cDecl.unbridged()->getASTContext(), + cDecl.unbridged()); +} + void BridgedParamDecl_setTypeRepr(BridgedParamDecl cDecl, BridgedTypeRepr cType) { cDecl.unbridged()->setTypeRepr(cType.unbridged()); } +void BridgedParamDecl_setInterfaceType(BridgedParamDecl cDecl, + BridgedASTType cType) { + cDecl.unbridged()->setInterfaceType(cType.unbridged()); +} + void BridgedParamDecl_setSpecifier(BridgedParamDecl cDecl, BridgedParamSpecifier cSpecifier) { cDecl.unbridged()->setSpecifier(unbridge(cSpecifier)); } -void BridgedParamDecl_setImplicit(BridgedParamDecl cDecl) { +void BridgedDecl_setImplicit(BridgedDecl cDecl) { cDecl.unbridged()->setImplicit(); } +void BridgedGenericContext_setGenericSignature( + BridgedGenericContext cDecl, BridgedGenericSignature cGenSig) { + cDecl.unbridged()->setGenericSignature(cGenSig.unbridged()); +} + +//===----------------------------------------------------------------------===// +// MARK: BridgedNominalTypeDecl +//===----------------------------------------------------------------------===// + +void BridgedNominalTypeDecl_addMember(BridgedNominalTypeDecl cDecl, + BridgedDecl member) { + cDecl.unbridged()->addMember(member.unbridged()); +} + //===----------------------------------------------------------------------===// // MARK: BridgedSubscriptDecl //===----------------------------------------------------------------------===// @@ -618,6 +670,32 @@ BridgedConformance BridgedASTType::checkConformance(BridgedDeclObj proto) const return swift::checkConformance(unbridged(), proto.getAs(), /*allowMissing=*/ false); } +BridgedASTType BridgedASTType::mapTypeOutOfContext() const { + return {unbridged()->mapTypeOutOfContext().getPointer()}; +} + +BridgedCanType +BridgedASTType::getReducedType(BridgedGenericSignature sig) const { + return {unbridged()->getReducedType(sig.unbridged())}; +} + +swift::Identifier BridgedASTType::GenericTypeParam_getName() const { + return llvm::cast(type)->getName(); +} + +SwiftUInt BridgedASTType::GenericTypeParam_getDepth() const { + return llvm::cast(type)->getDepth(); +} + +SwiftUInt BridgedASTType::GenericTypeParam_getIndex() const { + return llvm::cast(type)->getIndex(); +} + +swift::GenericTypeParamKind +BridgedASTType::GenericTypeParam_getParamKind() const { + return llvm::cast(type)->getParamKind(); +} + static_assert((int)BridgedASTType::TraitResult::IsNot == (int)swift::TypeTraitResult::IsNot); static_assert((int)BridgedASTType::TraitResult::CanBe == (int)swift::TypeTraitResult::CanBe); static_assert((int)BridgedASTType::TraitResult::Is == (int)swift::TypeTraitResult::Is); @@ -644,6 +722,13 @@ BridgedASTType BridgedCanType::getRawType() const { return {type}; } +BridgedCanGenericSignature +BridgedCanType::SILFunctionType_getSubstGenericSignature() const { + return {swift::CanSILFunctionType(llvm::cast(type)) + ->getSubstGenericSignature() + .getPointer()}; +} + //===----------------------------------------------------------------------===// // MARK: BridgedASTTypeArray //===----------------------------------------------------------------------===// @@ -835,6 +920,20 @@ BridgedASTType BridgedGenericSignature::mapTypeIntoContext(BridgedASTType type) return {unbridged().getGenericEnvironment()->mapTypeIntoContext(type.unbridged()).getPointer()}; } +BridgedCanGenericSignature +BridgedGenericSignature::getCanonicalSignature() const { + return BridgedCanGenericSignature{impl}; +} + +swift::CanGenericSignature BridgedCanGenericSignature::unbridged() const { + return swift::GenericSignature(impl).getCanonicalSignature(); +} + +BridgedGenericSignature +BridgedCanGenericSignature::getGenericSignature() const { + return BridgedGenericSignature{impl}; +} + //===----------------------------------------------------------------------===// // MARK: BridgedFingerprint //===----------------------------------------------------------------------===// diff --git a/include/swift/AST/ASTBridgingWrappers.def b/include/swift/AST/ASTBridgingWrappers.def index 19af5d314740c..619f70fb033ed 100644 --- a/include/swift/AST/ASTBridgingWrappers.def +++ b/include/swift/AST/ASTBridgingWrappers.def @@ -95,7 +95,9 @@ // optional parameters. AST_BRIDGING_WRAPPER_NULLABLE(Decl) AST_BRIDGING_WRAPPER_NONNULL(DeclContext) -AST_BRIDGING_WRAPPER_NONNULL(SourceFile) +AST_BRIDGING_WRAPPER_NONNULL(GenericContext) +AST_BRIDGING_WRAPPER_NONNULL(FileUnit) +AST_BRIDGING_WRAPPER_NULLABLE(SourceFile) AST_BRIDGING_WRAPPER_NULLABLE(Stmt) AST_BRIDGING_WRAPPER_NULLABLE(Expr) AST_BRIDGING_WRAPPER_NULLABLE(Pattern) diff --git a/include/swift/SIL/SILBridging.h b/include/swift/SIL/SILBridging.h index 4384c1132fcff..77a2a7613d13e 100644 --- a/include/swift/SIL/SILBridging.h +++ b/include/swift/SIL/SILBridging.h @@ -251,6 +251,7 @@ BridgedYieldInfoArray SILFunctionType_getYields(BridgedCanType); SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLifetimeDependenceInfoArray SILFunctionType_getLifetimeDependencies(BridgedCanType); +enum class BridgedValueCategory { Address, Object }; struct BridgedType { void * _Nullable opaqueValue; @@ -270,6 +271,7 @@ struct BridgedType { BRIDGED_INLINE BridgedOwnedString getDebugDescription() const; BRIDGED_INLINE bool isNull() const; BRIDGED_INLINE bool isAddress() const; + BRIDGED_INLINE BridgedValueCategory getCategory() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getAddressType() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getObjectType() const; BRIDGED_INLINE bool isTrivial(BridgedFunction f) const; @@ -283,6 +285,8 @@ struct BridgedType { BRIDGED_INLINE bool isExactSuperclassOf(BridgedType t) const; BRIDGED_INLINE bool isMarkedAsImmortal() const; BRIDGED_INLINE bool isAddressableForDeps(BridgedFunction f) const; + SWIFT_IMPORT_UNSAFE bool + isAutodiffBranchTracingEnumInVJP(BridgedFunction vjp) const; BRIDGED_INLINE SWIFT_IMPORT_UNSAFE BridgedASTType getRawLayoutSubstitutedLikeType() const; BRIDGED_INLINE SWIFT_IMPORT_UNSAFE BridgedASTType getRawLayoutSubstitutedCountType() const; BRIDGED_INLINE SwiftInt getCaseIdxOfEnumType(BridgedStringRef name) const; @@ -297,13 +301,24 @@ struct BridgedType { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE EnumElementIterator getFirstEnumCaseIterator() const; BRIDGED_INLINE bool isEndCaseIterator(EnumElementIterator i) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getEnumCasePayload(EnumElementIterator i, BridgedFunction f) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType + getEnumCasePayload(SwiftInt caseIndex, BridgedFunction f) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclObj + getEnumElementDecl(EnumElementIterator i) const; BRIDGED_INLINE SwiftInt getNumTupleElements() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getTupleElementType(SwiftInt idx) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE swift::Identifier + getTupleElementLabel(SwiftInt idx) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getFunctionTypeWithNoEscape(bool withNoEscape) const; BRIDGED_INLINE BridgedArgumentConvention getCalleeConvention() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType mapTypeOutOfContext() const; }; +SWIFT_NAME("BridgedType.getPrimitiveType(canType:silValueCategory:)") +BRIDGED_INLINE BridgedType BridgedType_getPrimitiveType( + BridgedCanType canType, BridgedValueCategory silValueCategory); + // SIL Bridging struct BridgedValue { @@ -508,6 +523,9 @@ struct BridgedFunction { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getName() const; BridgedOwnedString getDebugDescription() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLocation getLocation() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNullableSourceFile + getSourceFile() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArrayRef getFilesForModule() const; BRIDGED_INLINE bool isAccessor() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getAccessorName() const; BRIDGED_INLINE bool hasOwnership() const; @@ -517,6 +535,8 @@ struct BridgedFunction { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGenericSignature getGenericSignature() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap getForwardingSubstitutionMap() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType mapTypeIntoContext(BridgedASTType ty) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType + mapTypeIntoContext(BridgedType ty) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getFirstBlock() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getLastBlock() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclRef getDeclRef() const; @@ -553,6 +573,8 @@ struct BridgedFunction { BRIDGED_INLINE void setIsPerformanceConstraint(bool isPerfConstraint) const; BRIDGED_INLINE bool isResilientNominalDecl(BridgedDeclObj decl) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getLoweredType(BridgedASTType type, bool maximallyAbstracted) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType + getLoweredType(BridgedCanType type) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getLoweredType(BridgedType type) const; BRIDGED_INLINE BridgedLinkage getLinkage() const; BRIDGED_INLINE void setLinkage(BridgedLinkage linkage) const; @@ -810,6 +832,8 @@ struct BridgedInstruction { BRIDGED_INLINE void RefElementAddrInst_setImmutable(bool isImmutable) const; BRIDGED_INLINE bool RefTailAddrInst_isImmutable() const; BRIDGED_INLINE SwiftInt PartialApplyInst_numArguments() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap + PartialApplyInst_getSubstitutionMap() const; BRIDGED_INLINE SwiftInt ApplyInst_numArguments() const; BRIDGED_INLINE bool ApplyInst_getNonThrowing() const; BRIDGED_INLINE bool ApplyInst_getNonAsync() const; @@ -842,6 +866,8 @@ struct BridgedInstruction { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock BranchInst_getTargetBlock() const; BRIDGED_INLINE SwiftInt SwitchEnumInst_getNumCases() const; BRIDGED_INLINE SwiftInt SwitchEnumInst_getCaseIndex(SwiftInt idx) const; + BRIDGED_INLINE OptionalBridgedBasicBlock + SwitchEnumInst_getSuccessorForDefault() const; BRIDGED_INLINE SwiftInt StoreInst_getStoreOwnership() const; BRIDGED_INLINE SwiftInt AssignInst_getAssignOwnership() const; BRIDGED_INLINE MarkDependenceKind MarkDependenceInst_dependenceKind() const; @@ -956,6 +982,8 @@ struct BridgedArgument { BRIDGED_INLINE void setReborrow(bool reborrow) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedDeclObj getDecl() const; BRIDGED_INLINE void copyFlags(BridgedArgument fromArgument) const; + BRIDGED_INLINE BridgedValue::Ownership getOwnership() const; + BRIDGED_INLINE void replaceAllUsesWith(BridgedArgument arg) const; }; struct OptionalBridgedArgument { @@ -988,6 +1016,9 @@ struct BridgedBasicBlock { BRIDGED_INLINE SwiftInt getNumArguments() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArgument getArgument(SwiftInt index) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArgument addBlockArgument(BridgedType type, BridgedValue::Ownership ownership) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArgument + insertPhiArgument(SwiftInt index, BridgedType type, + BridgedValue::Ownership ownership) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArgument addFunctionArgument(BridgedType type) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArgument insertFunctionArgument(SwiftInt atPosition, BridgedType type, BridgedValue::Ownership ownership, @@ -1337,6 +1368,8 @@ struct BridgedBuilder{ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestructureStruct(BridgedValue str) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTuple(BridgedType type, BridgedValueArray elements) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction + createTuple(BridgedValueArray elements) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTupleExtract(BridgedValue str, SwiftInt elementIndex) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTupleElementAddr(BridgedValue addr, @@ -1451,6 +1484,8 @@ struct BridgedContext { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap getContextSubstitutionMap(BridgedType type) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getBuiltinIntegerType(SwiftInt bitWidth) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType getTupleType(BridgedArrayRef elementTypes) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType getTupleTypeWithLabels( + BridgedArrayRef elementTypes, BridgedArrayRef labels) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclObj getSwiftArrayDecl() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclObj getSwiftMutableSpanDecl() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue getSILUndef(BridgedType type) const; diff --git a/include/swift/SIL/SILBridgingImpl.h b/include/swift/SIL/SILBridgingImpl.h index e5c031d7fbf45..69d4a3bf71a0d 100644 --- a/include/swift/SIL/SILBridgingImpl.h +++ b/include/swift/SIL/SILBridgingImpl.h @@ -321,6 +321,19 @@ bool BridgedType::isAddress() const { return unbridged().isAddress(); } +static inline BridgedValueCategory bridge(swift::SILValueCategory category) { + switch (category) { + case swift::SILValueCategory::Address: + return BridgedValueCategory::Address; + case swift::SILValueCategory::Object: + return BridgedValueCategory::Object; + } +} + +BridgedValueCategory BridgedType::getCategory() const { + return bridge(unbridged().getCategory()); +} + BridgedCanType BridgedType::getCanType() const { return unbridged().getASTType(); } @@ -437,6 +450,19 @@ BridgedType BridgedType::getEnumCasePayload(EnumElementIterator i, BridgedFuncti return swift::SILType(); } +BridgedDeclObj BridgedType::getEnumElementDecl(EnumElementIterator i) const { + swift::EnumElementDecl *elt = *unbridge(i); + return {elt}; +} + +BridgedType BridgedType::getEnumCasePayload(SwiftInt caseIndex, + BridgedFunction f) const { + swift::EnumElementDecl *elt = unbridged().getEnumElement(caseIndex); + if (elt->hasAssociatedValues()) + return unbridged().getEnumElementType(elt, f.getFunction()); + return swift::SILType(); +} + SwiftInt BridgedType::getNumTupleElements() const { return unbridged().getNumTupleElements(); } @@ -445,6 +471,12 @@ BridgedType BridgedType::getTupleElementType(SwiftInt idx) const { return unbridged().getTupleElementType(idx); } +swift::Identifier BridgedType::getTupleElementLabel(SwiftInt idx) const { + return llvm::cast(unbridged().getASTType().getPointer()) + ->getElement(idx) + .getName(); +} + BridgedType BridgedType::getFunctionTypeWithNoEscape(bool withNoEscape) const { auto fnType = unbridged().getAs(); auto newTy = fnType->getWithExtInfo(fnType->getExtInfo().withNoEscape(true)); @@ -456,6 +488,26 @@ BridgedArgumentConvention BridgedType::getCalleeConvention() const { return getArgumentConvention(fnType->getCalleeConvention()); } +BridgedType BridgedType::mapTypeOutOfContext() const { + return unbridged().mapTypeOutOfContext(); +} + +static inline swift::SILValueCategory unbridge(BridgedValueCategory category) { + switch (category) { + case BridgedValueCategory::Address: + return swift::SILValueCategory::Address; + case BridgedValueCategory::Object: + return swift::SILValueCategory::Object; + } +} + +BridgedType +BridgedType_getPrimitiveType(BridgedCanType canType, + BridgedValueCategory silValueCategory) { + return swift::SILType::getPrimitiveType(canType.unbridged(), + unbridge(silValueCategory)); +} + //===----------------------------------------------------------------------===// // BridgedValue //===----------------------------------------------------------------------===// @@ -611,6 +663,15 @@ void BridgedArgument::copyFlags(BridgedArgument fromArgument) const { fArg->copyFlags(static_cast(fromArgument.getArgument())); } +BridgedValue::Ownership BridgedArgument::getOwnership() const { + swift::ValueBase *val = getArgument(); + return BridgedValue{SwiftObject{val}}.getOwnership(); +} + +void BridgedArgument::replaceAllUsesWith(BridgedArgument arg) const { + getArgument()->replaceAllUsesWith(arg.getArgument()); +} + swift::SILArgument * _Nullable OptionalBridgedArgument::unbridged() const { if (!obj) return nullptr; @@ -689,6 +750,14 @@ BridgedLocation BridgedFunction::getLocation() const { return {swift::SILDebugLocation(getFunction()->getLocation(), getFunction()->getDebugScope())}; } +BridgedNullableSourceFile BridgedFunction::getSourceFile() const { + return {getFunction()->getSourceFile()}; +} + +BridgedArrayRef BridgedFunction::getFilesForModule() const { + return getFunction()->getModule().getSwiftModule()->getFiles(); +} + bool BridgedFunction::isAccessor() const { if (auto *valDecl = getFunction()->getDeclRef().getDecl()) { return llvm::isa(valDecl); @@ -725,6 +794,10 @@ BridgedASTType BridgedFunction::mapTypeIntoContext(BridgedASTType ty) const { return {getFunction()->mapTypeIntoContext(ty.unbridged()).getPointer()}; } +BridgedType BridgedFunction::mapTypeIntoContext(BridgedType ty) const { + return {getFunction()->mapTypeIntoContext(ty.unbridged())}; +} + OptionalBridgedBasicBlock BridgedFunction::getFirstBlock() const { return {getFunction()->empty() ? nullptr : getFunction()->getEntryBlock()}; } @@ -904,6 +977,14 @@ BridgedType BridgedFunction::getLoweredType(BridgedASTType type, bool maximallyA return BridgedType(getFunction()->getLoweredType(type.type)); } +BridgedType BridgedFunction::getLoweredType(BridgedCanType type) const { + swift::Lowering::AbstractionPattern pattern( + getFunction()->getLoweredFunctionType()->getSubstGenericSignature(), + type.unbridged()); + return getFunction()->getModule().Types.getLoweredType( + pattern, type.unbridged(), swift::TypeExpansionContext::minimal()); +} + BridgedType BridgedFunction::getLoweredType(BridgedType type) const { return BridgedType(getFunction()->getLoweredType(type.unbridged())); } @@ -1079,6 +1160,12 @@ bool BridgedInstruction::isIdenticalTo(BridgedInstruction inst) const { return unbridged()->isIdenticalTo(inst.unbridged()); } +BridgedSubstitutionMap +BridgedInstruction::PartialApplyInst_getSubstitutionMap() const { + auto *pai = llvm::cast(unbridged()); + return {pai->getSubstitutionMap()}; +} + SwiftInt BridgedInstruction::MultipleValueInstruction_getNumResults() const { return getAs()->getNumResults(); } @@ -1455,6 +1542,14 @@ SwiftInt BridgedInstruction::SwitchEnumInst_getCaseIndex(SwiftInt idx) const { return seInst->getModule().getCaseIndex(seInst->getCase(idx).first); } +OptionalBridgedBasicBlock +BridgedInstruction::SwitchEnumInst_getSuccessorForDefault() const { + auto *seInst = getAs(); + if (seInst->hasDefault()) + return {seInst->getDefaultBB()}; + return {nullptr}; +} + SwiftInt BridgedInstruction::StoreInst_getStoreOwnership() const { return (SwiftInt)getAs()->getOwnershipQualifier(); } @@ -1873,6 +1968,13 @@ BridgedArgument BridgedBasicBlock::addBlockArgument(BridgedType type, BridgedVal type.unbridged(), BridgedValue::unbridge(ownership))}; } +BridgedArgument +BridgedBasicBlock::insertPhiArgument(SwiftInt index, BridgedType type, + BridgedValue::Ownership ownership) const { + return {unbridged()->insertPhiArgument(index, type.unbridged(), + BridgedValue::unbridge(ownership))}; +} + BridgedArgument BridgedBasicBlock::addFunctionArgument(BridgedType type) const { return {unbridged()->createFunctionArgument(type.unbridged())}; } @@ -2629,6 +2731,23 @@ BridgedInstruction BridgedBuilder::createTuple(BridgedType type, BridgedValueArr elements.getValues(elementValues))}; } +BridgedInstruction +BridgedBuilder::createTuple(BridgedValueArray elements) const { + llvm::SmallVector elementValues; + llvm::ArrayRef values = elements.getValues(elementValues); + llvm::SmallVector tupleTyElts; + tupleTyElts.reserve(values.size()); + for (const swift::SILValue &value : values) { + tupleTyElts.emplace_back(value->getType().getASTType()); + } + swift::Type tupleTy = + swift::TupleType::get(tupleTyElts, unbridged().getASTContext()); + swift::SILType silTupleTy = + swift::SILType::getPrimitiveObjectType(tupleTy->getCanonicalType()); + + return {unbridged().createTuple(regularLoc(), silTupleTy, values)}; +} + BridgedInstruction BridgedBuilder::createTupleExtract(BridgedValue str, SwiftInt elementIndex) const { swift::SILValue v = str.getSILValue(); return {unbridged().createTupleExtract(regularLoc(), v, elementIndex)}; @@ -2893,6 +3012,24 @@ BridgedASTType BridgedContext::getTupleType(BridgedArrayRef elementTypes) const return {swift::TupleType::get(elements, context->getModule()->getASTContext())}; } +BridgedASTType +BridgedContext::getTupleTypeWithLabels(BridgedArrayRef elementTypes, + BridgedArrayRef labels) const { + assert(elementTypes.getCount() == labels.getCount()); + llvm::SmallVector elements; + elements.reserve(elementTypes.getCount()); + llvm::ArrayRef elementTypesArr = + elementTypes.unbridged(); + llvm::ArrayRef labelsArr = + labels.unbridged(); + for (const auto &[bridgedElmtTy, label] : + llvm::zip_equal(elementTypesArr, labelsArr)) { + elements.emplace_back(bridgedElmtTy.unbridged(), label); + } + return { + swift::TupleType::get(elements, context->getModule()->getASTContext())}; +} + BridgedDeclObj BridgedContext::getSwiftArrayDecl() const { return {context->getModule()->getASTContext().getArrayDecl()}; } diff --git a/lib/AST/Bridging/DeclBridging.cpp b/lib/AST/Bridging/DeclBridging.cpp index d826d6d4c9536..e7f3bc4235ccf 100644 --- a/lib/AST/Bridging/DeclBridging.cpp +++ b/lib/AST/Bridging/DeclBridging.cpp @@ -90,6 +90,25 @@ BridgedDeclNameLoc BridgedDeclNameLoc_createParsed(BridgedASTContext cContext, #define ABSTRACT_DECL(Id, Parent) DECL(Id, Parent) #include "swift/AST/DeclNodes.def" +// Define `.asValueDecl` on each BridgedXXXDecl type that's also a +// ValueDecl. +#define DECL(Id, Parent) +#define VALUE_DECL(Id, Parent) \ + BridgedValueDecl Bridged##Id##Decl_asValueDecl(Bridged##Id##Decl decl) { \ + return static_cast(decl.unbridged()); \ + } +#include "swift/AST/DeclNodes.def" + +// Define `.asNominalTypeDecl` on each BridgedXXXDecl type that's also a +// NominalTypeDecl. +#define DECL(Id, Parent) +#define NOMINAL_TYPE_DECL(Id, Parent) \ + BridgedNominalTypeDecl Bridged##Id##Decl_asNominalTypeDecl( \ + Bridged##Id##Decl decl) { \ + return static_cast(decl.unbridged()); \ + } +#include "swift/AST/DeclNodes.def" + // Define `.asDeclContext` on each BridgedXXXDecl type that's also a // DeclContext. #define DECL(Id, Parent) @@ -100,6 +119,17 @@ BridgedDeclNameLoc BridgedDeclNameLoc_createParsed(BridgedASTContext cContext, #define ABSTRACT_CONTEXT_DECL(Id, Parent) CONTEXT_DECL(Id, Parent) #include "swift/AST/DeclNodes.def" +// Define `.asGenericContext` on each BridgedXXXDecl type that's also a +// GenericContext. +#define DECL(Id, Parent) +#define GENERIC_DECL(Id, Parent) \ + BridgedGenericContext Bridged##Id##Decl_asGenericContext( \ + Bridged##Id##Decl decl) { \ + return static_cast(decl.unbridged()); \ + } +#define ITERABLE_GENERIC_DECL(Id, Parent) GENERIC_DECL(Id, Parent) +#include "swift/AST/DeclNodes.def" + static StaticSpellingKind unbridged(BridgedStaticSpelling kind) { return static_cast(kind); } @@ -117,6 +147,15 @@ void BridgedDecl_forEachDeclToHoist(BridgedDecl cDecl, }); } +BridgedDeclContext BridgedDecl_getDeclContext(BridgedDecl decl) { + return decl.unbridged()->getDeclContext(); +} + +void BridgedValueDecl_setAccess(BridgedValueDecl decl, + swift::AccessLevel accessLevel) { + decl.unbridged()->setAccess(accessLevel); +} + BridgedAccessorDecl BridgedAccessorDecl_createParsed( BridgedASTContext cContext, BridgedDeclContext cDeclContext, swift::AccessorKind Kind, BridgedAbstractStorageDecl cStorage, @@ -334,7 +373,7 @@ convertToInheritedEntries(ASTContext &ctx, BridgedArrayRef cInheritedTypes) { [](auto &e) { return InheritedEntry(e.unbridged()); }); } -BridgedNominalTypeDecl BridgedEnumDecl_createParsed( +BridgedEnumDecl BridgedEnumDecl_createParsed( BridgedASTContext cContext, BridgedDeclContext cDeclContext, SourceLoc enumKeywordLoc, swift::Identifier name, SourceLoc nameLoc, BridgedNullableGenericParamList genericParamList, @@ -343,7 +382,7 @@ BridgedNominalTypeDecl BridgedEnumDecl_createParsed( SourceRange braceRange) { ASTContext &context = cContext.unbridged(); - NominalTypeDecl *decl = new (context) + auto *decl = new (context) EnumDecl(enumKeywordLoc, name, nameLoc, convertToInheritedEntries(context, cInheritedTypes), genericParamList.unbridged(), cDeclContext.unbridged()); diff --git a/lib/AST/Bridging/GenericsBridging.cpp b/lib/AST/Bridging/GenericsBridging.cpp index 15766836fd79e..92cd54a67ca86 100644 --- a/lib/AST/Bridging/GenericsBridging.cpp +++ b/lib/AST/Bridging/GenericsBridging.cpp @@ -59,6 +59,15 @@ BridgedGenericTypeParamDecl BridgedGenericTypeParamDecl_createParsed( return decl; } +BridgedGenericTypeParamDecl BridgedGenericTypeParamDecl_createImplicit( + BridgedDeclContext cDeclContext, swift::Identifier name, SwiftUInt depth, + SwiftUInt index, swift::GenericTypeParamKind paramKind) { + auto *param = GenericTypeParamDecl::createImplicit( + cDeclContext.unbridged(), name, depth, index, paramKind); + param->setDeclContext(cDeclContext.unbridged()); + return param; +} + BridgedTrailingWhereClause BridgedTrailingWhereClause_createParsed(BridgedASTContext cContext, SourceLoc whereKeywordLoc, diff --git a/lib/ASTGen/Sources/ASTGen/Decls.swift b/lib/ASTGen/Sources/ASTGen/Decls.swift index 900eb1ab440be..9d7dad619e76c 100644 --- a/lib/ASTGen/Sources/ASTGen/Decls.swift +++ b/lib/ASTGen/Sources/ASTGen/Decls.swift @@ -109,7 +109,7 @@ extension ASTGenVisitor { return decl } - func generate(enumDecl node: EnumDeclSyntax) -> BridgedNominalTypeDecl? { + func generate(enumDecl node: EnumDeclSyntax) -> BridgedEnumDecl? { let attrs = self.generateDeclAttributes(node, allowStatic: false) guard let (name, nameLoc) = self.generateIdentifierDeclNameAndLoc(node.name) else { return nil @@ -135,7 +135,7 @@ extension ASTGenVisitor { self.generate(memberBlockItemList: node.memberBlock.members) } let fp = self.generateFingerprint(declGroup: node) - decl.setParsedMembers( + decl.asNominalTypeDecl.setParsedMembers( members.lazy.bridgedArray(in: self), fingerprint: fp.bridged ) diff --git a/lib/ASTGen/Sources/ASTGen/Exprs.swift b/lib/ASTGen/Sources/ASTGen/Exprs.swift index c30c23e06fc50..0537dc2443138 100644 --- a/lib/ASTGen/Sources/ASTGen/Exprs.swift +++ b/lib/ASTGen/Sources/ASTGen/Exprs.swift @@ -370,7 +370,7 @@ extension ASTGenVisitor { defaultValueInitContext: nil ) param.setSpecifier(.default) - param.setImplicit() + param.asDecl.setImplicit() params.append(param) } } From 02fcd218d7bac9247a89c23ab0a5e981a44cec88 Mon Sep 17 00:00:00 2001 From: Daniil Kovalev Date: Thu, 9 Oct 2025 21:52:22 +0300 Subject: [PATCH 2/7] Address review comments --- .../Sources/AST/Declarations.swift | 161 +++++++++++++++++- .../Sources/AST/GenericSignature.swift | 10 +- SwiftCompilerSources/Sources/AST/Type.swift | 34 ++-- .../Sources/Basic/SourceLoc.swift | 8 + .../Sources/SIL/Argument.swift | 4 - .../Sources/SIL/BasicBlock.swift | 4 +- .../Sources/SIL/Builder.swift | 7 - .../Sources/SIL/Context.swift | 14 +- .../Sources/SIL/Function.swift | 4 +- .../Sources/SIL/Instruction.swift | 4 +- SwiftCompilerSources/Sources/SIL/Type.swift | 29 ++-- SwiftCompilerSources/Sources/SIL/Value.swift | 21 --- include/swift/AST/ASTBridging.h | 12 +- include/swift/AST/ASTBridgingImpl.h | 4 +- include/swift/SIL/SILBridging.h | 12 +- include/swift/SIL/SILBridgingImpl.h | 54 +----- lib/AST/Bridging/GenericsBridging.cpp | 4 +- 17 files changed, 234 insertions(+), 152 deletions(-) diff --git a/SwiftCompilerSources/Sources/AST/Declarations.swift b/SwiftCompilerSources/Sources/AST/Declarations.swift index 6724cf2f16448..1b0fad1008068 100644 --- a/SwiftCompilerSources/Sources/AST/Declarations.swift +++ b/SwiftCompilerSources/Sources/AST/Declarations.swift @@ -29,6 +29,10 @@ public class Decl: CustomStringConvertible, Hashable { // True if this declaration is imported from C/C++/ObjC. public var hasClangNode: Bool { bridged.hasClangNode() } + public var declContext: DeclContext { bridgedDecl.declContext } + + var bridgedDecl: BridgedDecl { BridgedDecl(raw: bridged.obj) } + public static func ==(lhs: Decl, rhs: Decl) -> Bool { lhs === rhs } public func hash(into hasher: inout Hasher) { @@ -39,7 +43,7 @@ public class Decl: CustomStringConvertible, Hashable { public class ValueDecl: Decl { final public var nameLoc: SourceLoc? { SourceLoc(bridged: bridged.Value_getNameLoc()) } final public var userFacingName: StringRef { StringRef(bridged: bridged.Value_getUserFacingName()) } - final public var baseIdentifier: swift.Identifier { bridged.Value_getBaseIdentifier() } + final public var baseIdentifier: Identifier { bridged.Value_getBaseIdentifier() } final public var isObjC: Bool { bridged.Value_isObjC() } } @@ -58,8 +62,8 @@ public class NominalTypeDecl: GenericTypeDecl { bridged.NominalType_getValueTypeDestructor().getAs(DestructorDecl.self) } - public var declaredInterfaceType : AST.`Type` { - AST.`Type`(bridged: bridged.NominalType_getDeclaredInterfaceType()) + public var declaredInterfaceType: Type { + Type(bridged: bridged.NominalType_getDeclaredInterfaceType()) } } @@ -123,8 +127,8 @@ final public class MacroDecl: ValueDecl {} final public class EnumElementDecl: ValueDecl { public var hasAssociatedValues: Bool { bridged.EnumElementDecl_hasAssociatedValues() } - public var parameterList: BridgedParameterList { bridged.EnumElementDecl_getParameterList() } - public var nameStr: StringRef { StringRef(bridged: bridged.EnumElementDecl_getNameStr()) } + public var parameterList: ParameterList { bridged.EnumElementDecl_getParameterList() } + public var name: StringRef { StringRef(bridged: bridged.EnumElementDecl_getNameStr()) } } final public class ExtensionDecl: Decl {} @@ -172,3 +176,150 @@ extension Optional where Wrapped == Decl { OptionalBridgedDeclObj(self?.bridged.obj) } } + +public typealias Identifier = swift.Identifier + +public typealias GenericTypeParamKind = swift.GenericTypeParamKind + +public typealias ASTContext = BridgedASTContext + +public typealias DeclContext = BridgedDeclContext + +public typealias Expr = BridgedExpr + +public typealias ParameterList = BridgedParameterList + +public typealias SourceFile = BridgedSourceFile + +public typealias FileUnit = BridgedFileUnit + +public typealias GenericParamList = BridgedGenericParamList + +public typealias TrailingWhereClause = BridgedTrailingWhereClause + +public typealias BridgedParamDecl = ASTBridging.BridgedParamDecl + +public typealias BridgedGenericTypeParamDecl = ASTBridging.BridgedGenericTypeParamDecl + +public typealias BridgedEnumDecl = ASTBridging.BridgedEnumDecl + +public typealias BridgedEnumElementDecl = ASTBridging.BridgedEnumElementDecl + +extension ParameterList { + public subscript(_ index: Int) -> BridgedParamDecl { + return get(index) + } + + public static func createParsed( + _ astContext: ASTContext, leftParenLoc: SourceLoc?, parameters: [BridgedParamDecl], + rightParenLoc: SourceLoc? + ) -> ParameterList { + parameters.withBridgedArrayRef { + ParameterList.createParsed( + astContext, leftParenLoc: leftParenLoc.bridgedLocation, parameters: $0, + rightParenLoc: rightParenLoc.bridgedLocation) + } + } +} + +extension GenericParamList { + public static func createParsed( + _ astContext: ASTContext, leftAngleLoc: SourceLoc?, parameters: [BridgedGenericTypeParamDecl], + genericWhereClause: TrailingWhereClause?, + rightAngleLoc: SourceLoc? + ) -> GenericParamList { + return parameters.withBridgedArrayRef { + GenericParamList.createParsed( + astContext, leftAngleLoc: leftAngleLoc.bridgedLocation, parameters: $0, + genericWhereClause: genericWhereClause.bridged, rightAngleLoc: rightAngleLoc.bridgedLocation + ) + } + } +} + +extension BridgedDecl { + public var declObj: BridgedDeclObj { + BridgedDeclObj(SwiftObject(raw.bindMemory(to: BridgedSwiftObject.self, capacity: 1))) + } + public var decl: Decl { declObj.decl } +} + +extension BridgedEnumDecl { + public static func createParsed( + _ astContext: ASTContext, declContext: DeclContext, enumKeywordLoc: SourceLoc?, name: String, + nameLoc: SourceLoc?, genericParamList: GenericParamList?, inheritedTypes: [Type], + genericWhereClause: TrailingWhereClause?, braceRange: SourceRange + ) -> BridgedEnumDecl { + return name.withCString { strPtr in + inheritedTypes.withBridgedArrayRef { types in + BridgedEnumDecl.createParsed( + astContext, declContext: declContext, + enumKeywordLoc: enumKeywordLoc.bridgedLocation, + name: astContext.getIdentifier(BridgedStringRef(data: strPtr, count: name.count)), + nameLoc: nameLoc.bridgedLocation, + genericParamList: genericParamList.bridged, + inheritedTypes: types, + genericWhereClause: genericWhereClause.bridged, + braceRange: braceRange.bridged) + } + } + } +} + +extension BridgedEnumElementDecl { + public static func createParsed( + _ astContext: ASTContext, declContext: DeclContext, + name: Identifier, nameLoc: SourceLoc?, + parameterList: ParameterList?, + equalsLoc: SourceLoc?, rawValue: Expr? + ) -> BridgedEnumElementDecl { + BridgedEnumElementDecl.createParsed( + astContext, declContext: declContext, + name: name, nameLoc: nameLoc.bridgedLocation, + parameterList: parameterList.bridged, + equalsLoc: equalsLoc.bridgedLocation, rawValue: rawValue.bridged) + } +} + +extension SourceFile { + public init?(bridged: BridgedNullableSourceFile) { + guard let raw = bridged.raw else { + return nil + } + self.init(raw: raw) + } +} + +extension FileUnit { + public var asSourceFile: SourceFile? { SourceFile(bridged: self.castToSourceFile()) } +} + +extension BridgedParamDecl { + public func setInterfaceType(type: Type) { + self.setInterfaceType(type.bridged) + } +} + +extension ParameterList? { + public var bridged: BridgedNullableParameterList { + BridgedNullableParameterList(raw: self?.raw) + } +} + +extension GenericParamList? { + public var bridged: BridgedNullableGenericParamList { + BridgedNullableGenericParamList(raw: self?.raw) + } +} + +extension Expr? { + public var bridged: BridgedNullableExpr { + BridgedNullableExpr(raw: self?.raw) + } +} + +extension TrailingWhereClause? { + public var bridged: BridgedNullableTrailingWhereClause { + BridgedNullableTrailingWhereClause(raw: self?.raw) + } +} diff --git a/SwiftCompilerSources/Sources/AST/GenericSignature.swift b/SwiftCompilerSources/Sources/AST/GenericSignature.swift index f91ad0504ba00..68f2222785b0a 100644 --- a/SwiftCompilerSources/Sources/AST/GenericSignature.swift +++ b/SwiftCompilerSources/Sources/AST/GenericSignature.swift @@ -36,10 +36,12 @@ public struct GenericSignature: CustomStringConvertible, NoReflectionChildren { public var isEmpty: Bool { bridged.impl == nil } - public var canonicalSignature: CanGenericSignature { CanGenericSignature(bridged: bridged.getCanonicalSignature()) } + public var canonicalSignature: CanonicalGenericSignature { + CanonicalGenericSignature(bridged: bridged.getCanonicalSignature()) + } } -public struct CanGenericSignature { +public struct CanonicalGenericSignature { public let bridged: BridgedCanGenericSignature public init(bridged: BridgedCanGenericSignature) { @@ -48,5 +50,7 @@ public struct CanGenericSignature { public var isEmpty: Bool { bridged.impl == nil } - public var genericSignature: GenericSignature { GenericSignature(bridged: bridged.getGenericSignature()) } + public var genericSignature: GenericSignature { + GenericSignature(bridged: bridged.getGenericSignature()) + } } diff --git a/SwiftCompilerSources/Sources/AST/Type.swift b/SwiftCompilerSources/Sources/AST/Type.swift index 008fc55776bc0..937a60c399dbc 100644 --- a/SwiftCompilerSources/Sources/AST/Type.swift +++ b/SwiftCompilerSources/Sources/AST/Type.swift @@ -71,24 +71,26 @@ public struct Type: TypeProperties, CustomStringConvertible, NoReflectionChildre return Type(bridged: bridged.mapTypeOutOfContext()) } - public func getReducedType(sig: GenericSignature) -> CanonicalType { - CanonicalType(bridged: bridged.getReducedType(sig.bridged)) + /// Returns a stronger canonicalization which folds away equivalent + /// associated types, or type parameters that have been made concrete. + public func getReducedType(of signature: GenericSignature) -> CanonicalType { + CanonicalType(bridged: bridged.getReducedType(signature.bridged)) } - public func GenericTypeParam_getName() -> swift.Identifier { - return bridged.GenericTypeParam_getName() + public var nameOfGenericTypeParameter: Identifier { + bridged.GenericTypeParam_getName() } - public func GenericTypeParam_getDepth() -> UInt { - return bridged.GenericTypeParam_getDepth() + public var depthOfGenericTypeParameter: Int { + bridged.GenericTypeParam_getDepth() } - public func GenericTypeParam_getIndex() -> UInt { - return bridged.GenericTypeParam_getIndex() + public var indexOfGenericTypeParameter: Int { + bridged.GenericTypeParam_getIndex() } - public func GenericTypeParam_getParamKind() -> swift.GenericTypeParamKind { - return bridged.GenericTypeParam_getParamKind() + public var kindOfGenericTypeParameter: GenericTypeParameterKind { + bridged.GenericTypeParam_getParamKind() } } @@ -110,10 +112,6 @@ public struct CanonicalType: TypeProperties, CustomStringConvertible, NoReflecti public func subst(with substitutionMap: SubstitutionMap) -> CanonicalType { return rawType.subst(with: substitutionMap).canonical } - - public func SILFunctionType_getSubstGenericSignature() -> CanGenericSignature { - CanGenericSignature(bridged: bridged.SILFunctionType_getSubstGenericSignature()) - } } /// Implements the common members of `AST.Type`, `AST.CanonicalType` and `SIL.Type`. @@ -270,6 +268,12 @@ extension TypeProperties { public func checkConformance(to protocol: ProtocolDecl) -> Conformance { return Conformance(bridged: rawType.bridged.checkConformance(`protocol`.bridged)) } + + /// The generic signature that the component types are specified in terms of, if any. + public var substitutedGenericSignatureOfFunctionType: CanonicalGenericSignature { + CanonicalGenericSignature( + bridged: rawType.canonical.bridged.SILFunctionType_getSubstGenericSignature()) + } } public struct TypeArray : RandomAccessCollection, CustomReflectable { @@ -327,3 +331,5 @@ extension CanonicalType: Equatable { lhs.rawType == rhs.rawType } } + +public typealias GenericTypeParameterKind = swift.GenericTypeParamKind diff --git a/SwiftCompilerSources/Sources/Basic/SourceLoc.swift b/SwiftCompilerSources/Sources/Basic/SourceLoc.swift index 7eb37a720becb..8a18a869bd718 100644 --- a/SwiftCompilerSources/Sources/Basic/SourceLoc.swift +++ b/SwiftCompilerSources/Sources/Basic/SourceLoc.swift @@ -35,6 +35,14 @@ extension Optional { } } +public struct SourceRange { + public let bridged: swift.SourceRange + + public init(start: SourceLoc?) { + self.bridged = swift.SourceRange(start: start.bridgedLocation) + } +} + public struct CharSourceRange { public let start: SourceLoc public let byteLength: UInt32 diff --git a/SwiftCompilerSources/Sources/SIL/Argument.swift b/SwiftCompilerSources/Sources/SIL/Argument.swift index 88b3662761057..8a9c861366501 100644 --- a/SwiftCompilerSources/Sources/SIL/Argument.swift +++ b/SwiftCompilerSources/Sources/SIL/Argument.swift @@ -50,10 +50,6 @@ public class Argument : Value, Hashable { public var sourceLoc: SourceLoc? { findVarDecl()?.nameLoc } - public func replaceAllUsesWith(newArg: Argument) { - bridged.replaceAllUsesWith(newArg.bridged) - } - public static func ==(lhs: Argument, rhs: Argument) -> Bool { lhs === rhs } diff --git a/SwiftCompilerSources/Sources/SIL/BasicBlock.swift b/SwiftCompilerSources/Sources/SIL/BasicBlock.swift index cdd548f5dc8fe..10dc40d4474e2 100644 --- a/SwiftCompilerSources/Sources/SIL/BasicBlock.swift +++ b/SwiftCompilerSources/Sources/SIL/BasicBlock.swift @@ -68,7 +68,9 @@ final public class BasicBlock : CustomStringConvertible, HasShortDescription, Ha (decl as Decl?).bridged).argument as! FunctionArgument } - public func insertPhiArgument(atPosition: Int, type: Type, ownership: Ownership, _ context: some MutatingContext) -> Argument { + public func insertPhiArgument( + atPosition: Int, type: Type, ownership: Ownership, _ context: some MutatingContext + ) -> Argument { context.notifyInstructionsChanged() return bridged.insertPhiArgument(atPosition, type.bridged, ownership._bridged).argument } diff --git a/SwiftCompilerSources/Sources/SIL/Builder.swift b/SwiftCompilerSources/Sources/SIL/Builder.swift index 43fcb73ce27a5..5072bf4759393 100644 --- a/SwiftCompilerSources/Sources/SIL/Builder.swift +++ b/SwiftCompilerSources/Sources/SIL/Builder.swift @@ -662,13 +662,6 @@ public struct Builder { return notifyNew(tuple.getAs(TupleInst.self)) } - public func createTuple(elements: [Value]) -> TupleInst { - let tuple = elements.withBridgedValues { valuesRef in - return bridged.createTuple(valuesRef) - } - return notifyNew(tuple.getAs(TupleInst.self)) - } - public func createTupleExtract(tuple: Value, elementIndex: Int) -> TupleExtractInst { return notifyNew(bridged.createTupleExtract(tuple.bridged, elementIndex).getAs(TupleExtractInst.self)) } diff --git a/SwiftCompilerSources/Sources/SIL/Context.swift b/SwiftCompilerSources/Sources/SIL/Context.swift index 3384573b6a29d..2c2ffa6dad89b 100644 --- a/SwiftCompilerSources/Sources/SIL/Context.swift +++ b/SwiftCompilerSources/Sources/SIL/Context.swift @@ -49,10 +49,7 @@ extension Context { public func getBuiltinIntegerType(bitWidth: Int) -> Type { _bridged.getBuiltinIntegerType(bitWidth).type } public func getTupleType(elements: [Type]) -> AST.`Type` { - let bridgedElements = elements.map { $0.bridged } - return bridgedElements.withBridgedArrayRef { - AST.`Type`(bridged: _bridged.getTupleType($0)) - } + return getTupleType(elements: elements.map{ $0.rawType }) } public func getTupleType(elements: [AST.`Type`]) -> AST.`Type` { @@ -62,11 +59,10 @@ extension Context { } } - public func getTupleTypeWithLabels(elements: [AST.`Type`], labels: [swift.Identifier]) -> AST.`Type` { - assert(elements.count == labels.count) - return elements.withBridgedArrayRef{ - eltArr in labels.withBridgedArrayRef{labelsArr in - AST.`Type`(bridged: _bridged.getTupleTypeWithLabels(eltArr, labelsArr))}} + public func getTupleType(elements: [(label: Identifier, type: AST.`Type`)]) -> AST.`Type` { + return elements.map{$0.type}.withBridgedArrayRef{ + types in elements.map{$0.label}.withBridgedArrayRef{labels in + AST.`Type`(bridged: _bridged.getTupleTypeWithLabels(types, labels))}} } public var swiftArrayDecl: NominalTypeDecl { diff --git a/SwiftCompilerSources/Sources/SIL/Function.swift b/SwiftCompilerSources/Sources/SIL/Function.swift index 548b08b69da9b..6966dae7b0713 100644 --- a/SwiftCompilerSources/Sources/SIL/Function.swift +++ b/SwiftCompilerSources/Sources/SIL/Function.swift @@ -26,9 +26,7 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash return Location(bridged: bridged.getLocation()) } - public var sourceFile: BridgedNullableSourceFile { - return bridged.getSourceFile() - } + public var sourceFile: SourceFile? { SourceFile(bridged: bridged.getSourceFile()) } final public var description: String { return String(taking: bridged.getDebugDescription()) diff --git a/SwiftCompilerSources/Sources/SIL/Instruction.swift b/SwiftCompilerSources/Sources/SIL/Instruction.swift index c33ae1772f725..94dbd5e7d8de1 100644 --- a/SwiftCompilerSources/Sources/SIL/Instruction.swift +++ b/SwiftCompilerSources/Sources/SIL/Instruction.swift @@ -1351,7 +1351,6 @@ final public class PartialApplyInst : SingleValueInstruction, ApplySite { public var hasUnknownResultIsolation: Bool { bridged.PartialApplyInst_hasUnknownResultIsolation() } public var unappliedArgumentCount: Int { bridged.PartialApply_getCalleeArgIndexOfFirstAppliedArg() } public var calleeConvention: ArgumentConvention { type.bridged.getCalleeConvention().convention } - public var substitutionMap: SubstitutionMap { SubstitutionMap(bridged: bridged.PartialApplyInst_getSubstitutionMap()) } } final public class ApplyInst : SingleValueInstruction, FullApplySite { @@ -1930,7 +1929,6 @@ final public class SwitchValueInst : TermInst { final public class SwitchEnumInst : TermInst { public var enumOp: Value { operands[0].value } - public var numCases: Int { bridged.SwitchEnumInst_getNumCases() } public struct CaseIndexArray : RandomAccessCollection { fileprivate let switchEnum: SwitchEnumInst @@ -1949,6 +1947,8 @@ final public class SwitchEnumInst : TermInst { zip(caseIndices, successors) } + public var numCases: Int { caseIndices.count } + // This does not handle the special case where the default covers exactly // the "missing" case. public func getUniqueSuccessor(forCaseIndex: Int) -> BasicBlock? { diff --git a/SwiftCompilerSources/Sources/SIL/Type.swift b/SwiftCompilerSources/Sources/SIL/Type.swift index 397c4b4198e0d..6399212253d06 100644 --- a/SwiftCompilerSources/Sources/SIL/Type.swift +++ b/SwiftCompilerSources/Sources/SIL/Type.swift @@ -27,7 +27,6 @@ public struct Type : TypeProperties, CustomStringConvertible, NoReflectionChildr public var isAddress: Bool { bridged.isAddress() } public var isObject: Bool { !isAddress } - public var category: ValueCategory { ValueCategory(bridged: bridged.getCategory()) } public var addressType: Type { bridged.getAddressType().type } public var objectType: Type { bridged.getObjectType().type } @@ -186,6 +185,22 @@ public struct Type : TypeProperties, CustomStringConvertible, NoReflectionChildr return EnumCases(enumType: self, function: function) } + public func getEnumCase(in function: Function, at index: Int) -> EnumCase? { + guard let enumCases = getEnumCases(in: function) else { + return nil + } + + var enumCaseIndex = 0 + for enumCase in enumCases { + if index == enumCaseIndex { + return enumCase + } + enumCaseIndex += 1 + } + + return nil + } + public func getIndexOfEnumCase(withName name: String) -> Int? { let idx = name._withBridgedStringRef { bridged.getCaseIdxOfEnumType($0) @@ -216,14 +231,8 @@ public struct Type : TypeProperties, CustomStringConvertible, NoReflectionChildr return false } - public func getEnumCasePayload(caseIdx: Int, function: Function) -> Type { - bridged.getEnumCasePayload(caseIdx, function.bridged).type - } - - public func mapTypeOutOfContext() -> Type { bridged.mapTypeOutOfContext().type } - - public static func getPrimitiveType(canType: CanonicalType, silValueCategory: ValueCategory) -> Type { - BridgedType.getPrimitiveType(canType: canType.bridged, silValueCategory: silValueCategory._bridged).type + public func mapTypeOutOfContext(in function: Function) -> Type { + rawType.mapTypeOutOfContext().canonical.loweredType(in: function) } } @@ -318,7 +327,7 @@ public struct TupleElementArray : RandomAccessCollection, FormattedLikeArray { type.bridged.getTupleElementType(index).type } - public func label(at index: Int) -> swift.Identifier { + public func label(at index: Int) -> Identifier { type.bridged.getTupleElementLabel(index) } } diff --git a/SwiftCompilerSources/Sources/SIL/Value.swift b/SwiftCompilerSources/Sources/SIL/Value.swift index 213a176d72832..a346cb621ba80 100644 --- a/SwiftCompilerSources/Sources/SIL/Value.swift +++ b/SwiftCompilerSources/Sources/SIL/Value.swift @@ -41,27 +41,6 @@ public protocol Value : AnyObject, CustomStringConvertible { var isLexical: Bool { get } } -public enum ValueCategory { - case address - case object - - public init(bridged: BridgedValueCategory) { - switch bridged { - case .Address: self = .address - case .Object: self = .object - default: - fatalError("unsupported value category") - } - } - - public var _bridged: BridgedValueCategory { - switch self { - case .address: return BridgedValueCategory.Address - case .object: return BridgedValueCategory.Object - } - } -} - public enum Ownership { /// A Value with `unowned` ownership kind is an independent value that /// has a lifetime that is only guaranteed to last until the next program diff --git a/include/swift/AST/ASTBridging.h b/include/swift/AST/ASTBridging.h index 860ce0dfe5629..d7678ec9d8a44 100644 --- a/include/swift/AST/ASTBridging.h +++ b/include/swift/AST/ASTBridging.h @@ -1332,7 +1332,7 @@ SWIFT_NAME("BridgedDecl.forEachDeclToHoist(self:_:)") void BridgedDecl_forEachDeclToHoist(BridgedDecl decl, BridgedSwiftClosure closure); -SWIFT_NAME("BridgedDecl.getDeclContext(self:)") +SWIFT_NAME("getter:BridgedDecl.declContext(self:)") BridgedDeclContext BridgedDecl_getDeclContext(BridgedDecl decl); enum ENUM_EXTENSIBILITY_ATTR(closed) BridgedStaticSpelling { @@ -2923,8 +2923,8 @@ BridgedGenericTypeParamDecl BridgedGenericTypeParamDecl_createParsed( SWIFT_NAME("BridgedGenericTypeParamDecl.createImplicit(declContext:" "name:depth:index:paramKind:)") BridgedGenericTypeParamDecl BridgedGenericTypeParamDecl_createImplicit( - BridgedDeclContext cDeclContext, swift::Identifier name, SwiftUInt depth, - SwiftUInt index, swift::GenericTypeParamKind paramKind); + BridgedDeclContext cDeclContext, swift::Identifier name, SwiftInt depth, + SwiftInt index, swift::GenericTypeParamKind paramKind); SWIFT_NAME( "BridgedTrailingWhereClause.createParsed(_:whereKeywordLoc:requirements:)") @@ -3042,14 +3042,14 @@ struct BridgedASTType { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap getContextSubstitutionMap() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGenericSignature getInvocationGenericSignatureOfFunctionType() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType subst(BridgedSubstitutionMap substMap) const; - SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedConformance checkConformance(BridgedDeclObj proto) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedConformance checkConformance(BridgedDeclObj proto) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedASTType mapTypeOutOfContext() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedCanType getReducedType(BridgedGenericSignature sig) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE swift::Identifier GenericTypeParam_getName() const; - BRIDGED_INLINE SwiftUInt GenericTypeParam_getDepth() const; - BRIDGED_INLINE SwiftUInt GenericTypeParam_getIndex() const; + BRIDGED_INLINE SwiftInt GenericTypeParam_getDepth() const; + BRIDGED_INLINE SwiftInt GenericTypeParam_getIndex() const; BRIDGED_INLINE swift::GenericTypeParamKind GenericTypeParam_getParamKind() const; }; diff --git a/include/swift/AST/ASTBridgingImpl.h b/include/swift/AST/ASTBridgingImpl.h index e3b4c4a78e69c..27363715ef422 100644 --- a/include/swift/AST/ASTBridgingImpl.h +++ b/include/swift/AST/ASTBridgingImpl.h @@ -683,11 +683,11 @@ swift::Identifier BridgedASTType::GenericTypeParam_getName() const { return llvm::cast(type)->getName(); } -SwiftUInt BridgedASTType::GenericTypeParam_getDepth() const { +SwiftInt BridgedASTType::GenericTypeParam_getDepth() const { return llvm::cast(type)->getDepth(); } -SwiftUInt BridgedASTType::GenericTypeParam_getIndex() const { +SwiftInt BridgedASTType::GenericTypeParam_getIndex() const { return llvm::cast(type)->getIndex(); } diff --git a/include/swift/SIL/SILBridging.h b/include/swift/SIL/SILBridging.h index 77a2a7613d13e..c6e805b2255d5 100644 --- a/include/swift/SIL/SILBridging.h +++ b/include/swift/SIL/SILBridging.h @@ -251,8 +251,6 @@ BridgedYieldInfoArray SILFunctionType_getYields(BridgedCanType); SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLifetimeDependenceInfoArray SILFunctionType_getLifetimeDependencies(BridgedCanType); -enum class BridgedValueCategory { Address, Object }; - struct BridgedType { void * _Nullable opaqueValue; @@ -266,12 +264,12 @@ struct BridgedType { BRIDGED_INLINE BridgedType(swift::SILType t); BRIDGED_INLINE swift::SILType unbridged() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedCanType getCanType() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType mapTypeOutOfContext() const; static SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType createSILType(BridgedCanType canTy); BRIDGED_INLINE BridgedOwnedString getDebugDescription() const; BRIDGED_INLINE bool isNull() const; BRIDGED_INLINE bool isAddress() const; - BRIDGED_INLINE BridgedValueCategory getCategory() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getAddressType() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getObjectType() const; BRIDGED_INLINE bool isTrivial(BridgedFunction f) const; @@ -312,13 +310,8 @@ struct BridgedType { getTupleElementLabel(SwiftInt idx) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getFunctionTypeWithNoEscape(bool withNoEscape) const; BRIDGED_INLINE BridgedArgumentConvention getCalleeConvention() const; - SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType mapTypeOutOfContext() const; }; -SWIFT_NAME("BridgedType.getPrimitiveType(canType:silValueCategory:)") -BRIDGED_INLINE BridgedType BridgedType_getPrimitiveType( - BridgedCanType canType, BridgedValueCategory silValueCategory); - // SIL Bridging struct BridgedValue { @@ -983,7 +976,6 @@ struct BridgedArgument { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedDeclObj getDecl() const; BRIDGED_INLINE void copyFlags(BridgedArgument fromArgument) const; BRIDGED_INLINE BridgedValue::Ownership getOwnership() const; - BRIDGED_INLINE void replaceAllUsesWith(BridgedArgument arg) const; }; struct OptionalBridgedArgument { @@ -1368,8 +1360,6 @@ struct BridgedBuilder{ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestructureStruct(BridgedValue str) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTuple(BridgedType type, BridgedValueArray elements) const; - SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction - createTuple(BridgedValueArray elements) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTupleExtract(BridgedValue str, SwiftInt elementIndex) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTupleElementAddr(BridgedValue addr, diff --git a/include/swift/SIL/SILBridgingImpl.h b/include/swift/SIL/SILBridgingImpl.h index 69d4a3bf71a0d..801eb7a7498a4 100644 --- a/include/swift/SIL/SILBridgingImpl.h +++ b/include/swift/SIL/SILBridgingImpl.h @@ -321,17 +321,8 @@ bool BridgedType::isAddress() const { return unbridged().isAddress(); } -static inline BridgedValueCategory bridge(swift::SILValueCategory category) { - switch (category) { - case swift::SILValueCategory::Address: - return BridgedValueCategory::Address; - case swift::SILValueCategory::Object: - return BridgedValueCategory::Object; - } -} - -BridgedValueCategory BridgedType::getCategory() const { - return bridge(unbridged().getCategory()); +BridgedType BridgedType::mapTypeOutOfContext() const { + return unbridged().mapTypeOutOfContext(); } BridgedCanType BridgedType::getCanType() const { @@ -488,26 +479,6 @@ BridgedArgumentConvention BridgedType::getCalleeConvention() const { return getArgumentConvention(fnType->getCalleeConvention()); } -BridgedType BridgedType::mapTypeOutOfContext() const { - return unbridged().mapTypeOutOfContext(); -} - -static inline swift::SILValueCategory unbridge(BridgedValueCategory category) { - switch (category) { - case BridgedValueCategory::Address: - return swift::SILValueCategory::Address; - case BridgedValueCategory::Object: - return swift::SILValueCategory::Object; - } -} - -BridgedType -BridgedType_getPrimitiveType(BridgedCanType canType, - BridgedValueCategory silValueCategory) { - return swift::SILType::getPrimitiveType(canType.unbridged(), - unbridge(silValueCategory)); -} - //===----------------------------------------------------------------------===// // BridgedValue //===----------------------------------------------------------------------===// @@ -668,10 +639,6 @@ BridgedValue::Ownership BridgedArgument::getOwnership() const { return BridgedValue{SwiftObject{val}}.getOwnership(); } -void BridgedArgument::replaceAllUsesWith(BridgedArgument arg) const { - getArgument()->replaceAllUsesWith(arg.getArgument()); -} - swift::SILArgument * _Nullable OptionalBridgedArgument::unbridged() const { if (!obj) return nullptr; @@ -2731,23 +2698,6 @@ BridgedInstruction BridgedBuilder::createTuple(BridgedType type, BridgedValueArr elements.getValues(elementValues))}; } -BridgedInstruction -BridgedBuilder::createTuple(BridgedValueArray elements) const { - llvm::SmallVector elementValues; - llvm::ArrayRef values = elements.getValues(elementValues); - llvm::SmallVector tupleTyElts; - tupleTyElts.reserve(values.size()); - for (const swift::SILValue &value : values) { - tupleTyElts.emplace_back(value->getType().getASTType()); - } - swift::Type tupleTy = - swift::TupleType::get(tupleTyElts, unbridged().getASTContext()); - swift::SILType silTupleTy = - swift::SILType::getPrimitiveObjectType(tupleTy->getCanonicalType()); - - return {unbridged().createTuple(regularLoc(), silTupleTy, values)}; -} - BridgedInstruction BridgedBuilder::createTupleExtract(BridgedValue str, SwiftInt elementIndex) const { swift::SILValue v = str.getSILValue(); return {unbridged().createTupleExtract(regularLoc(), v, elementIndex)}; diff --git a/lib/AST/Bridging/GenericsBridging.cpp b/lib/AST/Bridging/GenericsBridging.cpp index 92cd54a67ca86..8960d889c7660 100644 --- a/lib/AST/Bridging/GenericsBridging.cpp +++ b/lib/AST/Bridging/GenericsBridging.cpp @@ -60,8 +60,8 @@ BridgedGenericTypeParamDecl BridgedGenericTypeParamDecl_createParsed( } BridgedGenericTypeParamDecl BridgedGenericTypeParamDecl_createImplicit( - BridgedDeclContext cDeclContext, swift::Identifier name, SwiftUInt depth, - SwiftUInt index, swift::GenericTypeParamKind paramKind) { + BridgedDeclContext cDeclContext, swift::Identifier name, SwiftInt depth, + SwiftInt index, swift::GenericTypeParamKind paramKind) { auto *param = GenericTypeParamDecl::createImplicit( cDeclContext.unbridged(), name, depth, index, paramKind); param->setDeclContext(cDeclContext.unbridged()); From f0bf57a26997c80976bf89462368661569ce6b32 Mon Sep 17 00:00:00 2001 From: Daniil Kovalev Date: Mon, 10 Nov 2025 19:16:54 +0300 Subject: [PATCH 3/7] Resolve merge conflicts & address review comments --- .../Sources/AST/Declarations.swift | 218 ++++++++++++------ SwiftCompilerSources/Sources/AST/Type.swift | 2 +- .../Sources/SIL/ASTExtensions.swift | 11 +- .../Sources/SIL/DeclRef.swift | 2 + .../Sources/SIL/Function.swift | 4 +- SwiftCompilerSources/Sources/SIL/Type.swift | 36 +-- include/swift/AST/ASTBridging.h | 45 +--- include/swift/AST/ASTBridgingImpl.h | 40 ++-- include/swift/SIL/SILBridging.h | 9 +- include/swift/SIL/SILBridgingImpl.h | 25 +- lib/AST/Bridging/DeclBridging.cpp | 29 --- lib/AST/DeclContext.cpp | 2 +- lib/ASTGen/Sources/ASTGen/Exprs.swift | 2 +- 13 files changed, 226 insertions(+), 199 deletions(-) diff --git a/SwiftCompilerSources/Sources/AST/Declarations.swift b/SwiftCompilerSources/Sources/AST/Declarations.swift index 1b0fad1008068..70c3b5bc93218 100644 --- a/SwiftCompilerSources/Sources/AST/Declarations.swift +++ b/SwiftCompilerSources/Sources/AST/Declarations.swift @@ -29,15 +29,45 @@ public class Decl: CustomStringConvertible, Hashable { // True if this declaration is imported from C/C++/ObjC. public var hasClangNode: Bool { bridged.hasClangNode() } - public var declContext: DeclContext { bridgedDecl.declContext } + public var declContext: DeclContext { + if let decl = parent { + return decl as! DeclContext + } + return DeclContextObj(bridged: bridged.getDeclContext()) + } - var bridgedDecl: BridgedDecl { BridgedDecl(raw: bridged.obj) } + public var bridgedDecl: BridgedDecl { BridgedDecl(raw: bridged.obj) } public static func ==(lhs: Decl, rhs: Decl) -> Bool { lhs === rhs } public func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } + + public func setImplicit() { bridged.setImplicit() } +} + +public protocol DeclContext { + var bridgedDeclContext: BridgedDeclContext { get } +} + +extension DeclContext { + public var astContext: ASTContext { bridgedDeclContext.astContext } +} + +fileprivate class DeclContextObj : DeclContext { + public var bridgedDeclContext: BridgedDeclContext + public init(bridged: BridgedDeclContext) { bridgedDeclContext = bridged } +} + +public protocol GenericContext: Decl, DeclContext {} + +extension GenericContext { + public func setGenericSignature(_ genericSignature: GenericSignature) { + bridged.GenericContext_setGenericSignature(genericSignature.bridged) + } + + public var bridgedDeclContext: BridgedDeclContext { bridged.asGenericContext() } } public class ValueDecl: Decl { @@ -45,13 +75,16 @@ public class ValueDecl: Decl { final public var userFacingName: StringRef { StringRef(bridged: bridged.Value_getUserFacingName()) } final public var baseIdentifier: Identifier { bridged.Value_getBaseIdentifier() } final public var isObjC: Bool { bridged.Value_isObjC() } + final public func setAccess(_ accessLevel : AccessLevel) { + bridged.ValueDecl_setAccess(accessLevel) + } } public class TypeDecl: ValueDecl { final public var name: StringRef { StringRef(bridged: bridged.Type_getName()) } } -public class GenericTypeDecl: TypeDecl { +public class GenericTypeDecl: TypeDecl, GenericContext { final public var isGenericAtAnyLevel: Bool { bridged.GenericType_isGenericAtAnyLevel() } } @@ -65,10 +98,34 @@ public class NominalTypeDecl: GenericTypeDecl { public var declaredInterfaceType: Type { Type(bridged: bridged.NominalType_getDeclaredInterfaceType()) } + + public func add(member: Decl) { + bridged.NominalTypeDecl_addMember(member.bridged) + } } final public class EnumDecl: NominalTypeDecl { public var hasRawType: Bool { bridged.Enum_hasRawType() } + + public static func create( + _ astContext: ASTContext, declContext: DeclContext, enumKeywordLoc: SourceLoc?, name: String, + nameLoc: SourceLoc?, genericParamList: GenericParamList?, inheritedTypes: [Type], + genericWhereClause: TrailingWhereClause?, braceRange: SourceRange + ) -> EnumDecl { + name.withCString { strPtr in + inheritedTypes.withBridgedArrayRef { types in + ASTBridging.BridgedEnumDecl.createParsed( + astContext, declContext: declContext.bridgedDeclContext, + enumKeywordLoc: enumKeywordLoc.bridgedLocation, + name: astContext.getIdentifier(BridgedStringRef(data: strPtr, count: name.count)), + nameLoc: nameLoc.bridgedLocation, + genericParamList: genericParamList.bridged, + inheritedTypes: types, + genericWhereClause: genericWhereClause.bridged, + braceRange: braceRange.bridged) + } + }.asDecl.declObj.getAs(EnumDecl.self) + } } final public class StructDecl: NominalTypeDecl { @@ -93,7 +150,19 @@ final public class OpaqueTypeDecl: GenericTypeDecl {} final public class TypeAliasDecl: GenericTypeDecl {} -final public class GenericTypeParamDecl: TypeDecl {} +final public class GenericTypeParamDecl: TypeDecl { + public static func create( + declContext: DeclContext, + name: Identifier, + depth: Int, + index: Int, + paramKind: GenericTypeParameterKind) -> GenericTypeParamDecl { + ASTBridging.BridgedGenericTypeParamDecl.createImplicit( + declContext: declContext.bridgedDeclContext, + name: name, depth: depth, index: index, + paramKind: paramKind).asDecl.declObj.getAs(GenericTypeParamDecl.self) + } +} final public class AssociatedTypeDecl: TypeDecl {} @@ -105,7 +174,15 @@ public class AbstractStorageDecl: ValueDecl { public class VarDecl: AbstractStorageDecl {} -final public class ParamDecl: VarDecl {} +final public class ParamDecl: VarDecl { + public func cloneWithoutType() -> ParamDecl { + BridgedParamDecl(raw: bridged.obj).cloneWithoutType().asDecl.declObj.getAs(ParamDecl.self) + } + + public func setInterfaceType(type: Type) { + BridgedParamDecl(raw: bridged.obj).setInterfaceType(type.bridged) + } +} final public class SubscriptDecl: AbstractStorageDecl {} @@ -127,8 +204,22 @@ final public class MacroDecl: ValueDecl {} final public class EnumElementDecl: ValueDecl { public var hasAssociatedValues: Bool { bridged.EnumElementDecl_hasAssociatedValues() } - public var parameterList: ParameterList { bridged.EnumElementDecl_getParameterList() } + public var parameterList: ParameterList { ParameterList(bridged: bridged.EnumElementDecl_getParameterList()) } public var name: StringRef { StringRef(bridged: bridged.EnumElementDecl_getNameStr()) } + + public static func create( + _ astContext: ASTContext, declContext: DeclContext, + name: Identifier, nameLoc: SourceLoc?, + parameterList: ParameterList?, + equalsLoc: SourceLoc?, rawValue: Expr? + ) -> EnumElementDecl { + BridgedEnumElementDecl.createParsed( + astContext, declContext: declContext.bridgedDeclContext, + name: name, nameLoc: nameLoc.bridgedLocation, + parameterList: parameterList.bridged.bridged, + equalsLoc: equalsLoc.bridgedLocation, + rawValue: rawValue.bridged).asDecl.declObj.getAs(EnumElementDecl.self) + } } final public class ExtensionDecl: Decl {} @@ -177,62 +268,83 @@ extension Optional where Wrapped == Decl { } } +public typealias AccessLevel = swift.AccessLevel + public typealias Identifier = swift.Identifier public typealias GenericTypeParamKind = swift.GenericTypeParamKind public typealias ASTContext = BridgedASTContext -public typealias DeclContext = BridgedDeclContext - public typealias Expr = BridgedExpr -public typealias ParameterList = BridgedParameterList - public typealias SourceFile = BridgedSourceFile public typealias FileUnit = BridgedFileUnit -public typealias GenericParamList = BridgedGenericParamList +public class GenericParamList { + public var bridged: BridgedGenericParamList + public init(bridged: BridgedGenericParamList) { self.bridged = bridged } +} public typealias TrailingWhereClause = BridgedTrailingWhereClause -public typealias BridgedParamDecl = ASTBridging.BridgedParamDecl +public class ParameterList : RandomAccessCollection { + public class Iterator : IteratorProtocol { + public typealias Element = ParamDecl + private var index : Int = 0 + private let parameterList : ParameterList + init(parameterList : ParameterList) { self.parameterList = parameterList } + public func next() -> Element? { + if index < parameterList.bridged.size { + return parameterList.bridged.get(index).asDecl.declObj.getAs(ParamDecl.self) + } + return nil + } + } + public typealias Index = Int + public var startIndex: Index { 0 } + public var endIndex: Index { bridged.size } + public func index(after i: Index) -> Index { i + 1 } -public typealias BridgedGenericTypeParamDecl = ASTBridging.BridgedGenericTypeParamDecl + public func makeIterator() -> Iterator { + Self.Iterator(parameterList: self) + } -public typealias BridgedEnumDecl = ASTBridging.BridgedEnumDecl + public var bridged: BridgedParameterList -public typealias BridgedEnumElementDecl = ASTBridging.BridgedEnumElementDecl + public init(bridged: BridgedParameterList) { + self.bridged = bridged + } -extension ParameterList { - public subscript(_ index: Int) -> BridgedParamDecl { - return get(index) + public subscript(_ index: Index) -> ParamDecl { + return bridged.get(index).asDecl.declObj.getAs(ParamDecl.self) } - public static func createParsed( - _ astContext: ASTContext, leftParenLoc: SourceLoc?, parameters: [BridgedParamDecl], + public static func create( + _ astContext: ASTContext, leftParenLoc: SourceLoc?, parameters: [ParamDecl], rightParenLoc: SourceLoc? ) -> ParameterList { - parameters.withBridgedArrayRef { - ParameterList.createParsed( + ParameterList(bridged: parameters.map{BridgedParamDecl(raw: $0.bridged.obj)}.withBridgedArrayRef { + BridgedParameterList.createParsed( astContext, leftParenLoc: leftParenLoc.bridgedLocation, parameters: $0, rightParenLoc: rightParenLoc.bridgedLocation) - } + }) } } extension GenericParamList { - public static func createParsed( - _ astContext: ASTContext, leftAngleLoc: SourceLoc?, parameters: [BridgedGenericTypeParamDecl], + public static func create( + _ astContext: ASTContext, leftAngleLoc: SourceLoc?, parameters: [GenericTypeParamDecl], genericWhereClause: TrailingWhereClause?, rightAngleLoc: SourceLoc? ) -> GenericParamList { - return parameters.withBridgedArrayRef { - GenericParamList.createParsed( + let paramsNew = parameters.map{ ASTBridging.BridgedGenericTypeParamDecl(raw: $0.bridged.obj) } + return paramsNew.withBridgedArrayRef { + GenericParamList(bridged: BridgedGenericParamList.createParsed( astContext, leftAngleLoc: leftAngleLoc.bridgedLocation, parameters: $0, genericWhereClause: genericWhereClause.bridged, rightAngleLoc: rightAngleLoc.bridgedLocation - ) + )) } } } @@ -244,43 +356,6 @@ extension BridgedDecl { public var decl: Decl { declObj.decl } } -extension BridgedEnumDecl { - public static func createParsed( - _ astContext: ASTContext, declContext: DeclContext, enumKeywordLoc: SourceLoc?, name: String, - nameLoc: SourceLoc?, genericParamList: GenericParamList?, inheritedTypes: [Type], - genericWhereClause: TrailingWhereClause?, braceRange: SourceRange - ) -> BridgedEnumDecl { - return name.withCString { strPtr in - inheritedTypes.withBridgedArrayRef { types in - BridgedEnumDecl.createParsed( - astContext, declContext: declContext, - enumKeywordLoc: enumKeywordLoc.bridgedLocation, - name: astContext.getIdentifier(BridgedStringRef(data: strPtr, count: name.count)), - nameLoc: nameLoc.bridgedLocation, - genericParamList: genericParamList.bridged, - inheritedTypes: types, - genericWhereClause: genericWhereClause.bridged, - braceRange: braceRange.bridged) - } - } - } -} - -extension BridgedEnumElementDecl { - public static func createParsed( - _ astContext: ASTContext, declContext: DeclContext, - name: Identifier, nameLoc: SourceLoc?, - parameterList: ParameterList?, - equalsLoc: SourceLoc?, rawValue: Expr? - ) -> BridgedEnumElementDecl { - BridgedEnumElementDecl.createParsed( - astContext, declContext: declContext, - name: name, nameLoc: nameLoc.bridgedLocation, - parameterList: parameterList.bridged, - equalsLoc: equalsLoc.bridgedLocation, rawValue: rawValue.bridged) - } -} - extension SourceFile { public init?(bridged: BridgedNullableSourceFile) { guard let raw = bridged.raw else { @@ -294,13 +369,16 @@ extension FileUnit { public var asSourceFile: SourceFile? { SourceFile(bridged: self.castToSourceFile()) } } -extension BridgedParamDecl { - public func setInterfaceType(type: Type) { - self.setInterfaceType(type.bridged) +extension ParameterList? { + public var bridged: BridgedParameterList? { + if self == nil { + return nil + } + return self!.bridged } } -extension ParameterList? { +extension BridgedParameterList? { public var bridged: BridgedNullableParameterList { BridgedNullableParameterList(raw: self?.raw) } @@ -308,7 +386,7 @@ extension ParameterList? { extension GenericParamList? { public var bridged: BridgedNullableGenericParamList { - BridgedNullableGenericParamList(raw: self?.raw) + BridgedNullableGenericParamList(raw: self?.bridged.raw) } } diff --git a/SwiftCompilerSources/Sources/AST/Type.swift b/SwiftCompilerSources/Sources/AST/Type.swift index a98399d871a55..46b31e2c5258c 100644 --- a/SwiftCompilerSources/Sources/AST/Type.swift +++ b/SwiftCompilerSources/Sources/AST/Type.swift @@ -67,7 +67,7 @@ public struct Type: TypeProperties, CustomStringConvertible, NoReflectionChildre return Type(bridged: bridged.subst(substitutionMap.bridged)) } - public func mapTypeOutOfContext() -> Type { + public func mapOutOfContext() -> Type { return Type(bridged: bridged.mapTypeOutOfContext()) } diff --git a/SwiftCompilerSources/Sources/SIL/ASTExtensions.swift b/SwiftCompilerSources/Sources/SIL/ASTExtensions.swift index 76b47a4cda938..453bddbde57e3 100644 --- a/SwiftCompilerSources/Sources/SIL/ASTExtensions.swift +++ b/SwiftCompilerSources/Sources/SIL/ASTExtensions.swift @@ -23,6 +23,13 @@ extension TypeProperties { public func loweredType(in function: Function, maximallyAbstracted: Bool = false) -> Type { function.bridged.getLoweredType(rawType.bridged, maximallyAbstracted).type.objectType } + + // Lowers the AST type to a SIL type - in a specific function. + // In contrast to `loweredType`, this takes `AbstractionPattern` constructed from `function`'s + // `SubstGenericSignature` into account when getting the lowered type. + public func loweredTypeWithAbstractionPattern(in function: Function) -> Type { + function.bridged.getLoweredTypeWithAbstractionPattern(rawType.canonical.bridged).type + } } extension CanonicalType { @@ -36,10 +43,6 @@ extension CanonicalType { precondition(isBox) return BoxFieldsArray(boxType: self, function: function) } - - public func loweredType(in function: Function) -> Type { - function.bridged.getLoweredType(bridged).type - } } extension Decl { diff --git a/SwiftCompilerSources/Sources/SIL/DeclRef.swift b/SwiftCompilerSources/Sources/SIL/DeclRef.swift index a41660a57cc2a..b94ff00cf7da5 100644 --- a/SwiftCompilerSources/Sources/SIL/DeclRef.swift +++ b/SwiftCompilerSources/Sources/SIL/DeclRef.swift @@ -36,6 +36,8 @@ public struct DeclRef: CustomStringConvertible, NoReflectionChildren { public func calleesAreStaticallyKnowable(_ context: some Context) -> Bool { context._bridged.calleesAreStaticallyKnowable(bridged) } + + public var sourceFile: SourceFile? { SourceFile(bridged: bridged.getSourceFile()) } } extension DeclRef: DiagnosticArgument { diff --git a/SwiftCompilerSources/Sources/SIL/Function.swift b/SwiftCompilerSources/Sources/SIL/Function.swift index e3da868f36066..27b102dbe40ce 100644 --- a/SwiftCompilerSources/Sources/SIL/Function.swift +++ b/SwiftCompilerSources/Sources/SIL/Function.swift @@ -26,7 +26,9 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash return Location(bridged: bridged.getLocation()) } - public var sourceFile: SourceFile? { SourceFile(bridged: bridged.getSourceFile()) } + public var declRef: DeclRef { DeclRef(bridged: bridged.getDeclRef()) } + + public var sourceFile: SourceFile? { declRef.sourceFile } final public var description: String { return String(taking: bridged.getDebugDescription()) diff --git a/SwiftCompilerSources/Sources/SIL/Type.swift b/SwiftCompilerSources/Sources/SIL/Type.swift index 1535f0133bf46..692b6bd7ca4c2 100644 --- a/SwiftCompilerSources/Sources/SIL/Type.swift +++ b/SwiftCompilerSources/Sources/SIL/Type.swift @@ -195,22 +195,6 @@ public struct Type : TypeProperties, CustomStringConvertible, NoReflectionChildr return EnumCases(enumType: self, function: function) } - public func getEnumCase(in function: Function, at index: Int) -> EnumCase? { - guard let enumCases = getEnumCases(in: function) else { - return nil - } - - var enumCaseIndex = 0 - for enumCase in enumCases { - if index == enumCaseIndex { - return enumCase - } - enumCaseIndex += 1 - } - - return nil - } - public func getIndexOfEnumCase(withName name: String) -> Int? { let idx = name._withBridgedStringRef { bridged.getCaseIdxOfEnumType($0) @@ -241,8 +225,8 @@ public struct Type : TypeProperties, CustomStringConvertible, NoReflectionChildr return false } - public func mapTypeOutOfContext(in function: Function) -> Type { - rawType.mapTypeOutOfContext().canonical.loweredType(in: function) + public func mapOutOfContext(in function: Function) -> Type { + rawType.mapOutOfContext().canonical.loweredType(in: function) } } @@ -325,6 +309,22 @@ public struct EnumCases : CollectionLikeSequence, IteratorProtocol { } return nil } + + // Note: this has O(n) complexity where n is number of enum cases + public subscript(_ index: Int) -> EnumCase? { + var iterator = enumType.bridged.getFirstEnumCaseIterator() + var currentIndex = 0 + while currentIndex != index && !enumType.bridged.isEndCaseIterator(iterator) { + iterator = iterator.getNext() + currentIndex += 1 + } + if currentIndex == index && !enumType.bridged.isEndCaseIterator(iterator) { + return EnumCase(enumElementDecl: enumType.bridged.getEnumElementDecl(iterator).getAs(EnumElementDecl.self), + payload: enumType.bridged.getEnumCasePayload(iterator, function.bridged).typeOrNil, + index: caseIndex) + } + return nil + } } public struct TupleElementArray : RandomAccessCollection, FormattedLikeArray { diff --git a/include/swift/AST/ASTBridging.h b/include/swift/AST/ASTBridging.h index 1cb22f97b5ec4..8d029b8959639 100644 --- a/include/swift/AST/ASTBridging.h +++ b/include/swift/AST/ASTBridging.h @@ -321,6 +321,9 @@ struct BridgedDeclObj { BRIDGED_INLINE swift::SourceLoc getLoc() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclObj getModuleContext() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedDeclObj getParent() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclContext getDeclContext() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclContext asGenericContext() const; + BRIDGED_INLINE void setImplicit() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef Type_getName() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef Value_getUserFacingName() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE swift::SourceLoc Value_getNameLoc() const; @@ -347,6 +350,9 @@ struct BridgedDeclObj { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef EnumElementDecl_getNameStr() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef AccessorDecl_getKindName() const; + BRIDGED_INLINE void GenericContext_setGenericSignature(BridgedGenericSignature genericSignature) const; + BRIDGED_INLINE void ValueDecl_setAccess(swift::AccessLevel accessLevel) const; + BRIDGED_INLINE void NominalTypeDecl_addMember(BridgedDeclObj member) const; }; enum ENUM_EXTENSIBILITY_ATTR(closed) BridgedASTNodeKind : uint8_t { @@ -399,14 +405,6 @@ class BridgedASTNode { #define ABSTRACT_DECL(Id, Parent) DECL(Id, Parent) #include "swift/AST/DeclNodes.def" -// Declare `.asValueDecl` on each BridgedXXXDecl type that's also a -// ValueDecl. -#define DECL(Id, Parent) -#define VALUE_DECL(Id, Parent) \ - SWIFT_NAME("getter:Bridged" #Id "Decl.asValueDecl(self:)") \ - BridgedValueDecl Bridged##Id##Decl_asValueDecl(Bridged##Id##Decl decl); -#include "swift/AST/DeclNodes.def" - // Declare `.asNominalTypeDecl` on each BridgedXXXDecl type that's also a // NominalTypeDecl. #define DECL(Id, Parent) @@ -425,16 +423,6 @@ class BridgedASTNode { #define ABSTRACT_CONTEXT_DECL(Id, Parent) CONTEXT_DECL(Id, Parent) #include "swift/AST/DeclNodes.def" -// Declare `.asGenericContext` on each BridgedXXXDecl type that's also a -// GenericContext. -#define DECL(Id, Parent) -#define GENERIC_DECL(Id, Parent) \ - SWIFT_NAME("getter:Bridged" #Id "Decl.asGenericContext(self:)") \ - BridgedGenericContext Bridged##Id##Decl_asGenericContext( \ - Bridged##Id##Decl decl); -#define ITERABLE_GENERIC_DECL(Id, Parent) GENERIC_DECL(Id, Parent) -#include "swift/AST/DeclNodes.def" - // Declare `.asStmt` on each BridgedXXXStmt type, which upcasts a wrapper for // a Stmt subclass to a BridgedStmt. #define STMT(Id, Parent) \ @@ -1348,9 +1336,6 @@ SWIFT_NAME("BridgedDecl.forEachDeclToHoist(self:_:)") void BridgedDecl_forEachDeclToHoist(BridgedDecl decl, BridgedSwiftClosure closure); -SWIFT_NAME("getter:BridgedDecl.declContext(self:)") -BridgedDeclContext BridgedDecl_getDeclContext(BridgedDecl decl); - enum ENUM_EXTENSIBILITY_ATTR(closed) BridgedStaticSpelling { BridgedStaticSpellingNone, BridgedStaticSpellingStatic, @@ -1428,13 +1413,8 @@ BRIDGED_INLINE void BridgedParamDecl_setSpecifier(BridgedParamDecl cDecl, BridgedParamSpecifier cSpecifier); -SWIFT_NAME("BridgedDecl.setImplicit(self:)") -BRIDGED_INLINE void BridgedDecl_setImplicit(BridgedDecl cDecl); - -SWIFT_NAME("BridgedGenericContext.setGenericSignature(self:_:)") -BRIDGED_INLINE void -BridgedGenericContext_setGenericSignature(BridgedGenericContext cDecl, - BridgedGenericSignature cGenSig); +SWIFT_NAME("BridgedParamDecl.setImplicit(self:)") +BRIDGED_INLINE void BridgedParamDecl_setImplicit(BridgedParamDecl cDecl); SWIFT_NAME("BridgedConstructorDecl.setParsedBody(self:_:)") void BridgedConstructorDecl_setParsedBody(BridgedConstructorDecl decl, @@ -1689,10 +1669,6 @@ void BridgedTopLevelCodeDecl_dump(BridgedTopLevelCodeDecl decl); SWIFT_NAME("BridgedDecl.dump(self:)") void BridgedDecl_dump(BridgedDecl decl); -SWIFT_NAME("BridgedValueDecl.setAccess(self:_:)") -void BridgedValueDecl_setAccess(BridgedValueDecl decl, - swift::AccessLevel accessLevel); - //===----------------------------------------------------------------------===// // MARK: AbstractStorageDecl //===----------------------------------------------------------------------===// @@ -1742,11 +1718,6 @@ SWIFT_NAME("BridgedNominalTypeDecl.getSourceLocation(self:)") BRIDGED_INLINE swift::SourceLoc BridgedNominalTypeDecl_getSourceLocation(BridgedNominalTypeDecl decl); -SWIFT_NAME("BridgedNominalTypeDecl.addMember(self:_:)") -BRIDGED_INLINE void -BridgedNominalTypeDecl_addMember(BridgedNominalTypeDecl cDecl, - BridgedDecl member); - //===----------------------------------------------------------------------===// // MARK: SubscriptDecl //===----------------------------------------------------------------------===// diff --git a/include/swift/AST/ASTBridgingImpl.h b/include/swift/AST/ASTBridgingImpl.h index fbabf5850fd62..76ccfafb8c79d 100644 --- a/include/swift/AST/ASTBridgingImpl.h +++ b/include/swift/AST/ASTBridgingImpl.h @@ -177,6 +177,18 @@ OptionalBridgedDeclObj BridgedDeclObj::getParent() const { return {unbridged()->getDeclContext()->getAsDecl()}; } +BridgedDeclContext BridgedDeclObj::getDeclContext() const { + return {unbridged()->getDeclContext()}; +} + +BridgedDeclContext BridgedDeclObj::asGenericContext() const { + return {static_cast(getAs())}; +} + +void BridgedDeclObj::setImplicit() const { + unbridged()->setImplicit(); +} + BridgedStringRef BridgedDeclObj::Type_getName() const { return getAs()->getName().str(); } @@ -264,6 +276,18 @@ BridgedASTType BridgedDeclObj::NominalType_getDeclaredInterfaceType() const { getAs()->getDeclaredInterfaceType().getPointer()}; } +void BridgedDeclObj::GenericContext_setGenericSignature(BridgedGenericSignature genericSignature) const { + getAs()->setGenericSignature(genericSignature.unbridged()); +} + +void BridgedDeclObj::ValueDecl_setAccess(swift::AccessLevel accessLevel) const { + getAs()->setAccess(accessLevel); +} + +void BridgedDeclObj::NominalTypeDecl_addMember(BridgedDeclObj member) const { + getAs()->addMember(member.unbridged()); +} + //===----------------------------------------------------------------------===// // MARK: BridgedASTNode //===----------------------------------------------------------------------===// @@ -387,24 +411,10 @@ void BridgedParamDecl_setSpecifier(BridgedParamDecl cDecl, cDecl.unbridged()->setSpecifier(unbridge(cSpecifier)); } -void BridgedDecl_setImplicit(BridgedDecl cDecl) { +void BridgedParamDecl_setImplicit(BridgedParamDecl cDecl) { cDecl.unbridged()->setImplicit(); } -void BridgedGenericContext_setGenericSignature( - BridgedGenericContext cDecl, BridgedGenericSignature cGenSig) { - cDecl.unbridged()->setGenericSignature(cGenSig.unbridged()); -} - -//===----------------------------------------------------------------------===// -// MARK: BridgedNominalTypeDecl -//===----------------------------------------------------------------------===// - -void BridgedNominalTypeDecl_addMember(BridgedNominalTypeDecl cDecl, - BridgedDecl member) { - cDecl.unbridged()->addMember(member.unbridged()); -} - //===----------------------------------------------------------------------===// // MARK: BridgedSubscriptDecl //===----------------------------------------------------------------------===// diff --git a/include/swift/SIL/SILBridging.h b/include/swift/SIL/SILBridging.h index e7bd8b32e2511..3967dce48988a 100644 --- a/include/swift/SIL/SILBridging.h +++ b/include/swift/SIL/SILBridging.h @@ -258,6 +258,7 @@ BridgedYieldInfoArray SILFunctionType_getYields(BridgedCanType); SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLifetimeDependenceInfoArray SILFunctionType_getLifetimeDependencies(BridgedCanType); + struct BridgedType { void * _Nullable opaqueValue; @@ -532,8 +533,6 @@ struct BridgedFunction { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getName() const; BridgedOwnedString getDebugDescription() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLocation getLocation() const; - SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNullableSourceFile - getSourceFile() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArrayRef getFilesForModule() const; BRIDGED_INLINE bool isAccessor() const; BRIDGED_INLINE bool isInitializer() const; @@ -586,7 +585,7 @@ struct BridgedFunction { BRIDGED_INLINE bool isResilientNominalDecl(BridgedDeclObj decl) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getLoweredType(BridgedASTType type, bool maximallyAbstracted) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType - getLoweredType(BridgedCanType type) const; + getLoweredTypeWithAbstractionPattern(BridgedCanType type) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getLoweredType(BridgedType type) const; BRIDGED_INLINE BridgedLinkage getLinkage() const; BRIDGED_INLINE void setLinkage(BridgedLinkage linkage) const; @@ -845,8 +844,6 @@ struct BridgedInstruction { BRIDGED_INLINE void RefElementAddrInst_setImmutable(bool isImmutable) const; BRIDGED_INLINE bool RefTailAddrInst_isImmutable() const; BRIDGED_INLINE SwiftInt PartialApplyInst_numArguments() const; - SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap - PartialApplyInst_getSubstitutionMap() const; BRIDGED_INLINE SwiftInt ApplyInst_numArguments() const; BRIDGED_INLINE bool ApplyInst_getNonThrowing() const; BRIDGED_INLINE bool ApplyInst_getNonAsync() const; @@ -1002,7 +999,6 @@ struct BridgedArgument { BRIDGED_INLINE void setReborrow(bool reborrow) const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedDeclObj getDecl() const; BRIDGED_INLINE void copyFlags(BridgedArgument fromArgument) const; - BRIDGED_INLINE BridgedValue::Ownership getOwnership() const; }; struct OptionalBridgedArgument { @@ -1080,6 +1076,7 @@ struct BridgedDeclRef { SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLocation getLocation() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclObj getDecl() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDiagnosticArgument asDiagnosticArgument() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNullableSourceFile getSourceFile() const; }; struct BridgedVTableEntry { diff --git a/include/swift/SIL/SILBridgingImpl.h b/include/swift/SIL/SILBridgingImpl.h index 83a206ac39f79..378a4c3d22db8 100644 --- a/include/swift/SIL/SILBridgingImpl.h +++ b/include/swift/SIL/SILBridgingImpl.h @@ -675,11 +675,6 @@ void BridgedArgument::copyFlags(BridgedArgument fromArgument) const { fArg->copyFlags(static_cast(fromArgument.getArgument())); } -BridgedValue::Ownership BridgedArgument::getOwnership() const { - swift::ValueBase *val = getArgument(); - return BridgedValue{SwiftObject{val}}.getOwnership(); -} - swift::SILArgument * _Nullable OptionalBridgedArgument::unbridged() const { if (!obj) return nullptr; @@ -758,10 +753,6 @@ BridgedLocation BridgedFunction::getLocation() const { return {swift::SILDebugLocation(getFunction()->getLocation(), getFunction()->getDebugScope())}; } -BridgedNullableSourceFile BridgedFunction::getSourceFile() const { - return {getFunction()->getSourceFile()}; -} - BridgedArrayRef BridgedFunction::getFilesForModule() const { return getFunction()->getModule().getSwiftModule()->getFiles(); } @@ -1000,7 +991,7 @@ BridgedType BridgedFunction::getLoweredType(BridgedASTType type, bool maximallyA return BridgedType(getFunction()->getLoweredType(type.type)); } -BridgedType BridgedFunction::getLoweredType(BridgedCanType type) const { +BridgedType BridgedFunction::getLoweredTypeWithAbstractionPattern(BridgedCanType type) const { swift::Lowering::AbstractionPattern pattern( getFunction()->getLoweredFunctionType()->getSubstGenericSignature(), type.unbridged()); @@ -1183,12 +1174,6 @@ bool BridgedInstruction::isIdenticalTo(BridgedInstruction inst) const { return unbridged()->isIdenticalTo(inst.unbridged()); } -BridgedSubstitutionMap -BridgedInstruction::PartialApplyInst_getSubstitutionMap() const { - auto *pai = llvm::cast(unbridged()); - return {pai->getSubstitutionMap()}; -} - SwiftInt BridgedInstruction::MultipleValueInstruction_getNumResults() const { return getAs()->getNumResults(); } @@ -2113,6 +2098,14 @@ BridgedDiagnosticArgument BridgedDeclRef::asDiagnosticArgument() const { return swift::DiagnosticArgument(unbridged().getDecl()->getName()); } +BridgedNullableSourceFile BridgedDeclRef::getSourceFile() const { + swift::SILDeclRef declRef = unbridged(); + if (!declRef) + return nullptr; + + return {declRef.getInnermostDeclContext()->getParentSourceFile()}; +} + //===----------------------------------------------------------------------===// // BridgedVTable //===----------------------------------------------------------------------===// diff --git a/lib/AST/Bridging/DeclBridging.cpp b/lib/AST/Bridging/DeclBridging.cpp index 7d7ac4493def1..1fed8d93549fc 100644 --- a/lib/AST/Bridging/DeclBridging.cpp +++ b/lib/AST/Bridging/DeclBridging.cpp @@ -95,15 +95,6 @@ BridgedDeclNameLoc BridgedDeclNameLoc_createParsed(BridgedASTContext cContext, #define ABSTRACT_DECL(Id, Parent) DECL(Id, Parent) #include "swift/AST/DeclNodes.def" -// Define `.asValueDecl` on each BridgedXXXDecl type that's also a -// ValueDecl. -#define DECL(Id, Parent) -#define VALUE_DECL(Id, Parent) \ - BridgedValueDecl Bridged##Id##Decl_asValueDecl(Bridged##Id##Decl decl) { \ - return static_cast(decl.unbridged()); \ - } -#include "swift/AST/DeclNodes.def" - // Define `.asNominalTypeDecl` on each BridgedXXXDecl type that's also a // NominalTypeDecl. #define DECL(Id, Parent) @@ -124,17 +115,6 @@ BridgedDeclNameLoc BridgedDeclNameLoc_createParsed(BridgedASTContext cContext, #define ABSTRACT_CONTEXT_DECL(Id, Parent) CONTEXT_DECL(Id, Parent) #include "swift/AST/DeclNodes.def" -// Define `.asGenericContext` on each BridgedXXXDecl type that's also a -// GenericContext. -#define DECL(Id, Parent) -#define GENERIC_DECL(Id, Parent) \ - BridgedGenericContext Bridged##Id##Decl_asGenericContext( \ - Bridged##Id##Decl decl) { \ - return static_cast(decl.unbridged()); \ - } -#define ITERABLE_GENERIC_DECL(Id, Parent) GENERIC_DECL(Id, Parent) -#include "swift/AST/DeclNodes.def" - static StaticSpellingKind unbridged(BridgedStaticSpelling kind) { return static_cast(kind); } @@ -152,15 +132,6 @@ void BridgedDecl_forEachDeclToHoist(BridgedDecl cDecl, }); } -BridgedDeclContext BridgedDecl_getDeclContext(BridgedDecl decl) { - return decl.unbridged()->getDeclContext(); -} - -void BridgedValueDecl_setAccess(BridgedValueDecl decl, - swift::AccessLevel accessLevel) { - decl.unbridged()->setAccess(accessLevel); -} - BridgedAccessorDecl BridgedAccessorDecl_createParsed( BridgedASTContext cContext, BridgedDeclContext cDeclContext, swift::AccessorKind Kind, BridgedAbstractStorageDecl cStorage, diff --git a/lib/AST/DeclContext.cpp b/lib/AST/DeclContext.cpp index 56dbbe4cf5678..3bcd8110c4699 100644 --- a/lib/AST/DeclContext.cpp +++ b/lib/AST/DeclContext.cpp @@ -1067,7 +1067,7 @@ void IterableDeclContext::addMember(Decl *member, Decl *hint, bool insertAtHead) case IterableDeclContextKind::NominalTypeDecl: { auto nominal = cast(this); nominal->addedMember(member); - assert(member->getDeclContext() == nominal && + assert(member->getDeclContext() == static_cast(nominal) && "Added member to the wrong context"); break; } diff --git a/lib/ASTGen/Sources/ASTGen/Exprs.swift b/lib/ASTGen/Sources/ASTGen/Exprs.swift index 5dfe2c1096148..084886bff1d9b 100644 --- a/lib/ASTGen/Sources/ASTGen/Exprs.swift +++ b/lib/ASTGen/Sources/ASTGen/Exprs.swift @@ -370,7 +370,7 @@ extension ASTGenVisitor { defaultValueInitContext: nil ) param.setSpecifier(.default) - param.asDecl.setImplicit() + param.setImplicit() params.append(param) } } From c12819f88102c98a93802ea226654c35fc37f4b3 Mon Sep 17 00:00:00 2001 From: Daniil Kovalev Date: Mon, 17 Nov 2025 14:13:09 +0300 Subject: [PATCH 4/7] Address review comments --- .../Sources/AST/CMakeLists.txt | 1 + .../Sources/AST/DeclContext.swift | 14 +++ .../Sources/AST/Declarations.swift | 90 ++++++------------- SwiftCompilerSources/Sources/AST/Type.swift | 4 +- .../Sources/SIL/Function.swift | 4 +- SwiftCompilerSources/Sources/SIL/Type.swift | 4 +- include/swift/AST/ASTBridgingImpl.h | 4 +- include/swift/SIL/SILBridgingImpl.h | 8 +- 8 files changed, 55 insertions(+), 74 deletions(-) create mode 100644 SwiftCompilerSources/Sources/AST/DeclContext.swift diff --git a/SwiftCompilerSources/Sources/AST/CMakeLists.txt b/SwiftCompilerSources/Sources/AST/CMakeLists.txt index 303857f3f98d7..00c95fd0b12dc 100644 --- a/SwiftCompilerSources/Sources/AST/CMakeLists.txt +++ b/SwiftCompilerSources/Sources/AST/CMakeLists.txt @@ -11,6 +11,7 @@ add_swift_compiler_module(AST Basic SOURCES Declarations.swift + DeclContext.swift Conformance.swift DiagnosticEngine.swift GenericSignature.swift diff --git a/SwiftCompilerSources/Sources/AST/DeclContext.swift b/SwiftCompilerSources/Sources/AST/DeclContext.swift new file mode 100644 index 0000000000000..d6e04b1b11dff --- /dev/null +++ b/SwiftCompilerSources/Sources/AST/DeclContext.swift @@ -0,0 +1,14 @@ +import ASTBridging + +public protocol DeclContext : AnyObject { + var bridgedDeclContext: BridgedDeclContext { get } +} + +extension DeclContext { + public var astContext: ASTContext { bridgedDeclContext.astContext } +} + +public class UnknownDeclContext : DeclContext { + public var bridgedDeclContext: BridgedDeclContext + public init(bridged: BridgedDeclContext) { bridgedDeclContext = bridged } +} diff --git a/SwiftCompilerSources/Sources/AST/Declarations.swift b/SwiftCompilerSources/Sources/AST/Declarations.swift index 70c3b5bc93218..867327638fd9d 100644 --- a/SwiftCompilerSources/Sources/AST/Declarations.swift +++ b/SwiftCompilerSources/Sources/AST/Declarations.swift @@ -16,48 +16,35 @@ import ASTBridging /// The base class for all declarations in Swift. @_semantics("arc.immortal") public class Decl: CustomStringConvertible, Hashable { - public var bridged: BridgedDeclObj { BridgedDeclObj(SwiftObject(self)) } + final public var bridged: BridgedDeclObj { BridgedDeclObj(SwiftObject(self)) } - public var description: String { String(taking: bridged.getDebugDescription()) } + final public var description: String { String(taking: bridged.getDebugDescription()) } /// The module in which this declaration resides. - public var parentModule: ModuleDecl { bridged.getModuleContext().getAs(ModuleDecl.self) } + final public var parentModule: ModuleDecl { bridged.getModuleContext().getAs(ModuleDecl.self) } /// The parent DeclContext if it is a Decl. - public var parent: Decl? { bridged.getParent().decl } + final public var parent: Decl? { bridged.getParent().decl } // True if this declaration is imported from C/C++/ObjC. - public var hasClangNode: Bool { bridged.hasClangNode() } + final public var hasClangNode: Bool { bridged.hasClangNode() } - public var declContext: DeclContext { + final public var declContext: DeclContext { if let decl = parent { return decl as! DeclContext } - return DeclContextObj(bridged: bridged.getDeclContext()) + return UnknownDeclContext(bridged: bridged.getDeclContext()) } - public var bridgedDecl: BridgedDecl { BridgedDecl(raw: bridged.obj) } + final public var bridgedDecl: BridgedDecl { BridgedDecl(raw: bridged.obj) } public static func ==(lhs: Decl, rhs: Decl) -> Bool { lhs === rhs } - public func hash(into hasher: inout Hasher) { + final public func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } - public func setImplicit() { bridged.setImplicit() } -} - -public protocol DeclContext { - var bridgedDeclContext: BridgedDeclContext { get } -} - -extension DeclContext { - public var astContext: ASTContext { bridgedDeclContext.astContext } -} - -fileprivate class DeclContextObj : DeclContext { - public var bridgedDeclContext: BridgedDeclContext - public init(bridged: BridgedDeclContext) { bridgedDeclContext = bridged } + final public func setImplicit() { bridged.setImplicit() } } public protocol GenericContext: Decl, DeclContext {} @@ -108,9 +95,9 @@ final public class EnumDecl: NominalTypeDecl { public var hasRawType: Bool { bridged.Enum_hasRawType() } public static func create( - _ astContext: ASTContext, declContext: DeclContext, enumKeywordLoc: SourceLoc?, name: String, - nameLoc: SourceLoc?, genericParamList: GenericParamList?, inheritedTypes: [Type], - genericWhereClause: TrailingWhereClause?, braceRange: SourceRange + declContext: DeclContext, enumKeywordLoc: SourceLoc?, name: String, + nameLoc: SourceLoc?, genericParamList: GenericParameterList?, inheritedTypes: [Type], + genericWhereClause: TrailingWhereClause?, braceRange: SourceRange, _ astContext: ASTContext ) -> EnumDecl { name.withCString { strPtr in inheritedTypes.withBridgedArrayRef { types in @@ -208,10 +195,10 @@ final public class EnumElementDecl: ValueDecl { public var name: StringRef { StringRef(bridged: bridged.EnumElementDecl_getNameStr()) } public static func create( - _ astContext: ASTContext, declContext: DeclContext, + declContext: DeclContext, name: Identifier, nameLoc: SourceLoc?, parameterList: ParameterList?, - equalsLoc: SourceLoc?, rawValue: Expr? + equalsLoc: SourceLoc?, rawValue: Expr?, _ astContext: ASTContext ) -> EnumElementDecl { BridgedEnumElementDecl.createParsed( astContext, declContext: declContext.bridgedDeclContext, @@ -282,7 +269,7 @@ public typealias SourceFile = BridgedSourceFile public typealias FileUnit = BridgedFileUnit -public class GenericParamList { +public class GenericParameterList { public var bridged: BridgedGenericParamList public init(bridged: BridgedGenericParamList) { self.bridged = bridged } } @@ -290,26 +277,8 @@ public class GenericParamList { public typealias TrailingWhereClause = BridgedTrailingWhereClause public class ParameterList : RandomAccessCollection { - public class Iterator : IteratorProtocol { - public typealias Element = ParamDecl - private var index : Int = 0 - private let parameterList : ParameterList - init(parameterList : ParameterList) { self.parameterList = parameterList } - public func next() -> Element? { - if index < parameterList.bridged.size { - return parameterList.bridged.get(index).asDecl.declObj.getAs(ParamDecl.self) - } - return nil - } - } - public typealias Index = Int - public var startIndex: Index { 0 } - public var endIndex: Index { bridged.size } - public func index(after i: Index) -> Index { i + 1 } - - public func makeIterator() -> Iterator { - Self.Iterator(parameterList: self) - } + public var startIndex: Int { 0 } + public var endIndex: Int { bridged.size } public var bridged: BridgedParameterList @@ -317,13 +286,13 @@ public class ParameterList : RandomAccessCollection { self.bridged = bridged } - public subscript(_ index: Index) -> ParamDecl { + public subscript(_ index: Int) -> ParamDecl { return bridged.get(index).asDecl.declObj.getAs(ParamDecl.self) } public static func create( - _ astContext: ASTContext, leftParenLoc: SourceLoc?, parameters: [ParamDecl], - rightParenLoc: SourceLoc? + leftParenLoc: SourceLoc?, parameters: [ParamDecl], + rightParenLoc: SourceLoc?, _ astContext: ASTContext ) -> ParameterList { ParameterList(bridged: parameters.map{BridgedParamDecl(raw: $0.bridged.obj)}.withBridgedArrayRef { BridgedParameterList.createParsed( @@ -333,15 +302,15 @@ public class ParameterList : RandomAccessCollection { } } -extension GenericParamList { +extension GenericParameterList { public static func create( - _ astContext: ASTContext, leftAngleLoc: SourceLoc?, parameters: [GenericTypeParamDecl], + leftAngleLoc: SourceLoc?, parameters: [GenericTypeParamDecl], genericWhereClause: TrailingWhereClause?, - rightAngleLoc: SourceLoc? - ) -> GenericParamList { + rightAngleLoc: SourceLoc?, _ astContext: ASTContext + ) -> GenericParameterList { let paramsNew = parameters.map{ ASTBridging.BridgedGenericTypeParamDecl(raw: $0.bridged.obj) } return paramsNew.withBridgedArrayRef { - GenericParamList(bridged: BridgedGenericParamList.createParsed( + GenericParameterList(bridged: BridgedGenericParamList.createParsed( astContext, leftAngleLoc: leftAngleLoc.bridgedLocation, parameters: $0, genericWhereClause: genericWhereClause.bridged, rightAngleLoc: rightAngleLoc.bridgedLocation )) @@ -371,10 +340,7 @@ extension FileUnit { extension ParameterList? { public var bridged: BridgedParameterList? { - if self == nil { - return nil - } - return self!.bridged + return self?.bridged } } @@ -384,7 +350,7 @@ extension BridgedParameterList? { } } -extension GenericParamList? { +extension GenericParameterList? { public var bridged: BridgedNullableGenericParamList { BridgedNullableGenericParamList(raw: self?.bridged.raw) } diff --git a/SwiftCompilerSources/Sources/AST/Type.swift b/SwiftCompilerSources/Sources/AST/Type.swift index 46b31e2c5258c..530dede8e4392 100644 --- a/SwiftCompilerSources/Sources/AST/Type.swift +++ b/SwiftCompilerSources/Sources/AST/Type.swift @@ -67,8 +67,8 @@ public struct Type: TypeProperties, CustomStringConvertible, NoReflectionChildre return Type(bridged: bridged.subst(substitutionMap.bridged)) } - public func mapOutOfContext() -> Type { - return Type(bridged: bridged.mapTypeOutOfContext()) + public func mapOutOfEnvironment() -> Type { + return Type(bridged: bridged.mapOutOfEnvironment()) } /// Returns a stronger canonicalization which folds away equivalent diff --git a/SwiftCompilerSources/Sources/SIL/Function.swift b/SwiftCompilerSources/Sources/SIL/Function.swift index 81bf55a659e16..44a80cbd86a47 100644 --- a/SwiftCompilerSources/Sources/SIL/Function.swift +++ b/SwiftCompilerSources/Sources/SIL/Function.swift @@ -94,8 +94,8 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash return AST.`Type`(bridged: bridged.mapTypeIntoEnvironment(type.bridged)) } - public func mapTypeIntoContext(_ type: Type) -> Type { - return Type(bridged: bridged.mapTypeIntoContext(type.bridged)) + public func mapTypeIntoEnvironment(_ type: Type) -> Type { + return Type(bridged: bridged.mapTypeIntoEnvironment(type.bridged)) } /// Returns true if the function is a definition and not only an external declaration. diff --git a/SwiftCompilerSources/Sources/SIL/Type.swift b/SwiftCompilerSources/Sources/SIL/Type.swift index 646bb066e1bca..8f5c60e2d5f31 100644 --- a/SwiftCompilerSources/Sources/SIL/Type.swift +++ b/SwiftCompilerSources/Sources/SIL/Type.swift @@ -233,8 +233,8 @@ public struct Type : TypeProperties, CustomStringConvertible, NoReflectionChildr return false } - public func mapOutOfContext(in function: Function) -> Type { - rawType.mapOutOfContext().canonical.loweredType(in: function) + public func mapOutOfEnvironment(in function: Function) -> Type { + rawType.mapOutOfEnvironment().canonical.loweredType(in: function) } } diff --git a/include/swift/AST/ASTBridgingImpl.h b/include/swift/AST/ASTBridgingImpl.h index f93b6a42d6859..0bbe728cb9b25 100644 --- a/include/swift/AST/ASTBridgingImpl.h +++ b/include/swift/AST/ASTBridgingImpl.h @@ -718,8 +718,8 @@ bool BridgedASTType::isSILPackElementAddress() const { return unbridged()->castTo()->isElementAddress(); } -BridgedASTType BridgedASTType::mapTypeOutOfContext() const { - return {unbridged()->mapTypeOutOfContext().getPointer()}; +BridgedASTType BridgedASTType::mapOutOfEnvironment() const { + return {unbridged()->mapTypeOutOfEnvironment().getPointer()}; } BridgedCanType diff --git a/include/swift/SIL/SILBridgingImpl.h b/include/swift/SIL/SILBridgingImpl.h index 2bd25bc372e8b..13edc89c48d8d 100644 --- a/include/swift/SIL/SILBridgingImpl.h +++ b/include/swift/SIL/SILBridgingImpl.h @@ -342,8 +342,8 @@ bool BridgedType::isAddress() const { return unbridged().isAddress(); } -BridgedType BridgedType::mapTypeOutOfContext() const { - return unbridged().mapTypeOutOfContext(); +BridgedType BridgedType::mapTypeOutOfEnvironment() const { + return unbridged().mapTypeOutOfEnvironment(); } BridgedCanType BridgedType::getCanType() const { @@ -812,8 +812,8 @@ BridgedASTType BridgedFunction::mapTypeIntoEnvironment(BridgedASTType ty) const return {getFunction()->mapTypeIntoEnvironment(ty.unbridged()).getPointer()}; } -BridgedType BridgedFunction::mapTypeIntoContext(BridgedType ty) const { - return {getFunction()->mapTypeIntoContext(ty.unbridged())}; +BridgedType BridgedFunction::mapTypeIntoEnvironment(BridgedType ty) const { + return {getFunction()->mapTypeIntoEnvironment(ty.unbridged())}; } OptionalBridgedBasicBlock BridgedFunction::getFirstBlock() const { From a172134162e1762729c79223b4b844bb98bc0cf3 Mon Sep 17 00:00:00 2001 From: Daniil Kovalev Date: Tue, 18 Nov 2025 01:46:49 +0300 Subject: [PATCH 5/7] Address review comments --- .../Sources/AST/DeclContext.swift | 14 ++++++ .../Sources/AST/Declarations.swift | 49 ++++++++++++------- .../EmbeddedSwiftDiagnostics.swift | 2 +- include/swift/AST/ASTBridging.h | 5 +- include/swift/AST/ASTBridgingImpl.h | 10 +++- include/swift/AST/ASTBridgingWrappers.def | 2 +- 6 files changed, 61 insertions(+), 21 deletions(-) diff --git a/SwiftCompilerSources/Sources/AST/DeclContext.swift b/SwiftCompilerSources/Sources/AST/DeclContext.swift index d6e04b1b11dff..0c1a4a7a27132 100644 --- a/SwiftCompilerSources/Sources/AST/DeclContext.swift +++ b/SwiftCompilerSources/Sources/AST/DeclContext.swift @@ -1,3 +1,15 @@ +//===--- DeclContext.swift -----------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + import ASTBridging public protocol DeclContext : AnyObject { @@ -8,6 +20,8 @@ extension DeclContext { public var astContext: ASTContext { bridgedDeclContext.astContext } } +// Used for DeclContext classes which are not Decls and are not bridged, yet. E.g. `FileUnit`. +// TODO: once we have bridged those DeclContext classes, get rid of UnknownDeclContext public class UnknownDeclContext : DeclContext { public var bridgedDeclContext: BridgedDeclContext public init(bridged: BridgedDeclContext) { bridgedDeclContext = bridged } diff --git a/SwiftCompilerSources/Sources/AST/Declarations.swift b/SwiftCompilerSources/Sources/AST/Declarations.swift index 867327638fd9d..a585fe5ff76d2 100644 --- a/SwiftCompilerSources/Sources/AST/Declarations.swift +++ b/SwiftCompilerSources/Sources/AST/Declarations.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors +// Copyright (c) 2014 - 2025 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information @@ -23,19 +23,22 @@ public class Decl: CustomStringConvertible, Hashable { /// The module in which this declaration resides. final public var parentModule: ModuleDecl { bridged.getModuleContext().getAs(ModuleDecl.self) } - /// The parent DeclContext if it is a Decl. - final public var parent: Decl? { bridged.getParent().decl } - - // True if this declaration is imported from C/C++/ObjC. - final public var hasClangNode: Bool { bridged.hasClangNode() } - - final public var declContext: DeclContext { - if let decl = parent { + /// The parent DeclContext. + final public var parentDeclContext: DeclContext? { + if let decl = bridged.getParent().decl { return decl as! DeclContext } - return UnknownDeclContext(bridged: bridged.getDeclContext()) + if let bridgedDeclContext = BridgedDeclContext(bridged: bridged.getDeclContext()) { + // A DeclContext which is not a Decl. + // TODO: once we have bridged those DeclContext classes, get rid of UnknownDeclContext + return UnknownDeclContext(bridged: bridgedDeclContext) + } + return nil } + // True if this declaration is imported from C/C++/ObjC. + final public var hasClangNode: Bool { bridged.hasClangNode() } + final public var bridgedDecl: BridgedDecl { BridgedDecl(raw: bridged.obj) } public static func ==(lhs: Decl, rhs: Decl) -> Bool { lhs === rhs } @@ -153,7 +156,9 @@ final public class GenericTypeParamDecl: TypeDecl { final public class AssociatedTypeDecl: TypeDecl {} -final public class ModuleDecl: TypeDecl {} +final public class ModuleDecl: TypeDecl, DeclContext { + public var bridgedDeclContext: BridgedDeclContext { bridged.asModuleDecl() } +} public class AbstractStorageDecl: ValueDecl { final public var isConst: Bool { bridged.AbstractStorage_isConst() } @@ -171,9 +176,9 @@ final public class ParamDecl: VarDecl { } } -final public class SubscriptDecl: AbstractStorageDecl {} +final public class SubscriptDecl: AbstractStorageDecl, GenericContext {} -public class AbstractFunctionDecl: ValueDecl { +public class AbstractFunctionDecl: ValueDecl, GenericContext { public var isOverridden: Bool { bridged.AbstractFunction_isOverridden() } } @@ -209,9 +214,11 @@ final public class EnumElementDecl: ValueDecl { } } -final public class ExtensionDecl: Decl {} +final public class ExtensionDecl: Decl, GenericContext {} -final public class TopLevelCodeDecl: Decl {} +final public class TopLevelCodeDecl: Decl, DeclContext { + public var bridgedDeclContext: BridgedDeclContext { bridged.asTopLevelCodeDecl() } +} final public class ImportDecl: Decl {} @@ -320,9 +327,17 @@ extension GenericParameterList { extension BridgedDecl { public var declObj: BridgedDeclObj { - BridgedDeclObj(SwiftObject(raw.bindMemory(to: BridgedSwiftObject.self, capacity: 1))) + BridgedDeclObj(self) + } +} + +extension BridgedDeclContext { + public init?(bridged: BridgedNullableDeclContext) { + guard let raw = bridged.raw else { + return nil + } + self.init(raw: raw) } - public var decl: Decl { declObj.decl } } extension SourceFile { diff --git a/SwiftCompilerSources/Sources/Optimizer/ModulePasses/EmbeddedSwiftDiagnostics.swift b/SwiftCompilerSources/Sources/Optimizer/ModulePasses/EmbeddedSwiftDiagnostics.swift index b2a3a1e0bd190..a765a9bb3e607 100644 --- a/SwiftCompilerSources/Sources/Optimizer/ModulePasses/EmbeddedSwiftDiagnostics.swift +++ b/SwiftCompilerSources/Sources/Optimizer/ModulePasses/EmbeddedSwiftDiagnostics.swift @@ -347,7 +347,7 @@ private extension Function { if decl is DestructorDecl || decl is ConstructorDecl { return 4 } - if let parent = decl.parent, parent is ClassDecl { + if let parent = decl.parentDeclContext, parent is ClassDecl { return 2 } } diff --git a/include/swift/AST/ASTBridging.h b/include/swift/AST/ASTBridging.h index 00e0dd4911ea3..6fbc8374d6550 100644 --- a/include/swift/AST/ASTBridging.h +++ b/include/swift/AST/ASTBridging.h @@ -318,12 +318,15 @@ struct BridgedDeclObj { #endif BridgedDeclObj(SwiftObject obj) : obj(obj) {} + BridgedDeclObj(BridgedDecl decl) : obj(decl.unbridged()) {} BridgedOwnedString getDebugDescription() const; BRIDGED_INLINE swift::SourceLoc getLoc() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclObj getModuleContext() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedDeclObj getParent() const; - SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclContext getDeclContext() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNullableDeclContext getDeclContext() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclContext asGenericContext() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclContext asTopLevelCodeDecl() const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclContext asModuleDecl() const; BRIDGED_INLINE void setImplicit() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef Type_getName() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef Value_getUserFacingName() const; diff --git a/include/swift/AST/ASTBridgingImpl.h b/include/swift/AST/ASTBridgingImpl.h index 0bbe728cb9b25..f9bd78782635f 100644 --- a/include/swift/AST/ASTBridgingImpl.h +++ b/include/swift/AST/ASTBridgingImpl.h @@ -177,7 +177,7 @@ OptionalBridgedDeclObj BridgedDeclObj::getParent() const { return {unbridged()->getDeclContext()->getAsDecl()}; } -BridgedDeclContext BridgedDeclObj::getDeclContext() const { +BridgedNullableDeclContext BridgedDeclObj::getDeclContext() const { return {unbridged()->getDeclContext()}; } @@ -185,6 +185,14 @@ BridgedDeclContext BridgedDeclObj::asGenericContext() const { return {static_cast(getAs())}; } +BridgedDeclContext BridgedDeclObj::asTopLevelCodeDecl() const { + return {static_cast(getAs())}; +} + +BridgedDeclContext BridgedDeclObj::asModuleDecl() const { + return {static_cast(getAs())}; +} + void BridgedDeclObj::setImplicit() const { unbridged()->setImplicit(); } diff --git a/include/swift/AST/ASTBridgingWrappers.def b/include/swift/AST/ASTBridgingWrappers.def index 619f70fb033ed..66ac89748c40a 100644 --- a/include/swift/AST/ASTBridgingWrappers.def +++ b/include/swift/AST/ASTBridgingWrappers.def @@ -94,7 +94,7 @@ // Some of the base classes need to be nullable to allow them to be used as // optional parameters. AST_BRIDGING_WRAPPER_NULLABLE(Decl) -AST_BRIDGING_WRAPPER_NONNULL(DeclContext) +AST_BRIDGING_WRAPPER_NULLABLE(DeclContext) AST_BRIDGING_WRAPPER_NONNULL(GenericContext) AST_BRIDGING_WRAPPER_NONNULL(FileUnit) AST_BRIDGING_WRAPPER_NULLABLE(SourceFile) From c0935fcca14bd4aa89aaf0ce91ae72b5eba122b2 Mon Sep 17 00:00:00 2001 From: Daniil Kovalev Date: Tue, 18 Nov 2025 22:50:44 +0300 Subject: [PATCH 6/7] Fix build --- include/swift/AST/ASTBridging.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/include/swift/AST/ASTBridging.h b/include/swift/AST/ASTBridging.h index 6fbc8374d6550..624e7491de19f 100644 --- a/include/swift/AST/ASTBridging.h +++ b/include/swift/AST/ASTBridging.h @@ -45,6 +45,7 @@ class AvailabilityDomainOrIdentifier; class Argument; class ASTContext; struct ASTNode; +class CanGenericSignature; struct CaptureListEntry; class DeclAttributes; class DeclBaseName; @@ -318,7 +319,8 @@ struct BridgedDeclObj { #endif BridgedDeclObj(SwiftObject obj) : obj(obj) {} - BridgedDeclObj(BridgedDecl decl) : obj(decl.unbridged()) {} + BridgedDeclObj(BridgedDecl decl) + : obj(static_cast(decl.unbridged())) {} BridgedOwnedString getDebugDescription() const; BRIDGED_INLINE swift::SourceLoc getLoc() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclObj getModuleContext() const; From 5bd3d80ec9e5bf5d18f087a4d2d882ffba08e939 Mon Sep 17 00:00:00 2001 From: Daniil Kovalev Date: Wed, 19 Nov 2025 04:15:12 +0300 Subject: [PATCH 7/7] Fix build --- include/swift/AST/ASTBridging.h | 3 +-- include/swift/AST/ASTBridgingImpl.h | 3 +++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/include/swift/AST/ASTBridging.h b/include/swift/AST/ASTBridging.h index 624e7491de19f..9f8c1ccfaa20a 100644 --- a/include/swift/AST/ASTBridging.h +++ b/include/swift/AST/ASTBridging.h @@ -319,8 +319,7 @@ struct BridgedDeclObj { #endif BridgedDeclObj(SwiftObject obj) : obj(obj) {} - BridgedDeclObj(BridgedDecl decl) - : obj(static_cast(decl.unbridged())) {} + BRIDGED_INLINE BridgedDeclObj(BridgedDecl decl); BridgedOwnedString getDebugDescription() const; BRIDGED_INLINE swift::SourceLoc getLoc() const; SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeclObj getModuleContext() const; diff --git a/include/swift/AST/ASTBridgingImpl.h b/include/swift/AST/ASTBridgingImpl.h index f9bd78782635f..2e236d083837d 100644 --- a/include/swift/AST/ASTBridgingImpl.h +++ b/include/swift/AST/ASTBridgingImpl.h @@ -165,6 +165,9 @@ BridgedFileUnit_castToSourceFile(BridgedFileUnit fileUnit) { // MARK: BridgedDeclObj //===----------------------------------------------------------------------===// +BridgedDeclObj::BridgedDeclObj(BridgedDecl decl) + : obj(static_cast(decl.unbridged())) {} + swift::SourceLoc BridgedDeclObj::getLoc() const { return unbridged()->getLoc(); }