Class: SyntaxTree::Lambda

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

Overview

Lambda represents using a lambda literal (not the lambda method call).

->(value) { value * 2 }

Instance Attribute Summary collapse

Attributes inherited from Node

#location

Instance Method Summary collapse

Methods inherited from Node

#pretty_print, #to_json

Constructor Details

#initialize(params:, statements:, location:, comments: []) ⇒ Lambda

Returns a new instance of Lambda.



5806
5807
5808
5809
5810
5811
# File 'lib/syntax_tree/node.rb', line 5806

def initialize(params:, statements:, location:, comments: [])
  @params = params
  @statements = statements
  @location = location
  @comments = comments
end

Instance Attribute Details

#comments ⇒ Object (readonly)

[Array[ Comment | EmbDoc ]] the comments attached to this node



5804
5805
5806
# File 'lib/syntax_tree/node.rb', line 5804

def comments
  @comments
end

#params ⇒ Object (readonly)

[Params | Paren] the parameter declaration for this lambda



5798
5799
5800
# File 'lib/syntax_tree/node.rb', line 5798

def params
  @params
end

#statements ⇒ Object (readonly)

[BodyStmt | Statements] the expressions to be executed in this lambda



5801
5802
5803
# File 'lib/syntax_tree/node.rb', line 5801

def statements
  @statements
end

Instance Method Details

#accept(visitor) ⇒ Object



5813
5814
5815
# File 'lib/syntax_tree/node.rb', line 5813

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

#child_nodes ⇒ Object Also known as: deconstruct



5817
5818
5819
# File 'lib/syntax_tree/node.rb', line 5817

def child_nodes
  [params, statements]
end

#deconstruct_keys(keys) ⇒ Object



5823
5824
5825
5826
5827
5828
5829
5830
# File 'lib/syntax_tree/node.rb', line 5823

def deconstruct_keys(keys)
  {
    params: params,
    statements: statements,
    location: location,
    comments: comments
  }
end

#format(q) ⇒ Object



5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
# File 'lib/syntax_tree/node.rb', line 5832

def format(q)
  q.group(0, "->") do
    if params.is_a?(Paren)
      q.format(params) unless params.contents.empty?
    elsif !params.empty?
      q.group do
        q.text("(")
        q.format(params)
        q.text(")")
      end
    end

    q.text(" ")
    q.if_break do
      force_parens =
        q.parents.any? do |node|
          node.is_a?(Command) || node.is_a?(CommandCall)
        end

      q.text(force_parens ? "{" : "do")
      q.indent do
        q.breakable
        q.format(statements)
      end

      q.breakable
      q.text(force_parens ? "}" : "end")
    end.if_flat do
      q.text("{ ")
      q.format(statements)
      q.text(" }")
    end
  end
end