github.com/Konstantin8105/c4go@v0.0.0-20240505174241-768bb1c65a51/ast/util.go (about) 1 package ast 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "strconv" 8 "strings" 9 ) 10 11 func removeQuotes(s string) string { 12 s = strings.TrimSpace(s) 13 14 if s == `""` { 15 return "" 16 } 17 if s == `''` { 18 return "" 19 } 20 21 if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' { 22 return s[1 : len(s)-1] 23 } 24 if len(s) >= 2 && s[0] == '\'' && s[len(s)-1] == '\'' { 25 return s[1 : len(s)-1] 26 } 27 28 return s 29 } 30 31 func atof(s string) float64 { 32 f, err := strconv.ParseFloat(s, 64) 33 if err != nil { 34 panic(err) 35 } 36 return f 37 } 38 39 func unquote(s string) string { 40 r, err := strconv.Unquote(s) 41 if err != nil { 42 return s 43 } 44 return r 45 } 46 47 // Atos - ASTree to string 48 // Typically using for debug 49 func Atos(node Node) string { 50 j, err := json.Marshal(node) 51 if err != nil { 52 panic(err) 53 } 54 var out bytes.Buffer 55 err = json.Indent(&out, j, "", " ") 56 if err != nil { 57 panic(err) 58 } 59 var str string 60 str += fmt.Sprint("==== START OF AST tree ====\n") 61 str += out.String() 62 str += TypesTree(node) 63 str += fmt.Sprint("==== END OF AST tree ====\n") 64 return str 65 } 66 67 // TypesTree - return tree of types for AST node 68 func TypesTree(node Node) (str string) { 69 str += fmt.Sprintf("\nTypes tree:\n") 70 str += typesTree(node, 0) 71 return str 72 } 73 74 func typesTree(node Node, depth int) (str string) { 75 if node == (Node)(nil) { 76 return "" 77 } 78 for i := 0; i < depth; i++ { 79 str += "\t" 80 } 81 str += fmt.Sprintf("%T\n", node) 82 depth++ 83 if len(node.Children()) > 0 { 84 for _, n := range node.Children() { 85 str += typesTree(n, depth) 86 } 87 } 88 return str 89 }