unifier.lisp 51.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
;;; -*- Mode: Lisp -*-

;;; unifier.lisp
;;; General CL structures unifier.

;;;; See file COPYING for copyright licensing information.

(in-package "CL.EXT.DACF.UNIFICATION") ; DACF = Data And Control Flow.

(defgeneric unify (a b &optional env &key &allow-other-keys)
  (:documentation
   "Unifies two objects A and B given a substitution ENV.
A is a Common Lisp object and B is either a Common Lisp object or a
\"template\", A and B can be commuted.

The unification rules are rather complex. Each method of the generic
function implements a specific rule of unification.

The generic function returns a `substitution' upon success or it
signals a UNIFICATION-FAILURE condition upon failure."))



;;;===========================================================================
;;; Simple, non template methods.

(defmethod unify ((a symbol) (b list)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  "Unifies a symbol A and a list B in an environment ENV.
If A is not a variable then an error of type UNIFICATION-FAILURE is
signaled. If A is a unification variable, then the environment ENV is
extended with a binding for A to B, unless the occurrence check is
called and fails, in which case an error is signaled."
  (cond ((variable-any-p a) env)
        ((variablep a) (var-unify a b env))
        (t (error 'unification-failure
                  :format-control "Cannot unify a symbol with a list: ~S ~S."
                  :format-arguments (list a b)))))


(defmethod unify ((b list) (a symbol)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  "Unifies a symbol B and a list A in an environment ENV.
If A is not a variable then an error of type UNIFICATION-FAILURE is
signaled. If A is a unification variable, then the environment ENV is
extended with a binding for A to B, unless the occurrence check is
called and fails, in which case an error is signaled."
  (cond ((variable-any-p a) env)
        ((variablep a) (var-unify a b env))
        (t (error 'unification-failure
                  :format-control "Cannot unify a list with a symbol: ~S ~S."
                  :format-arguments (list b a)))))


(defmethod unify ((a list) (b list)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  "Unifies a list A and a list B in an environment ENV.
The unification procedure proceedes recursively on each element of
both lists. If two elements cannot be unified then an error of type
UNIFICATION-FAILURE is signaled.  Otherwise a possibly extended
environment is returned."
  (unify (rest a) (rest b) (unify (first a) (first b) env)))



(defmethod unify ((a number) (b number)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  "Unifies two numbers A and B.
Two numbers unify only if and only if they are equal as per the function #'=, in
which case an unmodified envirironment ENV is returned.
Otherwise an error of type UNIFICATION-FAILURE is signalled.
Of course, asking for unification of two floating point numbers may
not yield the expected result."
  (if (= a b)
      env
      (error 'unification-failure
             :format-control "Cannot unify two different numbers: ~S ~S."
             :format-arguments (list a b))))


(defparameter *unify-string-case-sensitive-p* t)

(defmethod unify ((a character) (b character)
                  &optional (env (make-empty-environment))
                  &key
                  (case-sensitive *unify-string-case-sensitive-p*)
                  &allow-other-keys)
  "Unifies two strings A and B.
Two CHARACTERs A and B unify if and only if they satisfy either #'CHAR= or
#'CHAR-EQUAL. The choice of which of test to perform (#'CHAR= or #'CHAR-EQUAL)
is made according to the value of the variable
*UNIFY-STRING-CASE-SENSITIVE-P*, which defaults to T.
If A and B unify then an unmodified environment ENV is returned,
otherwise an error of type UNIFICATION-FAILURE is signaled."
  (cond ((and case-sensitive (char= a b))
         env)
        ((char-equal a b)
         env)
        (t
         (error 'unification-failure
                :format-control "Connot unify two different characters: ~S ~S."
                :format-arguments (list a b)))))


(defmethod unify ((a string) (b string)
                  &optional (env (make-empty-environment))
                  &key
                  (case-sensitive *unify-string-case-sensitive-p*)
                  &allow-other-keys)
  "Unifies two strings A and B.
Two strings A and B unify if and only if they satisfy either #'STRING= or
#'STRING-EQUAL. The choice of which of test to perform (#'STRING= or #'STRING-EQUAL)
is made according to the value of the variable
*UNIFY-STRING-CASE-SENSITIVE-P*, which defaults to T.
If A and B unify then an unmodified environment ENV is returned,
otherwise an error of type UNIFICATION-FAILURE is signaled."
  (cond ((and case-sensitive (string= a b))
         env)
        ((and (not case-sensitive) (string-equal a b))
         env)
        (t
         (error 'unification-failure
                :format-control "Connot unify two different strings: ~S ~S."
                :format-arguments (list a b)))))


(defmethod unify ((a symbol) (b string)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (cond ((variable-any-p a) env)
        ((variablep a) (var-unify a b env))
        (t (error 'unification-failure
		  :format-control "Cannot unify a symbol with a string: ~S ~S."
		  :format-arguments (list a b)))))


(defmethod unify ((b string) (a symbol)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (cond ((variable-any-p a) env)
        ((variablep a) (var-unify a b env))
        (t (error 'unification-failure
                  :format-control "Cannot unify a string with a symbol: ~S ~S."
                  :format-arguments (list b a)))))


(defmethod unify ((a symbol) (b symbol)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (cond ((variable-any-p a) env)
        ((variablep a) (var-unify a b env))
        ((variable-any-p b) env)
        ((variablep b) (var-unify b a env))
        ((eq a b) env)
        (t (error 'unification-failure
                  :format-control "Cannot unify two different symbols: ~S ~S."
                  :format-arguments (list a b)))))


(defmethod unify ((a symbol) (b t)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (cond ((variable-any-p a) env)
        ((variablep a) (var-unify a b env))
        (t (call-next-method))))


(defmethod unify ((b t) (a symbol)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (cond ((variable-any-p a) env)
        ((variablep a) (var-unify a b env))
        (t (call-next-method))))


(defmethod unify ((a symbol) (b array)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (cond ((variable-any-p a) env)
        ((variablep a) (var-unify a b env))
        (t (error 'unification-failure
                  :format-control "Cannot unify a symbol with ~
                                   an array or vector: ~S and ~S."
                  :format-arguments (list a b)))))


(defmethod unify ((b array) (a symbol)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (cond ((variable-any-p a) env)
        ((variablep a) (var-unify a b env))
        (t (error 'unification-failure
                  :format-control "Cannot unify an array or vector with a symbol: ~S and ~S."
                  :format-arguments (list a b)))))


(defmethod unify ((as vector) (bs vector)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unless (= (length as) (length bs))
    (error 'unification-failure
           :format-control "Cannot unify two vectors of different length: ~D and ~D."
           :format-arguments (list (length as) (length bs))))
  (loop for a across as
        for b across bs
        for mgu = (unify a b env) then (unify a b mgu)
        finally (return mgu)))


(defmethod unify ((s1 sequence) (s2 sequence)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unless (= (length s1) (length s2))
    (error 'unification-failure
           :format-control "Cannot unify two sequences of different length: ~D and ~D."
           :format-arguments (list (length s1) (length s2))))
  (loop for i from 0 below (length s1)
        for j from 0 below (length s2)
        for mgu = (unify (elt s1 i) (elt s2 j) env) then (unify (elt s1 i) (elt s2 j) mgu)
        finally (return mgu)))



(defgeneric untyped-unify (a b &optional env))

(defmethod untyped-unify ((as list) (bs vector)
                          &optional (env (make-empty-environment)))
  (loop for a in as
        for b across bs
        for mgu = (unify a b env) then (unify a b mgu)
        finally (return mgu)))


(defmethod untyped-unify ((as vector) (bs list)
                          &optional (env (make-empty-environment)))
  (untyped-unify bs as env))

(defmethod untyped-unify ((a t) (b t) &optional (env (make-empty-environment)))
  (unify a b env))


(defmethod unify ((as array) (bs array)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unless (= (array-total-size as) (array-total-size bs))
    (error 'unification-failure
           :format-control "Cannot unify two arrays of different total size: ~D and ~D."
           :format-arguments (list (array-total-size as) (array-total-size bs))))
  (loop for ai from 0 below (array-total-size as)
        for bi from 0 below (array-total-size bs)
        for mgu = (unify (row-major-aref as ai) (row-major-aref bs bi) env)
        then (unify (row-major-aref as ai) (row-major-aref bs bi) mgu)
        finally (return mgu)))


;;; Catch all method.

(defmethod unify ((a t) (b t)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (if (equalp a b)
      env
      (error 'unification-failure
             :format-control "Cannot unify a ~S and a ~S: ~S ~S."
             :format-arguments (list (type-of a) (type-of b) a b))))


;;;===========================================================================
;;; Templates methods.


;;; valid-template-p --
;;; Useful later.  Tests whether the object X can be considered a template.
;;; This should probably become a generic function.

(defun valid-template-p (x)
  (or (symbolp x)
      (consp x)
      (numberp x)
      (arrayp x)
      (typep (class-of x) 'structure-class)
      (typep (class-of x) 'standard-class)
      (typep (class-of x) 'built-in-class)
      (template-p x)))


;;; Special catch all method.

(defmethod unify ((x template) (y template)
                  &optional (env)
                  &key &allow-other-keys)
  (declare (ignore env))
  (error 'unification-failure
           :format-control "Unification of two templates of type ~A and ~A ~
                            has not been yet implemented."
           :format-arguments (list (class-name (class-of x))
                                   (class-name (class-of y)))))


;;;---------------------------------------------------------------------------
;;; NIL special unification methods.

(defmethod unify ((x null) (y null)
		  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  env)


(defmethod unify ((x null) (nt nil-template)
		  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  env)


(defmethod unify ((nt nil-template) (x null)
		  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  env)


(defmethod unify ((nt1 nil-template) (nt2 nil-template)
		  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  env)


;;;---------------------------------------------------------------------------
;;; Symbol methods.
;;;
;;; Note: when A is a variable, then the unification should proceed
;;; specially for each template.  The UNIFY TEMPLATE SYMBOL method
;;; takes care of commutativity.

(defmethod unify ((a symbol) (b symbol-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (cond ((variable-any-p a) env)
        ((variablep a) (var-unify a b env))
        (t (unify a (symbol-template-symbol b) env))))


(defmethod unify ((b symbol-template) (a symbol)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


#+old-version
(defmethod unify ((a symbol) (b template)
                  &optional (env)
                  &key &allow-other-keys)
  (declare (ignore env))
  (error 'unification-failure
         :format-control "Cannot unify symbol ~S with template ~S."
         :format-arguments (list a b)))


;;; New version of unification via symbols and templates.

(defmethod unify ((a symbol) (b template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (cond ((variable-any-p a) env)
        ((variablep a) (var-unify a b env))
        (t (error 'unification-failure
                  :format-control "Cannot unify symbol ~S with template ~S."
                  :format-arguments (list a b))))
  )


(defmethod unify ((b template) (a symbol)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


;;;---------------------------------------------------------------------------
;;; Number template methods.

#+not-right
(defmethod unify ((a symbol) (b number-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (cond ((variable-any-p a) env)
        ((variablep a) (unify a (number-template-number b) env))
        (t (call-next-method))))


(defmethod unify ((a number) (b number-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a (number-template-number b) env))


(defmethod unify ((b number-template) (a number)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


(defmethod unify :before ((a number) (b number-template)
                          &optional (env (make-empty-environment))
                          &key &allow-other-keys)
  (unless (typep a (number-template-numeric-type b))
    (error 'simple-type-error
           :datum a
           :expected-type (number-template-numeric-type b)
           :format-control "Cannot unify the number ~S with a number constrained to be a ~S."
           :format-arguments (list a (number-template-numeric-type b))))
  )


(defmethod unify ((a number) (b template)
                  &optional (env)
                  &key &allow-other-keys)
  (declare (ignore env))
  (error 'unification-failure
         :format-control "Cannot unify the number ~S with template ~S."
         :format-arguments (list a b)))

(defmethod unify ((b template) (a number)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


;;;---------------------------------------------------------------------------
;;; Sequence (List) template methods

(defmethod unify ((a sequence) (b template)
                  &optional (env)
                  &key &allow-other-keys)
  (declare (ignore env))
  (error 'unification-failure
         :format-control "Cannot unify a sequence with a non sequence ~
                         or non sequence access template: ~S and ~S."
         :format-arguments (list a b)))


(defmethod unify ((b template) (a sequence)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


#| Needs to be fixed.
(defmethod unify ((a list) (b lambda-template) &optional (env (make-empty-environment)))
  (unify a (template-spec b) env))


(defmethod unify ((b lambda-template) (a list) &optional (env (make-empty-environment)))
  (unify (template-spec b) a env))
|#


;;; The next is incomplete and does not signal appropriate errors.

(defmethod unify ((a list) (b template)
                  &optional (env)
                  &key &allow-other-keys)
  (declare (ignore env))
  (error 'unification-failure
         :format-control "Cannot unify a list with a non-list template: ~S ~S."
         :format-arguments (list a b)))


#+20121204-old-version
(defmethod unify ((a list) (b sequence-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (let ((template-lambda-list (sequence-template-lambda-list b))
        (ll (list-length a))
        )
    (multiple-value-bind (vars optionals keys rest)
        (parse-extended-ordinary-lambda-list template-lambda-list
                                             :ordinary-variable-test #'valid-template-p
                                             :optional-variable-test #'valid-template-p
                                             :key-variable-test #'valid-template-p
                                             :rest-variable-test #'valid-template-p
                                             )

      (let* ((n-vars (list-length vars))
             (n-optionals (list-length optionals))
             (env (unify (subseq a 0 (min ll (list-length vars)))
			 vars
			 env))
             )
        (when (and optionals (>= ll (+ n-vars n-optionals)))
          (setf env (unify (subseq a n-vars (+ n-vars n-optionals)) optionals env)))
        (when (and rest (>= ll (+ n-vars n-optionals)))
          (setf env (unify (subseq a (+ n-vars n-optionals)) (first rest) env)))
        (when keys (warn "Sorry matching of keywords ~S not yet implemented." keys))
        env
        ))))



(defmethod unify ((a list) (b sequence-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (declare (type environment env))
  (let ((template-lambda-list (sequence-template-lambda-list b))
        (rest-a ())
        (env1 env)
        )
    (declare (type environment env1)
             (type list template-lambda-list)
             )
    (multiple-value-bind (vars optionals keys rest)
        (parse-extended-ordinary-lambda-list template-lambda-list
                                             :ordinary-variable-test #'valid-template-p
                                             :optional-variable-test #'valid-template-p
                                             :key-variable-test #'valid-template-p
                                             :rest-variable-test #'valid-template-p
                                             )
      
      (loop for el-template in vars
            for (el . els) on a
            for env of-type environment = (unify el el-template env1)
            then (unify el el-template env)
            do (setf rest-a els
                     env1 env))
            

      (loop for el-template in optionals
            for (el . els) on rest-a
            for env of-type environment = (unify el el-template env1)
            then (unify el el-template env)
            do (setf rest-a els
                     env1 env))


      (when rest
        (setf env1 (unify rest-a (first rest) env1)))

      (when keys (warn "Sorry matching of keywords ~S not yet implemented." keys))
      env1
      )))



(defmethod unify ((b template) (a list)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))



;;;---------------------------------------------------------------------------
;;; Plist template methods.
;;;

#| Complicated version (not working)
;;; A plist template interprets the <destructuring template lambda list>
;;; (DTLL) in a special way.
;;; As a result of PARSE-EXTENDED-ORDINARY-LAMBDA-LIST the four values
;;; returned, VARS, OPTIONALS, KEYS and REST are interpreted as
;;; follows.  Not that a decision is made w.r.t. plists that are
;;; "bigger" than the specs in the DTLL.
;;;
;;; VARS must be a plist: all pairs must be present and match in the
;;;      plist A
;;; OPTIONALS must be a plist: all pairs may be present and match in
;;;      the plist A
;;; REST if present must be a unification variable and it indicates
;;;      that the plist A may be bigger than what is expected by the
;;;      rest of the DTLL; if KEYS is present the REST variable is
;;;      boud to the plist of the keyowrds (which may contain unbound
;;;      variables and templates)
;;; KEYS must be a keyword plist: all pairs mentioned may be present
;;;      and match in the plist A.
;;;
;;; Examples:
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 c 3 a 1)) ==> {}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 c ?C a 1)) ==> {C/3}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 a 1) ==> fail
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 a 1 &rest _) ==> {}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 a 1 &optional c 42) ==> {}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 a 1 &optional c 42) ==> {}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 &optional c 42) ==> fail
;;;         too few possible matches.
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 &key c 42) ==> fail
;;;         too few possible matches.
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 &rest _ &key c 42) ==> {}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 &optional c 42 &rest _) ==> {}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 &rest ?keys &key c 42) ==> {keys/(c 42)}
;;;
;;;
;;; Next a twist. In VARS and OPTIONALS we may have variables.  It is
;;; an error to have both elements in the pair variables (although we
;;; can have a variable and a template.  We have the
;;; following cases:
;;; 1 - if the value is a variable there are no particular problems
;;; 2 - if the indicator is a variable, then the match is the FIRST
;;;     indicator in the plist that has a value mathing the value.
;;; This is not important for KEYS as the keys must be symbols in that
;;; case.

(defmethod unify ((a list) (b plist-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (declare (type environment env))
  (let ((template-lambda-list (sequence-template-lambda-list b))
        (rest-a ())
        (env1 env)
        (not-found-token (gensym "NOT-FOUND-")) ; Make it a global?
        )
    (declare (type environment env1)
             (type list template-lambda-list)
             )
    (multiple-value-bind (vars optionals keys rest)
        (parse-extended-ordinary-lambda-list template-lambda-list
                                             :ordinary-variable-test #'valid-template-p
                                             :optional-variable-test #'valid-template-p
                                             :key-variable-test #'valid-template-p
                                             :rest-variable-test #'valid-template-p
                                             )

      ;; The following ASSERTs must be moved in the
      ;; INITIALIZE-INSTANCE :AFTER of the plist-template.

      (assert (evenp (list-length vars)))
      (assert (evenp (list-length optionals)))
      (assert (evenp (list-length keys)))

      (flet ((unify-entry (indicator value plist env)
               ;; Assume FTTB that indicator is a correct 
               (let ((v (getf plist indicator not-found-token)))
                 (if (eq v not-found-token)
                     (error 'unification-failure
                            :format-control "Indicator ~S not found in plist."
                            :format-arguments (list indicator))
                     (unify value v env))))
             )

      
        (loop with env = env1
              for (indicator value) on vars by #'cddr
              when (and (symbolp indicator) ; Is it?  We can generalize!
                      )
              do (setf env (unify-entry indicator value a env))
              finally (setf env1 env))

        (loop with env = env1
              for (indicator value) on optionals by #'cddr
              when (and (symbolp indicator) ; Is it?  We can generalize!
                      )
              do (setf env (unify-entry indicator value a env))
              finally (setf env1 env))

        (if (null rest)
            (loop for i in a by #'cddr
                  unless (or (member i vars :test #'eq)
                             (member i optionals :test #'eq))
                  do (error 'unification-failure
                            :format-control "Indicator ~S not matched in plist."
                            :format-arguments (list i)))
            (loop for (i v) on a by #'cddr
                  unless (or (member i vars :test #'eq)
                             (member i optionals :test #'eq))
                  collect i into pairs
                  and collect v into pairs
                  finally (let ((rv (first rest)))
                            (unless (variable-any-p rv)
                              (extend-environment rv pairs env1)))
                  )
            )

        #|

        (loop for el-template in optionals
              for (el . els) on rest-a
              for env of-type environment = (unify el el-template env1)
              then (unify el el-template env)
              do (setf rest-a els
                       env1 env))


        (when rest
          (setf env1 (unify rest-a (first rest) env1)))

        (when keys (warn "Sorry matching of keywords ~S not yet implemented." keys))
        |#
        env1
        ))))
|#

#|| Simpler version, calling for a TABLE-TEMPLATE ||#

;;; A plist template requires a different kind of template lambda
;;; list, as the match is not done in order. Therefore we must define
;;; a  <destructuring table lambda list> (DTLL) as follows.
;;; 
;;; <DTLL> ::= '(' <kv-pairs> <opt-kv-pair> <rest-kv-var> ')'
;;;
;;; <kv-pairs>    ::= (<key> <value>)*
;;;
;;; <opt-kv-var>  ::= [ &optional (<key> <value>)+ ]
;;;
;;; <rest-kv-var> ::= [ &rest <template> ]
;;;
;;; <key>   ::= <template>
;;;
;;; <value> ::= <template>
;;;
;;; In the above <key> and <value> appearing in pair cannot both be
;;; templates.  The <template> in <rest-kv-var> must be a
;;; LIST-TEMPLATE or another PLIST-TEMPLATE
;;;
;;; As a result of PARSE-EXTENDED-ORDINARY-LAMBDA-LIST the four values
;;; returned, VARS, OPTIONALS, KEYS and REST are interpreted as
;;; follows.  Not that a decision is made w.r.t. plists that are
;;; "bigger" than the specs in the DTLL.
;;;
;;; VARS must be a plist: all pairs must be present and match in the
;;;      plist A
;;; OPTIONALS must be a plist: all pairs may be present and match in
;;;      the plist A
;;; REST if present must be a unification variable and it indicates
;;;      that the plist A may be bigger than what is expected by the
;;;      rest of the DTLL; otherwise it must be a LIST- or
;;;      PLIST-TEMPLATE, and unification proceeds recursively on the
;;;      unmatched K-V pairs.
;;; KEYS must be NULL
;;;
;;; Examples:
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 c 3 a 1)) ==> {}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 c ?C a 1)) ==> {C/3}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 a 1) ==> fail
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 a 1 &rest _) ==> {}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 a 1 &optional c 42) ==> {}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 a 1 &optional c 42) ==> {}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 &optional c 42) ==> fail
;;;         too few possible matches.
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 &optional c 42 &rest _) ==> {}
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 &rest ?more)) ==> {MORE/(a 1 c3}
;;;         original order maintained
;;;
;;; (unify '(a 1 b 2 c 3) #T(plist b 2 &optional c 42 &rest ?more) ==> {MORE/(a 1)}
;;;
;;; Next a twist. In VARS and OPTIONALS we may have variables.  It is
;;; an error to have both elements in the pair variables (although we
;;; can have a variable and a template.  We have the
;;; following cases:
;;; 1 - if the value is a variable there are no particular problems
;;; 2 - if the indicator is a variable, then the match is the FIRST
;;;     indicator in the plist that has a value mathing the value.

(defmethod unify ((a list) (b plist-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (declare (type environment env))
  (let ((template-lambda-list (sequence-template-lambda-list b))
        (rest-a ())
        (env1 env)
        (not-found-token (gensym "NOT-FOUND-")) ; Make it a global?
        )
    (declare (type environment env1)
             (type list template-lambda-list)
             )
    (multiple-value-bind (vars optionals keys rest)
        (parse-extended-ordinary-lambda-list template-lambda-list
                                             :ordinary-variable-test #'valid-template-p
                                             :optional-variable-test #'valid-template-p
                                             :key-variable-test #'valid-template-p
                                             :rest-variable-test #'valid-template-p
                                             )

      ;; The following ASSERTs must be moved in the
      ;; INITIALIZE-INSTANCE :AFTER of the plist-template.

      (assert (evenp (list-length vars)))
      (assert (evenp (list-length optionals)))
      (assert (evenp (list-length keys)))

      (flet ((unify-entry (indicator value plist env)
               ;; Assume FTTB that indicator is a correct 
               (let ((v (getf plist indicator not-found-token)))
                 (if (eq v not-found-token)
                     (error 'unification-failure
                            :format-control "Indicator ~S not found in plist."
                            :format-arguments (list indicator))
                     (unify value v env))))
             (unify-entry-no-error (indicator value plist env)
               ;; Assume FTTB that indicator is a correct 
               (let ((v (getf plist indicator not-found-token)))
                 (unless (eq v not-found-token)
                   (unify value v env))))
             )

      
        (loop with env = env1
              for (indicator value) on vars by #'cddr
              when (and (symbolp indicator) ; Is it?  We can generalize!
                      )
              do (setf env (unify-entry indicator value a env))
              finally (setf env1 env))

        (loop with env = env1
              for (indicator value) on optionals by #'cddr
              when (and (symbolp indicator) ; Is it?  We can generalize!
                      )
              do (let ((new-env (unify-entry-no-error indicator value a env)))
                   (when new-env
                     (setf env new-env)))
              finally (setf env1 env))

        (cond ((null rest)
               (loop for i in a by #'cddr
                     unless (or (member i vars :test #'eq)
                                (member i optionals :test #'eq))
                     do (error 'unification-failure
                               :format-control "Indicator ~S not matched in plist."
                               :format-arguments (list i))))
              ((variable-any-p (first rest)) #| NO-OP |#)
              ((variablep (first rest))
               (loop for (i v) on a by #'cddr
                     unless (or (member i vars :test #'eq)
                                (member i optionals :test #'eq))
                     collect i into pairs
                     and collect v into pairs
                     finally (extend-environment (first rest) pairs env1)
                     )
               )
              )

        #|

        (loop for el-template in optionals
              for (el . els) on rest-a
              for env of-type environment = (unify el el-template env1)
              then (unify el el-template env)
              do (setf rest-a els
                       env1 env))


        (when rest
          (setf env1 (unify rest-a (first rest) env1)))

        (when keys (warn "Sorry matching of keywords ~S not yet implemented." keys))
        |#
        env1
        ))))



;;;---------------------------------------------------------------------------
;;; Vector template methods.

(defmethod unify ((a vector) (b template)
                  &optional (env)
                  &key &allow-other-keys)
  (declare (ignore env))
  (error 'unification-failure
         :format-control "Cannot unify a vector with a non-vector template: ~S ~S."
         :format-arguments (list a b)))


(defmethod unify ((a vector) (b sequence-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (let ((template-lambda-list (sequence-template-lambda-list b))
        (vl (length a))
        )
    (multiple-value-bind (vars optionals keys rest)
        (parse-extended-ordinary-lambda-list template-lambda-list
                                             :ordinary-variable-test #'valid-template-p
                                             :optional-variable-test #'valid-template-p
                                             :key-variable-test #'valid-template-p
                                             :rest-variable-test #'valid-template-p
                                             )

      (let ((n-vars (list-length vars))
            (n-optionals (list-length optionals))
            )
        (loop for v in vars
              for e across (subseq a 0 (list-length vars))
              for mgu = (unify v e env) then (unify v e mgu)
              finally (setf env mgu))
        (when (and optionals (>= vl (+ n-vars n-optionals)))
          (loop for v in optionals
                for e across (subseq a n-vars (+ n-vars n-optionals))
                for mgu = (unify v e env) then (unify v e mgu)
                finally (setf env mgu)))
        (when (and rest (>= vl (+ n-vars n-optionals)))
          (setf env (unify (subseq a (+ n-vars n-optionals)) (first rest) env)))
        (when keys (warn "Sorry matching of keywords ~S not yet implemented." keys))
        env
        ))))


(defmethod unify ((b template) (a vector)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


;;;---------------------------------------------------------------------------
;;; Array template methods.

(defmethod unify ((a array) (b template)
                  &optional (env)
                  &key &allow-other-keys)
  (declare (ignore env))
  (error 'unification-failure
         :format-control "Cannot unify an array with a non array ~
                          or non array access template: ~S and ~S."
         :format-arguments (list a b)))

(defmethod unify ((b template) (a array)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


(defun unify-array-row (array dims shape-template indexes env)
  (cond ((null dims) env)
        ((= (list-length dims) 1)
         ;; Unify the row with the shape-template.
         (let ((row (make-array (first dims)
                               :displaced-to array
                               :displaced-index-offset
                               (apply #'array-row-major-index
                                      array
                                      (append indexes (list 0))))))
           (declare (dynamic-extent row)
                    (type array row))
           (untyped-unify row shape-template env)))
        (t
         (loop for i from 0 below (first dims)
               for row-template in shape-template
               do (unify-array-row array
                                   (rest dims)
                                   row-template
                                   (append indexes (list i))
                                   env)
               finally (return env)))
        ))


(defun unify-array-rows (array shape-template env)
  (unify-array-row array (array-dimensions array) shape-template () env))


(defmethod unify ((a array) (b array-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (let ((template-spec (template-spec b)))
    (if (= 2 (length template-spec))

        ;; Template is (<array type specifier> <shape-template>)
        (destructuring-bind (array-type-spec shape-template)
            template-spec
          (declare (ignore array-type-spec))
          ;; Missing check for type-spec.
          (unify-array-rows a shape-template env))

        ;; Template is (array (['*' | <element type>] [<dimension spec>]) <shape template>)
        (destructuring-bind (array-kwd type-spec shape-template)
            template-spec
          (declare (ignore array-kwd type-spec))
          ;; Missing check for type-spec.
          (unify-array-rows a shape-template env))
        )))



;;;---------------------------------------------------------------------------
;;; Standard object template methods.

(defmethod unify ((a standard-object) (b template)
                  &optional (env)
                  &key &allow-other-keys)
  (declare (ignore env))
  (error 'unification-failure
         :format-control "Cannot unify a standard object with a ~
                          non standard object template: ~S and ~S."
         :format-arguments (list a b)))

#|| Old version with heavy syntax
(defmethod unify ((a standard-object) (b standard-object-template)
                  &optional (env (make-empty-environment)))
  (destructuring-bind (class &rest template-slot-specs)
      (template-spec b)
    (unless (typep a class)
      (error 'unification-failure
             :format-control "Cannot unify an instance of ~S with a template for class ~S."
             :format-arguments (list (class-of a) class)))
    (flet ((slot-spec-unify (accessor-spec reader value-template mgu)
             (ecase accessor-spec
               (slot-value
                (unify (slot-value a reader) value-template mgu))
               (slot-accessor
                (unify (funcall reader a) value-template mgu))))
           )
      (if template-slot-specs
          (loop for (accessor-spec reader value-template) in template-slot-specs
                for mgu = (slot-spec-unify accessor-spec reader value-template env)
                then (slot-spec-unify accessor-spec reader value-template mgu)
                finally (return mgu))
          env))))
||#


(defmethod unify ((a standard-object) (b standard-object-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (destructuring-bind (class &rest template-slot-specs)
      (template-spec b)
    (unless (typep a class)
      (error 'unification-failure
             :format-control "Cannot unify an instance of ~S with a template for class ~S."
             :format-arguments (list (class-of a) class)))
    (flet ((slot-spec-unify (reader value-template mgu)
             (etypecase reader
               (list
                (assert (eq (first reader) 'slot-value))
                (unify (slot-value a (second reader)) value-template mgu))
               ((or function symbol)
                (unify (funcall reader a) value-template mgu))))
           )
      (if template-slot-specs
          (loop for (reader value-template) on template-slot-specs by #'cddr
                for mgu = (slot-spec-unify reader value-template env)
                then (slot-spec-unify reader value-template mgu)
                finally (return mgu))
          env))))


(defmethod unify ((b template) (a standard-object)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


;;;---------------------------------------------------------------------------
;;; Structure object template methods.

(defmethod unify ((a structure-object) (b template)
                  &optional (env)
                  &key &allow-other-keys)
  (declare (ignore env))
  (error 'unification-failure
         :format-control "Cannot unify a structure object with ~
                          a non structure object template: ~S and ~S."
         :format-arguments (list a b)))


(defmethod unify ((a structure-object) (b structure-object-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (destructuring-bind (class &rest template-slot-specs)
      (template-spec b)
    (unless (typep a class)
      (error 'unification-failure
             :format-control "Cannot unify an instance of ~S with a ~
                              template for structure ~S."
             :format-arguments (list (class-of a) class)))
    (if template-slot-specs
        (loop for (reader value-template) on template-slot-specs by #'cddr
              for mgu = (unify (funcall reader a) value-template env)
              then (unify (funcall reader a) value-template mgu)
              finally (return mgu))
        env)))


(defmethod unify ((b template) (a structure-object)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


;;;---------------------------------------------------------------------------
;;; Expression template SUBSEQ methods.

;;; SEQUENCE
;;; For non LIST and non VECTOR possible SEQUENCE types.

(defmethod unify ((a sequence) (b subseq-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (destructuring-bind (subseq-kwd from to &rest spec)
      (template-spec b)
    (declare (ignore subseq-kwd))
    (let* ((seq-type (type-of a))
           (seq-template-kind (if (symbolp seq-type)
                                  seq-type
                                  (first seq-type))) ; Stupid FTTB.
           )
      (unify (subseq a from to)
             (make-template seq-template-kind `(,seq-template-kind ,@spec))
             env))))


;;; LIST

(defmethod unify ((a list) (b subseq-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (destructuring-bind (subseq-kwd from to &rest spec)
      (template-spec b)
    (declare (ignore subseq-kwd))
    (unify (subseq a from to)
	   (make-template 'list `(list ,@spec))
	   env)))


;;; VECTOR

(defmethod unify ((a vector) (b subseq-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (destructuring-bind (subseq-kwd from to &rest spec)
      (template-spec b)
    (declare (ignore subseq-kwd))
    (let ((seq-type (type-of a)))
      (unify (subseq a from to)
             (make-template seq-type `(,seq-type ,@spec))
             env))))


(defmethod unify ((b subseq-template) (a sequence)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


;;;---------------------------------------------------------------------------
;;; Expression templates

;;; AREF methods.

(defmethod unify ((a array) (b aref-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (destructuring-bind (aref-kwd indexes value-template)
      (template-spec b)
    (declare (ignore aref-kwd))
    ;; Missing check on index spec.
    (unless (consp indexes)
      (setf indexes (list indexes)))
    (unify (apply #'aref a indexes) value-template env)))


;;; Necessary due to standard method sorting.

(defmethod unify ((a vector) (b aref-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (destructuring-bind (aref-kwd indexes value-template)
      (template-spec b)
    (declare (ignore aref-kwd))
    ;; Missing check on index spec.
    (when (and (consp indexes) (> (length indexes) 1))
      (error 'unification-failure
             :format-control "Cannot unify a vector with an element ~
                              too many dimensions down~@
                              (AREF #(...)~{ ~S~})."
             :format-arguments (list indexes)
             ))
    (unless (consp indexes)
      (setf indexes (list indexes)))
    (unify (apply #'aref a indexes) value-template env)))


(defmethod unify ((b aref-template) (a array)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


;;; ELT methods.
;;; LIST and VECTOR methods must be specified separatedly because of
;;; the UNIFY (VECTOR TEMPLATE) methods above.  It is a snag, but a
;;; relatively small one.  Besides, they are more efficient.
;;; The (SEQUENCE ELT-TEMPLATE) ELT-TEMPLATE method is left for those
;;; sequences which, according to the ANSI spec may exist and not be
;;; either VECTOR or LIST.

(defmethod unify ((a sequence) (b elt-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (destructuring-bind (elt-kwd index value-template)
      (template-spec b)
    (declare (ignore elt-kwd)
             (type fixnum index))
    ;; Missing index check.
    (unify (elt a index) value-template env)))


(defmethod unify ((a vector) (b elt-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (destructuring-bind (elt-kwd index value-template)
      (template-spec b)
    (declare (ignore elt-kwd)
             (type fixnum index))
    ;; Missing index check.
    (unify (aref a index) value-template env)))


(defmethod unify ((a list) (b elt-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (destructuring-bind (elt-kwd index value-template)
      (template-spec b)
    (declare (ignore elt-kwd)
             (type fixnum index))
    ;; Missing index check.
    (unify (nth index a) value-template env)))


(defmethod unify ((b elt-template) (a sequence)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


;;; NTH methods.

(defmethod unify ((a list) (b nth-template)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (destructuring-bind (nth-kwd index value-template)
      (template-spec b)
    (declare (ignore nth-kwd))
    ;; Missing index check.
    (unify (nth index a) value-template env)))

(defmethod unify ((b nth-template) (a list)
                  &optional (env (make-empty-environment))
                  &key &allow-other-keys)
  (unify a b env))


;;;---------------------------------------------------------------------------
;;; Utilities.

(defun unify* (a b &optional (env (make-empty-environment)))
  (ignore-errors (unify a b env)))


(defun unify-equations (eqns &optional (env (make-empty-environment)))
  (loop for (a b) in eqns
        for result-env = (unify a b env) then (unify a b result-env)
        finally (return result-env)))


(defun unify-equations* (lhss rhss &optional (env (make-empty-environment)))
  (loop for a in lhss
        for b in rhss
        for result-env = (unify a b env) then (unify a b result-env)
        finally (return result-env)))


;;;---------------------------------------------------------------------------
;;; VAR-UNIFY

(defparameter *occurrence-check-p* t)

(defgeneric occurs-in-p (var pat env))


#+old-version-no-paip
(defun var-unify (var pat env)
  (if (eq var pat)
      env
      (multiple-value-bind (value foundp)
          (find-variable-value var env)
        (cond (foundp
               (unify value pat env))
              ((and *occurrence-check-p*
                    (occurs-in-p var pat env))
               (error 'unification-failure
                      :format-control "Variable ~S occurs in ~S."
                      :format-arguments (list var pat)))
              (t
               (extend-environment var pat env))))))


;;; Version with PAIP test.

1307 1308 1309 1310 1311
;;; Bug found by Masayuki Takagi.
;;; Occur-check may happen also when the first (UNIFY VALUE PAT ENV)
;;; succeds.

#+pre-masayuki-spotting
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
(defun var-unify (var pat env)
  (if (eq var pat)
      env
      (multiple-value-bind (value foundp)
          (find-variable-value var env)

        (cond (foundp
               (unify value pat env))
              ((variablep pat)
               (multiple-value-bind (pat-value foundp)
                   (find-variable-value pat env)
                 (if foundp
                     (return-from var-unify
                       (unify var pat-value env)))
                 )))

        (cond ((and *occurrence-check-p*
                    (occurs-in-p var pat env))
               (error 'unification-failure
                      :format-control "Variable ~S occurs in ~S."
                      :format-arguments (list var pat)))
              (t
               (extend-environment var pat env))))))


1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
(defun var-unify (var pat env)
  (declare (type symbol var) ; Really (satisfies variablep).
           (type environment env))

  ;; Case 0: VAR and PAT are the same.

  (when (eq var pat)
    (return-from var-unify env))

  ;; Case 1: VAR is a variable and it is bound in ENV.

  (let ((vb (find-variable-binding var env)))
    (when vb
      (return-from var-unify (unify (binding-value vb) pat env))))

  ;; Case 2: VAR is a variable, but it is NOT bound in ENV and PAT is
  ;; a variable.

  (when (variablep pat)
    (let ((pb (find-variable-binding pat env)))
      (when pb
        (return-from var-unify (unify var (binding-value pb) env)))))

  ;; Case 3: VAR is a variable, but it is NOT bound in ENV and PAT is
  ;; NOT a variable. Raise an error if doing the "occur check".

  (when (and *occurrence-check-p*
             (occurs-in-p var pat env))
    (error 'unification-failure
           :format-control "Variable ~S occurs in ~S."
           :format-arguments (list var pat)))
  
  ;; If we got here (no RETURN-FROM invoked), then let's extend the ENV.

  (extend-environment var pat env))

1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459

#||
(defmethod occurs-in-p ((var symbol) pat env)
  (cond ((variablep pat)
         (or (eq var pat)
             (multiple-value-bind (value foundp)
                 (find-variable-value pat env)
               (when foundp
                 (occurs-in-p var value env)))
             ))
        ((atom pat) nil)
        ((consp pat)
         (or (occurs-in-p var (first pat) env)
             (occurs-in-p var (rest pat) env)))
        (t
         (error "unimplemented"))))
||#


(defmethod occurs-in-p ((var symbol) (pat symbol) env)
  (when (variablep pat)
    (or (eq var pat)
        (multiple-value-bind (value foundp)
            (find-variable-value pat env)
          (when foundp
            (occurs-in-p var value env)))
        )))


(defmethod occurs-in-p ((var symbol) (pat list) env)
  (or (occurs-in-p var (first pat) env)
      (occurs-in-p var (rest pat) env)))


(defmethod occurs-in-p ((var symbol) (pat null) env)
  ;; This is needed because of different precedence rules among lisps
  ;; in COMPUTE-APPLICABLE-METHODS when NIL has to matched against
  ;; SYMBOL and LIST.

  ;; We know (assume) that VAR is not NIL.
  nil)


(defmethod occurs-in-p ((var symbol) (pat array) env)
  (loop for i from 0 below (array-total-size pat)
        thereis (occurs-in-p var (row-major-aref pat i) env)))


(defmethod occurs-in-p ((var symbol) (pat vector) env) ; This may be faster than the above.
  (some #'(lambda (x) (occurs-in-p var x env)) pat))


(defmethod occurs-in-p ((var symbol) (pat string) env) ; This is useless, but it's here for completeness.
  (declare (ignore env))
  nil)


(defmethod occurs-in-p ((var symbol) (pat number) env)
  (declare (ignore env))
  nil)


(defmethod occurs-in-p ((var symbol) (pat character) env)
  (declare (ignore env))
  nil)


(defmethod occurs-in-p ((var symbol) (pat template) env)
  (occurs-in-p var (template-spec pat) env))


(defmethod occurs-in-p ((var symbol) (pat t) env)
  (declare (ignore env))
  (warn "Occurrence test unimplemented for pattern ~S of type ~S in variable ~S;~@
         returning false."
        pat
        (type-of pat)
        var)
  nil)


(defmethod occurs-in-p ((var t) (pat t) env)
  (declare (ignore env))
  (error "Occurrence test called on a non symbol ~S. Major problem."
         var))

;;; end of file -- unifier.lisp --