Commit 91afca94 authored by closs's avatar closs Committed by Bryan Mills

ast: make ExampleCommentMap a runnable example

Fixes #20450

Change-Id: I2256282a8880e99508e98fefedfb94a7cccacbcf
Reviewed-on: https://go-review.googlesource.com/48969
Run-TryBot: Bryan Mills <bcmills@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: 's avatarBryan Mills <bcmills@google.com>
parent 42aec4c0
...@@ -44,7 +44,7 @@ var X = f(3.14)*2 + c ...@@ -44,7 +44,7 @@ var X = f(3.14)*2 + c
return true return true
}) })
// output: // Output:
// src.go:2:9: p // src.go:2:9: p
// src.go:3:7: c // src.go:3:7: c
// src.go:3:11: 1.0 // src.go:3:11: 1.0
...@@ -75,7 +75,7 @@ func main() { ...@@ -75,7 +75,7 @@ func main() {
// Print the AST. // Print the AST.
ast.Print(fset, f) ast.Print(fset, f)
// output: // Output:
// 0 *ast.File { // 0 *ast.File {
// 1 . Package: 2:1 // 1 . Package: 2:1
// 2 . Name: *ast.Ident { // 2 . Name: *ast.Ident {
...@@ -172,7 +172,12 @@ func main() { ...@@ -172,7 +172,12 @@ func main() {
cmap := ast.NewCommentMap(fset, f, f.Comments) cmap := ast.NewCommentMap(fset, f, f.Comments)
// Remove the first variable declaration from the list of declarations. // Remove the first variable declaration from the list of declarations.
f.Decls = removeFirstVarDecl(f.Decls) for i, decl := range f.Decls {
if gen, ok := decl.(*ast.GenDecl); ok && gen.Tok == token.VAR {
copy(f.Decls[i:], f.Decls[i+1:])
f.Decls = f.Decls[:len(f.Decls)-1]
}
}
// Use the comment map to filter comments that don't belong anymore // Use the comment map to filter comments that don't belong anymore
// (the comments associated with the variable declaration), and create // (the comments associated with the variable declaration), and create
...@@ -186,7 +191,7 @@ func main() { ...@@ -186,7 +191,7 @@ func main() {
} }
fmt.Printf("%s", buf.Bytes()) fmt.Printf("%s", buf.Bytes())
// output: // Output:
// // This is the package comment. // // This is the package comment.
// package main // package main
// //
...@@ -198,13 +203,3 @@ func main() { ...@@ -198,13 +203,3 @@ func main() {
// fmt.Println(hello) // line comment 3 // fmt.Println(hello) // line comment 3
// } // }
} }
func removeFirstVarDecl(list []ast.Decl) []ast.Decl {
for i, decl := range list {
if gen, ok := decl.(*ast.GenDecl); ok && gen.Tok == token.VAR {
copy(list[i:], list[i+1:])
return list[:len(list)-1]
}
}
panic("variable declaration not found")
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment