@@ -229,20 +229,25 @@ extension SyntaxProtocol {
229
229
230
230
private protocol PredicateSyntaxRewriter : SyntaxRewriter {
231
231
var success : Bool { get }
232
+ var ignorable : Bool { get }
232
233
var diagnostics : [ Diagnostic ] { get }
233
234
}
234
235
235
236
extension PredicateSyntaxRewriter {
236
237
var success : Bool { true }
238
+ var ignorable : Bool { false }
237
239
var diagnostics : [ Diagnostic ] { [ ] }
238
240
}
239
241
240
242
extension SyntaxProtocol {
241
243
fileprivate func rewrite( with rewriter: some PredicateSyntaxRewriter ) throws -> Syntax {
242
- let translated = rewriter. rewrite ( Syntax ( self ) )
244
+ let translated = rewriter. rewrite ( self )
243
245
guard rewriter. success else {
244
246
throw DiagnosticsError ( diagnostics: rewriter. diagnostics)
245
247
}
248
+ guard !rewriter. ignorable else {
249
+ return Syntax ( self )
250
+ }
246
251
return translated
247
252
}
248
253
}
@@ -251,6 +256,7 @@ private class OptionalChainRewriter: SyntaxRewriter, PredicateSyntaxRewriter {
251
256
var withinValidChainingTreeStart = true
252
257
var withinChainingTree = false
253
258
var optionalInput : ExprSyntax ? = nil
259
+ var ignorable = true
254
260
255
261
private func _prePossibleTopOfTree( ) -> Bool {
256
262
if !withinChainingTree && withinValidChainingTreeStart {
@@ -265,6 +271,7 @@ private class OptionalChainRewriter: SyntaxRewriter, PredicateSyntaxRewriter {
265
271
withinChainingTree = false
266
272
if let input = optionalInput {
267
273
optionalInput = nil
274
+ ignorable = false
268
275
let visited = self . visit ( input)
269
276
let closure = ClosureExprSyntax ( statements: [ CodeBlockItemSyntax ( item: CodeBlockItemSyntax . Item ( node) ) ] )
270
277
let functionMember = MemberAccessExprSyntax ( base: visited, name: " flatMap " )
@@ -282,10 +289,14 @@ private class OptionalChainRewriter: SyntaxRewriter, PredicateSyntaxRewriter {
282
289
283
290
// We're in the middle of a potential tree, so rewrite the closure with a fresh state
284
291
// This ensures potential chaining in the closure isn't rewritten outside of the closure
285
- guard let rewritten = ( try ? node. rewrite ( with: OptionalChainRewriter ( ) ) ) ? . as ( ExprSyntax . self) else {
292
+ let nestedRewriter = OptionalChainRewriter ( )
293
+ guard let rewritten = ( try ? node. rewrite ( with: nestedRewriter) ) ? . as ( ExprSyntax . self) else {
286
294
// If rewriting the closure failed, just leave the closure as-is
287
295
return ExprSyntax ( node)
288
296
}
297
+ if ignorable {
298
+ ignorable = nestedRewriter. ignorable
299
+ }
289
300
return rewritten
290
301
}
291
302
0 commit comments