Class: SyntaxTree::Paren

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

Overview

Paren represents using balanced parentheses in a couple places in a Ruby program. In general parentheses can be used anywhere a Ruby expression can be used.

(1 + 2)

Instance Attribute Summary collapse

Attributes inherited from Node

#location

Instance Method Summary collapse

Methods inherited from Node

#construct_keys, #end_char, #pretty_print, #start_char, #to_json, #to_mermaid

Constructor Details

#initialize(lparen:, contents:, location:) ⇒ Paren

Returns a new instance of Paren.



8505
8506
8507
8508
8509
8510
# File 'lib/syntax_tree/node.rb', line 8505

def initialize(lparen:, contents:, location:)
  @lparen = lparen
  @contents = contents
  @location = location
  @comments = []
end

Instance Attribute Details

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



8503
8504
8505
# File 'lib/syntax_tree/node.rb', line 8503

def comments
  @comments
end

#contentsObject (readonly)

nil | Node

the expression inside the parentheses



8500
8501
8502
# File 'lib/syntax_tree/node.rb', line 8500

def contents
  @contents
end

#lparenObject (readonly)

LParen

the left parenthesis that opened this statement



8497
8498
8499
# File 'lib/syntax_tree/node.rb', line 8497

def lparen
  @lparen
end

Instance Method Details

#===(other) ⇒ Object



8561
8562
8563
8564
# File 'lib/syntax_tree/node.rb', line 8561

def ===(other)
  other.is_a?(Paren) && lparen === other.lparen &&
    contents === other.contents
end

#accept(visitor) ⇒ Object



8512
8513
8514
# File 'lib/syntax_tree/node.rb', line 8512

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

#child_nodesObject Also known as: deconstruct



8516
8517
8518
# File 'lib/syntax_tree/node.rb', line 8516

def child_nodes
  [lparen, contents]
end

#copy(lparen: nil, contents: nil, location: nil) ⇒ Object



8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
# File 'lib/syntax_tree/node.rb', line 8520

def copy(lparen: nil, contents: nil, location: nil)
  node =
    Paren.new(
      lparen: lparen || self.lparen,
      contents: contents || self.contents,
      location: location || self.location
    )

  node.comments.concat(comments.map(&:copy))
  node
end

#deconstruct_keys(_keys) ⇒ Object



8534
8535
8536
8537
8538
8539
8540
8541
# File 'lib/syntax_tree/node.rb', line 8534

def deconstruct_keys(_keys)
  {
    lparen: lparen,
    contents: contents,
    location: location,
    comments: comments
  }
end

#format(q) ⇒ Object



8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
# File 'lib/syntax_tree/node.rb', line 8543

def format(q)
  contents = self.contents

  q.group do
    q.format(lparen)

    if contents && (!contents.is_a?(Params) || !contents.empty?)
      q.indent do
        q.breakable_empty
        q.format(contents)
      end
    end

    q.breakable_empty
    q.text(")")
  end
end