summaryrefslogtreecommitdiff
path: root/ext/psych/lib/psych/visitors/yaml_tree.rb
blob: bedf9d35b2450ffce12aef99529d9a04dc973dfb (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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
require 'psych/tree_builder'
require 'psych/scalar_scanner'
require 'psych/class_loader'

module Psych
  module Visitors
    ###
    # YAMLTree builds a YAML ast given a Ruby object.  For example:
    #
    #   builder = Psych::Visitors::YAMLTree.new
    #   builder << { :foo => 'bar' }
    #   builder.tree # => #<Psych::Nodes::Stream .. }
    #
    class YAMLTree < Psych::Visitors::Visitor
      class Registrar # :nodoc:
        def initialize
          @obj_to_id   = {}
          @obj_to_node = {}
          @targets     = []
          @counter     = 0
        end

        def register target, node
          @targets << target
          @obj_to_node[target.object_id] = node
        end

        def key? target
          @obj_to_node.key? target.object_id
        rescue NoMethodError
          false
        end

        def id_for target
          @obj_to_id[target.object_id] ||= (@counter += 1)
        end

        def node_for target
          @obj_to_node[target.object_id]
        end
      end

      attr_reader :started, :finished
      alias :finished? :finished
      alias :started? :started

      def self.create options = {}, emitter = nil
        emitter      ||= TreeBuilder.new
        class_loader = ClassLoader.new
        ss           = ScalarScanner.new class_loader
        new(emitter, ss, options)
      end

      def self.new emitter = nil, ss = nil, options = nil
        return super if emitter && ss && options

        if $VERBOSE
          warn "This API is deprecated, please pass an emitter, scalar scanner, and options or call #{self}.create() (#{caller.first})"
        end
        create emitter, ss
      end

      def initialize emitter, ss, options
        super()
        @started  = false
        @finished = false
        @emitter  = emitter
        @st       = Registrar.new
        @ss       = ss
        @options  = options
        @coders   = []

        @dispatch_cache = Hash.new do |h,klass|
          method = "visit_#{(klass.name || '').split('::').join('_')}"

          method = respond_to?(method) ? method : h[klass.superclass]

          raise(TypeError, "Can't dump #{target.class}") unless method

          h[klass] = method
        end
      end

      def start encoding = Nodes::Stream::UTF8
        @emitter.start_stream(encoding).tap do
          @started = true
        end
      end

      def finish
        @emitter.end_stream.tap do
          @finished = true
        end
      end

      def tree
        finish unless finished?
        @emitter.root
      end

      def push object
        start unless started?
        version = []
        version = [1,1] if @options[:header]

        case @options[:version]
        when Array
          version = @options[:version]
        when String
          version = @options[:version].split('.').map { |x| x.to_i }
        else
          version = [1,1]
        end if @options.key? :version

        @emitter.start_document version, [], false
        accept object
        @emitter.end_document !@emitter.streaming?
      end
      alias :<< :push

      def accept target
        # return any aliases we find
        if @st.key? target
          oid         = @st.id_for target
          node        = @st.node_for target
          anchor      = oid.to_s
          node.anchor = anchor
          return @emitter.alias anchor
        end

        if target.respond_to?(:to_yaml)
          begin
            loc = target.method(:to_yaml).source_location.first
            if loc !~ /(syck\/rubytypes.rb|psych\/core_ext.rb)/
              unless target.respond_to?(:encode_with)
                if $VERBOSE
                  warn "implementing to_yaml is deprecated, please implement \"encode_with\""
                end

                target.to_yaml(:nodump => true)
              end
            end
          rescue
            # public_method or source_location might be overridden,
            # and it's OK to skip it since it's only to emit a warning
          end
        end

        if target.respond_to?(:encode_with)
          dump_coder target
        else
          send(@dispatch_cache[target.class], target)
        end
      end

      def visit_Psych_Omap o
        seq = @emitter.start_sequence(nil, '!omap', false, Nodes::Sequence::BLOCK)
        register(o, seq)

        o.each { |k,v| visit_Hash k => v }
        @emitter.end_sequence
      end

      def visit_Encoding o
        tag = "!ruby/encoding"
        @emitter.scalar o.name, nil, tag, false, false, Nodes::Scalar::ANY
      end

      def visit_Object o
        tag = Psych.dump_tags[o.class]
        unless tag
          klass = o.class == Object ? nil : o.class.name
          tag   = ['!ruby/object', klass].compact.join(':')
        end

        map = @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK)
        register(o, map)

        dump_ivars o
        @emitter.end_mapping
      end

      def visit_Struct o
        tag = ['!ruby/struct', o.class.name].compact.join(':')

        register o, @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK)
        o.members.each do |member|
          @emitter.scalar member.to_s, nil, nil, true, false, Nodes::Scalar::ANY
          accept o[member]
        end

        dump_ivars o

        @emitter.end_mapping
      end

      def visit_Exception o
        tag = ['!ruby/exception', o.class.name].join ':'

        @emitter.start_mapping nil, tag, false, Nodes::Mapping::BLOCK

        {
          'message'   => private_iv_get(o, 'mesg'),
          'backtrace' => private_iv_get(o, 'backtrace'),
        }.each do |k,v|
          next unless v
          @emitter.scalar k, nil, nil, true, false, Nodes::Scalar::ANY
          accept v
        end

        dump_ivars o

        @emitter.end_mapping
      end

      def visit_NameError o
        tag = ['!ruby/exception', o.class.name].join ':'

        @emitter.start_mapping nil, tag, false, Nodes::Mapping::BLOCK

        {
          'message'   => o.message.to_s,
          'backtrace' => private_iv_get(o, 'backtrace'),
        }.each do |k,v|
          next unless v
          @emitter.scalar k, nil, nil, true, false, Nodes::Scalar::ANY
          accept v
        end

        dump_ivars o

        @emitter.end_mapping
      end

      def visit_Regexp o
        register o, @emitter.scalar(o.inspect, nil, '!ruby/regexp', false, false, Nodes::Scalar::ANY)
      end

      def visit_DateTime o
        formatted = if o.offset.zero?
                      o.strftime("%Y-%m-%d %H:%M:%S.%9N Z".freeze)
                    else
                      o.strftime("%Y-%m-%d %H:%M:%S.%9N %:z".freeze)
                    end
        tag = '!ruby/object:DateTime'
        register o, @emitter.scalar(formatted, nil, tag, false, false, Nodes::Scalar::ANY)
      end

      def visit_Time o
        formatted = format_time o
        register o, @emitter.scalar(formatted, nil, nil, true, false, Nodes::Scalar::ANY)
      end

      def visit_Rational o
        register o, @emitter.start_mapping(nil, '!ruby/object:Rational', false, Nodes::Mapping::BLOCK)

        [
          'denominator', o.denominator.to_s,
          'numerator', o.numerator.to_s
        ].each do |m|
          @emitter.scalar m, nil, nil, true, false, Nodes::Scalar::ANY
        end

        @emitter.end_mapping
      end

      def visit_Complex o
        register o, @emitter.start_mapping(nil, '!ruby/object:Complex', false, Nodes::Mapping::BLOCK)

        ['real', o.real.to_s, 'image', o.imag.to_s].each do |m|
          @emitter.scalar m, nil, nil, true, false, Nodes::Scalar::ANY
        end

        @emitter.end_mapping
      end

      def visit_Integer o
        @emitter.scalar o.to_s, nil, nil, true, false, Nodes::Scalar::ANY
      end
      alias :visit_TrueClass :visit_Integer
      alias :visit_FalseClass :visit_Integer
      alias :visit_Date :visit_Integer

      def visit_Float o
        if o.nan?
          @emitter.scalar '.nan', nil, nil, true, false, Nodes::Scalar::ANY
        elsif o.infinite?
          @emitter.scalar((o.infinite? > 0 ? '.inf' : '-.inf'),
            nil, nil, true, false, Nodes::Scalar::ANY)
        else
          @emitter.scalar o.to_s, nil, nil, true, false, Nodes::Scalar::ANY
        end
      end

      def visit_BigDecimal o
        @emitter.scalar o._dump, nil, '!ruby/object:BigDecimal', false, false, Nodes::Scalar::ANY
      end

      def visit_String o
        plain = true
        quote = true
        style = Nodes::Scalar::PLAIN
        tag   = nil
        str   = o

        if binary?(o)
          str   = [o].pack('m').chomp
          tag   = '!binary' # FIXME: change to below when syck is removed
          #tag   = 'tag:yaml.org,2002:binary'
          style = Nodes::Scalar::LITERAL
          plain = false
          quote = false
        elsif o =~ /\n/
          style = Nodes::Scalar::LITERAL
        elsif o == '<<'
          style = Nodes::Scalar::SINGLE_QUOTED
          tag   = 'tag:yaml.org,2002:str'
          plain = false
          quote = false
        elsif o =~ /^\W[^"]*$/
          style = Nodes::Scalar::DOUBLE_QUOTED
        else
          unless String === @ss.tokenize(o)
            style = Nodes::Scalar::SINGLE_QUOTED
          end
        end

        ivars = find_ivars o

        if ivars.empty?
          unless o.class == ::String
            tag = "!ruby/string:#{o.class}"
            plain = false
            quote = false
          end
          @emitter.scalar str, nil, tag, plain, quote, style
        else
          maptag = '!ruby/string'
          maptag << ":#{o.class}" unless o.class == ::String

          register o, @emitter.start_mapping(nil, maptag, false, Nodes::Mapping::BLOCK)
          @emitter.scalar 'str', nil, nil, true, false, Nodes::Scalar::ANY
          @emitter.scalar str, nil, tag, plain, quote, style

          dump_ivars o

          @emitter.end_mapping
        end
      end

      def visit_Module o
        raise TypeError, "can't dump anonymous module: #{o}" unless o.name
        register o, @emitter.scalar(o.name, nil, '!ruby/module', false, false, Nodes::Scalar::SINGLE_QUOTED)
      end

      def visit_Class o
        raise TypeError, "can't dump anonymous class: #{o}" unless o.name
        register o, @emitter.scalar(o.name, nil, '!ruby/class', false, false, Nodes::Scalar::SINGLE_QUOTED)
      end

      def visit_Range o
        register o, @emitter.start_mapping(nil, '!ruby/range', false, Nodes::Mapping::BLOCK)
        ['begin', o.begin, 'end', o.end, 'excl', o.exclude_end?].each do |m|
          accept m
        end
        @emitter.end_mapping
      end

      def visit_Hash o
        ivars    = o.instance_variables

        if ivars.any?
          tag = "!ruby/hash-with-ivars"
          tag << ":#{o.class}" unless o.class == ::Hash

          register(o, @emitter.start_mapping(nil, tag, false, Psych::Nodes::Mapping::BLOCK))

          @emitter.scalar 'elements', nil, nil, true, false, Nodes::Scalar::ANY

          @emitter.start_mapping nil, nil, true, Nodes::Mapping::BLOCK
          o.each do |k,v|
            accept k
            accept v
          end
          @emitter.end_mapping

          @emitter.scalar 'ivars', nil, nil, true, false, Nodes::Scalar::ANY

          @emitter.start_mapping nil, nil, true, Nodes::Mapping::BLOCK
          o.instance_variables.each do |ivar|
            accept ivar
            accept o.instance_variable_get ivar
          end
          @emitter.end_mapping

          @emitter.end_mapping
        else
          tag      = o.class == ::Hash ? nil : "!ruby/hash:#{o.class}"
          implicit = !tag

          register(o, @emitter.start_mapping(nil, tag, implicit, Psych::Nodes::Mapping::BLOCK))

          o.each do |k,v|
            accept k
            accept v
          end

          @emitter.end_mapping
        end
      end

      def visit_Psych_Set o
        register(o, @emitter.start_mapping(nil, '!set', false, Psych::Nodes::Mapping::BLOCK))

        o.each do |k,v|
          accept k
          accept v
        end

        @emitter.end_mapping
      end

      def visit_Array o
        if o.class == ::Array
          register o, @emitter.start_sequence(nil, nil, true, Nodes::Sequence::BLOCK)
          o.each { |c| accept c }
          @emitter.end_sequence
        else
          visit_array_subclass o
        end
      end

      def visit_NilClass o
        @emitter.scalar('', nil, 'tag:yaml.org,2002:null', true, false, Nodes::Scalar::ANY)
      end

      def visit_Symbol o
        if o.empty?
          @emitter.scalar "", nil, '!ruby/symbol', false, false, Nodes::Scalar::ANY
        else
          @emitter.scalar ":#{o}", nil, nil, true, false, Nodes::Scalar::ANY
        end
      end

      def visit_BasicObject o
        tag = Psych.dump_tags[o.class]
        tag ||= "!ruby/marshalable:#{o.class.name}"

        map = @emitter.start_mapping(nil, tag, false, Nodes::Mapping::BLOCK)
        register(o, map)

        o.marshal_dump.each(&method(:accept))

        @emitter.end_mapping
      end

      private
      # FIXME: Remove the index and count checks in Psych 3.0
      NULL         = "\x00"
      BINARY_RANGE = "\x00-\x7F"
      WS_RANGE     = "^ -~\t\r\n"

      def binary? string
        (string.encoding == Encoding::ASCII_8BIT && !string.ascii_only?) ||
          string.index(NULL) ||
          string.count(BINARY_RANGE, WS_RANGE).fdiv(string.length) > 0.3
      end

      def visit_array_subclass o
        tag = "!ruby/array:#{o.class}"
        if o.instance_variables.empty?
          node = @emitter.start_sequence(nil, tag, false, Nodes::Sequence::BLOCK)
          register o, node
          o.each { |c| accept c }
          @emitter.end_sequence
        else
          node = @emitter.start_mapping(nil, tag, false, Nodes::Sequence::BLOCK)
          register o, node

          # Dump the internal list
          accept 'internal'
          @emitter.start_sequence(nil, nil, true, Nodes::Sequence::BLOCK)
          o.each { |c| accept c }
          @emitter.end_sequence

          # Dump the ivars
          accept 'ivars'
          @emitter.start_mapping(nil, nil, true, Nodes::Sequence::BLOCK)
          o.instance_variables.each do |ivar|
            accept ivar
            accept o.instance_variable_get ivar
          end
          @emitter.end_mapping

          @emitter.end_mapping
        end
      end

      def dump_list o
      end

      # '%:z' was no defined until 1.9.3
      if RUBY_VERSION < '1.9.3'
        def format_time time
          formatted = time.strftime("%Y-%m-%d %H:%M:%S.%9N")

          if time.utc?
            formatted += " Z"
          else
            zone = time.strftime('%z')
            formatted += " #{zone[0,3]}:#{zone[3,5]}"
          end

          formatted
        end
      else
        def format_time time
          if time.utc?
            time.strftime("%Y-%m-%d %H:%M:%S.%9N Z")
          else
            time.strftime("%Y-%m-%d %H:%M:%S.%9N %:z")
          end
        end
      end

      # FIXME: remove this method once "to_yaml_properties" is removed
      def find_ivars target
        begin
          loc = target.method(:to_yaml_properties).source_location.first
          unless loc.start_with?(Psych::DEPRECATED) || loc.end_with?('rubytypes.rb')
            if $VERBOSE
              warn "#{loc}: to_yaml_properties is deprecated, please implement \"encode_with(coder)\""
            end
            return target.to_yaml_properties
          end
        rescue
          # public_method or source_location might be overridden,
          # and it's OK to skip it since it's only to emit a warning.
        end

        target.instance_variables
      end

      def register target, yaml_obj
        @st.register target, yaml_obj
        yaml_obj
      end

      def dump_coder o
        @coders << o
        tag = Psych.dump_tags[o.class]
        unless tag
          klass = o.class == Object ? nil : o.class.name
          tag   = ['!ruby/object', klass].compact.join(':')
        end

        c = Psych::Coder.new(tag)
        o.encode_with(c)
        emit_coder c
      end

      def emit_coder c
        case c.type
        when :scalar
          @emitter.scalar c.scalar, nil, c.tag, c.tag.nil?, false, Nodes::Scalar::ANY
        when :seq
          @emitter.start_sequence nil, c.tag, c.tag.nil?, Nodes::Sequence::BLOCK
          c.seq.each do |thing|
            accept thing
          end
          @emitter.end_sequence
        when :map
          @emitter.start_mapping nil, c.tag, c.implicit, c.style
          c.map.each do |k,v|
            accept k
            accept v
          end
          @emitter.end_mapping
        when :object
          accept c.object
        end
      end

      def dump_ivars target
        ivars = find_ivars target

        ivars.each do |iv|
          @emitter.scalar("#{iv.to_s.sub(/^@/, '')}", nil, nil, true, false, Nodes::Scalar::ANY)
          accept target.instance_variable_get(iv)
        end
      end
    end
  end
end