本文整理汇总了Golang中go/ast.NewCommentMap函数的典型用法代码示例。如果您正苦于以下问题:Golang NewCommentMap函数的具体用法?Golang NewCommentMap怎么用?Golang NewCommentMap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewCommentMap函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: RewriteGeneratedGogoProtobufFile
func RewriteGeneratedGogoProtobufFile(name string, extractFn ExtractFunc, optionalFn OptionalFunc, header []byte) error {
return rewriteFile(name, header, func(fset *token.FileSet, file *ast.File) error {
cmap := ast.NewCommentMap(fset, file, file.Comments)
// transform methods that point to optional maps or slices
for _, d := range file.Decls {
rewriteOptionalMethods(d, optionalFn)
}
// remove types that are already declared
decls := []ast.Decl{}
for _, d := range file.Decls {
if dropExistingTypeDeclarations(d, extractFn) {
continue
}
if dropEmptyImportDeclarations(d) {
continue
}
decls = append(decls, d)
}
file.Decls = decls
// remove unmapped comments
file.Comments = cmap.Filter(file).Comments()
return nil
})
}
开发者ID:kubernetes,项目名称:kubernetes,代码行数:27,代码来源:parser.go
示例2: ParseFile
// ParseFile will create a Build from the file path that
// was passed. FileSet of the Build will only contain a
// single file.
func ParseFile(path string) (*Build, error) {
var fileSet token.FileSet
astTree, err := parser.ParseFile(&fileSet, path, nil, parser.AllErrors|parser.ParseComments)
if err != nil {
return nil, err
}
fileName := filepath.Base(path)
// create a comment map from file
commentMap := ast.NewCommentMap(&fileSet, astTree, astTree.Comments)
// create new build for the file
build := NewBuild()
fileAST, err := ParseFileAST(fileName, astTree, commentMap)
if err != nil {
return nil, err
}
// add parsed file to the build file set
build.AddFile(fileName, fileAST)
return build, nil
}
开发者ID:flowup,项目名称:gogen,代码行数:28,代码来源:parse.go
示例3: rewriteFile
// rewriteFile applies the rewrite rule 'pattern -> replace' to an entire file.
func rewriteFile(pattern, replace ast.Expr, p *ast.File) *ast.File {
cmap := ast.NewCommentMap(fileSet, p, p.Comments)
m := make(map[string]reflect.Value)
pat := reflect.ValueOf(pattern)
repl := reflect.ValueOf(replace)
var rewriteVal func(val reflect.Value) reflect.Value
rewriteVal = func(val reflect.Value) reflect.Value {
// don't bother if val is invalid to start with
if !val.IsValid() {
return reflect.Value{}
}
for k := range m {
delete(m, k)
}
val = apply(rewriteVal, val)
if match(m, pat, val) {
val = subst(m, repl, reflect.ValueOf(val.Interface().(ast.Node).Pos()))
}
return val
}
r := apply(rewriteVal, reflect.ValueOf(p)).Interface().(*ast.File)
r.Comments = cmap.Filter(r).Comments() // recreate comments list
return r
}
开发者ID:jroelofs,项目名称:darwin-gcc-5,代码行数:27,代码来源:rewrite.go
示例4: processFile
func processFile(filename string) []Function {
var res []Function
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)
if err != nil {
panic(err)
}
cmap := ast.NewCommentMap(fset, f, f.Comments)
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.FuncDecl:
fun := Function{Begin: fset.Position(x.Pos()).Line,
Package: f.Name.String(),
Name: x.Name.String(),
End: fset.Position(x.End()).Line,
Filepath: fset.Position(x.Pos()).Filename}
fun.getTSpec(cmap[n])
res = append(res, fun)
}
return true
})
return res
}
开发者ID:srenatus,项目名称:threatspec-playground,代码行数:25,代码来源:tojson.go
示例5: process
func (gas *Analyzer) process(filename string, source interface{}) error {
mode := parser.ParseComments
root, err := parser.ParseFile(gas.context.FileSet, filename, source, mode)
if err == nil {
gas.context.Comments = ast.NewCommentMap(gas.context.FileSet, root, root.Comments)
gas.context.Root = root
// here we get type info
gas.context.Info = &types.Info{
Types: make(map[ast.Expr]types.TypeAndValue),
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
Selections: make(map[*ast.SelectorExpr]*types.Selection),
Scopes: make(map[ast.Node]*types.Scope),
Implicits: make(map[ast.Node]types.Object),
}
conf := types.Config{Importer: importer.Default()}
gas.context.Pkg, _ = conf.Check("pkg", gas.context.FileSet, []*ast.File{root}, gas.context.Info)
if err != nil {
gas.logger.Println("failed to check imports")
return err
}
ast.Walk(gas, root)
gas.Stats.NumFiles++
}
return err
}
开发者ID:vmware,项目名称:vic,代码行数:29,代码来源:analyzer.go
示例6: packageExports
// packageExports is a local implementation of ast.PackageExports
// which correctly updates each package file's comment list.
// (The ast.PackageExports signature is frozen, hence the local
// implementation).
//
func packageExports(fset *token.FileSet, pkg *ast.Package) {
for _, src := range pkg.Files {
cmap := ast.NewCommentMap(fset, src, src.Comments)
ast.FileExports(src)
src.Comments = cmap.Filter(src).Comments()
}
}
开发者ID:tintohill,项目名称:pythia,代码行数:12,代码来源:server.go
示例7: filterInfo
// filterInfo updates info to include only the nodes that match the given
// filter args.
func filterInfo(args []string, info *PageInfo) {
rx, err := makeRx(args)
if err != nil {
log.Fatalf("illegal regular expression from %v: %v", args, err)
}
filter := func(s string) bool { return rx.MatchString(s) }
switch {
case info.PAst != nil:
newPAst := map[string]*ast.File{}
for name, a := range info.PAst {
cmap := ast.NewCommentMap(info.FSet, a, a.Comments)
a.Comments = []*ast.CommentGroup{} // remove all comments.
ast.FilterFile(a, filter)
if len(a.Decls) > 0 {
newPAst[name] = a
}
for _, d := range a.Decls {
// add back the comments associated with d only
comments := cmap.Filter(d).Comments()
a.Comments = append(a.Comments, comments...)
}
}
info.PAst = newPAst // add only matching files.
case info.PDoc != nil:
info.PDoc.Filter(filter)
}
}
开发者ID:4honor,项目名称:obdi,代码行数:30,代码来源:cmdline.go
示例8: ParseDir
// ParseDir will create a Build from the directory that
// was passed into the function.
func ParseDir(path string) (*Build, error) {
var fileSet token.FileSet
packages, err := parser.ParseDir(&fileSet, path, nil, parser.AllErrors)
if err != nil {
return nil, err
}
// create new build for the file set
build := NewBuild()
// iterate over all packages in the directory
for _, pkg := range packages {
// iterate over all files within the package
for name, astTree := range pkg.Files {
baseName := filepath.Base(name)
// create a comment map from file
commentMap := ast.NewCommentMap(&fileSet, astTree, astTree.Comments)
fileAST, err := ParseFileAST(baseName, astTree, commentMap)
if err != nil {
return nil, err
}
build.AddFile(baseName, fileAST)
}
}
return build, nil
}
开发者ID:flowup,项目名称:gogen,代码行数:32,代码来源:parse.go
示例9: getCommentMap
func getCommentMap(fileName string) (cm map[string]string) {
fileSet := token.NewFileSet() // positions are relative to fset
// Parse the file containing this very example
// but stop after processing the imports.
f, err := parser.ParseFile(fileSet, fileName, nil, parser.ParseComments)
if err != nil {
fmt.Println(err)
return
}
commentMap := ast.NewCommentMap(fileSet, f, f.Comments)
cm = make(map[string]string)
for n, cgs := range commentMap {
fmt.Printf("%#v,%#v --- %#v\n", n.(ast.Node).Pos(), n.(ast.Node).End(), toText(cgs))
comment := toText(cgs)
if len(strings.TrimSpace(comment)) == 0 {
continue
}
split := strings.SplitN(comment, " ", 2)
godoc := split[1]
key := split[0]
cm[key] = godoc
}
return cm
}
开发者ID:sushil,项目名称:go-jsonschema-generator,代码行数:26,代码来源:main.go
示例10: ExampleCommentMap
// This example illustrates how to remove a variable declaration
// in a Go program while maintaining correct comment association
// using an ast.CommentMap.
func ExampleCommentMap() {
// src is the input for which we create the AST that we
// are going to manipulate.
src := `
// This is the package comment.
package main
// This comment is associated with the hello constant.
const hello = "Hello, World!" // line comment 1
// This comment is associated with the foo variable.
var foo = hello // line comment 2
// This comment is associated with the main function.
func main() {
fmt.Println(hello) // line comment 3
}
`
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "src.go", src, parser.ParseComments)
if err != nil {
panic(err)
}
// Create an ast.CommentMap from the ast.File's comments.
// This helps keeping the association between comments
// and AST nodes.
cmap := ast.NewCommentMap(fset, f, f.Comments)
// Remove the first variable declaration from the list of declarations.
f.Decls = removeFirstVarDecl(f.Decls)
// Use the comment map to filter comments that don't belong anymore
// (the comments associated with the variable declaration), and create
// the new comments list.
f.Comments = cmap.Filter(f).Comments()
// Print the modified AST.
var buf bytes.Buffer
if err := format.Node(&buf, fset, f); err != nil {
panic(err)
}
fmt.Printf("%s", buf.Bytes())
// output:
// // This is the package comment.
// package main
//
// // This comment is associated with the hello constant.
// const hello = "Hello, World!" // line comment 1
//
// // This comment is associated with the main function.
// func main() {
// fmt.Println(hello) // line comment 3
// }
}
开发者ID:2thetop,项目名称:go,代码行数:61,代码来源:example_test.go
示例11: functions
func functions(f *ast.File, info types.Info, fset *token.FileSet) ([]Function, error) {
fns := exportedFuncs(f, fset)
fns = errorOrVoid(fns, info)
cmtMap := ast.NewCommentMap(fset, f, f.Comments)
functions := make([]Function, len(fns))
for i, fn := range fns {
fun := Function{Name: fn.Name.Name}
fun.Comment = combine(cmtMap[fn])
// we only support null returns or error returns, so if there's a
// return, it's an error.
if len(fn.Type.Results.List) > 0 {
fun.IsError = true
}
params := fn.Type.Params.List
fun.Params = make([]Param, 0, len(params))
for _, field := range params {
t := info.TypeOf(field.Type)
pointer := false
if p, ok := t.(*types.Pointer); ok {
t = p.Elem()
pointer = true
}
if b, ok := t.(*types.Basic); ok {
if b.Kind() == types.UnsafePointer {
log.Printf(
"Can't create command for function %q because its parameter %q is an unsafe.Pointer.",
fn.Name.Name,
field.Names[0])
break
}
fieldCmt := combine(cmtMap[field])
// handle a, b, c int
for _, name := range field.Names {
nameCmt := combine(cmtMap[name])
if nameCmt == "" {
nameCmt = fieldCmt
}
param := Param{
Name: name.Name,
Type: b.Kind(),
IsPointer: pointer,
Comment: nameCmt,
}
fun.Params = append(fun.Params, param)
}
continue
}
}
functions[i] = fun
}
return functions, nil
}
开发者ID:natefinch,项目名称:cavalier,代码行数:57,代码来源:parse.go
示例12: Trim
// Trim trims the AST rooted at node based on the coverage profile,
// removing irrelevant and unreached parts of the program.
// If the node is an *ast.File, comments are updated as well using
// an ast.CommentMap.
func (p *Profile) Trim(node ast.Node) {
if f, ok := node.(*ast.File); ok {
cmap := ast.NewCommentMap(p.Fset, f, f.Comments)
ast.Walk(&trimVisitor{p}, f)
f.Comments = cmap.Filter(f).Comments()
} else {
ast.Walk(&trimVisitor{p}, node)
}
}
开发者ID:roger2000hk,项目名称:discover,代码行数:13,代码来源:trim.go
示例13: Inline
// Inline replaces each instance of identifier k with v.Ident in ast.File f,
// for k, v := range m.
// For all inlines that were triggeres it also adds imports from v.Imports to f.
// In addition, it removes top level type declarations of the form
// type k ...
// for all k in m.
//
// Every k in m should be a valid identifier.
// Every v.Ident should be a valid expression.
func Inline(fset *token.FileSet, f *ast.File, m map[string]Target) error {
// Build the inline map.
im := map[string]reflect.Value{}
for k, v := range m {
expr, err := parser.ParseExpr(k)
if err != nil {
return fmt.Errorf("failed to parse `%s`: %s", k, err)
}
if _, ok := expr.(*ast.Ident); !ok {
return fmt.Errorf("expected identifier, got %s which is %T", k, expr)
}
expr, err = parser.ParseExpr(v.Ident)
if err != nil {
return fmt.Errorf("failed to parse `%s`: %s", v.Ident, err)
}
s := v.Ident
if _, ok := expr.(*ast.StarExpr); ok {
s = fmt.Sprintf("(%s)", s)
}
im[k] = reflect.ValueOf(ast.Ident{Name: s})
}
// Filter `type XXX ...` declarations out if we are inlining XXX.
cmap := ast.NewCommentMap(fset, f, f.Comments)
to := 0
for _, d := range f.Decls {
skip := false
if t, ok := d.(*ast.GenDecl); ok {
for _, s := range t.Specs {
ts, ok := s.(*ast.TypeSpec)
if !ok {
continue
}
if _, ok = im[ts.Name.String()]; ok {
skip = true
}
}
}
if !skip {
f.Decls[to] = d
to++
}
}
if to != len(f.Decls) {
f.Decls = f.Decls[:to]
// Remove comments for the declarations that were filtered out.
f.Comments = cmap.Filter(f).Comments()
}
// Add imports for the inlines that were triggered.
for k := range inline(im, f) {
for _, imp := range m[k].Imports {
astutil.AddImport(fset, f, imp)
}
}
return nil
}
开发者ID:charl,项目名称:go-inline,代码行数:64,代码来源:goinline.go
示例14: initCMap
func (file *File) initCMap() {
goCMap := ast.NewCommentMap(file.FSet, file.AST, file.AST.Comments)
myCMap := make(map[int]cmapel, len(file.AST.Comments))
for _, comment := range file.AST.Comments {
end := file.FSet.Position(comment.End())
myCMap[end.Line] = cmapel{
Comment: comment,
End: end,
}
}
file.cmap = cmap{
GoCMap: goCMap,
MyCMap: myCMap,
}
}
开发者ID:LukeShu,项目名称:periwinkle,代码行数:16,代码来源:xgettext.go
示例15: AnalyzePkg
func AnalyzePkg(files []*ast.File, fileSet *token.FileSet, typesInfo *types.Info, typesPkg *types.Package, isBlocking func(*types.Func) bool) *Info {
info := &Info{
Info: typesInfo,
Pkg: typesPkg,
HasPointer: make(map[*types.Var]bool),
comments: make(ast.CommentMap),
IsBlocking: isBlocking,
FuncDeclInfos: make(map[*types.Func]*FuncInfo),
FuncLitInfos: make(map[*ast.FuncLit]*FuncInfo),
}
info.InitFuncInfo = info.newFuncInfo()
for _, file := range files {
for k, v := range ast.NewCommentMap(fileSet, file, file.Comments) {
info.comments[k] = v
}
ast.Walk(info.InitFuncInfo, file)
}
for {
done := true
for _, funcInfo := range info.allInfos {
for obj, calls := range funcInfo.LocalCalls {
if len(info.FuncDeclInfos[obj].Blocking) != 0 {
for _, call := range calls {
funcInfo.markBlocking(call)
}
delete(funcInfo.LocalCalls, obj)
done = false
}
}
}
if done {
break
}
}
for _, funcInfo := range info.allInfos {
for _, continueStmt := range funcInfo.ContinueStmts {
if funcInfo.Blocking[continueStmt.forStmt.Post] {
funcInfo.markBlocking(continueStmt.analyzeStack)
}
}
}
return info
}
开发者ID:rexposadas,项目名称:gx,代码行数:47,代码来源:info.go
示例16: main
func main() {
src := `
// HelloWorldService
package main
const hello = "Hello World!"
// This is a forbidden phrase!
const evil = "Where is my daily paçoca???"
func main() {
fmt.Println(hello)
}
`
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "src.go", src, parser.ParseComments)
if err != nil {
panic(err)
}
// Change the package comment
f.Comments[0].List[0].Text = f.Comments[0].List[0].Text + " - CENSORED BY NEOWAY"
// Create an ast.CommentMap from the ast.File's comments.
// This helps keeping the association between comments
// and AST nodes.
cmap := ast.NewCommentMap(fset, f, f.Comments)
// Remove the evil variable declaration from the list of declarations.
f.Decls = append(f.Decls[:1], f.Decls[2:]...)
// Use the comment map to filter comments that don't belong anymore
// (the comments associated with the variable declaration), and create
// the new comments list.
f.Comments = cmap.Filter(f).Comments()
// Print the modified AST.
var buf bytes.Buffer
if err := format.Node(&buf, fset, f); err != nil {
panic(err)
}
fmt.Printf("%s", buf.Bytes())
}
开发者ID:antonivargas,项目名称:presentations,代码行数:45,代码来源:censorship.go
示例17: parseFileStructs
func parseFileStructs(fset *token.FileSet, f *ast.File) []Struct {
parsedStructs := []Struct{}
commentMap := ast.NewCommentMap(fset, f, f.Comments)
for _, decl := range f.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
for _, spec := range genDecl.Specs {
typeSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
structType, ok := typeSpec.Type.(*ast.StructType)
if !ok {
continue
}
structName := typeSpec.Name.Name
var comments []string
commentGroups := commentMap[genDecl]
if commentGroups != nil {
for _, group := range commentGroups {
comments = append(comments, parseComments(group)...)
}
}
parsedStruct := parseStruct(fset, structType)
parsedStruct.Name = structName
parsedStruct.Comments = comments
parsedStructs = append(parsedStructs, *parsedStruct)
}
}
if len(parsedStructs) == 0 {
return nil
}
return parsedStructs
}
开发者ID:gofmt,项目名称:astx,代码行数:40,代码来源:astx.go
示例18: processFile
func processFile(filename string, out func(Measurement)) {
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)
if err != nil {
panic(err)
}
// use commentmap, since Doc() comment in ast below is not enough
cmap := ast.NewCommentMap(fset, f, f.Comments)
// iterate over function declarations from AST
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.FuncDecl:
name := f.Name.String() + "/" + x.Name.String()
out(Measurement{name + "/begin", strconv.Itoa(fset.Position(x.Pos()).Line)})
out(Measurement{name + "/end", strconv.Itoa(fset.Position(x.End()).Line)})
out(Measurement{name + "/filename", fset.Position(x.Pos()).Filename})
getTSpec(name, cmap[n], out)
}
return true
})
}
开发者ID:srenatus,项目名称:threatspec-playground,代码行数:24,代码来源:tocsv.go
示例19: filterInfo
func filterInfo(pres *Presentation, args []string, info *PageInfo) {
rx, err := makeRx(args)
if err != nil {
log.Fatalf("illegal regular expression from %v: %v", args, err)
}
filter := func(s string) bool { return rx.MatchString(s) }
switch {
case info.PAst != nil:
cmap := ast.NewCommentMap(info.FSet, info.PAst, info.PAst.Comments)
ast.FilterFile(info.PAst, filter)
// Special case: Don't use templates for printing
// so we only get the filtered declarations without
// package clause or extra whitespace.
for i, d := range info.PAst.Decls {
// determine the comments associated with d only
comments := cmap.Filter(d).Comments()
cn := &printer.CommentedNode{Node: d, Comments: comments}
if i > 0 {
fmt.Println()
}
if pres.HTMLMode {
var buf bytes.Buffer
pres.WriteNode(&buf, info.FSet, cn)
FormatText(os.Stdout, buf.Bytes(), -1, true, "", nil)
} else {
pres.WriteNode(os.Stdout, info.FSet, cn)
}
fmt.Println()
}
return
case info.PDoc != nil:
info.PDoc.Filter(filter)
}
}
开发者ID:amulyas,项目名称:bosh-cloudstack-cpi,代码行数:36,代码来源:cmdline.go
示例20: buildMockForInterface
func buildMockForInterface(o *options, t *ast.InterfaceType, imports []*ast.ImportSpec) string {
// TODO: if we're not building this mock in the package it came from then
// we need to qualify any local types and add an import.
// We make up a package name that's unlikely to be used
if o.pkg != nil {
thisdir, _ := os.Getwd()
if thisdir != o.pkg.Dir {
if qualifyLocalTypes(t, "utmocklocal") {
imports = append(imports, &ast.ImportSpec{
Name: ast.NewIdent("utmocklocal"),
Path: &ast.BasicLit{
Kind: token.STRING,
Value: "\"" + o.pkg.ImportPath + "\"",
},
})
}
}
}
// Mock Implementation of the interface
mockAst, fset, err := buildBasicFile(o.targetPackage, o.mockName)
if err != nil {
fmt.Printf("Failed to parse basic AST. %v", err)
os.Exit(2)
}
// Build a map to keep track of where the comments are
cmap := ast.NewCommentMap(fset, mockAst, mockAst.Comments)
// Method receiver for our mock interface
recv := buildMethodReceiver(o.mockName)
// Add methods to our mockAst for each interface method
for _, m := range t.Methods.List {
t, ok := m.Type.(*ast.FuncType)
if ok {
// Names for return values causes problems, so remove them.
if t.Results != nil {
removeFieldNames(t.Results)
}
// We can have multiple names for a method type if multiple
// methods are declared with the same signature
for _, n := range m.Names {
fd := buildMockMethod(recv, n.Name, t)
mockAst.Decls = append(mockAst.Decls, fd)
}
}
}
addImportsToMock(mockAst, fset, imports)
// Fixup the comments
mockAst.Comments = cmap.Filter(mockAst).Comments()
var buf bytes.Buffer
format.Node(&buf, fset, mockAst)
return buf.String()
}
开发者ID:patrickToca,项目名称:ut,代码行数:62,代码来源:main.go
注:本文中的go/ast.NewCommentMap函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论