CommentForObject returns the comment group associated with the object's declaration. For functions/methods it returns FuncDecl.Doc. For const/var/type it prefers Spec.Doc, else GenDecl.Doc. For struct/interface members it returns Field.Doc, else Field.Comment (trailing). Disclaimer: A lot of this co
(obj types.Object, pkg *packages.Package)
| 26 | // For struct/interface members it returns Field.Doc, else Field.Comment (trailing). |
| 27 | // Disclaimer: A lot of this code was AI generated. Feel free to improve it! |
| 28 | func CommentForObject(obj types.Object, pkg *packages.Package) []bindings.SyntheticComment { |
| 29 | if obj == nil || pkg == nil { |
| 30 | return nil |
| 31 | } |
| 32 | pos := obj.Pos() |
| 33 | |
| 34 | for _, f := range pkg.Syntax { |
| 35 | if !covers(f, pos) { |
| 36 | continue |
| 37 | } |
| 38 | |
| 39 | var found []bindings.SyntheticComment |
| 40 | ast.Inspect(f, func(n ast.Node) bool { |
| 41 | // The decl nodes "cover" the types they comment on. So we can check quickly if |
| 42 | // the node is relevant. |
| 43 | if n == nil || !covers(n, pos) { |
| 44 | return false |
| 45 | } |
| 46 | |
| 47 | switch nd := n.(type) { |
| 48 | case *ast.FuncDecl: |
| 49 | // Match function/method name token exactly. |
| 50 | if nd.Name != nil && nd.Name.Pos() == pos { |
| 51 | found = syntheticComments(true, nd.Doc) |
| 52 | return false |
| 53 | } |
| 54 | |
| 55 | case *ast.GenDecl: |
| 56 | // Walk specs to prefer per-spec docs over decl docs. |
| 57 | for _, sp := range nd.Specs { |
| 58 | if !covers(sp, pos) { |
| 59 | continue |
| 60 | } |
| 61 | |
| 62 | // nd.Doc are the comments for the entire type/const/var block. |
| 63 | if nd.Doc != nil { |
| 64 | found = append(found, syntheticComments(true, nd.Doc)...) |
| 65 | } |
| 66 | |
| 67 | switch spec := sp.(type) { |
| 68 | case *ast.ValueSpec: |
| 69 | // const/var |
| 70 | for _, name := range spec.Names { |
| 71 | if name.Pos() == pos { |
| 72 | found = append(found, syntheticComments(true, spec.Doc)...) |
| 73 | found = append(found, syntheticComments(false, spec.Comment)...) |
| 74 | return false |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | case *ast.TypeSpec: |
| 79 | // type declarations (struct/interface/alias) |
| 80 | if spec.Name != nil && spec.Name.Pos() == pos { |
| 81 | // comment on the type itself |
| 82 | found = append(found, syntheticComments(true, spec.Doc)...) |
| 83 | found = append(found, syntheticComments(false, spec.Comment)...) |
| 84 | return false |
| 85 | } |
no test coverage detected
searching dependent graphs…