Class: Twig::Util::CallableArgumentsExtractor

Inherits:
Object
  • Object
show all
Defined in:
lib/twig/util/callable_arguments_extractor.rb

Instance Method Summary collapse

Constructor Details

#initialize(node, twig_callable, environment) ⇒ CallableArgumentsExtractor



9
10
11
12
13
# File 'lib/twig/util/callable_arguments_extractor.rb', line 9

def initialize(node, twig_callable, environment)
  @node = node
  @twig_callable = twig_callable
  @environment = environment
end

Instance Method Details

#extract_arguments(arguments) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/twig/util/callable_arguments_extractor.rb', line 16

def extract_arguments(arguments)
  # Check argument order first
  found_named = false
  arguments.nodes.each_key do |key|
    if key.is_a?(Integer)
      if found_named
        raise Error::Syntax.new(
          "Positional arguments cannot be used after named arguments for #{@twig_callable.type} " \
          "\"#{@twig_callable.name}\".",
          @node.lineno,
          @node.source_context
        )
      end
    else
      found_named = true
    end
  end

  called_arguments = destination_arguments.keys.to_h { |k| [k, false] }

  spreads, arguments = arguments.nodes.partition do |_, node|
    node.is_a?(Node::Expression::Unary::Spread)
  end.map(&:to_h)

  positional, kwargs = arguments.partition do |key, _node|
    key.is_a?(Integer)
  end.map(&:to_h)

  positional = positional.values
  positional_count = positional.length

  kwargs.transform_keys!(&:to_sym)
  resolved_positional = []
  resolved_kwargs = {}
  rest = false
  keyrest = false

  destination_arguments.each do |name, type|
    if positional.any?
      case type
      when :req, :opt
        resolved_positional << positional.shift
      when :keyreq, :key
        arg = positional.shift

        if arg.is_a?(Node::Expression::Unary::HashSpread)
          keyrest = true
          resolved_positional << arg
        else
          resolved_kwargs[name] = arg
        end
      when :rest
        resolved_positional += positional
        positional = []
        rest = true
        next
      when :keyrest
        arg = positional.shift

        if arg.is_a?(Node::Expression::Unary::HashSpread)
          keyrest = true
          resolved_positional << arg
        else
          raise Error::Syntax.new(
            "Expected a hash spread for argument \"#{name}\" " \
            "for #{@twig_callable.type} \"#{@twig_callable.name}\".",
            @node.lineno,
            @node.source_context
          )
        end

        next
      else
        raise "Unknown argument type: #{name} #{type}"
      end
    elsif kwargs.key?(name) || (found = kwargs.keys.detect { |key| key.to_s.underscore.to_sym == name })
      found = name if found.nil?

      if i[opt req].include?(type)
        resolved_positional << kwargs.delete(found)
      else
        resolved_kwargs[name] = kwargs.delete(found)
      end
    else
      case type
      when :opt, :key, :rest
        next
      when :keyrest
        keyrest = true
        resolved_kwargs.merge!(kwargs)
        kwargs = {}
        next
      else
        # If we have spreads, we just can't know until runtime since we don't know if it's a
        # positional spread or kwarg spread because both use ...
        unless spreads.any? || keyrest
          raise Error::Syntax.new(
            "Value for argument \"#{name}\" is required for #{@twig_callable.type} \"#{@twig_callable.name}\".",
            @node.lineno,
            @node.source_context
          )
        end
      end
    end

    called_arguments[name] = true
  end

  # If any of our remaining kwargs intersect with called_arguments then we have a duplicate key
  duplicated = called_arguments.select { |_k, v| v }.keys & kwargs.keys
  duplicated = duplicated.map(&:to_s)
  duplicated = duplicated[0] if duplicated.one?

  unless duplicated.empty?
    raise Error::Syntax.new(
      "Argument #{duplicated.inspect} is defined twice for #{@twig_callable.type} " \
      "\"#{@twig_callable.name}\".",
      @node.lineno,
      @node.source_context
    )
  end

  unexpected_arguments = []
  unknown_argument = nil

  # If there's no keyrest and any kwargs left, they are extraneous
  if !keyrest && kwargs.any?
    unexpected_arguments += kwargs.keys
    unknown_argument = kwargs.values.first
  end

  # If there's a rest and any positional left, they are extraneous
  if !rest && positional.any?
    unexpected_arguments += [
      *((positional_count - positional.length)...positional_count),
    ]
    unknown_argument = positional.first
  end

  if unexpected_arguments.any?
    unknown_argument ||= @node

    raise Error::Syntax.new(
      "Unknown argument \"#{unexpected_arguments.join(', ')}\" " \
      "for #{@twig_callable.type} \"#{@twig_callable.name}(#{destination_arguments.keys.join(', ')})\".",
      unknown_argument.lineno,
      unknown_argument.source_context
    )
  end

  [resolved_positional + spreads.values, resolved_kwargs]
end