本文整理汇总了Golang中go/constant.MakeBool函数的典型用法代码示例。如果您正苦于以下问题:Golang MakeBool函数的具体用法?Golang MakeBool怎么用?Golang MakeBool使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了MakeBool函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
示例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))
}
示例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
}
示例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))
}
}
示例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))
}
}
示例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)
}
示例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]
}
示例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
}
示例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"
示例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" ")" .
示例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
}
示例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.
示例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
}
}
示例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())
}
}
示例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.