Skip to content

fix: Handle one-liner functions correctly in suggested fix#8

Merged
tomoemon merged 1 commit into
mainfrom
fix/one-liner-function-suggested-fix
Mar 3, 2026
Merged

fix: Handle one-liner functions correctly in suggested fix#8
tomoemon merged 1 commit into
mainfrom
fix/one-liner-function-suggested-fix

Conversation

@tomoemon

@tomoemon tomoemon commented Mar 3, 2026

Copy link
Copy Markdown
Owner

Summary

  • 1行に収まった関数(one-liner)に -fix を適用すると構文エラーが発生するバグを修正
  • buildDeferTextEdit に1ライナー検出ロジックを追加し、関数ボディを複数行に展開してから defer を挿入するよう変更
  • テストケース d_one_liner.go と golden ファイル d_one_liner.go.golden を追加

設計の背景

従来の buildDeferTextEdit{ の直後に \n\tdefer errstk.Wrap(&err) を挿入するだけだった。
通常の複数行関数では { の次にすでに改行があるため問題ないが、1ライナー関数では { の次に空白と return が続くため、

func (...) Write(b []byte) (_ int, err error) {
	defer errstk.Wrap(&err) return r.body.Write(b) }

のように deferreturn が同じ行に並び、Go の構文エラーになっていた。

修正では {} が同じ行にあるかを pass.Fset.Position で検出し、1ライナーの場合は { から } の直前までの内容を取り出して空白をトリムしたうえで複数行形式に再構築する。

検討した代替案

  • } の前に改行を挿入する別の TextEdit を追加する案: return 文の前にも改行が必要で、TextEdit が複数箇所に分散して管理が複雑になるため不採用
  • go/format で整形する案: TextEdit は文字列の差分で表現する必要があり、整形後の AST を TextEdit に変換するコストが高いため不採用

Test plan

  • go test ./errstklint/... がパスすることを確認済み
  • TestAnalyzerWithSuggestedFixes が新規テストケース(d_one_liner.go)を含めてパスすることを確認済み

🤖 Generated with Claude Code

When -fix is applied to a one-liner function like
  func (...) Write(b []byte) (int, error) { return r.body.Write(b) }
the previous implementation inserted the defer statement right after
'{' without adding a newline before the existing statement, producing
invalid Go syntax:
  { defer errstk.Wrap(&err) return r.body.Write(b) }

Now buildDeferTextEdit detects when the opening and closing braces are
on the same line and reformats the entire body to multi-line, placing
the defer at the top and the original statement below it.

Also adds a test case (d_one_liner.go + golden file) to cover this.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@tomoemon
tomoemon merged commit 97d4c1f into main Mar 3, 2026
1 check passed
@tomoemon
tomoemon deleted the fix/one-liner-function-suggested-fix branch March 3, 2026 08:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant