summaryrefslogtreecommitdiff
path: root/lib/pp.rb
blob: 0a18a6f318a4927360eace0a506f4a0f9ab101da (plain)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
# $Id$

=begin
= Pretty-printer for Ruby objects.

== Which seems better?

non-pretty-printed output by (({p})) is:
  #<PP:0x81a0d10 @stack=[], @genspace=#<Proc:0x81a0cc0>, @nest=[0], @newline="\n", @buf=#<PrettyPrint::Group:0x81a0c98 @group=0, @tail=0, @buf=[#<PrettyPrint::Group:0x81a0ba8 @group=1, @tail=0, @buf=[#<PrettyPrint::Text:0x81a0b30 @tail=2, @width=1, @text="[">, #<PrettyPrint::Group:0x81a0a68 @group=2, @tail=1, @buf=[#<PrettyPrint::Text:0x81a09f0 @tail=1, @width=1, @text="1">], @singleline_width=1>, #<PrettyPrint::Text:0x81a0a7c @tail=0, @width=1, @text=",">, #<PrettyPrint::Breakable:0x81a0a2c @group=2, @genspace=#<Proc:0x81a0cc0>, @newline="\n", @indent=1, @tail=2, @sep=" ", @width=1>, #<PrettyPrint::Group:0x81a09c8 @group=2, @tail=1, @buf=[#<PrettyPrint::Text:0x81a0950 @tail=1, @width=1, @text="2">], @singleline_width=1>, #<PrettyPrint::Text:0x81a0af4 @tail=0, @width=1, @text="]">], @singleline_width=6>], @singleline_width=6>, @sharing_detection=false>

pretty-printed output by (({pp})) is:
  #<PP:0x40d0688
   @buf=
    #<PrettyPrint::Group:0x40d064c
     @buf=
      [#<PrettyPrint::Group:0x40d05d4
	@buf=
	 [#<PrettyPrint::Text:0x40d0598 @tail=2, @text="[", @width=1>,
	  #<PrettyPrint::Group:0x40d0534
	   @buf=[#<PrettyPrint::Text:0x40d04f8 @tail=1, @text="1", @width=1>],
	   @group=2,
	   @singleline_width=1,
	   @tail=1>,
	  #<PrettyPrint::Text:0x40d053e @tail=0, @text=",", @width=1>,
	  #<PrettyPrint::Breakable:0x40d0516
	   @genspace=#<Proc:0x40d0656>,
	   @group=2,
	   @indent=1,
	   @newline="\n",
	   @sep=" ",
	   @tail=2,
	   @width=1>,
	  #<PrettyPrint::Group:0x40d04e4
	   @buf=[#<PrettyPrint::Text:0x40d04a8 @tail=1, @text="2", @width=1>],
	   @group=2,
	   @singleline_width=1,
	   @tail=1>,
	  #<PrettyPrint::Text:0x40d057a @tail=0, @text="]", @width=1>],
	@group=1,
	@singleline_width=6,
	@tail=0>],
     @group=0,
     @singleline_width=6,
     @tail=0>,
   @genspace=#<Proc:0x40d0656>,
   @nest=[0],
   @newline="\n",
   @sharing_detection=false,
   @stack=[]>

I like the latter.  If you do too, this library is for you.

== Usage

: pp(obj)
    output ((|obj|)) to (({$>})) in pretty printed format.

== Customized output
To define your customized pretty printing function for your class,
redefine a method (({pretty_print(((|pp|)))})) in the class.
It takes an argument ((|pp|)) which is an instance of the class ((<PP>)).
The method should use PP#text, PP#breakable, PP#nest, PP#group and
PP#pp to print the object.

= PP
== super class
((<PrettyPrint>))

== class methods
--- PP.pp(obj[, width[, out]])
    outputs ((|obj|)) to ((|out|)) in pretty printed format of
    ((|width|)) columns in width.

--- PP.sharing_detection
    returns the sharing detection flag as boolean value.
    It is false by default.

--- PP.sharing_detection = value
    sets the sharing detection flag.

== methods
--- pp(obj)
    adds ((|obj|)) to the pretty printing buffer
    using Object#pretty_print or Object#pretty_print_cycled.

    Object#pretty_print_cycled is used when ((|obj|)) is already
    printed, a.k.a the object reference chain has a cycle.

= Object
--- pretty_print(pp)
    is a default pretty printing method for general objects.

    If (({self})) has a customized (redefined) (({inspect})) method,
    the result of (({self.inspect})) is used but it obviously has no
    line break hints.

    This module provides predefined pretty_print() methods for some of
    the most commonly used built-in classes for convenience.

--- pretty_print_cycled(pp)
    is a default pretty printing method for general objects that are
    detected as part of a cycle.
=end

require 'prettyprint'

module Kernel
  private
  def pp(*objs)
    objs.each {|obj|
      PP.pp(obj)
    }
  end
end

class PP < PrettyPrint
  def PP.pp(obj, width=79, out=$>)
    pp = PP.new
    pp.guard_inspect_key {pp.pp obj}
    pp.format(out, width)
    #$pp = pp
    out << "\n"
  end

  @@sharing_detection = false
  def PP.sharing_detection
    return @@sharing_detection
  end

  def PP.sharing_detection=(val)
    @@sharing_detection = val
  end

  def initialize
    super
    @sharing_detection = @@sharing_detection
  end

  InspectKey = :__inspect_key__

  def guard_inspect_key
    if Thread.current[InspectKey] == nil
      Thread.current[InspectKey] = []
    end

    save = Thread.current[InspectKey]

    begin
      Thread.current[InspectKey] = []
      yield
    ensure
      Thread.current[InspectKey] = save
    end
  end

  def pp(obj)
    id = obj.__id__

    if Thread.current[InspectKey].include? id
      group {obj.pretty_print_cycled self}
      return
    end

    begin
      Thread.current[InspectKey] << id
      group {obj.pretty_print self}
    ensure
      Thread.current[InspectKey].pop unless @sharing_detection
    end
  end

  def pp_object(obj)
    group {
      text '#<'
      nest(1) {
	text obj.class.name
	text ':'
	text sprintf('0x%x', obj.__id__)
	first = true
	obj.instance_variables.sort.each {|v|
	  if first
	    first = false
	  else
	    text ','
	  end
	  breakable
	  group {
	    text v
	    text '='
	    nest(1) {
	      breakable ''
	      pp(obj.instance_eval v)
	    }
	  }
	}
      }
      text '>'
    }
  end

  def pp_hash(obj)
    group {
      text '{'
      nest(1) {
	first = true
	obj.each {|k, v|
	  if first
	    first = false
	  else
	    text ","
	    breakable
	  end
	  group {
	    pp k
	    text '=>'
	    nest(1) {
	      group {
		breakable ''
		pp v
	      }
	    }
	  }
	}
      }
      text '}'
    }
  end

  module ObjectMixin
    # 1. specific pretty_print
    # 2. specific inspect
    # 3. generic pretty_print

    Key = :__pp_instead_of_inspect__

    def pretty_print(pp)
      # specific pretty_print is not defined, try specific inspect.
      begin
        old = Thread.current[Key]
	result1 = sprintf('#<%s:0x%x pretty_printed>', self.class.name, self.__id__)
        Thread.current[Key] = [pp, result1]
	result2 = ObjectMixin.pp_call_inspect(self)
      ensure
        Thread.current[Key] = old
      end

      unless result1.equal? result2
        pp.text result2
      end
    end

    def ObjectMixin.pp_call_inspect(obj); obj.inspect; end
    CallInspectFrame = "#{__FILE__}:#{__LINE__ - 1}:in `pp_call_inspect'"

    def inspect
      if CallInspectFrame == caller[0]
	# specific inspect is also not defined, use generic pretty_print. 
	pp, result = Thread.current[Key]
	pp.pp_object(self)
	result
      else
	super
      end
    end

    def pretty_print_cycled(pp)
      pp.text sprintf("#<%s:0x%x", self.class.name, self.__id__)
      pp.breakable
      pp.text sprintf("...>")
    end
  end
end

[Numeric, FalseClass, TrueClass, Module].each {|c|
  c.class_eval {
    def pretty_print(pp)
      pp.text self.to_s
    end
  }
}

class Array
  def pretty_print(pp)
    pp.text "["
    pp.nest(1) {
      first = true
      self.each {|v|
	if first
	  first = false
	else
	  pp.text ","
	  pp.breakable
	end
	pp.pp v
      }
    }
    pp.text "]"
  end

  def pretty_print_cycled(pp)
    pp.text(empty? ? '[]' : '[...]')
  end
end

class Hash
  def pretty_print(pp)
    pp.pp_hash self
  end

  def pretty_print_cycled(pp)
    pp.text(empty? ? '{}' : '{...}')
  end
end

class << ENV
  def pretty_print(pp)
    pp.pp_hash self
  end
end

class Struct
  def pretty_print(pp)
    pp.text sprintf("#<%s", self.class.name)
    pp.nest(1) {
      first = true
      self.members.each {|member|
	if first
	  first = false
	else
	  pp.text ","
	end
	pp.breakable
	pp.group {
	  pp.text member.to_s
	  pp.text '='
	  pp.nest(1) {
	    pp.breakable ''
	    pp.pp self[member]
	  }
	}
      }
    }
    pp.text ">"
  end

  def pretty_print_cycled(pp)
    pp.text sprintf("#<%s:...>", self.class.name)
  end
end

class Range
  def pretty_print(pp)
    pp.pp self.begin
    pp.breakable ''
    pp.text(self.exclude_end? ? '...' : '..')
    pp.breakable ''
    pp.pp self.end
  end
end

class File
  class Stat
    def pretty_print(pp)
      require 'etc.so'
      pp.nest(1) {
	pp.text "#<"
	pp.text self.class.name
	pp.breakable; pp.text sprintf("dev=0x%x", self.dev); pp.text ','
	pp.breakable; pp.text "ino="; pp.pp self.ino; pp.text ','
	pp.breakable
	pp.group {
	  m = self.mode
	  pp.text sprintf("mode=0%o", m)
	  pp.breakable
	  pp.text sprintf("(%s %c%c%c%c%c%c%c%c%c)",
	    self.ftype,
	    (m & 0400 == 0 ? ?- : ?r),
	    (m & 0200 == 0 ? ?- : ?w),
	    (m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
	                     (m & 04000 == 0 ? ?x : ?s)),
	    (m & 0040 == 0 ? ?- : ?r),
	    (m & 0020 == 0 ? ?- : ?w),
	    (m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
	                     (m & 02000 == 0 ? ?x : ?s)),
	    (m & 0004 == 0 ? ?- : ?r),
	    (m & 0002 == 0 ? ?- : ?w),
	    (m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
	                     (m & 01000 == 0 ? ?x : ?t)))
	  pp.text ','
	}
	pp.breakable; pp.text "nlink="; pp.pp self.nlink; pp.text ','
	pp.breakable
	pp.group {
	  pp.text "uid="; pp.pp self.uid
	  begin
	    name = Etc.getpwuid(self.uid).name
	    pp.breakable; pp.text "(#{name})"
	  rescue ArgumentError
	  end
	  pp.text ','
	}
	pp.breakable
	pp.group {
	  pp.text "gid="; pp.pp self.gid
	  begin
	    name = Etc.getgrgid(self.gid).name
	    pp.breakable; pp.text "(#{name})"
	  rescue ArgumentError
	  end
	  pp.text ','
	}
	pp.breakable
	pp.group {
	  pp.text sprintf("rdev=0x%x", self.rdev)
	  pp.breakable
	  pp.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor)
	  pp.text ','
	}
	pp.breakable; pp.text "size="; pp.pp self.size; pp.text ','
	pp.breakable; pp.text "blksize="; pp.pp self.blksize; pp.text ','
	pp.breakable; pp.text "blocks="; pp.pp self.blocks; pp.text ','
	pp.breakable
	pp.group {
	  t = self.atime
	  pp.text "atime="; pp.pp t
	  pp.breakable; pp.text "(#{t.tv_sec})"
	  pp.text ','
	}
	pp.breakable
	pp.group {
	  t = self.mtime
	  pp.text "mtime="; pp.pp t
	  pp.breakable; pp.text "(#{t.tv_sec})"
	  pp.text ','
	}
	pp.breakable
	pp.group {
	  t = self.ctime
	  pp.text "ctime="; pp.pp t
	  pp.breakable; pp.text "(#{t.tv_sec})"
	}
	pp.text ">"
      }
    end
  end
end

class Object
  include PP::ObjectMixin
end

[Numeric, Symbol, FalseClass, TrueClass, NilClass, Module].each {|c|
  c.class_eval {
    alias :pretty_print_cycled :pretty_print
  }
}

if __FILE__ == $0
  require 'runit/testcase'
  require 'runit/cui/testrunner'

  class PPTest < RUNIT::TestCase
    def test_list0123_12
      assert_equal("[0, 1, 2, 3]\n", PP.pp([0,1,2,3], 12, ''))
    end

    def test_list0123_11
      assert_equal("[0,\n 1,\n 2,\n 3]\n", PP.pp([0,1,2,3], 11, ''))
    end
  end

  class HasInspect
    def initialize(a)
      @a = a
    end

    def inspect
      return "<inspect:#{@a.inspect}>"
    end
  end

  class HasPrettyPrint
    def initialize(a)
      @a = a
    end

    def pretty_print(pp)
      pp.text "<pretty_print:"
      pp.pp @a
      pp.text ">"
    end
  end

  class HasBoth
    def initialize(a)
      @a = a
    end

    def inspect
      return "<inspect:#{@a.inspect}>"
    end

    def pretty_print(pp)
      pp.text "<pretty_print:"
      pp.pp @a
      pp.text ">"
    end
  end

  class PPInspectTest < RUNIT::TestCase
    def test_hasinspect
      a = HasInspect.new(1)
      assert_equal("<inspect:1>\n", PP.pp(a, 79, ''))
    end

    def test_hasprettyprint
      a = HasPrettyPrint.new(1)
      assert_equal("<pretty_print:1>\n", PP.pp(a, 79, ''))
    end

    def test_hasboth
      a = HasBoth.new(1)
      assert_equal("<pretty_print:1>\n", PP.pp(a, 79, ''))
    end
  end

  class PPCycleTest < RUNIT::TestCase
    def test_array
      a = []
      a << a
      assert_equal("[[...]]\n", PP.pp(a, 79, ''))
    end

    def test_hash
      a = {}
      a[0] = a
      assert_equal("{0=>{...}}\n", PP.pp(a, 79, ''))
    end

    S = Struct.new("S", :a, :b)
    def test_struct
      a = S.new(1,2)
      a.b = a
      assert_equal("#<Struct::S a=1, b=#<Struct::S:...>>\n", PP.pp(a, 79, ''))
    end

    def test_object
      a = Object.new
      a.instance_eval {@a = a}
      hex = '0x' + ('%x'%a.id)
      assert_equal("#<Object:#{hex} @a=#<Object:#{hex} ...>>\n", PP.pp(a, 79, ''))
    end

    def test_withinspect
      a = []
      a << HasInspect.new(a)
      assert_equal("[<inspect:[...]>]\n", PP.pp(a, 79, ''))
    end
  end

  RUNIT::CUI::TestRunner.run(PPTest.suite)
  RUNIT::CUI::TestRunner.run(PPInspectTest.suite)
  RUNIT::CUI::TestRunner.run(PPCycleTest.suite)
end