node-equal.scm 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. ;;; Ported from Scheme 48 1.9. See file COPYING for notices and license.
  2. ;;;
  3. ;;; Port Author: Andrew Whatson
  4. ;;;
  5. ;;; Original Authors: Richard Kelsey
  6. ;;;
  7. ;;; scheme48-1.9.2/ps-compiler/node/node-equal.scm
  8. ;;;
  9. ;;; Determining if two nodes are functionally identical.
  10. (define-module (ps-compiler node node-equal)
  11. #:use-module (prescheme scheme48)
  12. #:use-module (ps-compiler node node)
  13. #:export (node-equal?))
  14. (define (node-equal? n1 n2)
  15. (if (call-node? n1)
  16. (and (call-node? n2)
  17. (call-node-eq? n1 n2))
  18. (value-node-eq? n1 n2)))
  19. ;; Compare two call nodes. The arguments to the nodes are compared
  20. ;; starting from the back to do leaf nodes first (usually).
  21. (define (call-node-eq? n1 n2)
  22. (and (= (call-arg-count n1) (call-arg-count n2))
  23. (= (call-exits n1) (call-exits n2))
  24. (eq? (call-primop n1) (call-primop n2))
  25. (let ((v1 (call-args n1))
  26. (v2 (call-args n2)))
  27. (let loop ((i (- (vector-length v1) '1)))
  28. (cond ((< i '0)
  29. #t)
  30. ((node-equal? (vector-ref v1 i) (vector-ref v2 i))
  31. (loop (- i '1)))
  32. (else
  33. #f))))))
  34. ;; Compare two value nodes. Reference nodes are the same if they refer to the
  35. ;; same variable or if they refer to corresponding variables in the two node
  36. ;; trees. Primop and literal nodes must be identical. Lambda nodes are compared
  37. ;; by their own procedure.
  38. (define (value-node-eq? n1 n2)
  39. (cond ((neq? (node-variant n1) (node-variant n2))
  40. #f)
  41. ((reference-node? n1)
  42. (let ((v1 (reference-variable n1))
  43. (v2 (reference-variable n2)))
  44. (or (eq? v1 v2) (eq? v1 (variable-flag v2)))))
  45. ((literal-node? n1)
  46. (and (eq? (literal-value n1) (literal-value n2))
  47. (eq? (literal-type n1) (literal-type n2))))
  48. ((lambda-node? n1)
  49. (lambda-node-eq? n1 n2))))
  50. ;; Lambda nodes are identical if they have identical variable lists and identical
  51. ;; bodies. The variables of N1 are stored in the flag fields of the variables of
  52. ;; N2 for the use of VALUE-NODE-EQ?.
  53. (define (lambda-node-eq? n1 n2)
  54. (let ((v1 (lambda-variables n1))
  55. (v2 (lambda-variables n2)))
  56. (let ((ok? (let loop ((v1 v1) (v2 v2))
  57. (cond ((null? v1)
  58. (if (null? v2)
  59. (call-node-eq? (lambda-body n1) (lambda-body n2))
  60. #f))
  61. ((null? v2) #f)
  62. ((variable-eq? (car v1) (car v2))
  63. (loop (cdr v1) (cdr v2)))
  64. (else #f)))))
  65. (map (lambda (v) (if v (set-variable-flag! v #f))) v2)
  66. ok?)))
  67. (define (variable-eq? v1 v2)
  68. (cond ((not v1)
  69. (not v2))
  70. ((not v2) #f)
  71. ((eq? (variable-type v1) (variable-type v2))
  72. (set-variable-flag! v2 v1)
  73. #t)
  74. (else #f)))