1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // This file defines a number of miscellaneous utility functions.
17 "golang.org/x/tools/go/ast/astutil"
22 func unparen(e ast.Expr) ast.Expr { return astutil.Unparen(e) }
24 // isBlankIdent returns true iff e is an Ident with name "_".
25 // They have no associated types.Object, and thus no type.
27 func isBlankIdent(e ast.Expr) bool {
28 id, ok := e.(*ast.Ident)
29 return ok && id.Name == "_"
32 //// Type utilities. Some of these belong in go/types.
34 // isPointer returns true for types whose underlying type is a pointer.
35 func isPointer(typ types.Type) bool {
36 _, ok := typ.Underlying().(*types.Pointer)
40 func isInterface(T types.Type) bool { return types.IsInterface(T) }
42 // deref returns a pointer's element type; otherwise it returns typ.
43 func deref(typ types.Type) types.Type {
44 if p, ok := typ.Underlying().(*types.Pointer); ok {
50 // recvType returns the receiver type of method obj.
51 func recvType(obj *types.Func) types.Type {
52 return obj.Type().(*types.Signature).Recv().Type()
55 // logStack prints the formatted "start" message to stderr and
56 // returns a closure that prints the corresponding "end" message.
57 // Call using 'defer logStack(...)()' to show builder stack on panic.
58 // Don't forget trailing parens!
60 func logStack(format string, args ...interface{}) func() {
61 msg := fmt.Sprintf(format, args...)
62 io.WriteString(os.Stderr, msg)
63 io.WriteString(os.Stderr, "\n")
65 io.WriteString(os.Stderr, msg)
66 io.WriteString(os.Stderr, " end\n")
70 // newVar creates a 'var' for use in a types.Tuple.
71 func newVar(name string, typ types.Type) *types.Var {
72 return types.NewParam(token.NoPos, nil, name, typ)
75 // anonVar creates an anonymous 'var' for use in a types.Tuple.
76 func anonVar(typ types.Type) *types.Var {
77 return newVar("", typ)
80 var lenResults = types.NewTuple(anonVar(tInt))
82 // makeLen returns the len builtin specialized to type func(T)int.
83 func makeLen(T types.Type) *Builtin {
84 lenParams := types.NewTuple(anonVar(T))
87 sig: types.NewSignature(nil, lenParams, lenResults, false),