v2 / vlib / v / ast / walker / walker_test.v
66 lines · 61 sloc · 1.26 KB · 667f65bb5fde05bcf1148784049cc28088efd4fa
Raw
1import v.ast
2import v.ast.walker
3import v.parser
4import v.pref
5
6fn parse_text(text string) &ast.File {
7 mut tbl := ast.new_table()
8 prefs := pref.new_preferences()
9 return parser.parse_text(text, '', mut tbl, .skip_comments, prefs)
10}
11
12struct NodeByOffset {
13 pos int
14mut:
15 node ast.Node
16}
17
18fn (mut n NodeByOffset) visit(node &ast.Node) ! {
19 node_pos := node.pos()
20 if n.pos >= node_pos.pos && n.pos <= node_pos.pos + node_pos.len && node !is ast.File {
21 n.node = node
22 return error('')
23 }
24 return
25}
26
27fn test_walk() {
28 source := '
29module main
30struct Foo {
31 name string
32}
33 '
34 file := parse_text(source)
35 mut nbo := NodeByOffset{
36 pos: 13
37 }
38 walker.walk(mut nbo, file)
39 assert nbo.node is ast.Stmt
40 stmt := nbo.node as ast.Stmt
41 assert stmt is ast.StructDecl
42}
43
44fn test_inspect() {
45 source := '
46module main
47 '
48 file := parse_text(source)
49 walker.inspect(file, unsafe { nil }, fn (node &ast.Node, data voidptr) bool {
50 // Second visit must be ast.Stmt
51 if node is ast.Stmt {
52 if node !is ast.Module {
53 // Proceed to another node
54 return false
55 }
56 assert node is ast.Module
57 mod := node as ast.Module
58 assert mod.name == 'main'
59 return false
60 }
61 assert node is ast.File
62 // True means that the inspector must now
63 // inspect the ast.File's children
64 return true
65 })
66}
67