Skip to content

indexInParent replacement for use with replacing(childAt #1872

Closed
@keith

Description

@keith

Description

I had some SwiftSyntax code that did:

override func visit(_ node: ImportDeclSyntax) -> DeclSyntax {
    guard let importAccessPathSyntax = node.path.first(where: { $0.name.text.contains("Foo") }) {
        return super.visit(node)
    }

    let newToken = importAccessPathSyntax.name.withKind(.stringSegment("Bar"))
    let newPath = node.path.replacing(childAt: importAccessPathSyntax.indexInParent,
                                        with: importAccessPathSyntax.with(\.name, newToken))
    let newNode = node.with(\.path, newPath)
    correctionPositions.append(importAccessPathSyntax.positionAfterSkippingLeadingTrivia)
    return super.visit(newNode)
}

In order to replace imports of Foo with Bar. I was able to do this without affecting any trivia using this approach, but it seems like with recent changes on the release/5.9 branch there is no way to get the equivalent of importAccessPathSyntax.indexInParent anymore. I attempted to use importAccessPathSyntax.keyPathInParent as a replacement here but in this case that results in nil. Should that be the new option? Should replacing(childAt: take SyntaxChildrenIndex now instead of an Int? In the meantime I worked around this case by assuming that 0 was the right index always:

override func visit(_ node: ImportDeclSyntax) -> DeclSyntax {
    guard let importAccessPathSyntax = node.path.first(where: { $0.name.text.contains("Foo") }) {
        return super.visit(node)
    }

    let newToken = importAccessPathSyntax.name.with(\.tokenKind, TokenKind.stringSegment("Bar"))
    let newPath = node.path.replacing(childAt: 0, with: importAccessPathSyntax.with(\.name, newToken))
    let newNode = node.with(\.path, newPath)
    correctionPositions.append(importAccessPathSyntax.positionAfterSkippingLeadingTrivia)
    return super.visit(newNode)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions