@@ -4,6 +4,26 @@ module SyntaxTree
4
4
# A slightly enhanced PP that knows how to format recursively including
5
5
# comments.
6
6
class Formatter < PrettierPrint
7
+ # It's very common to use seplist with ->(q) { q.breakable_return }. We wrap
8
+ # that pattern into an object to cut down on having to create a bunch of
9
+ # lambdas all over the place.
10
+ class BreakableReturnSeparator
11
+ def call ( q )
12
+ q . breakable_return
13
+ end
14
+ end
15
+
16
+ # Similar to the previous, it's common to ->(q) { q.breakable_space }. We
17
+ # also wrap that pattern into an object to cut down on lambdas.
18
+ class BreakableSpaceSeparator
19
+ def call ( q )
20
+ q . breakable_space
21
+ end
22
+ end
23
+
24
+ BREAKABLE_RETURN_SEPARATOR = BreakableReturnSeparator . new
25
+ BREAKABLE_SPACE_SEPARATOR = BreakableSpaceSeparator . new
26
+
7
27
# We want to minimize as much as possible the number of options that are
8
28
# available in syntax tree. For the most part, if users want non-default
9
29
# formatting, they should override the format methods on the specific nodes
@@ -75,8 +95,7 @@ def format(node, stackable: true)
75
95
doc =
76
96
if leading . last &.ignore?
77
97
range = source [ node . location . start_char ...node . location . end_char ]
78
- separator = -> { breakable ( indent : false , force : true ) }
79
- seplist ( range . split ( /\r ?\n / , -1 ) , separator ) { |line | text ( line ) }
98
+ seplist ( range . split ( /\r ?\n / , -1 ) , Formatter ::BREAKABLE_RETURN_SEPARATOR ) { |line | text ( line ) }
80
99
else
81
100
node . format ( self )
82
101
end
@@ -108,5 +127,42 @@ def parent
108
127
def parents
109
128
stack [ 0 ...-1 ] . reverse_each
110
129
end
130
+
131
+ # This is a simplified version of prettyprint's group. It doesn't provide
132
+ # any of the more advanced options because we don't need them and they take
133
+ # up expensive computation time.
134
+ def group
135
+ contents = [ ]
136
+ doc = Group . new ( 0 , contents : contents )
137
+
138
+ groups << doc
139
+ target << doc
140
+
141
+ with_target ( contents ) { yield }
142
+ groups . pop
143
+ doc
144
+ end
145
+
146
+ # A similar version to the super, except that it calls back into the
147
+ # separator proc with the instance of `self`.
148
+ def seplist ( list , sep = nil , iter_method = :each ) # :yield: element
149
+ first = true
150
+ list . __send__ ( iter_method ) do |*v |
151
+ if first
152
+ first = false
153
+ elsif sep
154
+ sep . call ( self )
155
+ else
156
+ comma_breakable
157
+ end
158
+ yield ( *v )
159
+ end
160
+ end
161
+
162
+ # This is a much simplified version of prettyprint's text. It avoids
163
+ # calculating width by pushing the string directly onto the target.
164
+ def text ( string )
165
+ target << string
166
+ end
111
167
end
112
168
end
0 commit comments