Class: SyntaxTree::StringLiteral

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

Overview

StringLiteral represents a string literal.

"string"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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



10763
10764
10765
10766
10767
10768
# File 'lib/syntax_tree.rb', line 10763

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



10761
10762
10763
# File 'lib/syntax_tree.rb', line 10761

def comments
  @comments
end

#locationObject (readonly)

Location

the location of this node



10758
10759
10760
# File 'lib/syntax_tree.rb', line 10758

def location
  @location
end

#partsObject (readonly)

Array[ StringEmbExpr | StringDVar | TStringContent ]

the parts of the

string literal



10752
10753
10754
# File 'lib/syntax_tree.rb', line 10752

def parts
  @parts
end

#quoteObject (readonly)

String

which quote was used by the string literal



10755
10756
10757
# File 'lib/syntax_tree.rb', line 10755

def quote
  @quote
end

Instance Method Details

#child_nodesObject



10770
10771
10772
# File 'lib/syntax_tree.rb', line 10770

def child_nodes
  parts
end

#format(q) ⇒ Object



10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
# File 'lib/syntax_tree.rb', line 10774

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]
    elsif quote.start_with?("%")
      [quote, Quotes.matching(quote[/%[qQ]?(.)/, 1])]
    else
      [quote, quote]
    end

  q.group(0, opening_quote, closing_quote) do
    parts.each do |part|
      if part.is_a?(TStringContent)
        value = Quotes.normalize(part.value, closing_quote)
        separator = -> { q.breakable(force: true, indent: false) }
        q.seplist(value.split(/\r?\n/, -1), separator) do |text|
          q.text(text)
        end
      else
        q.format(part)
      end
    end
  end
end

#pretty_print(q) ⇒ Object



10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
# File 'lib/syntax_tree.rb', line 10804

def pretty_print(q)
  q.group(2, "(", ")") do
    q.text("string_literal")

    q.breakable
    q.group(2, "(", ")") { q.seplist(parts) { |part| q.pp(part) } }

    q.pp(Comment::List.new(comments))
  end
end

#to_json(*opts) ⇒ Object



10815
10816
10817
10818
10819
10820
10821
10822
10823
# File 'lib/syntax_tree.rb', line 10815

def to_json(*opts)
  {
    type: :string_literal,
    parts: parts,
    quote: quote,
    loc: location,
    cmts: comments
  }.to_json(*opts)
end