github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/tools/oracle/definition14.go (about) 1 // Copyright 2013 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // +build !go1.5 6 7 package oracle 8 9 import ( 10 "fmt" 11 "go/ast" 12 "go/token" 13 14 "golang.org/x/tools/go/loader" 15 "golang.org/x/tools/go/types" 16 "golang.org/x/tools/oracle/serial" 17 ) 18 19 // definition reports the location of the definition of an identifier. 20 // 21 // TODO(adonovan): opt: for intra-file references, the parser's 22 // resolution might be enough; we should start with that. 23 // 24 func definition(q *Query) error { 25 lconf := loader.Config{Build: q.Build} 26 allowErrors(&lconf) 27 28 if _, err := importQueryPackage(q.Pos, &lconf); err != nil { 29 return err 30 } 31 32 // Load/parse/type-check the program. 33 lprog, err := lconf.Load() 34 if err != nil { 35 return err 36 } 37 q.Fset = lprog.Fset 38 39 qpos, err := parseQueryPos(lprog, q.Pos, false) 40 if err != nil { 41 return err 42 } 43 44 id, _ := qpos.path[0].(*ast.Ident) 45 if id == nil { 46 return fmt.Errorf("no identifier here") 47 } 48 49 obj := qpos.info.ObjectOf(id) 50 if obj == nil { 51 // Happens for y in "switch y := x.(type)", 52 // and the package declaration, 53 // but I think that's all. 54 return fmt.Errorf("no object for identifier") 55 } 56 57 q.result = &definitionResult{qpos, obj} 58 return nil 59 } 60 61 type definitionResult struct { 62 qpos *queryPos 63 obj types.Object // object it denotes 64 } 65 66 func (r *definitionResult) display(printf printfFunc) { 67 printf(r.obj, "defined here as %s", r.qpos.objectString(r.obj)) 68 } 69 70 func (r *definitionResult) toSerial(res *serial.Result, fset *token.FileSet) { 71 definition := &serial.Definition{ 72 Desc: r.obj.String(), 73 } 74 if pos := r.obj.Pos(); pos != token.NoPos { // Package objects have no Pos() 75 definition.ObjPos = fset.Position(pos).String() 76 } 77 res.Definition = definition 78 }