Class: Confuscript::Nodes::Print::PrintDefinitionNode

Inherits:
BaseNode
  • Object
show all
Defined in:
lib/confuscript/nodes/print/print_definition_node.rb

Overview

Represents a print definition node

Instance Method Summary collapse

Methods inherited from BaseNode

#find_node

Instance Method Details

#evaluate(context) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/confuscript/nodes/print/print_definition_node.rb', line 6

def evaluate(context)
  print_name = print_name_element.text_value
  print_arguments = retrieve_arguments(print_arguments_element.elements, context)
  print_body = print_body_element

  # I don't know I think I'll have to create a proc here
  # That will be used when printCallNode is evaluated
  print = proc do |*args|
    print_context = {}

    print_arguments.each_with_index do |argument, index|
      print_context[argument] = args[index]
    end

    print_body.evaluate(print_context)
  end

  # Some GuardRails to prevent overwriting
  raise Confuscript::SyntaxError, "Print #{print_name} already defined" if context[print_name]

  context[print_name] = print
end


33
34
35
# File 'lib/confuscript/nodes/print/print_definition_node.rb', line 33

def print_arguments_element
  elements[5]
end


37
38
39
# File 'lib/confuscript/nodes/print/print_definition_node.rb', line 37

def print_body_element
  elements[8]
end


29
30
31
# File 'lib/confuscript/nodes/print/print_definition_node.rb', line 29

def print_name_element
  elements[2]
end

#retrieve_arguments(elements, context) ⇒ Object

Since the VariableNodes are deeply nested We need to deep search and fetch the VariableNodes This method recursively does that We have a same named method in PrintCallNode that does the same thing Except it evaluates the value instead of returning the text_value TODO: DRY out the code with PrintCallNode#retrieve_arguments



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/confuscript/nodes/print/print_definition_node.rb', line 47

def retrieve_arguments(elements, context)
  elements.flat_map do |element|
    if element.is_a?(Confuscript::Nodes::Values::VariableNode)
      element.text_value
    elsif element.elements
      retrieve_arguments(element.elements, context)
    else
      nil
    end
  end.compact
end