Class: SyntaxTree::Lambda

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

Overview

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

->(value) { value * 2 }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Lambda.



7317
7318
7319
7320
7321
7322
# File 'lib/syntax_tree.rb', line 7317

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

Instance Attribute Details

#commentsObject (readonly)

Array[ Comment | EmbDoc ]

the comments attached to this node



7315
7316
7317
# File 'lib/syntax_tree.rb', line 7315

def comments
  @comments
end

#locationObject (readonly)

Location

the location of this node



7312
7313
7314
# File 'lib/syntax_tree.rb', line 7312

def location
  @location
end

#paramsObject (readonly)

Params | Paren

the parameter declaration for this lambda



7306
7307
7308
# File 'lib/syntax_tree.rb', line 7306

def params
  @params
end

#statementsObject (readonly)

BodyStmt | Statements

the expressions to be executed in this lambda



7309
7310
7311
# File 'lib/syntax_tree.rb', line 7309

def statements
  @statements
end

Instance Method Details

#child_nodesObject



7324
7325
7326
# File 'lib/syntax_tree.rb', line 7324

def child_nodes
  [params, statements]
end

#format(q) ⇒ Object



7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
# File 'lib/syntax_tree.rb', line 7328

def format(q)
  q.group(0, "->") do
    if params.is_a?(Paren)
      q.format(params) unless params.contents.empty?
    elsif !params.empty?
      q.text("(")
      q.format(params)
      q.text(")")
    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

#pretty_print(q) ⇒ Object



7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
# File 'lib/syntax_tree.rb', line 7361

def pretty_print(q)
  q.group(2, "(", ")") do
    q.text("lambda")

    q.breakable
    q.pp(params)

    q.breakable
    q.pp(statements)

    q.pp(Comment::List.new(comments))
  end
end

#to_json(*opts) ⇒ Object



7375
7376
7377
7378
7379
7380
7381
7382
7383
# File 'lib/syntax_tree.rb', line 7375

def to_json(*opts)
  {
    type: :lambda,
    params: params,
    stmts: statements,
    loc: location,
    cmts: comments
  }.to_json(*opts)
end