Module: SeeingIsBelieving::ParserHelpers

Extended by:
ParserHelpers
Included in:
Binary::CommentableLines, ParserHelpers, WrapExpressions
Defined in:
lib/seeing_is_believing/parser_helpers.rb

Defined Under Namespace

Classes: NullDiagnostics

Instance Method Summary collapse

Instance Method Details

#comments_from(parser, buffer) ⇒ Object

useful b/c it can find comments even in syntactically invalid code



30
31
32
33
34
# File 'lib/seeing_is_believing/parser_helpers.rb', line 30

def comments_from(parser, buffer)
  parser.instance_variable_set(:@diagnostics, NullDiagnostics.new) # seems really fucking risky
  success, comments, tokens, * = parser.tokenize buffer            # experimentally, seems to be what these things return
  comments
end

#heredoc?(ast) ⇒ Boolean

this is the scardest fucking method I think I’ve ever written. anything can go wrong!

Returns:

  • (Boolean)


38
39
40
41
42
43
44
45
46
47
# File 'lib/seeing_is_believing/parser_helpers.rb', line 38

def heredoc?(ast)
  # some strings are fucking weird.
  # e.g. the "1" in `%w[1]` returns nil for ast.location.begin
  # and `__FILE__` is a string whose location is a Parser::Source::Map instead of a Parser::Source::Map::Collection, so it has no #begin
  ast.kind_of?(Parser::AST::Node)           &&
    (ast.type == :dstr || ast.type == :str) &&
    (location  = ast.location)              &&
    (the_begin = location.begin)            &&
    (the_begin.source =~ /^\<\<-?/)
end

#heredoc_hack(ast) ⇒ Object



64
65
66
67
68
69
# File 'lib/seeing_is_believing/parser_helpers.rb', line 64

def heredoc_hack(ast)
  return ast unless heredoc? ast
  Parser::AST::Node.new :str,
                        [],
                        location: Parser::Source::Map.new(ast.location.begin)
end

#initialize_parser(code, name) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/seeing_is_believing/parser_helpers.rb', line 16

def initialize_parser(code, name)
  buffer                             = Parser::Source::Buffer.new(name)
  buffer.source                      = code

  builder                            = Parser::Builders::Default.new
  builder.emit_file_line_as_literals = false

  parser                             = Parser::CurrentRuby.new builder
  rewriter                           = Parser::Source::Rewriter.new buffer

  [buffer, parser, rewriter]
end

#void_value?(ast) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/seeing_is_believing/parser_helpers.rb', line 49

def void_value?(ast)
  case ast && ast.type
  when :begin, :kwbegin, :resbody
    void_value?(ast.children[-1])
  when :rescue, :ensure
    ast.children.any? { |child| void_value? child }
  when :if
    void_value?(ast.children[1]) || void_value?(ast.children[2])
  when :return, :next, :redo, :retry, :break
    true
  else
    false
  end
end