本文整理汇总了Golang中go/constant.ToInt函数的典型用法代码示例。如果您正苦于以下问题:Golang ToInt函数的具体用法?Golang ToInt怎么用?Golang ToInt使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ToInt函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: asConstantInt
// asConstantInt returns the value as an constant.Int if possible, along
// with a flag indicating whether the conversion was possible.
func (expr *NumVal) asConstantInt() (constant.Value, bool) {
intVal := constant.ToInt(expr.Value)
if intVal.Kind() == constant.Int {
return intVal, true
}
return nil, false
}
开发者ID:GitGoldie,项目名称:cockroach,代码行数:9,代码来源:constant.go
示例2: Uint64
// Uint64 returns the numeric value of this constant truncated to fit
// an unsigned 64-bit integer.
//
func (c *Const) Uint64() uint64 {
switch x := exact.ToInt(c.Value); x.Kind() {
case exact.Int:
if u, ok := exact.Uint64Val(x); ok {
return u
}
return 0
case exact.Float:
f, _ := exact.Float64Val(x)
return uint64(f)
}
panic(fmt.Sprintf("unexpected constant value: %T", c.Value))
}
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:16,代码来源:const.go
示例3: ResolveAsType
// ResolveAsType implements the Constant interface.
func (expr *NumVal) ResolveAsType(typ Datum) (Datum, error) {
switch {
case typ.TypeEqual(TypeInt):
i, exact := constant.Int64Val(constant.ToInt(expr.Value))
if !exact {
return nil, fmt.Errorf("integer value out of range: %v", expr.Value)
}
return NewDInt(DInt(i)), nil
case typ.TypeEqual(TypeFloat):
f, _ := constant.Float64Val(constant.ToFloat(expr.Value))
return NewDFloat(DFloat(f)), nil
case typ.TypeEqual(TypeDecimal):
dd := &DDecimal{}
s := expr.ExactString()
if idx := strings.IndexRune(s, '/'); idx != -1 {
// Handle constant.ratVal, which will return a rational string
// like 6/7. If only we could call big.Rat.FloatString() on it...
num, den := s[:idx], s[idx+1:]
if _, ok := dd.SetString(num); !ok {
return nil, fmt.Errorf("could not evaluate numerator of %v as Datum type DDecimal "+
"from string %q", expr, num)
}
denDec := new(inf.Dec)
if _, ok := denDec.SetString(den); !ok {
return nil, fmt.Errorf("could not evaluate denominator %v as Datum type DDecimal "+
"from string %q", expr, den)
}
dd.QuoRound(&dd.Dec, denDec, decimal.Precision, inf.RoundHalfUp)
} else {
if _, ok := dd.SetString(s); !ok {
return nil, fmt.Errorf("could not evaluate %v as Datum type DDecimal from "+
"string %q", expr, s)
}
}
return dd, nil
default:
return nil, fmt.Errorf("could not resolve %T %v into a %T", expr, expr, typ)
}
}
开发者ID:GitGoldie,项目名称:cockroach,代码行数:40,代码来源:constant.go
示例4: arrayLength
func (check *Checker) arrayLength(e ast.Expr) int64 {
var x operand
check.expr(&x, e)
if x.mode != constant_ {
if x.mode != invalid {
check.errorf(x.pos(), "array length %s must be constant", &x)
}
return 0
}
if isUntyped(x.typ) || isInteger(x.typ) {
if val := constant.ToInt(x.val); val.Kind() == constant.Int {
if representableConst(val, check.conf, Typ[Int], nil) {
if n, ok := constant.Int64Val(val); ok && n >= 0 {
return n
}
check.errorf(x.pos(), "invalid array length %s", &x)
return 0
}
}
}
check.errorf(x.pos(), "array length %s must be integer", &x)
return 0
}
开发者ID:2thetop,项目名称:go,代码行数:23,代码来源:typexpr.go
示例5: index
// index checks an index expression for validity.
// If max >= 0, it is the upper bound for index.
// If index is valid and the result i >= 0, then i is the constant value of index.
func (check *Checker) index(index ast.Expr, max int64) (i int64, valid bool) {
var x operand
check.expr(&x, index)
if x.mode == invalid {
return
}
// an untyped constant must be representable as Int
check.convertUntyped(&x, Typ[Int])
if x.mode == invalid {
return
}
// the index must be of integer type
if !isInteger(x.typ) {
check.invalidArg(x.pos(), "index %s must be integer", &x)
return
}
// a constant index i must be in bounds
if x.mode == constant_ {
if constant.Sign(x.val) < 0 {
check.invalidArg(x.pos(), "index %s must not be negative", &x)
return
}
i, valid = constant.Int64Val(constant.ToInt(x.val))
if !valid || max >= 0 && i >= max {
check.errorf(x.pos(), "index %s is out of bounds", &x)
return i, false
}
// 0 <= i [ && i < max ]
return i, true
}
return -1, true
}
开发者ID:2thetop,项目名称:go,代码行数:39,代码来源:expr.go
示例6: translateExpr
func (c *funcContext) translateExpr(expr ast.Expr) *expression {
exprType := c.p.TypeOf(expr)
if value := c.p.Types[expr].Value; value != nil {
basic := exprType.Underlying().(*types.Basic)
switch {
case isBoolean(basic):
return c.formatExpr("%s", strconv.FormatBool(constant.BoolVal(value)))
case isInteger(basic):
if is64Bit(basic) {
if basic.Kind() == types.Int64 {
d, ok := constant.Int64Val(constant.ToInt(value))
if !ok {
panic("could not get exact uint")
}
return c.formatExpr("new %s(%s, %s)", c.typeName(exprType), strconv.FormatInt(d>>32, 10), strconv.FormatUint(uint64(d)&(1<<32-1), 10))
}
d, ok := constant.Uint64Val(constant.ToInt(value))
if !ok {
panic("could not get exact uint")
}
return c.formatExpr("new %s(%s, %s)", c.typeName(exprType), strconv.FormatUint(d>>32, 10), strconv.FormatUint(d&(1<<32-1), 10))
}
d, ok := constant.Int64Val(constant.ToInt(value))
if !ok {
panic("could not get exact int")
}
return c.formatExpr("%s", strconv.FormatInt(d, 10))
case isFloat(basic):
f, _ := constant.Float64Val(value)
return c.formatExpr("%s", strconv.FormatFloat(f, 'g', -1, 64))
case isComplex(basic):
r, _ := constant.Float64Val(constant.Real(value))
i, _ := constant.Float64Val(constant.Imag(value))
if basic.Kind() == types.UntypedComplex {
exprType = types.Typ[types.Complex128]
}
return c.formatExpr("new %s(%s, %s)", c.typeName(exprType), strconv.FormatFloat(r, 'g', -1, 64), strconv.FormatFloat(i, 'g', -1, 64))
case isString(basic):
return c.formatExpr("%s", encodeString(constant.StringVal(value)))
default:
panic("Unhandled constant type: " + basic.String())
}
}
var obj types.Object
switch e := expr.(type) {
case *ast.SelectorExpr:
obj = c.p.Uses[e.Sel]
case *ast.Ident:
obj = c.p.Defs[e]
if obj == nil {
obj = c.p.Uses[e]
}
}
if obj != nil && typesutil.IsJsPackage(obj.Pkg()) {
switch obj.Name() {
case "Global":
return c.formatExpr("$global")
case "Module":
return c.formatExpr("$module")
case "Undefined":
return c.formatExpr("undefined")
}
}
switch e := expr.(type) {
case *ast.CompositeLit:
if ptrType, isPointer := exprType.(*types.Pointer); isPointer {
exprType = ptrType.Elem()
}
collectIndexedElements := func(elementType types.Type) []string {
var elements []string
i := 0
zero := c.translateExpr(c.zeroValue(elementType)).String()
for _, element := range e.Elts {
if kve, isKve := element.(*ast.KeyValueExpr); isKve {
key, ok := constant.Int64Val(constant.ToInt(c.p.Types[kve.Key].Value))
if !ok {
panic("could not get exact int")
}
i = int(key)
element = kve.Value
}
for len(elements) <= i {
elements = append(elements, zero)
}
elements[i] = c.translateImplicitConversionWithCloning(element, elementType).String()
i++
}
return elements
}
switch t := exprType.Underlying().(type) {
case *types.Array:
elements := collectIndexedElements(t.Elem())
if len(elements) == 0 {
return c.formatExpr("%s.zero()", c.typeName(t))
}
//.........这里部分代码省略.........
开发者ID:camlistore,项目名称:camlistore,代码行数:101,代码来源:expressions.go
示例7: formatExprInternal
func (c *funcContext) formatExprInternal(format string, a []interface{}, parens bool) *expression {
processFormat := func(f func(uint8, uint8, int)) {
n := 0
for i := 0; i < len(format); i++ {
b := format[i]
if b == '%' {
i++
k := format[i]
if k >= '0' && k <= '9' {
n = int(k - '0' - 1)
i++
k = format[i]
}
f(0, k, n)
n++
continue
}
f(b, 0, 0)
}
}
counts := make([]int, len(a))
processFormat(func(b, k uint8, n int) {
switch k {
case 'e', 'f', 'h', 'l', 'r', 'i':
counts[n]++
}
})
out := bytes.NewBuffer(nil)
vars := make([]string, len(a))
hasAssignments := false
for i, e := range a {
if counts[i] <= 1 {
continue
}
if _, isIdent := e.(*ast.Ident); isIdent {
continue
}
if val := c.p.Types[e.(ast.Expr)].Value; val != nil {
continue
}
if !hasAssignments {
hasAssignments = true
out.WriteByte('(')
parens = false
}
v := c.newVariable("x")
out.WriteString(v + " = " + c.translateExpr(e.(ast.Expr)).String() + ", ")
vars[i] = v
}
processFormat(func(b, k uint8, n int) {
writeExpr := func(suffix string) {
if vars[n] != "" {
out.WriteString(vars[n] + suffix)
return
}
out.WriteString(c.translateExpr(a[n].(ast.Expr)).StringWithParens() + suffix)
}
switch k {
case 0:
out.WriteByte(b)
case 's':
if e, ok := a[n].(*expression); ok {
out.WriteString(e.StringWithParens())
return
}
out.WriteString(a[n].(string))
case 'd':
out.WriteString(strconv.Itoa(a[n].(int)))
case 't':
out.WriteString(a[n].(token.Token).String())
case 'e':
e := a[n].(ast.Expr)
if val := c.p.Types[e].Value; val != nil {
out.WriteString(c.translateExpr(e).String())
return
}
writeExpr("")
case 'f':
e := a[n].(ast.Expr)
if val := c.p.Types[e].Value; val != nil {
d, _ := constant.Int64Val(constant.ToInt(val))
out.WriteString(strconv.FormatInt(d, 10))
return
}
if is64Bit(c.p.TypeOf(e).Underlying().(*types.Basic)) {
out.WriteString("$flatten64(")
writeExpr("")
out.WriteString(")")
return
}
writeExpr("")
case 'h':
e := a[n].(ast.Expr)
if val := c.p.Types[e].Value; val != nil {
d, _ := constant.Uint64Val(constant.ToInt(val))
if c.p.TypeOf(e).Underlying().(*types.Basic).Kind() == types.Int64 {
out.WriteString(strconv.FormatInt(int64(d)>>32, 10))
//.........这里部分代码省略.........
开发者ID:camlistore,项目名称:camlistore,代码行数:101,代码来源:expressions.go
示例8: shift
func (check *Checker) shift(x, y *operand, e *ast.BinaryExpr, op token.Token) {
untypedx := isUntyped(x.typ)
var xval constant.Value
if x.mode == constant_ {
xval = constant.ToInt(x.val)
}
if isInteger(x.typ) || untypedx && xval != nil && xval.Kind() == constant.Int {
// The lhs is of integer type or an untyped constant representable
// as an integer. Nothing to do.
} else {
// shift has no chance
check.invalidOp(x.pos(), "shifted operand %s must be integer", x)
x.mode = invalid
return
}
// spec: "The right operand in a shift expression must have unsigned
// integer type or be an untyped constant that can be converted to
// unsigned integer type."
switch {
case isUnsigned(y.typ):
// nothing to do
case isUntyped(y.typ):
check.convertUntyped(y, Typ[UntypedInt])
if y.mode == invalid {
x.mode = invalid
return
}
default:
check.invalidOp(y.pos(), "shift count %s must be unsigned integer", y)
x.mode = invalid
return
}
if x.mode == constant_ {
if y.mode == constant_ {
// rhs must be an integer value
yval := constant.ToInt(y.val)
if yval.Kind() != constant.Int {
check.invalidOp(y.pos(), "shift count %s must be unsigned integer", y)
x.mode = invalid
return
}
// rhs must be within reasonable bounds
const shiftBound = 1023 - 1 + 52 // so we can express smallestFloat64
s, ok := constant.Uint64Val(yval)
if !ok || s > shiftBound {
check.invalidOp(y.pos(), "invalid shift count %s", y)
x.mode = invalid
return
}
// The lhs is representable as an integer but may not be an integer
// (e.g., 2.0, an untyped float) - this can only happen for untyped
// non-integer numeric constants. Correct the type so that the shift
// result is of integer type.
if !isInteger(x.typ) {
x.typ = Typ[UntypedInt]
}
// x is a constant so xval != nil and it must be of Int kind.
x.val = constant.Shift(xval, op, uint(s))
// Typed constants must be representable in
// their type after each constant operation.
if isTyped(x.typ) {
if e != nil {
x.expr = e // for better error message
}
check.representable(x, x.typ.Underlying().(*Basic))
}
return
}
// non-constant shift with constant lhs
if untypedx {
// spec: "If the left operand of a non-constant shift
// expression is an untyped constant, the type of the
// constant is what it would be if the shift expression
// were replaced by its left operand alone.".
//
// Delay operand checking until we know the final type
// by marking the lhs expression as lhs shift operand.
//
// Usually (in correct programs), the lhs expression
// is in the untyped map. However, it is possible to
// create incorrect programs where the same expression
// is evaluated twice (via a declaration cycle) such
// that the lhs expression type is determined in the
// first round and thus deleted from the map, and then
// not found in the second round (double insertion of
// the same expr node still just leads to one entry for
// that node, and it can only be deleted once).
// Be cautious and check for presence of entry.
// Example: var e, f = int(1<<""[f]) // issue 11347
if info, found := check.untyped[x.expr]; found {
info.isLhs = true
check.untyped[x.expr] = info
}
// keep x's type
x.mode = value
//.........这里部分代码省略.........
开发者ID:2thetop,项目名称:go,代码行数:101,代码来源:expr.go
示例9: representableConst
// representableConst reports whether x can be represented as
// value of the given basic type and for the configuration
// provided (only needed for int/uint sizes).
//
// If rounded != nil, *rounded is set to the rounded value of x for
// representable floating-point and complex values, and to an Int
// value for integer values; it is left alone otherwise.
// It is ok to provide the addressof the first argument for rounded.
func representableConst(x constant.Value, conf *Config, typ *Basic, rounded *constant.Value) bool {
if x.Kind() == constant.Unknown {
return true // avoid follow-up errors
}
switch {
case isInteger(typ):
x := constant.ToInt(x)
if x.Kind() != constant.Int {
return false
}
if rounded != nil {
*rounded = x
}
if x, ok := constant.Int64Val(x); ok {
switch typ.kind {
case Int:
var s = uint(conf.sizeof(typ)) * 8
return int64(-1)<<(s-1) <= x && x <= int64(1)<<(s-1)-1
case Int8:
const s = 8
return -1<<(s-1) <= x && x <= 1<<(s-1)-1
case Int16:
const s = 16
return -1<<(s-1) <= x && x <= 1<<(s-1)-1
case Int32:
const s = 32
return -1<<(s-1) <= x && x <= 1<<(s-1)-1
case Int64, UntypedInt:
return true
case Uint, Uintptr:
if s := uint(conf.sizeof(typ)) * 8; s < 64 {
return 0 <= x && x <= int64(1)<<s-1
}
return 0 <= x
case Uint8:
const s = 8
return 0 <= x && x <= 1<<s-1
case Uint16:
const s = 16
return 0 <= x && x <= 1<<s-1
case Uint32:
const s = 32
return 0 <= x && x <= 1<<s-1
case Uint64:
return 0 <= x
default:
unreachable()
}
}
// x does not fit into int64
switch n := constant.BitLen(x); typ.kind {
case Uint, Uintptr:
var s = uint(conf.sizeof(typ)) * 8
return constant.Sign(x) >= 0 && n <= int(s)
case Uint64:
return constant.Sign(x) >= 0 && n <= 64
case UntypedInt:
return true
}
case isFloat(typ):
x := constant.ToFloat(x)
if x.Kind() != constant.Float {
return false
}
switch typ.kind {
case Float32:
if rounded == nil {
return fitsFloat32(x)
}
r := roundFloat32(x)
if r != nil {
*rounded = r
return true
}
case Float64:
if rounded == nil {
return fitsFloat64(x)
}
r := roundFloat64(x)
if r != nil {
*rounded = r
return true
}
case UntypedFloat:
return true
default:
unreachable()
}
case isComplex(typ):
//.........这里部分代码省略.........
开发者ID:2thetop,项目名称:go,代码行数:101,代码来源:expr.go
示例10: binary
// The binary expression e may be nil. It's passed in for better error messages only.
func (check *Checker) binary(x *operand, e *ast.BinaryExpr, lhs, rhs ast.Expr, op token.Token) {
var y operand
check.expr(x, lhs)
check.expr(&y, rhs)
if x.mode == invalid {
return
}
if y.mode == invalid {
x.mode = invalid
x.expr = y.expr
return
}
if isShift(op) {
check.shift(x, &y, e, op)
return
}
check.convertUntyped(x, y.typ)
if x.mode == invalid {
return
}
check.convertUntyped(&y, x.typ)
if y.mode == invalid {
x.mode = invalid
return
}
if isComparison(op) {
check.comparison(x, &y, op)
return
}
if !Identical(x.typ, y.typ) {
// only report an error if we have valid types
// (otherwise we had an error reported elsewhere already)
if x.typ != Typ[Invalid] && y.typ != Typ[Invalid] {
check.invalidOp(x.pos(), "mismatched types %s and %s", x.typ, y.typ)
}
x.mode = invalid
return
}
if !check.op(binaryOpPredicates, x, op) {
x.mode = invalid
return
}
if (op == token.QUO || op == token.REM) && (x.mode == constant_ || isInteger(x.typ)) && y.mode == constant_ && constant.Sign(y.val) == 0 {
check.invalidOp(y.pos(), "division by zero")
x.mode = invalid
return
}
if x.mode == constant_ && y.mode == constant_ {
xval := x.val
yval := y.val
typ := x.typ.Underlying().(*Basic)
// force integer division of integer operands
if op == token.QUO && isInteger(typ) {
xval = constant.ToInt(xval)
yval = constant.ToInt(yval)
op = token.QUO_ASSIGN
}
x.val = constant.BinaryOp(xval, op, yval)
// Typed constants must be representable in
// their type after each constant operation.
if isTyped(typ) {
if e != nil {
x.expr = e // for better error message
}
check.representable(x, typ)
}
return
}
x.mode = value
// x.typ is unchanged
}
开发者ID:danny8002,项目名称:go,代码行数:82,代码来源:expr.go
注:本文中的go/constant.ToInt函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论