Excersize Rewriting the code with SwiftSyntax

Updated
Oct 27, 2021 3:45 PM
Created
Oct 24, 2021 7:11 AM
Tags
Swift

Rename methods recursively

"""
func a() {
 func b() {
   func c() {
   }
 }
}
"""
override func visit(_ node: FunctionDeclSyntax) -> DeclSyntax {
  let a = node.withIdentifier(SyntaxFactory.makeIdentifier("_\(node.identifier)"))
  return super.visit(a)
}

matches easy.layout

then renames those

final class ModifyFunctionCalling: SyntaxRewriter {

  override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {

    guard let first = node.calledExpression.as(MemberAccessExprSyntax.self),
      first.name.text == "layout"
    else {
      return super.visit(node)
    }

    guard let previous = first.base?.as(MemberAccessExprSyntax.self),
      previous.name.text == "easy"
    else {
      return super.visit(node)
    }

    print("found easy-peasy")

    let easyPeasy = node

    let calledExpression =
      first
      .withName(SyntaxFactory.makeIdentifier("layout"))
      .withBase(.init(previous.withName(SyntaxFactory.makeIdentifier("mondrian"))))

    let modified =
      easyPeasy
      .withCalledExpression(.init(calledExpression))
    //          .withArgumentList(SyntaxFactory.makeTupleExprElementList([]))

    return super.visit(modified)

  }

}

Finds a CodeBlockItemSyntax from child

sequence(first: Syntax(node), next: { $0.parent }).flatMap { $0.as(CodeBlockItemSyntax.self) }.first?.description

Rewrite

final class Rewriter: SyntaxRewriter {

  let tupleExprElementSyntaxSet: Set<TupleExprElementSyntax>

  init(tupleExprElementSyntaxSet: Set<TupleExprElementSyntax>) {
    self.tupleExprElementSyntaxSet = tupleExprElementSyntaxSet
    super.init()
  }

  override func visit(_ node: TupleExprElementSyntax) -> Syntax {
    if let modified = tupleExprElementSyntaxSet.first(where: { $0.index == node.index}) {
      return super.visit(modified)
    }
    return super.visit(node)
  }

}