File: primitive.rb

package info (click to toggle)
ruby-unparser 0.6.13-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 936 kB
  • sloc: ruby: 7,691; sh: 6; makefile: 4
file content (119 lines) | stat: -rw-r--r-- 2,245 bytes parent folder | download
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
# frozen_string_literal: true

module Unparser
  class Emitter
    # Base class for primitive emitters
    class Primitive < self

      children :value

      # Emitter for primitives based on Object#inspect
      class Inspect < self

        handle :str

      private

        def dispatch
          write(value.inspect)
        end

      end # Inspect

      class Symbol < self

        handle :sym

        private

        # mutant:disable
        def dispatch
          if inspect_breaks_parsing?
            write(":#{value.name.inspect}")
          else
            write(value.inspect)
          end
        end

        # mutant:disable
        def inspect_breaks_parsing?
          return false unless RUBY_VERSION < '3.2.'

          Unparser.parse(value.inspect)
          false
        rescue Parser::SyntaxError
          true
        end
      end # Symbol

      # Emitter for complex literals
      class Complex < self

        handle :complex

        RATIONAL_FORMAT = 'i'.freeze

        MAP =
          {
            ::Float    => :float,
            ::Rational => :rational,
            ::Integer  => :int
          }.freeze

      private

        def dispatch
          emit_imaginary
          write(RATIONAL_FORMAT)
        end

        def emit_imaginary
          visit(imaginary_node)
        end

        def imaginary_node
          imaginary = value.imaginary
          s(MAP.fetch(imaginary.class), imaginary)
        end

      end # Rational

      # Emitter for rational literals
      class Rational < self

        handle :rational

        RATIONAL_FORMAT = 'r'.freeze

      private

        # rubocop:disable Lint/FloatComparison
        def dispatch
          integer = Integer(value)
          float   = value.to_f

          write_rational(integer.to_f.equal?(float) ? integer : float)
        end
        # rubocop:enable Lint/FloatComparison

        def write_rational(value)
          write(value.to_s, RATIONAL_FORMAT)
        end

      end # Rational

      # Emiter for numeric literals
      class Numeric < self

        handle :int

      private

        def dispatch
          write(value.inspect)
        end

      end # Numeric
    end # Primitive
  end # Emitter
end # Unparser