File: emitter.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 (95 lines) | stat: -rw-r--r-- 2,017 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
# frozen_string_literal: true

module Unparser
  UnknownNodeError = Class.new(ArgumentError)

  # Emitter base class
  class Emitter
    include Adamantium, AbstractType, Constants, Generation, NodeHelpers
    include Anima.new(:buffer, :comments, :node, :local_variable_scope)

    public :node

    extend DSL

    # Registry for node emitters
    REGISTRY = {} # rubocop:disable Style/MutableConstant

    NO_INDENT = %i[ensure rescue].freeze

    module LocalVariableRoot
      # Return local variable root
      #
      # @return [Parser::AST::Node]
      #
      # @api private
      #
      def local_variable_scope
        AST::LocalVariableScope.new(node)
      end

      def self.included(descendant)
        descendant.class_eval do
          memoize :local_variable_scope
        end
      end
    end # LocalVariableRoot

    def node_type
      node.type
    end

    # Register emitter for type
    #
    # @param [Symbol] types
    #
    # @return [undefined]
    #
    # @api private
    #
    def self.handle(*types)
      types.each do |type|
        fail "Handler for type: #{type} already registered" if REGISTRY.key?(type)

        REGISTRY[type] = self
      end
    end
    private_class_method :handle

    def emit_mlhs
      dispatch
    end

    # Return emitter
    #
    # @return [Emitter]
    #
    # @api private
    #
    # rubocop:disable Metrics/ParameterLists
    def self.emitter(buffer:, comments:, node:, local_variable_scope:)
      type = node.type

      klass = REGISTRY.fetch(type) do
        fail UnknownNodeError, "Unknown node type: #{type.inspect}"
      end

      klass.new(
        buffer:               buffer,
        comments:             comments,
        local_variable_scope: local_variable_scope,
        node:                 node
      )
    end
    # rubocop:enable Metrics/ParameterLists

    # Dispatch node write as statement
    #
    # @return [undefined]
    #
    # @api private
    #
    abstract_method :dispatch

  end # Emitter
end # Unparser