func (e *exporter) addImport(pkg *types.Package) { if _, found := e.imports[pkg]; found { return } fmt.Fprintf(e.out, "import %s \"%s\"\n", pkg.Name(), pkg.Path()) e.imports[pkg] = true }
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, 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 } } 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 }
func (x *exporter) export(pkg *types.Package) error { x.pkg = pkg x.writeFunc = true exportsFile := packageExportsFile(x.context, pkg.Path()) err := os.MkdirAll(filepath.Dir(exportsFile), 0755) if err != nil && !os.IsExist(err) { return err } f2, err := os.Create(exportsFile) if err != nil { return err } defer f2.Close() x.writer = f2 x.write("package %s\n", pkg.Name()) for _, imp := range pkg.Imports() { x.write("\timport %s \"%s\"\n", imp.Name(), imp.Path()) } for _, n := range pkg.Scope().Names() { if obj := pkg.Scope().Lookup(n); obj != nil { x.exportObject(obj) } } x.write("$$") return nil }
// Export generates a file containing package export data // suitable for importing with Importer.Import. func Export(ctx *build.Context, pkg *types.Package) error { exportsPath := packageExportsFile(ctx, pkg.Path()) err := os.MkdirAll(filepath.Dir(exportsPath), 0755) if err != nil && !os.IsExist(err) { return err } tracef("Writing import data to %q", exportsPath) return ioutil.WriteFile(exportsPath, importer.ExportData(pkg), 0644) }
func WriteArchive(code []byte, pkg *types.Package, w io.Writer) { w.Write(code) w.Write([]byte("$$\n")) for _, impPkg := range pkg.Imports() { w.Write([]byte(impPkg.Path())) w.Write([]byte{'\n'}) } w.Write([]byte("$$\n")) gcexporter.Write(pkg, w, sizes32) }
func typePackageToJson(p *types.Package) interface{} { if p == nil { return nil } else { return struct { Isa, Name, ImportPath string }{ "Package", p.Name(), p.Path(), } } }
// pkgString returns a string representation of a package's exported interface. func pkgString(pkg *types.Package) string { var buf bytes.Buffer fmt.Fprintf(&buf, "package %s\n", pkg.Name()) scope := pkg.Scope() for _, name := range scope.Names() { if exported(name) { obj := scope.Lookup(name) buf.WriteString(obj.String()) switch obj := obj.(type) { case *types.Const: // For now only print constant values if they are not float // or complex. This permits comparing go/types results with // gc-generated gcimported package interfaces. info := obj.Type().Underlying().(*types.Basic).Info() if info&types.IsFloat == 0 && info&types.IsComplex == 0 { fmt.Fprintf(&buf, " = %s", obj.Val()) } case *types.TypeName: // Print associated methods. // Basic types (e.g., unsafe.Pointer) have *types.Basic // type rather than *types.Named; so we need to check. if typ, _ := obj.Type().(*types.Named); typ != nil { if n := typ.NumMethods(); n > 0 { // Sort methods by name so that we get the // same order independent of whether the // methods got imported or coming directly // for the source. // TODO(gri) This should probably be done // in go/types. list := make([]*types.Func, n) for i := 0; i < n; i++ { list[i] = typ.Method(i) } sort.Sort(byName(list)) buf.WriteString("\nmethods (\n") for _, m := range list { fmt.Fprintf(&buf, "\t%s\n", m) } buf.WriteString(")") } } } buf.WriteByte('\n') } } return buf.String() }
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 }
func assocObjectPackages(pkg *types.Package, objectdata map[types.Object]*ObjectData) { for _, obj := range pkg.Scope().Entries { if data, ok := objectdata[obj]; ok { data.Package = pkg } else { objectdata[obj] = &ObjectData{Package: pkg} } } for _, pkg := range pkg.Imports() { assocObjectPackages(pkg, objectdata) } }
func (ctx *Context) getObjects(paths []string) ([]types.Object, []error) { var errors []error var objects []types.Object pathLoop: for _, path := range paths { buildPkg, err := build.Import(path, ".", 0) if err != nil { errors = append(errors, fmt.Errorf("Couldn't import %s: %s", path, err)) continue } fset := token.NewFileSet() var astFiles []*ast.File var pkg *types.Package if buildPkg.Goroot { // TODO what if the compiled package in GoRoot is // outdated? pkg, err = types.GcImport(ctx.allImports, path) if err != nil { errors = append(errors, fmt.Errorf("Couldn't import %s: %s", path, err)) continue } } else { if len(buildPkg.GoFiles) == 0 { errors = append(errors, fmt.Errorf("Couldn't parse %s: No (non cgo) Go files", path)) continue pathLoop } for _, file := range buildPkg.GoFiles { astFile, err := parseFile(fset, filepath.Join(buildPkg.Dir, file)) if err != nil { errors = append(errors, fmt.Errorf("Couldn't parse %s: %s", err)) continue pathLoop } astFiles = append(astFiles, astFile) } pkg, err = check(ctx, path, fset, astFiles) if err != nil { errors = append(errors, fmt.Errorf("Couldn't parse %s: %s\n", path, err)) continue pathLoop } } scope := pkg.Scope() for i := 0; i < scope.NumEntries(); i++ { obj := scope.At(i) objects = append(objects, obj) } } return objects, errors }
func assocObjectPackages(pkg *types.Package, objectdata map[types.Object]*ObjectData) { scope := pkg.Scope() for _, name := range scope.Names() { obj := scope.Lookup(name) if data, ok := objectdata[obj]; ok { data.Package = pkg } else { objectdata[obj] = &ObjectData{Package: pkg} } } for _, pkg := range pkg.Imports() { assocObjectPackages(pkg, objectdata) } }
func (r *renamer) checkExport(id *ast.Ident, pkg *types.Package, from types.Object) bool { // Reject cross-package references if r.to is unexported. // (Such references may be qualified identifiers or field/method // selections.) if !ast.IsExported(r.to) && pkg != from.Pkg() { r.errorf(from.Pos(), "renaming this %s %q to %q would make it unexported", objectKind(from), from.Name(), r.to) r.errorf(id.Pos(), "\tbreaking references from packages such as %q", pkg.Path()) return false } return true }
// export emits the exported package features. func (w *Walker) export(pkg *types.Package) { if *verbose { log.Println(pkg) } pop := w.pushScope("pkg " + pkg.Path()) w.current = pkg scope := pkg.Scope() for _, name := range scope.Names() { if ast.IsExported(name) { w.emitObj(scope.Lookup(name)) } } pop() }
func describePackage(o *Oracle, qpos *QueryPos, path []ast.Node) (*describePackageResult, error) { var description string var pkg *types.Package switch n := path[0].(type) { case *ast.ImportSpec: var pkgname *types.PkgName if n.Name != nil { pkgname = qpos.info.Defs[n.Name].(*types.PkgName) } else if p := qpos.info.Implicits[n]; p != nil { pkgname = p.(*types.PkgName) } description = fmt.Sprintf("import of package %q", pkgname.Pkg().Path()) pkg = pkgname.Pkg() case *ast.Ident: if _, isDef := path[1].(*ast.File); isDef { // e.g. package id pkg = qpos.info.Pkg description = fmt.Sprintf("definition of package %q", pkg.Path()) } else { // e.g. import id "..." // or id.F() pkg = qpos.info.ObjectOf(n).Pkg() description = fmt.Sprintf("reference to package %q", pkg.Path()) } default: // Unreachable? return nil, fmt.Errorf("unexpected AST for package: %T", n) } var members []*describeMember // NB: "unsafe" has no types.Package if pkg != nil { // Enumerate the accessible package members // in lexicographic order. for _, name := range pkg.Scope().Names() { if pkg == qpos.info.Pkg || ast.IsExported(name) { mem := pkg.Scope().Lookup(name) var methods []*types.Selection if mem, ok := mem.(*types.TypeName); ok { methods = accessibleMethods(mem.Type(), qpos.info.Pkg) } members = append(members, &describeMember{ mem, methods, }) } } } return &describePackageResult{o.fset, path[0], description, pkg, members}, nil }
func describePackage(o *Oracle, qpos *QueryPos, path []ast.Node) (*describePackageResult, error) { var description string var pkg *types.Package switch n := path[0].(type) { case *ast.ImportSpec: // Most ImportSpecs have no .Name Ident so we can't // use ObjectOf. // We could use the types.Info.Implicits mechanism, // but it's easier just to look it up by name. description = "import of package " + n.Path.Value importPath, _ := strconv.Unquote(n.Path.Value) pkg = o.prog.ImportedPackage(importPath).Object case *ast.Ident: if _, isDef := path[1].(*ast.File); isDef { // e.g. package id pkg = qpos.info.Pkg description = fmt.Sprintf("definition of package %q", pkg.Path()) } else { // e.g. import id // or id.F() pkg = qpos.info.ObjectOf(n).Pkg() description = fmt.Sprintf("reference to package %q", pkg.Path()) } default: // Unreachable? return nil, fmt.Errorf("unexpected AST for package: %T", n) } var members []*describeMember // NB: "unsafe" has no types.Package if pkg != nil { // Enumerate the accessible package members // in lexicographic order. for _, name := range pkg.Scope().Names() { if pkg == qpos.info.Pkg || ast.IsExported(name) { mem := pkg.Scope().Lookup(name) var methods []*types.Selection if mem, ok := mem.(*types.TypeName); ok { methods = accessibleMethods(mem.Type(), qpos.info.Pkg) } members = append(members, &describeMember{ mem, methods, }) } } } return &describePackageResult{o.prog.Fset, path[0], description, pkg, members}, nil }
func testExportImport(t *testing.T, pkg0 *types.Package, path string) (size, gcsize int) { data := ExportData(pkg0) size = len(data) imports := make(map[string]*types.Package) n, pkg1, err := ImportData(imports, data) if err != nil { t.Errorf("package %s: import failed: %s", pkg0.Name(), err) return } if n != size { t.Errorf("package %s: not all input data consumed", pkg0.Name()) return } s0 := pkgString(pkg0) s1 := pkgString(pkg1) if s1 != s0 { t.Errorf("package %s: \nimport got:\n%s\nwant:\n%s\n", pkg0.Name(), s1, s0) } // If we have a standard library, compare also against the gcimported package. if path == "" { return // not std library } gcdata, err := gcExportData(path) gcsize = len(gcdata) imports = make(map[string]*types.Package) pkg2, err := gcImportData(imports, gcdata, path) if err != nil { t.Errorf("package %s: gcimport failed: %s", pkg0.Name(), err) return } s2 := pkgString(pkg2) if s2 != s0 { t.Errorf("package %s: \ngcimport got:\n%s\nwant:\n%s\n", pkg0.Name(), s2, s0) } return }
func FindImplentations(i *types.Interface, pkg *types.Package) []string { var names []string scope := pkg.Scope() allNames := scope.Names() for _, name := range allNames { obj := scope.Lookup(name) if typeName, ok := obj.(*types.TypeName); ok { if types.Implements(typeName.Type(), i) { names = append(names, typeName.Name()) } else { println(typeName.Name(), "cannot be an ensurer") println(types.NewMethodSet(typeName.Type()).String()) } } } return names }
func (p *importer) obj(pkg *types.Package) { var obj types.Object switch tag := p.int(); tag { case constTag: obj = types.NewConst(token.NoPos, pkg, p.string(), p.typ(), p.value()) case typeTag: // type object is added to scope via respective named type _ = p.typ().(*types.Named) return case varTag: obj = types.NewVar(token.NoPos, pkg, p.string(), p.typ()) case funcTag: obj = types.NewFunc(token.NoPos, pkg, p.string(), p.typ().(*types.Signature)) default: panic(fmt.Sprintf("unexpected object tag %d", tag)) } if alt := pkg.Scope().Insert(obj); alt != nil { panic(fmt.Sprintf("%s already declared", alt.Name())) } }
func (p *exporter) pkg(pkg *types.Package) { if trace { p.tracef("package { ") defer p.tracef("} ") } if pkg == nil { panic("unexpected nil pkg") } // if the package was seen before, write its index (>= 0) if i, ok := p.pkgIndex[pkg]; ok { p.int(i) return } p.pkgIndex[pkg] = len(p.pkgIndex) // otherwise, write the package tag (< 0) and package data p.int(packageTag) p.string(pkg.Name()) p.string(pkg.Path()) }
// ExportData serializes the interface (exported package objects) // of package pkg and returns the corresponding data. The export // format is described elsewhere (TODO). func ExportData(pkg *types.Package) []byte { p := exporter{ data: []byte(magic), pkgIndex: make(map[*types.Package]int), typIndex: make(map[types.Type]int), } // populate typIndex with predeclared types for _, t := range types.Typ[1:] { p.typIndex[t] = len(p.typIndex) } p.typIndex[types.Universe.Lookup("error").Type()] = len(p.typIndex) if trace { p.tracef("export %s\n", pkg.Name()) defer p.tracef("\n") } p.string(version) p.pkg(pkg) // collect exported objects from package scope var list []types.Object scope := pkg.Scope() for _, name := range scope.Names() { if exported(name) { list = append(list, scope.Lookup(name)) } } // write objects p.int(len(list)) for _, obj := range list { p.obj(obj) } return p.data }
// pkgpath returns a package path suitable for naming symbols. func pkgpath(p *types.Package) string { path := p.Path() name := p.Name() if path == "" || name == "main" { path = p.Name() } return path }
// Structure computes the structure of the lexical environment of the // package specified by (pkg, info, files). // // The info.{Types,Defs,Uses,Implicits} maps must have been populated // by the type-checker // // fset is used for logging. // func Structure(fset *token.FileSet, pkg *types.Package, info *types.Info, files []*ast.File) *Info { r := resolver{ fset: fset, imports: make(map[string]*types.Package), result: &Info{ Defs: make(map[types.Object]*Block), Refs: make(map[types.Object][]Reference), Blocks: make(map[ast.Node]*Block), }, pkg: pkg, info: info, } // Build import map for just this package. r.imports["unsafe"] = types.Unsafe for _, imp := range pkg.Imports() { r.imports[imp.Path()] = imp } r.doPackage(pkg, files) return r.result }
func (c *exporter) Export(pkg *types.Package) error { c.pkg = pkg c.writeFunc = true f2, err := os.Create(c.compiler.packageExportsFile(pkg.Path())) if err != nil { return err } defer f2.Close() c.writer = f2 c.write("package %s\n", pkg.Name()) for _, imp := range c.pkg.Imports() { c.write("\timport %s \"%s\"\n", imp.Name(), imp.Path()) } for _, n := range pkg.Scope().Names() { if obj := pkg.Scope().Lookup(n); obj != nil { c.exportObject(obj) } } c.write("$$") return nil }
func newRuntimeInterface(pkg *types.Package, module llvm.Module, tm *llvmTypeMap, fr FuncResolver) (*runtimeInterface, error) { var ri runtimeInterface runtimeTypes := map[string]*runtimeType{ "eface": &ri.eface, "rtype": &ri.rtype, "uncommonType": &ri.uncommonType, "arrayType": &ri.arrayType, "chanType": &ri.chanType, "funcType": &ri.funcType, "iface": &ri.iface, "imethod": &ri.imethod, "interfaceType": &ri.interfaceType, "itab": &ri.itab, "mapiter": &ri.mapiter, "mapType": &ri.mapType, "method": &ri.method, "ptrType": &ri.ptrType, "sliceType": &ri.sliceType, "structField": &ri.structField, "structType": &ri.structType, "defers": &ri.defers, } for name, field := range runtimeTypes { obj := pkg.Scope().Lookup(name) if obj == nil { return nil, fmt.Errorf("no runtime type with name %s", name) } field.Type = obj.Type() field.llvm = tm.ToLLVM(field.Type) } intrinsics := map[string]**LLVMValue{ "chanclose": &ri.chanclose, "chanrecv": &ri.chanrecv, "chansend": &ri.chansend, "compareE2E": &ri.compareE2E, "convertE2I": &ri.convertE2I, "convertE2V": &ri.convertE2V, "mustConvertE2I": &ri.mustConvertE2I, "mustConvertE2V": &ri.mustConvertE2V, "convertI2E": &ri.convertI2E, "eqtyp": &ri.eqtyp, "Go": &ri.Go, "initdefers": &ri.initdefers, "llvm_stackrestore": &ri.stackrestore, "llvm_stacksave": &ri.stacksave, "llvm_setjmp": &ri.setjmp, "main": &ri.main, "printfloat": &ri.printfloat, "makechan": &ri.makechan, "makemap": &ri.makemap, "malloc": &ri.malloc, "mapaccess": &ri.mapaccess, "mapdelete": &ri.mapdelete, "mapiterinit": &ri.mapiterinit, "mapiternext": &ri.mapiternext, "maplookup": &ri.maplookup, "memcpy": &ri.memcpy, "memequal": &ri.memequal, "memset": &ri.memset, "panic_": &ri.panic_, "pushdefer": &ri.pushdefer, "recover_": &ri.recover_, "rundefers": &ri.rundefers, "chancap": &ri.chancap, "chanlen": &ri.chanlen, "maplen": &ri.maplen, "makeslice": &ri.makeslice, "selectdefault": &ri.selectdefault, "selectgo": &ri.selectgo, "selectinit": &ri.selectinit, "selectrecv": &ri.selectrecv, "selectsend": &ri.selectsend, "selectsize": &ri.selectsize, "sliceappend": &ri.sliceappend, "slicecopy": &ri.slicecopy, "sliceslice": &ri.sliceslice, "stringslice": &ri.stringslice, "strcat": &ri.strcat, "strcmp": &ri.strcmp, "strnext": &ri.strnext, "strrune": &ri.strrune, "strtorunes": &ri.strtorunes, "runestostr": &ri.runestostr, "streqalg": &ri.streqalg, "f32eqalg": &ri.f32eqalg, "f64eqalg": &ri.f64eqalg, "c64eqalg": &ri.c64eqalg, "c128eqalg": &ri.c128eqalg, } for name, field := range intrinsics { obj := pkg.Scope().Lookup(name) if obj == nil { return nil, fmt.Errorf("no runtime function with name %s", name) } *field = fr.ResolveFunc(obj.(*types.Func)) } return &ri, nil }
// Transform applies the transformation to the specified parsed file, // whose type information is supplied in info, and returns the number // of replacements that were made. // // It mutates the AST in place (the identity of the root node is // unchanged), and may add nodes for which no type information is // available in info. // // Derived from rewriteFile in $GOROOT/src/cmd/gofmt/rewrite.go. // func (tr *Transformer) Transform(info *types.Info, pkg *types.Package, file *ast.File) int { if !tr.seenInfos[info] { tr.seenInfos[info] = true mergeTypeInfo(&tr.info.Info, info) } tr.currentPkg = pkg tr.nsubsts = 0 if tr.verbose { fmt.Fprintf(os.Stderr, "before: %s\n", astString(tr.fset, tr.before)) fmt.Fprintf(os.Stderr, "after: %s\n", astString(tr.fset, tr.after)) } var f func(rv reflect.Value) reflect.Value f = func(rv reflect.Value) reflect.Value { // don't bother if val is invalid to start with if !rv.IsValid() { return reflect.Value{} } rv = apply(f, rv) e := rvToExpr(rv) if e != nil { savedEnv := tr.env tr.env = make(map[string]ast.Expr) // inefficient! Use a slice of k/v pairs if tr.matchExpr(tr.before, e) { if tr.verbose { fmt.Fprintf(os.Stderr, "%s matches %s", astString(tr.fset, tr.before), astString(tr.fset, e)) if len(tr.env) > 0 { fmt.Fprintf(os.Stderr, " with:") for name, ast := range tr.env { fmt.Fprintf(os.Stderr, " %s->%s", name, astString(tr.fset, ast)) } } fmt.Fprintf(os.Stderr, "\n") } tr.nsubsts++ // Clone the replacement tree, performing parameter substitution. // We update all positions to n.Pos() to aid comment placement. rv = tr.subst(tr.env, reflect.ValueOf(tr.after), reflect.ValueOf(e.Pos())) } tr.env = savedEnv } return rv } file2 := apply(f, reflect.ValueOf(file)).Interface().(*ast.File) // By construction, the root node is unchanged. if file != file2 { panic("BUG") } // Add any necessary imports. // TODO(adonovan): remove no-longer needed imports too. if tr.nsubsts > 0 { pkgs := make(map[string]*types.Package) for obj := range tr.importedObjs { pkgs[obj.Pkg().Path()] = obj.Pkg() } for _, imp := range file.Imports { path, _ := strconv.Unquote(imp.Path.Value) delete(pkgs, path) } delete(pkgs, pkg.Path()) // don't import self // NB: AddImport may completely replace the AST! // It thus renders info and tr.info no longer relevant to file. var paths []string for path := range pkgs { paths = append(paths, path) } sort.Strings(paths) for _, path := range paths { astutil.AddImport(tr.fset, file, path) } } tr.currentPkg = nil return tr.nsubsts }
func isJsPackage(pkg *types.Package) bool { return pkg != nil && pkg.Path() == "github.com/gopherjs/gopherjs/js" }
func (p *printer) printPackage(pkg *types.Package, filter func(types.Object) bool) { // collect objects by kind var ( consts []*types.Const typem []*types.Named // non-interface types with methods typez []*types.TypeName // interfaces or types without methods vars []*types.Var funcs []*types.Func builtins []*types.Builtin methods = make(map[*types.Named][]*types.Selection) // method sets for named types ) scope := pkg.Scope() for _, name := range scope.Names() { obj := scope.Lookup(name) if obj.Exported() { // collect top-level exported and possibly filtered objects if filter == nil || filter(obj) { switch obj := obj.(type) { case *types.Const: consts = append(consts, obj) case *types.TypeName: // group into types with methods and types without if named, m := methodsFor(obj); named != nil { typem = append(typem, named) methods[named] = m } else { typez = append(typez, obj) } case *types.Var: vars = append(vars, obj) case *types.Func: funcs = append(funcs, obj) case *types.Builtin: // for unsafe.Sizeof, etc. builtins = append(builtins, obj) } } } else if filter == nil { // no filtering: collect top-level unexported types with methods if obj, _ := obj.(*types.TypeName); obj != nil { // see case *types.TypeName above if named, m := methodsFor(obj); named != nil { typem = append(typem, named) methods[named] = m } } } } p.printf("package %s // %q\n", pkg.Name(), pkg.Path()) p.printDecl("const", len(consts), func() { for _, obj := range consts { p.printObj(obj) p.print("\n") } }) p.printDecl("var", len(vars), func() { for _, obj := range vars { p.printObj(obj) p.print("\n") } }) p.printDecl("type", len(typez), func() { for _, obj := range typez { p.printf("%s ", obj.Name()) p.writeType(p.pkg, obj.Type().Underlying()) p.print("\n") } }) // non-interface types with methods for _, named := range typem { first := true if obj := named.Obj(); obj.Exported() { if first { p.print("\n") first = false } p.printf("type %s ", obj.Name()) p.writeType(p.pkg, named.Underlying()) p.print("\n") } for _, m := range methods[named] { if obj := m.Obj(); obj.Exported() { if first { p.print("\n") first = false } p.printFunc(m.Recv(), obj.(*types.Func)) p.print("\n") } } } if len(funcs) > 0 { p.print("\n") for _, obj := range funcs { p.printFunc(nil, obj) p.print("\n") } } // TODO(gri) better handling of builtins (package unsafe only) if len(builtins) > 0 { p.print("\n") for _, obj := range builtins { p.printf("func %s() // builtin\n", obj.Name()) } } p.print("\n") }
// funcSig returns the signature of the specified package-level function. func funcSig(pkg *types.Package, name string) *types.Signature { if f, ok := pkg.Scope().Lookup(name).(*types.Func); ok { return f.Type().(*types.Signature) } return nil }
// FunctionType = ParamList ResultList . func (p *parser) parseFunctionType(pkg *types.Package) *types.Signature { params, isVariadic := p.parseParamList(pkg) results := p.parseResultList(pkg) return types.NewSignature(pkg.Scope(), nil, params, results, isVariadic) }
func (p *printer) printPackage(pkg *types.Package, filter func(types.Object) bool) { // collect objects by kind var ( consts []*types.Const typez []*types.TypeName // types without methods typem []*types.TypeName // types with methods vars []*types.Var funcs []*types.Func builtins []*types.Builtin ) scope := pkg.Scope() for _, name := range scope.Names() { obj := scope.Lookup(name) if !filter(obj) { continue } switch obj := obj.(type) { case *types.Const: consts = append(consts, obj) case *types.TypeName: if named, _ := obj.Type().(*types.Named); named != nil && named.NumMethods() > 0 { typem = append(typem, obj) } else { typez = append(typez, obj) } case *types.Var: vars = append(vars, obj) case *types.Func: funcs = append(funcs, obj) case *types.Builtin: // for unsafe.Sizeof, etc. builtins = append(builtins, obj) } } p.printf("package %s // %q\n\n", pkg.Name(), pkg.Path()) if len(consts) > 0 { p.print("const (\n") p.indent++ for _, obj := range consts { p.printObj(obj) p.print("\n") } p.indent-- p.print(")\n\n") } if len(vars) > 0 { p.print("var (\n") p.indent++ for _, obj := range vars { p.printObj(obj) p.print("\n") } p.indent-- p.print(")\n\n") } if len(typez) > 0 { p.print("type (\n") p.indent++ for _, obj := range typez { p.printf("%s ", obj.Name()) p.writeType(p.pkg, obj.Type().Underlying()) p.print("\n") } p.indent-- p.print(")\n\n") } for _, obj := range typem { p.printf("type %s ", obj.Name()) typ := obj.Type().(*types.Named) p.writeType(p.pkg, typ.Underlying()) p.print("\n") for i, n := 0, typ.NumMethods(); i < n; i++ { p.printFunc(typ.Method(i)) p.print("\n") } p.print("\n") } for _, obj := range funcs { p.printFunc(obj) p.print("\n") } // TODO(gri) better handling of builtins (package unsafe only) for _, obj := range builtins { p.printf("func %s() // builtin\n", obj.Name()) } p.print("\n") }