Class: SyntaxTree::StringLiteral

Inherits:
Node
  • Object
show all
Defined in:
lib/syntax_tree/node.rb

Overview

StringLiteral represents a string literal.

"string"

Instance Attribute Summary collapse

Attributes inherited from Node

#location

Instance Method Summary collapse

Methods inherited from Node

#construct_keys, #pretty_print, #to_json

Constructor Details

#initialize(parts:, quote:, location:, comments: []) ⇒ StringLiteral

Returns a new instance of StringLiteral.



8649
8650
8651
8652
8653
8654
# File 'lib/syntax_tree/node.rb', line 8649

def initialize(parts:, quote:, location:, comments: [])
  @parts = parts
  @quote = quote
  @location = location
  @comments = comments
end

Instance Attribute Details

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



8647
8648
8649
# File 'lib/syntax_tree/node.rb', line 8647

def comments
  @comments
end

#partsObject (readonly)

Array[ StringEmbExpr | StringDVar | TStringContent ]

the parts of the

string literal



8641
8642
8643
# File 'lib/syntax_tree/node.rb', line 8641

def parts
  @parts
end

#quoteObject (readonly)

String

which quote was used by the string literal



8644
8645
8646
# File 'lib/syntax_tree/node.rb', line 8644

def quote
  @quote
end

Instance Method Details

#accept(visitor) ⇒ Object



8656
8657
8658
# File 'lib/syntax_tree/node.rb', line 8656

def accept(visitor)
  visitor.visit_string_literal(self)
end

#child_nodesObject Also known as: deconstruct



8660
8661
8662
# File 'lib/syntax_tree/node.rb', line 8660

def child_nodes
  parts
end

#deconstruct_keys(_keys) ⇒ Object



8666
8667
8668
# File 'lib/syntax_tree/node.rb', line 8666

def deconstruct_keys(_keys)
  { parts: parts, quote: quote, location: location, comments: comments }
end

#format(q) ⇒ Object



8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
# File 'lib/syntax_tree/node.rb', line 8670

def format(q)
  if parts.empty?
    q.text("#{q.quote}#{q.quote}")
    return
  end

  opening_quote, closing_quote =
    if !Quotes.locked?(self, q.quote)
      [q.quote, q.quote]
    elsif quote.start_with?("%")
      [quote, Quotes.matching(quote[/%[qQ]?(.)/, 1])]
    else
      [quote, quote]
    end

  q.text(opening_quote)
  q.group do
    parts.each do |part|
      if part.is_a?(TStringContent)
        value = Quotes.normalize(part.value, closing_quote)
        first = true

        value.each_line(chomp: true) do |line|
          if first
            first = false
          else
            q.breakable_return
          end

          q.text(line)
        end

        q.breakable_return if value.end_with?("\n")
      else
        q.format(part)
      end
    end
  end
  q.text(closing_quote)
end