本文整理汇总了Golang中golang.org/x/tools/go/exact.StringVal函数的典型用法代码示例。如果您正苦于以下问题:Golang StringVal函数的具体用法?Golang StringVal怎么用?Golang StringVal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了StringVal函数的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: value
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))
}
}
示例2: 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() != exact.String {
f.Badf(call.Pos(), "constant %v not a string in call to %s", lit, name)
return
}
format := exact.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)
}
}
示例3: 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))
}
示例4: identifierConstant
func (c *funcContext) identifierConstant(expr ast.Expr) (string, bool) {
val := c.p.Types[expr].Value
if val == nil {
return "", false
}
s := exact.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
}
示例5: 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)
}
示例6: 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, *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
//.........这里部分代码省略.........
示例7: 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(exact.BoolVal(value)))
case isInteger(basic):
if is64Bit(basic) {
if basic.Kind() == types.Int64 {
d, ok := exact.Int64Val(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 := exact.Uint64Val(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 := exact.Int64Val(value)
if !ok {
panic("could not get exact int")
}
return c.formatExpr("%s", strconv.FormatInt(d, 10))
case isFloat(basic):
f, _ := exact.Float64Val(value)
return c.formatExpr("%s", strconv.FormatFloat(f, 'g', -1, 64))
case isComplex(basic):
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 isString(basic):
return c.formatExpr("%s", encodeString(exact.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 := exact.Int64Val(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))
}
//.........这里部分代码省略.........
示例8: Run
// Run runs program analysis and computes the resulting markup,
// populating *result in a thread-safe manner, first with type
// information then later with pointer analysis information if
// enabled by the pta flag.
//
func Run(pta bool, result *Result) {
conf := loader.Config{
AllowErrors: true,
}
// Silence the default error handler.
// Don't print all errors; we'll report just
// one per errant package later.
conf.TypeChecker.Error = func(e error) {}
var roots, args []string // roots[i] ends with os.PathSeparator
// Enumerate packages in $GOROOT.
root := filepath.Join(runtime.GOROOT(), "src") + string(os.PathSeparator)
roots = append(roots, root)
args = allPackages(root)
log.Printf("GOROOT=%s: %s\n", root, args)
// Enumerate packages in $GOPATH.
for i, dir := range filepath.SplitList(build.Default.GOPATH) {
root := filepath.Join(dir, "src") + string(os.PathSeparator)
roots = append(roots, root)
pkgs := allPackages(root)
log.Printf("GOPATH[%d]=%s: %s\n", i, root, pkgs)
args = append(args, pkgs...)
}
// Uncomment to make startup quicker during debugging.
//args = []string{"golang.org/x/tools/cmd/godoc"}
//args = []string{"fmt"}
if _, err := conf.FromArgs(args, true); err != nil {
// TODO(adonovan): degrade gracefully, not fail totally.
// (The crippling case is a parse error in an external test file.)
result.setStatusf("Analysis failed: %s.", err) // import error
return
}
result.setStatusf("Loading and type-checking packages...")
iprog, err := conf.Load()
if iprog != nil {
// Report only the first error of each package.
for _, info := range iprog.AllPackages {
for _, err := range info.Errors {
fmt.Fprintln(os.Stderr, err)
break
}
}
log.Printf("Loaded %d packages.", len(iprog.AllPackages))
}
if err != nil {
result.setStatusf("Loading failed: %s.\n", err)
return
}
// Create SSA-form program representation.
// Only the transitively error-free packages are used.
prog := ssautil.CreateProgram(iprog, ssa.GlobalDebug)
// Compute the set of main packages, including testmain.
allPackages := prog.AllPackages()
var mainPkgs []*ssa.Package
if testmain := prog.CreateTestMainPackage(allPackages...); testmain != nil {
mainPkgs = append(mainPkgs, testmain)
if p := testmain.Const("packages"); p != nil {
log.Printf("Tested packages: %v", exact.StringVal(p.Value.Value))
}
}
for _, pkg := range allPackages {
if pkg.Pkg.Name() == "main" && pkg.Func("main") != nil {
mainPkgs = append(mainPkgs, pkg)
}
}
log.Print("Transitively error-free main packages: ", mainPkgs)
// Build SSA code for bodies of all functions in the whole program.
result.setStatusf("Constructing SSA form...")
prog.Build()
log.Print("SSA construction complete")
a := analysis{
result: result,
prog: prog,
pcgs: make(map[*ssa.Package]*packageCallGraph),
}
// Build a mapping from openable filenames to godoc file URLs,
// i.e. "/src/" plus path relative to GOROOT/src or GOPATH[i]/src.
a.path2url = make(map[string]string)
for _, info := range iprog.AllPackages {
nextfile:
for _, f := range info.Files {
if f.Pos() == 0 {
continue // e.g. files generated by cgo
}
//.........这里部分代码省略.........
示例9: exprInternal
//.........这里部分代码省略.........
default:
// if utyp is invalid, an error was reported before
if utyp != Typ[Invalid] {
check.errorf(e.Pos(), "invalid composite literal type %s", typ)
goto Error
}
}
x.mode = value
x.typ = typ
case *ast.ParenExpr:
kind := check.rawExpr(x, e.X, nil)
x.expr = e
return kind
case *ast.SelectorExpr:
check.selector(x, e)
case *ast.IndexExpr:
check.expr(x, e.X)
if x.mode == invalid {
goto Error
}
valid := false
length := int64(-1) // valid if >= 0
switch typ := x.typ.Underlying().(type) {
case *Basic:
if isString(typ) {
valid = true
if x.mode == constant {
length = int64(len(exact.StringVal(x.val)))
}
// an indexed string always yields a byte value
// (not a constant) even if the string and the
// index are constant
x.mode = value
x.typ = UniverseByte // use 'byte' name
}
case *Array:
valid = true
length = typ.len
if x.mode != variable {
x.mode = value
}
x.typ = typ.elem
case *Pointer:
if typ, _ := typ.base.Underlying().(*Array); typ != nil {
valid = true
length = typ.len
x.mode = variable
x.typ = typ.elem
}
case *Slice:
valid = true
x.mode = variable
x.typ = typ.elem
case *Map:
var key operand
check.expr(&key, e.Index)
示例10: 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 exact.Value
switch typ = implicitArrayDeref(x.typ.Underlying()); t := typ.(type) {
case *Basic:
if isString(t) && id == _Len {
if x.mode == constant {
mode = constant
val = exact.MakeInt64(int64(len(exact.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 = exact.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]
示例11: newValueFromConst
// newValueFromConst converts a constant value to an LLVM value.
func (fr *frame) newValueFromConst(v exact.Value, typ types.Type) *govalue {
switch {
case v == nil:
llvmtyp := fr.types.ToLLVM(typ)
return newValue(llvm.ConstNull(llvmtyp), typ)
case isString(typ):
if isUntyped(typ) {
typ = types.Typ[types.String]
}
llvmtyp := fr.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(fr.module.Module, init.Type(), "")
ptr.SetInitializer(init)
ptr.SetLinkage(llvm.InternalLinkage)
ptr = llvm.ConstBitCast(ptr, i8ptr)
} else {
ptr = llvm.ConstNull(i8ptr)
}
len_ := llvm.ConstInt(fr.types.inttype, uint64(strlen), false)
llvmvalue := llvm.Undef(llvmtyp)
llvmvalue = llvm.ConstInsertValue(llvmvalue, ptr, []uint32{0})
llvmvalue = llvm.ConstInsertValue(llvmvalue, len_, []uint32{1})
return newValue(llvmvalue, typ)
case isInteger(typ):
if isUntyped(typ) {
typ = types.Typ[types.Int]
}
llvmtyp := fr.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 newValue(llvmvalue, typ)
case isBoolean(typ):
if isUntyped(typ) {
typ = types.Typ[types.Bool]
}
return newValue(boolLLVMValue(exact.BoolVal(v)), typ)
case isFloat(typ):
if isUntyped(typ) {
typ = types.Typ[types.Float64]
}
llvmtyp := fr.types.ToLLVM(typ)
floatval, _ := exact.Float64Val(v)
llvmvalue := llvm.ConstFloat(llvmtyp, floatval)
return newValue(llvmvalue, typ)
case typ == types.Typ[types.UnsafePointer]:
llvmtyp := fr.types.ToLLVM(typ)
v, _ := exact.Uint64Val(v)
llvmvalue := llvm.ConstInt(fr.types.inttype, v, false)
llvmvalue = llvm.ConstIntToPtr(llvmvalue, llvmtyp)
return newValue(llvmvalue, typ)
case isComplex(typ):
if isUntyped(typ) {
typ = types.Typ[types.Complex128]
}
llvmtyp := fr.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 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 := fr.newValueFromConst(v, types.Typ[types.String])
return fr.convert(strval, typ)
}
}
panic(fmt.Sprintf("unhandled: t=%s(%T), v=%v(%T)", typ, typ, v, v))
}