test-lr-associativity-03.scm 2.2 KB

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