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.



8390
8391
8392
8393
8394
8395
# File 'lib/syntax_tree/node.rb', line 8390

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



8388
8389
8390
# File 'lib/syntax_tree/node.rb', line 8388

def comments
  @comments
end

#partsObject (readonly)

Array[ StringEmbExpr | StringDVar | TStringContent ]

the parts of the

string literal



8382
8383
8384
# File 'lib/syntax_tree/node.rb', line 8382

def parts
  @parts
end

#quoteObject (readonly)

String

which quote was used by the string literal



8385
8386
8387
# File 'lib/syntax_tree/node.rb', line 8385

def quote
  @quote
end

Instance Method Details

#accept(visitor) ⇒ Object



8397
8398
8399
# File 'lib/syntax_tree/node.rb', line 8397

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

#child_nodesObject Also known as: deconstruct



8401
8402
8403
# File 'lib/syntax_tree/node.rb', line 8401

def child_nodes
  parts
end

#deconstruct_keys(_keys) ⇒ Object



8407
8408
8409
# File 'lib/syntax_tree/node.rb', line 8407

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

#format(q) ⇒ Object



8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
# File 'lib/syntax_tree/node.rb', line 8411

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.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