本文整理汇总了Golang中go/constant.MakeBool函数的典型用法代码示例。如果您正苦于以下问题:Golang MakeBool函数的具体用法?Golang MakeBool怎么用?Golang MakeBool使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了MakeBool函数的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: evalIdent
// Evaluates identifier expressions
func (scope *EvalScope) evalIdent(node *ast.Ident) (*Variable, error) {
switch node.Name {
case "true", "false":
return newConstant(constant.MakeBool(node.Name == "true"), scope.Thread), nil
case "nil":
return nilVariable, nil
}
// try to interpret this as a local variable
v, err := scope.extractVarInfo(node.Name)
if err != nil {
origErr := err
// workaround: sometimes go inserts an entry for '&varname' instead of varname
v, err = scope.extractVarInfo("&" + node.Name)
if err != nil {
// if it's not a local variable then it could be a package variable w/o explicit package name
_, _, fn := scope.Thread.dbp.PCToLine(scope.PC)
if fn != nil {
if v, err := scope.packageVarAddr(fn.PackageName() + "." + node.Name); err == nil {
v.Name = node.Name
return v, nil
}
}
return nil, origErr
}
v = v.maybeDereference()
v.Name = node.Name
}
return v, nil
}
开发者ID:mattn,项目名称:delve,代码行数:31,代码来源:eval.go
示例2: zeroConst
// zeroConst returns a new "zero" constant of the specified type,
// which must not be an array or struct type: the zero values of
// aggregates are well-defined but cannot be represented by Const.
//
func zeroConst(t types.Type) *Const {
switch t := t.(type) {
case *types.Basic:
switch {
case t.Info()&types.IsBoolean != 0:
return NewConst(exact.MakeBool(false), t)
case t.Info()&types.IsNumeric != 0:
return NewConst(exact.MakeInt64(0), t)
case t.Info()&types.IsString != 0:
return NewConst(exact.MakeString(""), t)
case t.Kind() == types.UnsafePointer:
fallthrough
case t.Kind() == types.UntypedNil:
return nilConst(t)
default:
panic(fmt.Sprint("zeroConst for unexpected type:", t))
}
case *types.Pointer, *types.Slice, *types.Interface, *types.Chan, *types.Map, *types.Signature:
return nilConst(t)
case *types.Named:
return NewConst(zeroConst(t.Underlying()).Value, t)
case *types.Array, *types.Struct, *types.Tuple:
panic(fmt.Sprint("zeroConst applied to aggregate:", t))
}
panic(fmt.Sprint("zeroConst: unexpected ", t))
}
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:30,代码来源:const15.go
示例3: zeroValue
func (c *funcContext) zeroValue(ty types.Type) ast.Expr {
switch t := ty.Underlying().(type) {
case *types.Basic:
switch {
case isBoolean(t):
return c.newConst(ty, constant.MakeBool(false))
case isNumeric(t):
return c.newConst(ty, constant.MakeInt64(0))
case isString(t):
return c.newConst(ty, constant.MakeString(""))
case t.Kind() == types.UnsafePointer:
// fall through to "nil"
case t.Kind() == types.UntypedNil:
panic("Zero value for untyped nil.")
default:
panic(fmt.Sprintf("Unhandled basic type: %v\n", t))
}
case *types.Array, *types.Struct:
return c.setType(&ast.CompositeLit{}, ty)
case *types.Chan, *types.Interface, *types.Map, *types.Signature, *types.Slice, *types.Pointer:
// fall through to "nil"
default:
panic(fmt.Sprintf("Unhandled type: %T\n", t))
}
id := c.newIdent("nil", ty)
c.p.Uses[id] = nilObj
return id
}
开发者ID:snyderep,项目名称:pongish,代码行数:28,代码来源:utils.go
示例4: value
func (p *importer) value() constant.Value {
switch kind := constant.Kind(p.int()); kind {
case falseTag:
return constant.MakeBool(false)
case trueTag:
return constant.MakeBool(true)
case int64Tag:
return constant.MakeInt64(p.int64())
case floatTag:
return p.float()
case complexTag:
re := p.float()
im := p.float()
return constant.BinaryOp(re, token.ADD, constant.MakeImag(im))
case stringTag:
return constant.MakeString(p.string())
default:
panic(fmt.Sprintf("unexpected value kind %d", kind))
}
}
开发者ID:jacobsa,项目名称:go,代码行数:20,代码来源:bimport.go
示例5: value
func (p *importer) value() constant.Value {
switch tag := p.tagOrIndex(); tag {
case falseTag:
return constant.MakeBool(false)
case trueTag:
return constant.MakeBool(true)
case int64Tag:
return constant.MakeInt64(p.int64())
case floatTag:
return p.float()
case complexTag:
re := p.float()
im := p.float()
return constant.BinaryOp(re, token.ADD, constant.MakeImag(im))
case stringTag:
return constant.MakeString(p.string())
default:
panic(fmt.Sprintf("unexpected value tag %d", tag))
}
}
开发者ID:CyCoreSystems,项目名称:coreos-kubernetes,代码行数:20,代码来源:bimport.go
示例6: makeTag
func (c *simplifyContext) makeTag(stmts *[]ast.Stmt, tag ast.Expr, needsTag bool) ast.Expr {
if tag == nil {
id := ast.NewIdent("true")
c.info.Types[id] = types.TypeAndValue{Type: types.Typ[types.Bool], Value: constant.MakeBool(true)}
return id
}
if !needsTag {
*stmts = append(*stmts, simpleAssign(ast.NewIdent("_"), token.ASSIGN, tag))
return nil
}
return c.newVar(stmts, tag)
}
开发者ID:neelance,项目名称:astrewrite,代码行数:12,代码来源:simplify.go
示例7: comparison
func (check *Checker) comparison(x, y *operand, op token.Token) {
// spec: "In any comparison, the first operand must be assignable
// to the type of the second operand, or vice versa."
err := ""
if x.assignableTo(check.conf, y.typ, nil) || y.assignableTo(check.conf, x.typ, nil) {
defined := false
switch op {
case token.EQL, token.NEQ:
// spec: "The equality operators == and != apply to operands that are comparable."
defined = Comparable(x.typ) || x.isNil() && hasNil(y.typ) || y.isNil() && hasNil(x.typ)
case token.LSS, token.LEQ, token.GTR, token.GEQ:
// spec: The ordering operators <, <=, >, and >= apply to operands that are ordered."
defined = isOrdered(x.typ)
default:
unreachable()
}
if !defined {
typ := x.typ
if x.isNil() {
typ = y.typ
}
err = check.sprintf("operator %s not defined for %s", op, typ)
}
} else {
err = check.sprintf("mismatched types %s and %s", x.typ, y.typ)
}
if err != "" {
check.errorf(x.pos(), "cannot compare %s %s %s (%s)", x.expr, op, y.expr, err)
x.mode = invalid
return
}
if x.mode == constant_ && y.mode == constant_ {
x.val = constant.MakeBool(constant.Compare(x.val, op, y.val))
// The operands are never materialized; no need to update
// their types.
} else {
x.mode = value
// The operands have now their final types, which at run-
// time will be materialized. Update the expression trees.
// If the current types are untyped, the materialized type
// is the respective default type.
check.updateExprType(x.expr, defaultType(x.typ), true)
check.updateExprType(y.expr, defaultType(y.typ), true)
}
// spec: "Comparison operators compare two operands and yield
// an untyped boolean value."
x.typ = Typ[UntypedBool]
}
开发者ID:2thetop,项目名称:go,代码行数:51,代码来源:expr.go
示例8: evalIdent
// Evaluates identifier expressions
func (scope *EvalScope) evalIdent(node *ast.Ident) (*Variable, error) {
switch node.Name {
case "true", "false":
return newConstant(constant.MakeBool(node.Name == "true"), scope.Thread), nil
case "nil":
return nilVariable, nil
}
// try to interpret this as a local variable
v, err := scope.extractVarInfo(node.Name)
if err != nil {
// if it's not a local variable then it could be a package variable w/o explicit package name
origErr := err
_, _, fn := scope.Thread.dbp.PCToLine(scope.PC)
if fn != nil {
if v, err := scope.packageVarAddr(fn.PackageName() + "." + node.Name); err == nil {
v.Name = node.Name
return v, nil
}
}
return nil, origErr
}
return v, nil
}
开发者ID:josephyzhou,项目名称:delve,代码行数:25,代码来源:eval.go
示例9: Compile
//.........这里部分代码省略.........
if fun.Recv != nil {
recvType := o.Type().(*types.Signature).Recv().Type()
ptr, isPointer := recvType.(*types.Pointer)
namedRecvType, _ := recvType.(*types.Named)
if isPointer {
namedRecvType = ptr.Elem().(*types.Named)
}
d.DceObjectFilter = namedRecvType.Obj().Name()
if !fun.Name.IsExported() {
d.DceMethodFilter = o.Name() + "~"
}
}
d.DceDeps = collectDependencies(func() {
d.DeclCode = c.translateToplevelFunction(fun, funcInfo)
})
funcDecls = append(funcDecls, &d)
}
if typesPkg.Name() == "main" {
if mainFunc == nil {
return nil, fmt.Errorf("missing main function")
}
id := c.newIdent("", types.NewSignature(nil, nil, nil, false))
c.p.Uses[id] = mainFunc
call := &ast.CallExpr{Fun: id}
ifStmt := &ast.IfStmt{
Cond: c.newIdent("$pkg === $mainPkg", types.Typ[types.Bool]),
Body: &ast.BlockStmt{
List: []ast.Stmt{
&ast.ExprStmt{X: call},
&ast.AssignStmt{
Lhs: []ast.Expr{c.newIdent("$mainFinished", types.Typ[types.Bool])},
Tok: token.ASSIGN,
Rhs: []ast.Expr{c.newConst(types.Typ[types.Bool], constant.MakeBool(true))},
},
},
},
}
if len(c.p.FuncDeclInfos[mainFunc].Blocking) != 0 {
c.Blocking[call] = true
c.Flattened[ifStmt] = true
}
funcDecls = append(funcDecls, &Decl{
InitCode: c.CatchOutput(1, func() {
c.translateStmt(ifStmt, nil)
}),
})
}
// named types
var typeDecls []*Decl
for _, o := range c.p.typeNames {
typeName := c.objectName(o)
d := Decl{
Vars: []string{typeName},
DceObjectFilter: o.Name(),
}
d.DceDeps = collectDependencies(func() {
d.DeclCode = c.CatchOutput(0, func() {
typeName := c.objectName(o)
lhs := typeName
if isPkgLevel(o) {
lhs += " = $pkg." + encodeIdent(o.Name())
}
size := int64(0)
constructor := "null"
开发者ID:farazfazli,项目名称:gopherjs,代码行数:67,代码来源:package.go
示例10: stmt
//.........这里部分代码省略.........
check.expr(&x, s.Cond)
if x.mode != invalid && !isBoolean(x.typ) {
check.error(s.Cond.Pos(), "non-boolean condition in if statement")
}
check.stmt(inner, s.Body)
// The parser produces a correct AST but if it was modified
// elsewhere the else branch may be invalid. Check again.
switch s.Else.(type) {
case nil, *ast.BadStmt:
// valid or error already reported
case *ast.IfStmt, *ast.BlockStmt:
check.stmt(inner, s.Else)
default:
check.error(s.Else.Pos(), "invalid else branch in if statement")
}
case *ast.SwitchStmt:
inner |= breakOk
check.openScope(s, "switch")
defer check.closeScope()
check.simpleStmt(s.Init)
var x operand
if s.Tag != nil {
check.expr(&x, s.Tag)
// By checking assignment of x to an invisible temporary
// (as a compiler would), we get all the relevant checks.
check.assignment(&x, nil, "switch expression")
} else {
// spec: "A missing switch expression is
// equivalent to the boolean value true."
x.mode = constant_
x.typ = Typ[Bool]
x.val = constant.MakeBool(true)
x.expr = &ast.Ident{NamePos: s.Body.Lbrace, Name: "true"}
}
check.multipleDefaults(s.Body.List)
seen := make(valueMap) // map of seen case values to positions and types
for i, c := range s.Body.List {
clause, _ := c.(*ast.CaseClause)
if clause == nil {
check.invalidAST(c.Pos(), "incorrect expression switch case")
continue
}
check.caseValues(&x, clause.List, seen)
check.openScope(clause, "case")
inner := inner
if i+1 < len(s.Body.List) {
inner |= fallthroughOk
}
check.stmtList(inner, clause.Body)
check.closeScope()
}
case *ast.TypeSwitchStmt:
inner |= breakOk
check.openScope(s, "type switch")
defer check.closeScope()
check.simpleStmt(s.Init)
// A type switch guard must be of the form:
//
// TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
开发者ID:duhaibo0404,项目名称:go-1,代码行数:67,代码来源:stmt.go
示例11: parseConstValue
// ConstValue = string | "false" | "true" | ["-"] (int ["'"] | FloatOrComplex) .
// FloatOrComplex = float ["i" | ("+"|"-") float "i"] .
func (p *parser) parseConstValue() (val constant.Value, typ types.Type) {
switch p.tok {
case scanner.String:
str := p.parseString()
val = constant.MakeString(str)
typ = types.Typ[types.UntypedString]
return
case scanner.Ident:
b := false
switch p.lit {
case "false":
case "true":
b = true
default:
p.errorf("expected const value, got %s (%q)", scanner.TokenString(p.tok), p.lit)
}
p.next()
val = constant.MakeBool(b)
typ = types.Typ[types.UntypedBool]
return
}
sign := ""
if p.tok == '-' {
p.next()
sign = "-"
}
switch p.tok {
case scanner.Int:
val = constant.MakeFromLiteral(sign+p.lit, token.INT, 0)
if val == nil {
p.error("could not parse integer literal")
}
p.next()
if p.tok == '\'' {
p.next()
typ = types.Typ[types.UntypedRune]
} else {
typ = types.Typ[types.UntypedInt]
}
case scanner.Float:
re := sign + p.lit
p.next()
var im string
switch p.tok {
case '+':
p.next()
im = p.expect(scanner.Float)
case '-':
p.next()
im = "-" + p.expect(scanner.Float)
case scanner.Ident:
// re is in fact the imaginary component. Expect "i" below.
im = re
re = "0"
default:
val = constant.MakeFromLiteral(re, token.FLOAT, 0)
if val == nil {
p.error("could not parse float literal")
}
typ = types.Typ[types.UntypedFloat]
return
}
p.expectKeyword("i")
reval := constant.MakeFromLiteral(re, token.FLOAT, 0)
if reval == nil {
p.error("could not parse real component of complex literal")
}
imval := constant.MakeFromLiteral(im+"i", token.IMAG, 0)
if imval == nil {
p.error("could not parse imag component of complex literal")
}
val = constant.BinaryOp(reval, token.ADD, imval)
typ = types.Typ[types.UntypedComplex]
default:
p.errorf("expected const value, got %s (%q)", scanner.TokenString(p.tok), p.lit)
}
return
}
开发者ID:syreclabs,项目名称:go-tools,代码行数:94,代码来源:parser.go
示例12: defPredeclaredConsts
// Error has a nil package in its qualified name since it is in no package
res := NewVar(token.NoPos, nil, "", Typ[String])
sig := &Signature{results: NewTuple(res)}
err := NewFunc(token.NoPos, nil, "Error", sig)
typ := &Named{underlying: NewInterface([]*Func{err}, nil).Complete()}
sig.recv = NewVar(token.NoPos, nil, "", typ)
def(NewTypeName(token.NoPos, nil, "error", typ))
}
var predeclaredConsts = [...]struct {
name string
kind BasicKind
val exact.Value
}{
{"true", UntypedBool, exact.MakeBool(true)},
{"false", UntypedBool, exact.MakeBool(false)},
{"iota", UntypedInt, exact.MakeInt64(0)},
}
func defPredeclaredConsts() {
for _, c := range predeclaredConsts {
def(NewConst(token.NoPos, nil, c.name, Typ[c.kind], c.val))
}
}
func defPredeclaredNil() {
def(&Nil{object{name: "nil", typ: Typ[UntypedNil]}})
}
// A builtinId is the id of a builtin function.
开发者ID:Ericean,项目名称:go,代码行数:30,代码来源:universe.go
示例13: evalBinary
func (scope *EvalScope) evalBinary(node *ast.BinaryExpr) (*Variable, error) {
switch node.Op {
case token.INC, token.DEC, token.ARROW:
return nil, fmt.Errorf("operator %s not supported", node.Op.String())
}
xv, err := scope.evalAST(node.X)
if err != nil {
return nil, err
}
yv, err := scope.evalAST(node.Y)
if err != nil {
return nil, err
}
xv.loadValue()
yv.loadValue()
if xv.Unreadable != nil {
return nil, xv.Unreadable
}
if yv.Unreadable != nil {
return nil, yv.Unreadable
}
typ, err := negotiateType(node.Op, xv, yv)
if err != nil {
return nil, err
}
op := node.Op
if typ != nil && (op == token.QUO) {
_, isint := typ.(*dwarf.IntType)
_, isuint := typ.(*dwarf.UintType)
if isint || isuint {
// forces integer division if the result type is integer
op = token.QUO_ASSIGN
}
}
switch op {
case token.EQL, token.LSS, token.GTR, token.NEQ, token.LEQ, token.GEQ:
v, err := compareOp(op, xv, yv)
if err != nil {
return nil, err
}
return newConstant(constant.MakeBool(v), xv.mem), nil
default:
if xv.Value == nil {
return nil, fmt.Errorf("operator %s can not be applied to \"%s\"", node.Op.String(), exprToString(node.X))
}
if yv.Value == nil {
return nil, fmt.Errorf("operator %s can not be applied to \"%s\"", node.Op.String(), exprToString(node.Y))
}
rc, err := constantBinaryOp(op, xv.Value, yv.Value)
if err != nil {
return nil, err
}
if typ == nil {
return newConstant(rc, xv.mem), nil
}
r := xv.newVariable("", 0, typ)
r.Value = rc
return r, nil
}
}
开发者ID:mattn,项目名称:delve,代码行数:73,代码来源:eval.go
示例14: loadValueInternal
func (v *Variable) loadValueInternal(recurseLevel int) {
if v.Unreadable != nil || v.loaded || (v.Addr == 0 && v.base == 0) {
return
}
v.loaded = true
switch v.Kind {
case reflect.Ptr, reflect.UnsafePointer:
v.Len = 1
v.Children = []Variable{*v.maybeDereference()}
// Don't increase the recursion level when dereferencing pointers
v.Children[0].loadValueInternal(recurseLevel)
case reflect.Chan:
sv := v.maybeDereference()
sv.loadValueInternal(recurseLevel)
v.Children = sv.Children
v.Len = sv.Len
v.base = sv.Addr
case reflect.Map:
v.loadMap(recurseLevel)
case reflect.String:
var val string
val, v.Unreadable = v.thread.readStringValue(v.base, v.Len)
v.Value = constant.MakeString(val)
case reflect.Slice, reflect.Array:
v.loadArrayValues(recurseLevel)
case reflect.Struct:
t := v.RealType.(*dwarf.StructType)
v.Len = int64(len(t.Field))
// Recursively call extractValue to grab
// the value of all the members of the struct.
if recurseLevel <= maxVariableRecurse {
v.Children = make([]Variable, 0, len(t.Field))
for i, field := range t.Field {
f, _ := v.toField(field)
v.Children = append(v.Children, *f)
v.Children[i].Name = field.Name
v.Children[i].loadValueInternal(recurseLevel + 1)
}
}
case reflect.Complex64, reflect.Complex128:
v.readComplex(v.RealType.(*dwarf.ComplexType).ByteSize)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
var val int64
val, v.Unreadable = v.thread.readIntRaw(v.Addr, v.RealType.(*dwarf.IntType).ByteSize)
v.Value = constant.MakeInt64(val)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
var val uint64
val, v.Unreadable = v.thread.readUintRaw(v.Addr, v.RealType.(*dwarf.UintType).ByteSize)
v.Value = constant.MakeUint64(val)
case reflect.Bool:
val, err := v.thread.readMemory(v.Addr, 1)
v.Unreadable = err
if err == nil {
v.Value = constant.MakeBool(val[0] != 0)
}
case reflect.Float32, reflect.Float64:
var val float64
val, v.Unreadable = v.readFloatRaw(v.RealType.(*dwarf.FloatType).ByteSize)
v.Value = constant.MakeFloat64(val)
case reflect.Func:
v.readFunctionPtr()
default:
v.Unreadable = fmt.Errorf("unknown or unsupported kind: \"%s\"", v.Kind.String())
}
}
开发者ID:josephyzhou,项目名称:delve,代码行数:72,代码来源:variables.go
示例15: defPredeclaredConsts
// Error has a nil package in its qualified name since it is in no package
res := NewVar(token.NoPos, nil, "", Typ[String])
sig := &Signature{results: NewTuple(res)}
err := NewFunc(token.NoPos, nil, "Error", sig)
typ := &Named{underlying: NewInterface([]*Func{err}, nil).Complete()}
sig.recv = NewVar(token.NoPos, nil, "", typ)
def(NewTypeName(token.NoPos, nil, "error", typ))
}
var predeclaredConsts = [...]struct {
name string
kind BasicKind
val constant.Value
}{
{"true", UntypedBool, constant.MakeBool(true)},
{"false", UntypedBool, constant.MakeBool(false)},
{"iota", UntypedInt, constant.MakeInt64(0)},
}
func defPredeclaredConsts() {
for _, c := range predeclaredConsts {
def(NewConst(token.NoPos, nil, c.name, Typ[c.kind], c.val))
}
}
func defPredeclaredNil() {
def(&Nil{object{name: "nil", typ: Typ[UntypedNil]}})
}
// A builtinId is the id of a builtin function.
开发者ID:RajibTheKing,项目名称:gcc,代码行数:30,代码来源:universe.go
示例16: parseConstDecl
// ConstDecl = "const" ExportedName [ Type ] "=" Literal .
// Literal = bool_lit | int_lit | float_lit | complex_lit | rune_lit | string_lit .
// bool_lit = "true" | "false" .
// complex_lit = "(" float_lit "+" float_lit "i" ")" .
// rune_lit = "(" int_lit "+" int_lit ")" .
// string_lit = `"` { unicode_char } `"` .
//
func (p *parser) parseConstDecl() {
p.expectKeyword("const")
pkg, name := p.parseExportedName()
var typ0 types.Type
if p.tok != '=' {
// constant types are never structured - no need for parent type
typ0 = p.parseType(nil)
}
p.expect('=')
var typ types.Type
var val exact.Value
switch p.tok {
case scanner.Ident:
// bool_lit
if p.lit != "true" && p.lit != "false" {
p.error("expected true or false")
}
typ = types.Typ[types.UntypedBool]
val = exact.MakeBool(p.lit == "true")
p.next()
case '-', scanner.Int:
// int_lit
typ, val = p.parseNumber()
case '(':
// complex_lit or rune_lit
p.next()
if p.tok == scanner.Char {
p.next()
p.expect('+')
typ = types.Typ[types.UntypedRune]
_, val = p.parseNumber()
p.expect(')')
break
}
_, re := p.parseNumber()
p.expect('+')
_, im := p.parseNumber()
p.expectKeyword("i")
p.expect(')')
typ = types.Typ[types.UntypedComplex]
val = exact.BinaryOp(re, token.ADD, exact.MakeImag(im))
case scanner.Char:
// rune_lit
typ = types.Typ[types.UntypedRune]
val = exact.MakeFromLiteral(p.lit, token.CHAR, 0)
p.next()
case scanner.String:
// string_lit
typ = types.Typ[types.UntypedString]
val = exact.MakeFromLiteral(p.lit, token.STRING, 0)
p.next()
default:
p.errorf("expected literal got %s", scanner.TokenString(p.tok))
}
if typ0 == nil {
typ0 = typ
}
pkg.Scope().Insert(types.NewConst(token.NoPos, pkg, name, typ0, val))
}
开发者ID:vmware,项目名称:vic,代码行数:75,代码来源:gcimporter.go
示例17: loadValueInternal
func (v *Variable) loadValueInternal(recurseLevel int, cfg LoadConfig) {
if v.Unreadable != nil || v.loaded || (v.Addr == 0 && v.Base == 0) {
return
}
v.loaded = true
switch v.Kind {
case reflect.Ptr, reflect.UnsafePointer:
v.Len = 1
v.Children = []Variable{*v.maybeDereference()}
if cfg.FollowPointers {
// Don't increase the recursion level when dereferencing pointers
v.Children[0].loadValueInternal(recurseLevel, cfg)
} else {
v.Children[0].OnlyAddr = true
}
case reflect.Chan:
sv := v.clone()
sv.RealType = resolveTypedef(&(sv.RealType.(*dwarf.ChanType).TypedefType))
sv = sv.maybeDereference()
sv.loadValueInternal(0, loadFullValue)
v.Children = sv.Children
v.Len = sv.Len
v.Base = sv.Addr
case reflect.Map:
if recurseLevel <= cfg.MaxVariableRecurse {
v.loadMap(recurseLevel, cfg)
}
case reflect.String:
var val string
val, v.Unreadable = readStringValue(v.mem, v.Base, v.Len, cfg)
v.Value = constant.MakeString(val)
case reflect.Slice, reflect.Array:
v.loadArrayValues(recurseLevel, cfg)
case reflect.Struct:
v.mem = cacheMemory(v.mem, v.Addr, int(v.RealType.Size()))
t := v.RealType.(*dwarf.StructType)
v.Len = int64(len(t.Field))
// Recursively call extractValue to grab
// the value of all the members of the struct.
if recurseLevel <= cfg.MaxVariableRecurse {
v.Children = make([]Variable, 0, len(t.Field))
for i, field := range t.Field {
if cfg.MaxStructFields >= 0 && len(v.Children) >= cfg.MaxStructFields {
break
}
f, _ := v.toField(field)
v.Children = append(v.Children, *f)
v.Children[i].Name = field.Name
v.Children[i].loadValueInternal(recurseLevel+1, cfg)
}
}
case reflect.Interface:
v.loadInterface(recurseLevel, true, cfg)
case reflect.Complex64, reflect.Complex128:
v.readComplex(v.RealType.(*dwarf.ComplexType).ByteSize)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
var val int64
val, v.Unreadable = readIntRaw(v.mem, v.Addr, v.RealType.(*dwarf.IntType).ByteSize)
v.Value = constant.MakeInt64(val)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
var val uint64
val, v.Unreadable = readUintRaw(v.mem, v.Addr, v.RealType.(*dwarf.UintType).ByteSize)
v.Value = constant.MakeUint64(val)
case reflect.Bool:
val, err := v.mem.readMemory(v.Addr, 1)
v.Unreadable = err
if err == nil {
v.Value = constant.MakeBool(val[0] != 0)
}
case reflect.Float32, reflect.Float64:
var val float64
val, v.Unreadable = v.readFloatRaw(v.RealType.(*dwarf.FloatType).ByteSize)
v.Value = constant.MakeFloat64(val)
case reflect.Func:
v.readFunctionPtr()
default:
v.Unreadable = fmt.Errorf("unknown or unsupported kind: \"%s\"", v.Kind.String())
}
}
开发者ID:DuoSoftware,项目名称:v6engine-deps,代码行数:88,代码来源:variables.go
示例18: translateStmt
func (c *funcContext) translateStmt(stmt ast.Stmt, label *types.Label) {
c.SetPos(stmt.Pos())
stmt = filter.IncDecStmt(stmt, c.p.Info)
stmt = filter.Assign(stmt, c.p.Info)
switch s := stmt.(type) {
case *ast.BlockStmt:
c.translateStmtList(s.List)
case *ast.IfStmt:
if s.Init != nil {
c.translateStmt(s.Init, nil)
}
var caseClauses []ast.Stmt
ifStmt := s
for {
caseClauses = append(caseClauses, &ast.CaseClause{List: []ast.Expr{ifStmt.Cond}, Body: ifStmt.Body.List})
switch elseStmt := ifStmt.Else.(type) {
case *ast.IfStmt:
if elseStmt.Init != nil {
caseClauses = append(caseClauses, &ast.CaseClause{List: nil, Body: []ast.Stmt{elseStmt}})
break
}
ifStmt = elseStmt
continue
case *ast.BlockStmt:
caseClauses = append(caseClauses, &ast.CaseClause{List: nil, Body: elseStmt.List})
case *ast.EmptyStmt, nil:
// no else clause
default:
panic(fmt.Sprintf("Unhandled else: %T\n", elseStmt))
}
break
}
c.translateBranchingStmt(caseClauses, false, nil, nil, nil, c.Flattened[s])
case *ast.SwitchStmt:
if s.Init != nil {
c.translateStmt(s.Init, nil)
}
tag := s.Tag
if tag == nil {
tag = ast.NewIdent("true")
c.p.Types[tag] = types.TypeAndValue{Type: types.Typ[types.Bool], Value: constant.MakeBool(true)}
}
if c.p.Types[tag].Value == nil {
refVar := c.newVariable("_ref")
c.Printf("%s = %s;", refVar, c.translateExpr(tag))
tag = c.newIdent(refVar, c.p.TypeOf(tag))
}
translateCond := func(cond ast.Expr) *expression {
return c.translateExpr(&ast.BinaryExpr{
X: tag,
Op: token.EQL,
Y: cond,
})
}
c.translateBranchingStmt(s.Body.List, true, translateCond, nil, label, c.Flattened[s])
case *ast.TypeSwitchStmt:
if s.Init != nil {
c.translateStmt(s.Init, nil)
}
refVar := c.newVariable("_ref")
var expr ast.Expr
var printCaseBodyPrefix func(index int)
switch a := s.Assign.(type) {
case *ast.AssignStmt:
expr = a.Rhs[0].(*ast.TypeAssertExpr).X
printCaseBodyPrefix = func(index int) {
value := refVar
caseClause := s.Body.List[index].(*ast.CaseClause)
if len(caseClause.List) == 1 {
t := c.p.TypeOf(caseClause.List[0])
if _, isInterface := t.Underlying().(*types.Interface); !isInterface && !types.Identical(t, types.Typ[types.UntypedNil]) {
value += ".$val"
}
}
c.Printf("%s = %s;", c.objectName(c.p.Implicits[caseClause]), value)
}
case *ast.ExprStmt:
expr = a.X.(*ast.TypeAssertExpr).X
}
c.Printf("%s = %s;", refVar, c.translateExpr(expr))
translateCond := func(cond ast.Expr) *expression {
if types.Identical(c.p.TypeOf(cond), types.Typ[types.UntypedNil]) {
return c.formatExpr("%s === $ifaceNil", refVar)
}
return c.formatExpr("$assertType(%s, %s, true)[1]", refVar, c.typeName(c.p.TypeOf(cond)))
}
c.translateBranchingStmt(s.Body.List, true, translateCond, printCaseBodyPrefix, label, c.Flattened[s])
case *ast.ForStmt:
if s.Init != nil {
c.translateStmt(s.Init, nil)
}
//.........这里部分代码省略.........
开发者ID:farazfazli,项目名称:gopherjs,代码行数:101,代码来源:statements.go
注:本文中的go/constant.MakeBool函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论