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.



11443
11444
11445
11446
11447
11448
# File 'lib/syntax_tree.rb', line 11443

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



11441
11442
11443
# File 'lib/syntax_tree.rb', line 11441

def comments
  @comments
end

#locationObject (readonly)

Location

the location of this node



11438
11439
11440
# File 'lib/syntax_tree.rb', line 11438

def location
  @location
end

#partsObject (readonly)

Array[ StringEmbExpr | StringDVar | TStringContent ]

the parts of the

string literal



11432
11433
11434
# File 'lib/syntax_tree.rb', line 11432

def parts
  @parts
end

#quoteObject (readonly)

String

which quote was used by the string literal



11435
11436
11437
# File 'lib/syntax_tree.rb', line 11435

def quote
  @quote
end

Instance Method Details

#child_nodesObject



11450
11451
11452
# File 'lib/syntax_tree.rb', line 11450

def child_nodes
  parts
end

#format(q) ⇒ Object



11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
# File 'lib/syntax_tree.rb', line 11454

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



11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
# File 'lib/syntax_tree.rb', line 11484

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



11495
11496
11497
11498
11499
11500
11501
11502
11503
# File 'lib/syntax_tree.rb', line 11495

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