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.



11311
11312
11313
11314
11315
11316
# File 'lib/syntax_tree.rb', line 11311

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



11309
11310
11311
# File 'lib/syntax_tree.rb', line 11309

def comments
  @comments
end

#locationObject (readonly)

Location

the location of this node



11306
11307
11308
# File 'lib/syntax_tree.rb', line 11306

def location
  @location
end

#partsObject (readonly)

Array[ StringEmbExpr | StringDVar | TStringContent ]

the parts of the

string literal



11300
11301
11302
# File 'lib/syntax_tree.rb', line 11300

def parts
  @parts
end

#quoteObject (readonly)

String

which quote was used by the string literal



11303
11304
11305
# File 'lib/syntax_tree.rb', line 11303

def quote
  @quote
end

Instance Method Details

#child_nodesObject



11318
11319
11320
# File 'lib/syntax_tree.rb', line 11318

def child_nodes
  parts
end

#format(q) ⇒ Object



11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
# File 'lib/syntax_tree.rb', line 11322

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



11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
# File 'lib/syntax_tree.rb', line 11352

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



11363
11364
11365
11366
11367
11368
11369
11370
11371
# File 'lib/syntax_tree.rb', line 11363

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