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

Returns a new instance of StringLiteral.



11233
11234
11235
11236
11237
11238
# File 'lib/syntax_tree.rb', line 11233

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



11231
11232
11233
# File 'lib/syntax_tree.rb', line 11231

def comments
  @comments
end

#locationObject (readonly)

Location

the location of this node



11228
11229
11230
# File 'lib/syntax_tree.rb', line 11228

def location
  @location
end

#partsObject (readonly)

Array[ StringEmbExpr | StringDVar | TStringContent ]

the parts of the

string literal



11222
11223
11224
# File 'lib/syntax_tree.rb', line 11222

def parts
  @parts
end

#quoteObject (readonly)

String

which quote was used by the string literal



11225
11226
11227
# File 'lib/syntax_tree.rb', line 11225

def quote
  @quote
end

Instance Method Details

#child_nodesObject



11240
11241
11242
# File 'lib/syntax_tree.rb', line 11240

def child_nodes
  parts
end

#format(q) ⇒ Object



11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
# File 'lib/syntax_tree.rb', line 11244

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



11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
# File 'lib/syntax_tree.rb', line 11274

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



11285
11286
11287
11288
11289
11290
11291
11292
11293
# File 'lib/syntax_tree.rb', line 11285

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