作者:rjammal
项目:emg
func writeFloat(w *bytes.Buffer, ev exact.Value, k types.BasicKind) {
v, _ := exact.Int64Val(exact.Num(ev))
w.WriteString(strconv.FormatInt(v, 10))
v, _ = exact.Int64Val(exact.Denom(ev))
if v != 1 {
w.WriteByte('/')
w.WriteString(strconv.FormatInt(v, 10))
}
w.WriteByte('.')
if k == types.Float32 {
w.WriteByte('F')
}
}
作者:hackrol
项目:daily-progra
func (p *exporter) value(x exact.Value) {
if trace {
p.tracef("value { ")
defer p.tracef("} ")
}
switch kind := x.Kind(); kind {
case exact.Bool:
tag := falseTag
if exact.BoolVal(x) {
tag = trueTag
}
p.int(tag)
case exact.Int:
if i, ok := exact.Int64Val(x); ok {
p.int(int64Tag)
p.int64(i)
return
}
p.int(floatTag)
p.float(x)
case exact.Float:
p.int(fractionTag)
p.fraction(x)
case exact.Complex:
p.int(complexTag)
p.fraction(exact.Real(x))
p.fraction(exact.Imag(x))
case exact.String:
p.int(stringTag)
p.string(exact.StringVal(x))
default:
panic(fmt.Sprintf("unexpected value kind %d", kind))
}
}
作者:pombredann
项目:tardisg
// IntVal is a utility function returns an int64 constant value from an exact.Value, split into high and low int32.
func IntVal(eVal exact.Value, posStr string) (high, low int32) {
iVal, isExact := exact.Int64Val(eVal)
if !isExact {
LogWarning(posStr, "inexact", fmt.Errorf("constant value %d cannot be accurately represented in int64", iVal))
}
return int32(iVal >> 32), int32(iVal & 0xFFFFFFFF)
}
作者:4hono
项目:obd
// Conversion type-checks the conversion T(x).
// The result is in x.
func (check *Checker) conversion(x *operand, T Type) {
constArg := x.mode == constant
var ok bool
switch {
case constArg && isConstType(T):
// constant conversion
switch t := T.Underlying().(*Basic); {
case representableConst(x.val, check.conf, t.kind, &x.val):
ok = true
case x.isInteger() && isString(t):
codepoint := int64(-1)
if i, ok := exact.Int64Val(x.val); ok {
codepoint = i
}
// If codepoint < 0 the absolute value is too large (or unknown) for
// conversion. This is the same as converting any other out-of-range
// value - let string(codepoint) do the work.
x.val = exact.MakeString(string(codepoint))
ok = true
}
case x.convertibleTo(check.conf, T):
// non-constant conversion
x.mode = value
ok = true
}
if !ok {
check.errorf(x.pos(), "cannot convert %s to %s", x, T)
x.mode = invalid
return
}
// The conversion argument types are final. For untyped values the
// conversion provides the type, per the spec: "A constant may be
// given a type explicitly by a constant declaration or conversion,...".
final := x.typ
if isUntyped(x.typ) {
final = T
// - For conversions to interfaces, use the argument's default type.
// - For conversions of untyped constants to non-constant types, also
// use the default type (e.g., []byte("foo") should report string
// not []byte as type for the constant "foo").
// - Keep untyped nil for untyped nil arguments.
if isInterface(T) || constArg && !isConstType(T) {
final = defaultType(x.typ)
}
check.updateExprType(x.expr, final, true)
}
x.typ = T
}
作者:pombredann
项目:go.tool
// Int64 returns the numeric value of this literal truncated to fit
// a signed 64-bit integer.
//
func (l *Literal) Int64() int64 {
switch x := l.Value; x.Kind() {
case exact.Int:
if i, ok := exact.Int64Val(x); ok {
return i
}
return 0
case exact.Float:
f, _ := exact.Float64Val(x)
return int64(f)
}
panic(fmt.Sprintf("unexpected literal value: %T", l.Value))
}
作者:nagyistg
项目:hm-workspac
// Int64 returns the numeric value of this constant truncated to fit
// a signed 64-bit integer.
//
func (c *Const) Int64() int64 {
switch x := c.Value; x.Kind() {
case exact.Int:
if i, ok := exact.Int64Val(x); ok {
return i
}
return 0
case exact.Float:
f, _ := exact.Float64Val(x)
return int64(f)
}
panic(fmt.Sprintf("unexpected constant value: %T", c.Value))
}
作者:rock
项目:ssa-inter
func doOp(x exact.Value, op token.Token, y exact.Value) (z exact.Value) {
defer panicHandler(&z)
if x == nil {
return exact.UnaryOp(op, y, -1)
}
switch op {
case token.EQL, token.NEQ, token.LSS, token.LEQ, token.GTR, token.GEQ:
return exact.MakeBool(exact.Compare(x, op, y))
case token.SHL, token.SHR:
s, _ := exact.Int64Val(y)
return exact.Shift(x, op, uint(s))
default:
return exact.BinaryOp(x, op, y)
}
}
作者:ufo2294026
项目:two-server-other
func ext۰reflect۰rtype۰InOut(a *analysis, cgn *cgnode, out bool) {
// If we have access to the callsite,
// and the argument is an int constant,
// return only that parameter.
index := -1
if site := cgn.callersite; site != nil {
if c, ok := site.instr.Common().Args[0].(*ssa.Const); ok {
v, _ := exact.Int64Val(c.Value)
index = int(v)
}
}
a.addConstraint(&rtypeInOutConstraint{
cgn: cgn,
t: a.funcParams(cgn.obj),
result: a.funcResults(cgn.obj),
out: out,
i: index,
})
}
作者:hackrol
项目:daily-progra
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 !x.isInteger() {
check.errorf(x.pos(), "array length %s must be integer", &x)
return 0
}
n, ok := exact.Int64Val(x.val)
if !ok || n < 0 {
check.errorf(x.pos(), "invalid array length %s", &x)
return 0
}
return n
}
作者:bryanx
项目:go-zh.tool
// checkLongShift checks if shift or shift-assign operations shift by more than
// the length of the underlying variable.
func checkLongShift(f *File, node ast.Node, x, y ast.Expr) {
v := f.pkg.types[y].Value
if v == nil {
return
}
amt, ok := exact.Int64Val(v)
if !ok {
return
}
t := f.pkg.types[x].Type
if t == nil {
return
}
b, ok := t.Underlying().(*types.Basic)
if !ok {
return
}
var size int64
var msg string
switch b.Kind() {
case types.Uint8, types.Int8:
size = 8
case types.Uint16, types.Int16:
size = 16
case types.Uint32, types.Int32:
size = 32
case types.Uint64, types.Int64:
size = 64
case types.Int, types.Uint, types.Uintptr:
// These types may be as small as 32 bits, but no smaller.
size = 32
msg = "might be "
default:
return
}
if amt >= size {
ident := f.gofmt(x)
f.Badf(node.Pos(), "%s %stoo small for shift of %d", ident, msg, amt)
}
}
作者:rock
项目:ssa-inter
func evalAction(n ast.Node) exact.Value {
switch e := n.(type) {
case *ast.BasicLit:
return val(e.Value)
case *ast.BinaryExpr:
x := evalAction(e.X)
if x == nil {
return nil
}
y := evalAction(e.Y)
if y == nil {
return nil
}
switch e.Op {
case token.EQL, token.NEQ, token.LSS, token.LEQ, token.GTR, token.GEQ:
return exact.MakeBool(exact.Compare(x, e.Op, y))
case token.SHL, token.SHR:
s, _ := exact.Int64Val(y)
return exact.Shift(x, e.Op, uint(s))
default:
return exact.BinaryOp(x, e.Op, y)
}
case *ast.UnaryExpr:
return exact.UnaryOp(e.Op, evalAction(e.X), -1)
case *ast.CallExpr:
fmt.Printf("Can't handle call (%s) yet at pos %d\n", e.Fun, e.Pos())
return nil
case *ast.Ident:
fmt.Printf("Can't handle Ident %s here at pos %d\n", e.Name, e.Pos())
return nil
case *ast.ParenExpr:
return evalAction(e.X)
default:
fmt.Println("Can't handle")
fmt.Printf("n: %s, e: %s\n", n, e)
return nil
}
}
作者:hackrol
项目:daily-progra
// 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 exact.Sign(x.val) < 0 {
check.invalidArg(x.pos(), "index %s must not be negative", &x)
return
}
i, valid = exact.Int64Val(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
}
作者:qioixi
项目:llg
func (c *compiler) NewConstValue(v exact.Value, typ types.Type) *LLVMValue {
switch {
case v.Kind() == exact.Unknown:
// TODO nil literals should be represented more appropriately once the exact-package supports it.
llvmtyp := c.types.ToLLVM(typ)
return c.NewValue(llvm.ConstNull(llvmtyp), typ)
case isString(typ):
if isUntyped(typ) {
typ = types.Typ[types.String]
}
llvmtyp := c.types.ToLLVM(typ)
strval := exact.StringVal(v)
strlen := len(strval)
i8ptr := llvm.PointerType(llvm.Int8Type(), 0)
var ptr llvm.Value
if strlen > 0 {
init := llvm.ConstString(strval, false)
ptr = llvm.AddGlobal(c.module.Module, init.Type(), "")
ptr.SetInitializer(init)
ptr = llvm.ConstBitCast(ptr, i8ptr)
} else {
ptr = llvm.ConstNull(i8ptr)
}
len_ := llvm.ConstInt(c.types.inttype, uint64(strlen), false)
llvmvalue := llvm.Undef(llvmtyp)
llvmvalue = llvm.ConstInsertValue(llvmvalue, ptr, []uint32{0})
llvmvalue = llvm.ConstInsertValue(llvmvalue, len_, []uint32{1})
return c.NewValue(llvmvalue, typ)
case isInteger(typ):
if isUntyped(typ) {
typ = types.Typ[types.Int]
}
llvmtyp := c.types.ToLLVM(typ)
var llvmvalue llvm.Value
if isUnsigned(typ) {
v, _ := exact.Uint64Val(v)
llvmvalue = llvm.ConstInt(llvmtyp, v, false)
} else {
v, _ := exact.Int64Val(v)
llvmvalue = llvm.ConstInt(llvmtyp, uint64(v), true)
}
return c.NewValue(llvmvalue, typ)
case isBoolean(typ):
if isUntyped(typ) {
typ = types.Typ[types.Bool]
}
var llvmvalue llvm.Value
if exact.BoolVal(v) {
llvmvalue = llvm.ConstAllOnes(llvm.Int1Type())
} else {
llvmvalue = llvm.ConstNull(llvm.Int1Type())
}
return c.NewValue(llvmvalue, typ)
case isFloat(typ):
if isUntyped(typ) {
typ = types.Typ[types.Float64]
}
llvmtyp := c.types.ToLLVM(typ)
floatval, _ := exact.Float64Val(v)
llvmvalue := llvm.ConstFloat(llvmtyp, floatval)
return c.NewValue(llvmvalue, typ)
case typ == types.Typ[types.UnsafePointer]:
llvmtyp := c.types.ToLLVM(typ)
v, _ := exact.Uint64Val(v)
llvmvalue := llvm.ConstInt(llvmtyp, v, false)
return c.NewValue(llvmvalue, typ)
case isComplex(typ):
if isUntyped(typ) {
typ = types.Typ[types.Complex128]
}
llvmtyp := c.types.ToLLVM(typ)
floattyp := llvmtyp.StructElementTypes()[0]
llvmvalue := llvm.ConstNull(llvmtyp)
realv := exact.Real(v)
imagv := exact.Imag(v)
realfloatval, _ := exact.Float64Val(realv)
imagfloatval, _ := exact.Float64Val(imagv)
llvmre := llvm.ConstFloat(floattyp, realfloatval)
llvmim := llvm.ConstFloat(floattyp, imagfloatval)
llvmvalue = llvm.ConstInsertValue(llvmvalue, llvmre, []uint32{0})
llvmvalue = llvm.ConstInsertValue(llvmvalue, llvmim, []uint32{1})
return c.NewValue(llvmvalue, typ)
}
// Special case for string -> [](byte|rune)
if u, ok := typ.Underlying().(*types.Slice); ok && isInteger(u.Elem()) {
if v.Kind() == exact.String {
strval := c.NewConstValue(v, types.Typ[types.String])
return strval.Convert(typ).(*LLVMValue)
}
}
panic(fmt.Sprintf("unhandled: t=%s(%T), v=%v(%T)", c.types.TypeString(typ), typ, v, v))
}
作者:kpsmit
项目:gopherj
func Write(pkg *types.Package, out io.Writer, sizes types.Sizes) {
fmt.Fprintf(out, "package %s\n", pkg.Name())
e := &exporter{pkg: pkg, imports: make(map[*types.Package]bool), out: out}
for _, imp := range pkg.Imports() {
e.addImport(imp)
}
for _, name := range pkg.Scope().Names() {
obj := pkg.Scope().Lookup(name)
_, isTypeName := obj.(*types.TypeName)
if obj.Exported() || isTypeName {
e.toExport = append(e.toExport, obj)
}
}
for i := 0; i < len(e.toExport); i++ {
switch o := e.toExport[i].(type) {
case *types.TypeName:
fmt.Fprintf(out, "type %s %s\n", e.makeName(o), e.makeType(o.Type().Underlying()))
if _, isInterface := o.Type().Underlying().(*types.Interface); !isInterface {
writeMethods := func(t types.Type) {
methods := types.NewMethodSet(t)
for i := 0; i < methods.Len(); i++ {
m := methods.At(i)
if len(m.Index()) > 1 {
continue // method of embedded field
}
out.Write([]byte("func (? " + e.makeType(m.Recv()) + ") " + e.makeName(m.Obj()) + e.makeSignature(m.Type()) + "\n"))
}
}
writeMethods(o.Type())
writeMethods(types.NewPointer(o.Type()))
}
case *types.Func:
out.Write([]byte("func " + e.makeName(o) + e.makeSignature(o.Type()) + "\n"))
case *types.Const:
optType := ""
basic, isBasic := o.Type().(*types.Basic)
if !isBasic || basic.Info()&types.IsUntyped == 0 {
optType = " " + e.makeType(o.Type())
}
basic = o.Type().Underlying().(*types.Basic)
var val string
switch {
case basic.Info()&types.IsBoolean != 0:
val = strconv.FormatBool(exact.BoolVal(o.Val()))
case basic.Info()&types.IsInteger != 0:
if basic.Kind() == types.Uint64 {
d, _ := exact.Uint64Val(o.Val())
val = fmt.Sprintf("%#x", d)
break
}
d, _ := exact.Int64Val(o.Val())
if basic.Kind() == types.UntypedRune {
switch {
case d < 0 || d > unicode.MaxRune:
val = fmt.Sprintf("('\\x00' + %d)", d)
case d > 0xffff:
val = fmt.Sprintf("'\\U%08x'", d)
default:
val = fmt.Sprintf("'\\u%04x'", d)
}
break
}
val = fmt.Sprintf("%#x", d)
case basic.Info()&types.IsFloat != 0:
f, _ := exact.Float64Val(o.Val())
val = strconv.FormatFloat(f, 'b', -1, 64)
case basic.Info()&types.IsComplex != 0:
r, _ := exact.Float64Val(exact.Real(o.Val()))
i, _ := exact.Float64Val(exact.Imag(o.Val()))
val = fmt.Sprintf("(%s+%si)", strconv.FormatFloat(r, 'b', -1, 64), strconv.FormatFloat(i, 'b', -1, 64))
case basic.Info()&types.IsString != 0:
val = fmt.Sprintf("%#v", exact.StringVal(o.Val()))
default:
panic("Unhandled constant type: " + basic.String())
}
out.Write([]byte("const " + e.makeName(o) + optType + " = " + val + "\n"))
case *types.Var:
out.Write([]byte("var " + e.makeName(o) + " " + e.makeType(o.Type()) + "\n"))
default:
panic(fmt.Sprintf("Unhandled object: %T\n", o))
}
}
fmt.Fprintf(out, "$$\n")
}
作者:nvdnkp
项目:gopherj
func (c *funcContext) translateExpr(expr ast.Expr) *expression {
exprType := c.p.info.Types[expr].Type
if value := c.p.info.Types[expr].Value; value != nil {
basic := types.Typ[types.String]
if value.Kind() != exact.String { // workaround for bug in go/types
basic = exprType.Underlying().(*types.Basic)
}
switch {
case basic.Info()&types.IsBoolean != 0:
return c.formatExpr("%s", strconv.FormatBool(exact.BoolVal(value)))
case basic.Info()&types.IsInteger != 0:
if is64Bit(basic) {
d, _ := exact.Uint64Val(value)
if basic.Kind() == types.Int64 {
return c.formatExpr("new %s(%s, %s)", c.typeName(exprType), strconv.FormatInt(int64(d)>>32, 10), strconv.FormatUint(d&(1<<32-1), 10))
}
return c.formatExpr("new %s(%s, %s)", c.typeName(exprType), strconv.FormatUint(d>>32, 10), strconv.FormatUint(d&(1<<32-1), 10))
}
d, _ := exact.Int64Val(value)
return c.formatExpr("%s", strconv.FormatInt(d, 10))
case basic.Info()&types.IsFloat != 0:
f, _ := exact.Float64Val(value)
return c.formatExpr("%s", strconv.FormatFloat(f, 'g', -1, 64))
case basic.Info()&types.IsComplex != 0:
r, _ := exact.Float64Val(exact.Real(value))
i, _ := exact.Float64Val(exact.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 basic.Info()&types.IsString != 0:
return c.formatExpr("%s", encodeString(exact.StringVal(value)))
default:
panic("Unhandled constant type: " + basic.String())
}
}
switch e := expr.(type) {
case *ast.CompositeLit:
if ptrType, isPointer := exprType.(*types.Pointer); isPointer {
exprType = ptrType.Elem()
}
collectIndexedElements := func(elementType types.Type) []string {
elements := make([]string, 0)
i := 0
zero := c.zeroValue(elementType)
for _, element := range e.Elts {
if kve, isKve := element.(*ast.KeyValueExpr); isKve {
key, _ := exact.Int64Val(c.p.info.Types[kve.Key].Value)
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", c.zeroValue(t))
}
zero := c.zeroValue(t.Elem())
for len(elements) < int(t.Len()) {
elements = append(elements, zero)
}
return c.formatExpr(`$toNativeArray("%s", [%s])`, typeKind(t.Elem()), strings.Join(elements, ", "))
case *types.Slice:
return c.formatExpr("new %s([%s])", c.typeName(exprType), strings.Join(collectIndexedElements(t.Elem()), ", "))
case *types.Map:
mapVar := c.newVariable("_map")
keyVar := c.newVariable("_key")
assignments := ""
for _, element := range e.Elts {
kve := element.(*ast.KeyValueExpr)
assignments += c.formatExpr(`%s = %s, %s[%s] = { k: %s, v: %s }, `, keyVar, c.translateImplicitConversion(kve.Key, t.Key()), mapVar, c.makeKey(c.newIdent(keyVar, t.Key()), t.Key()), keyVar, c.translateImplicitConversion(kve.Value, t.Elem())).String()
}
return c.formatExpr("(%s = new $Map(), %s%s)", mapVar, assignments, mapVar)
case *types.Struct:
elements := make([]string, t.NumFields())
isKeyValue := true
if len(e.Elts) != 0 {
_, isKeyValue = e.Elts[0].(*ast.KeyValueExpr)
}
if !isKeyValue {
for i, element := range e.Elts {
elements[i] = c.translateImplicitConversion(element, t.Field(i).Type()).String()
}
}
if isKeyValue {
for i := range elements {
elements[i] = c.zeroValue(t.Field(i).Type())
}
for _, element := range e.Elts {
//.........这里部分代码省略.........
作者:nvdnkp
项目:gopherj
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.info.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.info.Types[e].Value; val != nil {
out.WriteString(c.translateExpr(e).String())
return
}
writeExpr("")
case 'f':
e := a[n].(ast.Expr)
if val := c.p.info.Types[e].Value; val != nil {
d, _ := exact.Int64Val(val)
out.WriteString(strconv.FormatInt(d, 10))
return
}
if is64Bit(c.p.info.Types[e].Type.Underlying().(*types.Basic)) {
out.WriteString("$flatten64(")
writeExpr("")
out.WriteString(")")
return
}
writeExpr("")
case 'h':
e := a[n].(ast.Expr)
if val := c.p.info.Types[e].Value; val != nil {
d, _ := exact.Uint64Val(val)
if c.p.info.Types[e].Type.Underlying().(*types.Basic).Kind() == types.Int64 {
out.WriteString(strconv.FormatInt(int64(d)>>32, 10))
//.........这里部分代码省略.........
作者:rjammal
项目:emg
func (cdd *CDD) varDecl(w *bytes.Buffer, typ types.Type, global bool, name string, val ast.Expr) (acds []*CDD) {
dim, acds := cdd.Type(w, typ)
w.WriteByte(' ')
w.WriteString(dimFuncPtr(name, dim))
constInit := true // true if C declaration can init value
if global {
cdd.copyDecl(w, ";\n") // Global variables may need declaration
if val != nil {
if i, ok := val.(*ast.Ident); !ok || i.Name != "nil" {
constInit = cdd.exprValue(val) != nil
}
}
}
if constInit {
w.WriteString(" = ")
if val != nil {
cdd.Expr(w, val, typ)
} else {
zeroVal(w, typ)
}
}
w.WriteString(";\n")
cdd.copyDef(w)
if !constInit {
w.Reset()
// Runtime initialisation
assign := false
switch t := underlying(typ).(type) {
case *types.Slice:
switch vt := val.(type) {
case *ast.CompositeLit:
aname := "array" + cdd.gtc.uniqueId()
var n int64
for _, elem := range vt.Elts {
switch e := elem.(type) {
case *ast.KeyValueExpr:
val := cdd.exprValue(e.Key)
if val == nil {
panic("slice: composite literal with non-constant key")
}
m, ok := exact.Int64Val(val)
if !ok {
panic("slice: can't convert " + val.String() + " to int64")
}
m++
if m > n {
n = m
}
default:
n++
}
}
at := types.NewArray(t.Elem(), n)
o := types.NewVar(vt.Lbrace, cdd.gtc.pkg, aname, at)
cdd.gtc.pkg.Scope().Insert(o)
acd := cdd.gtc.newCDD(o, VarDecl, cdd.il)
av := *vt
cdd.gtc.ti.Types[&av] = types.TypeAndValue{Type: at} // BUG: thread-unsafe
acd.varDecl(new(bytes.Buffer), o.Type(), cdd.gtc.isGlobal(o), aname, &av)
cdd.InitNext = acd
acds = append(acds, acd)
w.WriteByte('\t')
w.WriteString(name)
w.WriteString(" = ASLICE(")
w.WriteString(strconv.FormatInt(at.Len(), 10))
w.WriteString(", ")
w.WriteString(aname)
w.WriteString(");\n")
default:
assign = true
}
case *types.Array:
w.WriteByte('\t')
w.WriteString("ACPY(")
w.WriteString(name)
w.WriteString(", ")
switch val.(type) {
case *ast.CompositeLit:
w.WriteString("((")
dim, _ := cdd.Type(w, t.Elem())
dim = append([]string{"[]"}, dim...)
w.WriteString("(" + dimFuncPtr("", dim) + "))")
cdd.Expr(w, val, typ)
default:
cdd.Expr(w, val, typ)
}
//.........这里部分代码省略.........
作者:hackrol
项目:daily-progra
// representableConst reports whether x can be represented as
// value of the given basic type kind 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 values; it is left alone otherwise.
// It is ok to provide the addressof the first argument for rounded.
func representableConst(x exact.Value, conf *Config, as BasicKind, rounded *exact.Value) bool {
switch x.Kind() {
case exact.Unknown:
return true
case exact.Bool:
return as == Bool || as == UntypedBool
case exact.Int:
if x, ok := exact.Int64Val(x); ok {
switch as {
case Int:
var s = uint(conf.sizeof(Typ[as])) * 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:
return true
case Uint, Uintptr:
if s := uint(conf.sizeof(Typ[as])) * 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
case Float32, Float64, Complex64, Complex128,
UntypedInt, UntypedFloat, UntypedComplex:
return true
}
}
n := exact.BitLen(x)
switch as {
case Uint, Uintptr:
var s = uint(conf.sizeof(Typ[as])) * 8
return exact.Sign(x) >= 0 && n <= int(s)
case Uint64:
return exact.Sign(x) >= 0 && n <= 64
case Float32, Complex64:
if rounded == nil {
return fitsFloat32(x)
}
r := roundFloat32(x)
if r != nil {
*rounded = r
return true
}
case Float64, Complex128:
if rounded == nil {
return fitsFloat64(x)
}
r := roundFloat64(x)
if r != nil {
*rounded = r
return true
}
case UntypedInt, UntypedFloat, UntypedComplex:
return true
}
case exact.Float:
switch as {
case Float32, Complex64:
if rounded == nil {
return fitsFloat32(x)
}
r := roundFloat32(x)
if r != nil {
*rounded = r
return true
}
case Float64, Complex128:
if rounded == nil {
return fitsFloat64(x)
}
r := roundFloat64(x)
if r != nil {
//.........这里部分代码省略.........
作者:hajimehosh
项目:gopherj
func (c *funcContext) translateExpr(expr ast.Expr) *expression {
exprType := c.p.info.Types[expr].Type
if value := c.p.info.Types[expr].Value; value != nil {
basic := types.Typ[types.String]
if value.Kind() != exact.String { // workaround for bug in go/types
basic = exprType.Underlying().(*types.Basic)
}
switch {
case basic.Info()&types.IsBoolean != 0:
return c.formatExpr("%s", strconv.FormatBool(exact.BoolVal(value)))
case basic.Info()&types.IsInteger != 0:
if is64Bit(basic) {
d, _ := exact.Uint64Val(value)
if basic.Kind() == types.Int64 {
return c.formatExpr("new %s(%s, %s)", c.typeName(exprType), strconv.FormatInt(int64(d)>>32, 10), strconv.FormatUint(d&(1<<32-1), 10))
}
return c.formatExpr("new %s(%s, %s)", c.typeName(exprType), strconv.FormatUint(d>>32, 10), strconv.FormatUint(d&(1<<32-1), 10))
}
d, _ := exact.Int64Val(value)
return c.formatExpr("%s", strconv.FormatInt(d, 10))
case basic.Info()&types.IsFloat != 0:
f, _ := exact.Float64Val(value)
return c.formatExpr("%s", strconv.FormatFloat(f, 'g', -1, 64))
case basic.Info()&types.IsComplex != 0:
r, _ := exact.Float64Val(exact.Real(value))
i, _ := exact.Float64Val(exact.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 basic.Info()&types.IsString != 0:
return c.formatExpr("%s", encodeString(exact.StringVal(value)))
default:
panic("Unhandled constant type: " + basic.String())
}
}
switch e := expr.(type) {
case *ast.CompositeLit:
if ptrType, isPointer := exprType.(*types.Pointer); isPointer {
exprType = ptrType.Elem()
}
collectIndexedElements := func(elementType types.Type) []string {
elements := make([]string, 0)
i := 0
zero := c.zeroValue(elementType)
for _, element := range e.Elts {
if kve, isKve := element.(*ast.KeyValueExpr); isKve {
key, _ := exact.Int64Val(c.p.info.Types[kve.Key].Value)
i = int(key)
element = kve.Value
}
for len(elements) <= i {
elements = append(elements, zero)
}
elements[i] = c.translateImplicitConversion(element, elementType).String()
i++
}
return elements
}
switch t := exprType.Underlying().(type) {
case *types.Array:
elements := collectIndexedElements(t.Elem())
if len(elements) != 0 {
zero := c.zeroValue(t.Elem())
for len(elements) < int(t.Len()) {
elements = append(elements, zero)
}
return c.formatExpr(`go$toNativeArray("%s", [%s])`, typeKind(t.Elem()), strings.Join(elements, ", "))
}
return c.formatExpr(`go$makeNativeArray("%s", %d, function() { return %s; })`, typeKind(t.Elem()), int(t.Len()), c.zeroValue(t.Elem()))
case *types.Slice:
return c.formatExpr("new %s([%s])", c.typeName(exprType), strings.Join(collectIndexedElements(t.Elem()), ", "))
case *types.Map:
mapVar := c.newVariable("_map")
keyVar := c.newVariable("_key")
assignments := ""
for _, element := range e.Elts {
kve := element.(*ast.KeyValueExpr)
assignments += c.formatExpr(`%s = %s, %s[%s] = { k: %s, v: %s }, `, keyVar, c.translateImplicitConversion(kve.Key, t.Key()), mapVar, c.makeKey(c.newIdent(keyVar, t.Key()), t.Key()), keyVar, c.translateImplicitConversion(kve.Value, t.Elem())).String()
}
return c.formatExpr("(%s = new Go$Map(), %s%s)", mapVar, assignments, mapVar)
case *types.Struct:
elements := make([]string, t.NumFields())
isKeyValue := true
if len(e.Elts) != 0 {
_, isKeyValue = e.Elts[0].(*ast.KeyValueExpr)
}
if !isKeyValue {
for i, element := range e.Elts {
elements[i] = c.translateImplicitConversion(element, t.Field(i).Type()).String()
}
}
if isKeyValue {
for i := range elements {
elements[i] = c.zeroValue(t.Field(i).Type())
}
for _, element := range e.Elts {
//.........这里部分代码省略.........
作者:Bosh-for-Cp
项目:bosh-260
// typInternal contains the core of type checking of types.
// Must only be called by typ.
//
func (check *checker) typInternal(e ast.Expr, def *Named, cycleOk bool) Type {
switch e := e.(type) {
case *ast.BadExpr:
// ignore - error reported before
case *ast.Ident:
var x operand
check.ident(&x, e, def, cycleOk)
switch x.mode {
case typexpr:
return x.typ
case invalid:
// ignore - error reported before
case novalue:
check.errorf(x.pos(), "%s used as type", &x)
default:
check.errorf(x.pos(), "%s is not a type", &x)
}
case *ast.SelectorExpr:
var x operand
check.selector(&x, e)
switch x.mode {
case typexpr:
return x.typ
case invalid:
// ignore - error reported before
case novalue:
check.errorf(x.pos(), "%s used as type", &x)
default:
check.errorf(x.pos(), "%s is not a type", &x)
}
case *ast.ParenExpr:
return check.typ(e.X, def, cycleOk)
case *ast.ArrayType:
if e.Len != nil {
var x operand
check.expr(&x, e.Len)
if x.mode != constant {
if x.mode != invalid {
check.errorf(x.pos(), "array length %s must be constant", &x)
}
break
}
if !x.isInteger() {
check.errorf(x.pos(), "array length %s must be integer", &x)
break
}
n, ok := exact.Int64Val(x.val)
if !ok || n < 0 {
check.errorf(x.pos(), "invalid array length %s", &x)
break
}
typ := new(Array)
if def != nil {
def.underlying = typ
}
typ.len = n
typ.elem = check.typ(e.Elt, nil, cycleOk)
return typ
} else {
typ := new(Slice)
if def != nil {
def.underlying = typ
}
typ.elem = check.typ(e.Elt, nil, true)
return typ
}
case *ast.StructType:
typ := new(Struct)
if def != nil {
def.underlying = typ
}
typ.fields, typ.tags = check.collectFields(e.Fields, cycleOk)
return typ
case *ast.StarExpr:
typ := new(Pointer)
if def != nil {
def.underlying = typ
}
typ.base = check.typ(e.X, nil, true)
return typ
case *ast.FuncType:
return check.funcType(nil, e, def)
//.........这里部分代码省略.........