module Unparser

Library namespace

Constants

EMPTY_ARRAY
EMPTY_STRING
UnknownNodeError

Public Class Methods

buffer(source, identification = '(string)') click to toggle source

Construct a parser buffer from string

@param [String] source

@return [Parser::Source::Buffer]

# File lib/unparser.rb, line 147
def self.buffer(source, identification = '(string)')
  Parser::Source::Buffer.new(identification, source: source)
end
parse(source) click to toggle source

Parse string into AST

@param [String] source

@return [Parser::AST::Node, nil]

# File lib/unparser.rb, line 105
def self.parse(source)
  parser.parse(buffer(source))
end
parse_either(source) click to toggle source

Parse string into either syntax error or AST

@param [String] source

@return [Either<Parser::SyntaxError, (Parser::ASTNode, nil)>]

# File lib/unparser.rb, line 114
def self.parse_either(source)
  Either.wrap_error(Parser::SyntaxError) do
    parser.parse(buffer(source))
  end
end
parse_with_comments(source) click to toggle source

Parse string into AST, with comments

@param [String] source

@return [Parser::AST::Node]

# File lib/unparser.rb, line 125
def self.parse_with_comments(source)
  parser.parse_with_comments(buffer(source))
end
parser() click to toggle source

Parser instance that produces AST unparser understands

@return [Parser::Base]

@api private

# File lib/unparser.rb, line 134
def self.parser
  Parser::CurrentRuby.new(Builder.new).tap do |parser|
    parser.diagnostics.tap do |diagnostics|
      diagnostics.all_errors_are_fatal = true
    end
  end
end
unparse(node, comment_array = []) click to toggle source

Unparse an AST (and, optionally, comments) into a string

@param [Parser::AST::Node, nil] node @param [Array] comment_array

@return [String]

@raise InvalidNodeError

if the node passed is invalid

@api public

# File lib/unparser.rb, line 60
def self.unparse(node, comment_array = [])
  return '' if node.nil?

  Buffer.new.tap do |buffer|
    Emitter::Root.new(
      buffer,
      node,
      Comments.new(comment_array)
    ).write_to_buffer
  end.content
end
unparse_either(node) click to toggle source

Unparse capturing errors

This is mostly useful for writing testing tools against unparser.

@param [Parser::AST::Node, nil] node

@return [Either<Exception, String>]

# File lib/unparser.rb, line 96
def self.unparse_either(node)
  Either.wrap_error(Exception) { unparse(node) }
end
unparse_validate(node, comment_array = []) click to toggle source

Unparse with validation

@param [Parser::AST::Node, nil] node @param [Array] comment_array

@return [Either<Validation,String>]

# File lib/unparser.rb, line 78
def self.unparse_validate(node, comment_array = [])
  generated = unparse(node, comment_array)
  validation = Validation.from_string(generated)

  if validation.success?
    Either::Right.new(generated)
  else
    Either::Left.new(validation)
  end
end