edit.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Package edit contains helpers for creating suggested fixes.
  2. package edit
  3. import (
  4. "bytes"
  5. "go/ast"
  6. "go/format"
  7. "go/token"
  8. "golang.org/x/tools/go/analysis"
  9. "honnef.co/go/tools/pattern"
  10. )
  11. // Ranger describes values that have a start and end position.
  12. // In most cases these are either ast.Node or manually constructed ranges.
  13. type Ranger interface {
  14. Pos() token.Pos
  15. End() token.Pos
  16. }
  17. // Range implements the Ranger interface.
  18. type Range [2]token.Pos
  19. func (r Range) Pos() token.Pos { return r[0] }
  20. func (r Range) End() token.Pos { return r[1] }
  21. // ReplaceWithString replaces a range with a string.
  22. func ReplaceWithString(old Ranger, new string) analysis.TextEdit {
  23. return analysis.TextEdit{
  24. Pos: old.Pos(),
  25. End: old.End(),
  26. NewText: []byte(new),
  27. }
  28. }
  29. // ReplaceWithNode replaces a range with an AST node.
  30. func ReplaceWithNode(fset *token.FileSet, old Ranger, new ast.Node) analysis.TextEdit {
  31. buf := &bytes.Buffer{}
  32. if err := format.Node(buf, fset, new); err != nil {
  33. panic("internal error: " + err.Error())
  34. }
  35. return analysis.TextEdit{
  36. Pos: old.Pos(),
  37. End: old.End(),
  38. NewText: buf.Bytes(),
  39. }
  40. }
  41. // ReplaceWithPattern replaces a range with the result of executing a pattern.
  42. func ReplaceWithPattern(fset *token.FileSet, old Ranger, new pattern.Pattern, state pattern.State) analysis.TextEdit {
  43. r := pattern.NodeToAST(new.Root, state)
  44. buf := &bytes.Buffer{}
  45. format.Node(buf, fset, r)
  46. return analysis.TextEdit{
  47. Pos: old.Pos(),
  48. End: old.End(),
  49. NewText: buf.Bytes(),
  50. }
  51. }
  52. // Delete deletes a range of code.
  53. func Delete(old Ranger) analysis.TextEdit {
  54. return analysis.TextEdit{
  55. Pos: old.Pos(),
  56. End: old.End(),
  57. NewText: nil,
  58. }
  59. }
  60. func Fix(msg string, edits ...analysis.TextEdit) analysis.SuggestedFix {
  61. return analysis.SuggestedFix{
  62. Message: msg,
  63. TextEdits: edits,
  64. }
  65. }
  66. // Selector creates a new selector expression.
  67. func Selector(x, sel string) *ast.SelectorExpr {
  68. return &ast.SelectorExpr{
  69. X: &ast.Ident{Name: x},
  70. Sel: &ast.Ident{Name: sel},
  71. }
  72. }