本文整理汇总了Golang中code/google/com/p/go/tools/go/types.NewSlice函数的典型用法代码示例。如果您正苦于以下问题:Golang NewSlice函数的具体用法?Golang NewSlice怎么用?Golang NewSlice使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewSlice函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: makeSlice
// makeSlice allocates a new slice with the optional length and capacity,
// initialising its contents to their zero values.
func (c *compiler) makeSlice(elttyp types.Type, length, capacity Value) llvm.Value {
var lengthValue llvm.Value
if length != nil {
lengthValue = length.Convert(types.Typ[types.Int]).LLVMValue()
} else {
lengthValue = llvm.ConstNull(c.llvmtypes.inttype)
}
// TODO check capacity >= length
capacityValue := lengthValue
if capacity != nil {
capacityValue = capacity.Convert(types.Typ[types.Int]).LLVMValue()
}
eltType := c.types.ToLLVM(elttyp)
sizeof := llvm.ConstTruncOrBitCast(llvm.SizeOf(eltType), c.types.inttype)
size := c.builder.CreateMul(capacityValue, sizeof, "")
mem := c.createMalloc(size)
mem = c.builder.CreateIntToPtr(mem, llvm.PointerType(eltType, 0), "")
c.memsetZero(mem, size)
slicetyp := types.NewSlice(elttyp)
struct_ := llvm.Undef(c.types.ToLLVM(slicetyp))
struct_ = c.builder.CreateInsertValue(struct_, mem, 0, "")
struct_ = c.builder.CreateInsertValue(struct_, lengthValue, 1, "")
struct_ = c.builder.CreateInsertValue(struct_, capacityValue, 2, "")
return struct_
}
开发者ID:hzmangel,项目名称:llgo,代码行数:30,代码来源:slice.go
示例2: slice
func (c *compiler) slice(x, low, high *LLVMValue) *LLVMValue {
if low != nil {
low = low.Convert(types.Typ[types.Int]).(*LLVMValue)
} else {
low = c.NewValue(llvm.ConstNull(c.types.inttype), types.Typ[types.Int])
}
if high != nil {
high = high.Convert(types.Typ[types.Int]).(*LLVMValue)
} else {
// all bits set is -1
high = c.NewValue(llvm.ConstAllOnes(c.types.inttype), types.Typ[types.Int])
}
switch typ := x.Type().Underlying().(type) {
case *types.Pointer: // *array
sliceslice := c.runtime.sliceslice.LLVMValue()
i8slice := sliceslice.Type().ElementType().ReturnType()
sliceValue := llvm.Undef(i8slice) // temporary slice
arraytyp := typ.Elem().Underlying().(*types.Array)
arrayptr := x.LLVMValue()
arrayptr = c.builder.CreateBitCast(arrayptr, i8slice.StructElementTypes()[0], "")
arraylen := llvm.ConstInt(c.llvmtypes.inttype, uint64(arraytyp.Len()), false)
sliceValue = c.builder.CreateInsertValue(sliceValue, arrayptr, 0, "")
sliceValue = c.builder.CreateInsertValue(sliceValue, arraylen, 1, "")
sliceValue = c.builder.CreateInsertValue(sliceValue, arraylen, 2, "")
sliceTyp := types.NewSlice(arraytyp.Elem())
runtimeTyp := c.types.ToRuntime(sliceTyp)
runtimeTyp = c.builder.CreatePtrToInt(runtimeTyp, c.target.IntPtrType(), "")
args := []llvm.Value{runtimeTyp, sliceValue, low.LLVMValue(), high.LLVMValue()}
result := c.builder.CreateCall(sliceslice, args, "")
llvmSliceTyp := c.types.ToLLVM(sliceTyp)
return c.NewValue(c.coerceSlice(result, llvmSliceTyp), sliceTyp)
case *types.Slice:
sliceslice := c.runtime.sliceslice.LLVMValue()
i8slice := sliceslice.Type().ElementType().ReturnType()
sliceValue := x.LLVMValue()
sliceTyp := sliceValue.Type()
sliceValue = c.coerceSlice(sliceValue, i8slice)
runtimeTyp := c.types.ToRuntime(x.Type())
runtimeTyp = c.builder.CreatePtrToInt(runtimeTyp, c.target.IntPtrType(), "")
args := []llvm.Value{runtimeTyp, sliceValue, low.LLVMValue(), high.LLVMValue()}
result := c.builder.CreateCall(sliceslice, args, "")
return c.NewValue(c.coerceSlice(result, sliceTyp), x.Type())
case *types.Basic:
stringslice := c.runtime.stringslice.LLVMValue()
llv := x.LLVMValue()
args := []llvm.Value{
c.coerceString(llv, stringslice.Type().ElementType().ParamTypes()[0]),
low.LLVMValue(),
high.LLVMValue(),
}
result := c.builder.CreateCall(stringslice, args, "")
return c.NewValue(c.coerceString(result, llv.Type()), x.Type())
default:
panic("unimplemented")
}
panic("unreachable")
}
开发者ID:rvedam,项目名称:llgo,代码行数:59,代码来源:slice.go
示例3: funcLLVMType
func (tm *LLVMTypeMap) funcLLVMType(tstr string, f *types.Signature) llvm.Type {
typ, ok := tm.types[tstr]
if !ok {
// If there's a receiver change the receiver to an
// additional (first) parameter, and take the value of
// the resulting signature instead.
var param_types []llvm.Type
if recv := f.Recv(); recv != nil {
params := f.Params()
paramvars := make([]*types.Var, int(params.Len()+1))
paramvars[0] = recv
for i := 0; i < int(params.Len()); i++ {
paramvars[i+1] = params.At(i)
}
params = types.NewTuple(paramvars...)
f := types.NewSignature(nil, params, f.Results(), f.IsVariadic())
return tm.ToLLVM(f)
}
typ = llvm.GlobalContext().StructCreateNamed("")
tm.types[tstr] = typ
params := f.Params()
nparams := int(params.Len())
for i := 0; i < nparams; i++ {
typ := params.At(i).Type()
if f.IsVariadic() && i == nparams-1 {
typ = types.NewSlice(typ)
}
llvmtyp := tm.ToLLVM(typ)
param_types = append(param_types, llvmtyp)
}
var return_type llvm.Type
results := f.Results()
switch nresults := int(results.Len()); nresults {
case 0:
return_type = llvm.VoidType()
case 1:
return_type = tm.ToLLVM(results.At(0).Type())
default:
elements := make([]llvm.Type, nresults)
for i := range elements {
result := results.At(i)
elements[i] = tm.ToLLVM(result.Type())
}
return_type = llvm.StructType(elements, false)
}
fntyp := llvm.FunctionType(return_type, param_types, false)
fnptrtyp := llvm.PointerType(fntyp, 0)
i8ptr := llvm.PointerType(llvm.Int8Type(), 0)
elements := []llvm.Type{fnptrtyp, i8ptr} // func, closure
typ.StructSetBody(elements, false)
}
return typ
}
开发者ID:hzmangel,项目名称:llgo,代码行数:57,代码来源:typemap.go
示例4: generate
// generate generates offline constraints for the entire program.
func (a *analysis) generate() {
start("Constraint generation")
if a.log != nil {
fmt.Fprintln(a.log, "==== Generating constraints")
}
// Create a dummy node since we use the nodeid 0 for
// non-pointerlike variables.
a.addNodes(tInvalid, "(zero)")
// Create the global node for panic values.
a.panicNode = a.addNodes(tEface, "panic")
// Create nodes and constraints for all methods of reflect.rtype.
// (Shared contours are used by dynamic calls to reflect.Type
// methods---typically just String().)
if rtype := a.reflectRtypePtr; rtype != nil {
a.genMethodsOf(rtype)
}
root := a.genRootCalls()
if a.config.BuildCallGraph {
a.result.CallGraph = callgraph.New(root.fn)
}
// Create nodes and constraints for all methods of all types
// that are dynamically accessible via reflection or interfaces.
for _, T := range a.prog.TypesWithMethodSets() {
a.genMethodsOf(T)
}
// Generate constraints for entire program.
for len(a.genq) > 0 {
cgn := a.genq[0]
a.genq = a.genq[1:]
a.genFunc(cgn)
}
// The runtime magically allocates os.Args; so should we.
if os := a.prog.ImportedPackage("os"); os != nil {
// In effect: os.Args = new([1]string)[:]
T := types.NewSlice(types.Typ[types.String])
obj := a.addNodes(sliceToArray(T), "<command-line args>")
a.endObject(obj, nil, "<command-line args>")
a.addressOf(T, a.objectNode(nil, os.Var("Args")), obj)
}
// Discard generation state, to avoid confusion after node renumbering.
a.panicNode = 0
a.globalval = nil
a.localval = nil
a.localobj = nil
stop("Constraint generation")
}
开发者ID:bryanxu,项目名称:go-zh.tools,代码行数:57,代码来源:gen.go
示例5: createParams
// createParams creates parameters for wrapper method fn based on its
// Signature.Params, which do not include the receiver.
//
func createParams(fn *Function) {
var last *Parameter
tparams := fn.Signature.Params()
for i, n := 0, tparams.Len(); i < n; i++ {
last = fn.addParamObj(tparams.At(i))
}
if fn.Signature.Variadic() {
last.typ = types.NewSlice(last.typ)
}
}
开发者ID:Karthikvb,项目名称:15640_projects,代码行数:13,代码来源:promote.go
示例6: stringToRuneSlice
func (v *LLVMValue) stringToRuneSlice() *LLVMValue {
c := v.compiler
strtorunes := c.NamedFunction("runtime.strtorunes", "func(_string) slice")
_string := strtorunes.Type().ElementType().ParamTypes()[0]
args := []llvm.Value{c.coerceString(v.LLVMValue(), _string)}
result := c.builder.CreateCall(strtorunes, args, "")
runeslice := types.NewSlice(types.Typ[types.Rune])
result = c.coerceSlice(result, c.types.ToLLVM(runeslice))
return c.NewValue(result, runeslice)
}
开发者ID:payco,项目名称:llgo,代码行数:10,代码来源:strings.go
示例7: parseArrayOrSliceType
// ArrayOrSliceType = "[" [ int ] "]" Type .
func (p *parser) parseArrayOrSliceType(pkg *types.Package) types.Type {
p.expect('[')
if p.tok == ']' {
p.next()
return types.NewSlice(p.parseType(pkg))
}
n := p.parseInt()
p.expect(']')
return types.NewArray(p.parseType(pkg), n)
}
开发者ID:hackrole,项目名称:daily-program,代码行数:12,代码来源:parser.go
示例8: arrayRuntimeType
func (tm *TypeMap) arrayRuntimeType(a *types.Array) (global, ptr llvm.Value) {
rtype := tm.makeRtype(a, reflect.Array)
elemRuntimeType := tm.ToRuntime(a.Elem())
sliceRuntimeType := tm.ToRuntime(types.NewSlice(a.Elem()))
uintptrlen := llvm.ConstInt(tm.target.IntPtrType(), uint64(a.Len()), false)
arrayType := llvm.ConstNull(tm.runtime.arrayType.llvm)
arrayType = llvm.ConstInsertValue(arrayType, rtype, []uint32{0})
arrayType = llvm.ConstInsertValue(arrayType, elemRuntimeType, []uint32{1})
arrayType = llvm.ConstInsertValue(arrayType, sliceRuntimeType, []uint32{2})
arrayType = llvm.ConstInsertValue(arrayType, uintptrlen, []uint32{3})
return tm.makeRuntimeTypeGlobal(arrayType, typeString(a))
}
开发者ID:minux,项目名称:llgo,代码行数:12,代码来源:typemap.go
示例9: solve
func (c *reflectSliceOfConstraint) solve(a *analysis, _ *node, delta nodeset) {
changed := false
for tObj := range delta {
T := a.rtypeTaggedValue(tObj)
if a.addLabel(c.result, a.makeRtype(types.NewSlice(T))) {
changed = true
}
}
if changed {
a.addWork(c.result)
}
}
开发者ID:ufo22940268,项目名称:two-server-others,代码行数:13,代码来源:reflect.go
示例10: createParams
// createParams creates parameters for bridge method fn based on its Signature.
func createParams(fn *Function) {
var last *Parameter
tparams := fn.Signature.Params()
for i, n := 0, tparams.Len(); i < n; i++ {
p := tparams.At(i)
name := p.Name()
if name == "" {
name = fmt.Sprintf("arg%d", i)
}
last = fn.addParam(name, p.Type())
}
if fn.Signature.IsVariadic() {
last.Type_ = types.NewSlice(last.Type_)
}
}
开发者ID:pombredanne,项目名称:go.tools,代码行数:16,代码来源:promote.go
示例11: parseArrayOrSliceType
// ArrayOrSliceType = "[" [ int ] "]" Type .
func (p *parser) parseArrayOrSliceType(pkg *types.Package) types.Type {
p.expect('[')
if p.tok == ']' {
p.next()
return types.NewSlice(p.parseType(pkg))
}
lit := p.expect(scanner.Int)
n, err := strconv.ParseInt(lit, 10, 0)
if err != nil {
p.error(err)
}
p.expect(']')
return types.NewArray(p.parseType(pkg), n)
}
开发者ID:Karthikvb,项目名称:15640_projects,代码行数:16,代码来源:parser.go
示例12: parseParam
// Param = Name ["..."] Type .
func (p *parser) parseParam(pkg *types.Package) (param *types.Var, isVariadic bool) {
name := p.parseName()
if p.tok == '.' {
p.next()
p.expect('.')
p.expect('.')
isVariadic = true
}
typ := p.parseType(pkg)
if isVariadic {
typ = types.NewSlice(typ)
}
param = types.NewParam(token.NoPos, pkg, name, typ)
return
}
开发者ID:Karthikvb,项目名称:15640_projects,代码行数:16,代码来源:parser.go
示例13: parseType
// Type =
// BasicType | TypeName | ArrayType | SliceType | StructType |
// PointerType | FuncType | InterfaceType | MapType | ChanType |
// "(" Type ")" .
//
// BasicType = ident .
// TypeName = ExportedName .
// SliceType = "[" "]" Type .
// PointerType = "*" Type .
// FuncType = "func" Signature .
//
func (p *parser) parseType() types.Type {
switch p.tok {
case scanner.Ident:
switch p.lit {
default:
return p.parseBasicType()
case "struct":
return p.parseStructType()
case "func":
// FuncType
p.next()
return p.parseSignature(nil)
case "interface":
return p.parseInterfaceType()
case "map":
return p.parseMapType()
case "chan":
return p.parseChanType()
}
case '@':
// TypeName
pkg, name := p.parseExportedName()
return declTypeName(pkg, name).Type()
case '[':
p.next() // look ahead
if p.tok == ']' {
// SliceType
p.next()
return types.NewSlice(p.parseType())
}
return p.parseArrayType()
case '*':
// PointerType
p.next()
return types.NewPointer(p.parseType())
case '<':
return p.parseChanType()
case '(':
// "(" Type ")"
p.next()
typ := p.parseType()
p.expect(')')
return typ
}
p.errorf("expected type, got %s (%q)", scanner.TokenString(p.tok), p.lit)
return nil
}
开发者ID:ufo22940268,项目名称:two-server-others,代码行数:58,代码来源:gcimporter.go
示例14: makeLiteralSlice
// makeLiteralSlice allocates a new slice, storing in it the provided elements.
func (c *compiler) makeLiteralSlice(v []llvm.Value, elttyp types.Type) llvm.Value {
n := llvm.ConstInt(c.types.inttype, uint64(len(v)), false)
eltType := c.types.ToLLVM(elttyp)
arrayType := llvm.ArrayType(eltType, len(v))
mem := c.createMalloc(llvm.SizeOf(arrayType))
mem = c.builder.CreateIntToPtr(mem, llvm.PointerType(eltType, 0), "")
for i, value := range v {
indices := []llvm.Value{llvm.ConstInt(llvm.Int32Type(), uint64(i), false)}
ep := c.builder.CreateGEP(mem, indices, "")
c.builder.CreateStore(value, ep)
}
slicetyp := types.NewSlice(elttyp)
struct_ := llvm.Undef(c.types.ToLLVM(slicetyp))
struct_ = c.builder.CreateInsertValue(struct_, mem, 0, "")
struct_ = c.builder.CreateInsertValue(struct_, n, 1, "")
struct_ = c.builder.CreateInsertValue(struct_, n, 2, "")
return struct_
}
开发者ID:hzmangel,项目名称:llgo,代码行数:19,代码来源:slice.go
示例15: 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
示例16: 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
示例17: buildFunction
// buildFunction takes a function Value, a list of parameters, and a body,
// and generates code for the function.
func (c *compiler) buildFunction(f *LLVMValue, context, params, results *types.Tuple, body *ast.BlockStmt, isvariadic bool) {
if currblock := c.builder.GetInsertBlock(); !currblock.IsNil() {
defer c.builder.SetInsertPointAtEnd(currblock)
}
llvm_fn := llvm.ConstExtractValue(f.LLVMValue(), []uint32{0})
entry := llvm.AddBasicBlock(llvm_fn, "entry")
c.builder.SetInsertPointAtEnd(entry)
// For closures, context is the captured context values.
var paramoffset int
if context != nil {
paramoffset++
// Store the existing values. We're going to temporarily
// replace the values with offsets into the context param.
oldvalues := make([]*LLVMValue, context.Len())
for i := range oldvalues {
v := context.At(i)
oldvalues[i] = c.objectdata[v].Value
}
defer func() {
for i := range oldvalues {
v := context.At(i)
c.objectdata[v].Value = oldvalues[i]
}
}()
// The context parameter is a pointer to a struct
// whose elements are pointers to captured values.
arg0 := llvm_fn.Param(0)
for i := range oldvalues {
v := context.At(i)
argptr := c.builder.CreateStructGEP(arg0, i, "")
argptr = c.builder.CreateLoad(argptr, "")
ptrtyp := oldvalues[i].pointer.Type()
newvalue := c.NewValue(argptr, ptrtyp)
c.objectdata[v].Value = newvalue.makePointee()
}
}
// Bind receiver, arguments and return values to their
// identifiers/objects. We'll store each parameter on the stack so
// they're addressable.
nparams := int(params.Len())
for i := 0; i < nparams; i++ {
v := params.At(i)
name := v.Name()
if name != "" {
value := llvm_fn.Param(i + paramoffset)
typ := v.Type()
if isvariadic && i == nparams-1 {
typ = types.NewSlice(typ)
}
stackvalue := c.builder.CreateAlloca(c.types.ToLLVM(typ), name)
c.builder.CreateStore(value, stackvalue)
ptrvalue := c.NewValue(stackvalue, types.NewPointer(typ))
stackvar := ptrvalue.makePointee()
stackvar.stack = f
c.objectdata[v].Value = stackvar
}
}
funcstate := &function{LLVMValue: f, results: results}
c.functions.push(funcstate)
hasdefer := hasDefer(funcstate, body)
// Allocate space on the stack for named results.
results.ForEach(func(v *types.Var) {
name := v.Name()
allocstack := name != ""
if !allocstack && hasdefer {
c.objectdata[v] = &ObjectData{}
allocstack = true
}
if allocstack {
typ := v.Type()
llvmtyp := c.types.ToLLVM(typ)
stackptr := c.builder.CreateAlloca(llvmtyp, name)
c.builder.CreateStore(llvm.ConstNull(llvmtyp), stackptr)
ptrvalue := c.NewValue(stackptr, types.NewPointer(typ))
stackvar := ptrvalue.makePointee()
stackvar.stack = f
c.objectdata[v].Value = stackvar
}
})
// Create the function body.
if hasdefer {
c.makeDeferBlock(funcstate, body)
}
c.VisitBlockStmt(body, false)
c.functions.pop()
// If the last instruction in the function is not a terminator, then
// we either have unreachable code or a missing optional return statement
// (the latter case is allowable only for functions without results).
//
// Use GetInsertBlock rather than LastBasicBlock, since the
//.........这里部分代码省略.........
开发者ID:hzmangel,项目名称:llgo,代码行数:101,代码来源:decl.go
示例18: Convert
func (v *LLVMValue) Convert(dsttyp types.Type) Value {
b := v.compiler.builder
// If it's a stack allocated value, we'll want to compare the
// value type, not the pointer type.
srctyp := v.typ
// Get the underlying type, if any.
origdsttyp := dsttyp
dsttyp = dsttyp.Underlying()
srctyp = srctyp.Underlying()
// Identical (underlying) types? Just swap in the destination type.
if types.IsIdentical(srctyp, dsttyp) {
// A method converted to a function type without the
// receiver is where we convert a "method value" into a
// function.
if srctyp, ok := srctyp.(*types.Signature); ok && srctyp.Recv() != nil {
if dsttyp, ok := dsttyp.(*types.Signature); ok && dsttyp.Recv() == nil {
return v.convertMethodValue(origdsttyp)
}
}
// TODO avoid load here by reusing pointer value, if exists.
return v.compiler.NewValue(v.LLVMValue(), origdsttyp)
}
// Both pointer types with identical underlying types? Same as above.
if srctyp, ok := srctyp.(*types.Pointer); ok {
if dsttyp, ok := dsttyp.(*types.Pointer); ok {
srctyp := srctyp.Elem().Underlying()
dsttyp := dsttyp.Elem().Underlying()
if types.IsIdentical(srctyp, dsttyp) {
return v.compiler.NewValue(v.LLVMValue(), origdsttyp)
}
}
}
// Convert from an interface type.
if _, isinterface := srctyp.(*types.Interface); isinterface {
if interface_, isinterface := dsttyp.(*types.Interface); isinterface {
return v.mustConvertI2I(interface_)
} else {
return v.mustConvertI2V(origdsttyp)
}
}
// Converting to an interface type.
if interface_, isinterface := dsttyp.(*types.Interface); isinterface {
return v.convertV2I(interface_)
}
byteslice := types.NewSlice(types.Typ[types.Byte])
runeslice := types.NewSlice(types.Typ[types.Rune])
// string ->
if isString(srctyp) {
// (untyped) string -> string
// XXX should untyped strings be able to escape go/types?
if isString(dsttyp) {
return v.compiler.NewValue(v.LLVMValue(), origdsttyp)
}
// string -> []byte
if types.IsIdentical(dsttyp, byteslice) {
c := v.compiler
value := v.LLVMValue()
strdata := c.builder.CreateExtractValue(value, 0, "")
strlen := c.builder.CreateExtractValue(value, 1, "")
// Data must be copied, to prevent changes in
// the byte slice from mutating the string.
newdata := c.builder.CreateArrayMalloc(strdata.Type().ElementType(), strlen, "")
memcpy := c.NamedFunction("runtime.memcpy", "func(uintptr, uintptr, uintptr)")
c.builder.CreateCall(memcpy, []llvm.Value{
c.builder.CreatePtrToInt(newdata, c.target.IntPtrType(), ""),
c.builder.CreatePtrToInt(strdata, c.target.IntPtrType(), ""),
strlen,
}, "")
strdata = newdata
struct_ := llvm.Undef(c.types.ToLLVM(byteslice))
struct_ = c.builder.CreateInsertValue(struct_, strdata, 0, "")
struct_ = c.builder.CreateInsertValue(struct_, strlen, 1, "")
struct_ = c.builder.CreateInsertValue(struct_, strlen, 2, "")
return c.NewValue(struct_, byteslice)
}
// string -> []rune
if types.IsIdentical(dsttyp, runeslice) {
return v.stringToRuneSlice()
}
}
// []byte -> string
if types.IsIdentical(srctyp, byteslice) && isString(dsttyp) {
c := v.compiler
value := v.LLVMValue()
data := c.builder.CreateExtractValue(value, 0, "")
len := c.builder.CreateExtractValue(value, 1, "")
//.........这里部分代码省略.........
开发者ID:qioixiy,项目名称:llgo,代码行数:101,代码来源:value.go
示例19: 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.
//
func (info *PackageInfo) BuiltinCallSignature(e *ast.CallExpr) *types.Signature {
var params []*types.Var
var isVariadic bool
switch builtin := unparen(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(tslice, tslice...) []T
// append(byteslice, "foo"...) []byte
t1 = info.TypeOf(e.Args[1]) // no conversion
} else {
// append([]T, x, y, z) []T
t1 = t0.Underlying()
isVariadic = true
}
params = append(params,
types.NewVar(token.NoPos, nil, "", t0),
types.NewVar(token.NoPos, 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(token.NoPos, nil, "", info.TypeOf(e.Args[0])),
types.NewVar(token.NoPos, nil, "", types.NewSlice(tEface)))
case "close":
params = append(params, types.NewVar(token.NoPos, 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(token.NoPos, 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(token.NoPos, nil, "", tmap),
types.NewVar(token.NoPos, nil, "", tkey))
case "len", "cap":
params = append(params, types.NewVar(token.NoPos, 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(token.NoPos, 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(token.NoPos, nil, "", argType)
params = append(params, v, v)
case "panic":
params = append(params, types.NewVar(token.NoPos, nil, "", tEface))
case "recover":
// no params
//.........这里部分代码省略.........
开发者ID:nagyistge,项目名称:hm-workspace,代码行数:101,代码来源:pkginfo.go
示例20: translateConversion
func (c *funcContext) translateConversion(expr ast.Expr, desiredType types.Type) *expression {
exprType := c.p.info.Types[expr].Type
if types.Identical(exprType, desiredType) {
return c.translateExpr(expr)
}
if c.p.pkg.Path() == "reflect" {
if call, isCall := expr.(*ast.CallExpr); isCall && types.Identical(c.p.info.Types[call.Fun].Type, types.Typ[types.UnsafePointer]) {
if ptr, isPtr := desiredType.(*types.Pointer); isPtr {
if named, isNamed := ptr.Elem().(*types.Named); isNamed {
switch named.Obj().Name() {
case "arrayType", "chanType", "funcType", "interfaceType", "mapType", "ptrType", "sliceType", "structType":
return c.formatExpr("%e.%s", call.Args[0], named.Obj().Name()) // unsafe conversion
default:
return c.translateExpr(expr)
}
}
}
}
}
switch t := desiredType.Underlying().(type) {
case *types.Basic:
switch {
case t.Info()&types.IsInteger != 0:
basicExprType := exprType.Underlying().(*types.Basic)
switch {
case is64Bit(t):
if !is64Bit(basicExprType) {
if basicExprType.Kind() == types.Uintptr { // this might be an Object returned from reflect.Value.Pointer()
return c.formatExpr("new %1s(0, %2e.constructor === Number ? %2e : 1)", c.typeName(desiredType), expr)
}
return c.formatExpr("new %s(0, %e)", c.typeName(desiredType), expr)
}
return c.formatExpr("new %1s(%2h, %2l)", c.typeName(desiredType), expr)
case is64Bit(basicExprType):
if t.Info()&types.IsUnsigned == 0 && basicExprType.Info()&types.IsUnsigned == 0 {
return c.fixNumber(c.formatParenExpr("%1l + ((%1h >> 31) * 4294967296)", expr), t)
}
return c.fixNumber(c.formatExpr("%s.$low", c.translateExpr(expr)), t)
case basicExprType.Info()&types.IsFloat != 0:
return c.formatParenExpr("%e >> 0", expr)
case types.Identical(exprType, types.Typ[types.UnsafePointer]):
return c.translateExpr(expr)
default:
return c.fixNumber(c.translateExpr(expr), t)
}
case t.Info()&types.IsFloat != 0:
if t.Kind() == types.Float64 && exprType.Underlying().(*types.Basic).Kind() == types.Float32 {
return c.formatExpr("$coerceFloat32(%f)", expr)
}
return c.formatExpr("%f", expr)
case t.Info()&types.IsComplex != 0:
return c.formatExpr("new %1s(%2r, %2i)", c.typeName(desiredType), expr)
case t.Info()&types.IsString != 0:
value := c.translateExpr(expr)
switch et := exprType.Underlying().(type) {
case *types.Basic:
if is64Bit(et) {
value = c.formatExpr("%s.$low", value)
}
if et.Info()&types.IsNumeric != 0 {
return c.formatExpr("$encodeRune(%s)", value)
}
return value
case *types.Slice:
if types.Identical(et.Elem().Underlying(), types.Typ[types.Rune]) {
return c.formatExpr("$runesToString(%s)", value)
}
return c.formatExpr("$bytesToString(%s)", value)
default:
panic(fmt.Sprintf("Unhandled conversion: %v\n", et))
}
case t.Kind() == types.UnsafePointer:
if unary, isUnary := expr.(*ast.UnaryExpr); isUnary && unary.Op == token.AND {
if indexExpr, isIndexExpr := unary.X.(*ast.IndexExpr); isIndexExpr {
return c.formatExpr("$sliceToArray(%s)", c.translateConversionToSlice(indexExpr.X, types.NewSlice(types.Typ[types.Uint8])))
}
if ident, isIdent := unary.X.(*ast.Ident); isIdent && ident.Name == "_zero" {
return c.formatExpr("new Uint8Array(0)")
}
}
if ptr, isPtr := c.p.info.Types[expr].Type.(*types.Pointer); c.p.pkg.Path() == "syscall" && isPtr {
if s, isStruct := ptr.Elem().Underlying().(*types.Struct); isStruct {
array := c.newVariable("_array")
target := c.newVariable("_struct")
c.Printf("%s = new Uint8Array(%d);", array, sizes32.Sizeof(s))
c.Delayed(func() {
c.Printf("%s = %s, %s;", target, c.translateExpr(expr), c.loadStruct(array, target, s))
})
return c.formatExpr("%s", array)
}
}
if call, ok := expr.(*ast.CallExpr); ok {
if id, ok := call.Fun.(*ast.Ident); ok && id.Name == "new" {
return c.formatExpr("new Uint8Array(%d)", int(sizes32.Sizeof(c.p.info.Types[call.Args[0]].Type)))
}
}
}
//.........这里部分代码省略.........
开发者ID:nvdnkpr,项目名称:gopherjs,代码行数:101,代码来源:expressions.go
注:本文中的code/google/com/p/go/tools/go/types.NewSlice函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论