10 "golang.org/x/tools/go/analysis"
13 type IsDeprecated struct{ Msg string }
15 func (*IsDeprecated) AFact() {}
16 func (d *IsDeprecated) String() string { return "Deprecated: " + d.Msg }
18 type DeprecatedResult struct {
19 Objects map[types.Object]*IsDeprecated
20 Packages map[*types.Package]*IsDeprecated
23 var Deprecated = &analysis.Analyzer{
24 Name: "fact_deprecated",
25 Doc: "Mark deprecated objects",
27 FactTypes: []analysis.Fact{(*IsDeprecated)(nil)},
28 ResultType: reflect.TypeOf(DeprecatedResult{}),
31 func deprecated(pass *analysis.Pass) (interface{}, error) {
32 var names []*ast.Ident
34 extractDeprecatedMessage := func(docs []*ast.CommentGroup) string {
35 for _, doc := range docs {
39 parts := strings.Split(doc.Text(), "\n\n")
40 for _, part := range parts {
41 if !strings.HasPrefix(part, "Deprecated: ") {
44 alt := part[len("Deprecated: "):]
45 alt = strings.Replace(alt, "\n", " ", -1)
51 doDocs := func(names []*ast.Ident, docs []*ast.CommentGroup) {
52 alt := extractDeprecatedMessage(docs)
57 for _, name := range names {
58 obj := pass.TypesInfo.ObjectOf(name)
59 pass.ExportObjectFact(obj, &IsDeprecated{alt})
63 var docs []*ast.CommentGroup
64 for _, f := range pass.Files {
65 docs = append(docs, f.Doc)
67 if alt := extractDeprecatedMessage(docs); alt != "" {
68 // Don't mark package syscall as deprecated, even though
69 // it is. A lot of people still use it for simple
70 // constants like SIGKILL, and I am not comfortable
71 // telling them to use x/sys for that.
72 if pass.Pkg.Path() != "syscall" {
73 pass.ExportPackageFact(&IsDeprecated{alt})
78 for _, f := range pass.Files {
79 fn := func(node ast.Node) bool {
84 switch node := node.(type) {
87 case token.TYPE, token.CONST, token.VAR:
88 docs = append(docs, node.Doc)
94 docs = append(docs, node.Doc)
95 names = []*ast.Ident{node.Name}
98 docs = append(docs, node.Doc)
99 names = []*ast.Ident{node.Name}
102 docs = append(docs, node.Doc)
107 case *ast.StructType:
108 for _, field := range node.Fields.List {
109 doDocs(field.Names, []*ast.CommentGroup{field.Doc})
112 case *ast.InterfaceType:
113 for _, field := range node.Methods.List {
114 doDocs(field.Names, []*ast.CommentGroup{field.Doc})
120 if len(names) == 0 || len(docs) == 0 {
132 out := DeprecatedResult{
133 Objects: map[types.Object]*IsDeprecated{},
134 Packages: map[*types.Package]*IsDeprecated{},
137 for _, fact := range pass.AllObjectFacts() {
138 out.Objects[fact.Object] = fact.Fact.(*IsDeprecated)
140 for _, fact := range pass.AllPackageFacts() {
141 out.Packages[fact.Package] = fact.Fact.(*IsDeprecated)