diff --git a/lib/ASTGen/.swift-format b/lib/ASTGen/.swift-format new file mode 100644 index 0000000000000..22b48e0903d5e --- /dev/null +++ b/lib/ASTGen/.swift-format @@ -0,0 +1,17 @@ +{ + "version": 1, + "lineLength": 120, + "indentation": { + "spaces": 2 + }, + "lineBreakBeforeEachArgument": true, + "indentConditionalCompilationBlocks": false, + "rules": { + "AlwaysUseLowerCamelCase": false, + "AmbiguousTrailingClosureOverload": false, + "NoBlockComments": false, + "OrderedImports": true, + "UseLetInEveryBoundCaseVariable": false, + "UseSynthesizedInitializer": false + } +} diff --git a/lib/ASTGen/Package.swift b/lib/ASTGen/Package.swift index 151ea07f960ba..077520beb288d 100644 --- a/lib/ASTGen/Package.swift +++ b/lib/ASTGen/Package.swift @@ -42,7 +42,7 @@ let package = Package( .product(name: "SwiftSyntaxBuilder", package: "swift-syntax"), .product(name: "SwiftSyntaxMacros", package: "swift-syntax"), .product(name: "SwiftSyntaxMacroExpansion", package: "swift-syntax"), - "swiftLLVMJSON" + "swiftLLVMJSON", ], path: "Sources/ASTGen", swiftSettings: swiftSetttings diff --git a/lib/ASTGen/Sources/ASTGen/ASTGen.swift b/lib/ASTGen/Sources/ASTGen/ASTGen.swift index 8a9623d6172a0..8e729fe9e0699 100644 --- a/lib/ASTGen/Sources/ASTGen/ASTGen.swift +++ b/lib/ASTGen/Sources/ASTGen/ASTGen.swift @@ -1,9 +1,8 @@ import CASTBridging import CBasicBridging - // Needed to use BumpPtrAllocator -@_spi(BumpPtrAllocator) -import SwiftSyntax +@_spi(BumpPtrAllocator) import SwiftSyntax + import struct SwiftDiagnostics.Diagnostic extension UnsafePointer { @@ -107,13 +106,19 @@ struct ASTGenVisitor { out.append(d.raw) case .stmt(let s): let topLevelDecl = BridgedTopLevelCodeDecl.createParsed( - self.ctx, declContext: self.declContext, startLoc: loc, stmt: s, + self.ctx, + declContext: self.declContext, + startLoc: loc, + stmt: s, endLoc: loc ) out.append(topLevelDecl.raw) case .expr(let e): let topLevelDecl = BridgedTopLevelCodeDecl.createParsed( - self.ctx, declContext: self.declContext, startLoc: loc, expr: e, + self.ctx, + declContext: self.declContext, + startLoc: loc, + expr: e, endLoc: loc ) out.append(topLevelDecl.raw) @@ -174,7 +179,7 @@ extension ASTGenVisitor { func generate(_ node: some SyntaxChildChoices) -> ASTNode { return self.generate(Syntax(node)) } - + func generate(_ node: Syntax) -> ASTNode { switch node.as(SyntaxEnum.self) { case .actorDecl(let node): diff --git a/lib/ASTGen/Sources/ASTGen/Bridge.swift b/lib/ASTGen/Sources/ASTGen/Bridge.swift index 5710f6c029668..ef9ce9045d270 100644 --- a/lib/ASTGen/Sources/ASTGen/Bridge.swift +++ b/lib/ASTGen/Sources/ASTGen/Bridge.swift @@ -90,7 +90,7 @@ extension Optional where Wrapped: SyntaxProtocol { guard let self else { return nil } - + return self.bridgedSourceLoc(in: astgen) } } diff --git a/lib/ASTGen/Sources/ASTGen/Decls.swift b/lib/ASTGen/Sources/ASTGen/Decls.swift index f4070f69ea85a..c7404074b1c6d 100644 --- a/lib/ASTGen/Sources/ASTGen/Decls.swift +++ b/lib/ASTGen/Sources/ASTGen/Decls.swift @@ -1,8 +1,6 @@ import CASTBridging - -@_spi(ExperimentalLanguageFeatures) -import SwiftSyntax import SwiftDiagnostics +@_spi(ExperimentalLanguageFeatures) import SwiftSyntax // MARK: - TypeDecl @@ -37,7 +35,7 @@ extension ASTGenVisitor { genericWhereClause: self.generate(node.genericWhereClause), braceRange: BridgedSourceRange( startToken: node.memberBlock.leftBrace, - endToken: node.memberBlock.rightBrace, + endToken: node.memberBlock.rightBrace, in: self ) ) @@ -63,7 +61,7 @@ extension ASTGenVisitor { genericWhereClause: self.generate(node.genericWhereClause), braceRange: BridgedSourceRange( startToken: node.memberBlock.leftBrace, - endToken: node.memberBlock.rightBrace, + endToken: node.memberBlock.rightBrace, in: self ) ) @@ -339,14 +337,17 @@ extension BridgedOperatorFixity { extension ASTGenVisitor { func generate(_ node: OperatorDeclSyntax) -> BridgedOperatorDecl { let (name, nameLoc) = node.name.bridgedIdentifierAndSourceLoc(in: self) - let (precedenceGroupName, precedenceGroupLoc) = (node.operatorPrecedenceAndTypes?.precedenceGroup).bridgedIdentifierAndSourceLoc(in: self) + let (precedenceGroupName, precedenceGroupLoc) = (node.operatorPrecedenceAndTypes?.precedenceGroup) + .bridgedIdentifierAndSourceLoc(in: self) let fixity: BridgedOperatorFixity if let value = BridgedOperatorFixity(from: node.fixitySpecifier.tokenKind) { fixity = value } else { fixity = .infix - self.diagnose(Diagnostic(node: node.fixitySpecifier, message: UnexpectedTokenKindError(token: node.fixitySpecifier))) + self.diagnose( + Diagnostic(node: node.fixitySpecifier, message: UnexpectedTokenKindError(token: node.fixitySpecifier)) + ) } return .createParsed( @@ -388,7 +389,9 @@ extension ASTGenVisitor { } func diagnoseDuplicateSyntax(_ duplicate: some SyntaxProtocol, original: some SyntaxProtocol) { - self.diagnose(Diagnostic(node: duplicate, message: DuplicateSyntaxError(duplicate: duplicate, original: original))) + self.diagnose( + Diagnostic(node: duplicate, message: DuplicateSyntaxError(duplicate: duplicate, original: original)) + ) } let body = node.groupAttributes.reduce(into: PrecedenceGroupBody()) { body, element in diff --git a/lib/ASTGen/Sources/ASTGen/Diagnostics.swift b/lib/ASTGen/Sources/ASTGen/Diagnostics.swift index 23b65e9d4b746..71923e70bc8a8 100644 --- a/lib/ASTGen/Sources/ASTGen/Diagnostics.swift +++ b/lib/ASTGen/Sources/ASTGen/Diagnostics.swift @@ -76,7 +76,9 @@ struct DuplicateSyntaxError: ASTGenError { init(duplicate: some SyntaxProtocol, original: some SyntaxProtocol) { precondition(duplicate.kind == original.kind, "Expected duplicate and original to be of same kind") - guard let duplicateParent = duplicate.parent, let originalParent = original.parent, duplicateParent == originalParent, duplicateParent.kind.isSyntaxCollection else { + guard let duplicateParent = duplicate.parent, let originalParent = original.parent, + duplicateParent == originalParent, duplicateParent.kind.isSyntaxCollection + else { preconditionFailure("Expected a shared syntax collection parent") } diff --git a/lib/ASTGen/Sources/ASTGen/DiagnosticsBridge.swift b/lib/ASTGen/Sources/ASTGen/DiagnosticsBridge.swift index b6be1098b39df..7b31ef0da8cf9 100644 --- a/lib/ASTGen/Sources/ASTGen/DiagnosticsBridge.swift +++ b/lib/ASTGen/Sources/ASTGen/DiagnosticsBridge.swift @@ -52,7 +52,8 @@ fileprivate func emitDiagnosticParts( case .replaceLeadingTrivia(let oldToken, let newTrivia): replaceStartLoc = bridgedSourceLoc(at: oldToken.position) replaceEndLoc = bridgedSourceLoc( - at: oldToken.positionAfterSkippingLeadingTrivia) + at: oldToken.positionAfterSkippingLeadingTrivia + ) newText = newTrivia.description case .replaceTrailingTrivia(let oldToken, let newTrivia): @@ -63,7 +64,8 @@ fileprivate func emitDiagnosticParts( newText.withBridgedString { bridgedMessage in diag.fixItReplace( - start: replaceStartLoc, end: replaceEndLoc, + start: replaceStartLoc, + end: replaceEndLoc, replacement: bridgedMessage ) } @@ -117,11 +119,11 @@ func emitDiagnostic( extension DiagnosticSeverity { var bridged: BridgedDiagnosticSeverity { switch self { - case .error: return .error - case .note: return .note - case .warning: return .warning - case .remark: return .remark - @unknown default: return .error + case .error: return .error + case .note: return .note + case .warning: return .warning + case .remark: return .remark + @unknown default: return .error } } } @@ -186,7 +188,8 @@ extension SourceManager { case .replaceTrailingTrivia(let oldToken, let newTrivia): replaceStartLoc = bridgedSourceLoc( for: oldToken, - at: oldToken.endPositionBeforeTrailingTrivia) + at: oldToken.endPositionBeforeTrailingTrivia + ) replaceEndLoc = bridgedSourceLoc( for: oldToken, at: oldToken.endPosition @@ -196,7 +199,8 @@ extension SourceManager { newText.withBridgedString { bridgedMessage in diag.fixItReplace( - start: replaceStartLoc, end: replaceEndLoc, + start: replaceStartLoc, + end: replaceEndLoc, replacement: bridgedMessage ) } @@ -222,11 +226,11 @@ extension SourceManager { // Emit Fix-Its. for fixIt in diagnostic.fixIts { diagnoseSingle( - message: fixIt.message.message, - severity: .note, - node: diagnostic.node, - position: diagnostic.position, - fixItChanges: fixIt.changes + message: fixIt.message.message, + severity: .note, + node: diagnostic.node, + position: diagnostic.position, + fixItChanges: fixIt.changes ) } @@ -315,7 +319,8 @@ public func addQueuedSourceFile( // Determine the parent link, for a child buffer. let parent: (GroupedDiagnostics.SourceFileID, AbsolutePosition)? if parentID >= 0, - let parentSourceFileID = queuedDiagnostics.pointee.sourceFileIDs[parentID] { + let parentSourceFileID = queuedDiagnostics.pointee.sourceFileIDs[parentID] + { parent = (parentSourceFileID.pointee, AbsolutePosition(utf8Offset: positionInParent)) } else { parent = nil @@ -387,17 +392,20 @@ public func addQueuedDiagnostic( // Map the highlights. var highlights: [Syntax] = [] let highlightRanges = UnsafeBufferPointer( - start: highlightRangesPtr, count: numHighlightRanges * 2 + start: highlightRangesPtr, + count: numHighlightRanges * 2 ) for index in 0..= sourceFileBaseAddress && start < sourceFileEndAddress, - end >= sourceFileBaseAddress && end <= sourceFileEndAddress else { + end >= sourceFileBaseAddress && end <= sourceFileEndAddress + else { continue } @@ -414,8 +422,9 @@ public func addQueuedDiagnostic( while true { // If this syntax matches our starting/ending positions, add the // highlight and we're done. - if highlightSyntax.positionAfterSkippingLeadingTrivia == startPos && - highlightSyntax.endPositionBeforeTrailingTrivia == endPos { + if highlightSyntax.positionAfterSkippingLeadingTrivia == startPos + && highlightSyntax.endPositionBeforeTrailingTrivia == endPos + { highlights.append(highlightSyntax) break } diff --git a/lib/ASTGen/Sources/ASTGen/Exprs.swift b/lib/ASTGen/Sources/ASTGen/Exprs.swift index 1ad6f101c24de..ceaf263705451 100644 --- a/lib/ASTGen/Sources/ASTGen/Exprs.swift +++ b/lib/ASTGen/Sources/ASTGen/Exprs.swift @@ -1,6 +1,6 @@ import CASTBridging -import SwiftSyntax import SwiftDiagnostics +import SwiftSyntax extension ASTGenVisitor { public func generate(_ node: ClosureExprSyntax) -> BridgedClosureExpr { @@ -18,10 +18,14 @@ extension ASTGenVisitor { public func generate(_ node: FunctionCallExprSyntax) -> BridgedCallExpr { if !node.arguments.isEmpty || node.trailingClosure == nil { if node.leftParen == nil { - self.diagnose(Diagnostic(node: node, message: MissingChildTokenError(parent: node, kindOfTokenMissing: .leftParen))) + self.diagnose( + Diagnostic(node: node, message: MissingChildTokenError(parent: node, kindOfTokenMissing: .leftParen)) + ) } if node.rightParen == nil { - self.diagnose(Diagnostic(node: node, message: MissingChildTokenError(parent: node, kindOfTokenMissing: .rightParen))) + self.diagnose( + Diagnostic(node: node, message: MissingChildTokenError(parent: node, kindOfTokenMissing: .rightParen)) + ) } } @@ -30,14 +34,20 @@ extension ASTGenVisitor { // Transform the trailing closure into an argument. if let trailingClosure = node.trailingClosure { let tupleElement = LabeledExprSyntax( - label: nil, colon: nil, expression: ExprSyntax(trailingClosure), trailingComma: nil) + label: nil, + colon: nil, + expression: ExprSyntax(trailingClosure), + trailingComma: nil + ) node.arguments.append(tupleElement) node.trailingClosure = nil } let argumentTuple = self.generate( - node.arguments, leftParen: node.leftParen, rightParen: node.rightParen + node.arguments, + leftParen: node.leftParen, + rightParen: node.rightParen ) let callee = generate(node.calledExpression) @@ -69,7 +79,10 @@ extension ASTGenVisitor { // Wrap in a SingleValueStmtExpr to embed as an expression. return .createWithWrappedBranches( - ctx, stmt: stmt, declContext: declContext, mustBeExpr: true + ctx, + stmt: stmt, + declContext: declContext, + mustBeExpr: true ) } @@ -94,7 +107,7 @@ extension ASTGenVisitor { return $0.bridgedSourceLoc(in: self) } - + return BridgedTupleExpr.createParsed( self.ctx, leftParenLoc: leftParen.bridgedSourceLoc(in: self), diff --git a/lib/ASTGen/Sources/ASTGen/Macros.swift b/lib/ASTGen/Sources/ASTGen/Macros.swift index 4b82f8e855fe5..9de21f6580aa3 100644 --- a/lib/ASTGen/Sources/ASTGen/Macros.swift +++ b/lib/ASTGen/Sources/ASTGen/Macros.swift @@ -11,13 +11,13 @@ //===----------------------------------------------------------------------===// import CASTBridging +import SwiftCompilerPluginMessageHandling import SwiftDiagnostics import SwiftOperators +import SwiftSyntax import SwiftSyntaxBuilder -import SwiftSyntaxMacros import SwiftSyntaxMacroExpansion -import SwiftCompilerPluginMessageHandling -import SwiftSyntax +import SwiftSyntaxMacros extension SyntaxProtocol { func token(at position: AbsolutePosition) -> TokenSyntax? { @@ -118,10 +118,13 @@ public func resolveExecutableMacro( // Executable plugins is "trusted" to have the macro implementation. If not, // the actual expansion fails. let exportedPtr = UnsafeMutablePointer.allocate(capacity: 1) - exportedPtr.initialize(to: .init( - moduleName: String(cString: moduleName), - typeName: String(cString: typeName), - plugin: CompilerPlugin(opaqueHandle: pluginOpaqueHandle))) + exportedPtr.initialize( + to: .init( + moduleName: String(cString: moduleName), + typeName: String(cString: typeName), + plugin: CompilerPlugin(opaqueHandle: pluginOpaqueHandle) + ) + ) return UnsafeRawPointer(exportedPtr) } @@ -189,9 +192,10 @@ enum ASTGenMacroDiagnostic: DiagnosticMessage, FixItMessage { /// single identifier. fileprivate func identifierFromStringLiteral(_ node: ExprSyntax) -> String? { guard let stringLiteral = node.as(StringLiteralExprSyntax.self), - stringLiteral.segments.count == 1, - let segment = stringLiteral.segments.first, - case .stringSegment(let stringSegment) = segment else { + stringLiteral.segments.count == 1, + let segment = stringLiteral.segments.first, + case .stringSegment(let stringSegment) = segment + else { return nil } @@ -202,7 +206,7 @@ fileprivate func identifierFromStringLiteral(_ node: ExprSyntax) -> String? { /// for use in macro expansion. /// /// When the resulting macro requires expansion, the result will come in -/// two parts: +/// two parts: /// /// - Returns: -1 on failure, BridgedMacroDefinitionKind on success. When the /// successful result is "expanded macro", `replacementsPtr` will point to a @@ -214,12 +218,12 @@ fileprivate func identifierFromStringLiteral(_ node: ExprSyntax) -> String? { /// argument matching the corresponding parameter. @_cdecl("swift_ASTGen_checkMacroDefinition") func checkMacroDefinition( - diagEnginePtr: UnsafeMutableRawPointer, - sourceFilePtr: UnsafeRawPointer, - macroLocationPtr: UnsafePointer, - externalMacroOutPtr: UnsafeMutablePointer, - replacementsPtr: UnsafeMutablePointer?>, - numReplacementsPtr: UnsafeMutablePointer + diagEnginePtr: UnsafeMutableRawPointer, + sourceFilePtr: UnsafeRawPointer, + macroLocationPtr: UnsafePointer, + externalMacroOutPtr: UnsafeMutablePointer, + replacementsPtr: UnsafeMutablePointer?>, + numReplacementsPtr: UnsafeMutablePointer ) -> Int { // Assert "out" parameters are initialized. assert(externalMacroOutPtr.pointee.isEmptyInitialized) @@ -228,11 +232,13 @@ func checkMacroDefinition( let sourceFilePtr = sourceFilePtr.bindMemory(to: ExportedSourceFile.self, capacity: 1) // Find the macro declaration. - guard let macroDecl = findSyntaxNodeInSourceFile( - sourceFilePtr: sourceFilePtr, - sourceLocationPtr: macroLocationPtr, - type: MacroDeclSyntax.self - ) else { + guard + let macroDecl = findSyntaxNodeInSourceFile( + sourceFilePtr: sourceFilePtr, + sourceLocationPtr: macroLocationPtr, + type: MacroDeclSyntax.self + ) + else { // FIXME: Produce an error return -1 } @@ -294,12 +300,13 @@ func checkMacroDefinition( return Int(BridgedMacroDefinitionKind.externalMacro.rawValue) case let .expansion(expansionSyntax, replacements: _) - where expansionSyntax.macroName.text == "externalMacro": + where expansionSyntax.macroName.text == "externalMacro": // Extract the identifier from the "module" argument. guard let firstArg = expansionSyntax.arguments.first, - let firstArgLabel = firstArg.label?.text, - firstArgLabel == "module", - let module = identifierFromStringLiteral(firstArg.expression) else { + let firstArgLabel = firstArg.label?.text, + firstArgLabel == "module", + let module = identifierFromStringLiteral(firstArg.expression) + else { let srcMgr = SourceManager(cxxDiagnosticEngine: diagEnginePtr) srcMgr.insert(sourceFilePtr) srcMgr.diagnose( @@ -313,9 +320,10 @@ func checkMacroDefinition( // Extract the identifier from the "type" argument. guard let secondArg = expansionSyntax.arguments.dropFirst().first, - let secondArgLabel = secondArg.label?.text, - secondArgLabel == "type", - let type = identifierFromStringLiteral(secondArg.expression) else { + let secondArgLabel = secondArg.label?.text, + secondArgLabel == "type", + let type = identifierFromStringLiteral(secondArg.expression) + else { let srcMgr = SourceManager(cxxDiagnosticEngine: diagEnginePtr) srcMgr.insert(sourceFilePtr) srcMgr.diagnose( @@ -337,7 +345,6 @@ func checkMacroDefinition( externalMacroOutPtr.pointee = allocateBridgedString(expansionSyntax.trimmedDescription) - // If there are no replacements, we're done. if replacements.isEmpty { return Int(BridgedMacroDefinitionKind.expandedMacro.rawValue) @@ -348,8 +355,10 @@ func checkMacroDefinition( for (index, replacement) in replacements.enumerated() { let expansionStart = expansionSyntax.positionAfterSkippingLeadingTrivia.utf8Offset - replacementBuffer[index * 3] = replacement.reference.positionAfterSkippingLeadingTrivia.utf8Offset - expansionStart - replacementBuffer[index * 3 + 1] = replacement.reference.endPositionBeforeTrailingTrivia.utf8Offset - expansionStart + replacementBuffer[index * 3] = + replacement.reference.positionAfterSkippingLeadingTrivia.utf8Offset - expansionStart + replacementBuffer[index * 3 + 1] = + replacement.reference.endPositionBeforeTrailingTrivia.utf8Offset - expansionStart replacementBuffer[index * 3 + 2] = replacement.parameterIndex } @@ -420,18 +429,24 @@ func expandFreestandingMacro( let sourceFilePtr = sourceFilePtr.bindMemory(to: ExportedSourceFile.self, capacity: 1) - guard let macroSyntax = findSyntaxNodeInSourceFile( - sourceFilePtr: sourceFilePtr, sourceLocationPtr: sourceLocationPtr, type: Syntax.self) else { + guard + let macroSyntax = findSyntaxNodeInSourceFile( + sourceFilePtr: sourceFilePtr, + sourceLocationPtr: sourceLocationPtr, + type: Syntax.self + ) + else { return 1 } - guard let expansion = macroSyntax.asProtocol( - FreestandingMacroExpansionSyntax.self - ) else { + guard + let expansion = macroSyntax.asProtocol( + FreestandingMacroExpansionSyntax.self + ) + else { print("not on a macro expansion node: \(macroSyntax.debugDescription)") return 1 } - let discriminator = String(cString: discriminatorText) let macroRole = MacroRole(rawMacroRole: rawMacroRole) @@ -444,7 +459,8 @@ func expandFreestandingMacro( diagEnginePtr: diagEnginePtr, expansionSyntax: expansion, sourceFilePtr: sourceFilePtr, - discriminator: discriminator) + discriminator: discriminator + ) case .Executable: expandedSource = expandFreestandingMacroIPC( macroPtr: macroPtr, @@ -452,7 +468,8 @@ func expandFreestandingMacro( diagEnginePtr: diagEnginePtr, expansionSyntax: expansion, sourceFilePtr: sourceFilePtr, - discriminator: discriminator) + discriminator: discriminator + ) } return makeExpansionOutputResult( @@ -497,15 +514,15 @@ func expandFreestandingMacroIPC( macro: .init(moduleName: macro.moduleName, typeName: macro.typeName, name: macroName), macroRole: pluginMacroRole, discriminator: discriminator, - syntax: PluginMessage.Syntax(syntax: Syntax(expansionSyntax), in: sourceFilePtr)!) + syntax: PluginMessage.Syntax(syntax: Syntax(expansionSyntax), in: sourceFilePtr)! + ) do { let result = try macro.plugin.sendMessageAndWait(message) let expandedSource: String? let diagnostics: [PluginMessage.Diagnostic] switch result { - case - .expandMacroResult(let _expandedSource, let _diagnostics), - .expandFreestandingMacroResult(let _expandedSource, let _diagnostics): + case .expandMacroResult(let _expandedSource, let _diagnostics), + .expandFreestandingMacroResult(let _expandedSource, let _diagnostics): expandedSource = _expandedSource diagnostics = _diagnostics default: @@ -596,7 +613,8 @@ func findSyntaxNodeInSourceFile( } let sourceFilePtr = sourceFilePtr.bindMemory( - to: ExportedSourceFile.self, capacity: 1 + to: ExportedSourceFile.self, + capacity: 1 ) // Find the offset. @@ -638,14 +656,16 @@ func findSyntaxNodeInSourceFile( while let parentSyntax = resultSyntax.parent { // Look through type compositions. if let compositionElement = parentSyntax.as(CompositionTypeElementSyntax.self), - let compositionList = compositionElement.parent?.as(CompositionTypeElementListSyntax.self), - let typedParent = compositionList.parent?.as(type) { + let compositionList = compositionElement.parent?.as(CompositionTypeElementListSyntax.self), + let typedParent = compositionList.parent?.as(type) + { resultSyntax = typedParent continue } guard let typedParent = parentSyntax.as(type), - typedParent.position == resultSyntax.position else { + typedParent.position == resultSyntax.position + else { break } @@ -678,21 +698,25 @@ func expandAttachedMacro( assert(expandedSourceOutPtr.pointee.isEmptyInitialized) // Dig out the custom attribute for the attached macro declarations. - guard let customAttrNode = findSyntaxNodeInSourceFile( - sourceFilePtr: customAttrSourceFilePtr, - sourceLocationPtr: customAttrSourceLocPointer, - type: AttributeSyntax.self - ) else { + guard + let customAttrNode = findSyntaxNodeInSourceFile( + sourceFilePtr: customAttrSourceFilePtr, + sourceLocationPtr: customAttrSourceLocPointer, + type: AttributeSyntax.self + ) + else { return 1 } // Dig out the node for the declaration to which the custom attribute is // attached. - guard let declarationNode = findSyntaxNodeInSourceFile( - sourceFilePtr: declarationSourceFilePtr, - sourceLocationPtr: declarationSourceLocPointer, - type: DeclSyntax.self - ) else { + guard + let declarationNode = findSyntaxNodeInSourceFile( + sourceFilePtr: declarationSourceFilePtr, + sourceLocationPtr: declarationSourceLocPointer, + type: DeclSyntax.self + ) + else { return 1 } @@ -728,7 +752,8 @@ func expandAttachedMacro( declarationSourceFilePtr: declarationSourceFilePtr, attachedTo: declarationNode, parentDeclSourceFilePtr: parentDeclSourceFilePtr, - parentDeclNode: parentDeclNode) + parentDeclNode: parentDeclNode + ) case .InProcess: expandedSource = expandAttachedMacroInProcess( diagEnginePtr: diagEnginePtr, @@ -742,7 +767,8 @@ func expandAttachedMacro( declarationSourceFilePtr: declarationSourceFilePtr, attachedTo: declarationNode, parentDeclSourceFilePtr: parentDeclSourceFilePtr, - parentDeclNode: parentDeclNode) + parentDeclNode: parentDeclNode + ) } return makeExpansionOutputResult( @@ -777,19 +803,22 @@ func expandAttachedMacroIPC( case .peer: macroRole = .peer case .conformance: macroRole = .conformance case .extension: macroRole = .`extension` - case - .expression, - .declaration, - .codeItem: + case .expression, + .declaration, + .codeItem: preconditionFailure("unhandled macro role for attached macro") } // Prepare syntax nodes to transfer. let customAttributeSyntax = PluginMessage.Syntax( - syntax: Syntax(customAttrNode), in: customAttrSourceFilePtr)! + syntax: Syntax(customAttrNode), + in: customAttrSourceFilePtr + )! let declSyntax = PluginMessage.Syntax( - syntax: Syntax(declarationNode), in: customAttrSourceFilePtr)! + syntax: Syntax(declarationNode), + in: customAttrSourceFilePtr + )! let parentDeclSyntax: PluginMessage.Syntax? if parentDeclNode != nil { @@ -826,7 +855,8 @@ func expandAttachedMacroIPC( declSyntax: declSyntax, parentDeclSyntax: parentDeclSyntax, extendedTypeSyntax: extendedTypeSyntax, - conformanceListSyntax: conformanceListSyntax) + conformanceListSyntax: conformanceListSyntax + ) do { let expandedSource: String? let diagnostics: [PluginMessage.Diagnostic] diff --git a/lib/ASTGen/Sources/ASTGen/PluginHost.swift b/lib/ASTGen/Sources/ASTGen/PluginHost.swift index 8aab03a268b9b..9ba4546158c0d 100644 --- a/lib/ASTGen/Sources/ASTGen/PluginHost.swift +++ b/lib/ASTGen/Sources/ASTGen/PluginHost.swift @@ -12,9 +12,9 @@ import CASTBridging import CBasicBridging +import SwiftCompilerPluginMessageHandling import SwiftSyntax import swiftLLVMJSON -import SwiftCompilerPluginMessageHandling enum PluginError: String, Error, CustomStringConvertible { case stalePlugin = "plugin is stale" @@ -47,7 +47,7 @@ public func _initializePlugin( public func _deinitializePlugin( opaqueHandle: UnsafeMutableRawPointer ) { - let plugin = CompilerPlugin(opaqueHandle: opaqueHandle) + let plugin = CompilerPlugin(opaqueHandle: opaqueHandle) plugin.deinitialize() } @@ -60,7 +60,7 @@ func swift_ASTGen_pluginServerLoadLibraryPlugin( moduleName: UnsafePointer, errorOut: UnsafeMutablePointer? ) -> Bool { - let plugin = CompilerPlugin(opaqueHandle: opaqueHandle) + let plugin = CompilerPlugin(opaqueHandle: opaqueHandle) if plugin.capability?.features.contains(.loadPluginLibrary) != true { errorOut?.pointee = allocateBridgedString("compiler plugin not loaded: '\(libraryPath); invalid plugin server") @@ -81,7 +81,7 @@ func swift_ASTGen_pluginServerLoadLibraryPlugin( assert(diagnostics.isEmpty) return true } - var errorMsgs = diagnostics.map({$0.message}).joined(separator: ", "); + var errorMsgs = diagnostics.map({ $0.message }).joined(separator: ", "); errorOut?.pointee = allocateBridgedString(errorMsgs); return false } catch { @@ -234,7 +234,8 @@ class PluginDiagnosticsEngine { message: diagnostic.message + (messageSuffix ?? ""), severity: diagnostic.severity, position: diagnostic.position, - highlights: diagnostic.highlights) + highlights: diagnostic.highlights + ) // Emit Fix-Its. for fixIt in diagnostic.fixIts { @@ -242,7 +243,8 @@ class PluginDiagnosticsEngine { message: fixIt.message, severity: .note, position: diagnostic.position, - fixItChanges: fixIt.changes) + fixItChanges: fixIt.changes + ) } // Emit any notes as follow-ons. @@ -250,7 +252,8 @@ class PluginDiagnosticsEngine { emitSingle( message: note.message, severity: .note, - position: note.position) + position: note.position + ) } } /// Emit single C++ diagnostic. @@ -298,7 +301,10 @@ class PluginDiagnosticsEngine { var newText = change.newText newText.withBridgedString { bridgedFixItText in diag.fixItReplace( - start: startLoc, end: endLoc, replacement: bridgedFixItText) + start: startLoc, + end: endLoc, + replacement: bridgedFixItText + ) } } @@ -330,7 +336,8 @@ class PluginDiagnosticsEngine { /// Produce the C++ source location for a given position based on a /// syntax node. private func bridgedSourceLoc( - at offset: Int, in fileName: String + at offset: Int, + in fileName: String ) -> BridgedSourceLoc { // Find the corresponding exported source file. guard let exportedSourceFile = exportedSourceFileByName[fileName] else { @@ -361,7 +368,7 @@ class PluginDiagnosticsEngine { if start.raw == nil || end.raw == nil { return nil } - return (start: start, end: end ) + return (start: start, end: end) } } @@ -393,7 +400,9 @@ extension PluginMessage.Syntax { fileName: fileName, offset: loc.offset, line: loc.line, - column: loc.column)) + column: loc.column + ) + ) } init?(syntax: Syntax) { diff --git a/lib/ASTGen/Sources/ASTGen/SourceFile.swift b/lib/ASTGen/Sources/ASTGen/SourceFile.swift index edd4657d0e42b..84e249283f347 100644 --- a/lib/ASTGen/Sources/ASTGen/SourceFile.swift +++ b/lib/ASTGen/Sources/ASTGen/SourceFile.swift @@ -1,12 +1,9 @@ -import CBasicBridging import CASTBridging - +import CBasicBridging import SwiftDiagnostics -import SwiftSyntax +@_spi(ExperimentalLanguageFeatures) import SwiftParser import SwiftParserDiagnostics - -@_spi(ExperimentalLanguageFeatures) -import SwiftParser +import SwiftSyntax /// Describes a source file that has been "exported" to the C++ part of the /// compiler, with enough information to interface with the C++ layer. @@ -45,8 +42,10 @@ extension Parser.ExperimentalFeatures { /// ExportedSourceFile instance. @_cdecl("swift_ASTGen_parseSourceFile") public func parseSourceFile( - buffer: UnsafePointer, bufferLength: Int, - moduleName: UnsafePointer, filename: UnsafePointer, + buffer: UnsafePointer, + bufferLength: Int, + moduleName: UnsafePointer, + filename: UnsafePointer, ctxPtr: UnsafeMutableRawPointer? ) -> UnsafeRawPointer { let buffer = UnsafeBufferPointer(start: buffer, count: bufferLength) @@ -57,8 +56,11 @@ public func parseSourceFile( let exportedPtr = UnsafeMutablePointer.allocate(capacity: 1) exportedPtr.initialize( to: .init( - buffer: buffer, moduleName: String(cString: moduleName), - fileName: String(cString: filename), syntax: sourceFile) + buffer: buffer, + moduleName: String(cString: moduleName), + fileName: String(cString: filename), + syntax: sourceFile + ) ) return UnsafeRawPointer(exportedPtr) @@ -106,7 +108,8 @@ public func emitParserDiagnostics( downgradePlaceholderErrorsToWarnings: CInt ) -> CInt { return sourceFilePtr.withMemoryRebound( - to: ExportedSourceFile.self, capacity: 1 + to: ExportedSourceFile.self, + capacity: 1 ) { sourceFile in var anyDiags = false @@ -124,7 +127,9 @@ public func emitParserDiagnostics( } let diagnosticSeverity: DiagnosticSeverity - if downgradePlaceholderErrorsToWarnings == 1 && diag.diagMessage.diagnosticID == StaticTokenError.editorPlaceholder.diagnosticID { + if downgradePlaceholderErrorsToWarnings == 1 + && diag.diagMessage.diagnosticID == StaticTokenError.editorPlaceholder.diagnosticID + { diagnosticSeverity = .warning } else { diagnosticSeverity = diag.diagMessage.severity diff --git a/lib/ASTGen/Sources/ASTGen/SourceManager+MacroExpansionContext.swift b/lib/ASTGen/Sources/ASTGen/SourceManager+MacroExpansionContext.swift index b42fbc6186d7d..88410dfa8bb76 100644 --- a/lib/ASTGen/Sources/ASTGen/SourceManager+MacroExpansionContext.swift +++ b/lib/ASTGen/Sources/ASTGen/SourceManager+MacroExpansionContext.swift @@ -34,7 +34,8 @@ extension SourceManager { discriminator: String = "" ) -> MacroExpansionContext { return MacroExpansionContext( - sourceManager: self, discriminator: discriminator + sourceManager: self, + discriminator: discriminator ) } } @@ -43,13 +44,15 @@ extension String { /// Retrieve the base name of a string that represents a path, removing the /// directory. var basename: String { - guard let lastSlash = lastIndex(where: { -#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS) || os(Android) || os(Linux) + guard + let lastSlash = lastIndex(where: { + #if os(iOS) || os(macOS) || os(tvOS) || os(watchOS) || os(Android) || os(Linux) ["/"].contains($0) -#else + #else ["/", "\\"].contains($0) -#endif - }) else { + #endif + }) + else { return self } @@ -96,8 +99,8 @@ extension SourceManager.MacroExpansionContext: MacroExpansionContext { filePathMode: SourceLocationFilePathMode ) -> AbstractSourceLocation? { guard let (sourceFile, rootPosition) = sourceManager.rootSourceFile(of: node), - let exportedSourceFile = - sourceManager.exportedSourceFilesBySyntax[sourceFile]?.pointee + let exportedSourceFile = + sourceManager.exportedSourceFilesBySyntax[sourceFile]?.pointee else { return nil } diff --git a/lib/ASTGen/Sources/ASTGen/SourceManager.swift b/lib/ASTGen/Sources/ASTGen/SourceManager.swift index 2af74a95b078c..8d6f4a9b40260 100644 --- a/lib/ASTGen/Sources/ASTGen/SourceManager.swift +++ b/lib/ASTGen/Sources/ASTGen/SourceManager.swift @@ -14,9 +14,7 @@ class SourceManager { /// The set of source files that have been exported to the C++ code of /// the program. - var exportedSourceFilesBySyntax: [ - SourceFileSyntax : UnsafePointer - ] = [:] + var exportedSourceFilesBySyntax: [SourceFileSyntax: UnsafePointer] = [:] /// The set of nodes that have been detached from their parent nodes. /// @@ -90,8 +88,8 @@ extension SourceManager { // The position of our node is... let finalPosition = - node.position // Our position relative to its root - + SourceLength(utf8Length: offset) // and that root's offset in its parent + node.position // Our position relative to its root + + SourceLength(utf8Length: offset) // and that root's offset in its parent + SourceLength(utf8Length: parentOffset.utf8Offset) return (rootSF, finalPosition) } diff --git a/lib/ASTGen/Sources/ASTGen/Types.swift b/lib/ASTGen/Sources/ASTGen/Types.swift index 72de61e76d7d7..89f386ace69f8 100644 --- a/lib/ASTGen/Sources/ASTGen/Types.swift +++ b/lib/ASTGen/Sources/ASTGen/Types.swift @@ -1,8 +1,6 @@ import CASTBridging - -@_spi(ExperimentalLanguageFeatures) -import SwiftSyntax import SwiftDiagnostics +@_spi(ExperimentalLanguageFeatures) import SwiftSyntax extension ASTGenVisitor { public func generate(_ node: IdentifierTypeSyntax) -> BridgedTypeRepr { @@ -69,7 +67,9 @@ extension ASTGenVisitor { let memberComponents = reverseMemberComponents.reversed().bridgedArray(in: self) return BridgedMemberTypeRepr.createParsed( - self.ctx, base: baseComponent, members: memberComponents + self.ctx, + base: baseComponent, + members: memberComponents ) } @@ -78,7 +78,9 @@ extension ASTGenVisitor { let lSquareLoc = node.leftSquare.bridgedSourceLoc(in: self) let rSquareLoc = node.rightSquare.bridgedSourceLoc(in: self) return BridgedArrayTypeRepr.createParsed( - self.ctx, base: elementType, leftSquareLoc: lSquareLoc, + self.ctx, + base: elementType, + leftSquareLoc: lSquareLoc, rightSquareLoc: rSquareLoc ) } @@ -90,8 +92,12 @@ extension ASTGenVisitor { let lSquareLoc = node.leftSquare.bridgedSourceLoc(in: self) let rSquareLoc = node.rightSquare.bridgedSourceLoc(in: self) return BridgedDictionaryTypeRepr.createParsed( - self.ctx, leftSquareLoc: lSquareLoc, keyType: keyType, colonLoc: colonLoc, - valueType: valueType, rightSquareLoc: rSquareLoc + self.ctx, + leftSquareLoc: lSquareLoc, + keyType: keyType, + colonLoc: colonLoc, + valueType: valueType, + rightSquareLoc: rSquareLoc ) } @@ -100,12 +106,16 @@ extension ASTGenVisitor { let tyLoc = node.metatypeSpecifier.bridgedSourceLoc(in: self) if node.metatypeSpecifier.text == "Type" { return BridgedMetatypeTypeRepr.createParsed( - self.ctx, base: baseType, typeKeywordLoc: tyLoc + self.ctx, + base: baseType, + typeKeywordLoc: tyLoc ) } else { assert(node.metatypeSpecifier.text == "Protocol") return BridgedProtocolTypeRepr.createParsed( - self.ctx, base: baseType, protocolKeywordLoc: tyLoc + self.ctx, + base: baseType, + protocolKeywordLoc: tyLoc ) } } @@ -114,7 +124,9 @@ extension ASTGenVisitor { let base = generate(node.wrappedType) let exclaimLoc = node.exclamationMark.bridgedSourceLoc(in: self) return BridgedImplicitlyUnwrappedOptionalTypeRepr.createParsed( - self.ctx, base: base, exclaimLoc: exclaimLoc + self.ctx, + base: base, + exclaimLoc: exclaimLoc ) } @@ -122,7 +134,9 @@ extension ASTGenVisitor { let base = generate(node.wrappedType) let questionLoc = node.questionMark.bridgedSourceLoc(in: self) return BridgedOptionalTypeRepr.createParsed( - self.ctx, base: base, questionLoc: questionLoc + self.ctx, + base: base, + questionLoc: questionLoc ) } @@ -130,7 +144,9 @@ extension ASTGenVisitor { let base = generate(node.repetitionPattern) let repeatLoc = node.repeatKeyword.bridgedSourceLoc(in: self) return BridgedPackExpansionTypeRepr.createParsed( - self.ctx, base: base, repeatKeywordLoc: repeatLoc + self.ctx, + base: base, + repeatKeywordLoc: repeatLoc ) } @@ -185,12 +201,16 @@ extension ASTGenVisitor { let baseTy = generate(node.constraint) if node.someOrAnySpecifier.text == "some" { return BridgedOpaqueReturnTypeRepr.createParsed( - self.ctx, someKeywordLoc: someOrAnyLoc, base: baseTy + self.ctx, + someKeywordLoc: someOrAnyLoc, + base: baseTy ) } else { assert(node.someOrAnySpecifier.text == "any") return BridgedExistentialTypeRepr.createParsed( - self.ctx, anyKeywordLoc: someOrAnyLoc, base: baseTy + self.ctx, + anyKeywordLoc: someOrAnyLoc, + base: baseTy ) } } @@ -221,7 +241,9 @@ extension ASTGenVisitor { if let specifier = node.specifier { if let kind = BridgedAttributedTypeSpecifier(from: specifier.tokenKind) { type = BridgedSpecifierTypeRepr.createParsed( - self.ctx, base: type, specifier: kind, + self.ctx, + base: type, + specifier: kind, specifierLoc: specifier.bridgedSourceLoc(in: self) ) } else { @@ -252,33 +274,35 @@ extension ASTGenVisitor { let atLoc = attribute.atSign.bridgedSourceLoc(in: self) let attrLoc = nameSyntax.bridgedSourceLoc(in: self) switch typeAttrKind { - // SIL attributes - // FIXME: Diagnose if not in SIL mode? Or should that move to the - // type checker? - case .out, .in, .owned, .unowned_inner_pointer, .guaranteed, - .autoreleased, .callee_owned, .callee_guaranteed, .objc_metatype, - .sil_weak, .sil_unowned, .inout, .block_storage, .box, - .dynamic_self, .sil_unmanaged, .error, .error_indirect, - .error_unowned, .direct, .inout_aliasable, - .in_guaranteed, .in_constant, .captures_generics, .moveOnly: - fallthrough - - case .autoclosure, .escaping, .noescape, .noDerivative, .async, - .sendable, .retroactive, .unchecked, ._local, ._noMetadata, - .pack_owned, .pack_guaranteed, .pack_inout, .pack_out, - .pseudogeneric, .yields, .yield_once, .yield_many, .thin, .thick, - .count, .unimplementable: - TypeAttributes_addSimpleAttr(typeAttributes, typeAttrKind, atLoc, attrLoc) - - case .opened, .pack_element, .differentiable, .convention, - ._opaqueReturnTypeOf: - // FIXME: These require more complicated checks - break + // SIL attributes + // FIXME: Diagnose if not in SIL mode? Or should that move to the + // type checker? + case .out, .in, .owned, .unowned_inner_pointer, .guaranteed, + .autoreleased, .callee_owned, .callee_guaranteed, .objc_metatype, + .sil_weak, .sil_unowned, .inout, .block_storage, .box, + .dynamic_self, .sil_unmanaged, .error, .error_indirect, + .error_unowned, .direct, .inout_aliasable, + .in_guaranteed, .in_constant, .captures_generics, .moveOnly: + fallthrough + + case .autoclosure, .escaping, .noescape, .noDerivative, .async, + .sendable, .retroactive, .unchecked, ._local, ._noMetadata, + .pack_owned, .pack_guaranteed, .pack_inout, .pack_out, + .pseudogeneric, .yields, .yield_once, .yield_many, .thin, .thick, + .count, .unimplementable: + TypeAttributes_addSimpleAttr(typeAttributes, typeAttrKind, atLoc, attrLoc) + + case .opened, .pack_element, .differentiable, .convention, + ._opaqueReturnTypeOf: + // FIXME: These require more complicated checks + break } } type = BridgedAttributedTypeRepr.createParsed( - self.ctx, base: type, attributes: typeAttributes + self.ctx, + base: type, + attributes: typeAttributes ) } @@ -294,7 +318,9 @@ extension ASTGenVisitor { var type = generate(element.type) if let ellipsis = element.ellipsis { type = BridgedVarargTypeRepr.createParsed( - self.ctx, base: type, ellipsisLoc: ellipsis.bridgedSourceLoc(in: self) + self.ctx, + base: type, + ellipsisLoc: ellipsis.bridgedSourceLoc(in: self) ) } @@ -323,16 +349,19 @@ func buildTypeRepr( endTypeLocPtr: UnsafeMutablePointer?> ) -> UnsafeMutableRawPointer? { let sourceFile = sourceFilePtr.bindMemory( - to: ExportedSourceFile.self, capacity: 1 + to: ExportedSourceFile.self, + capacity: 1 ) // Find the type syntax node. - guard let typeSyntax = findSyntaxNodeInSourceFile( - sourceFilePtr: sourceFilePtr, - sourceLocationPtr: typeLocPtr, - type: TypeSyntax.self, - wantOutermost: true - ) else { + guard + let typeSyntax = findSyntaxNodeInSourceFile( + sourceFilePtr: sourceFilePtr, + sourceLocationPtr: typeLocPtr, + type: TypeSyntax.self, + wantOutermost: true + ) + else { // FIXME: Produce an error return nil } diff --git a/lib/ASTGen/Sources/LLVMJSON/LLVMJSON.swift b/lib/ASTGen/Sources/LLVMJSON/LLVMJSON.swift index 4cfcbb0c25567..0231235508701 100644 --- a/lib/ASTGen/Sources/LLVMJSON/LLVMJSON.swift +++ b/lib/ASTGen/Sources/LLVMJSON/LLVMJSON.swift @@ -71,20 +71,21 @@ fileprivate struct LLVMJSONDecoding: Decoder { var valuePtr: UnsafeMutableRawPointer var codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey : Any] + var userInfo: [CodingUserInfoKey: Any] - init(from valuePtr: UnsafeMutableRawPointer, codingPath: [CodingKey] = [], userInfo: [CodingUserInfoKey : Any] = [:]) { + init(from valuePtr: UnsafeMutableRawPointer, codingPath: [CodingKey] = [], userInfo: [CodingUserInfoKey: Any] = [:]) { self.valuePtr = valuePtr self.codingPath = codingPath self.userInfo = userInfo } - func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer where Key : CodingKey { + func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer where Key: CodingKey { var objectPtr: UnsafeMutableRawPointer? = nil if JSON_value_getAsObject(valuePtr, &objectPtr) { throw DecodingError.typeMismatch( KeyedContainer.self, - .init(codingPath: codingPath, debugDescription: "type mismatch")) + .init(codingPath: codingPath, debugDescription: "type mismatch") + ) } return KeyedDecodingContainer(KeyedContainer(objectPtr: objectPtr!, codingPath: codingPath)) } @@ -94,7 +95,8 @@ fileprivate struct LLVMJSONDecoding: Decoder { if JSON_value_getAsArray(valuePtr, &arrayPtr) { throw DecodingError.typeMismatch( UnkeyedContainer.self, - .init(codingPath: codingPath, debugDescription: "type mismatch")) + .init(codingPath: codingPath, debugDescription: "type mismatch") + ) } return UnkeyedContainer(arrayPtr: arrayPtr!, codingPath: codingPath) } @@ -195,7 +197,7 @@ extension LLVMJSONDecoding.SingleValueContainer: SingleValueDecodingContainer { try _decodeInteger(UInt64.self) } - func decode(_ type: T.Type) throws -> T where T : Decodable { + func decode(_ type: T.Type) throws -> T where T: Decodable { let decoder = LLVMJSONDecoding(from: valuePtr, codingPath: codingPath) return try T.init(from: decoder) } @@ -210,7 +212,7 @@ extension LLVMJSONDecoding.KeyedContainer: KeyedDecodingContainerProtocol { var keys: [Key] = [] let size = JSON_object_getSize(objectPtr) keys.reserveCapacity(size) - for i in 0 ..< size { + for i in 0.. SingleContainer { - SingleContainer(valuePtr: try _getValueOrThrow(forKey: key), - codingPath: codingPath + [key]) + SingleContainer( + valuePtr: try _getValueOrThrow(forKey: key), + codingPath: codingPath + [key] + ) } - private func _typeMismatchError(_ type: Any.Type, forKey key: Key) -> DecodingError { DecodingError.typeMismatch(type, .init(codingPath: codingPath + [key], debugDescription: "type misatch")) } @@ -307,7 +310,7 @@ extension LLVMJSONDecoding.KeyedContainer: KeyedDecodingContainerProtocol { try _getSingle(forKey: key).decode(type) } - func decode(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { + func decode(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { try _getSingle(forKey: key).decode(type) } @@ -381,12 +384,14 @@ extension LLVMJSONDecoding.KeyedContainer: KeyedDecodingContainerProtocol { return try decode(type, forKey: key) } - func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable { + func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable { guard contains(key) else { return nil } return try decode(type, forKey: key) } - func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer where NestedKey : CodingKey { + func nestedContainer(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer< + NestedKey + > where NestedKey: CodingKey { var objectPtr: UnsafeMutableRawPointer? = nil if JSON_value_getAsObject(try _getValueOrThrow(forKey: key), &objectPtr) { throw _typeMismatchError(KeyedDecodingContainer.self, forKey: key) @@ -439,7 +444,8 @@ extension LLVMJSONDecoding.UnkeyedContainer: UnkeyedDecodingContainer { guard !isAtEnd else { throw DecodingError.valueNotFound( Bool.self, - .init(codingPath: codingPath, debugDescription: "tried to decode too many")) + .init(codingPath: codingPath, debugDescription: "tried to decode too many") + ) } let index = currentIndex currentIndex += 1 @@ -447,8 +453,10 @@ extension LLVMJSONDecoding.UnkeyedContainer: UnkeyedDecodingContainer { } private mutating func _getSingle() throws -> SingleContainer { - SingleContainer(valuePtr: try _getValueOrThrow(), - codingPath: codingPath + [IndexKey(intValue: currentIndex)]) + SingleContainer( + valuePtr: try _getValueOrThrow(), + codingPath: codingPath + [IndexKey(intValue: currentIndex)] + ) } mutating func decodeNil() throws -> Bool { @@ -511,17 +519,22 @@ extension LLVMJSONDecoding.UnkeyedContainer: UnkeyedDecodingContainer { try _getSingle().decode(type) } - mutating func decode(_ type: T.Type) throws -> T where T : Decodable { + mutating func decode(_ type: T.Type) throws -> T where T: Decodable { try _getSingle().decode(type) } private func _typeMismatchError(_ type: Any.Type) -> DecodingError { DecodingError.typeMismatch( - type, .init(codingPath: codingPath + [IndexKey(intValue: currentIndex)], - debugDescription: "type misatch")) + type, + .init( + codingPath: codingPath + [IndexKey(intValue: currentIndex)], + debugDescription: "type misatch" + ) + ) } - mutating func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer where NestedKey : CodingKey { + mutating func nestedContainer(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer + where NestedKey: CodingKey { var objectPtr: UnsafeMutableRawPointer? = nil let newPath = codingPath + [IndexKey(intValue: currentIndex)] if JSON_value_getAsObject(try _getValueOrThrow(), &objectPtr) { @@ -566,15 +579,15 @@ fileprivate struct LLVMJSONEncoding: Encoder { var valuePtr: UnsafeMutableRawPointer var codingPath: [CodingKey] - var userInfo: [CodingUserInfoKey : Any] + var userInfo: [CodingUserInfoKey: Any] - init(to valuePtr: UnsafeMutableRawPointer, codingPath: [CodingKey] = [], userInfo: [CodingUserInfoKey : Any] = [:]) { + init(to valuePtr: UnsafeMutableRawPointer, codingPath: [CodingKey] = [], userInfo: [CodingUserInfoKey: Any] = [:]) { self.valuePtr = valuePtr self.codingPath = codingPath self.userInfo = userInfo } - func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key : CodingKey { + func container(keyedBy type: Key.Type) -> KeyedEncodingContainer where Key: CodingKey { let objectPtr = JSON_value_emplaceNewObject(valuePtr) return KeyedEncodingContainer(KeyedContainer(objectPtr: objectPtr, codingPath: codingPath)) } @@ -653,13 +666,15 @@ extension LLVMJSONEncoding.KeyedContainer: KeyedEncodingContainerProtocol { JSON_object_setInteger(objectPtr, key.stringValue, Int64(value)) } - mutating func encode(_ value: T, forKey key: Key) throws where T : Encodable { + mutating func encode(_ value: T, forKey key: Key) throws where T: Encodable { let valuePtr = JSON_object_setNewValue(objectPtr, key.stringValue) let encoder = LLVMJSONEncoding(to: valuePtr, codingPath: codingPath + [key]) try value.encode(to: encoder) } - mutating func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer where NestedKey : CodingKey { + mutating func nestedContainer(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer< + NestedKey + > where NestedKey: CodingKey { let nestedObjectPtr = JSON_object_setNewObject(objectPtr, key.stringValue) return KeyedEncodingContainer(KeyedContainer(objectPtr: nestedObjectPtr, codingPath: codingPath + [key])) } @@ -755,18 +770,23 @@ extension LLVMJSONEncoding.UnkeyedContainer: UnkeyedEncodingContainer { JSON_array_pushInteger(arrayPtr, Int64(value)) } - mutating func encode(_ value: T) throws where T : Encodable { + mutating func encode(_ value: T) throws where T: Encodable { let key = IndexKey(intValue: self.count) let valuePtr = JSON_array_pushNewValue(arrayPtr) let encoder = LLVMJSONEncoding(to: valuePtr, codingPath: codingPath + [key]) try value.encode(to: encoder) } - mutating func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer where NestedKey : CodingKey { + mutating func nestedContainer(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer + where NestedKey: CodingKey { let key = IndexKey(intValue: self.count) let nestedObjectPtr = JSON_array_pushNewObject(arrayPtr) - return KeyedEncodingContainer(KeyedContainer(objectPtr: nestedObjectPtr, - codingPath: codingPath + [key])) + return KeyedEncodingContainer( + KeyedContainer( + objectPtr: nestedObjectPtr, + codingPath: codingPath + [key] + ) + ) } mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { @@ -841,7 +861,7 @@ extension LLVMJSONEncoding.SingleValueContainer: SingleValueEncodingContainer { JSON_value_emplaceInteger(valuePtr, Int64(value)); } - mutating func encode(_ value: T) throws where T : Encodable { + mutating func encode(_ value: T) throws where T: Encodable { let encoder = LLVMJSONEncoding(to: valuePtr, codingPath: codingPath) try value.encode(to: encoder) }