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.



8489
8490
8491
8492
8493
8494
# File 'lib/syntax_tree/node.rb', line 8489

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



8487
8488
8489
# File 'lib/syntax_tree/node.rb', line 8487

def comments
  @comments
end

#contentsObject (readonly)

nil | Node

the expression inside the parentheses



8484
8485
8486
# File 'lib/syntax_tree/node.rb', line 8484

def contents
  @contents
end

#lparenObject (readonly)

LParen

the left parenthesis that opened this statement



8481
8482
8483
# File 'lib/syntax_tree/node.rb', line 8481

def lparen
  @lparen
end

Instance Method Details

#===(other) ⇒ Object



8545
8546
8547
8548
# File 'lib/syntax_tree/node.rb', line 8545

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

#accept(visitor) ⇒ Object



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

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

#child_nodesObject Also known as: deconstruct



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

def child_nodes
  [lparen, contents]
end

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



8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
# File 'lib/syntax_tree/node.rb', line 8504

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



8518
8519
8520
8521
8522
8523
8524
8525
# File 'lib/syntax_tree/node.rb', line 8518

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

#format(q) ⇒ Object



8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
# File 'lib/syntax_tree/node.rb', line 8527

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