You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

confusing-results.go 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package rule
  2. import (
  3. "go/ast"
  4. "github.com/mgechev/revive/lint"
  5. )
  6. // ConfusingResultsRule lints given function declarations
  7. type ConfusingResultsRule struct{}
  8. // Apply applies the rule to given file.
  9. func (r *ConfusingResultsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
  10. var failures []lint.Failure
  11. fileAst := file.AST
  12. walker := lintConfusingResults{
  13. onFailure: func(failure lint.Failure) {
  14. failures = append(failures, failure)
  15. },
  16. }
  17. ast.Walk(walker, fileAst)
  18. return failures
  19. }
  20. // Name returns the rule name.
  21. func (r *ConfusingResultsRule) Name() string {
  22. return "confusing-results"
  23. }
  24. type lintConfusingResults struct {
  25. onFailure func(lint.Failure)
  26. }
  27. func (w lintConfusingResults) Visit(n ast.Node) ast.Visitor {
  28. fn, ok := n.(*ast.FuncDecl)
  29. if !ok || fn.Type.Results == nil || len(fn.Type.Results.List) < 2 {
  30. return w
  31. }
  32. lastType := ""
  33. for _, result := range fn.Type.Results.List {
  34. if len(result.Names) > 0 {
  35. return w
  36. }
  37. t, ok := result.Type.(*ast.Ident)
  38. if !ok {
  39. return w
  40. }
  41. if t.Name == lastType {
  42. w.onFailure(lint.Failure{
  43. Node: n,
  44. Confidence: 1,
  45. Category: "naming",
  46. Failure: "unnamed results of the same type may be confusing, consider using named results",
  47. })
  48. break
  49. }
  50. lastType = t.Name
  51. }
  52. return w
  53. }