Class: SyntaxTree::Translation::Parser::HeredocBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/syntax_tree/translation/parser.rb

Overview

Heredocs are represented very differently in the parser gem from how they are represented in the Syntax Tree AST. This class is responsible for handling the translation.

Defined Under Namespace

Classes: Line

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(node) ⇒ HeredocBuilder

Returns a new instance of HeredocBuilder.



16
17
18
19
# File 'lib/syntax_tree/translation/parser.rb', line 16

def initialize(node)
  @node = node
  @segments = []
end

Instance Attribute Details

#nodeObject (readonly)

Returns the value of attribute node.



14
15
16
# File 'lib/syntax_tree/translation/parser.rb', line 14

def node
  @node
end

#segmentsObject (readonly)

Returns the value of attribute segments.



14
15
16
# File 'lib/syntax_tree/translation/parser.rb', line 14

def segments
  @segments
end

Instance Method Details

#<<(segment) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/syntax_tree/translation/parser.rb', line 21

def <<(segment)
  if segment.type == :str && segments.last &&
       segments.last.type == :str &&
       !segments.last.children.first.end_with?("\n")
    segments.last.children.first << segment.children.first
  else
    segments << segment
  end
end

#trim!Object



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
# File 'lib/syntax_tree/translation/parser.rb', line 31

def trim!
  return unless node.beginning.value[2] == "~"
  lines = [Line.new(+"", [])]

  segments.each do |segment|
    lines.last.segments << segment

    if segment.type == :str
      lines.last.value << segment.children.first
      lines << Line.new(+"", []) if lines.last.value.end_with?("\n")
    end
  end

  lines.pop if lines.last.value.empty?
  return if lines.empty?

  segments.clear
  lines.each do |line|
    remaining = node.dedent

    line.segments.each do |segment|
      if segment.type == :str
        if remaining > 0
          whitespace = segment.children.first[/^\s{0,#{remaining}}/]
          segment.children.first.sub!(/^#{whitespace}/, "")
          remaining -= whitespace.length
        end

        if node.beginning.value[3] != "'" && segments.any? &&
             segments.last.type == :str &&
             segments.last.children.first.end_with?("\\\n")
          segments.last.children.first.gsub!(/\\\n\z/, "")
          segments.last.children.first.concat(segment.children.first)
        elsif !segment.children.first.empty?
          segments << segment
        end
      else
        segments << segment
      end
    end
  end
end