• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang types.TypeString函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中go/types.TypeString函数的典型用法代码示例。如果您正苦于以下问题:Golang TypeString函数的具体用法?Golang TypeString怎么用?Golang TypeString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了TypeString函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: formatMember

func formatMember(obj types.Object, maxname int) string {
	qualifier := types.RelativeTo(obj.Pkg())
	var buf bytes.Buffer
	fmt.Fprintf(&buf, "%-5s %-*s", tokenOf(obj), maxname, obj.Name())
	switch obj := obj.(type) {
	case *types.Const:
		fmt.Fprintf(&buf, " %s = %s", types.TypeString(obj.Type(), qualifier), obj.Val().String())

	case *types.Func:
		fmt.Fprintf(&buf, " %s", types.TypeString(obj.Type(), qualifier))

	case *types.TypeName:
		// Abbreviate long aggregate type names.
		var abbrev string
		switch t := obj.Type().Underlying().(type) {
		case *types.Interface:
			if t.NumMethods() > 1 {
				abbrev = "interface{...}"
			}
		case *types.Struct:
			if t.NumFields() > 1 {
				abbrev = "struct{...}"
			}
		}
		if abbrev == "" {
			fmt.Fprintf(&buf, " %s", types.TypeString(obj.Type().Underlying(), qualifier))
		} else {
			fmt.Fprintf(&buf, " %s", abbrev)
		}

	case *types.Var:
		fmt.Fprintf(&buf, " %s", types.TypeString(obj.Type(), qualifier))
	}
	return buf.String()
}
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:35,代码来源:describe.go


示例2: Params

func (f *fn) Params() string {
	sig := f.TypeInfo.Type().(*types.Signature)
	params := sig.Params()
	p := ""
	comma := ""
	to := params.Len()
	var i int

	if sig.Variadic() {
		to--
	}
	for i = 0; i < to; i++ {
		param := params.At(i)
		name := param.Name()
		if name == "" {
			name = fmt.Sprintf("p%d", i)
		}
		p += fmt.Sprintf("%s%s %s", comma, name, types.TypeString(param.Type(), f.Qualifier))
		comma = ", "
	}
	if sig.Variadic() {
		param := params.At(params.Len() - 1)
		name := param.Name()
		if name == "" {
			name = fmt.Sprintf("p%d", to)
		}
		p += fmt.Sprintf("%s%s ...%s", comma, name, types.TypeString(param.Type().(*types.Slice).Elem(), f.Qualifier))
	}
	return p
}
开发者ID:ernesto-jimenez,项目名称:gogen,代码行数:30,代码来源:generator.go


示例3: identicalSansNames

// identicalSansNames compares two functions to check if their types are identical
// according to the names. e.g.
//   - It does not care if the names of the parameters or return values differ
//   - It does not care if the implementations of the types differ
func identicalSansNames(fa, fb *types.Func) bool {
	// must always succeed
	sigA := fa.Type().(*types.Signature)
	sigB := fb.Type().(*types.Signature)

	var (
		lenParams  = sigA.Params().Len()
		lenResults = sigA.Results().Len()
	)

	if sigB.Params().Len() != lenParams {
		return false
	}

	if sigB.Results().Len() != lenResults {
		return false
	}

	for i := 0; i < lenParams; i++ {
		if types.TypeString(sigA.Params().At(i).Type(), nil) != types.TypeString(sigB.Params().At(i).Type(), nil) {
			return false
		}
	}

	for i := 0; i < lenResults; i++ {
		if types.TypeString(sigA.Results().At(i).Type(), nil) != types.TypeString(sigB.Results().At(i).Type(), nil) {
			return false
		}
	}

	return true
}
开发者ID:motemen,项目名称:gompatible,代码行数:36,代码来源:func.go


示例4: typeString

func (g *goGen) typeString(typ types.Type) string {
	pkg := g.pkg

	switch t := typ.(type) {
	case *types.Named:
		obj := t.Obj()
		if obj.Pkg() == nil { // e.g. error type is *types.Named.
			return types.TypeString(typ, types.RelativeTo(pkg))
		}
		if obj.Pkg() != g.pkg {
			g.errorf("type %s not defined in package %s", t, g.pkg)
		}

		switch t.Underlying().(type) {
		case *types.Interface, *types.Struct:
			return fmt.Sprintf("%s.%s", pkg.Name(), types.TypeString(typ, types.RelativeTo(pkg)))
		default:
			g.errorf("unsupported named type %s / %T", t, t)
		}
	case *types.Pointer:
		switch t := t.Elem().(type) {
		case *types.Named:
			return fmt.Sprintf("*%s", g.typeString(t))
		default:
			g.errorf("not yet supported, pointer type %s / %T", t, t)
		}
	default:
		return types.TypeString(typ, types.RelativeTo(pkg))
	}
	return ""
}
开发者ID:stmuk,项目名称:mobile,代码行数:31,代码来源:gengo.go


示例5: typeString

func (g *goGen) typeString(typ types.Type) string {
	pkg := g.Pkg

	switch t := typ.(type) {
	case *types.Named:
		obj := t.Obj()
		if obj.Pkg() == nil { // e.g. error type is *types.Named.
			return types.TypeString(typ, types.RelativeTo(pkg))
		}
		oPkg := obj.Pkg()
		if !g.validPkg(oPkg) && !isWrapperType(t) {
			g.errorf("type %s is defined in %s, which is not bound", t, oPkg)
			return "TODO"
		}

		switch t.Underlying().(type) {
		case *types.Interface, *types.Struct:
			return fmt.Sprintf("%s%s", g.pkgName(oPkg), types.TypeString(typ, types.RelativeTo(oPkg)))
		default:
			g.errorf("unsupported named type %s / %T", t, t)
		}
	case *types.Pointer:
		switch t := t.Elem().(type) {
		case *types.Named:
			return fmt.Sprintf("*%s", g.typeString(t))
		default:
			g.errorf("not yet supported, pointer type %s / %T", t, t)
		}
	default:
		return types.TypeString(typ, types.RelativeTo(pkg))
	}
	return ""
}
开发者ID:pankona,项目名称:mobile,代码行数:33,代码来源:gengo.go


示例6: PrintSkeleton

//!+
func PrintSkeleton(pkg *types.Package, ifacename, concname string) error {
	obj := pkg.Scope().Lookup(ifacename)
	if obj == nil {
		return fmt.Errorf("%s.%s not found", pkg.Path(), ifacename)
	}
	if _, ok := obj.(*types.TypeName); !ok {
		return fmt.Errorf("%v is not a named type", obj)
	}
	iface, ok := obj.Type().Underlying().(*types.Interface)
	if !ok {
		return fmt.Errorf("type %v is a %T, not an interface",
			obj, obj.Type().Underlying())
	}
	// Use first letter of type name as receiver parameter.
	if !isValidIdentifier(concname) {
		return fmt.Errorf("invalid concrete type name: %q", concname)
	}
	r, _ := utf8.DecodeRuneInString(concname)

	fmt.Printf("// *%s implements %s.%s.\n", concname, pkg.Path(), ifacename)
	fmt.Printf("type %s struct{}\n", concname)
	mset := types.NewMethodSet(iface)
	for i := 0; i < mset.Len(); i++ {
		meth := mset.At(i).Obj()
		sig := types.TypeString(meth.Type(), (*types.Package).Name)
		fmt.Printf("func (%c *%s) %s%s {\n\tpanic(\"unimplemented\")\n}\n",
			r, concname, meth.Name(),
			strings.TrimPrefix(sig, "func"))
	}
	return nil
}
开发者ID:CoderLinDaCheng,项目名称:example,代码行数:32,代码来源:main.go


示例7: printFields

func printFields(printf printfFunc, node ast.Node, fields []describeField) {
	if len(fields) > 0 {
		printf(node, "Fields:")
	}

	// Align the names and the types (requires two passes).
	var width int
	var names []string
	for _, f := range fields {
		var buf bytes.Buffer
		for _, fld := range f.implicits {
			buf.WriteString(fld.Obj().Name())
			buf.WriteByte('.')
		}
		buf.WriteString(f.field.Name())
		name := buf.String()
		if n := utf8.RuneCountInString(name); n > width {
			width = n
		}
		names = append(names, name)
	}

	for i, f := range fields {
		// Print the field type relative to the package
		// in which it was defined, not the query package,
		printf(f.field, "\t%*s %s", -width, names[i],
			types.TypeString(f.field.Type(), types.RelativeTo(f.field.Pkg())))
	}
}
开发者ID:guycook,项目名称:tools,代码行数:29,代码来源:describe.go


示例8: asCandidate

func (b *candidateCollector) asCandidate(obj types.Object) Candidate {
	objClass := classifyObject(obj)
	var typ types.Type
	switch objClass {
	case "const", "func", "var":
		typ = obj.Type()
	case "type":
		typ = obj.Type().Underlying()
	}

	var typStr string
	switch t := typ.(type) {
	case *types.Interface:
		typStr = "interface"
	case *types.Struct:
		typStr = "struct"
	default:
		if _, isBuiltin := obj.(*types.Builtin); isBuiltin {
			typStr = builtinTypes[obj.Name()]
		} else if t != nil {
			typStr = types.TypeString(t, b.qualify)
		}
	}

	return Candidate{
		Class: objClass,
		Name:  obj.Name(),
		Type:  typStr,
	}
}
开发者ID:trevordixon,项目名称:gocode,代码行数:30,代码来源:candidate.go


示例9: listTypes

func (m Method) listTypes(t *types.Tuple) []string {
	num := t.Len()
	list := make([]string, num)
	for i := 0; i < num; i++ {
		list[i] = types.TypeString(t.At(i).Type(), m.gen.qf)
	}
	return list
}
开发者ID:ernesto-jimenez,项目名称:gogen,代码行数:8,代码来源:method.go


示例10: Params

func (f *testFunc) Params() string {
	sig := f.TypeInfo.Type().(*types.Signature)
	params := sig.Params()
	p := ""
	comma := ""
	to := params.Len()
	var i int

	if sig.Variadic() {
		to--
	}
	for i = 1; i < to; i++ {
		param := params.At(i)
		p += fmt.Sprintf("%s%s %s", comma, param.Name(), types.TypeString(param.Type(), f.Qualifier))
		comma = ", "
	}
	if sig.Variadic() {
		param := params.At(params.Len() - 1)
		p += fmt.Sprintf("%s%s ...%s", comma, param.Name(), types.TypeString(param.Type().(*types.Slice).Elem(), f.Qualifier))
	}
	return p
}
开发者ID:rawlingsj,项目名称:gofabric8,代码行数:22,代码来源:main.go


示例11: IsTable

func (p *Parser) IsTable(typ types.Type) (bool, string, Relationship) {
	// log.Printf("--> %s %T\n", types.TypeString(typ, p.Qualifier), typ)
	switch utyp := typ.(type) {
	case *types.Named:
		is, table, rel := p.IsTable(utyp.Underlying())
		if _, ok := utyp.Underlying().(*types.Pointer); !ok {
			table = types.TypeString(utyp, p.Qualifier)
		}
		return is, table, rel
	case *types.Pointer:
		return p.IsTable(utyp.Elem())
	case *types.Struct:
		return true, types.TypeString(utyp, p.Qualifier), RelationshipHasOne
	case *types.Slice:
		is, table, _ := p.IsTable(utyp.Elem())
		return is, table, RelationshipHasMany
	case *types.Array:
		is, table, _ := p.IsTable(utyp.Elem())
		return is, table, RelationshipHasMany
	}

	return false, "", 0
}
开发者ID:bom-d-van,项目名称:go2sql,代码行数:23,代码来源:types.go


示例12: prettyFunc

// prettyFunc pretty-prints fn for the user interface.
// TODO(adonovan): return HTML so we have more markup freedom.
func prettyFunc(this *types.Package, fn *ssa.Function) string {
	if fn.Parent() != nil {
		return fmt.Sprintf("%s in %s",
			types.TypeString(fn.Signature, types.RelativeTo(this)),
			prettyFunc(this, fn.Parent()))
	}
	if fn.Synthetic != "" && fn.Name() == "init" {
		// (This is the actual initializer, not a declared 'func init').
		if fn.Pkg.Pkg == this {
			return "package initializer"
		}
		return fmt.Sprintf("%q package initializer", fn.Pkg.Pkg.Path())
	}
	return fn.RelString(this)
}
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:17,代码来源:callgraph.go


示例13: PrintPlain

func (r *freevarsResult) PrintPlain(printf printfFunc) {
	if len(r.refs) == 0 {
		printf(r.qpos, "No free identifiers.")
	} else {
		printf(r.qpos, "Free identifiers:")
		qualifier := types.RelativeTo(r.qpos.info.Pkg)
		for _, ref := range r.refs {
			// Avoid printing "type T T".
			var typstr string
			if ref.kind != "type" && ref.kind != "label" {
				typstr = " " + types.TypeString(ref.typ, qualifier)
			}
			printf(ref.obj, "%s %s%s", ref.kind, ref.ref, typstr)
		}
	}
}
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:16,代码来源:freevars.go


示例14: TestIntuitiveMethodSet

func TestIntuitiveMethodSet(t *testing.T) {
	const source = `
package P
type A int
func (A) f()
func (*A) g()
`

	fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "hello.go", source, 0)
	if err != nil {
		t.Fatal(err)
	}

	var conf types.Config
	pkg, err := conf.Check("P", fset, []*ast.File{f}, nil)
	if err != nil {
		t.Fatal(err)
	}
	qual := types.RelativeTo(pkg)

	for _, test := range []struct {
		expr string // type expression
		want string // intuitive method set
	}{
		{"A", "(A).f (*A).g"},
		{"*A", "(*A).f (*A).g"},
		{"error", "(error).Error"},
		{"*error", ""},
		{"struct{A}", "(struct{A}).f (*struct{A}).g"},
		{"*struct{A}", "(*struct{A}).f (*struct{A}).g"},
	} {
		tv, err := types.Eval(fset, pkg, 0, test.expr)
		if err != nil {
			t.Errorf("Eval(%s) failed: %v", test.expr, err)
		}
		var names []string
		for _, m := range typeutil.IntuitiveMethodSet(tv.Type, nil) {
			name := fmt.Sprintf("(%s).%s", types.TypeString(m.Recv(), qual), m.Obj().Name())
			names = append(names, name)
		}
		got := strings.Join(names, " ")
		if got != test.want {
			t.Errorf("IntuitiveMethodSet(%s) = %q, want %q", test.expr, got, test.want)
		}
	}
}
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:47,代码来源:ui_test.go


示例15: ReturnTypes

func (f *fn) ReturnTypes() string {
	sig := f.TypeInfo.Type().(*types.Signature)
	params := sig.Results()
	p := ""
	comma := ""
	to := params.Len()
	var i int

	for i = 0; i < to; i++ {
		param := params.At(i)
		p += fmt.Sprintf("%s %s", comma, types.TypeString(param.Type(), f.Qualifier))
		comma = ", "
	}
	if to > 1 {
		p = fmt.Sprintf("(%s)", p)
	}
	return p
}
开发者ID:ernesto-jimenez,项目名称:gogen,代码行数:18,代码来源:generator.go


示例16: printResult

func printResult(res *rta.Result, from *types.Package) string {
	var buf bytes.Buffer

	writeSorted := func(ss []string) {
		sort.Strings(ss)
		for _, s := range ss {
			fmt.Fprintf(&buf, "  %s\n", s)
		}
	}

	buf.WriteString("Dynamic calls\n")
	var edges []string
	callgraph.GraphVisitEdges(res.CallGraph, func(e *callgraph.Edge) error {
		if strings.Contains(e.Description(), "dynamic") {
			edges = append(edges, fmt.Sprintf("%s --> %s",
				e.Caller.Func.RelString(from),
				e.Callee.Func.RelString(from)))
		}
		return nil
	})
	writeSorted(edges)

	buf.WriteString("Reachable functions\n")
	var reachable []string
	for f := range res.Reachable {
		reachable = append(reachable, f.RelString(from))
	}
	writeSorted(reachable)

	buf.WriteString("Reflect types\n")
	var rtypes []string
	res.RuntimeTypes.Iterate(func(key types.Type, value interface{}) {
		if value == false { // accessible to reflection
			rtypes = append(rtypes, types.TypeString(key, types.RelativeTo(from)))
		}
	})
	writeSorted(rtypes)

	return strings.TrimSpace(buf.String())
}
开发者ID:ChloeTigre,项目名称:golang-tools,代码行数:40,代码来源:rta_test.go


示例17: typeString

// TypeString prints type T relative to the query position.
func (qpos *queryPos) typeString(T types.Type) string {
	return types.TypeString(T, types.RelativeTo(qpos.info.Pkg))
}
开发者ID:tsandall,项目名称:opa,代码行数:4,代码来源:guru.go


示例18: genFuncBody

func (g *goGen) genFuncBody(f Func) {
	sig := f.Signature()
	results := sig.Results()
	for i := range results {
		if i > 0 {
			g.Printf(", ")
		}
		g.Printf("_gopy_%03d", i)
	}
	if len(results) > 0 {
		g.Printf(" := ")
	}

	g.Printf("%s.%s(", g.pkg.Name(), f.GoName())

	args := sig.Params()
	for i, arg := range args {
		tail := ""
		if i+1 < len(args) {
			tail = ", "
		}
		head := arg.Name()
		if arg.needWrap() {
			head = fmt.Sprintf(
				"*(*%s)(unsafe.Pointer(%s))",
				types.TypeString(
					arg.GoType(),
					func(*types.Package) string { return g.pkg.Name() },
				),
				arg.Name(),
			)
		}
		g.Printf("%s%s", head, tail)
	}
	g.Printf(")\n")

	if len(results) <= 0 {
		return
	}

	for i, res := range results {
		if !res.needWrap() {
			continue
		}
		g.Printf("cgopy_incref(unsafe.Pointer(&_gopy_%03d))\n", i)
	}

	g.Printf("return ")
	for i, res := range results {
		if i > 0 {
			g.Printf(", ")
		}
		// if needWrap(res.GoType()) {
		// 	g.Printf("")
		// }
		if res.needWrap() {
			g.Printf("%s(unsafe.Pointer(&", res.sym.cgoname)
		}
		g.Printf("_gopy_%03d", i)
		if res.needWrap() {
			g.Printf("))")
		}
	}
	g.Printf("\n")
}
开发者ID:ashrafulratul,项目名称:gopy,代码行数:65,代码来源:gengo.go


示例19: getTypeString

func getTypeString(t types.Type) string {
	return types.TypeString(t, func(*types.Package) string { return " " })
}
开发者ID:ashrafulratul,项目名称:gopy,代码行数:3,代码来源:vars.go


示例20: Parse

func (p *Parser) Parse(info types.Info) (err error) {
	for ident, obj := range info.Defs {
		if ident.Obj == nil {
			continue
		}
		switch ident.Obj.Kind {
		case ast.Con:
			p.Consts[obj.Name()], err = strconv.Unquote(info.Types[ident.Obj.Decl.(*ast.ValueSpec).Values[0]].Value.String())
			if err != nil {
				return
			}
		case ast.Typ:
			struc, ok := obj.Type().Underlying().(*types.Struct)
			if !ok {
				continue
			}

			var table Table
			// table.struc = node
			table.Name = ident.Name
			table.RefName = strings.ToLower(ident.Name[:1])
			table.VarName = strings.ToLower(ident.Name[:1]) + ident.Name[1:]
			table.ColName = inflect.Pluralize(table.Name)
			table.ColRefName = inflect.Pluralize(table.RefName)
			table.ColVarName = inflect.Pluralize(table.VarName)
			table.SQLName = inflect.Pluralize(toSnake(table.Name)) + TableNameSuffix

			for i := 0; i < struc.NumFields(); i++ {
				field := struc.Field(i)
				flags := strings.Split(reflect.StructTag(struc.Tag(i)).Get("go2sql"), ",")

				var column Column
				column.Name = field.Name()
				column.field = field
				column.flags = flags
				column.Table = &table
				column.parser = p

				if len(flags) > 0 && flags[0] != "" {
					if flags[0] == FlagIgnore {
						continue
					}
					column.SQLName = flags[0]
				} else {
					column.SQLName = toSnake(column.Name)
				}

				_, column.IsPointer = field.Type().(*types.Pointer)
				if contains(flags, FlagID) {
					table.IDColumn = &column
				}
				if contains(flags, FlagPK) {
					column.IsPrimaryKey = true
					table.PrimaryKeys = append(table.PrimaryKeys, &column)
				}

				column.Type = types.TypeString(field.Type(), p.Qualifier)
				column.IsTable, column.TableType, column.Relationship = p.IsTable(field.Type())
				if column.IsTable && contains(flags, FlagInline) {
					column.IsTable = false
				}
				table.Columns = append(table.Columns, &column)
			}
			p.Tables[table.Name] = &table
		}
	}

	for _, host := range p.Tables {
		if name, ok := p.Consts[host.Name+TableNameSuffix]; ok {
			host.HasCustomSQLName = true
			host.SQLName = name
		}

		for _, hostc := range host.Columns {
			if !hostc.IsTable {
				continue
			}
			guest := p.Tables[hostc.TableType]
			if guest == nil {
				log.Printf("can't found struct %s\n", hostc.TableType)
				continue
			}

			hostc.TypeTable = guest
			if hostc.Relationship == RelationshipHasOne {
				// reanalyze if it's a valid belongs-to
				belongsTo := true
				for _, pk := range guest.PrimaryKeys {
					// TODO: custome primary key naming
					belongsTo = belongsTo && host.HasColumn(hostc.Name+pk.Name)
				}
				if belongsTo {
					hostc.Relationship = RelationshipBelongsTo
					continue
				}

				// reanalyze if it's a valid has-one
				hasOne := true
				for _, pk := range host.PrimaryKeys {
					// TODO: custome primary key naming
//.........这里部分代码省略.........
开发者ID:bom-d-van,项目名称:go2sql,代码行数:101,代码来源:types.go



注:本文中的go/types.TypeString函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang types.Array类代码示例发布时间:2022-05-28
下一篇:
Golang types.SelectionString函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap