File: print.go

package info (click to toggle)
golang-github-antonmedv-expr 1.8.9-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 4,524 kB
  • sloc: makefile: 6
file content (59 lines) | stat: -rw-r--r-- 1,139 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package ast

import (
	"fmt"
	"reflect"
	"regexp"
)

func Dump(node Node) string {
	return dump(reflect.ValueOf(node), "")
}

func dump(v reflect.Value, ident string) string {
	if !v.IsValid() {
		return "nil"
	}
	t := v.Type()
	switch t.Kind() {
	case reflect.Struct:
		out := t.Name() + "{\n"
		for i := 0; i < t.NumField(); i++ {
			f := t.Field(i)
			if isPrivate(f.Name) {
				continue
			}
			s := v.Field(i)
			out += fmt.Sprintf("%v%v: %v,\n", ident+"\t", f.Name, dump(s, ident+"\t"))
		}
		return out + ident + "}"
	case reflect.Slice:
		if v.Len() == 0 {
			return "[]"
		}
		out := "[\n"
		for i := 0; i < v.Len(); i++ {
			s := v.Index(i)
			out += fmt.Sprintf("%v%v,", ident+"\t", dump(s, ident+"\t"))
			if i+1 < v.Len() {
				out += "\n"
			}
		}
		return out + "\n" + ident + "]"
	case reflect.Ptr:
		return dump(v.Elem(), ident)
	case reflect.Interface:
		return dump(reflect.ValueOf(v.Interface()), ident)

	case reflect.String:
		return fmt.Sprintf("%q", v)
	default:
		return fmt.Sprintf("%v", v)
	}
}

var isCapital = regexp.MustCompile("^[A-Z]")

func isPrivate(s string) bool {
	return !isCapital.Match([]byte(s))
}