Skip to content

Instantly share code, notes, and snippets.

@tenntenn
Created December 28, 2016 07:24
Show Gist options
  • Save tenntenn/eba0ac51f0d588e9ecfa47eab634ebb2 to your computer and use it in GitHub Desktop.
Save tenntenn/eba0ac51f0d588e9ecfa47eab634ebb2 to your computer and use it in GitHub Desktop.
コメントに関連付けられたコードを取得する #golang ref: http://qiita.com/tenntenn/items/090922826c9164ac5496
// Hoge です。
type Hoge struct {
N int
}
package main
// comment for hoge
var hoge int
// comment for main
func main() {
// line comment 1/2
// line comment 2/2
/*
block comment1
block comment2
*/
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "sample.go", src, parser.ParseComments)
if err != nil {
log.Fatalln("Error:", err)
}
type File struct {
Doc *CommentGroup // associated documentation; or nil
Package token.Pos // position of "package" keyword
Name *Ident // package name
Decls []Decl // top-level declarations; or nil
Scope *Scope // package scope (this file only)
Imports []*ImportSpec // imports in this file
Unresolved []*Ident // unresolved identifiers in this file
Comments []*CommentGroup // list of all comments in the source file
}
type CommentGroup struct {
List []*Comment // len(List) > 0
}
for _, cg := range f.Comments {
fmt.Println(cg.Text())
}
comment for hoge
comment for main
line comment 1/2
line comment 2/2
block comment1
block comment2
type CommentMap map[Node][]*CommentGroup
func NewCommentMap(fset *token.FileSet, node Node, comments []*CommentGroup) CommentMap
func (cmap CommentMap) Filter(node Node) CommentMap {
umap := make(CommentMap)
Inspect(node, func(n Node) bool {
if g := cmap[n]; len(g) > 0 {
umap[n] = g
}
return true
})
return umap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment