/
ast14.go
72 lines (60 loc) · 1.32 KB
/
ast14.go
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
60
61
62
63
64
65
66
67
68
69
70
71
72
// Seriál "Programovací jazyk Go"
// https://www.root.cz/serialy/programovaci-jazyk-go/
//
// Seznam příkladů z osmdesáté druhé části:
// https://github.com/tisnik/go-root/blob/master/article_82/README.md
package main
import (
"fmt"
"log"
"strings"
"go/ast"
"go/parser"
)
// výraz, který se má naparsovat
const source = `
array1[10] + array2[x] + array3[a*b+c*d]
`
// nový datový typ implementující rozhraní ast.Visitor
type visitor int
// implementace (jediné) funkce předepsané v rozhraní ast.Visitor
func (v visitor) Visit(n ast.Node) ast.Visitor {
// dosáhli jsme koncového uzlu?
if n == nil {
return nil
}
// tisk pozice a typu uzlu
fmt.Printf("%3d\t", v)
var s string
switch x := n.(type) {
case *ast.BasicLit:
s = x.Value
case *ast.Ident:
s = x.Name
case *ast.UnaryExpr:
s = x.Op.String()
case *ast.BinaryExpr:
s = x.Op.String()
case *ast.IndexExpr:
s = "["
case *ast.ParenExpr:
s = "("
}
indent := strings.Repeat(" ", int(v))
if s != "" {
fmt.Printf("%s%s\n", indent, s)
} else {
fmt.Printf("%s%T\n", indent, n)
}
return v + 1
}
func main() {
// konstrukce parseru a parsing zdrojového kódu
f, err := parser.ParseExpr(source)
if err != nil {
log.Fatal(err)
}
var v visitor
// zahájení průchodu abstraktním syntaktickým stromem
ast.Walk(v, f)
}