-
-
Notifications
You must be signed in to change notification settings - Fork 54
/
json_visitor.rb
55 lines (44 loc) · 1.09 KB
/
json_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
# frozen_string_literal: true
require "json"
module SyntaxTree
# This visitor transforms the AST into a hash that contains only primitives
# that can be easily serialized into JSON.
class JSONVisitor < FieldVisitor
attr_reader :target
def initialize
@target = nil
end
private
def comments(node)
target[:comments] = visit_all(node.comments)
end
def field(name, value)
target[name] = value.is_a?(Node) ? visit(value) : value
end
def list(name, values)
target[name] = visit_all(values)
end
def node(node, type)
previous = @target
@target = { type: type, location: visit_location(node.location) }
yield
@target
ensure
@target = previous
end
def pairs(name, values)
target[name] = values.map { |(key, value)| [visit(key), visit(value)] }
end
def text(name, value)
target[name] = value
end
def visit_location(location)
[
location.start_line,
location.start_char,
location.end_line,
location.end_char
]
end
end
end