Class: SyntaxTree::Translator::Parser::HeredocSegments

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

Defined Under Namespace

Classes: HeredocLine

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(node) ⇒ HeredocSegments

Returns a new instance of HeredocSegments.



481
482
483
484
# File 'lib/syntax_tree/translator/parser.rb', line 481

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

Instance Attribute Details

#nodeObject (readonly)

Returns the value of attribute node.



479
480
481
# File 'lib/syntax_tree/translator/parser.rb', line 479

def node
  @node
end

#segmentsObject (readonly)

Returns the value of attribute segments.



479
480
481
# File 'lib/syntax_tree/translator/parser.rb', line 479

def segments
  @segments
end

Instance Method Details

#<<(segment) ⇒ Object



486
487
488
489
490
491
492
# File 'lib/syntax_tree/translator/parser.rb', line 486

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



496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'lib/syntax_tree/translator/parser.rb', line 496

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

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

    if segment.type == :str
      lines.last.value << segment.children.first

      if lines.last.value.end_with?("\n")
        lines << HeredocLine.new(+"", [])
      end
    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.length > 0
          segments << segment
        end
      else
        segments << segment
      end
    end
  end
end