From 18f56c9de54318fb0357c3ba4b3fba06e370bb85 Mon Sep 17 00:00:00 2001 From: Ben Barham Date: Sun, 21 May 2023 12:23:23 -0700 Subject: [PATCH] [NFC][ASTGen] Add wrapping structs for commonly bridged types Adds wrapping structs for a bunch of commonly bridged types (but not all the AST nodes yet). --- include/swift/AST/CASTBridging.h | 390 +++++--- lib/AST/CASTBridging.cpp | 918 ++++++++++-------- lib/ASTGen/Sources/ASTGen/ASTGen.swift | 22 +- lib/ASTGen/Sources/ASTGen/Decls.swift | 56 +- lib/ASTGen/Sources/ASTGen/Diagnostics.swift | 119 ++- lib/ASTGen/Sources/ASTGen/Exprs.swift | 46 +- lib/ASTGen/Sources/ASTGen/Generics.swift | 22 +- lib/ASTGen/Sources/ASTGen/Literals.swift | 22 +- lib/ASTGen/Sources/ASTGen/Misc.swift | 49 + lib/ASTGen/Sources/ASTGen/PluginHost.swift | 63 +- lib/ASTGen/Sources/ASTGen/SourceFile.swift | 3 +- lib/ASTGen/Sources/ASTGen/SourceManager.swift | 27 +- lib/ASTGen/Sources/ASTGen/Stmts.swift | 10 +- lib/ASTGen/Sources/ASTGen/Types.swift | 105 +- 14 files changed, 1011 insertions(+), 841 deletions(-) diff --git a/include/swift/AST/CASTBridging.h b/include/swift/AST/CASTBridging.h index 9647ddf561f14..4f181c1d1f916 100644 --- a/include/swift/AST/CASTBridging.h +++ b/include/swift/AST/CASTBridging.h @@ -42,27 +42,46 @@ SWIFT_BEGIN_NULLABILITY_ANNOTATIONS typedef long SwiftInt; typedef unsigned long SwiftUInt; +typedef struct { + const unsigned char *_Nullable data; + long length; +} BridgedString; + typedef struct { const void *_Nullable data; long numElements; } BridgedArrayRef; +typedef struct BridgedASTContext { + void *raw; +} BridgedASTContext; + +typedef struct BridgedDeclContext { + void *raw; +} BridgedDeclContext; + +typedef struct BridgedSourceLoc { + const void *_Nullable raw; +} BridgedSourceLoc; + +typedef struct BridgedIdentifier { + const void *_Nullable raw; +} BridgedIdentifier; + typedef struct { void *start; SwiftInt byteLength; } BridgedCharSourceRange; -typedef void *BridgedIdentifier; - typedef struct { - BridgedIdentifier _Nullable Name; - void *_Nullable NameLoc; - BridgedIdentifier _Nullable SecondName; - void *_Nullable SecondNameLoc; - void *_Nullable UnderscoreLoc; - void *_Nullable ColonLoc; + BridgedIdentifier Name; + BridgedSourceLoc NameLoc; + BridgedIdentifier SecondName; + BridgedSourceLoc SecondNameLoc; + BridgedSourceLoc UnderscoreLoc; + BridgedSourceLoc ColonLoc; void *Type; - void *_Nullable TrailingCommaLoc; + BridgedSourceLoc TrailingCommaLoc; } BridgedTupleTypeElement; typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedRequirementReprKind : long { @@ -84,7 +103,7 @@ typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedRequirementReprKind : long { } BridgedRequirementReprKind; typedef struct { - void *_Nullable SeparatorLoc; + BridgedSourceLoc SeparatorLoc; BridgedRequirementReprKind Kind; void *FirstType; void *SecondType; @@ -100,7 +119,13 @@ typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedDiagnosticSeverity : long { BridgedNote, } BridgedDiagnosticSeverity; -typedef void* BridgedDiagnostic; +typedef struct BridgedDiagnostic { + void *raw; +} BridgedDiagnostic; + +typedef struct BridgedDiagnosticEngine { + void *raw; +} BridgedDiagnosticEngine; typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedMacroDefinitionKind : long { /// An expanded macro. @@ -123,7 +148,6 @@ typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedAttributedTypeSpecifier : long BridgedAttributedTypeSpecifierIsolated, } BridgedAttributedTypeSpecifier; - // Bridged type attribute kinds, which mirror TypeAttrKind exactly. typedef enum ENUM_EXTENSIBILITY_ATTR(closed) BridgedTypeAttrKind : long { BridgedTypeAttrKind_autoclosure, @@ -176,11 +200,37 @@ typedef enum ENUM_EXTENSIBILITY_ATTR(closed) BridgedTypeAttrKind : long { BridgedTypeAttrKind_Count } BridgedTypeAttrKind; +typedef enum ENUM_EXTENSIBILITY_ATTR(open) ASTNodeKind : long { + ASTNodeKindExpr, + ASTNodeKindStmt, + ASTNodeKindDecl +} ASTNodeKind; + +typedef struct BridgedASTNode { + void *ptr; + ASTNodeKind kind; +} BridgedASTNode; + +typedef struct BridgedFuncDecl { + BridgedDeclContext declContext; + void *funcDecl; + void *decl; +} BridgedFuncDecl; + +typedef struct BridgedDeclContextAndDecl { + BridgedDeclContext declContext; + void *nominalDecl; + void *decl; +} BridgedDeclContextAndDecl; + +typedef struct BridgedTypeAttributes { + void *raw; +} BridgedTypeAttributes; + #ifdef __cplusplus extern "C" { #define _Bool bool - #endif // Diagnostics @@ -190,192 +240,212 @@ extern "C" { /// /// \returns a diagnostic instance that can be extended with additional /// information and then must be finished via \c SwiftDiagnostic_finish. -BridgedDiagnostic SwiftDiagnostic_create(void *diagnosticEngine, - BridgedDiagnosticSeverity severity, - const void *_Nullable sourceLoc, - const unsigned char *_Nullable text, - long textLen); +BridgedDiagnostic Diagnostic_create(BridgedDiagnosticEngine cDiags, + BridgedDiagnosticSeverity severity, + BridgedSourceLoc cLoc, BridgedString cText); /// Highlight a source range as part of the diagnostic. -void SwiftDiagnostic_highlight( - BridgedDiagnostic diag, const void *_Nullable startLoc, const void *_Nullable endLoc); +void Diagnostic_highlight(BridgedDiagnostic cDiag, BridgedSourceLoc cStartLoc, + BridgedSourceLoc cEndLoc); /// Add a Fix-It to replace a source range as part of the diagnostic. -void SwiftDiagnostic_fixItReplace(BridgedDiagnostic diag, - const void *_Nullable replaceStartLoc, - const void *_Nullable replaceEndLoc, - const unsigned char *_Nullable newText, - long newTextLen); +void Diagnostic_fixItReplace(BridgedDiagnostic cDiag, + BridgedSourceLoc cStartLoc, + BridgedSourceLoc cEndLoc, + BridgedString cReplaceText); /// Finish the given diagnostic and emit it. -void SwiftDiagnostic_finish(BridgedDiagnostic diag); +void Diagnostic_finish(BridgedDiagnostic cDiag); -BridgedIdentifier -SwiftASTContext_getIdentifier(void *ctx, const unsigned char *_Nullable str, - long len); +BridgedIdentifier ASTContext_getIdentifier(BridgedASTContext cContext, + BridgedString cStr); -void *SwiftImportDecl_create(void *, void *, void *, char, void *, - BridgedArrayRef, BridgedArrayRef); +void *ImportDecl_create(BridgedASTContext cContext, + BridgedDeclContext cDeclContext, + BridgedSourceLoc cImportLoc, char kind, + BridgedSourceLoc cKindLoc, BridgedArrayRef path, + BridgedArrayRef cPathLocs); -void *SwiftTopLevelCodeDecl_createStmt(void *ctx, void *DC, void *startLoc, - void *element, void *endLoc); -void *SwiftTopLevelCodeDecl_createExpr(void *ctx, void *DC, void *startLoc, - void *element, void *endLoc); +void *TopLevelCodeDecl_createStmt(BridgedASTContext cContext, + BridgedDeclContext cDeclContext, + BridgedSourceLoc cStartLoc, void *element, + BridgedSourceLoc cEndLoc); +void *TopLevelCodeDecl_createExpr(BridgedASTContext cContext, + BridgedDeclContext cDeclContext, + BridgedSourceLoc cStartLoc, void *element, + BridgedSourceLoc cEndLoc); -void *ReturnStmt_create(void *ctx, void *loc, void *_Nullable expr); +void *ReturnStmt_create(BridgedASTContext cContext, BridgedSourceLoc cLoc, + void *_Nullable expr); -void *SwiftSequenceExpr_create(void *ctx, BridgedArrayRef exprs); +void *SequenceExpr_create(BridgedASTContext cContext, BridgedArrayRef exprs); -void *SwiftTupleExpr_create(void *ctx, void *lparen, BridgedArrayRef subs, - BridgedArrayRef names, - BridgedArrayRef nameLocs, - void *rparen); +void *TupleExpr_create(BridgedASTContext cContext, BridgedSourceLoc cLParen, + BridgedArrayRef subs, BridgedArrayRef names, + BridgedArrayRef cNameLocs, BridgedSourceLoc cRParen); -void *SwiftFunctionCallExpr_create(void *ctx, void *fn, void *args); +void *FunctionCallExpr_create(BridgedASTContext cContext, void *fn, void *args); -void *SwiftIdentifierExpr_create(void *ctx, BridgedIdentifier base, void *loc); +void *IdentifierExpr_create(BridgedASTContext cContext, BridgedIdentifier base, + BridgedSourceLoc cLoc); -void *SwiftStringLiteralExpr_create(void *ctx, - const unsigned char *_Nullable string, - long len, void *TokenLoc); +void *StringLiteralExpr_create(BridgedASTContext cContext, BridgedString cStr, + BridgedSourceLoc cTokenLoc); -void *SwiftIntegerLiteralExpr_create(void *ctx, - const unsigned char *_Nullable string, - long len, void *TokenLoc); +void *IntegerLiteralExpr_create(BridgedASTContext cContext, BridgedString cStr, + BridgedSourceLoc cTokenLoc); -void *SwiftBooleanLiteralExpr_create(void *ctx, _Bool value, void *TokenLoc); +void *BooleanLiteralExpr_create(BridgedASTContext cContext, _Bool value, + BridgedSourceLoc cTokenLoc); -void *ArrayExpr_create(void *ctx, void *lLoc, BridgedArrayRef elements, - BridgedArrayRef commas, void *rLoc); +void *ArrayExpr_create(BridgedASTContext cContext, BridgedSourceLoc cLLoc, + BridgedArrayRef elements, BridgedArrayRef commas, + BridgedSourceLoc cRLoc); -void *SwiftVarDecl_create(void *ctx, BridgedIdentifier _Nullable name, - void *initExpr, void *loc, _Bool isStatic, - _Bool isLet, void *dc); +void *VarDecl_create(BridgedASTContext cContext, void *nameExpr, void *initExpr, + BridgedSourceLoc cLoc, _Bool isStatic, _Bool isLet, + BridgedDeclContext cDeclContext); -void *SingleValueStmtExpr_createWithWrappedBranches(void *ctx, void *S, - void *DC, _Bool mustBeExpr); +void *SingleValueStmtExpr_createWithWrappedBranches( + BridgedASTContext cContext, void *S, BridgedDeclContext cDeclContext, + _Bool mustBeExpr); -void *IfStmt_create(void *ctx, void *ifLoc, void *cond, void *_Nullable then, - void *_Nullable elseLoc, void *_Nullable elseStmt); - -typedef enum ENUM_EXTENSIBILITY_ATTR(open) ASTNodeKind : long { - ASTNodeKindExpr, - ASTNodeKindStmt, - ASTNodeKindDecl -} ASTNodeKind; +void *IfStmt_create(BridgedASTContext cContext, BridgedSourceLoc cIfLoc, + void *cond, void *_Nullable then, BridgedSourceLoc cElseLoc, + void *_Nullable elseStmt); -struct ASTNodeBridged { - void *ptr; - ASTNodeKind kind; -}; +void *BraceStmt_create(BridgedASTContext cContext, BridgedSourceLoc cLBLoc, + BridgedArrayRef elements, BridgedSourceLoc cRBLoc); -void *BraceStmt_create(void *ctx, void *lbloc, BridgedArrayRef elements, - void *rbloc); +BridgedSourceLoc SourceLoc_advanced(BridgedSourceLoc cLoc, long len); -void *BridgedSourceLoc_advanced(void *loc, long len); +void *ParamDecl_create(BridgedASTContext cContext, BridgedSourceLoc cLoc, + BridgedSourceLoc cArgLoc, BridgedIdentifier argName, + BridgedSourceLoc cParamLoc, BridgedIdentifier paramName, + void *_Nullable type, BridgedDeclContext cDeclContext); -void *ParamDecl_create(void *ctx, void *loc, void *_Nullable argLoc, - void *_Nullable argName, void *_Nullable paramLoc, - void *_Nullable paramName, void *_Nullable type, - void *declContext); -struct FuncDeclBridged { - void *declContext; - void *funcDecl; - void *decl; -}; - -struct FuncDeclBridged -FuncDecl_create(void *ctx, void *staticLoc, _Bool isStatic, void *funcLoc, - BridgedIdentifier name, void *nameLoc, _Bool isAsync, - void *_Nullable asyncLoc, _Bool throws, - void *_Nullable throwsLoc, void *paramLLoc, - BridgedArrayRef params, void *paramRLoc, - void *_Nullable returnType, void *declContext); +struct BridgedFuncDecl +FuncDecl_create(BridgedASTContext cContext, BridgedSourceLoc cStaticLoc, + _Bool isStatic, BridgedSourceLoc cFuncLoc, + BridgedIdentifier name, BridgedSourceLoc cNameLoc, + _Bool isAsync, BridgedSourceLoc cAsyncLoc, _Bool throws, + BridgedSourceLoc cThrowsLoc, BridgedSourceLoc cParamLLoc, + BridgedArrayRef params, BridgedSourceLoc cParamRLoc, + void *_Nullable returnType, BridgedDeclContext cDeclContext); void FuncDecl_setBody(void *fn, void *body); -void *SimpleIdentTypeRepr_create(void *ctx, void *loc, BridgedIdentifier id); +void *SimpleIdentTypeRepr_create(BridgedASTContext cContext, + BridgedSourceLoc cLoc, BridgedIdentifier id); -void *UnresolvedDotExpr_create(void *ctx, void *base, void *dotLoc, - BridgedIdentifier name, void *nameLoc); +void *UnresolvedDotExpr_create(BridgedASTContext cContext, void *base, + BridgedSourceLoc cDotLoc, BridgedIdentifier name, + BridgedSourceLoc cNameLoc); -void *ClosureExpr_create(void *ctx, void *body, void *dc); +void *ClosureExpr_create(BridgedASTContext cContext, void *body, + BridgedDeclContext cDeclContext); void NominalTypeDecl_setMembers(void *decl, BridgedArrayRef members); -struct DeclContextAndDecl { - void *declContext; - void *nominalDecl; - void *decl; -}; - -struct DeclContextAndDecl -StructDecl_create(void *ctx, void *loc, BridgedIdentifier name, void *nameLoc, - void *_Nullable genericParams, void *dc); -struct DeclContextAndDecl ClassDecl_create(void *ctx, void *loc, +BridgedDeclContextAndDecl StructDecl_create(BridgedASTContext cContext, + BridgedSourceLoc cLoc, + BridgedIdentifier name, + BridgedSourceLoc cNameLoc, + void *_Nullable genericParams, + BridgedDeclContext cDeclContext); +BridgedDeclContextAndDecl ClassDecl_create(BridgedASTContext cContext, + BridgedSourceLoc cLoc, BridgedIdentifier name, - void *nameLoc, void *dc); - -void *ArrayTypeRepr_create(void *ctx, void *base, void *lsquareLoc, - void *rsquareLoc); -void *DictionaryTypeRepr_create(void *ctx, void *keyType, void *valueType, - void *lsquareLoc, void *colonloc, - void *rsquareLoc); -void *OptionalTypeRepr_create(void *ctx, void *base, void *questionLoc); -void *ImplicitlyUnwrappedOptionalTypeRepr_create(void *ctx, void *base, - void *exclamationLoc); -void *MetatypeTypeRepr_create(void *ctx, void *baseType, void *typeLoc); -void *ProtocolTypeRepr_create(void *ctx, void *baseType, void *protoLoc); - -BridgedTypeAttrKind getBridgedTypeAttrKindFromString( - const unsigned char * _Nullable str, long len); - -typedef void *BridgedTypeAttributes; -BridgedTypeAttributes BridgedTypeAttributes_create(void); -void BridgedTypeAttributes_addSimpleAttr( - BridgedTypeAttributes typeAttributes, BridgedTypeAttrKind kind, void *atLoc, void *attrLoc); -void *AttributedTypeRepr_create(void *ctx, void *base, BridgedTypeAttributes typeAttributes); - -void *AttributedTypeSpecifierRepr_create( - void *ctx, void *base, BridgedAttributedTypeSpecifier specifier, void *specifierLoc); -void *VarargTypeRepr_create(void *ctx, void *base, void *ellipsisLocPtr); -void *PackExpansionTypeRepr_create(void *ctx, void *base, void *repeatLoc); -void *TupleTypeRepr_create(void *ctx, BridgedArrayRef elements, void *lParenLoc, - void *rParenLoc); -void *MemberTypeRepr_create(void *ctx, void *baseComponent, - BridgedArrayRef bridgedMemberComponents); -void *GenericIdentTypeRepr_create(void *ctx, BridgedIdentifier name, - void *nameLoc, BridgedArrayRef genericArgs, - void *lAngle, void *rAngle); -void *EmptyCompositionTypeRepr_create(void *ctx, void *anyLoc); -void *CompositionTypeRepr_create(void *ctx, BridgedArrayRef types, - void *firstTypeLoc, void *firstAmpLoc); -void *FunctionTypeRepr_create(void *ctx, void *argsTy, void *_Nullable asyncLoc, - void *_Nullable throwsLoc, void *arrowLoc, - void *returnType); -void *NamedOpaqueReturnTypeRepr_create(void *ctx, void *baseTy); -void *OpaqueReturnTypeRepr_create(void *ctx, void *opaqueLoc, void *baseTy); -void *ExistentialTypeRepr_create(void *ctx, void *anyLoc, void *baseTy); -void *GenericParamList_create(void *ctx, void *lAngleLoc, - BridgedArrayRef params, void *_Nullable whereLoc, - BridgedArrayRef reqs, void *rAngleLoc); -void *GenericTypeParamDecl_create(void *ctx, void *declContext, - BridgedIdentifier name, void *nameLoc, - void *_Nullable eachLoc, long index, + BridgedSourceLoc cNameLoc, + BridgedDeclContext cDeclContext); + +void *GenericParamList_create(BridgedASTContext cContext, + BridgedSourceLoc cLAngleLoc, + BridgedArrayRef params, + BridgedSourceLoc cWhereLoc, BridgedArrayRef reqs, + BridgedSourceLoc cRAngleLoc); +void *GenericTypeParamDecl_create(BridgedASTContext cContext, + BridgedDeclContext cDeclContext, + BridgedIdentifier name, + BridgedSourceLoc cNameLoc, + BridgedSourceLoc cEachLoc, long index, _Bool isParameterPack); -void GenericTypeParamDecl_setInheritedType(void *ctx, void *Param, void *ty); +void GenericTypeParamDecl_setInheritedType(BridgedASTContext cContext, + void *Param, void *ty); -struct DeclContextAndDecl TypeAliasDecl_create(void *ctx, void *declContext, - void *aliasLoc, void *equalLoc, +BridgedDeclContextAndDecl TypeAliasDecl_create(BridgedASTContext cContext, + BridgedDeclContext cDeclContext, + BridgedSourceLoc cAliasLoc, + BridgedSourceLoc cEqualLoc, BridgedIdentifier name, - void *nameLoc, + BridgedSourceLoc cNameLoc, void *_Nullable genericParams); void TypeAliasDecl_setUnderlyingTypeRepr(void *decl, void *underlyingType); -void TopLevelCodeDecl_dump(void *); -void Expr_dump(void *); -void Decl_dump(void *); -void Stmt_dump(void *); -void Type_dump(void *); +BridgedTypeAttrKind TypeAttrKind_fromString(BridgedString cStr); +BridgedTypeAttributes TypeAttributes_create(void); +void TypeAttributes_addSimpleAttr(BridgedTypeAttributes cAttributes, + BridgedTypeAttrKind kind, + BridgedSourceLoc cAtLoc, + BridgedSourceLoc cAttrLoc); + +void *ArrayTypeRepr_create(BridgedASTContext cContext, void *base, + BridgedSourceLoc cLSquareLoc, + BridgedSourceLoc cRSquareLoc); +void *AttributedTypeRepr_create(BridgedASTContext cContext, void *base, + BridgedTypeAttributes cAttributes); +void * +AttributedTypeSpecifierRepr_create(BridgedASTContext cContext, void *base, + BridgedAttributedTypeSpecifier specifier, + BridgedSourceLoc cSpecifierLoc); +void *CompositionTypeRepr_create(BridgedASTContext cContext, + BridgedArrayRef types, + BridgedSourceLoc cFirstTypeLoc, + BridgedSourceLoc cFirstAmpLoc); +void *DictionaryTypeRepr_create(BridgedASTContext cContext, void *keyType, + void *valueType, BridgedSourceLoc cLSquareLoc, + BridgedSourceLoc cColonloc, + BridgedSourceLoc cRSquareLoc); +void *EmptyCompositionTypeRepr_create(BridgedASTContext cContext, + BridgedSourceLoc cAnyLoc); +void *FunctionTypeRepr_create(BridgedASTContext cContext, void *argsTy, + BridgedSourceLoc cAsyncLoc, + BridgedSourceLoc cThrowsLoc, + BridgedSourceLoc cArrowLoc, void *returnType); +void *GenericIdentTypeRepr_create(BridgedASTContext cContext, + BridgedIdentifier name, + BridgedSourceLoc cNameLoc, + BridgedArrayRef genericArgs, + BridgedSourceLoc cLAngleLoc, + BridgedSourceLoc cRAngleLoc); +void *OptionalTypeRepr_create(BridgedASTContext cContext, void *base, + BridgedSourceLoc cQuestionLoc); +void *ImplicitlyUnwrappedOptionalTypeRepr_create( + BridgedASTContext cContext, void *base, BridgedSourceLoc cExclamationLoc); +void *MemberTypeRepr_create(BridgedASTContext cContext, void *baseComponent, + BridgedArrayRef bridgedMemberComponents); +void *MetatypeTypeRepr_create(BridgedASTContext cContext, void *baseType, + BridgedSourceLoc cTypeLoc); +void *ProtocolTypeRepr_create(BridgedASTContext cContext, void *baseType, + BridgedSourceLoc cProtoLoc); +void *PackExpansionTypeRepr_create(BridgedASTContext cContext, void *base, + BridgedSourceLoc cRepeatLoc); +void *TupleTypeRepr_create(BridgedASTContext cContext, BridgedArrayRef elements, + BridgedSourceLoc cLParenLoc, + BridgedSourceLoc cRParenLoc); +void *NamedOpaqueReturnTypeRepr_create(BridgedASTContext cContext, + void *baseTy); +void *OpaqueReturnTypeRepr_create(BridgedASTContext cContext, + BridgedSourceLoc cOpaqueLoc, void *baseTy); +void *ExistentialTypeRepr_create(BridgedASTContext cContext, + BridgedSourceLoc cAnyLoc, void *baseTy); +void *VarargTypeRepr_create(BridgedASTContext cContext, void *base, + BridgedSourceLoc cEllipsisLoc); + +void TopLevelCodeDecl_dump(void *decl); +void Expr_dump(void *expr); +void Decl_dump(void *decl); +void Stmt_dump(void *statement); +void Type_dump(void *type); //===----------------------------------------------------------------------===// // Plugins diff --git a/lib/AST/CASTBridging.cpp b/lib/AST/CASTBridging.cpp index b76dcfa8e5cc8..76b9b484e8f80 100644 --- a/lib/AST/CASTBridging.cpp +++ b/lib/AST/CASTBridging.cpp @@ -15,46 +15,91 @@ using namespace swift; +namespace { +struct BridgedDiagnosticImpl { + InFlightDiagnostic inFlight; + std::vector textBlobs; + + BridgedDiagnosticImpl(const BridgedDiagnosticImpl &) = delete; + BridgedDiagnosticImpl(BridgedDiagnosticImpl &&) = delete; + BridgedDiagnosticImpl &operator=(const BridgedDiagnosticImpl &) = delete; + BridgedDiagnosticImpl &operator=(BridgedDiagnosticImpl &&) = delete; + + ~BridgedDiagnosticImpl() { + inFlight.flush(); + for (auto text : textBlobs) { + free((void *)text.data()); + } + } +}; +} // namespace + template -inline llvm::ArrayRef getArrayRef(BridgedArrayRef bridged) { +static inline llvm::ArrayRef convertArrayRef(const BridgedArrayRef bridged) { return {static_cast(bridged.data), size_t(bridged.numElements)}; } -static SourceLoc getSourceLocFromPointer(const void *loc) { - auto smLoc = llvm::SMLoc::getFromPointer((const char *)loc); +static inline StringRef convertString(BridgedString cStr) { + return StringRef{reinterpret_cast(cStr.data), + size_t(cStr.length)}; +} + +static inline ASTContext &convertASTContext(BridgedASTContext cContext) { + return *static_cast(cContext.raw); +} + +static inline DeclContext *convertDeclContext(BridgedDeclContext cDeclContext) { + return static_cast(cDeclContext.raw); +} + +static inline BridgedDeclContext bridgeDeclContext(DeclContext *declContext) { + return BridgedDeclContext{declContext}; +} + +static inline SourceLoc convertSourceLoc(BridgedSourceLoc cLoc) { + auto smLoc = llvm::SMLoc::getFromPointer(static_cast(cLoc.raw)); return SourceLoc(smLoc); } -namespace { - struct BridgedDiagnosticImpl { - InFlightDiagnostic inFlight; - std::vector textBlobs; - - BridgedDiagnosticImpl(const BridgedDiagnosticImpl&) = delete; - BridgedDiagnosticImpl(BridgedDiagnosticImpl &&) = delete; - BridgedDiagnosticImpl &operator=(const BridgedDiagnosticImpl&) = delete; - BridgedDiagnosticImpl &operator=(BridgedDiagnosticImpl &&) = delete; - - ~BridgedDiagnosticImpl() { - inFlight.flush(); - for (auto text: textBlobs) { - free((void*)text.data()); - } - } - }; +static inline Identifier convertIdentifier(BridgedIdentifier cIdentifier) { + return Identifier::getFromOpaquePointer(const_cast(cIdentifier.raw)); +} + +static inline BridgedDiagnosticImpl * +convertDiagnostic(BridgedDiagnostic cDiag) { + return static_cast(cDiag.raw); +} + +static inline DiagnosticEngine & +convertDiagnosticEngine(BridgedDiagnosticEngine cEngine) { + return *static_cast(cEngine.raw); +} + +static inline TypeAttributes * +convertTypeAttributes(BridgedTypeAttributes cAttributes) { + return static_cast(cAttributes.raw); +} + +static TypeAttrKind convertTypeAttrKind(BridgedTypeAttrKind kind) { + switch (kind) { +#define TYPE_ATTR(X) \ + case BridgedTypeAttrKind_##X: \ + return TAK_##X; +#include "swift/AST/Attr.def" + case BridgedTypeAttrKind_Count: + return TAK_Count; + } } -BridgedDiagnostic SwiftDiagnostic_create(void *diagnosticEngine, - BridgedDiagnosticSeverity severity, - const void *sourceLocPtr, - const unsigned char *textPtr, - long textLen) { - StringRef origText{ - reinterpret_cast(textPtr), size_t(textLen)}; +BridgedDiagnostic Diagnostic_create(BridgedDiagnosticEngine cDiags, + BridgedDiagnosticSeverity severity, + BridgedSourceLoc cLoc, + BridgedString cText) { + StringRef origText = convertString(cText); llvm::MallocAllocator mallocAlloc; StringRef text = origText.copy(mallocAlloc); - SourceLoc loc = getSourceLocFromPointer(sourceLocPtr); + SourceLoc loc = convertSourceLoc(cLoc); Diag diagID; switch (severity) { @@ -75,230 +120,232 @@ BridgedDiagnostic SwiftDiagnostic_create(void *diagnosticEngine, break; } - DiagnosticEngine &diags = *static_cast(diagnosticEngine); - return new BridgedDiagnosticImpl{diags.diagnose(loc, diagID, text), {text}}; + DiagnosticEngine &diags = convertDiagnosticEngine(cDiags); + return {new BridgedDiagnosticImpl{diags.diagnose(loc, diagID, text), {text}}}; } /// Highlight a source range as part of the diagnostic. -void SwiftDiagnostic_highlight( - BridgedDiagnostic diagPtr, const void *startLocPtr, const void *endLocPtr -) { - SourceLoc startLoc = getSourceLocFromPointer(startLocPtr); - SourceLoc endLoc = getSourceLocFromPointer(endLocPtr); +void Diagnostic_highlight(BridgedDiagnostic cDiag, BridgedSourceLoc cStartLoc, + BridgedSourceLoc cEndLoc) { + SourceLoc startLoc = convertSourceLoc(cStartLoc); + SourceLoc endLoc = convertSourceLoc(cEndLoc); - BridgedDiagnosticImpl *impl = static_cast(diagPtr); - impl->inFlight.highlightChars(startLoc, endLoc); + BridgedDiagnosticImpl *diag = convertDiagnostic(cDiag); + diag->inFlight.highlightChars(startLoc, endLoc); } /// Add a Fix-It to replace a source range as part of the diagnostic. -void SwiftDiagnostic_fixItReplace(BridgedDiagnostic diagPtr, - const void *replaceStartLocPtr, - const void *replaceEndLocPtr, - const unsigned char *newTextPtr, - long newTextLen) { +void Diagnostic_fixItReplace(BridgedDiagnostic cDiag, + BridgedSourceLoc cStartLoc, + BridgedSourceLoc cEndLoc, + BridgedString cReplaceText) { - SourceLoc startLoc = getSourceLocFromPointer(replaceStartLocPtr); - SourceLoc endLoc = getSourceLocFromPointer(replaceEndLocPtr); + SourceLoc startLoc = convertSourceLoc(cStartLoc); + SourceLoc endLoc = convertSourceLoc(cEndLoc); - StringRef origReplaceText{ - reinterpret_cast(newTextPtr), size_t(newTextLen)}; + StringRef origReplaceText = convertString(cReplaceText); llvm::MallocAllocator mallocAlloc; StringRef replaceText = origReplaceText.copy(mallocAlloc); - BridgedDiagnosticImpl *impl = static_cast(diagPtr); - impl->textBlobs.push_back(replaceText); - impl->inFlight.fixItReplaceChars(startLoc, endLoc, replaceText); + BridgedDiagnosticImpl *diag = convertDiagnostic(cDiag); + diag->textBlobs.push_back(replaceText); + diag->inFlight.fixItReplaceChars(startLoc, endLoc, replaceText); } /// Finish the given diagnostic and emit it. -void SwiftDiagnostic_finish(BridgedDiagnostic diagPtr) { - BridgedDiagnosticImpl *impl = static_cast(diagPtr); - delete impl; +void Diagnostic_finish(BridgedDiagnostic cDiag) { + BridgedDiagnosticImpl *diag = convertDiagnostic(cDiag); + delete diag; } -BridgedIdentifier -SwiftASTContext_getIdentifier(void *ctx, const unsigned char *_Nullable str, - long len) { - if (len == 1 && str[0] == '_') +BridgedIdentifier ASTContext_getIdentifier(BridgedASTContext cContext, + BridgedString cStr) { + StringRef str = convertString(cStr); + if (str.size() == 1 && str.front() == '_') return BridgedIdentifier(); // If this was a back-ticked identifier, drop the back-ticks. - if (len >= 2 && str[0] == '`' && str[len-1] == '`') { - ++str; - len -= 2; + if (str.size() >= 2 && str.front() == '`' && str.back() == '`') { + str = str.drop_front().drop_back(); } - return const_cast( - static_cast(ctx) - ->getIdentifier( - StringRef{reinterpret_cast(str), size_t(len)}) - .getAsOpaquePointer()); + return {convertASTContext(cContext).getIdentifier(str).getAsOpaquePointer()}; } -void *SwiftImportDecl_create(void *ctx, void *dc, void *importLoc, char kind, - void *kindLoc, BridgedArrayRef path, - BridgedArrayRef pathLocs) { - assert(path.numElements == pathLocs.numElements); - ASTContext &Context = *static_cast(ctx); +void *ImportDecl_create(BridgedASTContext cContext, + BridgedDeclContext cDeclContext, + BridgedSourceLoc cImportLoc, char kind, + BridgedSourceLoc cKindLoc, BridgedArrayRef path, + BridgedArrayRef cPathLocs) { + assert(path.numElements == cPathLocs.numElements); + ASTContext &context = convertASTContext(cContext); + DeclContext *declContext = convertDeclContext(cDeclContext); + ImportPath::Builder importPath; - for (auto p : llvm::zip(getArrayRef(path), - getArrayRef(pathLocs))) { + for (auto p : llvm::zip(convertArrayRef(path), + convertArrayRef(cPathLocs))) { Identifier ident; SourceLoc loc; std::tie(ident, loc) = p; importPath.push_back(ident, loc); } - return ImportDecl::create( - Context, static_cast(dc), - getSourceLocFromPointer(importLoc), static_cast(kind), - getSourceLocFromPointer(kindLoc), std::move(importPath).get()); + return ImportDecl::create(context, declContext, convertSourceLoc(cImportLoc), + static_cast(kind), + convertSourceLoc(cKindLoc), + std::move(importPath).get()); } -void *BridgedSourceLoc_advanced(void *loc, long len) { - SourceLoc l = getSourceLocFromPointer(loc).getAdvancedLoc(len); - return const_cast(l.getOpaquePointerValue()); +BridgedSourceLoc SourceLoc_advanced(BridgedSourceLoc cLoc, long len) { + SourceLoc loc = convertSourceLoc(cLoc).getAdvancedLoc(len); + return {loc.getOpaquePointerValue()}; } -void *SwiftTopLevelCodeDecl_createStmt(void *ctx, void *DC, void *startLoc, - void *element, void *endLoc) { - ASTContext &Context = *static_cast(ctx); +void *TopLevelCodeDecl_createStmt(BridgedASTContext cContext, + BridgedDeclContext cDeclContext, + BridgedSourceLoc cStartLoc, void *element, + BridgedSourceLoc cEndLoc) { + ASTContext &context = convertASTContext(cContext); + DeclContext *declContext = convertDeclContext(cDeclContext); + auto *S = static_cast(element); - auto Brace = BraceStmt::create(Context, getSourceLocFromPointer(startLoc), - {S}, getSourceLocFromPointer(endLoc), + auto Brace = BraceStmt::create(context, convertSourceLoc(cStartLoc), {S}, + convertSourceLoc(cEndLoc), /*Implicit=*/true); - auto *TLCD = - new (Context) TopLevelCodeDecl(static_cast(DC), Brace); + auto *TLCD = new (context) TopLevelCodeDecl(declContext, Brace); return (Decl *)TLCD; } -void *SwiftTopLevelCodeDecl_createExpr(void *ctx, void *DC, void *startLoc, - void *element, void *endLoc) { - ASTContext &Context = *static_cast(ctx); +void *TopLevelCodeDecl_createExpr(BridgedASTContext cContext, + BridgedDeclContext cDeclContext, + BridgedSourceLoc cStartLoc, void *element, + BridgedSourceLoc cEndLoc) { + ASTContext &context = convertASTContext(cContext); + DeclContext *declContext = convertDeclContext(cDeclContext); + auto *E = static_cast(element); - auto Brace = BraceStmt::create(Context, getSourceLocFromPointer(startLoc), - {E}, getSourceLocFromPointer(endLoc), + auto Brace = BraceStmt::create(context, convertSourceLoc(cStartLoc), {E}, + convertSourceLoc(cEndLoc), /*Implicit=*/true); - auto *TLCD = - new (Context) TopLevelCodeDecl(static_cast(DC), Brace); + auto *TLCD = new (context) TopLevelCodeDecl(declContext, Brace); return (Decl *)TLCD; } -void *SwiftSequenceExpr_create(void *ctx, BridgedArrayRef exprs) { - return SequenceExpr::create(*static_cast(ctx), - getArrayRef(exprs)); +void *SequenceExpr_create(BridgedASTContext cContext, BridgedArrayRef exprs) { + return SequenceExpr::create(convertASTContext(cContext), + convertArrayRef(exprs)); } -void *SwiftTupleExpr_create(void *ctx, void *lparen, BridgedArrayRef subs, - BridgedArrayRef names, - BridgedArrayRef nameLocs, - void *rparen) { - auto &Context = *static_cast(ctx); +void *TupleExpr_create(BridgedASTContext cContext, BridgedSourceLoc cLParen, + BridgedArrayRef subs, BridgedArrayRef names, + BridgedArrayRef cNameLocs, BridgedSourceLoc cRParen) { + ASTContext &context = convertASTContext(cContext); return TupleExpr::create( - Context, getSourceLocFromPointer(lparen), - getArrayRef(subs), getArrayRef(names), - getArrayRef(nameLocs), getSourceLocFromPointer(rparen), + context, convertSourceLoc(cLParen), convertArrayRef(subs), + convertArrayRef(names), convertArrayRef(cNameLocs), + convertSourceLoc(cRParen), /*Implicit*/ false); } -void *SwiftFunctionCallExpr_create(void *ctx, void *fn, void *args) { - ASTContext &Context = *static_cast(ctx); +void *FunctionCallExpr_create(BridgedASTContext cContext, void *fn, + void *args) { + ASTContext &context = convertASTContext(cContext); TupleExpr *TE = static_cast(args); SmallVector arguments; for (unsigned i = 0; i < TE->getNumElements(); ++i) { arguments.emplace_back(TE->getElementNameLoc(i), TE->getElementName(i), TE->getElement(i)); } - auto *argList = ArgumentList::create(Context, TE->getLParenLoc(), arguments, + auto *argList = ArgumentList::create(context, TE->getLParenLoc(), arguments, TE->getRParenLoc(), None, /*isImplicit*/ false); - return CallExpr::create(Context, static_cast(fn), argList, + return CallExpr::create(context, static_cast(fn), argList, /*implicit*/ false); } -void *SwiftIdentifierExpr_create(void *ctx, BridgedIdentifier base, void *loc) { - ASTContext &Context = *static_cast(ctx); - auto name = DeclNameRef{swift::Identifier::getFromOpaquePointer(base)}; - Expr *E = new (Context) UnresolvedDeclRefExpr( - name, DeclRefKind::Ordinary, DeclNameLoc{getSourceLocFromPointer(loc)}); +void *IdentifierExpr_create(BridgedASTContext cContext, BridgedIdentifier base, + BridgedSourceLoc cLoc) { + ASTContext &context = convertASTContext(cContext); + auto name = DeclNameRef{convertIdentifier(base)}; + Expr *E = new (context) UnresolvedDeclRefExpr( + name, DeclRefKind::Ordinary, DeclNameLoc{convertSourceLoc(cLoc)}); return E; } -void *SwiftStringLiteralExpr_create(void *ctx, - const unsigned char *_Nullable string, - long len, void *TokenLoc) { - ASTContext &Context = *static_cast(ctx); - auto stringRef = Context.AllocateCopy( - StringRef{reinterpret_cast(string), size_t(len)}); - return new (Context) - StringLiteralExpr(stringRef, getSourceLocFromPointer(TokenLoc)); +void *StringLiteralExpr_create(BridgedASTContext cContext, BridgedString cStr, + BridgedSourceLoc cTokenLoc) { + ASTContext &context = convertASTContext(cContext); + auto str = context.AllocateCopy(convertString(cStr)); + return new (context) StringLiteralExpr(str, convertSourceLoc(cTokenLoc)); } -void *SwiftIntegerLiteralExpr_create(void *ctx, - const unsigned char *_Nullable string, - long len, void *TokenLoc) { - ASTContext &Context = *static_cast(ctx); - auto stringRef = Context.AllocateCopy( - StringRef{reinterpret_cast(string), size_t(len)}); - return new (Context) - IntegerLiteralExpr(stringRef, getSourceLocFromPointer(TokenLoc)); +void *IntegerLiteralExpr_create(BridgedASTContext cContext, BridgedString cStr, + BridgedSourceLoc cTokenLoc) { + ASTContext &context = convertASTContext(cContext); + auto str = context.AllocateCopy(convertString(cStr)); + return new (context) IntegerLiteralExpr(str, convertSourceLoc(cTokenLoc)); } -void *ArrayExpr_create(void *ctx, void *lLoc, BridgedArrayRef elements, - BridgedArrayRef commas, void *rLoc) { - ASTContext &Context = *static_cast(ctx); +void *ArrayExpr_create(BridgedASTContext cContext, BridgedSourceLoc cLLoc, + BridgedArrayRef elements, BridgedArrayRef commas, + BridgedSourceLoc cRLoc) { + ASTContext &context = convertASTContext(cContext); return ArrayExpr::create( - Context, getSourceLocFromPointer(lLoc), getArrayRef(elements), - getArrayRef(commas), getSourceLocFromPointer(rLoc)); + context, convertSourceLoc(cLLoc), convertArrayRef(elements), + convertArrayRef(commas), convertSourceLoc(cRLoc)); } -void *SwiftBooleanLiteralExpr_create(void *ctx, bool value, void *TokenLoc) { - ASTContext &Context = *static_cast(ctx); - return new (Context) - BooleanLiteralExpr(value, getSourceLocFromPointer(TokenLoc)); +void *BooleanLiteralExpr_create(BridgedASTContext cContext, bool value, + BridgedSourceLoc cTokenLoc) { + ASTContext &context = convertASTContext(cContext); + return new (context) BooleanLiteralExpr(value, convertSourceLoc(cTokenLoc)); } -void *SwiftVarDecl_create(void *ctx, BridgedIdentifier _Nullable nameId, - void *initExpr, void *loc, bool isStatic, bool isLet, - void *dc) { - ASTContext &Context = *static_cast(ctx); - auto name = (UnresolvedDeclRefExpr *)nameId; - auto sourceLoc = getSourceLocFromPointer(loc); - auto varDecl = new (Context) VarDecl( +void *VarDecl_create(BridgedASTContext cContext, void *nameExpr, void *initExpr, + BridgedSourceLoc cLoc, bool isStatic, bool isLet, + BridgedDeclContext cDeclContext) { + ASTContext &context = convertASTContext(cContext); + DeclContext *declContext = convertDeclContext(cDeclContext); + + auto name = (UnresolvedDeclRefExpr *)nameExpr; + auto sourceLoc = convertSourceLoc(cLoc); + auto varDecl = new (context) VarDecl( isStatic, isLet ? VarDecl::Introducer::Let : VarDecl::Introducer::Var, - sourceLoc, name->getName().getBaseIdentifier(), - reinterpret_cast(dc)); - auto pattern = NamedPattern::createImplicit(Context, varDecl); + sourceLoc, name->getName().getBaseIdentifier(), declContext); + auto pattern = NamedPattern::createImplicit(context, varDecl); return PatternBindingDecl::create( - Context, sourceLoc, + context, sourceLoc, isStatic ? StaticSpellingKind::KeywordStatic : StaticSpellingKind::None, - sourceLoc, pattern, sourceLoc, (Expr *)initExpr, - reinterpret_cast(dc)); + sourceLoc, pattern, sourceLoc, (Expr *)initExpr, declContext); } -void *SingleValueStmtExpr_createWithWrappedBranches(void *_ctx, void *S, - void *DC, bool mustBeExpr) { - auto &ctx = *static_cast(_ctx); +void *SingleValueStmtExpr_createWithWrappedBranches( + BridgedASTContext cContext, void *S, BridgedDeclContext cDeclContext, + bool mustBeExpr) { + ASTContext &context = convertASTContext(cContext); + DeclContext *declContext = convertDeclContext(cDeclContext); return SingleValueStmtExpr::createWithWrappedBranches( - ctx, (Stmt *)S, (DeclContext *)DC, mustBeExpr); + context, (Stmt *)S, declContext, mustBeExpr); } -void *IfStmt_create(void *ctx, void *ifLoc, void *cond, void *_Nullable then, - void *_Nullable elseLoc, void *_Nullable elseStmt) { - ASTContext &Context = *static_cast(ctx); - return new (Context) - IfStmt(getSourceLocFromPointer(ifLoc), (Expr *)cond, (Stmt *)then, - getSourceLocFromPointer(elseLoc), (Stmt *)elseStmt, None, Context); +void *IfStmt_create(BridgedASTContext cContext, BridgedSourceLoc cIfLoc, + void *cond, void *_Nullable then, BridgedSourceLoc cElseLoc, + void *_Nullable elseStmt) { + ASTContext &context = convertASTContext(cContext); + return new (context) + IfStmt(convertSourceLoc(cIfLoc), (Expr *)cond, (Stmt *)then, + convertSourceLoc(cElseLoc), (Stmt *)elseStmt, None, context); } -void *ReturnStmt_create(void *ctx, void *loc, void *_Nullable expr) { - ASTContext &Context = *static_cast(ctx); - return new (Context) ReturnStmt(getSourceLocFromPointer(loc), (Expr *)expr); +void *ReturnStmt_create(BridgedASTContext cContext, BridgedSourceLoc cLoc, + void *_Nullable expr) { + ASTContext &context = convertASTContext(cContext); + return new (context) ReturnStmt(convertSourceLoc(cLoc), (Expr *)expr); } -void *BraceStmt_create(void *ctx, void *lbloc, BridgedArrayRef elements, - void *rbloc) { +void *BraceStmt_create(BridgedASTContext cContext, BridgedSourceLoc cLBLoc, + BridgedArrayRef elements, BridgedSourceLoc cRBLoc) { llvm::SmallVector nodes; - for (auto node : getArrayRef(elements)) { + for (auto node : convertArrayRef(elements)) { if (node.kind == ASTNodeKindExpr) { auto expr = (Expr *)node.ptr; nodes.push_back(expr); @@ -312,88 +359,94 @@ void *BraceStmt_create(void *ctx, void *lbloc, BridgedArrayRef elements, } } - ASTContext &Context = *static_cast(ctx); - return BraceStmt::create(Context, getSourceLocFromPointer(lbloc), - Context.AllocateCopy(nodes), - getSourceLocFromPointer(rbloc)); + ASTContext &context = convertASTContext(cContext); + return BraceStmt::create(context, convertSourceLoc(cLBLoc), + context.AllocateCopy(nodes), + convertSourceLoc(cRBLoc)); } -void *ParamDecl_create(void *ctx, void *loc, void *_Nullable argLoc, - BridgedIdentifier _Nullable argName, - void *_Nullable paramLoc, - BridgedIdentifier _Nullable paramName, - void *_Nullable type, void *declContext) { - ASTContext &Context = *static_cast(ctx); - if (!paramName) +void *ParamDecl_create(BridgedASTContext cContext, BridgedSourceLoc cLoc, + BridgedSourceLoc cArgLoc, BridgedIdentifier argName, + BridgedSourceLoc cParamLoc, BridgedIdentifier paramName, + void *_Nullable type, BridgedDeclContext cDeclContext) { + ASTContext &context = convertASTContext(cContext); + DeclContext *declContext = convertDeclContext(cDeclContext); + + if (!paramName.raw) paramName = argName; - auto paramDecl = new (Context) ParamDecl( - getSourceLocFromPointer(loc), getSourceLocFromPointer(argLoc), - Identifier::getFromOpaquePointer(argName), - getSourceLocFromPointer(paramLoc), - Identifier::getFromOpaquePointer(paramName), (DeclContext *)declContext); + auto paramDecl = new (context) + ParamDecl(convertSourceLoc(cLoc), convertSourceLoc(cArgLoc), + convertIdentifier(argName), convertSourceLoc(cParamLoc), + convertIdentifier(paramName), declContext); paramDecl->setTypeRepr((TypeRepr *)type); return paramDecl; } -struct FuncDeclBridged -FuncDecl_create(void *ctx, void *staticLoc, bool isStatic, void *funcLoc, - BridgedIdentifier name, void *nameLoc, bool isAsync, - void *_Nullable asyncLoc, bool throws, - void *_Nullable throwsLoc, void *paramLLoc, - BridgedArrayRef params, void *paramRLoc, - void *_Nullable returnType, void *declContext) { - auto *paramList = ParameterList::create( - *static_cast(ctx), getSourceLocFromPointer(paramLLoc), - getArrayRef(params), getSourceLocFromPointer(paramRLoc)); - auto declName = DeclName(*static_cast(ctx), - Identifier::getFromOpaquePointer(name), paramList); +BridgedFuncDecl +FuncDecl_create(BridgedASTContext cContext, BridgedSourceLoc cStaticLoc, + bool isStatic, BridgedSourceLoc cFuncLoc, + BridgedIdentifier name, BridgedSourceLoc cNameLoc, bool isAsync, + BridgedSourceLoc cAsyncLoc, bool throws, + BridgedSourceLoc cThrowsLoc, BridgedSourceLoc cParamLLoc, + BridgedArrayRef params, BridgedSourceLoc cParamRLoc, + void *_Nullable returnType, BridgedDeclContext cDeclContext) { + ASTContext &context = convertASTContext(cContext); + DeclContext *declContext = convertDeclContext(cDeclContext); + + auto *paramList = ParameterList::create(context, convertSourceLoc(cParamLLoc), + convertArrayRef(params), + convertSourceLoc(cParamRLoc)); + auto declName = + DeclName(convertASTContext(cContext), convertIdentifier(name), paramList); auto *out = FuncDecl::create( - *static_cast(ctx), getSourceLocFromPointer(staticLoc), + context, convertSourceLoc(cStaticLoc), isStatic ? StaticSpellingKind::KeywordStatic : StaticSpellingKind::None, - getSourceLocFromPointer(funcLoc), declName, - getSourceLocFromPointer(nameLoc), isAsync, - getSourceLocFromPointer(asyncLoc), throws, - getSourceLocFromPointer(throwsLoc), nullptr, paramList, - (TypeRepr *)returnType, (DeclContext *)declContext); + convertSourceLoc(cFuncLoc), declName, convertSourceLoc(cNameLoc), isAsync, + convertSourceLoc(cAsyncLoc), throws, convertSourceLoc(cThrowsLoc), + nullptr, paramList, (TypeRepr *)returnType, declContext); - return {static_cast(out), static_cast(out), - static_cast(out)}; + return {bridgeDeclContext(out), cast(out), cast(out)}; } void FuncDecl_setBody(void *fn, void *body) { ((FuncDecl *)fn)->setBody((BraceStmt *)body, FuncDecl::BodyKind::Parsed); } -void *SimpleIdentTypeRepr_create(void *ctx, void *loc, BridgedIdentifier id) { - ASTContext &Context = *static_cast(ctx); - return new (Context) - SimpleIdentTypeRepr(DeclNameLoc(getSourceLocFromPointer(loc)), - DeclNameRef(Identifier::getFromOpaquePointer(id))); -} - -void *GenericIdentTypeRepr_create(void *ctx, BridgedIdentifier name, - void *nameLoc, BridgedArrayRef genericArgs, - void *lAngle, void *rAngle) { - ASTContext &Context = *static_cast(ctx); - auto Loc = DeclNameLoc(getSourceLocFromPointer(nameLoc)); - auto Name = DeclNameRef(Identifier::getFromOpaquePointer(name)); - SourceLoc lAngleLoc = getSourceLocFromPointer(lAngle); - SourceLoc rAngleLoc = getSourceLocFromPointer(rAngle); - return GenericIdentTypeRepr::create(Context, Loc, Name, - getArrayRef(genericArgs), +void *SimpleIdentTypeRepr_create(BridgedASTContext cContext, + BridgedSourceLoc cLoc, BridgedIdentifier id) { + ASTContext &context = convertASTContext(cContext); + return new (context) SimpleIdentTypeRepr(DeclNameLoc(convertSourceLoc(cLoc)), + DeclNameRef(convertIdentifier(id))); +} + +void *GenericIdentTypeRepr_create(BridgedASTContext cContext, + BridgedIdentifier name, + BridgedSourceLoc cNameLoc, + BridgedArrayRef genericArgs, + BridgedSourceLoc cLAngleLoc, + BridgedSourceLoc cRAngleLoc) { + ASTContext &context = convertASTContext(cContext); + auto Loc = DeclNameLoc(convertSourceLoc(cNameLoc)); + auto Name = DeclNameRef(convertIdentifier(name)); + SourceLoc lAngleLoc = convertSourceLoc(cLAngleLoc); + SourceLoc rAngleLoc = convertSourceLoc(cRAngleLoc); + return GenericIdentTypeRepr::create(context, Loc, Name, + convertArrayRef(genericArgs), SourceRange{lAngleLoc, rAngleLoc}); } -void *UnresolvedDotExpr_create(void *ctx, void *base, void *dotLoc, - BridgedIdentifier name, void *nameLoc) { - ASTContext &Context = *static_cast(ctx); - return new (Context) - UnresolvedDotExpr((Expr *)base, getSourceLocFromPointer(dotLoc), - DeclNameRef(Identifier::getFromOpaquePointer(name)), - DeclNameLoc(getSourceLocFromPointer(nameLoc)), false); +void *UnresolvedDotExpr_create(BridgedASTContext cContext, void *base, + BridgedSourceLoc cDotLoc, BridgedIdentifier name, + BridgedSourceLoc cNameLoc) { + ASTContext &context = convertASTContext(cContext); + return new (context) + UnresolvedDotExpr((Expr *)base, convertSourceLoc(cDotLoc), + DeclNameRef(convertIdentifier(name)), + DeclNameLoc(convertSourceLoc(cNameLoc)), false); } -void *ClosureExpr_create(void *ctx, void *body, void *dc) { +void *ClosureExpr_create(BridgedASTContext cContext, void *body, + BridgedDeclContext cDeclContext) { DeclAttributes attributes; SourceRange bracketRange; SourceLoc asyncLoc; @@ -401,99 +454,118 @@ void *ClosureExpr_create(void *ctx, void *body, void *dc) { SourceLoc arrowLoc; SourceLoc inLoc; - ASTContext &Context = *static_cast(ctx); - auto params = ParameterList::create(Context, inLoc, {}, inLoc); + ASTContext &context = convertASTContext(cContext); + DeclContext *declContext = convertDeclContext(cDeclContext); - auto *out = new (Context) + auto params = ParameterList::create(context, inLoc, {}, inLoc); + + auto *out = new (context) ClosureExpr(attributes, bracketRange, nullptr, nullptr, asyncLoc, - throwsLoc, arrowLoc, inLoc, nullptr, (DeclContext *)dc); + throwsLoc, arrowLoc, inLoc, nullptr, declContext); out->setBody((BraceStmt *)body, true); out->setParameterList(params); return (Expr *)out; } void NominalTypeDecl_setMembers(void *decl, BridgedArrayRef members) { - auto declMembers = getArrayRef(members); + auto declMembers = convertArrayRef(members); for (auto m : declMembers) ((NominalTypeDecl *)decl)->addMember(m); } -DeclContextAndDecl StructDecl_create(void *ctx, void *loc, - BridgedIdentifier name, void *nameLoc, - void *_Nullable genericParams, void *dc) { - ASTContext &Context = *static_cast(ctx); - auto *out = new (Context) StructDecl( - getSourceLocFromPointer(loc), Identifier::getFromOpaquePointer(name), - getSourceLocFromPointer(nameLoc), {}, (GenericParamList *)genericParams, - (DeclContext *)dc); +BridgedDeclContextAndDecl StructDecl_create(BridgedASTContext cContext, + BridgedSourceLoc cLoc, + BridgedIdentifier name, + BridgedSourceLoc cNameLoc, + void *_Nullable genericParams, + BridgedDeclContext cDeclContext) { + ASTContext &context = convertASTContext(cContext); + DeclContext *declContext = convertDeclContext(cDeclContext); + + auto *out = + new (context) StructDecl(convertSourceLoc(cLoc), convertIdentifier(name), + convertSourceLoc(cNameLoc), {}, + (GenericParamList *)genericParams, declContext); out->setImplicit(); // TODO: remove this. - return {(DeclContext *)out, (NominalTypeDecl *)out, (Decl *)out}; + return {bridgeDeclContext(out->getDeclContext()), cast(out), cast(out)}; } -DeclContextAndDecl ClassDecl_create(void *ctx, void *loc, - BridgedIdentifier name, void *nameLoc, - void *dc) { - ASTContext &Context = *static_cast(ctx); - auto *out = new (Context) ClassDecl( - getSourceLocFromPointer(loc), Identifier::getFromOpaquePointer(name), - getSourceLocFromPointer(nameLoc), {}, nullptr, (DeclContext *)dc, false); +BridgedDeclContextAndDecl ClassDecl_create(BridgedASTContext cContext, + BridgedSourceLoc cLoc, + BridgedIdentifier name, + BridgedSourceLoc cNameLoc, + BridgedDeclContext cDeclContext) { + ASTContext &context = convertASTContext(cContext); + DeclContext *declContext = convertDeclContext(cDeclContext); + + auto *out = new (context) + ClassDecl(convertSourceLoc(cLoc), convertIdentifier(name), + convertSourceLoc(cNameLoc), {}, nullptr, declContext, false); out->setImplicit(); // TODO: remove this. - return {(DeclContext *)out, (NominalTypeDecl *)out, (Decl *)out}; + return {BridgedDeclContext{out}, (NominalTypeDecl *)out, (Decl *)out}; } -void *OptionalTypeRepr_create(void *ctx, void *base, void *questionLoc) { - ASTContext &Context = *static_cast(ctx); - return new (Context) - OptionalTypeRepr((TypeRepr *)base, getSourceLocFromPointer(questionLoc)); +void *OptionalTypeRepr_create(BridgedASTContext cContext, void *base, + BridgedSourceLoc cQuestionLoc) { + ASTContext &context = convertASTContext(cContext); + return new (context) + OptionalTypeRepr((TypeRepr *)base, convertSourceLoc(cQuestionLoc)); } -void *ImplicitlyUnwrappedOptionalTypeRepr_create(void *ctx, void *base, - void *exclamationLoc) { - ASTContext &Context = *static_cast(ctx); - return new (Context) ImplicitlyUnwrappedOptionalTypeRepr( - (TypeRepr *)base, getSourceLocFromPointer(exclamationLoc)); +void *ImplicitlyUnwrappedOptionalTypeRepr_create( + BridgedASTContext cContext, void *base, BridgedSourceLoc cExclamationLoc) { + ASTContext &context = convertASTContext(cContext); + return new (context) ImplicitlyUnwrappedOptionalTypeRepr( + (TypeRepr *)base, convertSourceLoc(cExclamationLoc)); } -void *ArrayTypeRepr_create(void *ctx, void *base, void *lsquareLoc, - void *rsquareLoc) { - ASTContext &Context = *static_cast(ctx); - SourceLoc lSquareLoc = getSourceLocFromPointer(lsquareLoc); - SourceLoc rSquareLoc = getSourceLocFromPointer(rsquareLoc); - return new (Context) +void *ArrayTypeRepr_create(BridgedASTContext cContext, void *base, + BridgedSourceLoc cLSquareLoc, + BridgedSourceLoc cRSquareLoc) { + ASTContext &context = convertASTContext(cContext); + SourceLoc lSquareLoc = convertSourceLoc(cLSquareLoc); + SourceLoc rSquareLoc = convertSourceLoc(cRSquareLoc); + return new (context) ArrayTypeRepr((TypeRepr *)base, SourceRange{lSquareLoc, rSquareLoc}); } -void *DictionaryTypeRepr_create(void *ctx, void *keyType, void *valueType, - void *lsquareLoc, void *colonloc, - void *rsquareLoc) { - ASTContext &Context = *static_cast(ctx); - SourceLoc lSquareLoc = getSourceLocFromPointer(lsquareLoc); - SourceLoc colonLoc = getSourceLocFromPointer(colonloc); - SourceLoc rSquareLoc = getSourceLocFromPointer(rsquareLoc); - return new (Context) +void *DictionaryTypeRepr_create(BridgedASTContext cContext, void *keyType, + void *valueType, BridgedSourceLoc cLSquareLoc, + BridgedSourceLoc cColonloc, + BridgedSourceLoc cRSquareLoc) { + ASTContext &context = convertASTContext(cContext); + SourceLoc lSquareLoc = convertSourceLoc(cLSquareLoc); + SourceLoc colonLoc = convertSourceLoc(cColonloc); + SourceLoc rSquareLoc = convertSourceLoc(cRSquareLoc); + return new (context) DictionaryTypeRepr((TypeRepr *)keyType, (TypeRepr *)valueType, colonLoc, SourceRange{lSquareLoc, rSquareLoc}); } -void *MetatypeTypeRepr_create(void *ctx, void *baseType, void *typeLoc) { - ASTContext &Context = *static_cast(ctx); - SourceLoc tyLoc = getSourceLocFromPointer(typeLoc); - return new (Context) MetatypeTypeRepr((TypeRepr *)baseType, tyLoc); +void *MetatypeTypeRepr_create(BridgedASTContext cContext, void *baseType, + BridgedSourceLoc cTypeLoc) { + ASTContext &context = convertASTContext(cContext); + SourceLoc tyLoc = convertSourceLoc(cTypeLoc); + return new (context) MetatypeTypeRepr((TypeRepr *)baseType, tyLoc); } -void *ProtocolTypeRepr_create(void *ctx, void *baseType, void *protoLoc) { - ASTContext &Context = *static_cast(ctx); - SourceLoc protocolLoc = getSourceLocFromPointer(protoLoc); - return new (Context) ProtocolTypeRepr((TypeRepr *)baseType, protocolLoc); +void *ProtocolTypeRepr_create(BridgedASTContext cContext, void *baseType, + BridgedSourceLoc cProtoLoc) { + ASTContext &context = convertASTContext(cContext); + SourceLoc protoLoc = convertSourceLoc(cProtoLoc); + return new (context) ProtocolTypeRepr((TypeRepr *)baseType, protoLoc); } -void *PackExpansionTypeRepr_create(void *ctx, void *base, void *repeatLoc) { - ASTContext &Context = *static_cast(ctx); - return new (Context) PackExpansionTypeRepr( - getSourceLocFromPointer(repeatLoc), (TypeRepr *)base); +void *PackExpansionTypeRepr_create(BridgedASTContext cContext, void *base, + BridgedSourceLoc cRepeatLoc) { + ASTContext &context = convertASTContext(cContext); + return new (context) + PackExpansionTypeRepr(convertSourceLoc(cRepeatLoc), (TypeRepr *)base); } -static BridgedTypeAttrKind bridgeTypeAttrKind(TypeAttrKind kind) { +BridgedTypeAttrKind TypeAttrKind_fromString(BridgedString cStr) { + TypeAttrKind kind = + TypeAttributes::getAttrKindFromString(convertString(cStr)); switch (kind) { #define TYPE_ATTR(X) case TAK_##X: return BridgedTypeAttrKind_##X; #include "swift/AST/Attr.def" @@ -501,212 +573,217 @@ static BridgedTypeAttrKind bridgeTypeAttrKind(TypeAttrKind kind) { } } -static TypeAttrKind bridgeTypeAttrKind(BridgedTypeAttrKind kind) { - switch (kind) { -#define TYPE_ATTR(X) case BridgedTypeAttrKind_##X: return TAK_##X; -#include "swift/AST/Attr.def" - case BridgedTypeAttrKind_Count: return TAK_Count; - } -} - -BridgedTypeAttrKind getBridgedTypeAttrKindFromString( - const unsigned char *str, intptr_t len) { - return bridgeTypeAttrKind( - TypeAttributes::getAttrKindFromString(StringRef((const char *)str, len))); -} +BridgedTypeAttributes TypeAttributes_create() { return {new TypeAttributes()}; } -BridgedTypeAttributes BridgedTypeAttributes_create() { - return new TypeAttributes(); -} - -void BridgedTypeAttributes_addSimpleAttr( - BridgedTypeAttributes typeAttributesPtr, BridgedTypeAttrKind kind, - void *atLoc, void *attrLoc -) { - TypeAttributes *typeAttributes = (TypeAttributes *)typeAttributesPtr; - typeAttributes->setAttr( - bridgeTypeAttrKind(kind), getSourceLocFromPointer(attrLoc)); +void TypeAttributes_addSimpleAttr(BridgedTypeAttributes cAttributes, + BridgedTypeAttrKind cKind, + BridgedSourceLoc cAtLoc, + BridgedSourceLoc cAttrLoc) { + TypeAttributes *typeAttributes = convertTypeAttributes(cAttributes); + typeAttributes->setAttr(convertTypeAttrKind(cKind), + convertSourceLoc(cAttrLoc)); if (typeAttributes->AtLoc.isInvalid()) - typeAttributes->AtLoc = getSourceLocFromPointer(atLoc); + typeAttributes->AtLoc = convertSourceLoc(cAtLoc); } -void *AttributedTypeRepr_create( - void *ctx, void *base, BridgedTypeAttributes typeAttributesPtr) { - TypeAttributes *typeAttributes = (TypeAttributes *)typeAttributesPtr; +void *AttributedTypeRepr_create(BridgedASTContext cContext, void *base, + BridgedTypeAttributes cAttributes) { + TypeAttributes *typeAttributes = convertTypeAttributes(cAttributes); if (typeAttributes->empty()) return base; - ASTContext &Context = *static_cast(ctx); + ASTContext &context = convertASTContext(cContext); auto attributedType = - new (Context) AttributedTypeRepr(*typeAttributes, (TypeRepr *)base); + new (context) AttributedTypeRepr(*typeAttributes, (TypeRepr *)base); delete typeAttributes; return attributedType; } -void *AttributedTypeSpecifierRepr_create( - void *ctx, void *base, BridgedAttributedTypeSpecifier specifier, void *specifierLoc -) { - ASTContext &Context = *static_cast(ctx); - SourceLoc loc = getSourceLocFromPointer(specifierLoc); +void * +AttributedTypeSpecifierRepr_create(BridgedASTContext cContext, void *base, + BridgedAttributedTypeSpecifier specifier, + BridgedSourceLoc cSpecifierLoc) { + ASTContext &context = convertASTContext(cContext); + SourceLoc loc = convertSourceLoc(cSpecifierLoc); TypeRepr *baseType = (TypeRepr *)base; switch (specifier) { case BridgedAttributedTypeSpecifierInOut: - return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::InOut, loc); + return new (context) + OwnershipTypeRepr(baseType, ParamSpecifier::InOut, loc); case BridgedAttributedTypeSpecifierBorrowing: - return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::Borrowing, loc); + return new (context) + OwnershipTypeRepr(baseType, ParamSpecifier::Borrowing, loc); case BridgedAttributedTypeSpecifierConsuming: - return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::Consuming, loc); + return new (context) + OwnershipTypeRepr(baseType, ParamSpecifier::Consuming, loc); case BridgedAttributedTypeSpecifierLegacyShared: - return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::LegacyShared, loc); + return new (context) + OwnershipTypeRepr(baseType, ParamSpecifier::LegacyShared, loc); case BridgedAttributedTypeSpecifierLegacyOwned: - return new (Context) OwnershipTypeRepr(baseType, ParamSpecifier::LegacyOwned, loc); + return new (context) + OwnershipTypeRepr(baseType, ParamSpecifier::LegacyOwned, loc); case BridgedAttributedTypeSpecifierConst: - return new (Context) CompileTimeConstTypeRepr(baseType, loc); + return new (context) CompileTimeConstTypeRepr(baseType, loc); case BridgedAttributedTypeSpecifierIsolated: - return new (Context) IsolatedTypeRepr(baseType, loc); + return new (context) IsolatedTypeRepr(baseType, loc); } } -void *VarargTypeRepr_create(void *ctx, void *base, void *ellipsisLocPtr) { - ASTContext &Context = *static_cast(ctx); - SourceLoc ellipsisLoc = getSourceLocFromPointer(ellipsisLocPtr); +void *VarargTypeRepr_create(BridgedASTContext cContext, void *base, + BridgedSourceLoc cEllipsisLoc) { + ASTContext &context = convertASTContext(cContext); + SourceLoc ellipsisLoc = convertSourceLoc(cEllipsisLoc); TypeRepr *baseType = (TypeRepr *)base; - return new (Context) VarargTypeRepr(baseType, ellipsisLoc); + return new (context) VarargTypeRepr(baseType, ellipsisLoc); } -void *TupleTypeRepr_create(void *ctx, BridgedArrayRef elements, void *lParenLoc, - void *rParenLoc) { - ASTContext &Context = *static_cast(ctx); - SourceLoc lParen = getSourceLocFromPointer(lParenLoc); - SourceLoc rParen = getSourceLocFromPointer(rParenLoc); +void *TupleTypeRepr_create(BridgedASTContext cContext, BridgedArrayRef elements, + BridgedSourceLoc cLParenLoc, + BridgedSourceLoc cRParenLoc) { + ASTContext &context = convertASTContext(cContext); + SourceLoc lParen = convertSourceLoc(cLParenLoc); + SourceLoc rParen = convertSourceLoc(cRParenLoc); + SmallVector tupleElements; - for (auto element : getArrayRef(elements)) { + for (auto element : convertArrayRef(elements)) { TupleTypeReprElement elementRepr; - elementRepr.Name = Identifier::getFromOpaquePointer(element.Name); - elementRepr.NameLoc = getSourceLocFromPointer(element.NameLoc); - elementRepr.SecondName = - Identifier::getFromOpaquePointer(element.SecondName); - elementRepr.SecondNameLoc = getSourceLocFromPointer(element.SecondNameLoc); - elementRepr.UnderscoreLoc = getSourceLocFromPointer(element.UnderscoreLoc); - elementRepr.ColonLoc = getSourceLocFromPointer(element.ColonLoc); + elementRepr.Name = convertIdentifier(element.Name); + elementRepr.NameLoc = convertSourceLoc(element.NameLoc); + elementRepr.SecondName = convertIdentifier(element.SecondName); + elementRepr.SecondNameLoc = convertSourceLoc(element.SecondNameLoc); + elementRepr.UnderscoreLoc = convertSourceLoc(element.UnderscoreLoc); + elementRepr.ColonLoc = convertSourceLoc(element.ColonLoc); elementRepr.Type = (TypeRepr *)element.Type; - elementRepr.TrailingCommaLoc = - getSourceLocFromPointer(element.TrailingCommaLoc); + elementRepr.TrailingCommaLoc = convertSourceLoc(element.TrailingCommaLoc); tupleElements.emplace_back(elementRepr); } - return TupleTypeRepr::create(Context, tupleElements, + return TupleTypeRepr::create(context, tupleElements, SourceRange{lParen, rParen}); } -void *MemberTypeRepr_create(void *ctx, void *baseComponent, +void *MemberTypeRepr_create(BridgedASTContext cContext, void *baseComponent, BridgedArrayRef bridgedMemberComponents) { - ASTContext &Context = *static_cast(ctx); - auto memberComponents = getArrayRef(bridgedMemberComponents); + ASTContext &context = convertASTContext(cContext); + auto memberComponents = + convertArrayRef(bridgedMemberComponents); - return MemberTypeRepr::create(Context, (TypeRepr *)baseComponent, + return MemberTypeRepr::create(context, (TypeRepr *)baseComponent, memberComponents); } -void *EmptyCompositionTypeRepr_create(void *ctx, void *anyLocPtr) { - ASTContext &Context = *static_cast(ctx); - SourceLoc anyLoc = getSourceLocFromPointer(anyLocPtr); - return CompositionTypeRepr::createEmptyComposition(Context, anyLoc); +void *EmptyCompositionTypeRepr_create(BridgedASTContext cContext, + BridgedSourceLoc cAnyLoc) { + ASTContext &context = convertASTContext(cContext); + SourceLoc anyLoc = convertSourceLoc(cAnyLoc); + return CompositionTypeRepr::createEmptyComposition(context, anyLoc); } -void *CompositionTypeRepr_create(void *ctx, BridgedArrayRef typesPtr, - void *firstTypeLoc, void *firstAmpLocPtr) { - ASTContext &Context = *static_cast(ctx); - SourceLoc firstType = getSourceLocFromPointer(firstTypeLoc); - SourceLoc firstAmpLoc = getSourceLocFromPointer(firstAmpLocPtr); - auto types = getArrayRef(typesPtr); +void *CompositionTypeRepr_create(BridgedASTContext cContext, + BridgedArrayRef cTypes, + BridgedSourceLoc cFirstTypeLoc, + BridgedSourceLoc cFirstAmpLoc) { + ASTContext &context = convertASTContext(cContext); + SourceLoc firstTypeLoc = convertSourceLoc(cFirstTypeLoc); + SourceLoc firstAmpLoc = convertSourceLoc(cFirstAmpLoc); + auto types = convertArrayRef(cTypes); return CompositionTypeRepr::create( - Context, types, firstType, + context, types, firstTypeLoc, SourceRange{firstAmpLoc, types.back()->getEndLoc()}); } -void *FunctionTypeRepr_create(void *ctx, void *argsTy, void *_Nullable asyncLoc, - void *_Nullable throwsLoc, void *arrowLoc, - void *returnType) { - ASTContext &Context = *static_cast(ctx); - return new (Context) FunctionTypeRepr( - nullptr, (TupleTypeRepr *)argsTy, getSourceLocFromPointer(asyncLoc), - getSourceLocFromPointer(throwsLoc), getSourceLocFromPointer(arrowLoc), +void *FunctionTypeRepr_create(BridgedASTContext cContext, void *argsTy, + BridgedSourceLoc cAsyncLoc, + BridgedSourceLoc cThrowsLoc, + BridgedSourceLoc cArrowLoc, void *returnType) { + ASTContext &context = convertASTContext(cContext); + return new (context) FunctionTypeRepr( + nullptr, (TupleTypeRepr *)argsTy, convertSourceLoc(cAsyncLoc), + convertSourceLoc(cThrowsLoc), convertSourceLoc(cArrowLoc), (TypeRepr *)returnType); } -void *NamedOpaqueReturnTypeRepr_create(void *ctx, void *baseTy) { - ASTContext &Context = *static_cast(ctx); - return new (Context) NamedOpaqueReturnTypeRepr((TypeRepr *)baseTy, nullptr); +void *NamedOpaqueReturnTypeRepr_create(BridgedASTContext cContext, + void *baseTy) { + ASTContext &context = convertASTContext(cContext); + return new (context) NamedOpaqueReturnTypeRepr((TypeRepr *)baseTy, nullptr); } -void *OpaqueReturnTypeRepr_create(void *ctx, void *opaqueLoc, void *baseTy) { - ASTContext &Context = *static_cast(ctx); - return new (Context) OpaqueReturnTypeRepr(getSourceLocFromPointer(opaqueLoc), - (TypeRepr *)baseTy); +void *OpaqueReturnTypeRepr_create(BridgedASTContext cContext, + BridgedSourceLoc cOpaqueLoc, void *baseTy) { + ASTContext &context = convertASTContext(cContext); + return new (context) + OpaqueReturnTypeRepr(convertSourceLoc(cOpaqueLoc), (TypeRepr *)baseTy); } -void *ExistentialTypeRepr_create(void *ctx, void *anyLoc, void *baseTy) { - ASTContext &Context = *static_cast(ctx); - return new (Context) - ExistentialTypeRepr(getSourceLocFromPointer(anyLoc), (TypeRepr *)baseTy); +void *ExistentialTypeRepr_create(BridgedASTContext cContext, + BridgedSourceLoc cAnyLoc, void *baseTy) { + ASTContext &context = convertASTContext(cContext); + return new (context) + ExistentialTypeRepr(convertSourceLoc(cAnyLoc), (TypeRepr *)baseTy); } -void *GenericParamList_create(void *ctx, void *lAngleLoc, - BridgedArrayRef params, void *_Nullable whereLoc, - BridgedArrayRef reqs, void *rAngleLoc) { - ASTContext &Context = *static_cast(ctx); +void *GenericParamList_create(BridgedASTContext cContext, + BridgedSourceLoc cLAngleLoc, + BridgedArrayRef params, + BridgedSourceLoc cWhereLoc, BridgedArrayRef reqs, + BridgedSourceLoc cRAngleLoc) { + ASTContext &context = convertASTContext(cContext); SmallVector requirements; - for (auto req : getArrayRef(reqs)) { + for (auto req : convertArrayRef(reqs)) { switch (req.Kind) { case BridgedRequirementReprKindTypeConstraint: requirements.push_back(RequirementRepr::getTypeConstraint( - (TypeRepr *)req.FirstType, getSourceLocFromPointer(req.SeparatorLoc), - (TypeRepr *)req.SecondType, /*isExpansionPattern*/false)); + (TypeRepr *)req.FirstType, convertSourceLoc(req.SeparatorLoc), + (TypeRepr *)req.SecondType, /*isExpansionPattern*/ false)); break; case BridgedRequirementReprKindSameType: requirements.push_back(RequirementRepr::getSameType( - (TypeRepr *)req.FirstType, getSourceLocFromPointer(req.SeparatorLoc), - (TypeRepr *)req.SecondType, /*isExpansionPattern*/false)); + (TypeRepr *)req.FirstType, convertSourceLoc(req.SeparatorLoc), + (TypeRepr *)req.SecondType, /*isExpansionPattern*/ false)); break; case BridgedRequirementReprKindLayoutConstraint: llvm_unreachable("cannot handle layout constraints!"); } } - return GenericParamList::create(Context, getSourceLocFromPointer(lAngleLoc), - getArrayRef(params), - getSourceLocFromPointer(whereLoc), - requirements, - getSourceLocFromPointer(rAngleLoc)); + return GenericParamList::create( + context, convertSourceLoc(cLAngleLoc), + convertArrayRef(params), + convertSourceLoc(cWhereLoc), requirements, convertSourceLoc(cRAngleLoc)); } -void *GenericTypeParamDecl_create(void *ctx, void *declContext, - BridgedIdentifier name, void *nameLoc, - void *_Nullable eachLoc, long index, +void *GenericTypeParamDecl_create(BridgedASTContext cContext, + BridgedDeclContext cDeclContext, + BridgedIdentifier name, + BridgedSourceLoc cNameLoc, + BridgedSourceLoc cEachLoc, long index, bool isParameterPack) { return GenericTypeParamDecl::createParsed( - static_cast(declContext), - Identifier::getFromOpaquePointer(name), getSourceLocFromPointer(nameLoc), - getSourceLocFromPointer(eachLoc), + convertDeclContext(cDeclContext), convertIdentifier(name), + convertSourceLoc(cNameLoc), convertSourceLoc(cEachLoc), /*index*/ index, isParameterPack); } -void GenericTypeParamDecl_setInheritedType(void *ctx, void *Param, void *ty) { - ASTContext &Context = *static_cast(ctx); - auto entries = Context.AllocateCopy( +void GenericTypeParamDecl_setInheritedType(BridgedASTContext cContext, + void *param, void *ty) { + ASTContext &context = convertASTContext(cContext); + auto entries = context.AllocateCopy( ArrayRef{InheritedEntry{(TypeRepr *)ty}}); - ((GenericTypeParamDecl *)Param)->setInherited(entries); + ((GenericTypeParamDecl *)param)->setInherited(entries); } -DeclContextAndDecl TypeAliasDecl_create(void *ctx, void *declContext, - void *aliasLoc, void *equalLoc, - BridgedIdentifier name, void *nameLoc, - void *_Nullable genericParams) { - ASTContext &Context = *static_cast(ctx); - auto *out = new (Context) TypeAliasDecl( - getSourceLocFromPointer(aliasLoc), getSourceLocFromPointer(equalLoc), - Identifier::getFromOpaquePointer(name), getSourceLocFromPointer(nameLoc), - (GenericParamList *)genericParams, (DeclContext *)declContext); - return {(DeclContext *)out, (TypeAliasDecl *)out, (Decl *)out}; +BridgedDeclContextAndDecl TypeAliasDecl_create(BridgedASTContext cContext, + BridgedDeclContext cDeclContext, + BridgedSourceLoc cAliasLoc, + BridgedSourceLoc cEqualLoc, + BridgedIdentifier name, + BridgedSourceLoc cNameLoc, + void *_Nullable genericParams) { + ASTContext &context = convertASTContext(cContext); + auto *out = new (context) TypeAliasDecl( + convertSourceLoc(cAliasLoc), convertSourceLoc(cEqualLoc), + convertIdentifier(name), convertSourceLoc(cNameLoc), + (GenericParamList *)genericParams, convertDeclContext(cDeclContext)); + return {BridgedDeclContext{out}, (TypeAliasDecl *)out, (Decl *)out}; } void TypeAliasDecl_setUnderlyingTypeRepr(void *decl, void *underlyingType) { @@ -717,13 +794,14 @@ void TypeAliasDecl_setUnderlyingTypeRepr(void *decl, void *underlyingType) { #pragma clang diagnostic ignored "-Wdeprecated-declarations" void TopLevelCodeDecl_dump(void *decl) { - ((TopLevelCodeDecl *)decl)->dump(llvm::errs()); + static_cast(decl)->dump(llvm::errs()); } - -void Expr_dump(void *expr) { ((Expr *)expr)->dump(llvm::errs()); } -void Decl_dump(void *expr) { ((Decl *)expr)->dump(llvm::errs()); } -void Stmt_dump(void *expr) { ((Stmt *)expr)->dump(llvm::errs()); } -void Type_dump(void *expr) { ((TypeRepr *)expr)->dump(); } +void Expr_dump(void *expr) { static_cast(expr)->dump(llvm::errs()); } +void Decl_dump(void *decl) { static_cast(decl)->dump(llvm::errs()); } +void Stmt_dump(void *statement) { + static_cast(statement)->dump(llvm::errs()); +} +void Type_dump(void *type) { static_cast(type)->dump(); } #pragma clang diagnostic pop diff --git a/lib/ASTGen/Sources/ASTGen/ASTGen.swift b/lib/ASTGen/Sources/ASTGen/ASTGen.swift index 4aa3321190403..5cfedde85a4d6 100644 --- a/lib/ASTGen/Sources/ASTGen/ASTGen.swift +++ b/lib/ASTGen/Sources/ASTGen/ASTGen.swift @@ -38,14 +38,14 @@ enum ASTNode { } } - func bridged() -> ASTNodeBridged { + var bridged: BridgedASTNode { switch self { case .expr(let e): - return ASTNodeBridged(ptr: e, kind: .expr) + return BridgedASTNode(ptr: e, kind: .expr) case .stmt(let s): - return ASTNodeBridged(ptr: s, kind: .stmt) + return BridgedASTNode(ptr: s, kind: .stmt) case .decl(let d): - return ASTNodeBridged(ptr: d, kind: .decl) + return BridgedASTNode(ptr: d, kind: .decl) default: fatalError("Must be expr, stmt, or decl.") } @@ -66,10 +66,10 @@ class Boxed { struct ASTGenVisitor: SyntaxTransformVisitor { typealias ResultType = ASTNode - let ctx: UnsafeMutableRawPointer - let base: UnsafePointer + let ctx: BridgedASTContext + let base: UnsafeBufferPointer - @Boxed var declContext: UnsafeMutableRawPointer + @Boxed var declContext: BridgedDeclContext // TODO: this some how messes up the witness table when I uncomment it locally :/ // public func visit(_ node: T?) -> [UnsafeMutableRawPointer]? { @@ -90,15 +90,15 @@ struct ASTGenVisitor: SyntaxTransformVisitor { var out = [UnsafeMutableRawPointer]() for element in node.statements { - let loc = self.base.advanced(by: element.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: element) let swiftASTNodes = visit(element) switch swiftASTNodes { case .decl(let d): out.append(d) case .stmt(let s): - out.append(SwiftTopLevelCodeDecl_createStmt(ctx, declContext, loc, s, loc)) + out.append(TopLevelCodeDecl_createStmt(ctx, declContext, loc, s, loc)) case .expr(let e): - out.append(SwiftTopLevelCodeDecl_createExpr(ctx, declContext, loc, e, loc)) + out.append(TopLevelCodeDecl_createExpr(ctx, declContext, loc, e, loc)) default: fatalError("Top level nodes must be decls, stmts, or exprs.") } @@ -118,7 +118,7 @@ public func buildTopLevelASTNodes( callback: @convention(c) (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void ) { sourceFilePtr.withMemoryRebound(to: ExportedSourceFile.self, capacity: 1) { sourceFile in - ASTGenVisitor(ctx: ctx, base: sourceFile.pointee.buffer.baseAddress!, declContext: dc) + ASTGenVisitor(ctx: BridgedASTContext(raw: ctx), base: sourceFile.pointee.buffer, declContext: BridgedDeclContext(raw: dc)) .visit(sourceFile.pointee.syntax) .forEach { callback($0, outputContext) } } diff --git a/lib/ASTGen/Sources/ASTGen/Decls.swift b/lib/ASTGen/Sources/ASTGen/Decls.swift index 815bb696b137b..d1f60d3a94df3 100644 --- a/lib/ASTGen/Sources/ASTGen/Decls.swift +++ b/lib/ASTGen/Sources/ASTGen/Decls.swift @@ -4,13 +4,13 @@ import SwiftSyntax extension ASTGenVisitor { public func visit(_ node: TypealiasDeclSyntax) -> ASTNode { - let aliasLoc = self.base.advanced(by: node.typealiasKeyword.position.utf8Offset).raw - let equalLoc = self.base.advanced(by: node.initializer.equal.position.utf8Offset).raw + let aliasLoc = bridgedSourceLoc(for: node.typealiasKeyword) + let equalLoc = bridgedSourceLoc(for: node.initializer.equal) var nameText = node.identifier.text - let name = nameText.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + let name = nameText.withBridgedString { bridgedName in + return ASTContext_getIdentifier(ctx, bridgedName) } - let nameLoc = self.base.advanced(by: node.identifier.position.utf8Offset).raw + let nameLoc = bridgedSourceLoc(for: node.identifier) let genericParams = node.genericParameterClause.map { self.visit($0).rawValue } let out = TypeAliasDecl_create( self.ctx, self.declContext, aliasLoc, equalLoc, name, nameLoc, genericParams) @@ -26,10 +26,10 @@ extension ASTGenVisitor { } public func visit(_ node: StructDeclSyntax) -> ASTNode { - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) var nameText = node.identifier.text - let name = nameText.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + let name = nameText.withBridgedString { bridgedName in + return ASTContext_getIdentifier(ctx, bridgedName) } let genericParams = node.genericParameterClause @@ -49,10 +49,10 @@ extension ASTGenVisitor { } public func visit(_ node: ClassDeclSyntax) -> ASTNode { - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) var nameText = node.identifier.text - let name = nameText.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + let name = nameText.withBridgedString { bridgedName in + return ASTContext_getIdentifier(ctx, bridgedName) } let out = ClassDecl_create(ctx, loc, name, loc, declContext) @@ -73,29 +73,29 @@ extension ASTGenVisitor { let pattern = visit(node.bindings.first!.pattern).rawValue let initializer = visit(node.bindings.first!.initializer!).rawValue - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) let isStatic = false // TODO: compute this let isLet = node.bindingKeyword.tokenKind == .keyword(.let) // TODO: don't drop "initializer" on the floor. return .decl( - SwiftVarDecl_create( + VarDecl_create( ctx, pattern, initializer, loc, isStatic, isLet, declContext)) } public func visit(_ node: FunctionParameterSyntax) -> ASTNode { - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) + + let firstName: BridgedIdentifier + let secondName: BridgedIdentifier - let firstName: UnsafeMutableRawPointer? - let secondName: UnsafeMutableRawPointer? - let nodeFirstName = node.firstName if nodeFirstName.text != "_" { // Swift AST represents "_" as nil. var text = nodeFirstName.text - firstName = text.withUTF8 { buf in - SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + firstName = text.withBridgedString { bridgedName in + ASTContext_getIdentifier(ctx, bridgedName) } } else { firstName = nil @@ -103,8 +103,8 @@ extension ASTGenVisitor { if let nodeSecondName = node.secondName { var text = nodeSecondName.text - secondName = text.withUTF8 { buf in - SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + secondName = text.withBridgedString { bridgedName in + ASTContext_getIdentifier(ctx, bridgedName) } } else { secondName = nil @@ -116,15 +116,15 @@ extension ASTGenVisitor { } public func visit(_ node: FunctionDeclSyntax) -> ASTNode { - let staticLoc = self.base.advanced(by: node.position.utf8Offset).raw - let funcLoc = self.base.advanced(by: node.funcKeyword.position.utf8Offset).raw - let nameLoc = self.base.advanced(by: node.identifier.position.utf8Offset).raw - let rParamLoc = self.base.advanced(by: node.signature.input.leftParen.position.utf8Offset).raw - let lParamLoc = self.base.advanced(by: node.signature.input.rightParen.position.utf8Offset).raw + let staticLoc = bridgedSourceLoc(for: node) + let funcLoc = bridgedSourceLoc(for: node.funcKeyword) + let nameLoc = bridgedSourceLoc(for: node.identifier) + let rParamLoc = bridgedSourceLoc(for: node.signature.input.leftParen) + let lParamLoc = bridgedSourceLoc(for: node.signature.input.rightParen) var nameText = node.identifier.text - let name = nameText.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + let name = nameText.withBridgedString { bridgedName in + return ASTContext_getIdentifier(ctx, bridgedName) } let returnType: ASTNode? diff --git a/lib/ASTGen/Sources/ASTGen/Diagnostics.swift b/lib/ASTGen/Sources/ASTGen/Diagnostics.swift index 7071029c43983..4d299cc6f19eb 100644 --- a/lib/ASTGen/Sources/ASTGen/Diagnostics.swift +++ b/lib/ASTGen/Sources/ASTGen/Diagnostics.swift @@ -4,13 +4,15 @@ import SwiftSyntax fileprivate func emitDiagnosticParts( diagEnginePtr: UnsafeMutablePointer, - sourceFileBuffer: UnsafeMutableBufferPointer, + sourceFileBuffer: UnsafeBufferPointer, message: String, severity: DiagnosticSeverity, position: AbsolutePosition, highlights: [Syntax] = [], fixItChanges: [FixIt.Change] = [] ) { + let bridgedDiagEngine = BridgedDiagnosticEngine(raw: diagEnginePtr) + // Map severity let bridgedSeverity: BridgedDiagnosticSeverity switch severity { @@ -19,75 +21,66 @@ fileprivate func emitDiagnosticParts( case .warning: bridgedSeverity = .warning } - // Form a source location for the given absolute position - func sourceLoc( - at position: AbsolutePosition - ) -> UnsafeMutablePointer? { - if let sourceFileBase = sourceFileBuffer.baseAddress, - position.utf8Offset >= 0 && - position.utf8Offset < sourceFileBuffer.count { - return sourceFileBase + position.utf8Offset - } - - return nil + func bridgedSourceLoc(at position: AbsolutePosition) -> BridgedSourceLoc { + return BridgedSourceLoc(at: position, in: sourceFileBuffer) } // Emit the diagnostic var mutableMessage = message - let diag = mutableMessage.withUTF8 { messageBuffer in - SwiftDiagnostic_create( - diagEnginePtr, bridgedSeverity, sourceLoc(at: position), - messageBuffer.baseAddress, messageBuffer.count + let diag = mutableMessage.withBridgedString { bridgedMessage in + Diagnostic_create( + bridgedDiagEngine, bridgedSeverity, bridgedSourceLoc(at: position), + bridgedMessage ) } // Emit highlights for highlight in highlights { - SwiftDiagnostic_highlight( - diag, sourceLoc(at: highlight.positionAfterSkippingLeadingTrivia), - sourceLoc(at: highlight.endPositionBeforeTrailingTrivia) + Diagnostic_highlight( + diag, bridgedSourceLoc(at: highlight.positionAfterSkippingLeadingTrivia), + bridgedSourceLoc(at: highlight.endPositionBeforeTrailingTrivia) ) } // Emit changes for a Fix-It. for change in fixItChanges { - let replaceStartLoc: UnsafeMutablePointer? - let replaceEndLoc: UnsafeMutablePointer? + let replaceStartLoc: BridgedSourceLoc + let replaceEndLoc: BridgedSourceLoc var newText: String switch change { case .replace(let oldNode, let newNode): - replaceStartLoc = sourceLoc(at: oldNode.position) - replaceEndLoc = sourceLoc(at: oldNode.endPosition) + replaceStartLoc = bridgedSourceLoc(at: oldNode.position) + replaceEndLoc = bridgedSourceLoc(at: oldNode.endPosition) newText = newNode.description case .replaceLeadingTrivia(let oldToken, let newTrivia): - replaceStartLoc = sourceLoc(at: oldToken.position) - replaceEndLoc = sourceLoc( + replaceStartLoc = bridgedSourceLoc(at: oldToken.position) + replaceEndLoc = bridgedSourceLoc( at: oldToken.positionAfterSkippingLeadingTrivia) newText = newTrivia.description case .replaceTrailingTrivia(let oldToken, let newTrivia): - replaceStartLoc = sourceLoc(at: oldToken.endPositionBeforeTrailingTrivia) - replaceEndLoc = sourceLoc(at: oldToken.endPosition) + replaceStartLoc = bridgedSourceLoc(at: oldToken.endPositionBeforeTrailingTrivia) + replaceEndLoc = bridgedSourceLoc(at: oldToken.endPosition) newText = newTrivia.description } - newText.withUTF8 { textBuffer in - SwiftDiagnostic_fixItReplace( + newText.withBridgedString { bridgedMessage in + Diagnostic_fixItReplace( diag, replaceStartLoc, replaceEndLoc, - textBuffer.baseAddress, textBuffer.count + bridgedMessage ) } } - SwiftDiagnostic_finish(diag); + Diagnostic_finish(diag); } /// Emit the given diagnostic via the diagnostic engine. func emitDiagnostic( diagEnginePtr: UnsafeMutablePointer, - sourceFileBuffer: UnsafeMutableBufferPointer, + sourceFileBuffer: UnsafeBufferPointer, diagnostic: Diagnostic, diagnosticSeverity: DiagnosticSeverity, messageSuffix: String? = nil @@ -145,69 +138,69 @@ extension SourceManager { // Emit the diagnostic var mutableMessage = message - let diag = mutableMessage.withUTF8 { messageBuffer in - SwiftDiagnostic_create( - cxxDiagnosticEngine, bridgedSeverity, - cxxSourceLocation(for: node, at: position), - messageBuffer.baseAddress, messageBuffer.count + let diag = mutableMessage.withBridgedString { bridgedMessage in + Diagnostic_create( + bridgedDiagEngine, bridgedSeverity, + bridgedSourceLoc(for: node, at: position), + bridgedMessage ) } // Emit highlights for highlight in highlights { - SwiftDiagnostic_highlight( + Diagnostic_highlight( diag, - cxxSourceLocation(for: highlight, at: highlight.positionAfterSkippingLeadingTrivia), - cxxSourceLocation(for: highlight, at: highlight.endPositionBeforeTrailingTrivia) + bridgedSourceLoc(for: highlight, at: highlight.positionAfterSkippingLeadingTrivia), + bridgedSourceLoc(for: highlight, at: highlight.endPositionBeforeTrailingTrivia) ) } // Emit changes for a Fix-It. for change in fixItChanges { - let replaceStartLoc: CxxSourceLoc? - let replaceEndLoc: CxxSourceLoc? + let replaceStartLoc: BridgedSourceLoc + let replaceEndLoc: BridgedSourceLoc var newText: String switch change { case .replace(let oldNode, let newNode): - replaceStartLoc = cxxSourceLocation( + replaceStartLoc = bridgedSourceLoc( for: oldNode, at: oldNode.positionAfterSkippingLeadingTrivia ) - replaceEndLoc = cxxSourceLocation( + replaceEndLoc = bridgedSourceLoc( for: oldNode, at: oldNode.endPositionBeforeTrailingTrivia ) newText = newNode.description case .replaceLeadingTrivia(let oldToken, let newTrivia): - replaceStartLoc = cxxSourceLocation(for: oldToken) - replaceEndLoc = cxxSourceLocation( + replaceStartLoc = bridgedSourceLoc(for: oldToken) + replaceEndLoc = bridgedSourceLoc( for: oldToken, at: oldToken.positionAfterSkippingLeadingTrivia ) newText = newTrivia.description case .replaceTrailingTrivia(let oldToken, let newTrivia): - replaceStartLoc = cxxSourceLocation( + replaceStartLoc = bridgedSourceLoc( for: oldToken, at: oldToken.endPositionBeforeTrailingTrivia) - replaceEndLoc = cxxSourceLocation( + replaceEndLoc = bridgedSourceLoc( for: oldToken, at: oldToken.endPosition ) newText = newTrivia.description } - newText.withUTF8 { textBuffer in - SwiftDiagnostic_fixItReplace( + newText.withBridgedString { bridgedMessage in + Diagnostic_fixItReplace( diag, replaceStartLoc, replaceEndLoc, - textBuffer.baseAddress, textBuffer.count + bridgedMessage ) } } - SwiftDiagnostic_finish(diag); + Diagnostic_finish(diag); } /// Emit a diagnostic via the C++ diagnostic engine. @@ -357,21 +350,25 @@ public func addQueuedDiagnostic( text: UnsafePointer, textLength: Int, severity: BridgedDiagnosticSeverity, - position: CxxSourceLoc, - highlightRangesPtr: UnsafePointer?, + position: BridgedSourceLoc, + highlightRangesPtr: UnsafePointer?, numHighlightRanges: Int ) { let queuedDiagnostics = queuedDiagnosticsPtr.assumingMemoryBound( to: QueuedDiagnostics.self ) + guard let rawPosition = position.raw else { + return + } + // Find the source file that contains this location. let sourceFile = queuedDiagnostics.pointee.sourceFiles.first { sf in guard let baseAddress = sf.buffer.baseAddress else { return false } - return position >= baseAddress && position < baseAddress + sf.buffer.count + return rawPosition >= baseAddress && rawPosition < baseAddress + sf.buffer.count } guard let sourceFile = sourceFile else { // FIXME: Hard to report an error here... @@ -379,22 +376,24 @@ public func addQueuedDiagnostic( } // Find the token at that offset. - let sourceFileBaseAddress = sourceFile.buffer.baseAddress! + let sourceFileBaseAddress = UnsafeRawPointer(sourceFile.buffer.baseAddress!) let sourceFileEndAddress = sourceFileBaseAddress + sourceFile.buffer.count - let offset = position - sourceFileBaseAddress + let offset = rawPosition - sourceFileBaseAddress guard let token = sourceFile.syntax.token(at: AbsolutePosition(utf8Offset: offset)) else { return } // Map the highlights. var highlights: [Syntax] = [] - let highlightRanges = UnsafeBufferPointer( + let highlightRanges = UnsafeBufferPointer( start: highlightRangesPtr, count: numHighlightRanges * 2 ) for index in 0..= sourceFileBaseAddress && start < sourceFileEndAddress, end >= sourceFileBaseAddress && end <= sourceFileEndAddress else { diff --git a/lib/ASTGen/Sources/ASTGen/Exprs.swift b/lib/ASTGen/Sources/ASTGen/Exprs.swift index 38097c72cc218..432a1e77cbee2 100644 --- a/lib/ASTGen/Sources/ASTGen/Exprs.swift +++ b/lib/ASTGen/Sources/ASTGen/Exprs.swift @@ -4,10 +4,10 @@ import SwiftSyntax extension ASTGenVisitor { public func visit(_ node: ClosureExprSyntax) -> ASTNode { - let statements = node.statements.map { self.visit($0).bridged() } + let statements = node.statements.map { self.visit($0).bridged } let body: UnsafeMutableRawPointer = statements.withBridgedArrayRef { ref in - let startLoc = self.base.advanced(by: node.leftBrace.position.utf8Offset).raw - let endLoc = self.base.advanced(by: node.rightBrace.position.utf8Offset).raw + let startLoc = bridgedSourceLoc(for: node.leftBrace) + let endLoc = bridgedSourceLoc(for: node.rightBrace) return BraceStmt_create(ctx, startLoc, ref, endLoc) } @@ -26,37 +26,37 @@ extension ASTGenVisitor { let args = visit(node.argumentList).rawValue let callee = visit(node.calledExpression).rawValue - return .expr(SwiftFunctionCallExpr_create(self.ctx, callee, args)) + return .expr(FunctionCallExpr_create(self.ctx, callee, args)) } public func visit(_ node: IdentifierExprSyntax) -> ASTNode { - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) var text = node.identifier.text - let id = text.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + let id = text.withBridgedString { bridgedText in + return ASTContext_getIdentifier(ctx, bridgedText) } - return .expr(SwiftIdentifierExpr_create(ctx, id, loc)) + return .expr(IdentifierExpr_create(ctx, id, loc)) } public func visit(_ node: IdentifierPatternSyntax) -> ASTNode { - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) var text = node.identifier.text - let id = text.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + let id = text.withBridgedString { bridgedText in + return ASTContext_getIdentifier(ctx, bridgedText) } - return .expr(SwiftIdentifierExpr_create(ctx, id, loc)) + return .expr(IdentifierExpr_create(ctx, id, loc)) } public func visit(_ node: MemberAccessExprSyntax) -> ASTNode { - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) let base = visit(node.base!).rawValue var nameText = node.name.text - let name = nameText.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + let name = nameText.withBridgedString { bridgedName in + return ASTContext_getIdentifier(ctx, bridgedName) } return .expr(UnresolvedDotExpr_create(ctx, base, loc, name, loc)) @@ -77,24 +77,24 @@ extension ASTGenVisitor { guard var name = $0.label?.text else { return nil } - return name.withUTF8 { buf in - SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + return name.withBridgedString { bridgedName in + ASTContext_getIdentifier(ctx, bridgedName) } } - let labelLocs: [UnsafeMutableRawPointer] = node.map { + let labelLocs: [BridgedSourceLoc] = node.map { let pos = $0.label?.position ?? $0.position - return base.advanced(by: pos.utf8Offset).raw + return bridgedSourceLoc(at: pos) } - let lParenLoc = self.base.advanced(by: node.position.utf8Offset).raw - let rParenLoc = self.base.advanced(by: node.endPosition.utf8Offset).raw + let lParenLoc = bridgedSourceLoc(for: node) + let rParenLoc = bridgedSourceLoc(at: node.endPosition) return .expr( elements.withBridgedArrayRef { elementsRef in labels.withBridgedArrayRef { labelsRef in labelLocs.withBridgedArrayRef { labelLocRef in - SwiftTupleExpr_create(self.ctx, lParenLoc, elementsRef, labelsRef, - labelLocRef, rParenLoc) + TupleExpr_create(self.ctx, lParenLoc, elementsRef, labelsRef, + labelLocRef, rParenLoc) } } }) diff --git a/lib/ASTGen/Sources/ASTGen/Generics.swift b/lib/ASTGen/Sources/ASTGen/Generics.swift index 22163381143b0..46b4b3bf90419 100644 --- a/lib/ASTGen/Sources/ASTGen/Generics.swift +++ b/lib/ASTGen/Sources/ASTGen/Generics.swift @@ -4,11 +4,9 @@ import SwiftSyntax extension ASTGenVisitor { func visit(_ node: GenericParameterClauseSyntax) -> ASTNode { - let lAngleLoc = self.base.advanced(by: node.leftAngleBracket.position.utf8Offset).raw - let whereLoc = node.genericWhereClause.map { - self.base.advanced(by: $0.whereKeyword.position.utf8Offset).raw - } - let rAngleLoc = self.base.advanced(by: node.rightAngleBracket.position.utf8Offset).raw + let lAngleLoc = bridgedSourceLoc(for: node.leftAngleBracket) + let whereLoc = bridgedSourceLoc(for: node.genericWhereClause?.whereKeyword) + let rAngleLoc = bridgedSourceLoc(for: node.rightAngleBracket) return .misc( self.withBridgedParametersAndRequirements(node) { params, reqs in return GenericParamList_create(self.ctx, lAngleLoc, params, whereLoc, reqs, rAngleLoc) @@ -17,11 +15,11 @@ extension ASTGenVisitor { func visit(_ node: GenericParameterSyntax) -> ASTNode { var nodeName = node.name.text - let name = nodeName.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + let name = nodeName.withBridgedString { bridgedName in + return ASTContext_getIdentifier(ctx, bridgedName) } - let nameLoc = self.base.advanced(by: node.name.position.utf8Offset).raw - let eachLoc = node.each.map { self.base.advanced(by: $0.position.utf8Offset).raw } + let nameLoc = bridgedSourceLoc(for: node.name) + let eachLoc = bridgedSourceLoc(for: node.each) var genericParameterIndex: Int? for (index, sibling) in (node.parent?.as(GenericParameterListSyntax.self) ?? []).enumerated() { @@ -37,7 +35,7 @@ extension ASTGenVisitor { return .decl( GenericTypeParamDecl_create( self.ctx, self.declContext, name, nameLoc, eachLoc, genericParameterIndex, - eachLoc != nil)) + eachLoc.raw != nil)) } } @@ -65,7 +63,7 @@ extension ASTGenVisitor { switch requirement.body { case .conformanceRequirement(let conformance): let firstType = self.visit(conformance.leftTypeIdentifier).rawValue - let separatorLoc = self.base.advanced(by: conformance.colon.position.utf8Offset).raw + let separatorLoc = bridgedSourceLoc(for: conformance.colon) let secondType = self.visit(conformance.rightTypeIdentifier).rawValue requirements.append( BridgedRequirementRepr( @@ -75,7 +73,7 @@ extension ASTGenVisitor { SecondType: secondType)) case .sameTypeRequirement(let sameType): let firstType = self.visit(sameType.leftTypeIdentifier).rawValue - let separatorLoc = self.base.advanced(by: sameType.equalityToken.position.utf8Offset).raw + let separatorLoc = bridgedSourceLoc(for: sameType.equalityToken) let secondType = self.visit(sameType.rightTypeIdentifier).rawValue requirements.append( BridgedRequirementRepr( diff --git a/lib/ASTGen/Sources/ASTGen/Literals.swift b/lib/ASTGen/Sources/ASTGen/Literals.swift index 1653d09ac348d..21d538df2d939 100644 --- a/lib/ASTGen/Sources/ASTGen/Literals.swift +++ b/lib/ASTGen/Sources/ASTGen/Literals.swift @@ -4,38 +4,38 @@ import SwiftSyntax extension ASTGenVisitor { public func visit(_ node: StringLiteralExprSyntax) -> ASTNode { - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) var segment = node.segments.first!.as(StringSegmentSyntax.self)!.content.text return .expr( - segment.withUTF8 { buf in - return SwiftStringLiteralExpr_create(ctx, buf.baseAddress, buf.count, loc) + segment.withBridgedString { bridgedSegment in + return StringLiteralExpr_create(ctx, bridgedSegment, loc) }) } public func visit(_ node: IntegerLiteralExprSyntax) -> ASTNode { - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) var segment = node.digits.text return .expr( - segment.withUTF8 { buf in - return SwiftIntegerLiteralExpr_create(ctx, buf.baseAddress, buf.count, loc) + segment.withBridgedString { bridgedSegment in + return IntegerLiteralExpr_create(ctx, bridgedSegment, loc) }) } public func visit(_ node: BooleanLiteralExprSyntax) -> ASTNode { - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) let value = node.booleanLiteral == .keyword(.true) - return .expr(SwiftBooleanLiteralExpr_create(ctx, value, loc)) + return .expr(BooleanLiteralExpr_create(ctx, value, loc)) } public func visit(_ node: ArrayExprSyntax) -> ASTNode { - let lLoc = self.base.advanced(by: node.leftSquare.position.utf8Offset).raw - let rLoc = self.base.advanced(by: node.rightSquare.position.utf8Offset).raw + let lLoc = bridgedSourceLoc(for: node.leftSquare) + let rLoc = bridgedSourceLoc(for: node.rightSquare) let elements = node.elements.map { self.visit($0).rawValue } let commas = node.elements .compactMap { $0.trailingComma } .map { - self.base.advanced(by: $0.position.utf8Offset).raw + bridgedSourceLoc(for: $0) } return elements.withBridgedArrayRef { elementsRef in diff --git a/lib/ASTGen/Sources/ASTGen/Misc.swift b/lib/ASTGen/Sources/ASTGen/Misc.swift index bb63fd0b1b181..0cecfdbe7bb69 100644 --- a/lib/ASTGen/Sources/ASTGen/Misc.swift +++ b/lib/ASTGen/Sources/ASTGen/Misc.swift @@ -26,4 +26,53 @@ extension ASTGenVisitor { public func visit(_ node: ArrayElementSyntax) -> ASTNode { visit(node.expression) } + + /// Form a source location at the given absolute position in the current + /// file. + public func bridgedSourceLoc(at position: AbsolutePosition) -> BridgedSourceLoc { + return BridgedSourceLoc(at: position, in: base) + } + + /// Form a source location at the given node's position in the current file. + public func bridgedSourceLoc(for node: Node?) -> BridgedSourceLoc { + guard let node = node else { + return nil + } + return BridgedSourceLoc(at: node.position, in: base) + } +} + +extension BridgedSourceLoc: ExpressibleByNilLiteral { + public init(nilLiteral: ()) { + self.init(raw: nil) + } +} + +extension BridgedIdentifier: ExpressibleByNilLiteral { + public init(nilLiteral: ()) { + self.init(raw: nil) + } +} + +extension BridgedSourceLoc { + /// Form a source location at the given absolute position in `buffer`. + init( + at position: AbsolutePosition, + in buffer: UnsafeBufferPointer + ) { + if let start = buffer.baseAddress, + position.utf8Offset >= 0 && position.utf8Offset < buffer.count { + self = SourceLoc_advanced(BridgedSourceLoc(raw: start), position.utf8Offset) + } else { + self = nil + } + } +} + +extension String { + mutating func withBridgedString(_ body: (BridgedString) throws -> R) rethrows -> R { + try withUTF8 { buffer in + try body(BridgedString(data: buffer.baseAddress, length: buffer.count)) + } + } } diff --git a/lib/ASTGen/Sources/ASTGen/PluginHost.swift b/lib/ASTGen/Sources/ASTGen/PluginHost.swift index ee90ad3990f2f..e14c14db41ded 100644 --- a/lib/ASTGen/Sources/ASTGen/PluginHost.swift +++ b/lib/ASTGen/Sources/ASTGen/PluginHost.swift @@ -188,11 +188,11 @@ struct CompilerPlugin { } class PluginDiagnosticsEngine { - private let cxxDiagnosticEngine: UnsafeMutablePointer + private let bridgedDiagEngine: BridgedDiagnosticEngine private var exportedSourceFileByName: [String: UnsafePointer] = [:] init(cxxDiagnosticEngine: UnsafeMutablePointer) { - self.cxxDiagnosticEngine = cxxDiagnosticEngine + self.bridgedDiagEngine = BridgedDiagnosticEngine(raw: cxxDiagnosticEngine) } /// Failable convenience initializer for optional cxx engine pointer. @@ -258,34 +258,34 @@ class PluginDiagnosticsEngine { // Emit the diagnostic var mutableMessage = message - let diag = mutableMessage.withUTF8 { messageBuffer in - SwiftDiagnostic_create( - cxxDiagnosticEngine, bridgedSeverity, - cxxSourceLocation(at: position), - messageBuffer.baseAddress, messageBuffer.count) + let diag = mutableMessage.withBridgedString { bridgedMessage in + Diagnostic_create( + bridgedDiagEngine, bridgedSeverity, + bridgedSourceLoc(at: position), + bridgedMessage) } // Emit highlights for highlight in highlights { - guard let (startLoc, endLoc) = cxxSourceRange(for: highlight) else { + guard let (startLoc, endLoc) = bridgedSourceRange(for: highlight) else { continue } - SwiftDiagnostic_highlight(diag, startLoc, endLoc) + Diagnostic_highlight(diag, startLoc, endLoc) } // Emit changes for a Fix-It. for change in fixItChanges { - guard let (startLoc, endLoc) = cxxSourceRange(for: change.range) else { + guard let (startLoc, endLoc) = bridgedSourceRange(for: change.range) else { continue } var newText = change.newText - newText.withUTF8 { textBuffer in - SwiftDiagnostic_fixItReplace( - diag, startLoc, endLoc, textBuffer.baseAddress, textBuffer.count) + newText.withBridgedString { bridgedFixItText in + Diagnostic_fixItReplace( + diag, startLoc, endLoc, bridgedFixItText) } } - SwiftDiagnostic_finish(diag) + Diagnostic_finish(diag) } /// Emit diagnostics. @@ -312,40 +312,36 @@ class PluginDiagnosticsEngine { /// Produce the C++ source location for a given position based on a /// syntax node. - private func cxxSourceLocation( + private func bridgedSourceLoc( at offset: Int, in fileName: String - ) -> CxxSourceLoc? { + ) -> BridgedSourceLoc { // Find the corresponding exported source file. - guard - let exportedSourceFile = exportedSourceFileByName[fileName] - else { + guard let exportedSourceFile = exportedSourceFileByName[fileName] else { return nil } // Compute the resulting address. - guard - let bufferBaseAddress = exportedSourceFile.pointee.buffer.baseAddress - else { + guard let bufferBaseAddress = exportedSourceFile.pointee.buffer.baseAddress else { return nil } - return bufferBaseAddress.advanced(by: offset) + return SourceLoc_advanced(BridgedSourceLoc(raw: bufferBaseAddress), offset) } /// C++ source location from a position value from a plugin. - private func cxxSourceLocation( + private func bridgedSourceLoc( at position: PluginMessage.Diagnostic.Position - ) -> CxxSourceLoc? { - cxxSourceLocation(at: position.offset, in: position.fileName) + ) -> BridgedSourceLoc { + return bridgedSourceLoc(at: position.offset, in: position.fileName) } /// C++ source range from a range value from a plugin. - private func cxxSourceRange( + private func bridgedSourceRange( for range: PluginMessage.Diagnostic.PositionRange - ) -> (start: CxxSourceLoc, end: CxxSourceLoc)? { - guard - let start = cxxSourceLocation(at: range.startOffset, in: range.fileName), - let end = cxxSourceLocation(at: range.endOffset, in: range.fileName) - else { + ) -> (start: BridgedSourceLoc, end: BridgedSourceLoc)? { + let start = bridgedSourceLoc(at: range.startOffset, in: range.fileName) + let end = bridgedSourceLoc(at: range.endOffset, in: range.fileName) + + if start.raw == nil || end.raw == nil { return nil } return (start: start, end: end ) @@ -364,9 +360,8 @@ extension PluginMessage.Syntax { case syntax.is(AttributeSyntax.self): kind = .attribute default: return nil } - let source = syntax.description - + let source = syntax.description let sourceStr = String(decoding: sourceFilePtr.pointee.buffer, as: UTF8.self) let fileName = sourceFilePtr.pointee.fileName let fileID = "\(sourceFilePtr.pointee.moduleName)/\(sourceFilePtr.pointee.fileName.basename)" diff --git a/lib/ASTGen/Sources/ASTGen/SourceFile.swift b/lib/ASTGen/Sources/ASTGen/SourceFile.swift index 5def6146f4a6a..227f00e83e75c 100644 --- a/lib/ASTGen/Sources/ASTGen/SourceFile.swift +++ b/lib/ASTGen/Sources/ASTGen/SourceFile.swift @@ -110,8 +110,7 @@ public func emitParserDiagnostics( emitDiagnostic( diagEnginePtr: diagEnginePtr, - sourceFileBuffer: UnsafeMutableBufferPointer( - mutating: sourceFile.pointee.buffer), + sourceFileBuffer: sourceFile.pointee.buffer, diagnostic: diag, diagnosticSeverity: diagnosticSeverity ) diff --git a/lib/ASTGen/Sources/ASTGen/SourceManager.swift b/lib/ASTGen/Sources/ASTGen/SourceManager.swift index e7b410a2fa765..a3e2551e07dba 100644 --- a/lib/ASTGen/Sources/ASTGen/SourceManager.swift +++ b/lib/ASTGen/Sources/ASTGen/SourceManager.swift @@ -1,18 +1,16 @@ +import CASTBridging import SwiftOperators import SwiftSyntax import SwiftSyntaxMacros -/// A C++ source location. -public typealias CxxSourceLoc = UnsafePointer - /// A source manager that keeps track of the source files in the program. class SourceManager { init(cxxDiagnosticEngine: UnsafeMutablePointer) { - self.cxxDiagnosticEngine = cxxDiagnosticEngine + self.bridgedDiagEngine = BridgedDiagnosticEngine(raw: cxxDiagnosticEngine) } - /// A pointer to the C++ diagnostic engine. - let cxxDiagnosticEngine: UnsafeMutablePointer + /// The bridged diagnostic engine (just the wrapped C++ `DiagnosticEngine`). + let bridgedDiagEngine: BridgedDiagnosticEngine /// The set of source files that have been exported to the C++ code of /// the program. @@ -100,10 +98,10 @@ extension SourceManager { /// Produce the C++ source location for a given position based on a /// syntax node. - func cxxSourceLocation( + func bridgedSourceLoc( for node: Node, at position: AbsolutePosition? = nil - ) -> CxxSourceLoc? { + ) -> BridgedSourceLoc { // Find the source file and this node's position within it. guard let (sourceFile, rootPosition) = rootSourceFile(of: node) else { return nil @@ -118,16 +116,9 @@ extension SourceManager { // Find the offset of the given position based on the root of the given // node. let position = position ?? node.position - let offsetWithinSyntaxNode = - position.utf8Offset - node.position.utf8Offset - let offsetFromSourceFile = rootPosition.utf8Offset + offsetWithinSyntaxNode + let nodeOffset = SourceLength(utf8Length: position.utf8Offset - node.position.utf8Offset) + let realPosition = rootPosition + nodeOffset - // Compute the resulting address. - guard let bufferBaseAddress = exportedSourceFile.pointee.buffer.baseAddress - else { - return nil - } - let address = bufferBaseAddress.advanced(by: offsetFromSourceFile) - return address + return BridgedSourceLoc(at: realPosition, in: exportedSourceFile.pointee.buffer) } } diff --git a/lib/ASTGen/Sources/ASTGen/Stmts.swift b/lib/ASTGen/Sources/ASTGen/Stmts.swift index 9b8b625974520..5b32bd6611270 100644 --- a/lib/ASTGen/Sources/ASTGen/Stmts.swift +++ b/lib/ASTGen/Sources/ASTGen/Stmts.swift @@ -4,9 +4,9 @@ import SwiftSyntax extension ASTGenVisitor { public func visit(_ node: CodeBlockSyntax) -> ASTNode { - let statements = node.statements.map { self.visit($0).bridged() } - let startLoc = self.base.advanced(by: node.leftBrace.position.utf8Offset).raw - let endLoc = self.base.advanced(by: node.rightBrace.position.utf8Offset).raw + let statements = node.statements.map { self.visit($0).bridged } + let startLoc = bridgedSourceLoc(for: node.leftBrace) + let endLoc = bridgedSourceLoc(for: node.rightBrace) return .stmt( statements.withBridgedArrayRef { ref in @@ -19,7 +19,7 @@ extension ASTGenVisitor { assert(conditions.count == 1) // TODO: handle multiple conditions. let body = visit(node.body).rawValue - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) if let elseBody = node.elseBody, node.elseKeyword != nil { return .stmt(IfStmt_create(ctx, loc, conditions.first!, body, loc, @@ -39,7 +39,7 @@ extension ASTGenVisitor { } public func visit(_ node: ReturnStmtSyntax) -> ASTNode { - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) let expr: ASTNode? if let expression = node.expression { diff --git a/lib/ASTGen/Sources/ASTGen/Types.swift b/lib/ASTGen/Sources/ASTGen/Types.swift index 82bbca53bf4b2..34a185fe13fbf 100644 --- a/lib/ASTGen/Sources/ASTGen/Types.swift +++ b/lib/ASTGen/Sources/ASTGen/Types.swift @@ -4,7 +4,7 @@ import SwiftSyntax extension ASTGenVisitor { public func visit(_ node: SimpleTypeIdentifierSyntax) -> ASTNode { - let loc = self.base.advanced(by: node.position.utf8Offset).raw + let loc = bridgedSourceLoc(for: node) // If this is the bare 'Any' keyword, produce an empty composition type. if node.name.tokenKind == .keyword(.Any) && node.genericArgumentClause == nil { @@ -12,16 +12,16 @@ extension ASTGenVisitor { } var text = node.name.text - let id = text.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + let id = text.withBridgedString { bridgedText in + return ASTContext_getIdentifier(ctx, bridgedText) } guard let generics = node.genericArgumentClause else { return .type(SimpleIdentTypeRepr_create(ctx, loc, id)) } - let lAngle = self.base.advanced(by: generics.leftAngleBracket.position.utf8Offset).raw - let rAngle = self.base.advanced(by: generics.rightAngleBracket.position.utf8Offset).raw + let lAngle = bridgedSourceLoc(for: generics.leftAngleBracket) + let rAngle = bridgedSourceLoc(for: generics.rightAngleBracket) return .type( generics.arguments.map({ self.visit($0.argumentType).rawValue @@ -42,14 +42,14 @@ extension ASTGenVisitor { let generics = memberType.genericArgumentClause var nameText = nameToken.text - let name = nameText.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) + let name = nameText.withBridgedString { bridgedName in + return ASTContext_getIdentifier(ctx, bridgedName) } - let nameLoc = self.base.advanced(by: nameToken.position.utf8Offset).raw + let nameLoc = bridgedSourceLoc(for: nameToken) if let generics = generics { - let lAngle = self.base.advanced(by: generics.leftAngleBracket.position.utf8Offset).raw - let rAngle = self.base.advanced(by: generics.rightAngleBracket.position.utf8Offset).raw + let lAngle = bridgedSourceLoc(for: generics.leftAngleBracket) + let rAngle = bridgedSourceLoc(for: generics.rightAngleBracket) reverseMemberComponents.append( generics.arguments.map({ self.visit($0.argumentType).rawValue }).withBridgedArrayRef { genericArgs in @@ -72,24 +72,24 @@ extension ASTGenVisitor { public func visit(_ node: ArrayTypeSyntax) -> ASTNode { let elementType = visit(node.elementType).rawValue - let lSquareLoc = self.base.advanced(by: node.leftSquareBracket.position.utf8Offset).raw - let rSquareLoc = self.base.advanced(by: node.rightSquareBracket.position.utf8Offset).raw + let lSquareLoc = bridgedSourceLoc(for: node.leftSquareBracket) + let rSquareLoc = bridgedSourceLoc(for: node.rightSquareBracket) return .type(ArrayTypeRepr_create(self.ctx, elementType, lSquareLoc, rSquareLoc)) } public func visit(_ node: DictionaryTypeSyntax) -> ASTNode { let keyType = visit(node.keyType).rawValue let valueType = visit(node.valueType).rawValue - let colonLoc = self.base.advanced(by: node.colon.position.utf8Offset).raw - let lSquareLoc = self.base.advanced(by: node.leftSquareBracket.position.utf8Offset).raw - let rSquareLoc = self.base.advanced(by: node.rightSquareBracket.position.utf8Offset).raw + let colonLoc = bridgedSourceLoc(for: node.colon) + let lSquareLoc = bridgedSourceLoc(for: node.leftSquareBracket) + let rSquareLoc = bridgedSourceLoc(for: node.rightSquareBracket) return .type( DictionaryTypeRepr_create(self.ctx, keyType, valueType, colonLoc, lSquareLoc, rSquareLoc)) } public func visit(_ node: MetatypeTypeSyntax) -> ASTNode { let baseType = visit(node.baseType).rawValue - let tyLoc = self.base.advanced(by: node.typeOrProtocol.position.utf8Offset).raw + let tyLoc = bridgedSourceLoc(for: node.typeOrProtocol) if node.typeOrProtocol.text == "Type" { return .type(MetatypeTypeRepr_create(self.ctx, baseType, tyLoc)) } else { @@ -100,26 +100,26 @@ extension ASTGenVisitor { public func visit(_ node: ImplicitlyUnwrappedOptionalTypeSyntax) -> ASTNode { let base = visit(node.wrappedType).rawValue - let exclaimLoc = self.base.advanced(by: node.exclamationMark.position.utf8Offset).raw + let exclaimLoc = bridgedSourceLoc(for: node.exclamationMark) return .type(ImplicitlyUnwrappedOptionalTypeRepr_create(self.ctx, base, exclaimLoc)) } public func visit(_ node: OptionalTypeSyntax) -> ASTNode { let base = visit(node.wrappedType).rawValue - let questionLoc = self.base.advanced(by: node.questionMark.position.utf8Offset).raw + let questionLoc = bridgedSourceLoc(for: node.questionMark) return .type(OptionalTypeRepr_create(self.ctx, base, questionLoc)) } public func visit(_ node: PackExpansionTypeSyntax) -> ASTNode { let base = visit(node.patternType).rawValue - let repeatLoc = self.base.advanced(by: node.repeatKeyword.position.utf8Offset).raw + let repeatLoc = bridgedSourceLoc(for: node.repeatKeyword) return .type(PackExpansionTypeRepr_create(self.ctx, base, repeatLoc)) } public func visit(_ node: TupleTypeSyntax) -> ASTNode { return self.withBridgedTupleElements(node.elements) { elements in - let lParenLoc = self.base.advanced(by: node.leftParen.position.utf8Offset).raw - let rParenLoc = self.base.advanced(by: node.rightParen.position.utf8Offset).raw + let lParenLoc = bridgedSourceLoc(for: node.leftParen) + let rParenLoc = bridgedSourceLoc(for: node.rightParen) return .type(TupleTypeRepr_create(self.ctx, elements, lParenLoc, rParenLoc)) } } @@ -127,9 +127,8 @@ extension ASTGenVisitor { public func visit(_ node: CompositionTypeSyntax) -> ASTNode { assert(node.elements.count > 1) let types = node.elements.map { visit($0.type) }.map { $0.rawValue } - let firstTypeLoc = self.base.advanced(by: node.elements.first!.type.position.utf8Offset).raw - let firstAmpOffset = node.elements.first?.ampersand.map { $0.position.utf8Offset } ?? 0 - let firstAmpLoc = self.base.advanced(by: firstAmpOffset).raw + let firstTypeLoc = bridgedSourceLoc(for: node.elements.first?.type) + let firstAmpLoc = bridgedSourceLoc(for: node.elements.first?.ampersand) return .type( types.withBridgedArrayRef { types in return CompositionTypeRepr_create(self.ctx, types, firstTypeLoc, firstAmpLoc) @@ -138,14 +137,12 @@ extension ASTGenVisitor { public func visit(_ node: FunctionTypeSyntax) -> ASTNode { return self.withBridgedTupleElements(node.arguments) { elements in - let lParenLoc = self.base.advanced(by: node.leftParen.position.utf8Offset).raw - let rParenLoc = self.base.advanced(by: node.rightParen.position.utf8Offset).raw + let lParenLoc = bridgedSourceLoc(for: node.leftParen) + let rParenLoc = bridgedSourceLoc(for: node.rightParen) let args = TupleTypeRepr_create(self.ctx, elements, lParenLoc, rParenLoc) - let asyncLoc = node.effectSpecifiers?.asyncSpecifier.map { self.base.advanced(by: $0.position.utf8Offset).raw } - let throwsLoc = node.effectSpecifiers?.throwsSpecifier.map { - self.base.advanced(by: $0.position.utf8Offset).raw - } - let arrowLoc = self.base.advanced(by: node.output.arrow.position.utf8Offset).raw + let asyncLoc = bridgedSourceLoc(for: node.effectSpecifiers?.asyncSpecifier) + let throwsLoc = bridgedSourceLoc(for: node.effectSpecifiers?.throwsSpecifier) + let arrowLoc = bridgedSourceLoc(for: node.output.arrow) let retTy = visit(node.output.returnType).rawValue return .type(FunctionTypeRepr_create(self.ctx, args, asyncLoc, throwsLoc, arrowLoc, retTy)) } @@ -157,7 +154,7 @@ extension ASTGenVisitor { } public func visit(_ node: ConstrainedSugarTypeSyntax) -> ASTNode { - let someOrAnyLoc = self.base.advanced(by: node.someOrAnySpecifier.position.utf8Offset).raw + let someOrAnyLoc = bridgedSourceLoc(for: node.someOrAnySpecifier) let baseTy = visit(node.baseType).rawValue if node.someOrAnySpecifier.text == "some" { return .type(OpaqueReturnTypeRepr_create(self.ctx, someOrAnyLoc, baseTy)) @@ -172,7 +169,7 @@ extension ASTGenVisitor { // Handle specifiers. if let specifier = node.specifier { - let specifierLoc = self.base.advanced(by: specifier.position.utf8Offset).raw + let specifierLoc = bridgedSourceLoc(for: specifier) let kind: BridgedAttributedTypeSpecifier switch specifier.tokenKind { @@ -191,7 +188,7 @@ extension ASTGenVisitor { // Handle type attributes. if let attributes = node.attributes { - let typeAttributes = BridgedTypeAttributes_create() + let typeAttributes = TypeAttributes_create() for attributeElt in attributes { // FIXME: Ignoring #ifs entirely. We want to provide a filtered view, // but we don't have that ability right now. @@ -206,11 +203,11 @@ extension ASTGenVisitor { let nameSyntax = identType.name var name = nameSyntax.text - let typeAttrKind = name.withUTF8 { buf in - getBridgedTypeAttrKindFromString(buf.baseAddress, buf.count) + let typeAttrKind = name.withBridgedString { bridgedName in + TypeAttrKind_fromString(bridgedName) } - let atLoc = self.base.advanced(by: attribute.atSignToken.position.utf8Offset).raw - let attrLoc = self.base.advanced(by: nameSyntax.position.utf8Offset).raw + let atLoc = bridgedSourceLoc(for: attribute.atSignToken) + let attrLoc = bridgedSourceLoc(for: nameSyntax) switch typeAttrKind { // SIL attributes // FIXME: Diagnose if not in SIL mode? Or should that move to the @@ -226,7 +223,7 @@ extension ASTGenVisitor { .sendable, .unchecked, ._local, ._noMetadata, .pack_owned, .pack_guaranteed, .pack_inout, .pack_out, .pseudogeneric, .yields, .yield_once, .yield_many, .thin, .thick, .count: - BridgedTypeAttributes_addSimpleAttr(typeAttributes, typeAttrKind, atLoc, attrLoc) + TypeAttributes_addSimpleAttr(typeAttributes, typeAttrKind, atLoc, attrLoc) case .opened, .pack_element, .differentiable, .convention, ._opaqueReturnTypeOf: @@ -250,28 +247,22 @@ extension ASTGenVisitor { var elements = [BridgedTupleTypeElement]() for element in elementList { var nameText = element.name?.text - let name = nameText?.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) - } - let nameLoc = element.name.map { self.base.advanced(by: $0.position.utf8Offset).raw } + let name = nameText?.withBridgedString { bridgedName in + return ASTContext_getIdentifier(ctx, bridgedName) + } ?? nil + let nameLoc = bridgedSourceLoc(for: element.name) var secondNameText = element.secondName?.text - let secondName = secondNameText?.withUTF8 { buf in - return SwiftASTContext_getIdentifier(ctx, buf.baseAddress, buf.count) - } - let secondNameLoc = element.secondName.map { - self.base.advanced(by: $0.position.utf8Offset).raw - } - let colonLoc = element.colon.map { self.base.advanced(by: $0.position.utf8Offset).raw } - + let secondName = secondNameText?.withBridgedString { bridgedName in + return ASTContext_getIdentifier(ctx, bridgedName) + } ?? nil + let secondNameLoc = bridgedSourceLoc(for: element.secondName) + let colonLoc = bridgedSourceLoc(for: element.colon) var type = visit(element.type).rawValue if let ellipsis = element.ellipsis { - let ellipsisLoc = self.base.advanced(by: ellipsis.positionAfterSkippingLeadingTrivia.utf8Offset).raw + let ellipsisLoc = bridgedSourceLoc(at: ellipsis.positionAfterSkippingLeadingTrivia) type = VarargTypeRepr_create(self.ctx, type, ellipsisLoc) } - - let trailingCommaLoc = element.trailingComma.map { - self.base.advanced(by: $0.position.utf8Offset).raw - } + let trailingCommaLoc = bridgedSourceLoc(for: element.trailingComma) elements.append( BridgedTupleTypeElement( @@ -318,7 +309,7 @@ func buildTypeRepr( endTypeLocPtr.pointee = sourceFile.pointee.buffer.baseAddress!.advanced(by: typeSyntax.endPosition.utf8Offset) // Convert the type syntax node. - let typeReprNode = ASTGenVisitor(ctx: ctx, base: sourceFile.pointee.buffer.baseAddress!, declContext: dc) + let typeReprNode = ASTGenVisitor(ctx: BridgedASTContext(raw: ctx), base: sourceFile.pointee.buffer, declContext: BridgedDeclContext(raw: dc)) .visit(typeSyntax) return typeReprNode.rawValue