本文整理汇总了Golang中go/constant.StringVal函数的典型用法代码示例。如果您正苦于以下问题:Golang StringVal函数的具体用法?Golang StringVal怎么用?Golang StringVal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了StringVal函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: compareOp
// Comapres xv to yv using operator op
// Both xv and yv must be loaded and have a compatible type (as determined by negotiateType)
func compareOp(op token.Token, xv *Variable, yv *Variable) (bool, error) {
switch xv.Kind {
case reflect.Bool:
fallthrough
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
fallthrough
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
fallthrough
case reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
return constantCompare(op, xv.Value, yv.Value)
case reflect.String:
if int64(len(constant.StringVal(xv.Value))) != xv.Len || int64(len(constant.StringVal(yv.Value))) != yv.Len {
return false, fmt.Errorf("string too long for comparison")
}
return constantCompare(op, xv.Value, yv.Value)
}
if op != token.EQL && op != token.NEQ {
return false, fmt.Errorf("operator %s not defined on %s", op.String(), xv.Kind.String())
}
var eql bool
var err error
switch xv.Kind {
case reflect.Ptr:
eql = xv.Children[0].Addr == yv.Children[0].Addr
case reflect.Array:
if int64(len(xv.Children)) != xv.Len || int64(len(yv.Children)) != yv.Len {
return false, fmt.Errorf("array too long for comparison")
}
eql, err = equalChildren(xv, yv, true)
case reflect.Struct:
if len(xv.Children) != len(yv.Children) {
return false, nil
}
if int64(len(xv.Children)) != xv.Len || int64(len(yv.Children)) != yv.Len {
return false, fmt.Errorf("sturcture too deep for comparison")
}
eql, err = equalChildren(xv, yv, false)
case reflect.Slice, reflect.Map, reflect.Func, reflect.Chan:
if xv != nilVariable && yv != nilVariable {
return false, fmt.Errorf("can not compare %s variables", xv.Kind.String())
}
eql = xv.base == yv.base
default:
return false, fmt.Errorf("unimplemented comparison of %s variables", xv.Kind.String())
}
if op == token.NEQ {
return !eql, err
}
return eql, err
}
开发者ID:josephyzhou,项目名称:delve,代码行数:57,代码来源:eval.go
示例2: goVal
// goVal returns the Go value for val, or nil.
func goVal(val constant.Value) interface{} {
// val should exist, but be conservative and check
if val == nil {
return nil
}
// Match implementation restriction of other compilers.
// gc only checks duplicates for integer, floating-point
// and string values, so only create Go values for these
// types.
switch val.Kind() {
case constant.Int:
if x, ok := constant.Int64Val(val); ok {
return x
}
if x, ok := constant.Uint64Val(val); ok {
return x
}
case constant.Float:
if x, ok := constant.Float64Val(val); ok {
return x
}
case constant.String:
return constant.StringVal(val)
}
return nil
}
开发者ID:duhaibo0404,项目名称:go-1,代码行数:27,代码来源:stmt.go
示例3: value
func (p *exporter) value(x constant.Value) {
if trace {
p.tracef("value { ")
defer p.tracef("} ")
}
switch kind := x.Kind(); kind {
case constant.Bool:
tag := falseTag
if constant.BoolVal(x) {
tag = trueTag
}
p.int(tag)
case constant.Int:
if i, ok := constant.Int64Val(x); ok {
p.int(int64Tag)
p.int64(i)
return
}
p.int(floatTag)
p.float(x)
case constant.Float:
p.int(fractionTag)
p.fraction(x)
case constant.Complex:
p.int(complexTag)
p.fraction(constant.Real(x))
p.fraction(constant.Imag(x))
case constant.String:
p.int(stringTag)
p.string(constant.StringVal(x))
default:
panic(fmt.Sprintf("unexpected value kind %d", kind))
}
}
开发者ID:julesGoullee,项目名称:gopherjs,代码行数:35,代码来源:export.go
示例4: getGoInformation
func (dbp *Process) getGoInformation() (ver GoVersion, isextld bool, err error) {
vv, err := dbp.EvalPackageVariable("runtime.buildVersion")
if err != nil {
err = fmt.Errorf("Could not determine version number: %v\n", err)
return
}
if vv.Unreadable != nil {
err = fmt.Errorf("Unreadable version number: %v\n", vv.Unreadable)
return
}
ver, ok := parseVersionString(constant.StringVal(vv.Value))
if !ok {
err = fmt.Errorf("Could not parse version number: %v\n", vv.Value)
return
}
rdr := dbp.DwarfReader()
rdr.Seek(0)
for entry, err := rdr.NextCompileUnit(); entry != nil; entry, err = rdr.NextCompileUnit() {
if err != nil {
return ver, isextld, err
}
if prod, ok := entry.Val(dwarf.AttrProducer).(string); ok && (strings.HasPrefix(prod, "GNU AS")) {
isextld = true
break
}
}
return
}
开发者ID:CedarLogic,项目名称:delve,代码行数:30,代码来源:proc.go
示例5: parseG
func (gvar *Variable) parseG() (*G, error) {
mem := gvar.mem
dbp := gvar.dbp
gaddr := uint64(gvar.Addr)
_, deref := gvar.RealType.(*dwarf.PtrType)
initialInstructions := make([]byte, dbp.arch.PtrSize()+1)
initialInstructions[0] = op.DW_OP_addr
binary.LittleEndian.PutUint64(initialInstructions[1:], gaddr)
if deref {
gaddrbytes, err := mem.readMemory(uintptr(gaddr), dbp.arch.PtrSize())
if err != nil {
return nil, fmt.Errorf("error derefing *G %s", err)
}
initialInstructions = append([]byte{op.DW_OP_addr}, gaddrbytes...)
gaddr = binary.LittleEndian.Uint64(gaddrbytes)
if gaddr == 0 {
id := 0
if thread, ok := mem.(*Thread); ok {
id = thread.ID
}
return nil, NoGError{tid: id}
}
}
if gaddr == 0 {
return nil, NoGError{}
}
gvar.loadValue()
if gvar.Unreadable != nil {
return nil, gvar.Unreadable
}
schedVar := gvar.toFieldNamed("sched")
pc, _ := constant.Int64Val(schedVar.toFieldNamed("pc").Value)
sp, _ := constant.Int64Val(schedVar.toFieldNamed("sp").Value)
id, _ := constant.Int64Val(gvar.toFieldNamed("goid").Value)
gopc, _ := constant.Int64Val(gvar.toFieldNamed("gopc").Value)
waitReason := constant.StringVal(gvar.toFieldNamed("waitreason").Value)
d := gvar.toFieldNamed("_defer")
deferPC := int64(0)
fnvar := d.toFieldNamed("fn")
if fnvar != nil {
fnvalvar := fnvar.toFieldNamed("fn")
deferPC, _ = constant.Int64Val(fnvalvar.Value)
}
status, _ := constant.Int64Val(gvar.toFieldNamed("atomicstatus").Value)
f, l, fn := gvar.dbp.goSymTable.PCToLine(uint64(pc))
g := &G{
ID: int(id),
GoPC: uint64(gopc),
PC: uint64(pc),
SP: uint64(sp),
WaitReason: waitReason,
DeferPC: uint64(deferPC),
Status: uint64(status),
CurrentLoc: Location{PC: uint64(pc), File: f, Line: l, Fn: fn},
dbp: gvar.dbp,
}
return g, nil
}
开发者ID:oldenbur,项目名称:delve,代码行数:59,代码来源:variables.go
示例6: checkPrintf
// checkPrintf checks a call to a formatted print routine such as Printf.
// call.Args[formatIndex] is (well, should be) the format argument.
func (f *File) checkPrintf(call *ast.CallExpr, name string, formatIndex int) {
if formatIndex >= len(call.Args) {
f.Bad(call.Pos(), "too few arguments in call to", name)
return
}
lit := f.pkg.types[call.Args[formatIndex]].Value
if lit == nil {
if *verbose {
f.Warn(call.Pos(), "can't check non-constant format in call to", name)
}
return
}
if lit.Kind() != constant.String {
f.Badf(call.Pos(), "constant %v not a string in call to %s", lit, name)
return
}
format := constant.StringVal(lit)
firstArg := formatIndex + 1 // Arguments are immediately after format string.
if !strings.Contains(format, "%") {
if len(call.Args) > firstArg {
f.Badf(call.Pos(), "no formatting directive in %s call", name)
}
return
}
// Hard part: check formats against args.
argNum := firstArg
indexed := false
for i, w := 0, 0; i < len(format); i += w {
w = 1
if format[i] == '%' {
state := f.parsePrintfVerb(call, name, format[i:], firstArg, argNum)
if state == nil {
return
}
w = len(state.format)
if state.indexed {
indexed = true
}
if !f.okPrintfArg(call, state) { // One error per format is enough.
return
}
if len(state.argNums) > 0 {
// Continue with the next sequential argument.
argNum = state.argNums[len(state.argNums)-1] + 1
}
}
}
// Dotdotdot is hard.
if call.Ellipsis.IsValid() && argNum >= len(call.Args)-1 {
return
}
// If the arguments were direct indexed, we assume the programmer knows what's up.
// Otherwise, there should be no leftover arguments.
if !indexed && argNum != len(call.Args) {
expect := argNum - firstArg
numArgs := len(call.Args) - firstArg
f.Badf(call.Pos(), "wrong number of args for format in %s call: %d needed but %d args", name, expect, numArgs)
}
}
开发者ID:wheelcomplex,项目名称:go-1,代码行数:61,代码来源:print.go
示例7: stringConstantArg
// stringConstantArg returns call's string constant argument at the index idx.
//
// ("", false) is returned if call's argument at the index idx isn't a string
// constant.
func stringConstantArg(f *File, call *ast.CallExpr, idx int) (string, bool) {
if idx >= len(call.Args) {
return "", false
}
arg := call.Args[idx]
lit := f.pkg.types[arg].Value
if lit != nil && lit.Kind() == constant.String {
return constant.StringVal(lit), true
}
return "", false
}
开发者ID:Harvey-OS,项目名称:go,代码行数:15,代码来源:print.go
示例8: constValue
// constValue returns the value of the constant with the
// dynamic type tag appropriate for c.Type().
func constValue(c *ssa.Const) value {
if c.IsNil() {
return zero(c.Type()) // typed nil
}
if t, ok := c.Type().Underlying().(*types.Basic); ok {
// TODO(adonovan): eliminate untyped constants from SSA form.
switch t.Kind() {
case types.Bool, types.UntypedBool:
return exact.BoolVal(c.Value)
case types.Int, types.UntypedInt:
// Assume sizeof(int) is same on host and target.
return int(c.Int64())
case types.Int8:
return int8(c.Int64())
case types.Int16:
return int16(c.Int64())
case types.Int32, types.UntypedRune:
return int32(c.Int64())
case types.Int64:
return c.Int64()
case types.Uint:
// Assume sizeof(uint) is same on host and target.
return uint(c.Uint64())
case types.Uint8:
return uint8(c.Uint64())
case types.Uint16:
return uint16(c.Uint64())
case types.Uint32:
return uint32(c.Uint64())
case types.Uint64:
return c.Uint64()
case types.Uintptr:
// Assume sizeof(uintptr) is same on host and target.
return uintptr(c.Uint64())
case types.Float32:
return float32(c.Float64())
case types.Float64, types.UntypedFloat:
return c.Float64()
case types.Complex64:
return complex64(c.Complex128())
case types.Complex128, types.UntypedComplex:
return c.Complex128()
case types.String, types.UntypedString:
if c.Value.Kind() == exact.String {
return exact.StringVal(c.Value)
}
return string(rune(c.Int64()))
}
}
panic(fmt.Sprintf("constValue: %s", c))
}
开发者ID:tsandall,项目名称:opa,代码行数:55,代码来源:ops.go
示例9: identifierConstant
func (c *funcContext) identifierConstant(expr ast.Expr) (string, bool) {
val := c.p.Types[expr].Value
if val == nil {
return "", false
}
s := constant.StringVal(val)
if len(s) == 0 {
return "", false
}
for i, c := range s {
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (i > 0 && c >= '0' && c <= '9') || c == '_' || c == '$') {
return "", false
}
}
return s, true
}
开发者ID:camlistore,项目名称:camlistore,代码行数:16,代码来源:expressions.go
示例10: RelString
func (c *Const) RelString(from *types.Package) string {
var s string
if c.Value == nil {
s = "nil"
} else if c.Value.Kind() == exact.String {
s = exact.StringVal(c.Value)
const max = 20
// TODO(adonovan): don't cut a rune in half.
if len(s) > max {
s = s[:max-3] + "..." // abbreviate
}
s = strconv.Quote(s)
} else {
s = c.Value.String()
}
return s + ":" + relType(c.Type(), from)
}
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:17,代码来源:const15.go
示例11: newConstant
func newConstant(val constant.Value, mem memoryReadWriter) *Variable {
v := &Variable{Value: val, mem: mem, loaded: true}
switch val.Kind() {
case constant.Int:
v.Kind = reflect.Int
case constant.Float:
v.Kind = reflect.Float64
case constant.Bool:
v.Kind = reflect.Bool
case constant.Complex:
v.Kind = reflect.Complex128
case constant.String:
v.Kind = reflect.String
v.Len = int64(len(constant.StringVal(val)))
}
return v
}
开发者ID:DuoSoftware,项目名称:v6engine-deps,代码行数:17,代码来源:variables.go
示例12: value
func (p *exporter) value(x constant.Value) {
if trace {
p.tracef("= ")
}
switch x.Kind() {
case constant.Bool:
tag := falseTag
if constant.BoolVal(x) {
tag = trueTag
}
p.tag(tag)
case constant.Int:
if v, exact := constant.Int64Val(x); exact {
// common case: x fits into an int64 - use compact encoding
p.tag(int64Tag)
p.int64(v)
return
}
// uncommon case: large x - use float encoding
// (powers of 2 will be encoded efficiently with exponent)
p.tag(floatTag)
p.float(constant.ToFloat(x))
case constant.Float:
p.tag(floatTag)
p.float(x)
case constant.Complex:
p.tag(complexTag)
p.float(constant.Real(x))
p.float(constant.Imag(x))
case constant.String:
p.tag(stringTag)
p.string(constant.StringVal(x))
case constant.Unknown:
// package contains type errors
p.tag(unknownTag)
default:
log.Fatalf("gcimporter: unexpected value %v (%T)", x, x)
}
}
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:46,代码来源:bexport.go
示例13: ConvertVar
func ConvertVar(v *proc.Variable) *Variable {
r := Variable{
Addr: v.Addr,
Name: v.Name,
Kind: v.Kind,
Len: v.Len,
Cap: v.Cap,
}
if v.DwarfType != nil {
r.Type = v.DwarfType.String()
}
if v.RealType != nil {
r.RealType = v.RealType.String()
}
if v.Unreadable != nil {
r.Unreadable = v.Unreadable.Error()
}
if v.Value != nil {
switch v.Kind {
case reflect.Float32:
f, _ := constant.Float64Val(v.Value)
r.Value = strconv.FormatFloat(f, 'f', -1, 32)
case reflect.Float64:
f, _ := constant.Float64Val(v.Value)
r.Value = strconv.FormatFloat(f, 'f', -1, 64)
case reflect.String, reflect.Func:
r.Value = constant.StringVal(v.Value)
default:
r.Value = v.Value.String()
}
}
r.Children = make([]Variable, len(v.Children))
for i := range v.Children {
r.Children[i] = *ConvertVar(&v.Children[i])
}
return &r
}
开发者ID:puyox,项目名称:delve,代码行数:44,代码来源:conversions.go
示例14: convertConstantValue
func (c *converter) convertConstantValue(v goconstant.Value) constant.Value {
if v == nil {
return nil
}
if v, ok := c.converted[v]; ok {
return v.(constant.Value)
}
var ret constant.Value
switch v.Kind() {
case goconstant.Bool:
ret = constant.MakeBool(goconstant.BoolVal(v))
case goconstant.String:
ret = constant.MakeString(goconstant.StringVal(v))
case goconstant.Int:
ret = constant.MakeFromLiteral(v.String(), token.INT, 0)
case goconstant.Float:
ret = constant.MakeFromLiteral(v.String(), token.FLOAT, 0)
case goconstant.Complex:
ret = constant.MakeFromLiteral(v.String(), token.IMAG, 0)
}
c.converted[v] = ret
return ret
}
开发者ID:tcard,项目名称:sgo,代码行数:23,代码来源:importer.go
示例15: stringVal
// stringVal returns the (unquoted) string value and true if
// tv is a string constant; otherwise it returns "" and false.
func stringVal(tv types.TypeAndValue) (string, bool) {
if tv.IsValue() && tv.Value != nil && tv.Value.Kind() == constant.String {
return constant.StringVal(tv.Value), true
}
return "", false
}
开发者ID:Harvey-OS,项目名称:go,代码行数:8,代码来源:fmt_test.go
示例16: ConvertVar
// ConvertVar converts from proc.Variable to api.Variable.
func ConvertVar(v *proc.Variable) *Variable {
r := Variable{
Addr: v.Addr,
OnlyAddr: v.OnlyAddr,
Name: v.Name,
Kind: v.Kind,
Len: v.Len,
Cap: v.Cap,
}
r.Type = prettyTypeName(v.DwarfType)
r.RealType = prettyTypeName(v.RealType)
if v.Unreadable != nil {
r.Unreadable = v.Unreadable.Error()
}
if v.Value != nil {
switch v.Kind {
case reflect.Float32:
f, _ := constant.Float64Val(v.Value)
r.Value = strconv.FormatFloat(f, 'f', -1, 32)
case reflect.Float64:
f, _ := constant.Float64Val(v.Value)
r.Value = strconv.FormatFloat(f, 'f', -1, 64)
case reflect.String, reflect.Func:
r.Value = constant.StringVal(v.Value)
default:
r.Value = v.Value.String()
}
}
switch v.Kind {
case reflect.Complex64:
r.Children = make([]Variable, 2)
r.Len = 2
real, _ := constant.Float64Val(constant.Real(v.Value))
imag, _ := constant.Float64Val(constant.Imag(v.Value))
r.Children[0].Name = "real"
r.Children[0].Kind = reflect.Float32
r.Children[0].Value = strconv.FormatFloat(real, 'f', -1, 32)
r.Children[1].Name = "imaginary"
r.Children[1].Kind = reflect.Float32
r.Children[1].Value = strconv.FormatFloat(imag, 'f', -1, 32)
case reflect.Complex128:
r.Children = make([]Variable, 2)
r.Len = 2
real, _ := constant.Float64Val(constant.Real(v.Value))
imag, _ := constant.Float64Val(constant.Imag(v.Value))
r.Children[0].Name = "real"
r.Children[0].Kind = reflect.Float64
r.Children[0].Value = strconv.FormatFloat(real, 'f', -1, 64)
r.Children[1].Name = "imaginary"
r.Children[1].Kind = reflect.Float64
r.Children[1].Value = strconv.FormatFloat(imag, 'f', -1, 64)
default:
r.Children = make([]Variable, len(v.Children))
for i := range v.Children {
r.Children[i] = *ConvertVar(&v.Children[i])
}
}
return &r
}
开发者ID:RJAugust,项目名称:delve,代码行数:73,代码来源:conversions.go
示例17: builtin
//.........这里部分代码省略.........
// fallthrough
}
// check general case by creating custom signature
sig := makeSig(S, S, NewSlice(T)) // []T required for variadic signature
sig.variadic = true
check.arguments(x, call, sig, func(x *operand, i int) {
// only evaluate arguments that have not been evaluated before
if i < len(alist) {
*x = alist[i]
return
}
arg(x, i)
}, nargs)
// ok to continue even if check.arguments reported errors
x.mode = value
x.typ = S
if check.Types != nil {
check.recordBuiltinType(call.Fun, sig)
}
case _Cap, _Len:
// cap(x)
// len(x)
mode := invalid
var typ Type
var val constant.Value
switch typ = implicitArrayDeref(x.typ.Underlying()); t := typ.(type) {
case *Basic:
if isString(t) && id == _Len {
if x.mode == constant_ {
mode = constant_
val = constant.MakeInt64(int64(len(constant.StringVal(x.val))))
} else {
mode = value
}
}
case *Array:
mode = value
// spec: "The expressions len(s) and cap(s) are constants
// if the type of s is an array or pointer to an array and
// the expression s does not contain channel receives or
// function calls; in this case s is not evaluated."
if !check.hasCallOrRecv {
mode = constant_
val = constant.MakeInt64(t.len)
}
case *Slice, *Chan:
mode = value
case *Map:
if id == _Len {
mode = value
}
}
if mode == invalid {
check.invalidArg(x.pos(), "%s for %s", x, bin.name)
return
}
x.mode = mode
x.typ = Typ[Int]
开发者ID:Greentor,项目名称:go,代码行数:67,代码来源:builtins.go
示例18: TestVariableEvaluation
func TestVariableEvaluation(t *testing.T) {
testcases := []struct {
name string
st reflect.Kind
value interface{}
length, cap int64
childrenlen int
}{
{"a1", reflect.String, "foofoofoofoofoofoo", 18, 0, 0},
{"a11", reflect.Array, nil, 3, -1, 3},
{"a12", reflect.Slice, nil, 2, 2, 2},
{"a13", reflect.Slice, nil, 3, 3, 3},
{"a2", reflect.Int, int64(6), 0, 0, 0},
{"a3", reflect.Float64, float64(7.23), 0, 0, 0},
{"a4", reflect.Array, nil, 2, -1, 2},
{"a5", reflect.Slice, nil, 5, 5, 5},
{"a6", reflect.Struct, nil, 2, 0, 2},
{"a7", reflect.Ptr, nil, 1, 0, 1},
{"a8", reflect.Struct, nil, 2, 0, 2},
{"a9", reflect.Ptr, nil, 1, 0, 1},
{"baz", reflect.String, "bazburzum", 9, 0, 0},
{"neg", reflect.Int, int64(-1), 0, 0, 0},
{"f32", reflect.Float32, float64(float32(1.2)), 0, 0, 0},
{"c64", reflect.Complex64, complex128(complex64(1 + 2i)), 0, 0, 0},
{"c128", reflect.Complex128, complex128(2 + 3i), 0, 0, 0},
{"a6.Baz", reflect.Int, int64(8), 0, 0, 0},
{"a7.Baz", reflect.Int, int64(5), 0, 0, 0},
{"a8.Baz", reflect.String, "feh", 3, 0, 0},
{"a8", reflect.Struct, nil, 2, 0, 2},
{"i32", reflect.Array, nil, 2, -1, 2},
{"b1", reflect.Bool, true, 0, 0, 0},
{"b2", reflect.Bool, false, 0, 0, 0},
{"f", reflect.Func, "main.barfoo", 0, 0, 0},
{"ba", reflect.Slice, nil, 200, 200, 64},
}
withTestProcess("testvariables", t, func(p *Process, fixture protest.Fixture) {
assertNoError(p.Continue(), t, "Continue() returned an error")
for _, tc := range testcases {
v, err := evalVariable(p, tc.name)
assertNoError(err, t, fmt.Sprintf("EvalVariable(%s)", tc.name))
if v.Kind != tc.st {
t.Fatalf("%s simple type: expected: %s got: %s", tc.name, tc.st, v.Kind.String())
}
if v.Value == nil && tc.value != nil {
t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
} else {
switch v.Kind {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
x, _ := constant.Int64Val(v.Value)
if y, ok := tc.value.(int64); !ok || x != y {
t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
}
case reflect.Float32, reflect.Float64:
x, _ := constant.Float64Val(v.Value)
if y, ok := tc.value.(float64); !ok || x != y {
t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
}
case reflect.Complex64, reflect.Complex128:
xr, _ := constant.Float64Val(constant.Real(v.Value))
xi, _ := constant.Float64Val(constant.Imag(v.Value))
if y, ok := tc.value.(complex128); !ok || complex(xr, xi) != y {
t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
}
case reflect.String:
if y, ok := tc.value.(string); !ok || constant.StringVal(v.Value) != y {
t.Fatalf("%s value: expected: %v got: %v", tc.name, tc.value, v.Value)
}
}
}
if v.Len != tc.length {
t.Fatalf("%s len: expected: %d got: %d", tc.name, tc.length, v.Len)
}
if v.Cap != tc.cap {
t.Fatalf("%s cap: expected: %d got: %d", tc.name, tc.cap, v.Cap)
}
if len(v.Children) != tc.childrenlen {
t.Fatalf("%s children len: expected %d got: %d", tc.name, tc.childrenlen, len(v.Children))
}
}
})
}
开发者ID:vornet,项目名称:delve,代码行数:84,代码来源:proc_test.go
示例19: Test
func Test(t *testing.T) {
switch runtime.GOOS {
case "windows":
t.Skipf("skipping test on %q (no /usr/bin/diff)", runtime.GOOS)
}
conf := loader.Config{
Fset: token.NewFileSet(),
ParserMode: parser.ParseComments,
}
// Each entry is a single-file package.
// (Multi-file packages aren't interesting for this test.)
// Order matters: each non-template package is processed using
// the preceding template package.
for _, filename := range []string{
"testdata/A.template",
"testdata/A1.go",
"testdata/A2.go",
"testdata/B.template",
"testdata/B1.go",
"testdata/C.template",
"testdata/C1.go",
"testdata/D.template",
"testdata/D1.go",
"testdata/E.template",
"testdata/E1.go",
"testdata/F.template",
"testdata/F1.go",
"testdata/G.template",
"testdata/G1.go",
"testdata/H.template",
"testdata/H1.go",
"testdata/bad_type.template",
"testdata/no_before.template",
"testdata/no_after_return.template",
"testdata/type_mismatch.template",
"testdata/expr_type_mismatch.template",
} {
pkgname := strings.TrimSuffix(filepath.Base(filename), ".go")
conf.CreateFromFilenames(pkgname, filename)
}
iprog, err := conf.Load()
if err != nil {
t.Fatal(err)
}
var xform *eg.Transformer
for _, info := range iprog.Created {
file := info.Files[0]
filename := iprog.Fset.File(file.Pos()).Name() // foo.go
if strings.HasSuffix(filename, "template") {
// a new template
shouldFail, _ := info.Pkg.Scope().Lookup("shouldFail").(*types.Const)
xform, err = eg.NewTransformer(iprog.Fset, info.Pkg, file, &info.Info, *verboseFlag)
if err != nil {
if shouldFail == nil {
t.Errorf("NewTransformer(%s): %s", filename, err)
} else if want := exact.StringVal(shouldFail.Val()); !strings.Contains(err.Error(), want) {
t.Errorf("NewTransformer(%s): got error %q, want error %q", filename, err, want)
}
} else if shouldFail != nil {
t.Errorf("NewTransformer(%s) succeeded unexpectedly; want error %q",
filename, shouldFail.Val())
}
continue
}
if xform == nil {
t.Errorf("%s: no previous template", filename)
continue
}
// apply previous template to this package
n := xform.Transform(&info.Info, info.Pkg, file)
if n == 0 {
t.Errorf("%s: no matches", filename)
continue
}
got := filename + "t" // foo.got
golden := filename + "lden" // foo.golden
// Write actual output to foo.got.
if err := eg.WriteAST(iprog.Fset, got, file); err != nil {
t.Error(err)
}
defer os.Remove(got)
// Compare foo.got with foo.golden.
var cmd *exec.Cmd
//.........这里部分代码省略.........
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:101,代码来源:eg_test.go
示例20: 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
注:本文中的go/constant.StringVal函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论