当前位置: 首页>>代码示例>>Golang>>正文


Golang FileSet.Position方法代码示例

本文整理汇总了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
}
开发者ID:rainycape,项目名称:gondola,代码行数:32,代码来源:extract.go

示例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
}
开发者ID:idvoretskyi,项目名称:coreos-kubernetes,代码行数:7,代码来源:definition.go

示例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
	})
}
开发者ID:ildarisaev,项目名称:srclib-go,代码行数:26,代码来源:coverage_test.go

示例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
}
开发者ID:rakyll,项目名称:GCSolutions,代码行数:34,代码来源:main.go

示例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])
}
开发者ID:serussell,项目名称:gen,代码行数:7,代码来源:main.go

示例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
}
开发者ID:charlievieth,项目名称:define,代码行数:7,代码来源:find.go

示例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",
	}
}
开发者ID:Karthikvb,项目名称:15640_projects,代码行数:7,代码来源:describe.go

示例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)
		}
	}
}
开发者ID:ProjectSerenity,项目名称:myth,代码行数:38,代码来源:error_test.go

示例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
}
开发者ID:Joinhack,项目名称:peony,代码行数:28,代码来源:gowalker.go

示例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
}
开发者ID:vpavkin,项目名称:GoRefactor,代码行数:33,代码来源:printer.go

示例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
}
开发者ID:elvin-du,项目名称:revel,代码行数:74,代码来源:reflect.go

示例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
}
开发者ID:vpavkin,项目名称:GoRefactor,代码行数:28,代码来源:printer.go

示例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)
	}
}
开发者ID:vpavkin,项目名称:GoRefactor,代码行数:32,代码来源:printer.go

示例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:])
	}
}
开发者ID:anuvazhayil,项目名称:HelloWorld_32bitOS,代码行数:27,代码来源:import.go

示例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
}
开发者ID:syreclabs,项目名称:go-tools,代码行数:29,代码来源:imports.go


注:本文中的go/token.FileSet.Position方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。