-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
pretty_print_visitor.rb
83 lines (70 loc) · 1.71 KB
/
pretty_print_visitor.rb
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
73
74
75
76
77
78
79
80
81
82
83
# frozen_string_literal: true
module SyntaxTree
# This visitor pretty-prints the AST into an equivalent s-expression.
class PrettyPrintVisitor < FieldVisitor
attr_reader :q
def initialize(q)
@q = q
end
# This is here because we need to make sure the operator is cast to a string
# before we print it out.
def visit_binary(node)
node(node, "binary") do
field("left", node.left)
text("operator", node.operator.to_s)
field("right", node.right)
comments(node)
end
end
# This is here to make it a little nicer to look at labels since they
# typically have their : at the end of the value.
def visit_label(node)
node(node, "label") do
q.breakable
q.text(":")
q.text(node.value[0...-1])
comments(node)
end
end
private
def comments(node)
return if node.comments.empty?
q.breakable
q.group(2, "(", ")") do
q.seplist(node.comments) { |comment| q.pp(comment) }
end
end
def field(_name, value)
q.breakable
q.pp(value)
end
def list(_name, values)
q.breakable
q.group(2, "(", ")") { q.seplist(values) { |value| q.pp(value) } }
end
def node(_node, type)
q.group(2, "(", ")") do
q.text(type)
yield
end
end
def pairs(_name, values)
q.group(2, "(", ")") do
q.seplist(values) do |(key, value)|
q.pp(key)
if value
q.text("=")
q.group(2) do
q.breakable("")
q.pp(value)
end
end
end
end
end
def text(_name, value)
q.breakable
q.text(value)
end
end
end