Skip to content

Make all syntax collections non-optional #2040

Closed
@allevato

Description

@allevato

Description

Let me know if I'm missing something else here, but I was updating swift-format to remove deprecation warnings around add* methods after #1958 and the code seems worse as a result.

The example I'm struggling with is when manipulating modifiers on a *DeclSyntax. For example:

return DeclSyntax(
  newEnumDecl
    .addModifier(newModifier)
    .with(\.memberBlock, newMemberBlock))

The benefit of the addModifier method was that it worked both in cases where newEnumDecl did have existing modifiers and when it didn't. But since newEnumDecl.modifiers returns DeclModifierListSyntax?, which is nil when empty. So I ended up with this:

return DeclSyntax(
  newEnumDecl
    .with(
      \.modifiers,
       (newEnumDecl.modifiers ?? DeclModifierListSyntax([])).append(newModifier))
    .with(\.memberBlock, newMemberBlock))

(Granted, I should probably look at SwiftSyntaxBuilder and string interpolation for a lot more tasks, but they didn't exist at the time most of these rules were built, so I'm trying to make smaller incremental changes.)

Would it make sense for properties that return node collections to always be non-optional, returning empty collections instead of nil? Then I could at least write:

return DeclSyntax(
  newEnumDecl
    .with(\.modifiers, newEnumDecl.modifiers.append(newModifier))
    .with(\.memberBlock, newMemberBlock))

which gets us at least closer to the original code.

Steps to Reproduce

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions