本文整理汇总了Golang中code/google/com/p/go/tools/go/types.NewInterface函数的典型用法代码示例。如果您正苦于以下问题:Golang NewInterface函数的具体用法?Golang NewInterface怎么用?Golang NewInterface使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewInterface函数的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: makeInterface
func (c *compiler) makeInterface(v *LLVMValue, iface types.Type) *LLVMValue {
llv := v.LLVMValue()
lltyp := llv.Type()
i8ptr := llvm.PointerType(llvm.Int8Type(), 0)
if lltyp.TypeKind() == llvm.PointerTypeKind {
llv = c.builder.CreateBitCast(llv, i8ptr, "")
} else {
// If the value fits exactly in a pointer, then we can just
// bitcast it. Otherwise we need to malloc.
if c.target.TypeStoreSize(lltyp) <= uint64(c.target.PointerSize()) {
bits := c.target.TypeSizeInBits(lltyp)
if bits > 0 {
llv = coerce(c.builder, llv, llvm.IntType(int(bits)))
llv = c.builder.CreateIntToPtr(llv, i8ptr, "")
} else {
llv = llvm.ConstNull(i8ptr)
}
} else {
ptr := c.createTypeMalloc(lltyp)
c.builder.CreateStore(llv, ptr)
llv = c.builder.CreateBitCast(ptr, i8ptr, "")
}
}
value := llvm.Undef(c.types.ToLLVM(iface))
rtype := c.types.ToRuntime(v.Type())
rtype = c.builder.CreateBitCast(rtype, llvm.PointerType(llvm.Int8Type(), 0), "")
value = c.builder.CreateInsertValue(value, rtype, 0, "")
value = c.builder.CreateInsertValue(value, llv, 1, "")
if iface.Underlying().(*types.Interface).NumMethods() > 0 {
result := c.NewValue(value, types.NewInterface(nil, nil))
result, _ = result.convertE2I(iface)
return result
}
return c.NewValue(value, iface)
}
开发者ID:minux,项目名称:llgo,代码行数:35,代码来源:interfaces.go
示例2: convertI2E
// convertI2E converts a non-empty interface value to an empty interface.
func (v *LLVMValue) convertI2E() *LLVMValue {
c := v.compiler
f := c.runtime.convertI2E.LLVMValue()
args := []llvm.Value{coerce(c.builder, v.LLVMValue(), c.runtime.iface.llvm)}
typ := types.NewInterface(nil, nil)
return c.NewValue(coerce(c.builder, c.builder.CreateCall(f, args, ""), c.llvmtypes.ToLLVM(typ)), typ)
}
开发者ID:minux,项目名称:llgo,代码行数:8,代码来源:convert.go
示例3: 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() 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(true)
sig := p.parseSignature(nil)
methods = append(methods, types.NewFunc(token.NoPos, pkg, name, sig))
}
p.expect('}')
return types.NewInterface(methods, nil)
}
开发者ID:ufo22940268,项目名称:two-server-others,代码行数:25,代码来源:gcimporter.go
示例4: 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() 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(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()
}
开发者ID:4honor,项目名称:obdi,代码行数:27,代码来源:gcimporter.go
示例5: 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)
}
开发者ID:Karthikvb,项目名称:15640_projects,代码行数:22,代码来源:parser.go
示例6: translateStmt
//.........这里部分代码省略.........
rhs = append(rhs, nil)
}
c.translateStmt(&ast.AssignStmt{
Lhs: lhs,
Tok: token.DEFINE,
Rhs: rhs,
}, "")
}
case token.TYPE:
for _, spec := range decl.Specs {
o := c.p.info.Defs[spec.(*ast.TypeSpec).Name].(*types.TypeName)
c.translateType(o, false)
c.initType(o)
}
case token.CONST:
// skip, constants are inlined
}
case *ast.ExprStmt:
c.printLabel(label)
expr := c.translateExpr(s.X)
if expr != nil {
c.Printf("%s;", expr)
}
case *ast.LabeledStmt:
c.printLabel(label)
c.translateStmt(s.Stmt, s.Label.Name)
case *ast.GoStmt:
c.printLabel(label)
c.Printf("$go(%s, [%s]);", c.translateExpr(s.Call.Fun), strings.Join(c.translateArgs(c.p.info.Types[s.Call.Fun].Type.Underlying().(*types.Signature), s.Call.Args, s.Call.Ellipsis.IsValid()), ", "))
case *ast.SendStmt:
chanType := c.p.info.Types[s.Chan].Type.Underlying().(*types.Chan)
call := &ast.CallExpr{
Fun: c.newIdent("$send", types.NewSignature(nil, nil, types.NewTuple(types.NewVar(0, nil, "", chanType), types.NewVar(0, nil, "", chanType.Elem())), nil, false)),
Args: []ast.Expr{s.Chan, s.Value},
}
c.blocking[call] = true
c.translateStmt(&ast.ExprStmt{call}, label)
case *ast.SelectStmt:
var channels []string
var caseClauses []ast.Stmt
flattened := false
hasDefault := false
for i, s := range s.Body.List {
clause := s.(*ast.CommClause)
switch comm := clause.Comm.(type) {
case nil:
channels = append(channels, "[]")
hasDefault = true
case *ast.ExprStmt:
channels = append(channels, c.formatExpr("[%e]", removeParens(comm.X).(*ast.UnaryExpr).X).String())
case *ast.AssignStmt:
channels = append(channels, c.formatExpr("[%e]", removeParens(comm.Rhs[0]).(*ast.UnaryExpr).X).String())
case *ast.SendStmt:
channels = append(channels, c.formatExpr("[%e, %e]", comm.Chan, comm.Value).String())
default:
panic(fmt.Sprintf("unhandled: %T", comm))
}
caseClauses = append(caseClauses, &ast.CaseClause{
List: []ast.Expr{c.newInt(i, types.Typ[types.Int])},
Body: clause.Body,
})
flattened = flattened || c.flattened[clause]
}
selectCall := c.setType(&ast.CallExpr{
Fun: c.newIdent("$select", types.NewSignature(nil, 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
selectionVar := c.newVariable("_selection")
c.Printf("%s = %s;", selectionVar, c.translateExpr(selectCall))
translateCond := func(cond ast.Expr) *expression {
return c.formatExpr("%s[0] === %e", selectionVar, cond)
}
printCaseBodyPrefix := func(index int) {
if assign, ok := s.Body.List[index].(*ast.CommClause).Comm.(*ast.AssignStmt); ok {
switch rhsType := c.p.info.Types[assign.Rhs[0]].Type.(type) {
case *types.Tuple:
c.translateStmt(&ast.AssignStmt{Lhs: assign.Lhs, Rhs: []ast.Expr{c.newIdent(selectionVar+"[1]", rhsType)}, Tok: assign.Tok}, "")
default:
c.translateStmt(&ast.AssignStmt{Lhs: assign.Lhs, Rhs: []ast.Expr{c.newIdent(selectionVar+"[1][0]", rhsType)}, Tok: assign.Tok}, "")
}
}
}
c.translateBranchingStmt(caseClauses, true, translateCond, printCaseBodyPrefix, label, flattened)
case *ast.EmptyStmt:
// skip
default:
panic(fmt.Sprintf("Unhandled statement: %T\n", s))
}
}
开发者ID:kpsmith,项目名称:gopherjs,代码行数:101,代码来源:statements.go
示例7: translateBuiltin
func (c *funcContext) translateBuiltin(name string, args []ast.Expr, ellipsis bool, typ types.Type) *expression {
switch name {
case "new":
t := typ.(*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("%s", c.zeroValue(t.Elem()))
default:
return c.formatExpr("$newDataPointer(%s, %s)", c.zeroValue(t.Elem()), c.typeName(t))
}
case "make":
switch argType := c.p.info.Types[args[0]].Type.Underlying().(type) {
case *types.Slice:
t := c.typeName(c.p.info.Types[args[0]].Type)
if len(args) == 3 {
return c.formatExpr("%s.make(%f, %f)", t, args[1], args[2])
}
return c.formatExpr("%s.make(%f)", t, args[1])
case *types.Map:
return c.formatExpr("new $Map()")
case *types.Chan:
length := "0"
if len(args) == 2 {
length = c.translateExpr(args[1]).String()
}
return c.formatExpr("new %s(%s)", c.typeName(c.p.info.Types[args[0]].Type), length)
default:
panic(fmt.Sprintf("Unhandled make type: %T\n", argType))
}
case "len":
switch argType := c.p.info.Types[args[0]].Type.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.info.Types[args[0]].Type.Underlying().(type) {
case *types.Slice:
return c.formatExpr("%e.$capacity", args[0])
case *types.Pointer:
return c.formatExpr("(%e, %d)", args[0], argType.Elem().(*types.Array).Len())
case *types.Chan:
return c.formatExpr("%e.$capacity", args[0])
// 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 len(args) == 1 {
return c.translateExpr(args[0])
}
if ellipsis {
return c.formatExpr("$appendSlice(%e, %s)", args[0], c.translateConversionToSlice(args[1], typ))
}
sliceType := typ.Underlying().(*types.Slice)
return c.formatExpr("$append(%e, %s)", args[0], strings.Join(c.translateExprSlice(args[1:], sliceType.Elem()), ", "))
case "delete":
return c.formatExpr(`delete %e[%s]`, args[0], c.makeKey(args[1], c.p.info.Types[args[0]].Type.Underlying().(*types.Map).Key()))
case "copy":
if basic, isBasic := c.p.info.Types[args[1]].Type.Underlying().(*types.Basic); isBasic && basic.Info()&types.IsString != 0 {
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":
return c.formatExpr("new %s(%e, %e)", c.typeName(typ), args[0], args[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))
}
}
开发者ID:nvdnkpr,项目名称:gopherjs,代码行数:94,代码来源:expressions.go
示例8: 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 "Str":
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
case "IsUndefined":
return c.formatParenExpr("%s === undefined", recv)
case "IsNull":
return c.formatParenExpr("%s === null", recv)
default:
panic("Invalid js package object: " + sel.Obj().Name())
}
}
if isWrapped(methodsRecvType) {
fun = c.formatExpr("(new %s(%s)).%s", c.typeName(methodsRecvType), recv, methodName)
break
}
fun = c.formatExpr("%s.%s", recv, methodName)
case types.FieldVal:
fields, jsTag := c.translateSelection(sel)
if jsTag != "" {
sig := sel.Type().(*types.Signature)
return c.internalize(c.formatExpr("%e.%s.%s(%s)", f.X, strings.Join(fields, "."), jsTag, externalizeArgs(e.Args)), sig.Results().At(0).Type())
}
fun = c.formatExpr("%e.%s", f.X, strings.Join(fields, "."))
case types.MethodExpr:
fun = c.translateExpr(f)
default:
panic("")
}
default:
开发者ID:nvdnkpr,项目名称:gopherjs,代码行数:67,代码来源:expressions.go
示例9: 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"
"code.google.com/p/go.tools/go/callgraph"
"code.google.com/p/go.tools/go/ssa"
"code.google.com/p/go.tools/go/types"
)
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.
//
开发者ID:bryanxu,项目名称:go-zh.tools,代码行数:30,代码来源:gen.go
示例10: translateExpr
//.........这里部分代码省略.........
args = append(args, c.translateExpr(arg))
}
return fmt.Sprintf("new %s(%s)", c.typeName(c.info.Types[e.Args[0]]), strings.Join(args, ", "))
}
case "len":
arg := c.translateExpr(e.Args[0])
switch argType := c.info.Types[e.Args[0]].Underlying().(type) {
case *types.Basic, *types.Slice:
return arg + ".length"
case *types.Pointer:
return fmt.Sprintf("(%s, %d)", arg, argType.Elem().(*types.Array).Len())
case *types.Map:
return fmt.Sprintf("(Go$obj = %s, Go$obj !== null ? Go$keys(Go$obj).length : 0)", arg)
case *types.Chan:
return "0"
// length of array is constant
default:
panic(fmt.Sprintf("Unhandled len type: %T\n", argType))
}
case "cap":
arg := c.translateExpr(e.Args[0])
switch argType := c.info.Types[e.Args[0]].Underlying().(type) {
case *types.Slice:
return arg + ".capacity"
case *types.Pointer:
return fmt.Sprintf("(%s, %d)", arg, argType.Elem().(*types.Array).Len())
case *types.Chan:
return "0"
// capacity of array is constant
default:
panic(fmt.Sprintf("Unhandled cap type: %T\n", argType))
}
case "panic":
return fmt.Sprintf("throw new Go$Panic(%s)", c.translateExprToType(e.Args[0], types.NewInterface(nil, nil)))
case "append":
if e.Ellipsis.IsValid() {
return fmt.Sprintf("Go$append(%s, %s)", c.translateExpr(e.Args[0]), c.translateExprToType(e.Args[1], exprType))
}
sliceType := exprType.Underlying().(*types.Slice)
toAppend := createListComposite(sliceType.Elem(), c.translateExprSlice(e.Args[1:], sliceType.Elem()))
return fmt.Sprintf("Go$append(%s, new %s(%s))", c.translateExpr(e.Args[0]), c.typeName(exprType), toAppend)
case "delete":
return fmt.Sprintf(`delete (%s || Go$Map.Go$nil)[%s]`, c.translateExpr(e.Args[0]), c.makeKey(e.Args[1], c.info.Types[e.Args[0]].Underlying().(*types.Map).Key()))
case "copy":
return fmt.Sprintf("Go$copy(%s, %s)", c.translateExprToType(e.Args[0], types.NewSlice(types.Typ[types.Byte])), c.translateExprToType(e.Args[1], types.NewSlice(types.Typ[types.Byte])))
case "print", "println":
return fmt.Sprintf("console.log(%s)", strings.Join(c.translateExprSlice(e.Args, nil), ", "))
case "complex":
return fmt.Sprintf("new %s(%s, %s)", c.typeName(c.info.Types[e]), c.translateExpr(e.Args[0]), c.translateExpr(e.Args[1]))
case "real":
return c.translateExpr(e.Args[0]) + ".real"
case "imag":
return c.translateExpr(e.Args[0]) + ".imag"
case "recover":
return "Go$recover()"
case "close":
return `Go$throwRuntimeError("not supported by GopherJS: close")`
default:
panic(fmt.Sprintf("Unhandled builtin: %s\n", o.Name()))
}
case *types.TypeName: // conversion
if basic, isBasic := o.Type().Underlying().(*types.Basic); isBasic && !types.IsIdentical(c.info.Types[e.Args[0]], types.Typ[types.UnsafePointer]) {
return fixNumber(c.translateExprToType(e.Args[0], o.Type()), basic)
}
return c.translateExprToType(e.Args[0], o.Type())
}
开发者ID:umisama,项目名称:gopherjs,代码行数:67,代码来源:expressions.go
示例11: 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:
t := new(types.Interface)
p.record(t)
// 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)
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 {
obj = types.NewTypeName(token.NoPos, pkg, name, nil)
scope.Insert(obj)
}
// associate new named type with obj if it doesn't exist yet
//.........这里部分代码省略.........
开发者ID:hackrole,项目名称:daily-program,代码行数:101,代码来源:import.go
示例12: 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"
"code.google.com/p/go.tools/go/callgraph"
"code.google.com/p/go.tools/go/ssa"
"code.google.com/p/go.tools/go/types"
)
var (
tEface = types.NewInterface(nil, nil)
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.
//
开发者ID:hackrole,项目名称:daily-program,代码行数:30,代码来源:gen.go
示例13: translateExpr
//.........这里部分代码省略.........
return c.formatExpr("new %s()", c.typeName(c.p.info.Types[e.Args[0]].Type))
default:
panic(fmt.Sprintf("Unhandled make type: %T\n", argType))
}
case "len":
arg := c.translateExpr(e.Args[0])
switch argType := c.p.info.Types[e.Args[0]].Type.Underlying().(type) {
case *types.Basic, *types.Slice:
return c.formatExpr("%s.length", arg)
case *types.Pointer:
return c.formatExpr("(%s, %d)", arg, argType.Elem().(*types.Array).Len())
case *types.Map:
return c.formatExpr("go$keys(%s).length", arg)
case *types.Chan:
return c.formatExpr("0")
// length of array is constant
default:
panic(fmt.Sprintf("Unhandled len type: %T\n", argType))
}
case "cap":
arg := c.translateExpr(e.Args[0])
switch argType := c.p.info.Types[e.Args[0]].Type.Underlying().(type) {
case *types.Slice:
return c.formatExpr("%s.capacity", arg)
case *types.Pointer:
return c.formatExpr("(%s, %d)", arg, argType.Elem().(*types.Array).Len())
case *types.Chan:
return c.formatExpr("0")
// capacity of array is constant
default:
panic(fmt.Sprintf("Unhandled cap type: %T\n", argType))
}
case "panic":
return c.formatExpr("throw go$panic(%s)", c.translateImplicitConversion(e.Args[0], types.NewInterface(nil, nil)))
case "append":
if len(e.Args) == 1 {
return c.translateExpr(e.Args[0])
}
if e.Ellipsis.IsValid() {
return c.formatExpr("go$appendSlice(%e, %s)", e.Args[0], c.translateConversionToSlice(e.Args[1], exprType))
}
sliceType := exprType.Underlying().(*types.Slice)
return c.formatExpr("go$append(%e, %s)", e.Args[0], strings.Join(c.translateExprSlice(e.Args[1:], sliceType.Elem()), ", "))
case "delete":
return c.formatExpr(`delete %e[%s]`, e.Args[0], c.makeKey(e.Args[1], c.p.info.Types[e.Args[0]].Type.Underlying().(*types.Map).Key()))
case "copy":
if basic, isBasic := c.p.info.Types[e.Args[1]].Type.Underlying().(*types.Basic); isBasic && basic.Info()&types.IsString != 0 {
return c.formatExpr("go$copyString(%e, %e)", e.Args[0], e.Args[1])
}
return c.formatExpr("go$copySlice(%e, %e)", e.Args[0], e.Args[1])
case "print", "println":
return c.formatExpr("console.log(%s)", strings.Join(c.translateExprSlice(e.Args, nil), ", "))
case "complex":
return c.formatExpr("new %s(%e, %e)", c.typeName(c.p.info.Types[e].Type), e.Args[0], e.Args[1])
case "real":
return c.formatExpr("%e.real", e.Args[0])
case "imag":
return c.formatExpr("%e.imag", e.Args[0])
case "recover":
return c.formatExpr("go$recover()")
case "close":
return c.formatExpr(`go$notSupported("close")`)
default:
panic(fmt.Sprintf("Unhandled builtin: %s\n", o.Name()))
}
}
开发者ID:hajimehoshi,项目名称:gopherjs,代码行数:67,代码来源:expressions.go
注:本文中的code/google/com/p/go/tools/go/types.NewInterface函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论