PageRenderTime 168ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/bundle/ruby/1.9.1/gems/treetop-1.4.10/examples/lambda_calculus/lambda_calculus_test.rb

https://bitbucket.org/sqctest02/sample_app_3_1
Ruby | 89 lines | 72 code | 17 blank | 0 comment | 0 complexity | c2d5ec6c4649aa09f8bc49f033782c55 MD5 | raw file
Possible License(s): GPL-2.0
  1. dir = File.dirname(__FILE__)
  2. require File.expand_path("#{dir}/test_helper")
  3. require File.expand_path("#{dir}/arithmetic_node_classes")
  4. require File.expand_path("#{dir}/lambda_calculus_node_classes")
  5. Treetop.load File.expand_path("#{dir}/arithmetic")
  6. Treetop.load File.expand_path("#{dir}/lambda_calculus")
  7. class Treetop::Runtime::SyntaxNode
  8. def method_missing(method, *args)
  9. raise "Node representing #{text_value} does not respond to #{method}"
  10. end
  11. end
  12. class LambdaCalculusParserTest < Test::Unit::TestCase
  13. include ParserTestHelper
  14. def setup
  15. @parser = LambdaCalculusParser.new
  16. end
  17. def test_free_variable
  18. assert_equal 'x', parse('x').eval.to_s
  19. end
  20. def test_variable_binding
  21. variable = parse('x').eval
  22. env = variable.bind(1, {})
  23. assert_equal 1, env['x']
  24. end
  25. def test_bound_variable_evaluation
  26. assert_equal 1, parse('x').eval({'x' => 1})
  27. end
  28. def test_identity_function
  29. assert_equal '\x(x)', parse('\x(x)').eval.to_s
  30. end
  31. def test_function_returning_constant_function
  32. assert_equal '\x(\y(x))', parse('\x(\y(x))').eval.to_s
  33. end
  34. def test_identity_function_application
  35. assert_equal 1, parse('\x(x) 1').eval
  36. assert_equal '\y(y)', parse('\x(x) \y(y)').eval.to_s
  37. end
  38. def test_constant_function_construction
  39. assert_equal '\y(1)', parse('\x(\y(x)) 1').eval.to_s
  40. end
  41. def test_multiple_argument_application_is_left_associative
  42. assert_equal '\b(b)', parse('\x(\y(x y)) \a(a) \b(b)').eval.to_s
  43. end
  44. def test_parentheses_override_application_order
  45. assert_equal '\y(\b(b) y)', parse('\x(\y(x y)) (\a(a) \b(b))').eval.to_s
  46. end
  47. def test_arithmetic_in_function_body
  48. assert_equal 10, parse('\x(x + 5) 5').eval
  49. end
  50. def test_addition_of_function_results
  51. assert_equal 20, parse('\x(x + 5) 5 + \x(15 - x) 5').eval
  52. end
  53. def test_conditional
  54. result = parse('if (x) 1 else 2')
  55. assert_equal 1, result.eval({'x' => true})
  56. assert_equal 2, result.eval({'x' => false})
  57. end
  58. def test_keyword
  59. assert @parser.parse('if').failure?
  60. assert @parser.parse('else').failure?
  61. assert parse('elsee').success?
  62. assert parse('iff').success?
  63. end
  64. def test_program
  65. result = parse('def fact \x(if (x == 0)
  66. 1
  67. else
  68. x * fact (x - 1));
  69. fact(5)').eval
  70. assert_equal 5 * 4 * 3 * 2, result
  71. end
  72. end