本文整理汇总了Golang中go/types.NewTuple函数的典型用法代码示例。如果您正苦于以下问题:Golang NewTuple函数的具体用法?Golang NewTuple怎么用?Golang NewTuple使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewTuple函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: parseSignature
// Signature = Parameters [ Result ] .
// Result = Type | Parameters .
//
func (p *parser) parseSignature(recv *types.Var) *types.Signature {
params, isVariadic := p.parseParameters()
// optional result type
var results []*types.Var
if p.tok == '(' {
var variadic bool
results, variadic = p.parseParameters()
if variadic {
p.error("... not permitted on result type")
}
}
return types.NewSignature(recv, types.NewTuple(params...), types.NewTuple(results...), isVariadic)
}
示例2: makeLen
// makeLen returns the len builtin specialized to type func(T)int.
func makeLen(T types.Type) *Builtin {
lenParams := types.NewTuple(anonVar(T))
return &Builtin{
name: "len",
sig: types.NewSignature(nil, lenParams, lenResults, false),
}
}
示例3: tuple
func (p *importer) tuple() *types.Tuple {
vars := make([]*types.Var, p.int())
for i := range vars {
vars[i] = p.param()
}
return types.NewTuple(vars...)
}
示例4: parseResultList
// ResultList = Type | ParamList .
func (p *parser) parseResultList(pkg *types.Package) *types.Tuple {
switch p.tok {
case '<':
return types.NewTuple(types.NewParam(token.NoPos, pkg, "", p.parseType(pkg)))
case '(':
params, _ := p.parseParamList(pkg)
return params
default:
return nil
}
}
示例5: 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(
newVar("value", t),
varOk,
))
return f.emit(a)
}
示例6: paramList
func (p *importer) paramList() (*types.Tuple, bool) {
n := p.int()
if n == 0 {
return nil, false
}
// negative length indicates unnamed parameters
named := true
if n < 0 {
n = -n
named = false
}
// n > 0
params := make([]*types.Var, n)
isddd := false
for i := range params {
params[i], isddd = p.param(named)
}
return types.NewTuple(params...), isddd
}
示例7: parseParamList
// ParamList = "(" [ { Parameter "," } Parameter ] ")" .
func (p *parser) parseParamList(pkg *types.Package) (*types.Tuple, bool) {
var list []*types.Var
isVariadic := false
p.expect('(')
for p.tok != ')' && p.tok != scanner.EOF {
if len(list) > 0 {
p.expect(',')
}
par, variadic := p.parseParam(pkg)
list = append(list, par)
if variadic {
if isVariadic {
p.error("... not on final argument")
}
isVariadic = true
}
}
p.expect(')')
return types.NewTuple(list...), isVariadic
}
示例8: assocMethods
func (p *exporter) assocMethods(named *types.Named) {
// Sort methods (for determinism).
var methods []*types.Func
for i := 0; i < named.NumMethods(); i++ {
methods = append(methods, named.Method(i))
}
sort.Sort(methodsByName(methods))
p.int(len(methods))
if trace && methods != nil {
p.tracef("associated methods {>\n")
}
for i, m := range methods {
if trace && i > 0 {
p.tracef("\n")
}
p.pos(m)
name := m.Name()
p.string(name)
if !exported(name) {
p.pkg(m.Pkg(), false)
}
sig := m.Type().(*types.Signature)
p.paramList(types.NewTuple(sig.Recv()), false)
p.paramList(sig.Params(), sig.Variadic())
p.paramList(sig.Results(), false)
p.int(0) // dummy value for go:nointerface pragma - ignored by importer
}
if trace && methods != nil {
p.tracef("<\n} ")
}
}
示例9: makeWrapper
// makeWrapper returns a synthetic method that delegates to the
// declared method denoted by meth.Obj(), first performing any
// necessary pointer indirections or field selections implied by meth.
//
// The resulting method's receiver type is meth.Recv().
//
// This function is versatile but quite subtle! Consider the
// following axes of variation when making changes:
// - optional receiver indirection
// - optional implicit field selections
// - meth.Obj() may denote a concrete or an interface method
// - the result may be a thunk or a wrapper.
//
// EXCLUSIVE_LOCKS_REQUIRED(prog.methodsMu)
//
func makeWrapper(prog *Program, sel *types.Selection) *Function {
obj := sel.Obj().(*types.Func) // the declared function
sig := sel.Type().(*types.Signature) // type of this wrapper
var recv *types.Var // wrapper's receiver or thunk's params[0]
name := obj.Name()
var description string
var start int // first regular param
if sel.Kind() == types.MethodExpr {
name += "$thunk"
description = "thunk"
recv = sig.Params().At(0)
start = 1
} else {
description = "wrapper"
recv = sig.Recv()
}
description = fmt.Sprintf("%s for %s", description, sel.Obj())
if prog.mode&LogSource != 0 {
defer logStack("make %s to (%s)", description, recv.Type())()
}
fn := &Function{
name: name,
method: sel,
object: obj,
Signature: sig,
Synthetic: description,
Prog: prog,
pos: obj.Pos(),
}
fn.startBody()
fn.addSpilledParam(recv)
createParams(fn, start)
indices := sel.Index()
var v Value = fn.Locals[0] // spilled receiver
if isPointer(sel.Recv()) {
v = emitLoad(fn, v)
// For simple indirection wrappers, perform an informative nil-check:
// "value method (T).f called using nil *T pointer"
if len(indices) == 1 && !isPointer(recvType(obj)) {
var c Call
c.Call.Value = &Builtin{
name: "ssa:wrapnilchk",
sig: types.NewSignature(nil,
types.NewTuple(anonVar(sel.Recv()), anonVar(tString), anonVar(tString)),
types.NewTuple(anonVar(sel.Recv())), false),
}
c.Call.Args = []Value{
v,
stringConst(deref(sel.Recv()).String()),
stringConst(sel.Obj().Name()),
}
c.setType(v.Type())
v = fn.emit(&c)
}
}
// 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).
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 r := recvType(obj); !isInterface(r) { // concrete method
if !isPointer(r) {
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)
//.........这里部分代码省略.........
示例10: translateExpr
//.........这里部分代码省略.........
switch x := astutil.RemoveParens(e.X).(type) {
case *ast.CompositeLit:
return c.formatExpr("$newDataPointer(%e, %s)", x, c.typeName(c.p.TypeOf(e)))
case *ast.Ident:
obj := c.p.Uses[x].(*types.Var)
if c.p.escapingVars[obj] {
return c.formatExpr("(%1s.$ptr || (%1s.$ptr = new %2s(function() { return this.$target[0]; }, function($v) { this.$target[0] = $v; }, %1s)))", c.p.objectNames[obj], c.typeName(exprType))
}
return c.formatExpr(`(%1s || (%1s = new %2s(function() { return %3s; }, function($v) { %4s })))`, c.varPtrName(obj), c.typeName(exprType), c.objectName(obj), c.translateAssign(x, c.newIdent("$v", exprType), false))
case *ast.SelectorExpr:
sel, ok := c.p.SelectionOf(x)
if !ok {
// qualified identifier
obj := c.p.Uses[x.Sel].(*types.Var)
return c.formatExpr(`(%1s || (%1s = new %2s(function() { return %3s; }, function($v) { %4s })))`, c.varPtrName(obj), c.typeName(exprType), c.objectName(obj), c.translateAssign(x, c.newIdent("$v", exprType), false))
}
newSel := &ast.SelectorExpr{X: c.newIdent("this.$target", c.p.TypeOf(x.X)), Sel: x.Sel}
c.setType(newSel, exprType)
c.p.additionalSelections[newSel] = sel
return c.formatExpr("(%1e.$ptr_%2s || (%1e.$ptr_%2s = new %3s(function() { return %4e; }, function($v) { %5s }, %1e)))", x.X, x.Sel.Name, c.typeName(exprType), newSel, c.translateAssign(newSel, c.newIdent("$v", exprType), false))
case *ast.IndexExpr:
if _, ok := c.p.TypeOf(x.X).Underlying().(*types.Slice); ok {
return c.formatExpr("$indexPtr(%1e.$array, %1e.$offset + %2e, %3s)", x.X, x.Index, c.typeName(exprType))
}
return c.formatExpr("$indexPtr(%e, %e, %s)", x.X, x.Index, c.typeName(exprType))
case *ast.StarExpr:
return c.translateExpr(x.X)
default:
panic(fmt.Sprintf("Unhandled: %T\n", x))
}
case token.ARROW:
call := &ast.CallExpr{
Fun: c.newIdent("$recv", types.NewSignature(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 isComplex(basic):
return c.formatExpr("new %1s(-%2r, -%2i)", c.typeName(t), e.X)
case isUnsigned(basic):
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:
return c.formatExpr("!%e", e.X)
default:
示例11: init
"comma-separated list of functions whose results must be used")
var unusedStringMethodsFlag = flag.String("unusedstringmethods",
"Error,String",
"comma-separated list of names of methods of type func() string whose results must be used")
func init() {
register("unusedresult",
"check for unused result of calls to functions in -unusedfuncs list and methods in -unusedstringmethods list",
checkUnusedResult,
exprStmt)
}
// func() string
var sigNoArgsStringResult = types.NewSignature(nil, nil, nil,
types.NewTuple(types.NewVar(token.NoPos, nil, "", types.Typ[types.String])),
false)
var unusedFuncs = make(map[string]bool)
var unusedStringMethods = make(map[string]bool)
func initUnusedFlags() {
commaSplit := func(s string, m map[string]bool) {
if s != "" {
for _, name := range strings.Split(s, ",") {
if len(name) == 0 {
flag.Usage()
}
m[name] = true
}
}
示例12: translateStmt
//.........这里部分代码省略.........
iVar := c.newVariable("_i")
c.Printf("%s = 0;", iVar)
c.translateLoopingStmt(func() string { return iVar + " < " + length }, s.Body, func() {
if !isBlank(s.Key) {
c.Printf("%s", c.translateAssign(s.Key, c.newIdent(iVar, types.Typ[types.Int]), s.Tok == token.DEFINE))
}
if !isBlank(s.Value) {
c.Printf("%s", c.translateAssign(s.Value, c.setType(&ast.IndexExpr{
X: c.newIdent(refVar, t),
Index: c.newIdent(iVar, types.Typ[types.Int]),
}, elemType), s.Tok == token.DEFINE))
}
}, func() {
c.Printf("%s++;", iVar)
}, label, c.Flattened[s])
case *types.Chan:
okVar := c.newIdent(c.newVariable("_ok"), types.Typ[types.Bool])
key := s.Key
tok := s.Tok
if key == nil {
key = ast.NewIdent("_")
tok = token.ASSIGN
}
forStmt := &ast.ForStmt{
Body: &ast.BlockStmt{
List: []ast.Stmt{
&ast.AssignStmt{
Lhs: []ast.Expr{
key,
okVar,
},
Rhs: []ast.Expr{
c.setType(&ast.UnaryExpr{X: c.newIdent(refVar, t), Op: token.ARROW}, types.NewTuple(types.NewVar(0, nil, "", t.Elem()), types.NewVar(0, nil, "", types.Typ[types.Bool]))),
},
Tok: tok,
},
&ast.IfStmt{
Cond: &ast.UnaryExpr{X: okVar, Op: token.NOT},
Body: &ast.BlockStmt{List: []ast.Stmt{&ast.BranchStmt{Tok: token.BREAK}}},
},
s.Body,
},
},
}
c.Flattened[forStmt] = true
c.translateStmt(forStmt, label)
default:
panic("")
}
case *ast.BranchStmt:
normalLabel := ""
blockingLabel := ""
data := c.flowDatas[nil]
if s.Label != nil {
normalLabel = " " + s.Label.Name
blockingLabel = " s" // use explicit label "s", because surrounding loop may not be flattened
data = c.flowDatas[c.p.Uses[s.Label].(*types.Label)]
}
switch s.Tok {
case token.BREAK:
c.PrintCond(data.endCase == 0, fmt.Sprintf("break%s;", normalLabel), fmt.Sprintf("$s = %d; continue%s;", data.endCase, blockingLabel))
case token.CONTINUE:
data.postStmt()
示例13: logStack
func logStack(format string, args ...interface{}) func() {
msg := fmt.Sprintf(format, args...)
io.WriteString(os.Stderr, msg)
io.WriteString(os.Stderr, "\n")
return func() {
io.WriteString(os.Stderr, msg)
io.WriteString(os.Stderr, " end\n")
}
}
// newVar creates a 'var' for use in a types.Tuple.
func newVar(name string, typ types.Type) *types.Var {
return types.NewParam(token.NoPos, nil, name, typ)
}
// anonVar creates an anonymous 'var' for use in a types.Tuple.
func anonVar(typ types.Type) *types.Var {
return newVar("", typ)
}
var lenResults = types.NewTuple(anonVar(tInt))
// makeLen returns the len builtin specialized to type func(T)int.
func makeLen(T types.Type) *Builtin {
lenParams := types.NewTuple(anonVar(T))
return &Builtin{
name: "len",
sig: types.NewSignature(nil, lenParams, lenResults, false),
}
}
示例14: simplifyStmt
//.........这里部分代码省略.........
var newS ast.Stmt
switch t := c.info.TypeOf(s.X).Underlying().(type) {
case *types.Chan:
key := s.Key
tok := s.Tok
if key == nil {
key = ast.NewIdent("_")
tok = token.DEFINE
}
okVar := c.newIdent(types.Typ[types.Bool])
if s.Tok == token.ASSIGN {
*stmts = append(*stmts, &ast.DeclStmt{
Decl: &ast.GenDecl{
Tok: token.VAR,
Specs: []ast.Spec{&ast.ValueSpec{
Names: []*ast.Ident{okVar},
Type: ast.NewIdent("bool"),
}},
},
})
}
newS = &ast.ForStmt{
For: s.For,
Body: &ast.BlockStmt{
Lbrace: s.Body.Lbrace,
List: append([]ast.Stmt{
&ast.AssignStmt{
Lhs: []ast.Expr{key, okVar},
TokPos: s.TokPos,
Tok: tok,
Rhs: []ast.Expr{c.setType(&ast.UnaryExpr{
Op: token.ARROW,
X: c.newVar(stmts, s.X),
}, types.NewTuple(
types.NewVar(token.NoPos, nil, "", t.Elem()),
types.NewVar(token.NoPos, nil, "", types.Typ[types.Bool]),
))},
},
&ast.IfStmt{
Cond: c.setType(&ast.UnaryExpr{
Op: token.NOT,
X: okVar,
}, types.Typ[types.Bool]),
Body: &ast.BlockStmt{
List: []ast.Stmt{
&ast.BranchStmt{Tok: token.BREAK},
},
},
},
}, c.simplifyStmtList(s.Body.List)...),
Rbrace: s.Body.Rbrace,
},
}
default:
newS = &ast.RangeStmt{
For: s.For,
Key: s.Key,
Value: s.Value,
TokPos: s.TokPos,
Tok: s.Tok,
X: s.X,
Body: c.simplifyBlock(s.Body),
}
}
c.info.Scopes[newS] = c.info.Scopes[s]
示例15: CreateTestMainPackage
// CreateTestMainPackage creates and returns a synthetic "main"
// package that runs all the tests of the supplied packages, similar
// to the one that would be created by the 'go test' tool.
//
// It returns nil if the program contains no tests.
//
func (prog *Program) CreateTestMainPackage(pkgs ...*Package) *Package {
pkgs, tests, benchmarks, examples := FindTests(pkgs)
if len(pkgs) == 0 {
return nil
}
testmain := &Package{
Prog: prog,
Members: make(map[string]Member),
values: make(map[types.Object]Value),
Pkg: types.NewPackage("test$main", "main"),
}
// Build package's init function.
init := &Function{
name: "init",
Signature: new(types.Signature),
Synthetic: "package initializer",
Pkg: testmain,
Prog: prog,
}
init.startBody()
if testMainStartBodyHook != nil {
testMainStartBodyHook(init)
}
// Initialize packages to test.
var pkgpaths []string
for _, pkg := range pkgs {
var v Call
v.Call.Value = pkg.init
v.setType(types.NewTuple())
init.emit(&v)
pkgpaths = append(pkgpaths, pkg.Pkg.Path())
}
sort.Strings(pkgpaths)
init.emit(new(Return))
init.finishBody()
testmain.init = init
testmain.Pkg.MarkComplete()
testmain.Members[init.name] = init
// For debugging convenience, define an unexported const
// that enumerates the packages.
packagesConst := types.NewConst(token.NoPos, testmain.Pkg, "packages", tString,
exact.MakeString(strings.Join(pkgpaths, " ")))
memberFromObject(testmain, packagesConst, nil)
// Create main *types.Func and *ssa.Function
mainFunc := types.NewFunc(token.NoPos, testmain.Pkg, "main", new(types.Signature))
memberFromObject(testmain, mainFunc, nil)
main := testmain.Func("main")
main.Synthetic = "test main function"
main.startBody()
if testMainStartBodyHook != nil {
testMainStartBodyHook(main)
}
if testingPkg := prog.ImportedPackage("testing"); testingPkg != nil {
testingMain := testingPkg.Func("Main")
testingMainParams := testingMain.Signature.Params()
// The generated code is as if compiled from this:
//
// func main() {
// match := func(_, _ string) (bool, error) { return true, nil }
// tests := []testing.InternalTest{{"TestFoo", TestFoo}, ...}
// benchmarks := []testing.InternalBenchmark{...}
// examples := []testing.InternalExample{...}
// testing.Main(match, tests, benchmarks, examples)
// }
matcher := &Function{
name: "matcher",
Signature: testingMainParams.At(0).Type().(*types.Signature),
Synthetic: "test matcher predicate",
parent: main,
Pkg: testmain,
Prog: prog,
}
main.AnonFuncs = append(main.AnonFuncs, matcher)
matcher.startBody()
matcher.emit(&Return{Results: []Value{vTrue, nilConst(types.Universe.Lookup("error").Type())}})
matcher.finishBody()
// Emit call: testing.Main(matcher, tests, benchmarks, examples).
var c Call
c.Call.Value = testingMain
c.Call.Args = []Value{
matcher,
//.........这里部分代码省略.........