Debian Codegraph @

vendor/mruby/mrbgems/mruby-pp/mrblib/1_pp.rb

raw
1 # Copyright (C) 2014-2020 Sutou Kouhei <[email protected]>
2
3 # This file is based on pp.rb in CRuby.
4
5 module Kernel
6 # Returns a pretty printed object as a string.
7 #
8 # In order to use this method you must first require the PP module:
9 #
10 # require 'pp'
11 #
12 # See the PP module for more information.
13 def pretty_inspect
14 PP.pp(self, '')
15 end
16
17 private
18 # prints arguments in pretty form.
19 #
20 # pp returns argument(s).
21 def pp(*objs) # :nodoc:
22 objs.each {|obj|
23 PP.pp(obj)
24 }
25 objs.size <= 1 ? objs.first : objs
26 end
27 module_function :pp # :nodoc:
28 end
29
30 ##
31 # A pretty-printer for Ruby objects.
32 #
33 # All examples assume you have loaded the PP class with:
34 # require 'pp'
35 #
36 ##
37 # == What PP Does
38 #
39 # Standard output by #p returns this:
40 # #<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>>
41 #
42 # Pretty-printed output returns this:
43 # #<PP:0x81fedf0
44 # @buffer=[],
45 # @buffer_width=0,
46 # @genspace=#<Proc:0x81feda0>,
47 # @group_queue=
48 # #<PrettyPrint::GroupQueue:0x81fed3c
49 # @queue=
50 # [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
51 # []]>,
52 # @group_stack=
53 # [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
54 # @indent=0,
55 # @maxwidth=79,
56 # @newline="\n",
57 # @output=#<IO:0x8114ee4>,
58 # @output_width=2>
59 #
60 ##
61 # == Usage
62 #
63 # pp(obj) #=> obj
64 # pp obj #=> obj
65 # pp(obj1, obj2, ...) #=> [obj1, obj2, ...]
66 # pp() #=> nil
67 #
68 # Output <tt>obj(s)</tt> to <tt>$></tt> in pretty printed format.
69 #
70 # It returns <tt>obj(s)</tt>.
71 #
72 ##
73 # == Output Customization
74 #
75 # To define a customized pretty printing function for your classes,
76 # redefine method <code>#pretty_print(pp)</code> in the class.
77 #
78 # <code>#pretty_print</code> takes the +pp+ argument, which is an instance of the PP class.
79 # The method uses #text, #breakable, #nest, #group and #pp to print the
80 # object.
81 #
82 ##
83 # == Pretty-Print JSON
84 #
85 # To pretty-print JSON refer to JSON#pretty_generate.
86 #
87 ##
88 # == Author
89 # Tanaka Akira <[email protected]>
90
91 class PP < PrettyPrint
92 class StandardOutput
93 def <<(string)
94 print(string)
95 self
96 end
97 end
98
99 # Outputs +obj+ to +out+ in pretty printed format of
100 # +width+ columns in width.
101 #
102 # If +out+ is omitted, <code>$></code> is assumed.
103 # If +width+ is omitted, 79 is assumed.
104 #
105 # PP.pp returns +out+.
106 def PP.pp(obj, out=nil, width=79)
107 out ||= StandardOutput.new
108 q = PP.new(out, width)
109 q.guard_inspect_key {q.pp obj}
110 q.flush
111 #$pp = q
112 out << "\n"
113 end
114
115 # Outputs +obj+ to +out+ like PP.pp but with no indent and
116 # newline.
117 #
118 # PP.singleline_pp returns +out+.
119 def PP.singleline_pp(obj, out=$>)
120 q = SingleLine.new(out)
121 q.guard_inspect_key {q.pp obj}
122 q.flush
123 out
124 end
125
126 @sharing_detection = false
127 class << self
128 # Returns the sharing detection flag as a boolean value.
129 # It is false by default.
130 attr_accessor :sharing_detection
131 end
132
133 module PPMethods
134 def initialize(*args)
135 super
136 @inspecting = {}
137 end
138
139 # Yields to a block
140 # and preserves the previous set of objects being printed.
141 def guard_inspect_key
142 save = @inspecting
143
144 begin
145 @inspecting = {}
146 yield
147 ensure
148 @inspecting = save
149 end
150 end
151
152 # Check whether the object_id +id+ is in the current buffer of objects
153 # to be pretty printed. Used to break cycles in chains of objects to be
154 # pretty printed.
155 def check_inspect_key(id)
156 @inspecting.include?(id)
157 end
158
159 # Adds the object_id +id+ to the set of objects being pretty printed, so
160 # as to not repeat objects.
161 def push_inspect_key(id)
162 @inspecting[id] = true
163 end
164
165 # Removes an object from the set of objects being pretty printed.
166 def pop_inspect_key(id)
167 @inspecting.delete id
168 end
169
170 # Adds +obj+ to the pretty printing buffer
171 # using Object#pretty_print or Object#pretty_print_cycle.
172 #
173 # Object#pretty_print_cycle is used when +obj+ is already
174 # printed, a.k.a the object reference chain has a cycle.
175 def pp(obj)
176 id = obj.object_id
177
178 if check_inspect_key(id)
179 group {obj.pretty_print_cycle self}
180 return
181 end
182
183 begin
184 push_inspect_key(id)
185 group {obj.pretty_print self}
186 ensure
187 pop_inspect_key(id) unless PP.sharing_detection
188 end
189 end
190
191 # A convenience method which is same as follows:
192 #
193 # group(1, '#<' + obj.class.name, '>') { ... }
194 def object_group(obj, &block) # :yield:
195 group(1, '#<' + obj.class.name, '>', &block)
196 end
197
198 # A convenience method, like object_group, but also reformats the Object's
199 # object_id.
200 def object_address_group(obj, &block)
201 str = obj.to_s
202 str.chomp!('>')
203 group(1, str, '>', &block)
204 end
205
206 # A convenience method which is same as follows:
207 #
208 # text ','
209 # breakable
210 def comma_breakable
211 text ','
212 breakable
213 end
214
215 # Adds a separated list.
216 # The list is separated by comma with breakable space, by default.
217 #
218 # #seplist iterates the +list+ using +iter_method+.
219 # It yields each object to the block given for #seplist.
220 # The procedure +separator_proc+ is called between each yields.
221 #
222 # If the iteration is zero times, +separator_proc+ is not called at all.
223 #
224 # If +separator_proc+ is nil or not given,
225 # +lambda { comma_breakable }+ is used.
226 # If +iter_method+ is not given, :each is used.
227 #
228 # For example, following 3 code fragments has similar effect.
229 #
230 # q.seplist([1,2,3]) {|v| xxx v }
231 #
232 # q.seplist([1,2,3], lambda { q.comma_breakable }, :each) {|v| xxx v }
233 #
234 # xxx 1
235 # q.comma_breakable
236 # xxx 2
237 # q.comma_breakable
238 # xxx 3
239 def seplist(list, sep=nil, iter_method=:each) # :yield: element
240 sep ||= lambda { comma_breakable }
241 first = true
242 list.__send__(iter_method) {|*v|
243 if first
244 first = false
245 else
246 sep.call
247 end
248 yield(*v)
249 }
250 end
251
252 # A present standard failsafe for pretty printing any given Object
253 def pp_object(obj)
254 object_address_group(obj) {
255 seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v|
256 breakable
257 v = v.to_s if Symbol === v
258 text v
259 text '='
260 group(1) {
261 breakable ''
262 pp(obj.instance_variable_get(v))
263 }
264 }
265 }
266 end
267
268 # A pretty print for a Hash
269 def pp_hash(obj)
270 group(1, '{', '}') {
271 seplist(obj, nil, :each) {|k, v|
272 group {
273 pp k
274 text '=>'
275 group(1) {
276 breakable ''
277 pp v
278 }
279 }
280 }
281 }
282 end
283 end
284
285 include PPMethods
286
287 class SingleLine < PrettyPrint::SingleLine # :nodoc:
288 include PPMethods
289 end
290
291 module ObjectMixin # :nodoc:
292 # 1. specific pretty_print
293 # 2. specific inspect
294 # 3. generic pretty_print
295
296 # A default pretty printing method for general objects.
297 # It calls #pretty_print_instance_variables to list instance variables.
298 #
299 # If +self+ has a customized (redefined) #inspect method,
300 # the result of self.inspect is used but it obviously has no
301 # line break hints.
302 #
303 # This module provides predefined #pretty_print methods for some of
304 # the most commonly used built-in classes for convenience.
305 def pretty_print(q)
306 if methods(false).include?(:inspect)
307 q.text self.inspect
308 else
309 q.pp_object(self)
310 end
311 end
312
313 # A default pretty printing method for general objects that are
314 # detected as part of a cycle.
315 def pretty_print_cycle(q)
316 q.object_address_group(self) {
317 q.breakable
318 q.text '...'
319 }
320 end
321
322 # Returns a sorted array of instance variable names.
323 #
324 # This method should return an array of names of instance variables as symbols or strings as:
325 # +[:@a, :@b]+.
326 def pretty_print_instance_variables
327 instance_variables.sort
328 end
329
330 # Is #inspect implementation using #pretty_print.
331 # If you implement #pretty_print, it can be used as follows.
332 #
333 # alias inspect pretty_print_inspect
334 #
335 # However, doing this requires that every class that #inspect is called on
336 # implement #pretty_print, or a RuntimeError will be raised.
337 def pretty_print_inspect
338 PP.singleline_pp(self, '')
339 end
340 end
341 end
342
343 class String # :nodoc:
344 def pretty_print(q) # :nodoc:
345 q.text inspect
346 end
347
348 def pretty_print_cycle(q) # :nodoc:
349 q.text inspect
350 end
351 end
352
353 class Array # :nodoc:
354 def pretty_print(q) # :nodoc:
355 q.group(1, '[', ']') {
356 q.seplist(self) {|v|
357 q.pp v
358 }
359 }
360 end
361
362 def pretty_print_cycle(q) # :nodoc:
363 q.text(empty? ? '[]' : '[...]')
364 end
365 end
366
367 class Hash # :nodoc:
368 def pretty_print(q) # :nodoc:
369 q.pp_hash self
370 end
371
372 def pretty_print_cycle(q) # :nodoc:
373 q.text(empty? ? '{}' : '{...}')
374 end
375 end
376
377 class Struct # :nodoc:
378 def pretty_print(q) # :nodoc:
379 q.group(1, sprintf("#<struct %s", self.class), '>') {
380 q.seplist(members, lambda { q.text "," }) {|member|
381 q.breakable
382 q.text member.to_s
383 q.text '='
384 q.group(1) {
385 q.breakable ''
386 q.pp self[member]
387 }
388 }
389 }
390 end
391
392 def pretty_print_cycle(q) # :nodoc:
393 q.text sprintf("#<struct %s:...>", self.class)
394 end
395 end
396
397 class Range # :nodoc:
398 def pretty_print(q) # :nodoc:
399 q.pp self.begin
400 q.breakable ''
401 q.text(self.exclude_end? ? '...' : '..')
402 q.breakable ''
403 q.pp self.end
404 end
405 end
406
407 class MatchData # :nodoc:
408 def pretty_print(q) # :nodoc:
409 nc = []
410 self.regexp.named_captures.each {|name, indexes|
411 indexes.each {|i| nc[i] = name }
412 }
413 q.object_group(self) {
414 q.breakable
415 q.seplist(0...self.size, lambda { q.breakable }) {|i|
416 if i == 0
417 q.pp self[i]
418 else
419 if nc[i]
420 q.text nc[i]
421 else
422 q.pp i
423 end
424 q.text ':'
425 q.pp self[i]
426 end
427 }
428 }
429 end
430 end
431
432 class Object < BasicObject # :nodoc:
433 include PP::ObjectMixin
434
435 [Numeric, Symbol, FalseClass, TrueClass, NilClass, Module].each {|c|
436 c.class_eval {
437 def pretty_print_cycle(q)
438 q.text inspect
439 end
440 }
441 }
442
443 [Numeric, FalseClass, TrueClass, NilClass, Module].each {|c|
444 c.class_eval {
445 def pretty_print(q)
446 q.text inspect
447 end
448 }
449 }
450 end