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 InspectKey = :__inspect_key__
110 def guard_inspect_key
111 if Thread.current[InspectKey] == nil
112 Thread.current[InspectKey] = []
115 save = Thread.current[InspectKey]
118 Thread.current[InspectKey] = []
121 Thread.current[InspectKey] = save
125 # Adds +obj+ to the pretty printing buffer
126 # using Object#pretty_print or Object#pretty_print_cycle.
128 # Object#pretty_print_cycle is used when +obj+ is already
129 # printed, a.k.a the object reference chain has a cycle.
133 if Thread.current[InspectKey].include? id
134 group {obj.pretty_print_cycle self}
139 Thread.current[InspectKey] << id
140 group {obj.pretty_print self}
142 Thread.current[InspectKey].pop unless PP.sharing_detection
146 # A convenience method which is same as follows:
148 # group(1, '#<' + obj.class.name, '>') { ... }
149 def object_group(obj, &block) # :yield:
150 group(1, '#<' + obj.class.name, '>', &block)
153 def object_address_group(obj, &block)
154 id = "%x" % (obj.__id__ * 2)
155 id.sub!(/\Af(?=[[:xdigit:]]{2}+\z)/, '') if id.sub!(/\A\.\./, '')
156 group(1, "\#<#{obj.class}:0x#{id}", '>', &block)
159 # A convenience method which is same as follows:
168 # Adds a separated list.
169 # The list is separated by comma with breakable space, by default.
171 # #seplist iterates the +list+ using +iter_method+.
172 # It yields each object to the block given for #seplist.
173 # The procedure +separator_proc+ is called between each yields.
175 # If the iteration is zero times, +separator_proc+ is not called at all.
177 # If +separator_proc+ is nil or not given,
178 # +lambda { comma_breakable }+ is used.
179 # If +iter_method+ is not given, :each is used.
181 # For example, following 3 code fragments has similar effect.
183 # q.seplist([1,2,3]) {|v| xxx v }
185 # q.seplist([1,2,3], lambda { comma_breakable }, :each) {|v| xxx v }
192 def seplist(list, sep=nil, iter_method=:each) # :yield: element
193 sep ||= lambda { comma_breakable }
195 list.__send__(iter_method) {|*v|
206 object_address_group(obj) {
207 seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v|
209 v = v.to_s if Symbol === v
214 pp(obj.instance_eval(v))
222 seplist(obj, nil, :each_pair) {|k, v|
238 class SingleLine < PrettyPrint::SingleLine
243 # 1. specific pretty_print
244 # 2. specific inspect
245 # 3. specific to_s if instance variable is empty
246 # 4. generic pretty_print
248 # A default pretty printing method for general objects.
249 # It calls #pretty_print_instance_variables to list instance variables.
251 # If +self+ has a customized (redefined) #inspect method,
252 # the result of self.inspect is used but it obviously has no
255 # This module provides predefined #pretty_print methods for some of
256 # the most commonly used built-in classes for convenience.
258 if /\(Kernel\)#/ !~ method(:inspect).inspect
260 elsif /\(Kernel\)#/ !~ method(:to_s).inspect && instance_variables.empty?
267 # A default pretty printing method for general objects that are
268 # detected as part of a cycle.
269 def pretty_print_cycle(q)
270 q.object_address_group(self) {
276 # Returns a sorted array of instance variable names.
278 # This method should return an array of names of instance variables as symbols or strings as:
280 def pretty_print_instance_variables
281 instance_variables.sort
284 # Is #inspect implementation using #pretty_print.
285 # If you implement #pretty_print, it can be used as follows.
287 # alias inspect pretty_print_inspect
289 # However, doing this requires that every class that #inspect is called on
290 # implement #pretty_print, or a RuntimeError will be raised.
291 def pretty_print_inspect
292 if /\(PP::ObjectMixin\)#/ =~ method(:pretty_print).inspect
293 raise "pretty_print is not overridden for #{self.class}"
295 PP.singleline_pp(self, '')
302 q.group(1, '[', ']') {
309 def pretty_print_cycle(q)
310 q.text(empty? ? '[]' : '[...]')
319 def pretty_print_cycle(q)
320 q.text(empty? ? '{}' : '{...}')
332 q.group(1, '#<struct ' + PP.mcall(self, Kernel, :class).name, '>') {
333 q.seplist(PP.mcall(self, Struct, :members), lambda { q.text "," }) {|member|
345 def pretty_print_cycle(q)
346 q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name)
354 q.text(self.exclude_end? ? '...' : '..')
363 q.object_group(self) {
365 q.text sprintf("dev=0x%x", self.dev); q.comma_breakable
366 q.text "ino="; q.pp self.ino; q.comma_breakable
369 q.text sprintf("mode=0%o", m)
371 q.text sprintf("(%s %c%c%c%c%c%c%c%c%c)",
373 (m & 0400 == 0 ? ?- : ?r),
374 (m & 0200 == 0 ? ?- : ?w),
375 (m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) :
376 (m & 04000 == 0 ? ?x : ?s)),
377 (m & 0040 == 0 ? ?- : ?r),
378 (m & 0020 == 0 ? ?- : ?w),
379 (m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) :
380 (m & 02000 == 0 ? ?x : ?s)),
381 (m & 0004 == 0 ? ?- : ?r),
382 (m & 0002 == 0 ? ?- : ?w),
383 (m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) :
384 (m & 01000 == 0 ? ?x : ?t)))
387 q.text "nlink="; q.pp self.nlink; q.comma_breakable
389 q.text "uid="; q.pp self.uid
391 pw = Etc.getpwuid(self.uid)
395 q.breakable; q.text "(#{pw.name})"
400 q.text "gid="; q.pp self.gid
402 gr = Etc.getgrgid(self.gid)
406 q.breakable; q.text "(#{gr.name})"
411 q.text sprintf("rdev=0x%x", self.rdev)
413 q.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor)
416 q.text "size="; q.pp self.size; q.comma_breakable
417 q.text "blksize="; q.pp self.blksize; q.comma_breakable
418 q.text "blocks="; q.pp self.blocks; q.comma_breakable
421 q.text "atime="; q.pp t
422 q.breakable; q.text "(#{t.tv_sec})"
427 q.text "mtime="; q.pp t
428 q.breakable; q.text "(#{t.tv_sec})"
433 q.text "ctime="; q.pp t
434 q.breakable; q.text "(#{t.tv_sec})"
443 q.object_group(self) {
445 q.seplist(1..self.size, lambda { q.breakable }) {|i|
453 include PP::ObjectMixin
456 [Numeric, Symbol, FalseClass, TrueClass, NilClass, Module].each {|c|
458 def pretty_print_cycle(q)
464 [Numeric, FalseClass, TrueClass, Module].each {|c|
476 class PPTest < Test::Unit::TestCase
478 assert_equal("[0, 1, 2, 3]\n", PP.pp([0,1,2,3], '', 12))
482 assert_equal("[0,\n 1,\n 2,\n 3]\n", PP.pp([0,1,2,3], '', 11))
485 OverriddenStruct = Struct.new("OverriddenStruct", :members, :class)
486 def test_struct_override_members # [ruby-core:7865]
487 a = OverriddenStruct.new(1,2)
488 assert_equal("#<struct Struct::OverriddenStruct members=1, class=2>\n", PP.pp(a, ''))
498 return "<inspect:#{@a.inspect}>"
508 q.text "<pretty_print:"
520 return "<inspect:#{@a.inspect}>"
524 q.text "<pretty_print:"
530 class PrettyPrintInspect < HasPrettyPrint
531 alias inspect pretty_print_inspect
534 class PrettyPrintInspectWithoutPrettyPrint
535 alias inspect pretty_print_inspect
538 class PPInspectTest < Test::Unit::TestCase
540 a = HasInspect.new(1)
541 assert_equal("<inspect:1>\n", PP.pp(a, ''))
544 def test_hasprettyprint
545 a = HasPrettyPrint.new(1)
546 assert_equal("<pretty_print:1>\n", PP.pp(a, ''))
551 assert_equal("<pretty_print:1>\n", PP.pp(a, ''))
554 def test_pretty_print_inspect
555 a = PrettyPrintInspect.new(1)
556 assert_equal("<pretty_print:1>", a.inspect)
557 a = PrettyPrintInspectWithoutPrettyPrint.new
558 assert_raise(RuntimeError) { a.inspect }
563 assert_equal("#{a.inspect}\n", PP.pp(a, ''))
566 def test_to_s_with_iv
568 def a.to_s() "aaa" end
569 a.instance_eval { @a = nil }
570 result = PP.pp(a, '')
571 assert_equal("#{a.inspect}\n", result)
572 assert_match(/\A#<Object.*>\n\z/m, result)
574 a.instance_eval { @a = nil }
575 result = PP.pp(a, '')
576 assert_equal("#{a.inspect}\n", result)
579 def test_to_s_without_iv
581 def a.to_s() "aaa" end
582 result = PP.pp(a, '')
583 assert_equal("#{a.inspect}\n", result)
584 assert_equal("aaa\n", result)
588 class PPCycleTest < Test::Unit::TestCase
592 assert_equal("[[...]]\n", PP.pp(a, ''))
593 assert_equal("#{a.inspect}\n", PP.pp(a, ''))
599 assert_equal("{0=>{...}}\n", PP.pp(a, ''))
600 assert_equal("#{a.inspect}\n", PP.pp(a, ''))
603 S = Struct.new("S", :a, :b)
607 assert_equal("#<struct Struct::S a=1, b=#<struct Struct::S:...>>\n", PP.pp(a, ''))
608 assert_equal("#{a.inspect}\n", PP.pp(a, ''))
613 a.instance_eval {@a = a}
614 assert_equal(a.inspect + "\n", PP.pp(a, ''))
619 assert_equal(a.inspect + "\n", PP.pp(a, ''))
624 a << HasInspect.new(a)
625 assert_equal("[<inspect:[...]>]\n", PP.pp(a, ''))
626 assert_equal("#{a.inspect}\n", PP.pp(a, ''))
631 PP.sharing_detection = true
633 assert_equal("[nil, nil]\n", PP.pp(a, ''))
635 PP.sharing_detection = false
640 class PPSingleLineTest < Test::Unit::TestCase
642 assert_equal("{1=>1}", PP.singleline_pp({ 1 => 1}, '')) # [ruby-core:02699]
643 assert_equal("[1#{', 1'*99}]", PP.singleline_pp([1]*100, ''))