Class: Twig::Node::Macro

Inherits:
Base
  • Object
show all
Defined in:
lib/twig/node/macro.rb

Overview

Represents a macro node.

Constant Summary collapse

VARARGS_NAME =
'varargs'

Instance Attribute Summary

Attributes inherited from Base

#attributes, #lineno, #nodes, #source_context, #tag

Instance Method Summary collapse

Methods inherited from Base

#empty?, #length, #template_name, #to_s

Constructor Details

#initialize(name, body, arguments, lineno) ⇒ Macro

Returns a new instance of Macro.

Parameters:



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/twig/node/macro.rb', line 13

def initialize(name, body, arguments, lineno)
  arguments.key_value_pairs.each do |key, value|
    next unless "\u035C#{VARARGS_NAME}" == key.attributes[:name]

    raise Error::Syntax.new(
      "The argument \"#{VARARGS_NAME}\" in macro \"#{name}\" cannot be defined because the variable " \
      "\"#{VARARGS_NAME}\" is reserved for arbitrary arguments.",
      value.lineno,
      value.source_context
    )
  end

  super({ body: body, arguments: arguments }, { name: name }, lineno)
end

Instance Method Details

#compile(compiler) ⇒ Object

Parameters:



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/twig/node/macro.rb', line 29

def compile(compiler)
  compiler.
    add_debug_info(self).
    write("def macro_#{attributes[:name]}(call_context, ")

  arguments = nodes[:arguments]
  arguments.key_value_pairs.each do |key, value|
    compiler.
      subcompile(key).
      raw(': ').
      subcompile(value).
      raw(', ')
  end

  compiler.
    raw('**varargs').
    raw(")\n").
    write("  macros = @macros\n").
    write("  context = ::Twig::Runtime::Context.new({\n")

  arguments.key_value_pairs.each do |pair|
    key = pair[0]
    var = key.attributes[:name]
    if var.start_with?("\u035C")
      var = var[("\u035C".length)..]
    end
    compiler.
      write('    ').
      string(var).
      raw(' => ').
      subcompile(key).
      raw(",\n")
  end

  capture_node = Node::Capture.new(nodes[:body], nodes[:body].lineno)

  compiler.
    write('    ').
    string(VARARGS_NAME).
    raw(' => ').
    raw("varargs,\n").
    write("  }.merge(env.globals), call_context:)\n\n").
    write("  blocks = {}\n\n").
    write('  ').
    subcompile(capture_node).
    raw("\n").
    write("end\n\n")
end