A toy dynamic programming language written in Ruby
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

function_call.rb 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. class AST::FunctionCall
  2. attr_reader :function, :arguments
  3. def initialize(function, arguments)
  4. @function = function
  5. @arguments = arguments
  6. end
  7. def ==(other)
  8. other.is_a?(AST::FunctionCall) && other.function == @function &&
  9. other.arguments == @arguments
  10. end
  11. def execute(env)
  12. env = Environment.new(env)
  13. function = if @function.is_a?(AST::Identifier)
  14. env.get(@function.name)
  15. elsif @function.is_a?(AST::FunctionDefinition)
  16. @function
  17. end
  18. if function.is_a?(AST::FunctionDefinition)
  19. env = function.env unless function.env.nil?
  20. if @arguments.size != function.parameters.size
  21. raise "Arity mismatch in call to function #{function.name}"
  22. end
  23. function.parameters.each_with_index do |param, i|
  24. env.set(param.name, @arguments[i].execute(env))
  25. end
  26. value = nil
  27. function.body.statements.each do |statement|
  28. value = statement.execute(env)
  29. end
  30. value
  31. elsif function.is_a?(Proc)
  32. arguments = @arguments.map { |arg| arg.execute(env) }
  33. function.call(*arguments)
  34. end
  35. end
  36. end