本文整理汇总了Golang中go/types.NewFunc函数的典型用法代码示例。如果您正苦于以下问题:Golang NewFunc函数的具体用法?Golang NewFunc怎么用?Golang NewFunc使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewFunc函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: obj
func (p *importer) obj(tag int) {
switch tag {
case constTag:
pos := p.pos()
pkg, name := p.qualifiedName()
typ := p.typ(nil)
val := p.value()
p.declare(types.NewConst(pos, pkg, name, typ, val))
case typeTag:
_ = p.typ(nil)
case varTag:
pos := p.pos()
pkg, name := p.qualifiedName()
typ := p.typ(nil)
p.declare(types.NewVar(pos, pkg, name, typ))
case funcTag:
pos := p.pos()
pkg, name := p.qualifiedName()
params, isddd := p.paramList()
result, _ := p.paramList()
sig := types.NewSignature(nil, params, result, isddd)
p.declare(types.NewFunc(pos, pkg, name, sig))
default:
panic(fmt.Sprintf("unexpected object tag %d", tag))
}
}
示例2: method
func (p *importer) method(parent *types.Package) *types.Func {
pos := p.pos()
pkg, name := p.fieldName(parent)
params, isddd := p.paramList()
result, _ := p.paramList()
sig := types.NewSignature(nil, params, result, isddd)
return types.NewFunc(pos, pkg, name, sig)
}
示例3: parseFunc
// Func = Name FunctionType .
func (p *parser) parseFunc(pkg *types.Package) *types.Func {
name := p.parseName()
if strings.ContainsRune(name, '$') {
// This is a Type$equal or Type$hash function, which we don't want to parse,
// except for the types.
p.discardDirectiveWhileParsingTypes(pkg)
return nil
}
return types.NewFunc(token.NoPos, pkg, name, p.parseFunctionType(pkg))
}
示例4: ParseFuncDecl
func ParseFuncDecl(fnDecl *gst.FuncDecl) (*types.Func, bool) {
var fn *types.Func
var pkg *types.Package
pkg = nil
name := fnDecl.Name
var sig *types.Signature
sig = types.NewSignature(nil, nil, nil, false)
var pos token.Pos
fn = types.NewFunc(pos, pkg, name, sig)
return fn, true
}
示例5: parseInterfaceType
// InterfaceType = "interface" "{" [ MethodList ] "}" .
// MethodList = Method { ";" Method } .
// Method = Name Signature .
//
// The methods of embedded interfaces are always "inlined"
// by the compiler and thus embedded interfaces are never
// visible in the export data.
//
func (p *parser) parseInterfaceType(parent *types.Package) types.Type {
var methods []*types.Func
p.expectKeyword("interface")
p.expect('{')
for i := 0; p.tok != '}' && p.tok != scanner.EOF; i++ {
if i > 0 {
p.expect(';')
}
pkg, name := p.parseName(parent, true)
sig := p.parseSignature(nil)
methods = append(methods, types.NewFunc(token.NoPos, pkg, name, sig))
}
p.expect('}')
// Complete requires the type's embedded interfaces to be fully defined,
// but we do not define any
return types.NewInterface(methods, nil).Complete()
}
示例6: obj
func (p *importer) obj(tag int) {
switch tag {
case constTag:
pos := p.pos()
pkg, name := p.qualifiedName()
typ := p.typ(nil)
val := p.value()
p.declare(types.NewConst(pos, pkg, name, typ, val))
case typeTag:
p.typ(nil)
case varTag:
pos := p.pos()
pkg, name := p.qualifiedName()
typ := p.typ(nil)
p.declare(types.NewVar(pos, pkg, name, typ))
case funcTag:
pos := p.pos()
pkg, name := p.qualifiedName()
params, isddd := p.paramList()
result, _ := p.paramList()
sig := types.NewSignature(nil, params, result, isddd)
p.declare(types.NewFunc(pos, pkg, name, sig))
case aliasTag:
pos := p.pos()
name := p.string()
var orig types.Object
if pkg, name := p.qualifiedName(); pkg != nil {
orig = pkg.Scope().Lookup(name)
}
// Alias-related code. Keep for now.
_ = pos
_ = name
_ = orig
// p.declare(types.NewAlias(pos, p.pkgList[0], name, orig))
default:
errorf("unexpected object tag %d", tag)
}
}
示例7: parseMethodDecl
// MethodDecl = "func" Receiver Name Func .
// Receiver = "(" ( identifier | "?" ) [ "*" ] ExportedName ")" .
//
func (p *parser) parseMethodDecl() {
// "func" already consumed
p.expect('(')
recv, _ := p.parseParameter() // receiver
p.expect(')')
// determine receiver base type object
base := deref(recv.Type()).(*types.Named)
// parse method name, signature, and possibly inlined body
_, name := p.parseName(nil, false)
sig := p.parseFunc(recv)
// methods always belong to the same package as the base type object
pkg := base.Obj().Pkg()
// add method to type unless type was imported before
// and method exists already
// TODO(gri) This leads to a quadratic algorithm - ok for now because method counts are small.
base.AddMethod(types.NewFunc(token.NoPos, pkg, name, sig))
}
示例8: obj
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()))
}
}
示例9: parseNamedType
// NamedType = TypeName Type { Method } .
// Method = "func" "(" Param ")" Name ParamList ResultList ";" .
func (p *parser) parseNamedType(n int) types.Type {
obj := p.parseTypeName()
pkg := obj.Pkg()
typ := obj.Type()
p.typeMap[n] = typ
nt, ok := typ.(*types.Named)
if !ok {
// This can happen for unsafe.Pointer, which is a TypeName holding a Basic type.
pt := p.parseType(pkg)
if pt != typ {
p.error("unexpected underlying type for non-named TypeName")
}
return typ
}
underlying := p.parseType(pkg)
if nt.Underlying() == nil {
nt.SetUnderlying(underlying.Underlying())
}
for p.tok == scanner.Ident {
// collect associated methods
p.expectKeyword("func")
p.expect('(')
receiver, _ := p.parseParam(pkg)
p.expect(')')
name := p.parseName()
params, isVariadic := p.parseParamList(pkg)
results := p.parseResultList(pkg)
p.expect(';')
sig := types.NewSignature(receiver, params, results, isVariadic)
nt.AddMethod(types.NewFunc(token.NoPos, pkg, name, sig))
}
return nt
}
示例10: BImportData
// BImportData imports a package from the serialized package data
// and returns the number of bytes consumed and a reference to the package.
// If data is obviously malformed, an error is returned but in
// general it is not recommended to call BImportData on untrusted data.
func BImportData(imports map[string]*types.Package, data []byte, path string) (int, *types.Package, error) {
p := importer{
imports: imports,
data: data,
}
p.buf = p.bufarray[:]
// read low-level encoding format
switch format := p.byte(); format {
case 'c':
// compact format - nothing to do
case 'd':
p.debugFormat = true
default:
return p.read, nil, fmt.Errorf("invalid encoding format in export data: got %q; want 'c' or 'd'", format)
}
// --- generic export data ---
if v := p.string(); v != "v0" {
return p.read, nil, fmt.Errorf("unknown version: %s", v)
}
// populate typList with predeclared "known" types
p.typList = append(p.typList, predeclared...)
// read package data
// TODO(gri) clean this up
i := p.tagOrIndex()
if i != packageTag {
panic(fmt.Sprintf("package tag expected, got %d", i))
}
name := p.string()
if s := p.string(); s != "" {
panic(fmt.Sprintf("empty path expected, got %s", s))
}
pkg := p.imports[path]
if pkg == nil {
pkg = types.NewPackage(path, name)
p.imports[path] = pkg
}
p.pkgList = append(p.pkgList, pkg)
if debug && p.pkgList[0] != pkg {
panic("imported packaged not found in pkgList[0]")
}
// read compiler-specific flags
p.string() // discard
// read consts
for i := p.int(); i > 0; i-- {
name := p.string()
typ := p.typ(nil)
val := p.value()
p.declare(types.NewConst(token.NoPos, pkg, name, typ, val))
}
// read vars
for i := p.int(); i > 0; i-- {
name := p.string()
typ := p.typ(nil)
p.declare(types.NewVar(token.NoPos, pkg, name, typ))
}
// read funcs
for i := p.int(); i > 0; i-- {
name := p.string()
sig := p.typ(nil).(*types.Signature)
p.int() // read and discard index of inlined function body
p.declare(types.NewFunc(token.NoPos, pkg, name, sig))
}
// read types
for i := p.int(); i > 0; i-- {
// name is parsed as part of named type and the
// type object is added to scope via respective
// named type
_ = p.typ(nil).(*types.Named)
}
// ignore compiler-specific import data
// complete interfaces
for _, typ := range p.typList {
if it, ok := typ.(*types.Interface); ok {
it.Complete()
}
}
// record all referenced packages as imports
list := append(([]*types.Package)(nil), p.pkgList[1:]...)
sort.Sort(byPath(list))
pkg.SetImports(list)
// package was imported completely and without errors
//.........这里部分代码省略.........
示例11: typ
// parent is the package which declared the type; parent == nil means
// the package currently imported. The parent package is needed for
// exported struct fields and interface methods which don't contain
// explicit package information in the export data.
func (p *importer) typ(parent *types.Package) types.Type {
// if the type was seen before, i is its index (>= 0)
i := p.tagOrIndex()
if i >= 0 {
return p.typList[i]
}
// otherwise, i is the type tag (< 0)
switch i {
case namedTag:
// read type object
name := p.string()
parent = p.pkg()
scope := parent.Scope()
obj := scope.Lookup(name)
// if the object doesn't exist yet, create and insert it
if obj == nil {
obj = types.NewTypeName(token.NoPos, parent, name, nil)
scope.Insert(obj)
}
if _, ok := obj.(*types.TypeName); !ok {
panic(fmt.Sprintf("pkg = %s, name = %s => %s", parent, name, obj))
}
// associate new named type with obj if it doesn't exist yet
t0 := types.NewNamed(obj.(*types.TypeName), nil, nil)
// but record the existing type, if any
t := obj.Type().(*types.Named)
p.record(t)
// read underlying type
t0.SetUnderlying(p.typ(parent))
// interfaces don't have associated methods
if _, ok := t0.Underlying().(*types.Interface); ok {
return t
}
// read associated methods
for i := p.int(); i > 0; i-- {
name := p.string()
recv, _ := p.paramList() // TODO(gri) do we need a full param list for the receiver?
params, isddd := p.paramList()
result, _ := p.paramList()
p.int() // read and discard index of inlined function body
sig := types.NewSignature(recv.At(0), params, result, isddd)
t0.AddMethod(types.NewFunc(token.NoPos, parent, name, sig))
}
return t
case arrayTag:
t := new(types.Array)
p.record(t)
n := p.int64()
*t = *types.NewArray(p.typ(parent), n)
return t
case sliceTag:
t := new(types.Slice)
p.record(t)
*t = *types.NewSlice(p.typ(parent))
return t
case dddTag:
t := new(dddSlice)
p.record(t)
t.elem = p.typ(parent)
return t
case structTag:
t := new(types.Struct)
p.record(t)
n := p.int()
fields := make([]*types.Var, n)
tags := make([]string, n)
for i := range fields {
fields[i] = p.field(parent)
tags[i] = p.string()
}
*t = *types.NewStruct(fields, tags)
return t
case pointerTag:
t := new(types.Pointer)
p.record(t)
*t = *types.NewPointer(p.typ(parent))
return t
//.........这里部分代码省略.........
示例12: parseFuncDecl
// FuncDecl = "func" ExportedName Func .
//
func (p *parser) parseFuncDecl() {
// "func" already consumed
pkg, name := p.parseExportedName()
typ := p.parseFunc(nil)
pkg.Scope().Insert(types.NewFunc(token.NoPos, pkg, name, typ))
}
示例13: typ
// parent is the package which declared the type; parent == nil means
// the package currently imported. The parent package is needed for
// exported struct fields and interface methods which don't contain
// explicit package information in the export data.
func (p *importer) typ(parent *types.Package) types.Type {
// if the type was seen before, i is its index (>= 0)
i := p.tagOrIndex()
if i >= 0 {
return p.typList[i]
}
// otherwise, i is the type tag (< 0)
switch i {
case namedTag:
// read type object
pos := p.pos()
parent, name := p.qualifiedName()
scope := parent.Scope()
obj := scope.Lookup(name)
// if the object doesn't exist yet, create and insert it
if obj == nil {
obj = types.NewTypeName(pos, parent, name, nil)
scope.Insert(obj)
}
if _, ok := obj.(*types.TypeName); !ok {
errorf("pkg = %s, name = %s => %s", parent, name, obj)
}
// associate new named type with obj if it doesn't exist yet
t0 := types.NewNamed(obj.(*types.TypeName), nil, nil)
// but record the existing type, if any
t := obj.Type().(*types.Named)
p.record(t)
// read underlying type
t0.SetUnderlying(p.typ(parent))
// interfaces don't have associated methods
if types.IsInterface(t0) {
return t
}
// read associated methods
for i := p.int(); i > 0; i-- {
// TODO(gri) replace this with something closer to fieldName
pos := p.pos()
name := p.string()
if !exported(name) {
p.pkg()
}
recv, _ := p.paramList() // TODO(gri) do we need a full param list for the receiver?
params, isddd := p.paramList()
result, _ := p.paramList()
p.int() // go:nointerface pragma - discarded
sig := types.NewSignature(recv.At(0), params, result, isddd)
t0.AddMethod(types.NewFunc(pos, parent, name, sig))
}
return t
case arrayTag:
t := new(types.Array)
if p.trackAllTypes {
p.record(t)
}
n := p.int64()
*t = *types.NewArray(p.typ(parent), n)
return t
case sliceTag:
t := new(types.Slice)
if p.trackAllTypes {
p.record(t)
}
*t = *types.NewSlice(p.typ(parent))
return t
case dddTag:
t := new(dddSlice)
if p.trackAllTypes {
p.record(t)
}
t.elem = p.typ(parent)
return t
case structTag:
t := new(types.Struct)
if p.trackAllTypes {
p.record(t)
}
*t = *types.NewStruct(p.fieldList(parent))
//.........这里部分代码省略.........
示例14: typ
func (p *importer) typ() types.Type {
// if the type was seen before, i is its index (>= 0)
i := p.int()
if i >= 0 {
return p.typList[i]
}
// otherwise, i is the type tag (< 0)
switch i {
case arrayTag:
t := new(types.Array)
p.record(t)
n := p.int64()
*t = *types.NewArray(p.typ(), n)
return t
case sliceTag:
t := new(types.Slice)
p.record(t)
*t = *types.NewSlice(p.typ())
return t
case structTag:
t := new(types.Struct)
p.record(t)
n := p.int()
fields := make([]*types.Var, n)
tags := make([]string, n)
for i := range fields {
fields[i] = p.field()
tags[i] = p.string()
}
*t = *types.NewStruct(fields, tags)
return t
case pointerTag:
t := new(types.Pointer)
p.record(t)
*t = *types.NewPointer(p.typ())
return t
case signatureTag:
t := new(types.Signature)
p.record(t)
*t = *p.signature()
return t
case interfaceTag:
// Create a dummy entry in the type list. This is safe because we
// cannot expect the interface type to appear in a cycle, as any
// such cycle must contain a named type which would have been
// first defined earlier.
n := len(p.typList)
p.record(nil)
// read embedded interfaces
embeddeds := make([]*types.Named, p.int())
for i := range embeddeds {
embeddeds[i] = p.typ().(*types.Named)
}
// read methods
methods := make([]*types.Func, p.int())
for i := range methods {
pkg, name := p.qualifiedName()
methods[i] = types.NewFunc(token.NoPos, pkg, name, p.typ().(*types.Signature))
}
t := types.NewInterface(methods, embeddeds)
p.typList[n] = t
return t
case mapTag:
t := new(types.Map)
p.record(t)
*t = *types.NewMap(p.typ(), p.typ())
return t
case chanTag:
t := new(types.Chan)
p.record(t)
*t = *types.NewChan(types.ChanDir(p.int()), p.typ())
return t
case namedTag:
// read type object
name := p.string()
pkg := p.pkg()
scope := pkg.Scope()
obj := scope.Lookup(name)
// if the object doesn't exist yet, create and insert it
if obj == nil {
//.........这里部分代码省略.........
示例15: CreateTestMainPackage
// CreateTestMainPackage creates and returns a synthetic "main"
// package that runs all the tests of the supplied packages, similar
// to the one that would be created by the 'go test' tool.
//
// It returns nil if the program contains no tests.
//
func (prog *Program) CreateTestMainPackage(pkgs ...*Package) *Package {
pkgs, tests, benchmarks, examples := FindTests(pkgs)
if len(pkgs) == 0 {
return nil
}
testmain := &Package{
Prog: prog,
Members: make(map[string]Member),
values: make(map[types.Object]Value),
Pkg: types.NewPackage("test$main", "main"),
}
// Build package's init function.
init := &Function{
name: "init",
Signature: new(types.Signature),
Synthetic: "package initializer",
Pkg: testmain,
Prog: prog,
}
init.startBody()
if testMainStartBodyHook != nil {
testMainStartBodyHook(init)
}
// Initialize packages to test.
var pkgpaths []string
for _, pkg := range pkgs {
var v Call
v.Call.Value = pkg.init
v.setType(types.NewTuple())
init.emit(&v)
pkgpaths = append(pkgpaths, pkg.Pkg.Path())
}
sort.Strings(pkgpaths)
init.emit(new(Return))
init.finishBody()
testmain.init = init
testmain.Pkg.MarkComplete()
testmain.Members[init.name] = init
// For debugging convenience, define an unexported const
// that enumerates the packages.
packagesConst := types.NewConst(token.NoPos, testmain.Pkg, "packages", tString,
exact.MakeString(strings.Join(pkgpaths, " ")))
memberFromObject(testmain, packagesConst, nil)
// Create main *types.Func and *ssa.Function
mainFunc := types.NewFunc(token.NoPos, testmain.Pkg, "main", new(types.Signature))
memberFromObject(testmain, mainFunc, nil)
main := testmain.Func("main")
main.Synthetic = "test main function"
main.startBody()
if testMainStartBodyHook != nil {
testMainStartBodyHook(main)
}
if testingPkg := prog.ImportedPackage("testing"); testingPkg != nil {
testingMain := testingPkg.Func("Main")
testingMainParams := testingMain.Signature.Params()
// The generated code is as if compiled from this:
//
// func main() {
// match := func(_, _ string) (bool, error) { return true, nil }
// tests := []testing.InternalTest{{"TestFoo", TestFoo}, ...}
// benchmarks := []testing.InternalBenchmark{...}
// examples := []testing.InternalExample{...}
// testing.Main(match, tests, benchmarks, examples)
// }
matcher := &Function{
name: "matcher",
Signature: testingMainParams.At(0).Type().(*types.Signature),
Synthetic: "test matcher predicate",
parent: main,
Pkg: testmain,
Prog: prog,
}
main.AnonFuncs = append(main.AnonFuncs, matcher)
matcher.startBody()
matcher.emit(&Return{Results: []Value{vTrue, nilConst(types.Universe.Lookup("error").Type())}})
matcher.finishBody()
// Emit call: testing.Main(matcher, tests, benchmarks, examples).
var c Call
c.Call.Value = testingMain
c.Call.Args = []Value{
matcher,
//.........这里部分代码省略.........