Beispiel #1
0
// NewTypeSignature returns a TypeSignature from the given typespec node
func NewTypeSignature(node *ast.TypeSpec) *TypeSignature {
	buf := new(bytes.Buffer)
	types.WriteExpr(buf, node.Type)

	sig := &TypeSignature{
		Name: node.Name.Name,
		Type: buf.String(),
	}

	sig.Full = fmt.Sprintf("type %s %s", sig.Name, sig.Type)
	return sig
}
Beispiel #2
0
// NewFuncSignature returns a function signature from the given node. Node should
// be of type *ast.FuncDecl or *ast.FuncLit
func NewFuncSignature(node ast.Node) *FuncSignature {
	getParams := func(list []*ast.Field) string {
		out := ""
		for i, p := range list {
			for j, n := range p.Names {
				out += n.Name
				if len(p.Names) != j+1 {
					out += ", "
				}
			}

			if len(p.Names) != 0 {
				out += " "
			}

			buf := new(bytes.Buffer)
			types.WriteExpr(buf, p.Type)
			out += buf.String()

			if len(list) != i+1 {
				out += ", "
			}
		}
		return out
	}

	switch x := node.(type) {
	case *ast.FuncDecl:
		sig := &FuncSignature{
			Name: x.Name.Name,
		}

		multiOutput := false

		if x.Type.Params != nil {
			sig.In = getParams(x.Type.Params.List)
		}
		if x.Type.Results != nil {
			sig.Out = getParams(x.Type.Results.List)
			multiOutput = len(x.Type.Results.List) > 1
		}
		if x.Recv != nil {
			sig.Recv = getParams(x.Recv.List)
		}

		full := "func "

		if sig.Recv != "" {
			full += fmt.Sprintf("(%s) ", sig.Recv)
		}

		full += fmt.Sprintf("%s", sig.Name)

		full += "("
		if sig.In != "" {
			full += fmt.Sprintf("%s", sig.In)
		}
		full += ")"

		if sig.Out != "" {
			if multiOutput {
				full += fmt.Sprintf(" (%s)", sig.Out)
			} else {
				full += fmt.Sprintf(" %s", sig.Out)
			}
		}

		sig.Full = full
		return sig
	case *ast.FuncLit:
		sig := &FuncSignature{}

		multiOutput := false

		if x.Type.Params != nil {
			sig.In = getParams(x.Type.Params.List)
		}
		if x.Type.Results != nil {
			sig.Out = getParams(x.Type.Results.List)
			multiOutput = len(x.Type.Results.List) > 1
		}

		full := "func"

		full += "("
		if sig.In != "" {
			full += fmt.Sprintf("%s", sig.In)
		}
		full += ")"

		if sig.Out != "" {
			if multiOutput {
				full += fmt.Sprintf(" (%s)", sig.Out)
			} else {
				full += fmt.Sprintf(" %s", sig.Out)
			}
		}

		sig.Full = full
		return sig
	default:
		return &FuncSignature{Full: "UNKNOWN"}
	}
}