本文整理汇总了Golang中go/token.FileSet.Position方法的典型用法代码示例。如果您正苦于以下问题:Golang FileSet.Position方法的具体用法?Golang FileSet.Position怎么用?Golang FileSet.Position使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类go/token.FileSet
的用法示例。
在下文中一共展示了FileSet.Position方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: extractGoType
func extractGoType(messages messageMap, fset *token.FileSet, f *ast.File, typ string) error {
// for castings
calls, err := astutil.Calls(fset, f, typ)
if err != nil {
return err
}
for _, c := range calls {
if len(c.Args) > 0 {
lit, pos := astutil.StringLiteral(fset, c.Args[0])
if pos == nil {
p := fset.Position(c.Pos())
log.Debugf("Skipping cast to %s (%v) - not a literal", typ, p)
continue
}
comment := comments(fset, f, pos)
if err := messages.AddString(&astutil.String{Value: lit, Position: pos}, comment); err != nil {
return err
}
}
}
strings, err := astutil.Strings(fset, f, typ)
if err != nil {
return err
}
for _, s := range strings {
comment := comments(fset, f, s.Position)
if err := messages.AddString(s, comment); err != nil {
return err
}
}
return nil
}
示例2: toSerial
func (r *definitionResult) toSerial(res *serial.Result, fset *token.FileSet) {
definition := &serial.Definition{
Desc: r.descr,
ObjPos: fset.Position(r.pos).String(),
}
res.Definition = definition
}
示例3: checkIdents
func checkIdents(t *testing.T, fset *token.FileSet, file *ast.File, idents map[identPos]interface{}, defs map[defPath]struct{}, g *Grapher, printAll bool) {
ast.Inspect(file, func(n ast.Node) bool {
if x, ok := n.(*ast.Ident); ok && !ignoreIdent(g, x) {
pos, end := fset.Position(x.Pos()), fset.Position(x.End())
if printAll {
t.Logf("ident %q at %s:%d-%d", x.Name, pos.Filename, pos.Offset, end.Offset)
}
ip := identPos{pos.Filename, uint32(pos.Offset), uint32(end.Offset)}
if obj, present := idents[ip]; !present {
t.Errorf("unresolved ident %q at %s", x.Name, pos)
} else if ref, ok := obj.(*Ref); ok {
if printAll {
t.Logf("ref to %+v from ident %q at %s:%d-%d", ref.Def, x.Name, pos.Filename, pos.Offset, end.Offset)
}
if *resolve {
if _, resolved := defs[ref.Def.defPath()]; !resolved && !ignoreRef(ref.Def.defPath()) {
t.Errorf("unresolved ref %q to %+v at %s", x.Name, ref.Def.defPath(), pos)
unresolvedIdents++
}
}
}
return false
}
return true
})
}
示例4: FindAllExports
func FindAllExports(pkg *types.Package, fset *token.FileSet) []UnexportCandidate {
candidates := []UnexportCandidate{}
for _, name := range pkg.Scope().Names() {
obj := pkg.Scope().Lookup(name)
if !obj.Exported() {
continue
}
displayName := obj.Name()
if _, ok := obj.(*types.Func); ok {
displayName += "()"
}
candidate := UnexportCandidate{obj.Name(), displayName, fset.Position(obj.Pos())}
candidates = append(candidates, candidate)
if tn, ok := obj.(*types.TypeName); ok {
if str, ok := tn.Type().Underlying().(*types.Struct); ok {
candidates = append(candidates, findStructFields(str, obj.Name(), fset)...)
}
ptrType := types.NewPointer(tn.Type())
methodSet := types.NewMethodSet(ptrType)
for i := 0; i < methodSet.Len(); i++ {
methodSel := methodSet.At(i)
method := methodSel.Obj()
// skip unexported functions, and functions from embedded fields.
// The best I can figure out for embedded functions is if the selection index path is longer than 1.
if !method.Exported() || len(methodSel.Index()) > 1 {
continue
}
candidate := UnexportCandidate{method.Name(), obj.Name() + "." + method.Name() + "()", fset.Position(method.Pos())}
candidates = append(candidates, candidate)
}
}
}
return candidates
}
示例5: getSourceString
func getSourceString(node ast.Node, fset *token.FileSet) string {
p1 := fset.Position(node.Pos())
p2 := fset.Position(node.End())
b := getFileBytes(p1.Filename)
return string(b[p1.Offset:p2.Offset])
}
示例6: Find
func (d docFinder) Find(af *ast.File, fset *token.FileSet) *token.Position {
if af.Comments != nil && len(af.Comments) != 0 {
p := fset.Position(af.Comments[0].Pos())
return &p
}
return nil
}
示例7: toSerial
func (r *describeStmtResult) toSerial(res *serial.Result, fset *token.FileSet) {
res.Describe = &serial.Describe{
Desc: r.description,
Pos: fset.Position(r.node.Pos()).String(),
Detail: "unknown",
}
}
示例8: compareErrors
// compareErrors compares the map of expected error messages with the list
// of found errors and reports discrepancies.
//
func compareErrors(t *testing.T, fset *token.FileSet, expected map[token.Pos]string, found scanner.ErrorList) {
for _, error := range found {
// error.Pos is a token.Position, but we want
// a token.Pos so we can do a map lookup
pos := getPos(fset, error.Pos.Filename, error.Pos.Offset)
if msg, found := expected[pos]; found {
// we expect a message at pos; check if it matches
rx, err := regexp.Compile(msg)
if err != nil {
t.Errorf("%s: %v", error.Pos, err)
continue
}
if match := rx.MatchString(error.Msg); !match {
t.Errorf("%s: %q does not match %q", error.Pos, error.Msg, msg)
continue
}
// we have a match - eliminate this error
delete(expected, pos)
} else {
// To keep in mind when analyzing failed test output:
// If the same error position occurs multiple times in errors,
// this message will be triggered (because the first error at
// the position removes this position from the expected errors).
t.Errorf("%s: unexpected error: %s", error.Pos, error.Msg)
}
}
// there should be no expected errors left
if len(expected) > 0 {
t.Errorf("%d errors not reported:", len(expected))
for pos, msg := range expected {
t.Errorf("%s: %s\n", fset.Position(pos), msg)
}
}
}
示例9: processComments
func (c *CodeGenCreaters) processComments(fileSet *token.FileSet, commentGroup *ast.CommentGroup, typ string, sepc CodeGenSpec) ([]CodeGen, error) {
codeGens := []CodeGen{}
if commentGroup == nil || len(commentGroup.List) <= 0 {
return codeGens, nil
}
for _, comment := range commentGroup.List {
if comment.Text[:2] == "//" {
content := strings.TrimSpace(comment.Text[2:])
if len(content) == 0 || content[0] != '@' {
continue
}
for _, codeGenCreater := range (*c)[typ] {
if codeGen, err := codeGenCreater(content, sepc); err == nil {
codeGens = append(codeGens, codeGen)
} else {
if err == NotMatch {
continue
}
position := fileSet.Position(comment.Pos())
perr := NewErrorFromPosition(position, err)
return nil, perr
}
}
}
}
return codeGens, nil
}
示例10: ModifyLine
func ModifyLine(fset *token.FileSet, file *ast.File, filename string, identMap st.IdentifierMap, Pos token.Pos, mod int) (*token.FileSet, *ast.File, int) {
baseMod := 1
if mod > 0 {
tokFile := GetFileFromFileSet(fset, filename)
baseMod = tokFile.Base()
Pos -= token.Pos(tokFile.Base()) - 1
fset, file = ReparseFile(file, filename, mod, identMap)
tokFile = GetFileFromFileSet(fset, filename)
lines := GetLines(tokFile)
tokFile.SetLines(lines[:len(lines)-(mod)])
}
tokFile := GetFileFromFileSet(fset, filename)
lines := GetLines(tokFile)
for i, offset := range lines {
fmt.Printf("%d -> %s(%d)\n", i+1, fset.Position(tokFile.Pos(offset)), offset)
}
var li int
for i, l := range lines {
if l > tokFile.Offset(Pos) {
li = i
break
}
}
for i := li; i < len(lines); i++ {
lines[i] += mod
}
tokFile.SetLines(lines)
for i, offset := range lines {
fmt.Printf("%d -> %s(%d)\n", i+1, fset.Position(tokFile.Pos(offset)), offset)
}
return fset, file, baseMod
}
示例11: getValidationKeys
// Scan app source code for calls to X.Y(), where X is of type *Validation.
//
// Recognize these scenarios:
// - "Y" = "Validation" and is a member of the receiver.
// (The common case for inline validation)
// - "X" is passed in to the func as a parameter.
// (For structs implementing Validated)
//
// The line number to which a validation call is attributed is that of the
// surrounding ExprStmt. This is so that it matches what runtime.Callers()
// reports.
//
// The end result is that we can set the default validation key for each call to
// be the same as the local variable.
func getValidationKeys(fset *token.FileSet, funcDecl *ast.FuncDecl, imports map[string]string) map[int]string {
var (
lineKeys = make(map[int]string)
// Check the func parameters and the receiver's members for the *revel.Validation type.
validationParam = getValidationParameter(funcDecl, imports)
)
ast.Inspect(funcDecl.Body, func(node ast.Node) bool {
// e.g. c.Validation.Required(arg) or v.Required(arg)
callExpr, ok := node.(*ast.CallExpr)
if !ok {
return true
}
// e.g. c.Validation.Required or v.Required
funcSelector, ok := callExpr.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
switch x := funcSelector.X.(type) {
case *ast.SelectorExpr: // e.g. c.Validation
if x.Sel.Name != "Validation" {
return true
}
case *ast.Ident: // e.g. v
if validationParam == nil || x.Obj != validationParam {
return true
}
default:
return true
}
if len(callExpr.Args) == 0 {
return true
}
// If the argument is a binary expression, take the first expression.
// (e.g. c.Validation.Required(myName != ""))
arg := callExpr.Args[0]
if binExpr, ok := arg.(*ast.BinaryExpr); ok {
arg = binExpr.X
}
// If it's a literal, skip it.
if _, ok = arg.(*ast.BasicLit); ok {
return true
}
if typeExpr := NewTypeExpr("", arg); typeExpr.Valid {
lineKeys[fset.Position(callExpr.End()).Line] = typeExpr.TypeName("")
}
return true
})
return lineKeys
}
示例12: DeleteNode
func DeleteNode(fset *token.FileSet, filename string, file *ast.File, posStart, posEnd token.Position) (bool, *errors.GoRefactorError) {
tokFile := GetFileFromFileSet(fset, filename)
if tokFile == nil {
return false, errors.PrinterError("couldn't find file " + filename + " in fileset")
}
node := FindNode(fset, file, posStart, posEnd)
if node == nil {
return false, errors.PrinterError("couldn't find node with given positions")
}
lines := GetLines(tokFile)
for i, offset := range lines {
fmt.Printf("%d -> %s(%d)\n", i+1, fset.Position(tokFile.Pos(offset)), offset)
}
nodeLines, firstLine := GetRangeLines(tokFile, node.Pos(), node.End(), tokFile.Size())
if _, ok := deleteNode(fset, posStart, posEnd, file); !ok {
return false, errors.PrinterError("didn't find node to delete")
}
deleteCommentsInRange(file, node.Pos(), node.End())
inc := -int(node.End() - node.Pos())
fmt.Printf("\n%v, %v, mod = %v\n", nodeLines, firstLine, inc)
FixPositions(node.Pos(), inc, file, true)
tokFile.SetLines(removeLinesOfRange(tokFile.Offset(node.Pos()), tokFile.Offset(node.End()), lines, nodeLines, firstLine))
return true, nil
}
示例13: AddLineForRange
func AddLineForRange(fset *token.FileSet, filename string, Pos, End token.Pos) {
tokFile := GetFileFromFileSet(fset, filename)
lines := GetLines(tokFile)
for i, offset := range lines {
fmt.Printf("%d -> %s(%d)\n", i+1, fset.Position(tokFile.Pos(offset)), offset)
}
var li int
for i, l := range lines {
if l > tokFile.Offset(Pos) {
li = i
break
}
}
if li == 0 {
li = len(lines) - 1
}
//mod := int(End-Pos) + tokFile.Offset(Pos) - lines[li-1]
fmt.Printf("node --------- %d %d\n", tokFile.Offset(Pos), tokFile.Offset(End))
mod := int(End - Pos)
fmt.Printf("mod = %d\n", mod)
newLines := make([]int, len(lines)+1)
copy(newLines, lines[0:li-1])
//newLines[li-1] = tokFile.Offset(Pos) - (tokFile.Offset(Pos) - lines[li-1])
newLines[li-1] = tokFile.Offset(Pos)
for i := li - 1; i < len(lines); i++ {
newLines[i+1] = lines[i] + mod
}
tokFile.SetLines(newLines)
for i, offset := range newLines {
fmt.Printf("%d -> %s(%d)\n", i+1, fset.Position(tokFile.Pos(offset)), offset)
}
}
示例14: SortImports
// SortImports sorts runs of consecutive import lines in import blocks in f.
func SortImports(fset *token.FileSet, f *File) {
for _, d := range f.Decls {
d, ok := d.(*GenDecl)
if !ok || d.Tok != token.IMPORT {
// Not an import declaration, so we're done.
// Imports are always first.
break
}
if d.Lparen == token.NoPos {
// Not a block: sorted by default.
continue
}
// Identify and sort runs of specs on successive lines.
i := 0
for j, s := range d.Specs {
if j > i && fset.Position(s.Pos()).Line > 1+fset.Position(d.Specs[j-1].End()).Line {
// j begins a new run. End this one.
sortSpecs(fset, f, d.Specs[i:j])
i = j
}
}
sortSpecs(fset, f, d.Specs[i:])
}
}
示例15: Imports
// Imports returns the file imports grouped by paragraph.
func Imports(fset *token.FileSet, f *ast.File) [][]*ast.ImportSpec {
var groups [][]*ast.ImportSpec
for _, decl := range f.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok || genDecl.Tok != token.IMPORT {
break
}
group := []*ast.ImportSpec{}
var lastLine int
for _, spec := range genDecl.Specs {
importSpec := spec.(*ast.ImportSpec)
pos := importSpec.Path.ValuePos
line := fset.Position(pos).Line
if lastLine > 0 && pos > 0 && line-lastLine > 1 {
groups = append(groups, group)
group = []*ast.ImportSpec{}
}
group = append(group, importSpec)
lastLine = line
}
groups = append(groups, group)
}
return groups
}