本文整理汇总了Golang中code/google/com/p/go/tools/go/types.NewVar函数的典型用法代码示例。如果您正苦于以下问题:Golang NewVar函数的具体用法?Golang NewVar怎么用?Golang NewVar使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewVar函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: descriptorInterface
func (m *TypeMap) descriptorInterface(t *types.Interface, name string) TypeDebugDescriptor {
ifaceStruct := types.NewStruct([]*types.Var{
types.NewVar(0, nil, "type", types.NewPointer(types.Typ[types.Uint8])),
types.NewVar(0, nil, "data", types.NewPointer(types.Typ[types.Uint8])),
}, nil)
return m.typeDebugDescriptor(ifaceStruct, name)
}
开发者ID:minux,项目名称:llgo,代码行数:7,代码来源:types.go
示例2: descriptorSlice
func (m *TypeMap) descriptorSlice(t *types.Slice, name string) TypeDebugDescriptor {
sliceStruct := types.NewStruct([]*types.Var{
types.NewVar(0, nil, "ptr", types.NewPointer(t.Elem())),
types.NewVar(0, nil, "len", types.Typ[types.Int]),
types.NewVar(0, nil, "cap", types.Typ[types.Int]),
}, nil)
return m.typeDebugDescriptor(sliceStruct, name)
}
开发者ID:minux,项目名称:llgo,代码行数:8,代码来源:types.go
示例3: loadStruct
func (c *PkgContext) loadStruct(array, target string, s *types.Struct) {
view := c.newVariable("_view")
c.Printf("%s = new DataView(%s.buffer, %s.byteOffset);", view, array, array)
var fields []*types.Var
var collectFields func(s *types.Struct, path string)
collectFields = func(s *types.Struct, path string) {
for i := 0; i < s.NumFields(); i++ {
field := s.Field(i)
if fs, isStruct := field.Type().Underlying().(*types.Struct); isStruct {
collectFields(fs, path+"."+field.Name())
continue
}
fields = append(fields, types.NewVar(0, nil, path+"."+field.Name(), field.Type()))
}
}
collectFields(s, target)
offsets := sizes32.Offsetsof(fields)
for i, field := range fields {
switch t := field.Type().Underlying().(type) {
case *types.Basic:
if t.Info()&types.IsNumeric != 0 {
if is64Bit(t) {
c.Printf("%s = new %s(%s.getUint32(%d, true), %s.getUint32(%d, true));", field.Name(), c.typeName(field.Type()), view, offsets[i]+4, view, offsets[i])
continue
}
c.Printf("%s = %s.get%s(%d, true);", field.Name(), view, toJavaScriptType(t), offsets[i])
}
continue
case *types.Array:
c.Printf("%s = new %s(%s.buffer, Go$min(%s.byteOffset + %d, %s.buffer.byteLength));", field.Name(), toArrayType(t.Elem()), array, array, offsets[i], array)
continue
}
c.Printf("// skipped: %s %s", field.Name(), field.Type().String())
}
}
开发者ID:umisama,项目名称:gopherjs,代码行数:35,代码来源:expressions.go
示例4: loadStruct
func (c *funcContext) loadStruct(array, target string, s *types.Struct) string {
view := c.newVariable("_view")
code := fmt.Sprintf("%s = new DataView(%s.buffer, %s.byteOffset)", view, array, array)
var fields []*types.Var
var collectFields func(s *types.Struct, path string)
collectFields = func(s *types.Struct, path string) {
for i := 0; i < s.NumFields(); i++ {
field := s.Field(i)
if fs, isStruct := field.Type().Underlying().(*types.Struct); isStruct {
collectFields(fs, path+"."+fieldName(s, i))
continue
}
fields = append(fields, types.NewVar(0, nil, path+"."+fieldName(s, i), field.Type()))
}
}
collectFields(s, target)
offsets := sizes32.Offsetsof(fields)
for i, field := range fields {
switch t := field.Type().Underlying().(type) {
case *types.Basic:
if t.Info()&types.IsNumeric != 0 {
if is64Bit(t) {
code += fmt.Sprintf(", %s = new %s(%s.getUint32(%d, true), %s.getUint32(%d, true))", field.Name(), c.typeName(field.Type()), view, offsets[i]+4, view, offsets[i])
break
}
code += fmt.Sprintf(", %s = %s.get%s(%d, true)", field.Name(), view, toJavaScriptType(t), offsets[i])
}
case *types.Array:
code += fmt.Sprintf(`, %s = new ($nativeArray("%s"))(%s.buffer, $min(%s.byteOffset + %d, %s.buffer.byteLength))`, field.Name(), typeKind(t.Elem()), array, array, offsets[i], array)
}
}
return code
}
开发者ID:nvdnkpr,项目名称:gopherjs,代码行数:33,代码来源:expressions.go
示例5: newIdent
func (c *PkgContext) newIdent(name string, t types.Type) *ast.Ident {
ident := ast.NewIdent(name)
c.info.Types[ident] = t
obj := types.NewVar(0, c.pkg, name, t)
c.info.Objects[ident] = obj
c.objectVars[obj] = name
return ident
}
开发者ID:umisama,项目名称:gopherjs,代码行数:8,代码来源:package.go
示例6: newIdent
func (c *funcContext) newIdent(name string, t types.Type) *ast.Ident {
ident := ast.NewIdent(name)
c.setType(ident, t)
obj := types.NewVar(0, c.p.pkg, name, t)
c.p.info.Uses[ident] = obj
c.p.objectVars[obj] = name
return ident
}
开发者ID:nvdnkpr,项目名称:gopherjs,代码行数:8,代码来源:utils.go
示例7: promoteMethod
// promoteMethod promotes a named type's method to another type
// which has embedded the named type.
func (c *compiler) promoteMethod(m *types.Func, recv types.Type, indices []int) types.Object {
var pkg *types.Package
if recv, ok := recv.(*types.Named); ok {
pkg = c.objectdata[recv.Obj()].Package
}
recvvar := types.NewVar(pkg, "", recv)
sig := m.Type().(*types.Signature)
sig = types.NewSignature(recvvar, sig.Params(), sig.Results(), sig.IsVariadic())
f := &synthFunc{pkg: pkg, name: m.Name(), typ: sig}
ident := ast.NewIdent(f.Name())
var isptr bool
if ptr, ok := recv.(*types.Pointer); ok {
isptr = true
recv = ptr.Elem()
}
c.objects[ident] = f
c.objectdata[f] = &ObjectData{Ident: ident, Package: pkg}
if pkg == nil || pkg == c.pkg {
if currblock := c.builder.GetInsertBlock(); !currblock.IsNil() {
defer c.builder.SetInsertPointAtEnd(currblock)
}
llvmfn := c.Resolve(ident).LLVMValue()
llvmfn = c.builder.CreateExtractValue(llvmfn, 0, "")
llvmfn.SetLinkage(llvm.LinkOnceODRLinkage)
entry := llvm.AddBasicBlock(llvmfn, "entry")
c.builder.SetInsertPointAtEnd(entry)
realfn := c.Resolve(c.objectdata[m].Ident).LLVMValue()
realfn = c.builder.CreateExtractValue(realfn, 0, "")
args := llvmfn.Params()
recvarg := args[0]
if !isptr {
ptr := c.builder.CreateAlloca(recvarg.Type(), "")
c.builder.CreateStore(recvarg, ptr)
recvarg = ptr
}
for _, i := range indices {
if i == -1 {
recvarg = c.builder.CreateLoad(recvarg, "")
} else {
recvarg = c.builder.CreateStructGEP(recvarg, i, "")
}
}
args[0] = recvarg
result := c.builder.CreateCall(realfn, args, "")
if sig.Results().Len() == 0 {
c.builder.CreateRetVoid()
} else {
c.builder.CreateRet(result)
}
}
return f
}
开发者ID:hzmangel,项目名称:llgo,代码行数:60,代码来源:functions.go
示例8: descriptorBasic
func (m *TypeMap) descriptorBasic(t *types.Basic, name string) TypeDebugDescriptor {
switch t.Kind() {
case types.String:
return m.descriptorStruct(types.NewStruct([]*types.Var{
types.NewVar(0, nil, "ptr", types.NewPointer(types.Typ[types.Uint8])),
types.NewVar(0, nil, "len", types.Typ[types.Int]),
}, nil), name)
case types.UnsafePointer:
return &BasicTypeDescriptor{
TypeDescriptorCommon: TypeDescriptorCommon{
Name: name,
Size: uint64(m.Sizes.Sizeof(t) * 8),
Alignment: uint64(m.Sizes.Alignof(t) * 8),
},
TypeEncoding: DW_ATE_unsigned,
}
default:
bt := &BasicTypeDescriptor{
TypeDescriptorCommon: TypeDescriptorCommon{
Name: t.String(),
Size: uint64(m.Sizes.Sizeof(t) * 8),
Alignment: uint64(m.Sizes.Alignof(t) * 8),
},
}
switch bi := t.Info(); {
case bi&types.IsBoolean != 0:
bt.TypeEncoding = DW_ATE_boolean
case bi&types.IsUnsigned != 0:
bt.TypeEncoding = DW_ATE_unsigned
case bi&types.IsInteger != 0:
bt.TypeEncoding = DW_ATE_signed
case bi&types.IsFloat != 0:
bt.TypeEncoding = DW_ATE_float
case bi&types.IsComplex != 0:
bt.TypeEncoding = DW_ATE_imaginary_float
case bi&types.IsUnsigned != 0:
bt.TypeEncoding = DW_ATE_unsigned
default:
panic(fmt.Sprintf("unhandled: %#v", t))
}
return bt
}
}
开发者ID:minux,项目名称:llgo,代码行数:43,代码来源:types.go
示例9: newMethod
// newMethod creates a new method of the specified name, package and receiver type.
func newMethod(pkg *ssa.Package, recvType types.Type, name string) *ssa.Function {
// TODO(adonovan): fix: hack: currently the only part of Signature
// that is needed is the "pointerness" of Recv.Type, and for
// now, we'll set it to always be false since we're only
// concerned with rtype. Encapsulate this better.
sig := types.NewSignature(nil, types.NewVar(token.NoPos, nil, "recv", recvType), nil, nil, false)
fn := pkg.Prog.NewFunction(name, sig, "fake reflect method")
fn.Pkg = pkg
return fn
}
开发者ID:4honor,项目名称:obdi,代码行数:11,代码来源:reflect.go
示例10: newMethod
// newMethod creates a new method of the specified name, package and receiver type.
func newMethod(pkg *ssa.Package, recvType types.Type, name string) *ssa.Function {
fn := &ssa.Function{
Name_: name,
Pkg: pkg,
Prog: pkg.Prog,
}
// TODO(adonovan): fix: hack: currently the only part of Signature
// that is needed is the "pointerness" of Recv.Type, and for
// now, we'll set it to always be false since we're only
// concerned with rtype. Encapsulate this better.
fn.Signature = types.NewSignature(types.NewVar(nil, "recv", recvType), nil, nil, false)
return fn
}
开发者ID:pombredanne,项目名称:go.tools,代码行数:14,代码来源:reflect.go
示例11: emitTypeTest
// emitTypeTest emits to f a type test value,ok := x.(t) and returns
// a (value, ok) tuple. x.Type() must be an interface.
//
func emitTypeTest(f *Function, x Value, t types.Type, pos token.Pos) Value {
a := &TypeAssert{
X: x,
AssertedType: t,
CommaOk: true,
}
a.setPos(pos)
a.setType(types.NewTuple(
types.NewVar(token.NoPos, nil, "value", t),
varOk,
))
return f.emit(a)
}
开发者ID:nagyistge,项目名称:hm-workspace,代码行数:16,代码来源:emit.go
示例12: emitTypeTest
// emitTypeTest emits to f a type test value,ok := x.(t) and returns
// a (value, ok) tuple. x.Type() must be an interface.
//
func emitTypeTest(f *Function, x Value, t types.Type) Value {
// TODO(adonovan): opt: simplify infallible tests as per
// emitTypeAssert, and return (x, vTrue).
// (Requires that exprN returns a slice of extracted values,
// not a single Value of type *types.Results.)
a := &TypeAssert{
X: x,
AssertedType: t,
CommaOk: true,
}
a.setType(types.NewTuple(
types.NewVar(nil, "value", t),
varOk,
))
return f.emit(a)
}
开发者ID:pombredanne,项目名称:go.tools,代码行数:19,代码来源:emit.go
示例13: 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()))
}
}
开发者ID:hackrole,项目名称:daily-program,代码行数:21,代码来源:import.go
示例14: parseParameter
// Parameter = ( identifier | "?" ) [ "..." ] Type [ string_lit ] .
//
func (p *parser) parseParameter() (par *types.Var, isVariadic bool) {
_, name := p.parseName(false)
if name == "" {
name = "_" // cannot access unnamed identifiers
}
if p.tok == '.' {
p.expectSpecial("...")
isVariadic = true
}
typ := p.parseType()
if isVariadic {
typ = types.NewSlice(typ)
}
// ignore argument tag (e.g. "noescape")
if p.tok == scanner.String {
p.next()
}
// TODO(gri) should we provide a package?
par = types.NewVar(token.NoPos, nil, name, typ)
return
}
开发者ID:amulyas,项目名称:bosh-cloudstack-cpi,代码行数:23,代码来源:gcimporter.go
示例15: parseParameter
// Parameter = ( identifier | "?" ) [ "..." ] Type [ string_lit ] .
//
func (p *parser) parseParameter() (par *types.Var, isVariadic bool) {
_, name := p.parseName(false)
// remove gc-specific parameter numbering
if i := strings.Index(name, "·"); i >= 0 {
name = name[:i]
}
if p.tok == '.' {
p.expectSpecial("...")
isVariadic = true
}
typ := p.parseType()
if isVariadic {
typ = types.NewSlice(typ)
}
// ignore argument tag (e.g. "noescape")
if p.tok == scanner.String {
p.next()
}
// TODO(gri) should we provide a package?
par = types.NewVar(token.NoPos, nil, name, typ)
return
}
开发者ID:ufo22940268,项目名称:two-server-others,代码行数:24,代码来源:gcimporter.go
示例16: varDecl
func (cdd *CDD) varDecl(w *bytes.Buffer, typ types.Type, global bool, name string, val ast.Expr) (acds []*CDD) {
dim, acds := cdd.Type(w, typ)
w.WriteByte(' ')
w.WriteString(dimFuncPtr(name, dim))
constInit := true // true if C declaration can init value
if global {
cdd.copyDecl(w, ";\n") // Global variables may need declaration
if val != nil {
if i, ok := val.(*ast.Ident); !ok || i.Name != "nil" {
constInit = cdd.exprValue(val) != nil
}
}
}
if constInit {
w.WriteString(" = ")
if val != nil {
cdd.Expr(w, val, typ)
} else {
zeroVal(w, typ)
}
}
w.WriteString(";\n")
cdd.copyDef(w)
if !constInit {
w.Reset()
// Runtime initialisation
assign := false
switch t := underlying(typ).(type) {
case *types.Slice:
switch vt := val.(type) {
case *ast.CompositeLit:
aname := "array" + cdd.gtc.uniqueId()
var n int64
for _, elem := range vt.Elts {
switch e := elem.(type) {
case *ast.KeyValueExpr:
val := cdd.exprValue(e.Key)
if val == nil {
panic("slice: composite literal with non-constant key")
}
m, ok := exact.Int64Val(val)
if !ok {
panic("slice: can't convert " + val.String() + " to int64")
}
m++
if m > n {
n = m
}
default:
n++
}
}
at := types.NewArray(t.Elem(), n)
o := types.NewVar(vt.Lbrace, cdd.gtc.pkg, aname, at)
cdd.gtc.pkg.Scope().Insert(o)
acd := cdd.gtc.newCDD(o, VarDecl, cdd.il)
av := *vt
cdd.gtc.ti.Types[&av] = types.TypeAndValue{Type: at} // BUG: thread-unsafe
acd.varDecl(new(bytes.Buffer), o.Type(), cdd.gtc.isGlobal(o), aname, &av)
cdd.InitNext = acd
acds = append(acds, acd)
w.WriteByte('\t')
w.WriteString(name)
w.WriteString(" = ASLICE(")
w.WriteString(strconv.FormatInt(at.Len(), 10))
w.WriteString(", ")
w.WriteString(aname)
w.WriteString(");\n")
default:
assign = true
}
case *types.Array:
w.WriteByte('\t')
w.WriteString("ACPY(")
w.WriteString(name)
w.WriteString(", ")
switch val.(type) {
case *ast.CompositeLit:
w.WriteString("((")
dim, _ := cdd.Type(w, t.Elem())
dim = append([]string{"[]"}, dim...)
w.WriteString("(" + dimFuncPtr("", dim) + "))")
cdd.Expr(w, val, typ)
default:
cdd.Expr(w, val, typ)
}
//.........这里部分代码省略.........
开发者ID:rjammala,项目名称:emgo,代码行数:101,代码来源:decl.go
示例17: promoteInterfaceMethod
// promoteInterfaceMethod promotes an interface method to a type
// which has embedded the interface.
//
// TODO consolidate this and promoteMethod.
func (c *compiler) promoteInterfaceMethod(iface *types.Interface, methodIndex int, recv types.Type, indices []int) types.Object {
m := iface.Method(methodIndex)
var pkg *types.Package
if recv, ok := recv.(*types.Named); ok {
pkg = c.objectdata[recv.Obj()].Package
}
recvvar := types.NewVar(pkg, "", recv)
sig := m.Type().(*types.Signature)
sig = types.NewSignature(recvvar, sig.Params(), sig.Results(), sig.IsVariadic())
f := &synthFunc{pkg: pkg, name: m.Name(), typ: sig}
ident := ast.NewIdent(f.Name())
var isptr bool
if ptr, ok := recv.(*types.Pointer); ok {
isptr = true
recv = ptr.Elem()
}
c.objects[ident] = f
c.objectdata[f] = &ObjectData{Ident: ident, Package: pkg}
if pkg == nil || pkg == c.pkg {
if currblock := c.builder.GetInsertBlock(); !currblock.IsNil() {
defer c.builder.SetInsertPointAtEnd(currblock)
}
llvmfn := c.Resolve(ident).LLVMValue()
llvmfn = c.builder.CreateExtractValue(llvmfn, 0, "")
llvmfn.SetLinkage(llvm.LinkOnceODRLinkage)
entry := llvm.AddBasicBlock(llvmfn, "entry")
c.builder.SetInsertPointAtEnd(entry)
args := llvmfn.Params()
ifaceval := args[0]
if !isptr {
ptr := c.builder.CreateAlloca(ifaceval.Type(), "")
c.builder.CreateStore(ifaceval, ptr)
ifaceval = ptr
}
for _, i := range indices {
if i == -1 {
ifaceval = c.builder.CreateLoad(ifaceval, "")
} else {
ifaceval = c.builder.CreateStructGEP(ifaceval, i, "")
}
}
recvarg := c.builder.CreateExtractValue(ifaceval, 0, "")
ifn := c.builder.CreateExtractValue(ifaceval, methodIndex+2, "")
// Add the receiver argument type.
fntyp := ifn.Type().ElementType()
returnType := fntyp.ReturnType()
paramTypes := fntyp.ParamTypes()
paramTypes = append([]llvm.Type{recvarg.Type()}, paramTypes...)
vararg := fntyp.IsFunctionVarArg()
fntyp = llvm.FunctionType(returnType, paramTypes, vararg)
fnptrtyp := llvm.PointerType(fntyp, 0)
ifn = c.builder.CreateBitCast(ifn, fnptrtyp, "")
args[0] = recvarg
result := c.builder.CreateCall(ifn, args, "")
if sig.Results().Len() == 0 {
c.builder.CreateRetVoid()
} else {
c.builder.CreateRet(result)
}
}
return f
}
开发者ID:hzmangel,项目名称:llgo,代码行数:74,代码来源:functions.go
示例18: translateExpr
//.........这里部分代码省略.........
}
return c.formatExpr("(function(%s) {\n%s%s})", strings.Join(params, ", "), string(body), strings.Repeat("\t", c.p.indentation))
case *ast.UnaryExpr:
t := c.p.info.Types[e.X].Type
switch e.Op {
case token.AND:
switch t.Underlying().(type) {
case *types.Struct, *types.Array:
return c.translateExpr(e.X)
}
switch x := removeParens(e.X).(type) {
case *ast.CompositeLit:
return c.formatExpr("$newDataPointer(%e, %s)", x, c.typeName(c.p.info.Types[e].Type))
case *ast.Ident:
if obj := c.p.info.Uses[x]; c.p.escapingVars[obj] {
return c.formatExpr("new %s(function() { return this.$target[0]; }, function($v) { this.$target[0] = $v; }, %s)", c.typeName(exprType), c.p.objectVars[obj])
}
return c.formatExpr("new %s(function() { return %e; }, function($v) { %s })", c.typeName(exprType), x, c.translateAssign(x, "$v", exprType, false))
case *ast.SelectorExpr:
newSel := &ast.SelectorExpr{X: c.newIdent("this.$target", c.p.info.Types[x.X].Type), Sel: x.Sel}
c.p.info.Selections[newSel] = c.p.info.Selections[x]
return c.formatExpr("new %s(function() { return %e; }, function($v) { %s }, %e)", c.typeName(exprType), newSel, c.translateAssign(newSel, "$v", exprType, false), x.X)
case *ast.IndexExpr:
newIndex := &ast.IndexExpr{X: c.newIdent("this.$target", c.p.info.Types[x.X].Type), Index: x.Index}
return c.formatExpr("new %s(function() { return %e; }, function($v) { %s }, %e)", c.typeName(exprType), newIndex, c.translateAssign(newIndex, "$v", exprType, false), x.X)
default:
panic(fmt.Sprintf("Unhandled: %T\n", x))
}
case token.ARROW:
call := &ast.CallExpr{
Fun: c.newIdent("$recv", types.NewSignature(nil, nil, types.NewTuple(types.NewVar(0, nil, "", t)), types.NewTuple(types.NewVar(0, nil, "", exprType), types.NewVar(0, nil, "", types.Typ[types.Bool])), false)),
Args: []ast.Expr{e.X},
}
c.blocking[call] = true
if _, isTuple := exprType.(*types.Tuple); isTuple {
return c.formatExpr("%e", call)
}
return c.formatExpr("%e[0]", call)
}
basic := t.Underlying().(*types.Basic)
switch e.Op {
case token.ADD:
return c.translateExpr(e.X)
case token.SUB:
switch {
case is64Bit(basic):
return c.formatExpr("new %1s(-%2h, -%2l)", c.typeName(t), e.X)
case basic.Info()&types.IsComplex != 0:
return c.formatExpr("new %1s(-%2r, -%2i)", c.typeName(t), e.X)
case basic.Info()&types.IsUnsigned != 0:
return c.fixNumber(c.formatExpr("-%e", e.X), basic)
default:
return c.formatExpr("-%e", e.X)
}
case token.XOR:
if is64Bit(basic) {
return c.formatExpr("new %1s(~%2h, ~%2l >>> 0)", c.typeName(t), e.X)
}
return c.fixNumber(c.formatExpr("~%e", e.X), basic)
case token.NOT:
x := c.translateExpr(e.X)
if x.String() == "true" {
开发者ID:nvdnkpr,项目名称:gopherjs,代码行数:67,代码来源:expressions.go
示例19: makeWrapper
// makeWrapper returns a synthetic wrapper Function that optionally
// performs receiver indirection, implicit field selections and then a
// tailcall of a "promoted" method. For example, given these decls:
//
// type A struct {B}
// type B struct {*C}
// type C ...
// func (*C) f()
//
// then makeWrapper(typ=A, obj={Func:(*C).f, Indices=[B,C,f]})
// synthesize this wrapper method:
//
// func (a A) f() { return a.B.C->f() }
//
// prog is the program to which the synthesized method will belong.
// typ is the receiver type of the wrapper method. obj is the
// type-checker's object for the promoted method; its Func may be a
// concrete or an interface method.
//
// EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu)
//
func makeWrapper(prog *Program, typ types.Type, meth *types.Selection) *Function {
obj := meth.Obj().(*types.Func)
oldsig := obj.Type().(*types.Signature)
recv := types.NewVar(token.NoPos, nil, "recv", typ)
description := fmt.Sprintf("wrapper for %s", obj)
if prog.mode&LogSource != 0 {
defer logStack("make %s to (%s)", description, typ)()
}
fn := &Function{
name: obj.Name(),
method: meth,
Signature: changeRecv(oldsig, recv),
Synthetic: description,
Prog: prog,
pos: obj.Pos(),
}
fn.startBody()
fn.addSpilledParam(recv)
createParams(fn)
var v Value = fn.Locals[0] // spilled receiver
if isPointer(typ) {
// TODO(adonovan): consider emitting a nil-pointer check here
// with a nice error message, like gc does.
v = emitLoad(fn, v)
}
// Invariant: v is a pointer, either
// value of *A receiver param, or
// address of A spilled receiver.
// We use pointer arithmetic (FieldAddr possibly followed by
// Load) in preference to value extraction (Field possibly
// preceded by Load).
indices := meth.Index()
v = emitImplicitSelections(fn, v, indices[:len(indices)-1])
// Invariant: v is a pointer, either
// value of implicit *C field, or
// address of implicit C field.
var c Call
if _, ok := oldsig.Recv().Type().Underlying().(*types.Interface); !ok { // concrete method
if !isPointer(oldsig.Recv().Type()) {
v = emitLoad(fn, v)
}
c.Call.Value = prog.declaredFunc(obj)
c.Call.Args = append(c.Call.Args, v)
} else {
c.Call.Method = obj
c.Call.Value = emitLoad(fn, v)
}
for _, arg := range fn.Params[1:] {
c.Call.Args = append(c.Call.Args, arg)
}
emitTailCall(fn, &c)
fn.finishBody()
return fn
}
开发者ID:Bosh-for-Cpi,项目名称:bosh-2605,代码行数:82,代码来源:promote.go
示例20: builtinCallSignature
// builtinCallSignature returns a new Signature describing the
// effective type of a builtin operator for the particular call e.
//
// This requires ad-hoc typing rules for all variadic (append, print,
// println) and polymorphic (append, copy, delete, close) built-ins.
// This logic could be part of the typechecker, and should arguably
// be moved there and made accessible via an additional types.Context
// callback.
//
// The returned Signature is degenerate and only intended for use by
// emitCallArgs.
//
func builtinCallSignature(info *TypeInfo, e *ast.CallExpr) *types.Signature {
var params []*types.Var
var isVariadic bool
switch builtin := noparens(e.Fun).(*ast.Ident).Name; builtin {
case "append":
var t0, t1 types.Type
t0 = info.TypeOf(e) // infer arg[0] type from result type
if e.Ellipsis != 0 {
// append([]T, []T) []T
// append([]byte, string) []byte
t1 = info.TypeOf(e.Args[1]) // no conversion
} else {
// append([]T, ...T) []T
t1 = t0.Underlying().(*types.Slice).Elem()
isVariadic = true
}
params = append(params,
types.NewVar(nil, "", t0),
types.NewVar(nil, "", t1))
case "print", "println": // print{,ln}(any, ...interface{})
isVariadic = true
// Note, arg0 may have any type, not necessarily tEface.
params = append(params,
types.NewVar(nil, "", info.TypeOf(e.Args[0])),
types.NewVar(nil, "", tEface))
case "close":
params = append(params, types.NewVar(nil, "", info.TypeOf(e.Args[0])))
case "copy":
// copy([]T, []T) int
// Infer arg types from each other. Sleazy.
var st *types.Slice
if t, ok := info.TypeOf(e.Args[0]).Underlying().(*types.Slice); ok {
st = t
} else if t, ok := info.TypeOf(e.Args[1]).Underlying().(*types.Slice); ok {
st = t
} else {
panic("cannot infer types in call to copy()")
}
stvar := types.NewVar(nil, "", st)
params = append(params, stvar, stvar)
case "delete":
// delete(map[K]V, K)
tmap := info.TypeOf(e.Args[0])
tkey := tmap.Underlying().(*types.Map).Key()
params = append(params,
types.NewVar(nil, "", tmap),
types.NewVar(nil, "", tkey))
case "len", "cap":
params = append(params, types.NewVar(nil, "", info.TypeOf(e.Args[0])))
case "real", "imag":
// Reverse conversion to "complex" case below.
var argType types.Type
switch info.TypeOf(e).(*types.Basic).Kind() {
case types.UntypedFloat:
argType = types.Typ[types.UntypedComplex]
case types.Float64:
argType = tComplex128
case types.Float32:
argType = tComplex64
default:
unreachable()
}
params = append(params, types.NewVar(nil, "", argType))
case "complex":
var argType types.Type
switch info.TypeOf(e).(*types.Basic).Kind() {
case types.UntypedComplex:
argType = types.Typ[types.UntypedFloat]
case types.Complex128:
argType = tFloat64
case types.Complex64:
argType = tFloat32
default:
unreachable()
}
v := types.NewVar(nil, "", argType)
params = append(params, v, v)
case "panic":
params = append(params, types.NewVar(nil, "", tEface))
//.........这里部分代码省略.........
开发者ID:pombredanne,项目名称:go.tools,代码行数:101,代码来源:typeinfo.go
注:本文中的code/google/com/p/go/tools/go/types.NewVar函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论