Class: Rjq::AST::FunctionCall

Inherits:
Node
  • Object
show all
Defined in:
lib/rjq/ast.rb

Instance Attribute Summary collapse

Attributes inherited from Node

#source_span

Instance Method Summary collapse

Methods inherited from Node

#assign_value, #invalid_path_message, #take, #with_source_span

Constructor Details

#initialize(name, args = []) ⇒ FunctionCall

Returns a new instance of FunctionCall.



1051
1052
1053
1054
# File 'lib/rjq/ast.rb', line 1051

def initialize(name, args = [])
  @name = name
  @args = args
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



1049
1050
1051
# File 'lib/rjq/ast.rb', line 1049

def args
  @args
end

#nameObject (readonly)

Returns the value of attribute name.



1049
1050
1051
# File 'lib/rjq/ast.rb', line 1049

def name
  @name
end

Instance Method Details

#eval(input, context) ⇒ Object



1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
# File 'lib/rjq/ast.rb', line 1056

def eval(input, context)
  if @args.empty? && context.variables[filter_variable_name(@name)].is_a?(Node)
    return context.variables[filter_variable_name(@name)].eval(input, context)
  end

  if context.functions.key?([@name, @args.length])
    return eval_user_function(input, context, context.functions.fetch([@name, @args.length]))
  end

  Builtins.call(@name, input, context, @args)
end

#paths(input, context) ⇒ Object

Raises:



1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
# File 'lib/rjq/ast.rb', line 1068

def paths(input, context)
  if @args.empty? && context.variables[filter_variable_name(@name)].is_a?(Node)
    return context.variables[filter_variable_name(@name)].paths(input, context)
  end

  return @args.first.eval(input, context).map { |path| Array(path) } if @name == 'getpath' && @args.length == 1

  if context.functions.key?([@name, @args.length])
    definition = context.functions.fetch([@name, @args.length])
    return call_contexts(input, context, definition).flat_map { |ctx| definition.body.paths(input, ctx) }
  end

  if @name == 'select' && @args.length == 1
    return @args.first.eval(input, context).any? { |value| Value.truthy?(value) } ? [[]] : []
  end
  return [] if @name == 'empty' && @args.empty?
  return [[0]] if @name == 'first' && @args.empty?
  return [[-1]] if @name == 'last' && @args.empty?

  result = eval(input, context)
  result = result.first if result.length == 1
  raise InvalidPathError.new(invalid_path_message(result, input, context), result)
end