Пример #1
0
func (w *PkgWalker) LookupStructFromField(info *types.Info, cursorPkg *types.Package, cursorObj types.Object, cursorPos token.Pos) types.Object {
	if info == nil {
		conf := &PkgConfig{
			IgnoreFuncBodies: true,
			AllowBinary:      true,
			WithTestFiles:    true,
			Info: &types.Info{
				Defs: make(map[*ast.Ident]types.Object),
			},
		}
		w.imported[cursorPkg.Path()] = nil
		pkg, _ := w.Import("", cursorPkg.Path(), conf)
		if pkg != nil {
			info = conf.Info
		}
	}
	if info == nil {
		return nil
	}
	for _, obj := range info.Defs {
		if obj == nil {
			continue
		}
		if _, ok := obj.(*types.TypeName); ok {
			if t, ok := obj.Type().Underlying().(*types.Struct); ok {
				for i := 0; i < t.NumFields(); i++ {
					if t.Field(i).Pos() == cursorPos {
						return obj
					}
				}
			}
		}
	}
	return nil
}
Пример #2
0
func declTypeName(pkg *types.Package, name string) *types.TypeName {
	scope := pkg.Scope()
	if obj := scope.Lookup(name); obj != nil {
		return obj.(*types.TypeName)
	}
	obj := types.NewTypeName(token.NoPos, pkg, name, nil)
	// a named type may be referred to before the underlying type
	// is known - set it up
	types.NewNamed(obj, nil, nil)
	scope.Insert(obj)
	return obj
}
Пример #3
0
func (w *PkgWalker) LookupImport(pkg *types.Package, pkgInfo *types.Info, cursor *FileCursor, is *ast.ImportSpec) []*Doc {
	fpath, err := strconv.Unquote(is.Path.Value)
	if err != nil {
		return []*Doc{}
	}

	ret := []*Doc{}

	if w.findDef {
		fpos := w.fset.Position(is.Pos())
		ret = append(ret, &Doc{
			Pkg:  pkg.Name(),
			Src:  "",
			Name: is.Name.Name,
			Kind: "package",
			Fn:   fpos.Filename,
			Row:  fpos.Line - 1,
			Col:  fpos.Column - 1,
		})
		fmt.Println(fpos)
	}

	fbase := fpath
	pos := strings.LastIndexAny(fpath, "./-\\")
	if pos != -1 {
		fbase = fpath[pos+1:]
	}

	var fname string
	if is.Name != nil {
		fname = is.Name.Name
	} else {
		fname = fbase
	}

	if w.findInfo {
		if fname == fpath {
			fmt.Printf("package %s\n", fname)
		} else {
			fmt.Printf("package %s (\"%s\")\n", fname, fpath)
		}
	}

	if !w.findUse {
		return ret
	}

	fid := pkg.Path() + "." + fname
	var usages []int
	for id, obj := range pkgInfo.Uses {
		if obj != nil && obj.Id() == fid { //!= nil && cursorObj.Pos() == obj.Pos() {
			usages = append(usages, int(id.Pos()))
		}
	}
	(sort.IntSlice(usages)).Sort()
	for _, pos := range usages {
		fpos := w.fset.Position(token.Pos(pos))
		ret = append(ret, &Doc{
			Pkg:  pkg.Name(),
			Src:  "",
			Name: fname,
			Kind: "package",
			Fn:   fpos.Filename,
			Row:  fpos.Line - 1,
			Col:  fpos.Column - 1,
		})
		if typeVerbose {
			log.Println(fpos)
		}
	}

	return ret
}