本文整理汇总了Golang中go/types.NewInterface函数的典型用法代码示例。如果您正苦于以下问题:Golang NewInterface函数的具体用法?Golang NewInterface怎么用?Golang NewInterface使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewInterface函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: initReflect
func initReflect(i *interpreter) {
i.reflectPackage = &ssa.Package{
Prog: i.prog,
Pkg: reflectTypesPackage,
Members: make(map[string]ssa.Member),
}
// Clobber the type-checker's notion of reflect.Value's
// underlying type so that it more closely matches the fake one
// (at least in the number of fields---we lie about the type of
// the rtype field).
//
// We must ensure that calls to (ssa.Value).Type() return the
// fake type so that correct "shape" is used when allocating
// variables, making zero values, loading, and storing.
//
// TODO(adonovan): obviously this is a hack. We need a cleaner
// way to fake the reflect package (almost---DeepEqual is fine).
// One approach would be not to even load its source code, but
// provide fake source files. This would guarantee that no bad
// information leaks into other packages.
if r := i.prog.ImportedPackage("reflect"); r != nil {
rV := r.Pkg.Scope().Lookup("Value").Type().(*types.Named)
// delete bodies of the old methods
mset := i.prog.MethodSets.MethodSet(rV)
for j := 0; j < mset.Len(); j++ {
i.prog.MethodValue(mset.At(j)).Blocks = nil
}
tEface := types.NewInterface(nil, nil).Complete()
rV.SetUnderlying(types.NewStruct([]*types.Var{
types.NewField(token.NoPos, r.Pkg, "t", tEface, false), // a lie
types.NewField(token.NoPos, r.Pkg, "v", tEface, false),
}, nil))
}
i.rtypeMethods = methodSet{
"Bits": newMethod(i.reflectPackage, rtypeType, "Bits"),
"Elem": newMethod(i.reflectPackage, rtypeType, "Elem"),
"Field": newMethod(i.reflectPackage, rtypeType, "Field"),
"In": newMethod(i.reflectPackage, rtypeType, "In"),
"Kind": newMethod(i.reflectPackage, rtypeType, "Kind"),
"NumField": newMethod(i.reflectPackage, rtypeType, "NumField"),
"NumIn": newMethod(i.reflectPackage, rtypeType, "NumIn"),
"NumMethod": newMethod(i.reflectPackage, rtypeType, "NumMethod"),
"NumOut": newMethod(i.reflectPackage, rtypeType, "NumOut"),
"Out": newMethod(i.reflectPackage, rtypeType, "Out"),
"Size": newMethod(i.reflectPackage, rtypeType, "Size"),
"String": newMethod(i.reflectPackage, rtypeType, "String"),
}
i.errorMethods = methodSet{
"Error": newMethod(i.reflectPackage, errorType, "Error"),
}
}
示例2: 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()
}
示例3: parseInterfaceType
// InterfaceType = "interface" "{" { ("?" Type | Func) ";" } "}" .
func (p *parser) parseInterfaceType(pkg *types.Package) types.Type {
p.expectKeyword("interface")
var methods []*types.Func
var typs []*types.Named
p.expect('{')
for p.tok != '}' && p.tok != scanner.EOF {
if p.tok == '?' {
p.next()
typs = append(typs, p.parseType(pkg).(*types.Named))
} else {
method := p.parseFunc(pkg)
methods = append(methods, method)
}
p.expect(';')
}
p.expect('}')
return types.NewInterface(methods, typs)
}
示例4: typ
//.........这里部分代码省略.........
*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
case signatureTag:
t := new(types.Signature)
p.record(t)
params, isddd := p.paramList()
result, _ := p.paramList()
*t = *types.NewSignature(nil, params, result, isddd)
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)
// no embedded interfaces with gc compiler
if p.int() != 0 {
panic("unexpected embedded interface")
}
// read methods
methods := make([]*types.Func, p.int())
for i := range methods {
pkg, name := p.fieldName(parent)
params, isddd := p.paramList()
result, _ := p.paramList()
sig := types.NewSignature(nil, params, result, isddd)
methods[i] = types.NewFunc(token.NoPos, pkg, name, sig)
}
t := types.NewInterface(methods, nil)
p.typList[n] = t
return t
case mapTag:
t := new(types.Map)
p.record(t)
key := p.typ(parent)
val := p.typ(parent)
*t = *types.NewMap(key, val)
return t
case chanTag:
t := new(types.Chan)
p.record(t)
var dir types.ChanDir
// tag values must match the constants in cmd/compile/internal/gc/go.go
switch d := p.int(); d {
case 1 /* Crecv */ :
dir = types.RecvOnly
case 2 /* Csend */ :
dir = types.SendOnly
case 3 /* Cboth */ :
dir = types.SendRecv
default:
panic(fmt.Sprintf("unexpected channel dir %d", d))
}
val := p.typ(parent)
*t = *types.NewChan(dir, val)
return t
default:
panic(fmt.Sprintf("unexpected type tag %d", i))
}
}
示例5: nextNode
// TODO(adonovan): move the constraint definitions and the store() etc
// functions which add them (and are also used by the solver) into a
// new file, constraints.go.
import (
"fmt"
"go/token"
"go/types"
"golang.org/x/tools/go/callgraph"
"golang.org/x/tools/go/ssa"
)
var (
tEface = types.NewInterface(nil, nil).Complete()
tInvalid = types.Typ[types.Invalid]
tUnsafePtr = types.Typ[types.UnsafePointer]
)
// ---------- Node creation ----------
// nextNode returns the index of the next unused node.
func (a *analysis) nextNode() nodeid {
return nodeid(len(a.nodes))
}
// addNodes creates nodes for all scalar elements in type typ, and
// returns the id of the first one, or zero if the type was
// analytically uninteresting.
//
示例6: translateBuiltin
func (c *funcContext) translateBuiltin(name string, sig *types.Signature, args []ast.Expr, ellipsis bool) *expression {
switch name {
case "new":
t := sig.Results().At(0).Type().(*types.Pointer)
if c.p.Pkg.Path() == "syscall" && types.Identical(t.Elem().Underlying(), types.Typ[types.Uintptr]) {
return c.formatExpr("new Uint8Array(8)")
}
switch t.Elem().Underlying().(type) {
case *types.Struct, *types.Array:
return c.formatExpr("%e", c.zeroValue(t.Elem()))
default:
return c.formatExpr("$newDataPointer(%e, %s)", c.zeroValue(t.Elem()), c.typeName(t))
}
case "make":
switch argType := c.p.TypeOf(args[0]).Underlying().(type) {
case *types.Slice:
t := c.typeName(c.p.TypeOf(args[0]))
if len(args) == 3 {
return c.formatExpr("$makeSlice(%s, %f, %f)", t, args[1], args[2])
}
return c.formatExpr("$makeSlice(%s, %f)", t, args[1])
case *types.Map:
if len(args) == 2 && c.p.Types[args[1]].Value == nil {
return c.formatExpr(`((%1f < 0 || %1f > 2147483647) ? $throwRuntimeError("makemap: size out of range") : {})`, args[1])
}
return c.formatExpr("{}")
case *types.Chan:
length := "0"
if len(args) == 2 {
length = c.formatExpr("%f", args[1]).String()
}
return c.formatExpr("new $Chan(%s, %s)", c.typeName(c.p.TypeOf(args[0]).Underlying().(*types.Chan).Elem()), length)
default:
panic(fmt.Sprintf("Unhandled make type: %T\n", argType))
}
case "len":
switch argType := c.p.TypeOf(args[0]).Underlying().(type) {
case *types.Basic:
return c.formatExpr("%e.length", args[0])
case *types.Slice:
return c.formatExpr("%e.$length", args[0])
case *types.Pointer:
return c.formatExpr("(%e, %d)", args[0], argType.Elem().(*types.Array).Len())
case *types.Map:
return c.formatExpr("$keys(%e).length", args[0])
case *types.Chan:
return c.formatExpr("%e.$buffer.length", args[0])
// length of array is constant
default:
panic(fmt.Sprintf("Unhandled len type: %T\n", argType))
}
case "cap":
switch argType := c.p.TypeOf(args[0]).Underlying().(type) {
case *types.Slice, *types.Chan:
return c.formatExpr("%e.$capacity", args[0])
case *types.Pointer:
return c.formatExpr("(%e, %d)", args[0], argType.Elem().(*types.Array).Len())
// capacity of array is constant
default:
panic(fmt.Sprintf("Unhandled cap type: %T\n", argType))
}
case "panic":
return c.formatExpr("$panic(%s)", c.translateImplicitConversion(args[0], types.NewInterface(nil, nil)))
case "append":
if ellipsis || len(args) == 1 {
argStr := c.translateArgs(sig, args, ellipsis, false)
return c.formatExpr("$appendSlice(%s, %s)", argStr[0], argStr[1])
}
sliceType := sig.Results().At(0).Type().Underlying().(*types.Slice)
return c.formatExpr("$append(%e, %s)", args[0], strings.Join(c.translateExprSlice(args[1:], sliceType.Elem()), ", "))
case "delete":
keyType := c.p.TypeOf(args[0]).Underlying().(*types.Map).Key()
return c.formatExpr(`delete %e[%s.keyFor(%s)]`, args[0], c.typeName(keyType), c.translateImplicitConversion(args[1], keyType))
case "copy":
if basic, isBasic := c.p.TypeOf(args[1]).Underlying().(*types.Basic); isBasic && isString(basic) {
return c.formatExpr("$copyString(%e, %e)", args[0], args[1])
}
return c.formatExpr("$copySlice(%e, %e)", args[0], args[1])
case "print", "println":
return c.formatExpr("console.log(%s)", strings.Join(c.translateExprSlice(args, nil), ", "))
case "complex":
argStr := c.translateArgs(sig, args, ellipsis, false)
return c.formatExpr("new %s(%s, %s)", c.typeName(sig.Results().At(0).Type()), argStr[0], argStr[1])
case "real":
return c.formatExpr("%e.$real", args[0])
case "imag":
return c.formatExpr("%e.$imag", args[0])
case "recover":
return c.formatExpr("$recover()")
case "close":
return c.formatExpr(`$close(%e)`, args[0])
default:
panic(fmt.Sprintf("Unhandled builtin: %s\n", name))
}
}
示例7: translateExpr
//.........这里部分代码省略.........
objVar := c.newVariable("obj")
return c.formatExpr("(%s = %s, %s.%s.apply(%s, %s))", objVar, recv, objVar, id, objVar, externalizeExpr(e.Args[1]))
}
return c.formatExpr("%s(%s)", globalRef(id), externalizeArgs(e.Args[1:]))
}
if e.Ellipsis.IsValid() {
objVar := c.newVariable("obj")
return c.formatExpr("(%s = %s, %s[$externalize(%e, $String)].apply(%s, %s))", objVar, recv, objVar, e.Args[0], objVar, externalizeExpr(e.Args[1]))
}
return c.formatExpr("%s[$externalize(%e, $String)](%s)", recv, e.Args[0], externalizeArgs(e.Args[1:]))
case "Invoke":
if e.Ellipsis.IsValid() {
return c.formatExpr("%s.apply(undefined, %s)", recv, externalizeExpr(e.Args[0]))
}
return c.formatExpr("%s(%s)", recv, externalizeArgs(e.Args))
case "New":
if e.Ellipsis.IsValid() {
return c.formatExpr("new ($global.Function.prototype.bind.apply(%s, [undefined].concat(%s)))", recv, externalizeExpr(e.Args[0]))
}
return c.formatExpr("new (%s)(%s)", recv, externalizeArgs(e.Args))
case "Bool":
return c.internalize(recv, types.Typ[types.Bool])
case "String":
return c.internalize(recv, types.Typ[types.String])
case "Int":
return c.internalize(recv, types.Typ[types.Int])
case "Int64":
return c.internalize(recv, types.Typ[types.Int64])
case "Uint64":
return c.internalize(recv, types.Typ[types.Uint64])
case "Float":
return c.internalize(recv, types.Typ[types.Float64])
case "Interface":
return c.internalize(recv, types.NewInterface(nil, nil))
case "Unsafe":
return recv
default:
panic("Invalid js package object: " + sel.Obj().Name())
}
}
methodName := sel.Obj().Name()
if reservedKeywords[methodName] {
methodName += "$"
}
return c.translateCall(e, sig, c.formatExpr("%s.%s", recv, methodName))
case types.FieldVal:
fields, jsTag := c.translateSelection(sel, f.Pos())
if jsTag != "" {
call := c.formatExpr("%e.%s.%s(%s)", f.X, strings.Join(fields, "."), jsTag, externalizeArgs(e.Args))
switch sig.Results().Len() {
case 0:
return call
case 1:
return c.internalize(call, sig.Results().At(0).Type())
default:
c.p.errList = append(c.p.errList, types.Error{Fset: c.p.fileSet, Pos: f.Pos(), Msg: "field with js tag can not have func type with multiple results"})
}
}
return c.translateCall(e, sig, c.formatExpr("%e.%s", f.X, strings.Join(fields, ".")))
case types.MethodExpr:
return c.translateCall(e, sig, c.translateExpr(f))
default:
示例8: translateStmt
//.........这里部分代码省略.........
o := c.p.Defs[spec.(*ast.TypeSpec).Name].(*types.TypeName)
c.p.typeNames = append(c.p.typeNames, o)
c.p.objectNames[o] = c.newVariableWithLevel(o.Name(), true)
c.p.dependencies[o] = true
}
case token.CONST:
// skip, constants are inlined
}
case *ast.ExprStmt:
expr := c.translateExpr(s.X)
if expr != nil && expr.String() != "" {
c.Printf("%s;", expr)
}
case *ast.LabeledStmt:
label := c.p.Defs[s.Label].(*types.Label)
if c.GotoLabel[label] {
c.PrintCond(false, s.Label.Name+":", fmt.Sprintf("case %d:", c.labelCase(label)))
}
c.translateStmt(s.Stmt, label)
case *ast.GoStmt:
c.Printf("$go(%s, [%s]);", c.translateExpr(s.Call.Fun), strings.Join(c.translateArgs(c.p.TypeOf(s.Call.Fun).Underlying().(*types.Signature), s.Call.Args, s.Call.Ellipsis.IsValid(), true), ", "))
case *ast.SendStmt:
chanType := c.p.TypeOf(s.Chan).Underlying().(*types.Chan)
call := &ast.CallExpr{
Fun: c.newIdent("$send", types.NewSignature(nil, types.NewTuple(types.NewVar(0, nil, "", chanType), types.NewVar(0, nil, "", chanType.Elem())), nil, false)),
Args: []ast.Expr{s.Chan, c.newIdent(c.translateImplicitConversionWithCloning(s.Value, chanType.Elem()).String(), chanType.Elem())},
}
c.Blocking[call] = true
c.translateStmt(&ast.ExprStmt{X: call}, label)
case *ast.SelectStmt:
selectionVar := c.newVariable("_selection")
var channels []string
var caseClauses []*ast.CaseClause
flattened := false
hasDefault := false
for i, cc := range s.Body.List {
clause := cc.(*ast.CommClause)
switch comm := clause.Comm.(type) {
case nil:
channels = append(channels, "[]")
hasDefault = true
case *ast.ExprStmt:
channels = append(channels, c.formatExpr("[%e]", astutil.RemoveParens(comm.X).(*ast.UnaryExpr).X).String())
case *ast.AssignStmt:
channels = append(channels, c.formatExpr("[%e]", astutil.RemoveParens(comm.Rhs[0]).(*ast.UnaryExpr).X).String())
case *ast.SendStmt:
chanType := c.p.TypeOf(comm.Chan).Underlying().(*types.Chan)
channels = append(channels, c.formatExpr("[%e, %s]", comm.Chan, c.translateImplicitConversionWithCloning(comm.Value, chanType.Elem())).String())
default:
panic(fmt.Sprintf("unhandled: %T", comm))
}
indexLit := &ast.BasicLit{Kind: token.INT}
c.p.Types[indexLit] = types.TypeAndValue{Type: types.Typ[types.Int], Value: constant.MakeInt64(int64(i))}
var bodyPrefix []ast.Stmt
if assign, ok := clause.Comm.(*ast.AssignStmt); ok {
switch rhsType := c.p.TypeOf(assign.Rhs[0]).(type) {
case *types.Tuple:
bodyPrefix = []ast.Stmt{&ast.AssignStmt{Lhs: assign.Lhs, Rhs: []ast.Expr{c.newIdent(selectionVar+"[1]", rhsType)}, Tok: assign.Tok}}
default:
bodyPrefix = []ast.Stmt{&ast.AssignStmt{Lhs: assign.Lhs, Rhs: []ast.Expr{c.newIdent(selectionVar+"[1][0]", rhsType)}, Tok: assign.Tok}}
}
}
caseClauses = append(caseClauses, &ast.CaseClause{
List: []ast.Expr{indexLit},
Body: append(bodyPrefix, clause.Body...),
})
flattened = flattened || c.Flattened[clause]
}
selectCall := c.setType(&ast.CallExpr{
Fun: c.newIdent("$select", types.NewSignature(nil, types.NewTuple(types.NewVar(0, nil, "", types.NewInterface(nil, nil))), types.NewTuple(types.NewVar(0, nil, "", types.Typ[types.Int])), false)),
Args: []ast.Expr{c.newIdent(fmt.Sprintf("[%s]", strings.Join(channels, ", ")), types.NewInterface(nil, nil))},
}, types.Typ[types.Int])
c.Blocking[selectCall] = !hasDefault
c.Printf("%s = %s;", selectionVar, c.translateExpr(selectCall))
if len(caseClauses) != 0 {
translateCond := func(cond ast.Expr) *expression {
return c.formatExpr("%s[0] === %e", selectionVar, cond)
}
c.translateBranchingStmt(caseClauses, nil, true, translateCond, label, flattened)
}
case *ast.EmptyStmt:
// skip
default:
panic(fmt.Sprintf("Unhandled statement: %T\n", s))
}
}
示例9: typ
//.........这里部分代码省略.........
*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))
return t
case pointerTag:
t := new(types.Pointer)
if p.trackAllTypes {
p.record(t)
}
*t = *types.NewPointer(p.typ(parent))
return t
case signatureTag:
t := new(types.Signature)
if p.trackAllTypes {
p.record(t)
}
params, isddd := p.paramList()
result, _ := p.paramList()
*t = *types.NewSignature(nil, params, result, isddd)
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)
if p.trackAllTypes {
p.record(nil)
}
// no embedded interfaces with gc compiler
if p.int() != 0 {
errorf("unexpected embedded interface")
}
t := types.NewInterface(p.methodList(parent), nil)
if p.trackAllTypes {
p.typList[n] = t
}
return t
case mapTag:
t := new(types.Map)
if p.trackAllTypes {
p.record(t)
}
key := p.typ(parent)
val := p.typ(parent)
*t = *types.NewMap(key, val)
return t
case chanTag:
t := new(types.Chan)
if p.trackAllTypes {
p.record(t)
}
var dir types.ChanDir
// tag values must match the constants in cmd/compile/internal/gc/go.go
switch d := p.int(); d {
case 1 /* Crecv */ :
dir = types.RecvOnly
case 2 /* Csend */ :
dir = types.SendOnly
case 3 /* Cboth */ :
dir = types.SendRecv
default:
errorf("unexpected channel dir %d", d)
}
val := p.typ(parent)
*t = *types.NewChan(dir, val)
return t
default:
errorf("unexpected type tag %d", i) // panics
panic("unreachable")
}
}
示例10: 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 {
//.........这里部分代码省略.........