Sha256: 13293be319e691ae3883fa8ddb6205019ddfd4a6e90b9737bc1defbf67fafea8

Contents?: true

Size: 1.17 KB

Versions: 31

Compression:

Stored size: 1.17 KB

Contents

# frozen_string_literal: true

module SyntaxTree
  class Visitor
    # This visitor transforms the AST into a hash that contains only primitives
    # that can be easily serialized into JSON.
    class JSONVisitor < FieldVisitor
      attr_reader :target

      def initialize
        @target = nil
      end

      private

      def comments(node)
        target[:comments] = visit_all(node.comments)
      end

      def field(name, value)
        target[name] = value.is_a?(Node) ? visit(value) : value
      end

      def list(name, values)
        target[name] = visit_all(values)
      end

      def node(node, type)
        previous = @target
        @target = { type: type, location: visit_location(node.location) }
        yield
        @target
      ensure
        @target = previous
      end

      def pairs(name, values)
        target[name] = values.map { |(key, value)| [visit(key), visit(value)] }
      end

      def text(name, value)
        target[name] = value
      end

      def visit_location(location)
        [
          location.start_line,
          location.start_char,
          location.end_line,
          location.end_char
        ]
      end
    end
  end
end

Version data entries

31 entries across 31 versions & 1 rubygems

Version Path
syntax_tree-5.3.0 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-5.2.0 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-5.1.0 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-5.0.1 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-5.0.0 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-4.3.0 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-4.2.0 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-4.1.0 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-4.0.2 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-4.0.1 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-4.0.0 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-3.6.3 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-3.6.2 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-3.6.1 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-3.6.0 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-3.5.0 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-3.4.0 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-3.3.0 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-3.2.1 lib/syntax_tree/visitor/json_visitor.rb
syntax_tree-3.2.0 lib/syntax_tree/visitor/json_visitor.rb