Skip to content

Autofix produces invalid syntax for else if err := ...; err != nil #9

Description

@AlwxSin

Description

The suggested fix inserts the assignment right before ifStmt.Pos(). When the if is an else if branch, the insertion lands between else and if, producing code that doesn't compile.

Reproduce

func elseIfDefine() error {
      x := 1
      if x > 0 {
              return nil
      } else if err := f(); err != nil {
              return err
      }
      return nil
}

Applying the suggested fix yields:

      } else err := f()
      if err != nil {

which fails to parse: expected if statement or block, found err.

Affected cases

Possible fix

Don't emit a SuggestedFix when the ifStmt is the Else branch of a parent *ast.IfStmt (e.g. walk with inspector.WithStack and check the parent node) — report the diagnostic message only. Alternatively, rewrite the whole else if chain, but that's much more involved.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions