1 # == Pretty-printer for Ruby objects.
3 # = Which seems better?
5 # non-pretty-printed output by #p is:
6 # #<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>>
8 # pretty-printed output by #pp is:
12 # @genspace=#<Proc:0x81feda0>,
14 # #<PrettyPrint::GroupQueue:0x81fed3c
16 # [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
19 # [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>],
23 # @output=#<IO:0x8114ee4>,
26 # I like the latter. If you do too, this library is for you.
32 # output +obj+ to +$>+ in pretty printed format.
36 # = Output Customization
37 # To define your customized pretty printing function for your classes,
38 # redefine a method #pretty_print(+pp+) in the class.
39 # It takes an argument +pp+ which is an instance of the class PP.
40 # The method should use PP#text, PP#breakable, PP#nest, PP#group and
41 # PP#pp to print the object.
44 # Tanaka Akira <akr@m17n.org>
49 # returns a pretty printed object as a string.
55 # prints arguments in pretty form.
67 class PP < PrettyPrint
68 # Outputs +obj+ to +out+ in pretty printed format of
69 # +width+ columns in width.
71 # If +out+ is omitted, +$>+ is assumed.
72 # If +width+ is omitted, 79 is assumed.
74 # PP.pp returns +out+.
75 def PP.pp(obj, out=$>, width=79)
76 q = PP.new(out, width)
77 q.guard_inspect_key {q.pp obj}
83 # Outputs +obj+ to +out+ like PP.pp but with no indent and
86 # PP.singleline_pp returns +out+.
87 def PP.singleline_pp(obj, out=$>)
88 q = SingleLine.new(out)
89 q.guard_inspect_key {q.pp obj}
95 def PP.mcall(obj, mod, meth, *args, &block)
96 mod.instance_method(meth).bind(obj).call(*args, &block)
100 @sharing_detection = false
102 # Returns the sharing detection flag as a boolean value.
103 # It is false by default.
104 attr_accessor :sharing_detection
108 def guard_inspect_key
109 if Thread.current[:__recursive_key__] == nil
110 Thread.current[:__recursive_key__] = {}
113 if Thread.current[:__recursive_key__][:inspect] == nil
114 Thread.current[:__recursive_key__][:inspect] = {}
117 save = Thread.current[:__recursive_key__][:inspect]
120 Thread.current[:__recursive_key__][:inspect] = {}
123 Thread.current[:__recursive_key__][:inspect] = save
127 def check_inspect_key(id)
128 Thread.current[:__recursive_key__] &&
129 Thread.current[:__recursive_key__][:inspect] &&
130 Thread.current[:__recursive_key__][:inspect].include?(id)
132 def push_inspect_key(id)
133 Thread.current[:__recursive_key__][:inspect][id] = true
135 def pop_inspect_key(id)
136 Thread.current[:__recursive_key__][:inspect].delete id
139 # Adds +obj+ to the pretty printing buffer
140 # using Object#pretty_print or Object#pretty_print_cycle.
142 # Object#pretty_print_cycle is used when +obj+ is already
143 # printed, a.k.a the object reference chain has a cycle.
147 if check_inspect_key(id)
148 group {obj.pretty_print_cycle self}
154 group {obj.pretty_print self}
156 pop_inspect_key(id) unless PP.sharing_detection
160 # A convenience method which is same as follows:
162 # group(1, '#<' + obj.class.name, '>') { ... }
163 def object_group(obj, &block) # :yield:
164 group(1, '#<' + obj.class.name, '>', &block)
167 if 0x100000000.class == Bignum
169 PointerMask = 0xffffffff
172 PointerMask = 0xffffffffffffffff
175 case Object.new.inspect
176 when /\A\#<Object:0x([0-9a-f]+)>\z/
177 PointerFormat = "%0#{$1.length}x"
182 def object_address_group(obj, &block)
183 id = PointerFormat % (obj.object_id * 2 & PointerMask)
184 group(1, "\#<#{obj.class}:0x#{id}", '>', &block)
187 # A convenience method which is same as follows:
196 # Adds a separated list.
197 # The list is separated by comma with breakable space, by default.
199 # #seplist iterates the +list+ using +iter_method+.
200 # It yields each object to the block given for #seplist.
201 # The procedure +separator_proc+ is called between each yields.
203 # If the iteration is zero times, +separator_proc+ is not called at all.
205 # If +separator_proc+ is nil or not given,
206 # +lambda { comma_breakable }+ is used.
207 # If +iter_method+ is not given, :each is used.
209 # For example, following 3 code fragments has similar effect.
211 # q.seplist([1,2,3]) {|v| xxx v }
213 # q.seplist([1,2,3], lambda { q.comma_breakable }, :each) {|v| xxx v }
220 def seplist(list, sep=nil, iter_method=:each) # :yield: element
221 sep ||= lambda { comma_breakable }
223 list.__send__(iter_method) {|*v|
234 object_address_group(obj) {
235 seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v|
237 v = v.to_s if Symbol === v
242 pp(obj.instance_eval(v))
250 seplist(obj, nil, :each_pair) {|k, v|
266 class SingleLine < PrettyPrint::SingleLine
271 # 1. specific pretty_print
272 # 2. specific inspect
273 # 3. specific to_s if instance variable is empty
274 # 4. generic pretty_print
276 # A default pretty printing method for general objects.
277 # It calls #pretty_print_instance_variables to list instance variables.
279 # If +self+ has a customized (redefined) #inspect method,
280 # the result of self.inspect is used but it obviously has no
283 # This module provides predefined #pretty_print methods for some of
284 # the most commonly used built-in classes for convenience.
286 if /\(Kernel\)#/ !~ Object.instance_method(:method).bind(self).call(:inspect).inspect
288 elsif /\(Kernel\)#/ !~ Object.instance_method(:method).bind(self).call(:to_s).inspect && instance_variables.empty?
295 # A default pretty printing method for general objects that are
296 # detected as part of a cycle.
297 def pretty_print_cycle(q)
298 q.object_address_group(self) {
304 # Returns a sorted array of instance variable names.
306 # This method should return an array of names of instance variables as symbols or strings as:
308 def pretty_print_instance_variables
309 instance_variables.sort
312 # Is #inspect implementation using #pretty_print.
313 # If you implement #pretty_print, it can be used as follows.
315 # alias inspect pretty_print_inspect
317 # However, doing this requires that every class that #inspect is called on
318 # implement #pretty_print, or a RuntimeError will be raised.
319 def pretty_print_inspect
320 if /\(PP::ObjectMixin\)#/ =~ Object.instance_method(:method).bind(self).call(:pretty_print).inspect
321 raise "pretty_print is not overridden for #{self.class}"
323 PP.singleline_pp(self, '')
330 q.group(1, '[', ']') {
337 def pretty_print_cycle(q)
338 q.text(empty? ? '[]' : '[...]')
347 def pretty_print_cycle(q)
348 q.text(empty? ? '{}' : '{...}')
355 ENV.keys.sort.each {|k|
364 q.group(1, '#<struct ' + PP.mcall(self, Kernel, :class).name, '>') {
365 q.seplist(PP.mcall(self, Struct, :members), lambda { q.text "," }) {|member|
377 def pretty_print_cycle(q)
378 q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name)
386 q.text(self.exclude_end? ? '...' : '..')
396 q.object_group(self) {
398 q.text sprintf("dev=0x%x", self.dev); q.comma_breakable
399 q.text "ino="; q.pp self.ino; q.comma_breakable
402 q.text sprintf("mode=0%o", m)
404 q.text sprintf("(%s %c%c%c%c%c%c%c%c%c)",
406 (m & 0400 == 0 ? ?- : ?r),
407 (m & 0200 == 0 ? ?- : ?w),
408 (m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
409 (m & 04000 == 0 ? ?x : ?s)),
410 (m & 0040 == 0 ? ?- : ?r),
411 (m & 0020 == 0 ? ?- : ?w),
412 (m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
413 (m & 02000 == 0 ? ?x : ?s)),
414 (m & 0004 == 0 ? ?- : ?r),
415 (m & 0002 == 0 ? ?- : ?w),
416 (m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
417 (m & 01000 == 0 ? ?x : ?t)))
420 q.text "nlink="; q.pp self.nlink; q.comma_breakable
422 q.text "uid="; q.pp self.uid
424 pw = Etc.getpwuid(self.uid)
428 q.breakable; q.text "(#{pw.name})"
433 q.text "gid="; q.pp self.gid
435 gr = Etc.getgrgid(self.gid)
439 q.breakable; q.text "(#{gr.name})"
444 q.text sprintf("rdev=0x%x", self.rdev)
446 q.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor)
449 q.text "size="; q.pp self.size; q.comma_breakable
450 q.text "blksize="; q.pp self.blksize; q.comma_breakable
451 q.text "blocks="; q.pp self.blocks; q.comma_breakable
454 q.text "atime="; q.pp t
455 q.breakable; q.text "(#{t.tv_sec})"
460 q.text "mtime="; q.pp t
461 q.breakable; q.text "(#{t.tv_sec})"
466 q.text "ctime="; q.pp t
467 q.breakable; q.text "(#{t.tv_sec})"
477 self.regexp.named_captures.each {|name, indexes|
478 indexes.each {|i| nc[i] = name }
480 q.object_group(self) {
482 q.seplist(0...self.size, lambda { q.breakable }) {|i|
500 include PP::ObjectMixin
503 [Numeric, Symbol, FalseClass, TrueClass, NilClass, Module].each {|c|
505 def pretty_print_cycle(q)
511 [Numeric, FalseClass, TrueClass, Module].each {|c|
523 class PPTest < Test::Unit::TestCase
525 assert_equal("[0, 1, 2, 3]\n", PP.pp([0,1,2,3], '', 12))
529 assert_equal("[0,\n 1,\n 2,\n 3]\n", PP.pp([0,1,2,3], '', 11))
532 OverriddenStruct = Struct.new("OverriddenStruct", :members, :class)
533 def test_struct_override_members # [ruby-core:7865]
534 a = OverriddenStruct.new(1,2)
535 assert_equal("#<struct Struct::OverriddenStruct members=1, class=2>\n", PP.pp(a, ''))
538 def test_redefined_method
542 assert_equal(%(""\n), PP.pp(o, ""))
552 return "<inspect:#{@a.inspect}>"
562 q.text "<pretty_print:"
574 return "<inspect:#{@a.inspect}>"
578 q.text "<pretty_print:"
584 class PrettyPrintInspect < HasPrettyPrint
585 alias inspect pretty_print_inspect
588 class PrettyPrintInspectWithoutPrettyPrint
589 alias inspect pretty_print_inspect
592 class PPInspectTest < Test::Unit::TestCase
594 a = HasInspect.new(1)
595 assert_equal("<inspect:1>\n", PP.pp(a, ''))
598 def test_hasprettyprint
599 a = HasPrettyPrint.new(1)
600 assert_equal("<pretty_print:1>\n", PP.pp(a, ''))
605 assert_equal("<pretty_print:1>\n", PP.pp(a, ''))
608 def test_pretty_print_inspect
609 a = PrettyPrintInspect.new(1)
610 assert_equal("<pretty_print:1>", a.inspect)
611 a = PrettyPrintInspectWithoutPrettyPrint.new
612 assert_raise(RuntimeError) { a.inspect }
617 assert_equal("#{a.inspect}\n", PP.pp(a, ''))
620 def test_to_s_with_iv
622 def a.to_s() "aaa" end
623 a.instance_eval { @a = nil }
624 result = PP.pp(a, '')
625 assert_equal("#{a.inspect}\n", result)
626 assert_match(/\A#<Object.*>\n\z/m, result)
628 a.instance_eval { @a = nil }
629 result = PP.pp(a, '')
630 assert_equal("#{a.inspect}\n", result)
633 def test_to_s_without_iv
635 def a.to_s() "aaa" end
636 result = PP.pp(a, '')
637 assert_equal("#{a.inspect}\n", result)
638 assert_equal("aaa\n", result)
642 class PPCycleTest < Test::Unit::TestCase
646 assert_equal("[[...]]\n", PP.pp(a, ''))
647 assert_equal("#{a.inspect}\n", PP.pp(a, ''))
653 assert_equal("{0=>{...}}\n", PP.pp(a, ''))
654 assert_equal("#{a.inspect}\n", PP.pp(a, ''))
657 S = Struct.new("S", :a, :b)
661 assert_equal("#<struct Struct::S a=1, b=#<struct Struct::S:...>>\n", PP.pp(a, ''))
662 assert_equal("#{a.inspect}\n", PP.pp(a, ''))
667 a.instance_eval {@a = a}
668 assert_equal(a.inspect + "\n", PP.pp(a, ''))
673 assert_equal(a.inspect + "\n", PP.pp(a, ''))
678 a << HasInspect.new(a)
679 assert_equal("[<inspect:[...]>]\n", PP.pp(a, ''))
680 assert_equal("#{a.inspect}\n", PP.pp(a, ''))
685 PP.sharing_detection = true
687 assert_equal("[nil, nil]\n", PP.pp(a, ''))
689 PP.sharing_detection = false
694 class PPSingleLineTest < Test::Unit::TestCase
696 assert_equal("{1=>1}", PP.singleline_pp({ 1 => 1}, '')) # [ruby-core:02699]
697 assert_equal("[1#{', 1'*99}]", PP.singleline_pp([1]*100, ''))