本文整理汇总了Golang中go/ast.File.Pos方法的典型用法代码示例。如果您正苦于以下问题:Golang File.Pos方法的具体用法?Golang File.Pos怎么用?Golang File.Pos使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类go/ast.File
的用法示例。
在下文中一共展示了File.Pos方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: generateGodebugIdentifiers
func generateGodebugIdentifiers(f *ast.File) {
// Variables that won't have suffixes.
idents.ctx = createConflictFreeName("ctx", f, false)
idents.ok = createConflictFreeName("ok", f, false)
idents.scope = createConflictFreeName("scope", f, false)
idents.receiver = createConflictFreeName("receiver", f, false)
idents.recoverChan = createConflictFreeName("rr", f, false)
idents.recoverChanChan = createConflictFreeName("r", f, false)
idents.recovers = createConflictFreeName("recovers", f, false)
idents.panicVal = createConflictFreeName("v", f, false)
idents.panicChan = createConflictFreeName("panicChan", f, false)
idents.godebug = generateGodebugPkgName(f)
// Variables that will have suffixes.
idents.result = createConflictFreeName("result", f, true)
idents.input = createConflictFreeName("input", f, true)
// Variables with names derived from the filename.
base := strings.Map(func(r rune) rune {
if !unicode.In(r, unicode.Digit, unicode.Letter) {
return '_'
}
return r
}, filepath.Base(fs.Position(f.Pos()).Filename))
if !unicode.IsLetter(rune(base[0])) {
// identifiers must start with letters
base = "a" + base
}
idents.fileScope = createConflictFreeName(base+"_scope", f, false)
idents.fileContents = createConflictFreeName(base+"_contents", f, false)
}
示例2: file
func (p *printer) file(src *ast.File) {
p.setComment(src.Doc)
p.print(src.Pos(), token.PACKAGE, blank)
p.expr(src.Name)
if len(src.Decls) > 0 {
tok := token.ILLEGAL
for _, d := range src.Decls {
prev := tok
tok = declToken(d)
// if the declaration token changed (e.g., from CONST to TYPE)
// or the next declaration has documentation associated with it,
// print an empty line between top-level declarations
// (because p.linebreak is called with the position of d, which
// is past any documentation, the minimum requirement is satisfied
// even w/o the extra getDoc(d) nil-check - leave it in case the
// linebreak logic improves - there's already a TODO).
min := 1
if prev != tok || getDoc(d) != nil {
min = 2
}
p.linebreak(p.lineFor(d.Pos()), min, ignore, false)
p.decl(d)
}
}
p.print(newline)
}
示例3: file
func (p *printer) file(src *ast.File) {
p.setComment(src.Doc)
p.print(src.Pos(), token.PACKAGE, blank)
p.expr(src.Name)
p.declList(src.Decls)
p.print(newline)
}
示例4: offsetLine
func offsetLine(fset *token.FileSet, af *ast.File, offset int) (line int) {
defer func() {
if err := recover(); err != nil {
line = 0
}
}()
return fset.File(af.Pos()).Position(token.Pos(offset)).Line
}
示例5: parseFileset
func parseFileset(wks filesystem.WorkspaceFS, f *ast.File, fs *token.FileSet) []TokenPosition {
var res []TokenPosition
if f.Name != nil {
res = appendTokenPosition(wks, res, fs.Position(f.Pos()), f.Name.Name, "", PACKAGE)
}
for _, i := range f.Imports {
if i.Path != nil {
res = appendTokenPosition(wks, res, fs.Position(f.Pos()), i.Path.Value, "", IMPORT)
}
}
for _, d := range f.Decls {
switch x := d.(type) {
case *ast.FuncDecl:
pos := fs.Position(x.Pos())
if x.Recv != nil && len(x.Recv.List) > 0 {
var recv *string
n := x.Recv.List[0].Type
id, ok := n.(*ast.Ident)
if !ok {
sid, ok := n.(*ast.StarExpr)
if ok {
id, ok = sid.X.(*ast.Ident)
if ok {
r := fmt.Sprintf("*%s", id.Name)
recv = &r
}
}
} else {
recv = &id.Name
}
res = appendTokenPosition(wks, res, pos, x.Name.Name, *recv, METH)
} else {
res = appendTokenPosition(wks, res, pos, x.Name.Name, "", FUNC)
}
case *ast.GenDecl:
switch x.Tok {
case token.CONST:
for _, s := range x.Specs {
vs := s.(*ast.ValueSpec)
res = appendTokenPosition(wks, res, fs.Position(vs.Pos()), vs.Names[0].Name, "", CONST)
}
case token.VAR:
for _, s := range x.Specs {
vs := s.(*ast.ValueSpec)
res = appendTokenPosition(wks, res, fs.Position(vs.Pos()), vs.Names[0].Name, "", VAR)
}
case token.TYPE:
for _, s := range x.Specs {
vs := s.(*ast.TypeSpec)
res = appendTokenPosition(wks, res, fs.Position(vs.Pos()), vs.Name.Name, "", TYPE)
}
}
}
}
return res
}
示例6: packageForFile
func (scp *schemaParser) packageForFile(gofile *ast.File) (*loader.PackageInfo, error) {
for pkg, pkgInfo := range scp.program.AllPackages {
if pkg.Name() == gofile.Name.Name {
return pkgInfo, nil
}
}
fn := scp.program.Fset.File(gofile.Pos()).Name()
return nil, fmt.Errorf("unable to determine package for %s", fn)
}
示例7: nodeAtOffset
// nodeAtOffset, returns the ast.Node for the given offset.
// Node types: *ast.Ident, *ast.SelectorExpr, *ast.ImportSpec
func nodeAtOffset(af *ast.File, fset *token.FileSet, offset int) (ast.Node, error) {
file := fset.File(af.Pos())
if file == nil {
return nil, errors.New("ast.File not in token.FileSet")
}
// Prevent file.Pos from panicking.
if offset < 0 || file.Size() < offset {
return nil, fmt.Errorf("invalid offset: %d", offset)
}
v := &offsetVisitor{pos: file.Pos(offset)}
ast.Walk(v, af)
if v.node == nil {
return nil, fmt.Errorf("no node at offset: %d", offset)
}
return v.node, nil
}
示例8: file
func (p *printer) file(src *ast.File) {
p.setComment(src.Doc)
p.print(src.Pos(), token.PACKAGE, blank)
p.expr(src.Name, ignoreMultiLine)
if len(src.Decls) > 0 {
tok := token.ILLEGAL
for _, d := range src.Decls {
prev := tok
tok = declToken(d)
// if the declaration token changed (e.g., from CONST to TYPE)
// print an empty line between top-level declarations
min := 1
if prev != tok {
min = 2
}
p.linebreak(d.Pos().Line, min, ignore, false)
p.decl(d, ignoreMultiLine)
}
}
p.print(newline)
}
示例9: PathEnclosingInterval
// PathEnclosingInterval returns the node that encloses the source
// interval [start, end), and all its ancestors up to the AST root.
//
// The definition of "enclosing" used by this function considers
// additional whitespace abutting a node to be enclosed by it.
// In this example:
//
// z := x + y // add them
// <-A->
// <----B----->
//
// the ast.BinaryExpr(+) node is considered to enclose interval B
// even though its [Pos()..End()) is actually only interval A.
// This behaviour makes user interfaces more tolerant of imperfect
// input.
//
// This function treats tokens as nodes, though they are not included
// in the result. e.g. PathEnclosingInterval("+") returns the
// enclosing ast.BinaryExpr("x + y").
//
// If start==end, the 1-char interval following start is used instead.
//
// The 'exact' result is true if the interval contains only path[0]
// and perhaps some adjacent whitespace. It is false if the interval
// overlaps multiple children of path[0], or if it contains only
// interior whitespace of path[0].
// In this example:
//
// z := x + y // add them
// <--C--> <---E-->
// ^
// D
//
// intervals C, D and E are inexact. C is contained by the
// z-assignment statement, because it spans three of its children (:=,
// x, +). So too is the 1-char interval D, because it contains only
// interior whitespace of the assignment. E is considered interior
// whitespace of the BlockStmt containing the assignment.
//
// Precondition: [start, end) both lie within the same file as root.
// TODO(adonovan): return (nil, false) in this case and remove precond.
// Requires FileSet; see tokenFileContainsPos.
//
// Postcondition: path is never nil; it always contains at least 'root'.
//
func PathEnclosingInterval(root *ast.File, start, end token.Pos) (path []ast.Node, exact bool) {
// fmt.Printf("EnclosingInterval %d %d\n", start, end) // debugging
// Precondition: node.[Pos..End) and adjoining whitespace contain [start, end).
var visit func(node ast.Node) bool
visit = func(node ast.Node) bool {
path = append(path, node)
nodePos := node.Pos()
nodeEnd := node.End()
// fmt.Printf("visit(%T, %d, %d)\n", node, nodePos, nodeEnd) // debugging
// Intersect [start, end) with interval of node.
if start < nodePos {
start = nodePos
}
if end > nodeEnd {
end = nodeEnd
}
// Find sole child that contains [start, end).
children := childrenOf(node)
l := len(children)
for i, child := range children {
// [childPos, childEnd) is unaugmented interval of child.
childPos := child.Pos()
childEnd := child.End()
// [augPos, augEnd) is whitespace-augmented interval of child.
augPos := childPos
augEnd := childEnd
if i > 0 {
augPos = children[i-1].End() // start of preceding whitespace
}
if i < l-1 {
nextChildPos := children[i+1].Pos()
// Does [start, end) lie between child and next child?
if start >= augEnd && end <= nextChildPos {
return false // inexact match
}
augEnd = nextChildPos // end of following whitespace
}
// fmt.Printf("\tchild %d: [%d..%d)\tcontains interval [%d..%d)?\n",
// i, augPos, augEnd, start, end) // debugging
// Does augmented child strictly contain [start, end)?
if augPos <= start && end <= augEnd {
_, isToken := child.(tokenNode)
return isToken || visit(child)
}
// Does [start, end) overlap multiple children?
// i.e. left-augmented child contains start
//.........这里部分代码省略.........
示例10: Import
func (w *PkgWalker) Import(parentDir string, name string, conf *PkgConfig) (pkg *types.Package, err error) {
defer func() {
err := recover()
if err != nil && typeVerbose {
log.Println(err)
}
}()
if strings.HasPrefix(name, ".") && parentDir != "" {
name = filepath.Join(parentDir, name)
}
pkg = w.imported[name]
if pkg != nil {
if pkg == &w.importing {
return nil, fmt.Errorf("cycle importing package %q", name)
}
return pkg, nil
}
if typeVerbose {
log.Println("parser pkg", name)
}
var bp *build.Package
if filepath.IsAbs(name) {
bp, err = w.context.ImportDir(name, 0)
} else {
bp, err = w.context.Import(name, "", 0)
}
checkName := name
if bp.ImportPath == "." {
checkName = bp.Name
} else {
checkName = bp.ImportPath
}
if err != nil {
return nil, err
//if _, nogo := err.(*build.NoGoError); nogo {
// return
//}
//return
//log.Fatalf("pkg %q, dir %q: ScanDir: %v", name, info.Dir, err)
}
filenames := append(append([]string{}, bp.GoFiles...), bp.CgoFiles...)
filenames = append(filenames, bp.TestGoFiles...)
if name == "runtime" {
n := fmt.Sprintf("zgoos_%s.go", w.context.GOOS)
if !contains(filenames, n) {
filenames = append(filenames, n)
}
n = fmt.Sprintf("zgoarch_%s.go", w.context.GOARCH)
if !contains(filenames, n) {
filenames = append(filenames, n)
}
}
parserFiles := func(filenames []string, cursor *FileCursor) (files []*ast.File) {
for _, file := range filenames {
var f *ast.File
if cursor != nil && cursor.fileName == file {
f, err = w.parseFile(bp.Dir, file, cursor.src)
cursor.pos = token.Pos(w.fset.File(f.Pos()).Base()) + token.Pos(cursor.cursorPos)
cursor.fileDir = bp.Dir
} else {
f, err = w.parseFile(bp.Dir, file, nil)
}
if err != nil && typeVerbose {
log.Printf("error parsing package %s: %s\n", name, err)
}
files = append(files, f)
}
return
}
files := parserFiles(filenames, conf.Cursor)
xfiles := parserFiles(bp.XTestGoFiles, conf.Cursor)
typesConf := types.Config{
IgnoreFuncBodies: conf.IgnoreFuncBodies,
FakeImportC: true,
Packages: w.gcimporter,
Import: func(imports map[string]*types.Package, name string) (pkg *types.Package, err error) {
if pkg != nil {
return pkg, nil
}
if conf.AllowBinary && w.isBinaryPkg(name) {
pkg = w.gcimporter[name]
if pkg != nil && pkg.Complete() {
return
}
pkg, err = gcimporter.Import(imports, name)
if pkg != nil && pkg.Complete() {
w.gcimporter[name] = pkg
return
}
//.........这里部分代码省略.........
示例11: filename
func filename(file *ast.File, fset *token.FileSet) string {
return fset.File(file.Pos()).Name()
}