test-lr-associativity-02.scm 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. ;;; test-lr-associativity-02.scm --
  2. ;;
  3. ;;Show how to use left and right associativity. Notice that the
  4. ;;terminal M is declared as left associative; this influences the
  5. ;;binding of values to the $n symbols in the semantic clauses. The
  6. ;;semantic clause in the rule:
  7. ;;
  8. ;; (E M E M E) : (list $1 $2 (list $3 $4 $5))
  9. ;;
  10. ;;looks like it is right-associated, but the result is left-associated
  11. ;;because we have declared M as "left:".
  12. ;;
  13. (load "common-test.scm")
  14. (define (doit . tokens)
  15. (let ((parser (lalr-parser
  16. (expect: 0)
  17. (N (left: A)
  18. (left: M)
  19. (nonassoc: U))
  20. (E (N) : $1
  21. (E A E) : (list $1 $2 $3)
  22. (E M E) : (list $1 $2 $3)
  23. (E M E M E) : (list $1 $2 (list $3 $4 $5))
  24. (A E (prec: U)) : (list '- $2)))))
  25. (parser (make-lexer tokens) error-handler)))
  26. ;;; --------------------------------------------------------------------
  27. ;;; Single operator.
  28. (check
  29. (doit (make-lexical-token 'N #f 1))
  30. => 1)
  31. (check
  32. (doit (make-lexical-token 'N #f 1)
  33. (make-lexical-token 'A #f '+)
  34. (make-lexical-token 'N #f 2))
  35. => '(1 + 2))
  36. (check
  37. (doit (make-lexical-token 'N #f 1)
  38. (make-lexical-token 'M #f '*)
  39. (make-lexical-token 'N #f 2))
  40. => '(1 * 2))
  41. (check
  42. (doit (make-lexical-token 'A #f '-)
  43. (make-lexical-token 'N #f 1))
  44. => '(- 1))
  45. ;;; --------------------------------------------------------------------
  46. ;;; Precedence.
  47. (check
  48. (doit (make-lexical-token 'N #f 1)
  49. (make-lexical-token 'A #f '+)
  50. (make-lexical-token 'N #f 2)
  51. (make-lexical-token 'M #f '*)
  52. (make-lexical-token 'N #f 3))
  53. => '(1 + (2 * 3)))
  54. (check
  55. (doit (make-lexical-token 'N #f 1)
  56. (make-lexical-token 'M #f '*)
  57. (make-lexical-token 'N #f 2)
  58. (make-lexical-token 'A #f '+)
  59. (make-lexical-token 'N #f 3))
  60. => '((1 * 2) + 3))
  61. ;;; --------------------------------------------------------------------
  62. ;;; Associativity.
  63. (check
  64. (doit (make-lexical-token 'N #f 1)
  65. (make-lexical-token 'A #f '+)
  66. (make-lexical-token 'N #f 2)
  67. (make-lexical-token 'A #f '+)
  68. (make-lexical-token 'N #f 3))
  69. => '((1 + 2) + 3))
  70. (check
  71. (doit (make-lexical-token 'N #f 1)
  72. (make-lexical-token 'M #f '*)
  73. (make-lexical-token 'N #f 2)
  74. (make-lexical-token 'M #f '*)
  75. (make-lexical-token 'N #f 3))
  76. => '((1 * 2) * 3))
  77. ;;; end of file