问题 Go解析器不检测结构类型的Doc注释


我正在尝试使用Go来阅读关于结构类型的关联Doc注释 解析器 和 AST 包。在此示例中,代码仅将自身用作源。

package main

import (
    "fmt"
    "go/ast"
    "go/parser"
    "go/token"
)

// FirstType docs
type FirstType struct {
    // FirstMember docs
    FirstMember string
}

// SecondType docs
type SecondType struct {
    // SecondMember docs
    SecondMember string
}

// Main docs
func main() {
    fset := token.NewFileSet() // positions are relative to fset

    d, err := parser.ParseDir(fset, "./", nil, parser.ParseComments)
    if err != nil {
        fmt.Println(err)
        return
    }

    for _, f := range d {
        ast.Inspect(f, func(n ast.Node) bool {
            switch x := n.(type) {
            case *ast.FuncDecl:
                fmt.Printf("%s:\tFuncDecl %s\t%s\n", fset.Position(n.Pos()), x.Name, x.Doc)
            case *ast.TypeSpec:
                fmt.Printf("%s:\tTypeSpec %s\t%s\n", fset.Position(n.Pos()), x.Name, x.Doc)
            case *ast.Field:
                fmt.Printf("%s:\tField %s\t%s\n", fset.Position(n.Pos()), x.Names, x.Doc)
            }

            return true
        })
    }
}

输出func和fields的注释文档没有问题,但由于某种原因,无法找到'FirstType docs'和'SecondType docs'。我错过了什么? Go版本是1.1.2。

(要运行上述操作,请将其保存到main.go文件中,然后执行 go run main.go


11123
2017-10-25 03:41


起源



答案:


你需要使用 go/doc 从ast中提取文档的包:

package main

import (
    "fmt"
    "go/doc"
    "go/parser"
    "go/token"
)

// FirstType docs
type FirstType struct {
    // FirstMember docs
    FirstMember string
}

// SecondType docs
type SecondType struct {
    // SecondMember docs
    SecondMember string
}

// Main docs
func main() {
    fset := token.NewFileSet() // positions are relative to fset

    d, err := parser.ParseDir(fset, "./", nil, parser.ParseComments)
    if err != nil {
        fmt.Println(err)
        return
    }

    for k, f := range d {
        fmt.Println("package", k)
        p := doc.New(f, "./", 0)

        for _, t := range p.Types {
            fmt.Println("  type", t.Name)
            fmt.Println("    docs:", t.Doc)
        }
    }
}

6
2017-10-25 03:50



虽然go / doc是一个解决方案,但仍然无法回答为什么go / ast不提供类型的注释/ doc(例如on TypeSpec) - themihai


答案:


你需要使用 go/doc 从ast中提取文档的包:

package main

import (
    "fmt"
    "go/doc"
    "go/parser"
    "go/token"
)

// FirstType docs
type FirstType struct {
    // FirstMember docs
    FirstMember string
}

// SecondType docs
type SecondType struct {
    // SecondMember docs
    SecondMember string
}

// Main docs
func main() {
    fset := token.NewFileSet() // positions are relative to fset

    d, err := parser.ParseDir(fset, "./", nil, parser.ParseComments)
    if err != nil {
        fmt.Println(err)
        return
    }

    for k, f := range d {
        fmt.Println("package", k)
        p := doc.New(f, "./", 0)

        for _, t := range p.Types {
            fmt.Println("  type", t.Name)
            fmt.Println("    docs:", t.Doc)
        }
    }
}

6
2017-10-25 03:50



虽然go / doc是一个解决方案,但仍然无法回答为什么go / ast不提供类型的注释/ doc(例如on TypeSpec) - themihai


好问题!

看一下源代码 go/doc,我们可以看到它必须处理同样的情况 readType 功能。在那里,它说:

324     func (r *reader) readType(decl *ast.GenDecl, spec *ast.TypeSpec) {
...
334     // compute documentation
335     doc := spec.Doc
336     spec.Doc = nil // doc consumed - remove from AST
337     if doc == nil {
338         // no doc associated with the spec, use the declaration doc, if any
339         doc = decl.Doc
340     }
...

特别注意它如何处理AST没有附加到TypeSpec的文档的情况。要做到这一点,它会落后于 GenDecl。这为我们提供了一条线索,告诉我们如何直接使用AST来解析结构的doc注释。调整问题代码中的for循环以添加案例 *ast.GenDecl

for _, f := range d {
    ast.Inspect(f, func(n ast.Node) bool {
        switch x := n.(type) {
        case *ast.FuncDecl:
            fmt.Printf("%s:\tFuncDecl %s\t%s\n", fset.Position(n.Pos()), x.Name, x.Doc.Text())
        case *ast.TypeSpec:
            fmt.Printf("%s:\tTypeSpec %s\t%s\n", fset.Position(n.Pos()), x.Name, x.Doc.Text())
        case *ast.Field:
            fmt.Printf("%s:\tField %s\t%s\n", fset.Position(n.Pos()), x.Names, x.Doc.Text())
        case *ast.GenDecl:
            fmt.Printf("%s:\tGenDecl %s\n", fset.Position(n.Pos()), x.Doc.Text())
        }

        return true
    })
}

运行这个给我们:

main.go:3:1:    GenDecl %!s(*ast.CommentGroup=<nil>)
main.go:11:1:   GenDecl &{[%!s(*ast.Comment=&{69 // FirstType docs})]}
main.go:11:6:   TypeSpec FirstType  %!s(*ast.CommentGroup=<nil>)
main.go:13:2:   Field [FirstMember] &{[%!s(*ast.Comment=&{112 // FirstMember docs})]}
main.go:17:1:   GenDecl &{[%!s(*ast.Comment=&{155 // SecondType docs})]}
main.go:17:6:   TypeSpec SecondType %!s(*ast.CommentGroup=<nil>)
main.go:19:2:   Field [SecondMember]    &{[%!s(*ast.Comment=&{200 // SecondMember docs})]}
main.go:23:1:   FuncDecl main   &{[%!s(*ast.Comment=&{245 // Main docs})]}
main.go:33:23:  Field [n]   %!s(*ast.CommentGroup=<nil>)
main.go:33:35:  Field []    %!s(*ast.CommentGroup=<nil>)

而且,嘿!

我们打印出了久违的 FirstType docs 和 SecondType docs!但这并不令人满意。为什么文档不附加于 TypeSpec?该 go/doc/reader.go 文件竭尽全力绕过这个问题,实际上产生了假货 GenDecl 并把它传递给 readType 如果没有与struct声明相关的文档,前面提到的函数!

   503  fake := &ast.GenDecl{
   504   Doc: d.Doc,
   505   // don't use the existing TokPos because it
   506   // will lead to the wrong selection range for
   507   // the fake declaration if there are more
   508   // than one type in the group (this affects
   509   // src/cmd/godoc/godoc.go's posLink_urlFunc)
   510   TokPos: s.Pos(),
   511   Tok:    token.TYPE,
   512   Specs:  []ast.Spec{s},
   513  }

但为什么这一切呢?

想象一下,我们稍微改变了问题中代码的类型定义(定义这样的结构并不常见,但仍然有效Go):

// This documents FirstType and SecondType together
type (
    // FirstType docs
    FirstType struct {
        // FirstMember docs
        FirstMember string
    }

    // SecondType docs
    SecondType struct {
        // SecondMember docs
        SecondMember string
    }
)

运行代码(包括案例) ast.GenDecl)我们得到:

main.go:3:1:    GenDecl %!s(*ast.CommentGroup=<nil>)
main.go:11:1:   GenDecl &{[%!s(*ast.Comment=&{69 // This documents FirstType and SecondType together})]}
main.go:13:2:   TypeSpec FirstType  &{[%!s(*ast.Comment=&{129 // FirstType docs})]}
main.go:15:3:   Field [FirstMember] &{[%!s(*ast.Comment=&{169 // FirstMember docs})]}
main.go:19:2:   TypeSpec SecondType &{[%!s(*ast.Comment=&{215 // SecondType docs})]}
main.go:21:3:   Field [SecondMember]    &{[%!s(*ast.Comment=&{257 // SecondMember docs})]}
main.go:26:1:   FuncDecl main   &{[%!s(*ast.Comment=&{306 // Main docs})]}
main.go:36:23:  Field [n]   %!s(*ast.CommentGroup=<nil>)
main.go:36:35:  Field []    %!s(*ast.CommentGroup=<nil>)

那就对了

现在结构类型定义有他们的文档和 GenDecl 也有自己的文档。在第一个案例中,发布在问题中,附加了文档 GenDecl,因为AST看到类型定义的括号版本的“收缩”的各个结构类型定义,并且想要处理所有定义相同,无论它们是否被分组。变量定义也会发生同样的事情,如:

// some general docs
var (
    // v docs
    v int

    // v2 docs
    v2 string
)

因此,如果您希望使用纯AST解析注释,则需要注意这是它的工作原理。但正如@mjibson建议的那样,首选方法是使用 go/doc。祝你好运!


7
2018-02-18 16:36