| 1 | import v.ast |
| 2 | import v.ast.walker |
| 3 | import v.parser |
| 4 | import v.pref |
| 5 | |
| 6 | fn 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 | |
| 12 | struct NodeByOffset { |
| 13 | pos int |
| 14 | mut: |
| 15 | node ast.Node |
| 16 | } |
| 17 | |
| 18 | fn (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 | |
| 27 | fn test_walk() { |
| 28 | source := ' |
| 29 | module main |
| 30 | struct 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 | |
| 44 | fn test_inspect() { |
| 45 | source := ' |
| 46 | module 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 | |