A toy dynamic programming language written in Ruby
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

function_call.rb 1.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. if @arguments.size != function.parameters.size
  20. raise "Arity mismatch in call to function #{function.name}"
  21. end
  22. function.parameters.each_with_index do |param, i|
  23. env.set(param.name, @arguments[i].execute(env))
  24. end
  25. value = nil
  26. function.body.statements.each do |statement|
  27. value = statement.execute(env)
  28. end
  29. value
  30. elsif function.is_a?(Proc)
  31. arguments = @arguments.map { |arg| arg.execute(env) }
  32. function.call(*arguments)
  33. end
  34. end
  35. end