id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
sequencelengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11,208 | newgeo5.lisp | lambdamikel_GenEd/src/geometry/newgeo5.lisp | ;;; -*- Mode: LISP; Syntax: Ansi-Common-Lisp; Package: GEOMETRY -*-
(in-package geometry)
(defconstant +big-int+ 10000)
(defparameter *tick-counter* 1)
(defparameter *hash-table* (make-hash-table))
;;;
;;; Topological Relations for Polygons.
;;;
;;;
;;; Konstruktoren
;;;
(defclass geom-thing ()
((tickval :initform 0 :accessor tickval :initarg :tickval)))
(defclass geom-line (geom-thing)
((p1 :initform nil :initarg :p1 :accessor p1)
(p2 :initform nil :initarg :p2 :accessor p2)))
(defclass geom-point (geom-thing)
((x :initform 0 :initarg :x :accessor x)
(y :initform 0 :initarg :y :accessor y)))
(defclass geom-polygon (geom-thing)
((point-arr :initform nil :initarg :point-arr :accessor point-arr) ; range: 1..n
(line-arr :initform nil :initarg :line-arr :accessor line-arr) ; range: 0..n/n-1
(closed :initform t :initarg :closed :accessor closed)))
;;;
;;; Basis-Funktionen
;;;
(defmethod ccw ((p0 geom-point) (p1 geom-point) (p2 geom-point))
"Quelle: Sedgewick"
(let* ((x0 (x p0))
(x1 (x p1))
(x2 (x p2))
(y0 (y p0))
(y1 (y p1))
(y2 (y p2))
(dx1 (- x1 x0))
(dy1 (- y1 y0))
(dx2 (- x2 x0))
(dy2 (- y2 y0)))
(cond ((> (* dx1 dy2) (* dy1 dx2)) 1)
((< (* dx1 dy2) (* dy1 dx2)) -1)
((or (< (* dx1 dx2) 0)
(< (* dy1 dy2) 0))
-1)
((< (+ (* dx1 dx1) (* dy1 dy1))
(+ (* dx2 dx2) (* dy2 dy2)))
1)
(t 0))))
;;;
;;; Hilfsfunktionen
;;;
(defun make-geom-polygon (point-list
&key (is-closed t)) ; Fehler: wenn &key (closed t) !
(let* ((poly
(make-instance 'geom-polygon :closed is-closed
:tickval (incf *tick-counter*))))
(setf
(point-arr poly)
(make-geom-point-arr point-list)
(line-arr poly)
(make-geom-line-arr
(point-arr poly) :closed is-closed))
poly))
(defun make-geom-point (x y)
(make-instance 'geom-point
:tickval (incf *tick-counter*)
:x x
:y y))
(defun make-geom-point-arr (liste)
(let ((arr (make-array (+ 2 (length liste))))
(i 1))
(dolist (elem liste)
(setf (aref arr i)
(make-geom-point (first elem)
(second elem)))
(incf i))
(setf (aref arr 0)
(aref arr (1- i)))
(setf (aref arr i)
(aref arr 1))
arr))
(defun make-geom-line (p1 p2)
(make-instance 'geom-line
:tickval (incf *tick-counter*)
:p1 p1
:p2 p2))
(defun make-geom-line-arr (point-arr
&key (closed t))
(let* ((dim (if closed
(- (first (array-dimensions point-arr)) 2)
(- (first (array-dimensions point-arr)) 3)))
(arr (make-array (list dim))))
(dotimes (i dim)
(setf (aref arr i)
(make-geom-line
(aref point-arr (+ i 1))
(aref point-arr (+ i 2)))))
arr))
;;;;
;;;;
;;;;
(defun high-index (arr)
(1- (first (array-dimensions arr))))
(defun calculate-bounding-box (arr)
(let* ((minx (x (aref arr 0)))
(miny (y (aref arr 0)))
(maxx minx)
(maxy miny))
(dotimes (i (1- (first (array-dimensions arr))))
(let* ((point (aref arr i))
(y (y point))
(x (x point)))
(cond ((< x minx) (setf minx x))
((> x maxx) (setf maxx x))
((< y miny) (setf miny y))
((> y maxy) (setf maxy y)))))
(values minx miny maxx maxy)))
(defun calculate-center (arr)
(multiple-value-bind (xf yf xt yt)
(calculate-bounding-box arr)
(values
(/ (+ xf xt) 2)
(/ (+ yf yt) 2))))
;;;
;;; Abstandsfunktionen
;;;
(defmethod parallelp ((thing1 geom-thing)
(thing2 geom-thing))
nil)
(defmethod parallelp ((line1 geom-line) (line2 geom-line))
(let ((dx1 (- (x (p1 line1)) (x (p2 line1))))
(dx2 (- (x (p1 line2)) (x (p2 line2))))
(dy1 (- (y (p1 line1)) (y (p2 line1))))
(dy2 (- (y (p1 line2)) (y (p2 line2)))))
(zerop (- (* dx1 dy2) (* dx2 dy1)))))
;;;
;;;
;;;
(defmethod distance-between ((point1 geom-point)
(point2 geom-point))
(let ((dx (- (x point1) (x point2)))
(dy (- (y point1) (y point2))))
(sqrt (+ (* dx dx) (* dy dy)))))
(defmethod distance-between ((line geom-line)
(point geom-point))
(distance-between point line))
(defmethod distance-between ((point geom-point)
(line geom-line))
(flet ((betw-0-and-1 (number)
(and (not (minusp number))
(<= number 1.0))))
(let* ((lp1 (p1 line))
(lp2 (p2 line))
(lx1 (x lp1))
(ly1 (y lp1))
(lx2 (x lp2))
(ly2 (y lp2))
(px (x point))
(py (y point))
(ax (- lx2 lx1))
(ay (- ly2 ly1))
(dx (- lx1 px))
(dy (- ly1 py))
(a2 (+ (* ax ax) (* ay ay)))
(scalar
(if (zerop a2)
+big-int+
(/ (+ (* ax (- dx))
(* ay (- dy)))
a2)))
(x (+ dx
(* scalar ax)))
(y (+ dy
(* scalar ay))))
(if (betw-0-and-1 scalar)
(sqrt (+ (* x x) (* y y)))
(min (distance-between point (p1 line))
(distance-between point (p2 line)))))))
(defmethod distance-between ((line1 geom-line)
(line2 geom-line))
(let* ((d1
(distance-between (p1 line1) line2))
(d2
(distance-between (p2 line1) line2))
(d3
(distance-between (p1 line2) line1))
(d4
(distance-between (p2 line2) line1)))
(min (min d1 d2 d3 d4))))
(defmethod distance-between ((poly1 geom-polygon)
(poly2 geom-polygon))
(let* (
(line-arr1 (line-arr poly1))
(line-arr2 (line-arr poly2))
(ind1 (high-index line-arr1))
(ind2 (high-index line-arr2)))
(loop for i from 0 to ind1 minimize
(loop for j from 0 to ind2 minimize
(distance-between
(aref line-arr1 i)
(aref line-arr2 j))))))
(defmethod distance-between ((line geom-line)
(poly geom-polygon))
(let (
(line-arr (line-arr poly)))
(loop for i from 0 to (high-index line-arr) minimize
(distance-between
(aref line-arr i)
line))))
(defmethod distance-between ((poly geom-polygon)
(line geom-line))
(distance-between line poly))
(defmethod distance-between ((poly geom-polygon)
(point geom-point))
(let (
(line-arr (line-arr poly)))
(loop for i from 0 to (high-index line-arr) minimize
(distance-between point
(aref line-arr i)))))
(defmethod distance-between ((point geom-point)
(poly geom-polygon))
(distance-between poly point))
;;;
;;;
;;;
(defmethod inside-s ((point1 geom-point) (point2 geom-point))
nil)
(defmethod inside-s ((point geom-point) (line geom-line))
nil)
(defmethod inside-s ((line geom-line) (point geom-point))
nil)
(defmethod inside-s ((line1 geom-line) (line2 geom-line))
nil)
(defmethod inside-s ((polygon geom-polygon) (point geom-point))
nil)
(defmethod inside-s ((polygon geom-polygon) (line geom-line))
nil)
(defmethod inside-s ((point geom-point) (polygon geom-polygon))
"Nicht ganz korrekt !!! Quelle: Sedgewick, modifiziert!"
(when (closed polygon)
(let* ((count1 0)
(count2 0)
(j 0)
(arr (point-arr polygon))
(n (- (first (array-dimensions arr)) 2))
(x (x point))
(y (y point))
(lp (make-geom-line
(make-geom-point 0 0)
(make-geom-point 0 0)))
(lt (make-geom-line
(make-geom-point x y)
(make-geom-point +big-int+ y)))) ; wegen ALIAS-Effekten!
(dotimes (m n)
(let ((i (1+ m)))
(setf (p1 lp) (aref arr i))
(when (and
(not (and (= (y (p1 lp))
(y (p1 lt)))
(>= (x (p1 lp))
(x (p1 lt)))))
(not (and (= (y (aref arr j))
(y (p1 lt)))
(>= (x (aref arr j))
(x (p1 lt))))))
(setf (p2 lp) (aref arr j))
(setf j i)
(when (intersects-s lp lt)
(incf count1)))))
(let ((lt (make-geom-line
(make-geom-point x y)
(make-geom-point (- +big-int+) y)))) ; wegen ALIAS-Effekten!
(dotimes (m n)
(let ((i (1+ m)))
(setf (p1 lp) (aref arr i))
(when (and
(not (and (= (y (p1 lp))
(y (p1 lt)))
(<= (x (p1 lp))
(x (p1 lt)))))
(not (and (= (y (aref arr j))
(y (p1 lt)))
(<= (x (aref arr j))
(x (p1 lt))))))
(setf (p2 lp) (aref arr j))
(setf j i)
(when (intersects-s lp lt)
(incf count2)))))
(or (not (zerop (mod count1 2)))
(not (zerop (mod count2 2))))))))
(defmethod inside-s ((poly1 geom-polygon) (poly2 geom-polygon))
(when (closed poly2)
(let* ((arr (point-arr poly1))
(ok
(dotimes (i (- (first (array-dimensions arr)) 2))
(when (not (inside-s (aref arr (1+ i)) poly2))
(return t)))))
(not ok))))
(defmethod inside-s ((line geom-line) (poly geom-polygon))
(and (not (intersects-s line poly))
(inside-s (p1 line) poly)
(inside-s (p2 line) poly)))
;;;
;;;
;;;
(defmethod inside ((object1 geom-thing) (object2 geom-thing))
"Fuer Aussen-Benutzung"
(and (not (intersects-s object1 object2))
(inside-s object1 object2)))
;;;
;;;
;;;
(defmethod intersects-s ((point1 geom-point) (point2 geom-point))
(values nil nil))
(defmethod intersects-s ((point geom-point) (line geom-line))
(if
(or
(zerop (ccw (p1 line) (p2 line) point))
(zerop (ccw (p2 line) (p1 line) point)))
(values t 0)
(values nil nil)))
(defmethod intersects-s ((line geom-line) (point geom-point))
(intersects-s point line))
#|
(defmethod intersects-s ((l1 geom-line) (l2 geom-line))
"Quelle: Sedgewick"
(let ((l1p1 (p1 l1))
(l2p1 (p1 l2))
(l1p2 (p2 l1))
(l2p2 (p2 l2)))
(if
(and (<= (* (ccw l1p1 l1p2 l2p1)
(ccw l1p1 l1p2 l2p2))
0)
(<= (* (ccw l2p1 l2p2 l1p1)
(ccw l2p1 l2p2 l1p2))
0))
(if (parallelp l1 l2)
(values t 1)
(values t 0))
(values nil nil))))
|#
(defmethod intersects-s ((l1 geom-line) (l2 geom-line))
"Quelle: Sedgewick"
(let ((l1p1 (p1 l1))
(l2p1 (p1 l2))
(l1p2 (p2 l1))
(l2p2 (p2 l2)))
(let ((a1 (* (ccw l1p1 l1p2 l2p1)
(ccw l1p1 l1p2 l2p2)))
(a2 (* (ccw l2p1 l2p2 l1p1)
(ccw l2p1 l2p2 l1p2))))
(if
(and (<= a1
0)
(<= a2
0))
(if (and (parallelp l1 l2)
(not (or
(and
(same-point l1p1 l2p1)
(not (intersects-s l1 l2p2)))
(and
(same-point l1p1 l2p2)
(not (intersects-s l1 l2p1)))
(and
(same-point l1p2 l2p1)
(not (intersects-s l1 l2p2)))
(and
(same-point l1p2 l2p2)
(not (intersects-s l1 l2p1))))))
(values t 1)
(values t 0))
(values nil nil)))))
(defun same-point (p1 p2)
(and (= (x p1) (x p2))
(= (y p1) (y p2))))
(defmethod intersects-s ((line geom-line) (poly geom-polygon))
(let* ((larr (line-arr poly))
(max-dim
(loop for i from 0 to (1- (first (array-dimensions larr)))
maximize
(multiple-value-bind (intersectsp dim)
(intersects-s (aref larr i) line)
(if intersectsp
dim
-1)))))
(if (minusp max-dim)
(values nil nil)
(values t max-dim))))
(defmethod intersects-s ((poly geom-polygon) (line geom-line))
(intersects-s line poly))
(defmethod intersects-s ((poly1 geom-polygon) (poly2 geom-polygon))
(let* ((arr (line-arr poly1))
(parr (point-arr poly1))
(counter 0)
(max-dim
(loop for i from 0 to (1- (first (array-dimensions arr)))
maximize
(multiple-value-bind (intersectsp dim)
(intersects-s (aref arr i) poly2)
(if intersectsp
(progn
(incf counter)
dim)
-1)))))
(if (minusp max-dim)
(values nil nil)
(values t
(if (and (> counter 1)
(loop for i from 0 to (1- (first (array-dimensions parr)))
thereis
(inside (aref parr i) poly2)))
2
max-dim)))))
(defmethod intersects-s ((point geom-point) (poly geom-polygon))
(let* ((arr (line-arr poly))
(ok
(dotimes (i (first (array-dimensions arr)))
(if (intersects-s point (aref arr i))
(return t)))))
(if ok
(values t 0)
(values nil nil))))
(defmethod intersects-s ((poly geom-polygon) (point geom-point))
(intersects-s point poly))
;;;
;;;
(defmethod intersects ((thing1 geom-thing) (thing2 geom-thing))
(multiple-value-bind (ip1 dim1)
(intersects-s thing1 thing2)
(if (not ip1)
(values nil nil)
(multiple-value-bind (ip2 dim2)
(intersects-s thing2 thing1)
(values t (max dim1 dim2))))))
;;;
;;;
;;;
(defmethod disjoint ((poly1 geom-thing) (poly2 geom-thing))
"Fuer Aussen-Benutzung!"
(and
(not
(inside poly1 poly2))
(not
(inside poly2 poly1))))
;;;
;;;
;;;
(defmethod touching-tres ((thing1 geom-thing) (thing2 geom-thing) tres)
"Arbeitet mit dem minimalen Abstand. Fuer Aussen-Benutzung"
(and
(not (intersects-s thing1 thing2))
(let ((d (distance-between thing1 thing2)))
(if (<= d tres) d))))
;;;
;;;
;;;
(defmethod covers-tres ((thing1 geom-thing) (thing2 geom-thing) tres)
"Fuer Aussen-Benutzung"
(and (inside-s thing2 thing1)
(touching-tres thing2 thing1 tres)))
;;;
;;;
;;;
(defun distance-and-orientation (x1 y1 x2 y2)
(let* (
(dx (- x2 x1))
(dy (- y2 y1))
(d (sqrt (+ (* dx dx) (* dy dy))))
(phi (if (zerop dx)
(if (minusp dy)
(- (/ pi 2))
(/ pi 2))
(atan (/ dy dx))))
(phi2 (if (minusp dx)
(+ phi pi)
phi)))
(values d phi2)))
;;;
;;; Master-Function
;;;
(defun inverse (relation)
(case relation
(is-inside 'contains)
(is-covered-by 'covers)
(contains 'is-inside)
(covers 'is-covered-by)
(t relation)))
(defun delete-object-from-cache (thing object-liste)
(dolist (elem object-liste)
(let* ((goedel1 (get-goedel thing elem))
(goedel2 (get-goedel elem thing)))
(remhash goedel1 *hash-table*)
(remhash goedel2 *hash-table*))))
(defun get-goedel (x y)
(* (expt 2 (tickval x))
(expt 3 (tickval y))))
;;;
;;;
;;;
(defun relate-poly-to-poly-unary-tres (thing1 thing2 tres)
(let* ((goedel (get-goedel thing1 thing2))
(hash-rel (gethash goedel
*hash-table*)))
(if hash-rel
hash-rel
(let ((relation
(multiple-value-bind (intersectsp dim)
(intersects thing1 thing2)
(if intersectsp
(case dim
(0 'intersects-0)
(1 'intersects-1)
(2 'intersects-2))
(if (inside-s thing1 thing2)
(let ((d (distance-between thing1 thing2)))
(if (<= d tres)
'is-covered-by
'is-inside))
(if (inside-s thing2 thing1)
(let ((d (distance-between thing2 thing1)))
(if (<= d tres)
'covers
'contains))
(let ((d (distance-between thing1 thing2)))
(if (<= d tres)
'touches
'is-disjoint-with))))))))
(setf (gethash goedel
*hash-table*)
relation)
(setf (gethash (get-goedel thing2 thing1)
*hash-table*)
(inverse relation))
relation))))
| 15,010 | Common Lisp | .lisp | 535 | 22.697196 | 93 | 0.578316 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | c7f60c0345f96692cc99d3ff04a561b04ed91805ae52dfc64b45d0c53ec1f08c | 11,208 | [
-1
] |
11,209 | janus-geometry.lisp | lambdamikel_GenEd/src/geometry/janus-geometry.lisp | ;;;-*- Mode: Lisp; Package: PJ -*-
(in-package :pj)
;;;----------------------------------------------------------------------------
#+:allegro
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun make-point (h v)
(declare (type fixnum h v))
(if (and (<= (abs h) #x7fff) (<= (abs v) #x7fff))
(the fixnum (logior (ash v 16) (logand #xffff h)))
(error "make-point called with wrong arguments: h=~D, v=~D" h v)))
(defun point-h (point)
(if (logbitp 15 point)
(the fixnum (- (logand #x7fff point) #x8000))
(the fixnum (logand #x7fff point))))
(defun point-v (point)
(ash point -16))
(defun point-string (point)
(format nil "#@(~D ~D)" (point-h point) (point-v point)))
(defun subtract-points (point1 point2)
(make-point (- (point-h point1) (point-h point2))
(- (point-v point1) (point-v point2))))
(defun add-points (point1 point2)
(make-point (+ (point-h point1) (point-h point2))
(+ (point-v point1) (point-v point2))))
(defun |#@-reader| (stream char arg)
(declare (ignore char arg))
(let ((coords (read stream)))
(if (and (consp coords) (= (length coords) 2))
(make-point (first coords) (second coords))
(error "#@-macro used with wrong parameters: ~S" coords))))
(set-dispatch-macro-character #\# #\@ #'|#@-reader|)
)
;;;----------------------------------------------------------------------------
(defclass geometry-feature ()
())
(defgeneric feature= (feature1 feature2))
;;;----------------------------------------------------------------------------
(defclass area-feature (geometry-feature)
((position :accessor area-position :initarg :position)
(size :accessor area-size :initarg :size)))
(defmethod print-object ((area area-feature) stream)
(flet ((safe-p (x)
(if (numberp x)
(format nil "(~D,~D)" (point-h x) (point-v x))
x))
(safe-e (x)
(if (numberp x)
(format nil "~Dx~D" (point-h x) (point-v x))
x)))
(print-unreadable-object (area stream :identity t)
(format stream "Area ~A ~A"
(safe-p (area-position area)) (safe-e (area-size area))))))
(defun make-area (&key pos size topleft bottomright)
(cond
((and pos size) (make-instance 'area-feature :position pos :size size))
((and topleft bottomright)
(make-instance 'area-feature
:position topleft :size (subtract-points bottomright topleft)))
(t (error "Invalid parameter combination"))))
(defmethod feature= ((area1 area-feature) (area2 area-feature))
(and (= (area-position area1) (area-position area2))
(= (area-size area1) (area-size area2))))
(defmethod topleft ((area area-feature))
(area-position area))
(defmethod bottomright ((area area-feature))
(add-points (area-position area) (area-size area)))
(defmethod empty-area-p ((area area-feature))
(slet ((size (area-size area)))
(or (minusp (point-h size)) (minusp (point-v size)))))
(defmethod line-p ((area area-feature))
)
(defmethod dimension ((object area-feature))
2)
(defmethod interior ((area area-feature))
"The interior of an area is the area itself without its bounary."
(make-area :pos (add-points (area-position area) #@(1 1))
:size (subtract-points (area-size area) #@(2 2))))
(defmethod boundary ((area area-feature))
"The boundary of an area is the circular line consisting of all the
accumulation points of the area."
(slet ((tl (topleft area)) (br (bottomright area))
(width (make-point (point-h (area-size area)) 0)))
(make-line (list tl (add-points tl width) br
(subtract-points br width))
:circular t)))
(defmethod bounding-box ((area area-feature))
(values (topleft area) (bottomright area)))
;;;----------------------------------------------------------------------------
(defclass line-segment ()
((start-point :accessor start-point :initarg :start-point :initform nil)
(end-point :accessor end-point :initarg :end-point :initform nil)))
(defmethod print-object ((segment line-segment) stream)
(flet ((safe-p (x)
(if (numberp x)
(format nil "(~D,~D)" (point-h x) (point-v x))
x)))
(print-unreadable-object (segment stream :identity t)
(format stream "Segment ~A->~A"
(safe-p (start-point segment)) (safe-p (end-point segment))))))
(defun make-segment (start end)
(make-instance 'line-segment :start-point start :end-point end))
(defun make-segment-list (point-list circular)
(mapcon #'(lambda (l)
(when (second l)
(list (make-segment (first l) (second l)))))
(if circular
(append point-list (list (first point-list)))
point-list)))
(defmethod bounding-box ((segment line-segment))
(slet ((sp (start-point segment)) (ep (end-point segment)))
(values (make-point (min (point-h sp) (point-h ep))
(min (point-v sp) (point-v ep)))
(make-point (max (point-h sp) (point-h ep))
(max (point-v sp) (point-v ep))))))
(defmethod intersecting-p ((seg1 line-segment) (seg2 line-segment))
(and (multiple-value-call #'bb-intersecting-p
(bounding-box seg1)
(bounding-box seg2))
(or (true-crossing-p seg1 seg2)
(point-touching-p seg1 seg2)
(collinear-overlapping-p seg1 seg2))))
(defun cross-prod (p1 p2)
;(print (list (point-string p1) (point-string p2)))
(- (* (point-h p1) (point-v p2)) (* (point-h p2) (point-v p1))))
(declaim (inline cross-prod))
(defun true-crossing-p (seg1 seg2)
"Both segments are truly crossing each other."
(slet ((p1 (start-point seg1)) (p2 (end-point seg1))
(p3 (start-point seg2)) (p4 (end-point seg2)))
(and (straddle-p p1 p2 p3 p4) (straddle-p p3 p4 p1 p2))))
(defun collinear-overlapping-p (seg1 seg2)
"Both segments are collinear and overlapping each other."
(slet* ((p1 (start-point seg1)) (p2 (end-point seg1))
(p3 (start-point seg2)) (p4 (end-point seg2))
(tmp (subtract-points p2 p1)))
(and (zerop (cross-prod (subtract-points p3 p1) tmp))
(zerop (cross-prod (subtract-points p4 p1) tmp)))))
(defun point-touching-p (seg1 seg2)
"At least one start/end point of one segment is touching the other one."
(slet ((p1 (start-point seg1)) (p2 (end-point seg1))
(p3 (start-point seg2)) (p4 (end-point seg2)))
(or (and (straddle-touch-p p1 p2 p3 p4) (straddle-or-touch-p p3 p4 p1 p2))
(and (straddle-touch-p p1 p2 p4 p3) (straddle-or-touch-p p4 p3 p1 p2))
(and (straddle-touch-p p4 p3 p1 p2) (straddle-or-touch-p p1 p2 p4 p3))
(and (straddle-touch-p p4 p3 p2 p1) (straddle-or-touch-p p2 p1 p4 p3)))
))
(defun straddle-p (p1 p2 p3 p4)
"A segment (p1 p2) straddles a line (p3 p4)
if point p1 lies on one side of the line and point p2 lies on the other side."
(slet ((tmp (subtract-points p2 p1)))
(minusp (* (signum (cross-prod (subtract-points p3 p1) tmp))
(signum (cross-prod (subtract-points p4 p1) tmp))))))
(defun almost-zero-p (value)
(zerop value))
; (< (abs value) 6))
(declaim (inline almost-zero-p))
(defun straddle-touch-p (p1 p2 p3 p4)
"A segment (p1 p2) straddles and touches a line (p3 p4)
if additionally one end point of the line lies on the segment."
; (print (list (point-string p1) (point-string p2)
; (point-string p3) (point-string p4)))
(slet ((tmp (subtract-points p2 p1)))
(and (not (almost-zero-p (cross-prod (subtract-points p3 p1) tmp)))
(almost-zero-p (cross-prod (subtract-points p4 p1) tmp)))))
(defun straddle-or-touch-p (p1 p2 p3 p4)
"Test whether s segment (p1 p2) straddles or touches a line (p3 p4)."
(or (straddle-p p1 p2 p3 p4) (straddle-touch-p p1 p2 p3 p4)))
;;;----------------------------------------------------------------------------
(defun bb-intersecting-p (tl1 br1 tl2 br2)
"Test whether two bounding boxes are intersecting."
(and (>= (max (point-h tl1) (point-h br1))
(min (point-h tl2) (point-h br2)))
(>= (max (point-h tl2) (point-h br2))
(min (point-h tl1) (point-h br1)))
(>= (max (point-v tl1) (point-v br1))
(min (point-v tl2) (point-v br2)))
(>= (max (point-v tl2) (point-v br2))
(min (point-v tl1) (point-v br1)))))
(defun bb-distance (tl1 br1 tl2 br2)
"Compute distance between two disjoint bounding boxes"
(list (bb-intersecting-p tl1 br1 tl2 br2)
(- (max (point-h tl1) (point-h br1))
(min (point-h tl2) (point-h br2)))
(- (max (point-h tl2) (point-h br2))
(min (point-h tl1) (point-h br1)))
(- (max (point-v tl1) (point-v br1))
(min (point-v tl2) (point-v br2)))
(- (max (point-v tl2) (point-v br2))
(min (point-v tl1) (point-v br1)))))
(defun bb-in-bb-p (tl1 br1 tl2 br2)
"Test whether bounding box (tl1 br1) is inside of bounding box (tl2 br2)."
(and (point-in-bb-p tl1 tl2 br2) (point-in-bb-p br1 tl2 br2)))
(defun point-in-bb-p (point topleft bottomright)
"Test whether point lies within this bounding box."
(and (<= (point-h topleft) (point-h point) (point-h bottomright))
(<= (point-v topleft) (point-v point) (point-v bottomright))))
(defun point-on-boundary-p (point topleft bottomright)
"Test whether point lies on the boundary of this bounding box."
;;;(print (mapcar #'point-string (list point topleft bottomright)))
(and (point-in-bb-p point topleft bottomright)
(or (= (point-h topleft) (point-h point))
(= (point-v topleft) (point-v point))
(= (point-h bottomright) (point-h point))
(= (point-v bottomright) (point-v point)))))
;;;----------------------------------------------------------------------------
(defclass line-feature (geometry-feature)
((segments :accessor line-segments :initarg :segments)
(circular :accessor circular-p :initarg :circular :initform nil)))
(defmethod print-object ((line line-feature) stream)
(flet ((safe-p (x) (if (numberp x)
(format nil "(~D,~D)" (point-h x) (point-v x))
x)))
(print-unreadable-object (line stream :identity t)
(format stream "Line:~D ~A->~A"
(when (slot-boundp line 'segments) (length (line-segments line)))
(safe-p (start-point line)) (safe-p (end-point line))))))
(defun make-line (point-list &key circular)
;(print (mapcar #'point-string point-list))
(let ((s-list (make-segment-list point-list circular)))
(make-instance 'line-feature
:segments (make-array (list (length s-list))
:element-type t
:initial-contents s-list)
:circular circular)))
(defmethod feature= ((line1 line-feature) (line2 line-feature))
(equalp (line-segments line1) (line-segments line1)))
(defmethod start-point ((line line-feature))
(start-point (svref (line-segments line) 0)))
(defmethod end-point ((line line-feature))
(slet ((segments (line-segments line)))
(end-point (svref segments (1- (length segments))))))
(defmethod (setf line-segments) :after (new-value (line line-feature))
(declare (ignore new-value))
(setf (circular-p line) (= (start-point line) (end-point line))))
(defmethod dimension ((line line-feature))
1)
(defmethod interior ((line line-feature))
"The interior of a line is equal to itself."
line)
(defmethod boundary ((line line-feature))
"The boundary of a line is an empty set in case of a circular line
otherwise is the set of start and end points."
(unless (circular-p line)
(make-point-set (list (start-point line) (end-point line)))))
(defmethod bounding-box ((line line-feature))
(slet ((segments (line-segments line)))
(if (= (length segments) 1)
(bounding-box (svref segments 0))
(error "Can't compute bounding box for multi-segment line ~S" line))))
;;;----------------------------------------------------------------------------
(defclass point-set ()
((elements :accessor elements :initarg :elements :initform nil)))
(defmethod print-object ((set point-set) stream)
(flet ((safe-p (x)
(if (numberp x)
(format nil "(~D,~D)" (point-h x) (point-v x))
x)))
(print-unreadable-object (set stream :identity t)
(format stream "Set:~D ~A"
(length (elements set)) (mapcar #'safe-p (elements set))))))
(defmethod start-point ((set point-set))
(first set))
(defmethod end-point ((set point-set))
(last set))
(defmethod empty ((set point-set))
(null (elements set)))
(defun make-point-set (elements)
(make-instance 'point-set :elements elements))
(defmethod dimension ((set point-set))
"The dimension of an intermediate set is the maximum of its elements."
(loop for elem in (elements set)
maximize (dimension elem)))
;;;----------------------------------------------------------------------------
(defmethod feature= ((point1 fixnum) (point2 fixnum))
(= point1 point2))
(defmethod dimension ((point fixnum))
0)
(defmethod interior ((point fixnum))
"The interior of a point is equal to itself."
point)
(defmethod boundary ((point fixnum))
"The boundary of a point is always empty."
nil)
(defmethod intersecting-p ((point fixnum) (seg line-segment))
(and (multiple-value-call #'point-in-bb-p point (bounding-box seg))
(collinear-overlapping-p (make-segment point (start-point seg)) seg)))
(defmethod intersecting-p ((seg line-segment) (point fixnum))
(intersecting-p point seg))
;;;----------------------------------------------------------------------------
(defmethod dim-of-intersect ((feature1 geometry-feature) (feature2 (eql nil)))
nil)
(defmethod dim-of-intersect ((feature1 (eql nil)) (feature2 geometry-feature))
nil)
(defmethod dim-of-intersect ((area1 area-feature) (area2 area-feature))
(slet* ((tl1 (topleft area1)) (br1 (bottomright area1))
(tl2 (topleft area2)) (br2 (bottomright area2))
(width (- (min (point-h br1) (point-h br2))
(max (point-h tl1) (point-h tl2))))
(height (- (min (point-v br1) (point-v br2))
(max (point-v tl1) (point-v tl2)))))
(cond ((or (minusp width) (minusp height)) nil) ;intersection is empty
((and (zerop width) (zerop height)) 0) ;point
((or (zerop width) (zerop height)) 1) ;line segment
(t 2))))
(defmethod dim-of-intersect ((area area-feature) (line line-feature))
(when (intersecting-p area line)
(slet ((sp-on (multiple-value-call #'point-on-boundary-p
(start-point line) (bounding-box area)))
(ep-on (multiple-value-call #'point-on-boundary-p
(end-point line) (bounding-box area))))
(if (and (or (and sp-on (not ep-on)) (and (not sp-on) ep-on))
(loop for seg across (line-segments line)
thereis (not (multiple-value-call #'bb-in-bb-p
(bounding-box seg)
(bounding-box area)))))
0
1))))
(defmethod dim-of-intersect ((line line-feature) (area area-feature))
(dim-of-intersect area line))
(defmethod dim-of-intersect ((line1 line-feature) (line2 line-feature))
(when (intersecting-p line1 line2)
(if (loop for seg1 across (line-segments line1)
thereis (loop for seg2 across (line-segments line2)
thereis (collinear-overlapping-p seg1 seg2)))
1
0)))
(defmethod dim-of-intersect ((line line-feature) (set point-set))
(loop for point in (elements set)
thereis (loop for line-seg across (line-segments line)
for seg = (make-segment (start-point line-seg) point)
when (and (multiple-value-call #'bb-in-bb-p
(bounding-box seg)
(bounding-box line-seg))
(collinear-overlapping-p seg line-seg))
return 0)))
(defmethod dim-of-intersect ((set point-set) (line line-feature))
(dim-of-intersect line set))
(defmethod dim-of-intersect ((set point-set) (feature (eql nil)))
nil)
(defmethod dim-of-intersect ((feature (eql nil)) (set point-set))
nil)
(defmethod dim-of-intersect ((feature geometry-feature) (point fixnum))
(when (intersecting-p point feature)
0))
(defmethod dim-of-intersect ((point fixnum) (feature geometry-feature))
(dim-of-intersect feature point))
(defmethod intersect ((area1 area-feature) (area2 area-feature))
(slet ((tl1 (topleft area1)) (br1 (bottomright area1))
(tl2 (topleft area2)) (br2 (bottomright area2)))
(make-area :topleft (make-point (max (point-h tl1) (point-h tl2))
(max (point-v tl1) (point-v tl2)))
:bottomright (make-point (min (point-h br1) (point-h br2))
(min (point-v br1) (point-v br2))))))
(defmethod intersecting-p ((area1 area-feature) (area2 area-feature))
(multiple-value-call #'bb-intersecting-p
(bounding-box area1) (bounding-box area2)))
(defmethod intersecting-p ((area area-feature) (line line-feature))
(or (multiple-value-call #'point-in-bb-p
(start-point line) (bounding-box area))
(multiple-value-call #'point-in-bb-p
(end-point line) (bounding-box area))
(intersecting-p (boundary area) line)))
(defmethod intersecting-p ((line line-feature) (area area-feature))
(intersecting-p area line))
(defmethod intersecting-p ((line1 line-feature) (line2 line-feature))
(loop for seg1 across (line-segments line1)
thereis (loop for seg2 across (line-segments line2)
thereis (intersecting-p seg1 seg2))))
(defmethod intersecting-p ((point fixnum) (area area-feature))
(multiple-value-call #'point-in-bb-p point (bounding-box area)))
(defmethod intersecting-p ((area area-feature) (point fixnum))
(intersecting-p point area))
(defmethod intersecting-p ((point fixnum) (line line-feature))
(loop for seg across (line-segments line)
thereis (intersecting-p point seg)))
(defmethod intersecting-p ((line line-feature) (point fixnum))
(intersecting-p point line))
(defmethod intersecting-p ((point1 fixnum) (point2 fixnum))
(= point1 point2))
| 18,623 | Common Lisp | .lisp | 379 | 42.079156 | 79 | 0.604169 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 65aacd548300f9aa7bf4b362c3b9ee8bd8734bc0f2aea1a08e0310a3bc1e3bf1 | 11,209 | [
-1
] |
11,210 | defpackage.lisp | lambdamikel_GenEd/src/geometry/defpackage.lisp | (defpackage :geometry
(:export
make-geom-polygon
make-geom-point
make-geom-line
intersects
distance-between
inside
intersects
covers
covers-tres
touching
touching-tres
distance-and-orientation
delete-object-from-cache
relate-poly-to-poly-unary-tres
relate-poly-to-poly-binary-tres))
| 331 | Common Lisp | .lisp | 17 | 15.647059 | 36 | 0.748408 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 758d610b04a97129fe8ad068ea8493f38c2829293c7bcc80bee33595fbb2efde | 11,210 | [
-1
] |
11,211 | newgeo2.lisp | lambdamikel_GenEd/src/geometry/newgeo2.lisp | ;;; -*- Mode: LISP; Syntax: Ansi-Common-Lisp; Package: GEOMETRY -*-
(in-package geometry)
(defconstant +big-int+ 10000)
(defparameter *tick-counter* 1)
(defparameter *hash-table* (make-hash-table))
;;;
;;; Topological Relations for Polygons.
;;;
;;;
;;; Konstruktoren
;;;
(defclass geom-thing ()
((tickval :initform 0 :accessor tickval :initarg :tickval)))
(defclass geom-line (geom-thing)
((p1 :initform nil :initarg :p1 :accessor p1)
(p2 :initform nil :initarg :p2 :accessor p2)))
(defclass geom-point (geom-thing)
((x :initform 0 :initarg :x :accessor x)
(y :initform 0 :initarg :y :accessor y)))
(defclass geom-polygon (geom-thing)
((point-arr :initform nil :initarg :point-arr :accessor point-arr) ; range: 1..n
(line-arr :initform nil :initarg :line-arr :accessor line-arr) ; range: 0..n/n-1
(closed :initform t :initarg :closed :accessor closed)))
;;;
;;; Basis-Funktionen
;;;
(defmethod ccw ((p0 geom-point) (p1 geom-point) (p2 geom-point))
"Quelle: Sedgewick"
(let* ((x0 (x p0))
(x1 (x p1))
(x2 (x p2))
(y0 (y p0))
(y1 (y p1))
(y2 (y p2))
(dx1 (- x1 x0))
(dy1 (- y1 y0))
(dx2 (- x2 x0))
(dy2 (- y2 y0)))
(cond ((> (* dx1 dy2) (* dy1 dx2)) 1)
((< (* dx1 dy2) (* dy1 dx2)) -1)
((or (< (* dx1 dx2) 0)
(< (* dy1 dy2) 0))
-1)
((< (+ (* dx1 dx1) (* dy1 dy1))
(+ (* dx2 dx2) (* dy2 dy2)))
1)
(t 0))))
(defmethod intersects ((l1 geom-line) (l2 geom-line))
"Quelle: Sedgewick"
(let ((l1p1 (p1 l1))
(l2p1 (p1 l2))
(l1p2 (p2 l1))
(l2p2 (p2 l2)))
(and (<= (* (ccw l1p1 l1p2 l2p1)
(ccw l1p1 l1p2 l2p2))
0)
(<= (* (ccw l2p1 l2p2 l1p1)
(ccw l2p1 l2p2 l1p2))
0))))
;;;
;;; Hilfsfunktionen
;;;
(defun make-geom-polygon (point-list
&key (is-closed t)) ; Fehler: wenn &key (closed t) !
(let* ((poly
(make-instance 'geom-polygon :closed is-closed
:tickval (incf *tick-counter*))))
(setf
(point-arr poly)
(make-geom-point-arr point-list)
(line-arr poly)
(make-geom-line-arr
(point-arr poly) :closed is-closed))
poly))
(defun make-geom-point (x y)
(make-instance 'geom-point
:x x
:y y))
(defun make-geom-point-arr (liste)
(let ((arr (make-array (+ 2 (length liste))))
(i 1))
(dolist (elem liste)
(setf (aref arr i)
(make-geom-point (first elem)
(second elem)))
(incf i))
(setf (aref arr 0)
(aref arr (1- i)))
(setf (aref arr i)
(aref arr 1))
arr))
(defun make-geom-line (p1 p2)
(make-instance 'geom-line
:p1 p1
:p2 p2)) ; Referenzen auf tats. Punkte, keine Kopien!!!
(defun make-geom-line-arr (point-arr
&key (closed t))
(let* ((dim (if closed
(- (first (array-dimensions point-arr)) 2)
(- (first (array-dimensions point-arr)) 3)))
(arr (make-array (list dim))))
(dotimes (i dim)
(setf (aref arr i)
(make-geom-line
(aref point-arr (+ i 1))
(aref point-arr (+ i 2)))))
arr))
;;;;
;;;;
;;;;
(defun calculate-bounding-box (arr)
(let* ((minx (x (aref arr 0)))
(miny (y (aref arr 0)))
(maxx minx)
(maxy miny))
(dotimes (i (1- (first (array-dimensions arr))))
(let* ((point (aref arr i))
(y (y point))
(x (x point)))
(cond ((< x minx) (setf minx x))
((> x maxx) (setf maxx x))
((< y miny) (setf miny y))
((> y maxy) (setf maxy y)))))
(values minx miny maxx maxy)))
(defun calculate-center (arr)
(multiple-value-bind (xf yf xt yt)
(calculate-bounding-box arr)
(values
(/ (+ xf xt) 2)
(/ (+ yf yt) 2))))
;;;
;;; Abstandsfunktionen
;;;
(defmethod distance-between ((point1 geom-point)
(point2 geom-point))
(let ((dx (- (x point1) (x point2)))
(dy (- (y point1) (y point2))))
(sqrt (+ (* dx dx) (* dy dy)))))
(defmethod distance-between ((line geom-line)
(point geom-point))
(distance-between point line))
(defmethod distance-between ((point geom-point)
(line geom-line))
(let* ((lp1 (p1 line))
(lp2 (p2 line))
(lx1 (x lp1))
(ly1 (y lp1))
(lx2 (x lp2))
(ly2 (y lp2))
(px (x point))
(py (y point))
(ax (- lx2 lx1))
(ay (- ly2 ly1))
(dx (- lx1 px))
(dy (- ly1 py))
(a2 (+ (* ax ax) (* ay ay)))
(scalar (/ (+ (* ax (- dx))
(* ay (- dy)))
a2))
(x (+ dx
(* scalar ax)))
(y (+ dy
(* scalar ay))))
(values
(sqrt (+ (* x x) (* y y)))
scalar
x y)))
(defmethod distance-between ((line1 geom-line)
(line2 geom-line))
(flet ((betw-0-and-1 (number)
(and (not (minusp number))
(<= number 1.0))))
(multiple-value-bind (d1 s1 x1 y1)
(distance-between (p1 line1) line2)
(multiple-value-bind (d2 s2 x2 y2)
(distance-between (p2 line1) line2)
(multiple-value-bind (d3 s3 x3 y3)
(distance-between (p1 line2) line1)
(multiple-value-bind (d4 s4 x4 y4)
(distance-between (p2 line2) line1)
(let* ((big-int 10000)
(min (min
(if (betw-0-and-1 s1) d1 big-int)
(if (betw-0-and-1 s2) d2 big-int)
(if (betw-0-and-1 s3) d3 big-int)
(if (betw-0-and-1 s4) d4 big-int))))
(cond
((= min d1) (values d1 x1 y1))
((= min d2) (values d2 x2 y2))
((= min d3) (values d3 x3 y3))
((= min d4) (values d4 x4 y4))
(t (let* ((dx1 (- (x (p1 line1)) (x (p1 line2))))
(dx2 (- (x (p2 line1)) (x (p1 line2))))
(dx3 (- (x (p1 line1)) (x (p2 line2))))
(dx4 (- (x (p2 line1)) (x (p2 line2))))
(dy1 (- (y (p1 line1)) (y (p1 line2))))
(dy2 (- (y (p2 line1)) (y (p1 line2))))
(dy3 (- (y (p1 line1)) (y (p2 line2))))
(dy4 (- (y (p2 line1)) (y (p2 line2))))
(d1 (sqrt (+ (* dx1 dx1) (* dy1 dy1))))
(d2 (sqrt (+ (* dx2 dx2) (* dy2 dy2))))
(d3 (sqrt (+ (* dx3 dx3) (* dy3 dy3))))
(d4 (sqrt (+ (* dx4 dx4) (* dy4 dy4)))))
(values (min d1 d2 d3 d4) 0 0)))))))))))
(defmethod distance-between ((poly1 geom-polygon)
(poly2 geom-polygon))
(let ((min +big-int+)
(line-arr1 (line-arr poly1))
(line-arr2 (line-arr poly2)))
(dotimes (i (first (array-dimensions line-arr1)))
(dotimes (j (first (array-dimensions line-arr2)))
(let ((d (distance-between
(aref line-arr1 i)
(aref line-arr2 j))))
(when (< d min)
(setf min d)))))
min))
(defmethod distance-between ((line geom-line)
(poly geom-polygon))
(let ((min +big-int+)
(line-arr (line-arr poly)))
(dotimes (i (first (array-dimensions line-arr)))
(let ((d
(distance-between
(aref line-arr i)
line)))
(when (< d min)
(setf min d)
)))
min))
(defmethod distance-between ((poly geom-polygon)
(line geom-line))
(distance-between line poly))
(defmethod distance-between ((poly geom-polygon)
(point geom-point))
(let ((min +big-int+)
(line-arr (line-arr poly)))
(flet ((betw-0-and-1 (number)
(and (not (minusp number))
(<= number 1.0))))
(dotimes (i (first (array-dimensions line-arr)))
(flet ((betw-0-and-1 (number)
(and (not (minusp number))
(<= number 1.0))))
(multiple-value-bind (d s x y)
(distance-between point
(aref line-arr i))
(let ((nd
(if (betw-0-and-1 s)
d
(min (distance-between
point
(p1 (aref line-arr i)))
(distance-between
point
(p2 (aref line-arr i)))))))
(if (< nd min)
(setf min nd)))))))
min))
(defmethod distance-between ((point geom-point)
(poly geom-polygon))
(distance-between poly point))
;;;
;;; Relationen!
;;;
(defmethod inside ((point1 geom-point) (point2 geom-point))
nil)
(defmethod inside ((point geom-point) (line geom-line))
nil)
(defmethod inside ((line geom-line) (point geom-point))
nil)
(defmethod inside ((line1 geom-line) (line2 geom-line))
nil)
(defmethod inside ((polygon geom-polygon) (point geom-point))
nil)
(defmethod inside ((polygon geom-polygon) (line geom-line))
nil)
(defmethod inside ((point geom-point) (polygon geom-polygon))
"Nicht ganz korrekt !!! Quelle: Sedgewick, modifiziert!"
(when (closed polygon)
(let* ((count1 0)
(count2 0)
(j 0)
(arr (point-arr polygon))
(n (- (first (array-dimensions arr)) 2))
(x (x point))
(y (y point))
(lp (make-geom-line
(make-geom-point 0 0)
(make-geom-point 0 0)))
(lt (make-geom-line
(make-geom-point x y)
(make-geom-point +big-int+ y)))) ; wegen ALIAS-Effekten!
(dotimes (m n)
(let ((i (1+ m)))
(setf (p1 lp) (aref arr i))
(when (and
(not (and (= (y (p1 lp))
(y (p1 lt)))
(>= (x (p1 lp))
(x (p1 lt)))))
(not (and (= (y (aref arr j))
(y (p1 lt)))
(>= (x (aref arr j))
(x (p1 lt))))))
(setf (p2 lp) (aref arr j))
(setf j i)
(when (intersects lp lt)
(incf count1)))))
(let ((lt (make-geom-line
(make-geom-point x y)
(make-geom-point (- +big-int+) y)))) ; wegen ALIAS-Effekten!
(dotimes (m n)
(let ((i (1+ m)))
(setf (p1 lp) (aref arr i))
(when (and
(not (and (= (y (p1 lp))
(y (p1 lt)))
(<= (x (p1 lp))
(x (p1 lt)))))
(not (and (= (y (aref arr j))
(y (p1 lt)))
(<= (x (aref arr j))
(x (p1 lt))))))
(setf (p2 lp) (aref arr j))
(setf j i)
(when (intersects lp lt)
(incf count2)))))
(or (not (zerop (mod count1 2)))
(not (zerop (mod count2 2))))))))
(defmethod inside ((poly1 geom-polygon) (poly2 geom-polygon))
(when (closed poly2)
(let* ((arr (point-arr poly1))
(ok
(dotimes (i (- (first (array-dimensions arr)) 2))
(when (not (inside (aref arr (1+ i)) poly2))
(return t)))))
(not ok))))
(defmethod inside ((line geom-line) (poly geom-polygon))
(and (inside (p1 line) poly)
(inside (p2 line) poly)
(not (intersects line poly))))
;;;
;;;
;;;
(defmethod intersects ((point1 geom-point) (point2 geom-point))
nil)
(defmethod intersects ((point geom-point) (line geom-line))
nil)
(defmethod intersects ((line geom-line) (point geom-point))
nil)
(defmethod intersects ((line geom-line) (poly geom-polygon))
(let* ((arr (line-arr poly))
(ok
(dotimes (i (first (array-dimensions arr)))
(if (intersects (aref arr i) line)
(return t)))))
ok))
(defmethod intersects ((poly geom-polygon) (line geom-line))
(intersects line poly))
(defmethod intersects ((poly1 geom-polygon) (poly2 geom-polygon))
(let* ((arr (line-arr poly1))
(ok
(dotimes (i (first (array-dimensions arr)))
(if (intersects (aref arr i) poly2)
(return t)))))
ok))
(defmethod intersects ((point geom-point) (poly geom-polygon))
nil)
(defmethod intersects ((poly geom-polygon) (point geom-point))
nil)
;;;
;;;
;;;
(defmethod disjoint ((poly1 geom-polygon) (poly2 geom-polygon))
(and (not
(inside poly1 poly2))
(not
(intersects poly1 poly2))))
;;;
;;;
;;;
(defmethod touching-tres ((poly1 geom-polygon) (poly2 geom-polygon) tres)
"Arbeitet mit dem minimalen Abstand"
(and
(not (intersects poly1 poly2))
(let ((d (distance-between poly1 poly2)))
(if (<= d tres) d))))
(defmethod touching-tres ((poly geom-polygon) (point geom-point) tres)
(let ((d (distance-between poly point)))
(if (<= d tres) d)))
(defmethod touching-tres ((point geom-point) (poly geom-polygon) tres)
(touching-tres poly point tres))
;;;
;;;
;;;
(defmethod covers-tres ((thing1 geom-thing) (thing2 geom-thing) tres)
(and (inside thing2 thing1)
(touching-tres thing2 thing1 tres)))
;;;
;;;
;;;
(defun distance-and-orientation (x1 y1 x2 y2)
(let* (
(dx (- x2 x1))
(dy (- y2 y1))
(d (sqrt (+ (* dx dx) (* dy dy))))
(phi (if (zerop dx)
(if (minusp dy)
(- (/ pi 2))
(/ pi 2))
(atan (/ dy dx))))
(phi2 (if (minusp dx)
(+ phi pi)
phi)))
(values d phi2)))
;;;
;;; Master-Function
;;;
(defun inverse (relation)
(case relation
(is-inside 'contains)
(is-covered-by 'covers)
(contains 'is-inside)
(covers 'is-covered-by)
(t relation)))
#|
(defun relate-poly-to-poly-binary-tres (poly1 poly2 tres)
(if (intersects poly1 poly2)
'intersects
(if (inside poly1 poly2)
(let ((d (distance-between poly1 poly2)))
(if (<= d tres)
'is-covered-by
'is-inside))
(if (inside poly2 poly1)
(let ((d (distance-between poly2 poly1)))
(if (<= d tres)
'covers
'contains))
(let ((d (distance-between poly1 poly2)))
(if (<= d tres)
'touches
'is-disjoint-with))))))
|#
(defun delete-object-from-cache (poly1 object-liste)
(dolist (elem object-liste)
(let* ((goedel1 (get-goedel poly1 elem))
(goedel2 (get-goedel elem poly1)))
(remhash goedel1 *hash-table*)
(remhash goedel2 *hash-table*))))
(defun get-goedel (x y)
(* (expt 2 (tickval x))
(expt 3 (tickval y))))
(defun relate-poly-to-poly-unary-tres (poly1 poly2 tres)
(let* ((goedel (get-goedel poly1 poly2))
(hash-rel (gethash goedel
*hash-table*)))
(if hash-rel
hash-rel
(let ((relation
(if (intersects poly1 poly2)
'intersects
(if (inside poly1 poly2)
(let ((d (distance-between poly1 poly2)))
(if (<= d tres)
'is-covered-by
'is-inside))
(let ((d (distance-between poly1 poly2)))
(if (<= d tres)
'touches
'is-disjoint-with))))))
(setf (gethash goedel
*hash-table*)
relation)
(if (member relation '(touches intersects))
(setf (gethash (get-goedel poly2 poly1)
*hash-table*)
relation))
relation))))
| 14,072 | Common Lisp | .lisp | 480 | 23.772917 | 93 | 0.568432 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 26b232e0bf9437e6d3c7261df37b5e84109dabb36fee6fd2a011a0c788f6dec6 | 11,211 | [
-1
] |
11,212 | georalph.lisp | lambdamikel_GenEd/src/geometry/georalph.lisp | ;;; -*- Mode: LISP; Syntax: Ansi-Common-Lisp; Package: GEOMETRY -*-
(in-package geometry)
(defconstant +big-int+ 10000)
(defparameter *tick-counter* 1)
(defparameter *hash-table* (make-hash-table :size 200 :rehash-size 50))
;;;
;;; Topological Relations for Polygons.
;;;
(defclass geom-thing ()
((tickval :initform nil :accessor tickval :initarg :tickval)))
(defclass geom-line (geom-thing)
((p1 :initform nil :initarg :p1 :accessor p1)
(p2 :initform nil :initarg :p2 :accessor p2)))
(defclass geom-point (geom-thing)
((x :initform 0 :initarg :x :accessor x)
(y :initform 0 :initarg :y :accessor y)))
(defclass geom-polygon (geom-thing)
((point-arr :initform nil :initarg :point-arr :accessor point-arr) ; range: 1..n
(line-arr :initform nil :initarg :line-arr :accessor line-arr) ; range: 0..n/n-1
(closed :initform t :initarg :closed :accessor closed)))
(defmethod get-points ((object geom-polygon))
(mapcan
#'(lambda (point)
(list (x point)
(y point)))
(coerce
(point-arr object)
'list)))
;;;
;;; Basis-Funktionen
;;;
(defmethod ccw ((p0 geom-point) (p1 geom-point) (p2 geom-point))
"Quelle: Sedgewick"
(let* ((x0 (x p0))
(x1 (x p1))
(x2 (x p2))
(y0 (y p0))
(y1 (y p1))
(y2 (y p2))
(dx1 (- x1 x0))
(dy1 (- y1 y0))
(dx2 (- x2 x0))
(dy2 (- y2 y0)))
(cond ((> (* dx1 dy2) (* dy1 dx2)) 1)
((< (* dx1 dy2) (* dy1 dx2)) -1)
((or (< (* dx1 dx2) 0)
(< (* dy1 dy2) 0))
-1)
((< (+ (* dx1 dx1) (* dy1 dy1))
(+ (* dx2 dx2) (* dy2 dy2)))
1)
(t 0))))
;;;
;;; Hilfsfunktionen
;;;
(defun make-geom-polygon (point-list
&key (is-closed t)
(tickval nil))
(let* ((poly
(make-instance 'geom-polygon :closed is-closed :tickval tickval)))
(setf
(point-arr poly)
(make-geom-point-arr point-list)
(line-arr poly)
(make-geom-line-arr
(point-arr poly) :closed is-closed))
poly))
(defun make-geom-point (x y &key (tickval nil))
(make-instance 'geom-point
:x x
:y y
:tickval tickval))
(defun make-geom-point-arr (liste)
(let ((arr (make-array (+ 2 (length liste))))
(i 1))
(dolist (elem liste)
(setf (aref arr i)
(make-geom-point (first elem)
(second elem)))
(incf i))
(setf (aref arr 0)
(aref arr (1- i)))
(setf (aref arr i)
(aref arr 1))
arr))
(defun make-geom-line (p1 p2 &key (tickval nil))
(make-instance 'geom-line
:p1 p1
:p2 p2
:tickval tickval))
(defun make-geom-line-arr (point-arr
&key (closed t))
(let* ((dim (if closed
(- (first (array-dimensions point-arr)) 2)
(- (first (array-dimensions point-arr)) 3)))
(arr (make-array (list dim))))
(dotimes (i dim)
(setf (aref arr i)
(make-geom-line
(aref point-arr (+ i 1))
(aref point-arr (+ i 2)))))
arr))
;;;;
;;;;
;;;;
(defun high-index (arr)
(1- (first (array-dimensions arr))))
(defun calculate-bounding-box (arr)
(let* ((minx (x (aref arr 0)))
(miny (y (aref arr 0)))
(maxx minx)
(maxy miny))
(dotimes (i (1- (first (array-dimensions arr))))
(let* ((point (aref arr i))
(y (y point))
(x (x point)))
(cond ((< x minx) (setf minx x))
((> x maxx) (setf maxx x))
((< y miny) (setf miny y))
((> y maxy) (setf maxy y)))))
(values minx miny maxx maxy)))
(defun calculate-center (arr)
(multiple-value-bind (xf yf xt yt)
(calculate-bounding-box arr)
(values
(/ (+ xf xt) 2)
(/ (+ yf yt) 2))))
;;;
;;; Abstandsfunktionen
;;;
(defmethod parallelp ((thing1 geom-thing)
(thing2 geom-thing))
nil)
(defmethod parallelp ((line1 geom-line) (line2 geom-line))
(let ((dx1 (- (x (p1 line1)) (x (p2 line1))))
(dx2 (- (x (p1 line2)) (x (p2 line2))))
(dy1 (- (y (p1 line1)) (y (p2 line1))))
(dy2 (- (y (p1 line2)) (y (p2 line2)))))
(or (zerop (- (* dx1 dy2) (* dx2 dy1)))
(zerop (- (* dx2 dy1) (* dx1 dy2))))))
;;;
;;;
;;;
(defmethod distance-between ((point1 geom-point)
(point2 geom-point))
(let ((dx (- (x point1) (x point2)))
(dy (- (y point1) (y point2))))
(sqrt (+ (* dx dx) (* dy dy)))))
(defmethod distance-between ((line geom-line)
(point geom-point))
(distance-between point line))
(defmethod distance-between ((point geom-point)
(line geom-line))
(flet ((betw-0-and-1 (number)
(and (not (minusp number))
(<= number 1.0))))
(let* ((lp1 (p1 line))
(lp2 (p2 line))
(lx1 (x lp1))
(ly1 (y lp1))
(lx2 (x lp2))
(ly2 (y lp2))
(px (x point))
(py (y point))
(ax (- lx2 lx1))
(ay (- ly2 ly1))
(dx (- lx1 px))
(dy (- ly1 py))
(a2 (+ (* ax ax) (* ay ay)))
(scalar
(if (zerop a2)
+big-int+
(/ (+ (* ax (- dx))
(* ay (- dy)))
a2)))
(x (+ dx
(* scalar ax)))
(y (+ dy
(* scalar ay))))
(if (betw-0-and-1 scalar)
(sqrt (+ (* x x) (* y y)))
(min (distance-between point (p1 line))
(distance-between point (p2 line)))))))
(defmethod distance-between ((line1 geom-line)
(line2 geom-line))
(let* ((d1
(distance-between (p1 line1) line2))
(d2
(distance-between (p2 line1) line2))
(d3
(distance-between (p1 line2) line1))
(d4
(distance-between (p2 line2) line1)))
(min (min d1 d2 d3 d4))))
(defmethod distance-between ((poly1 geom-polygon)
(poly2 geom-polygon))
(let* (
(line-arr1 (line-arr poly1))
(line-arr2 (line-arr poly2))
(ind1 (high-index line-arr1))
(ind2 (high-index line-arr2)))
(loop for i from 0 to ind1 minimize
(loop for j from 0 to ind2 minimize
(distance-between
(aref line-arr1 i)
(aref line-arr2 j))))))
(defmethod distance-between ((line geom-line)
(poly geom-polygon))
(let (
(line-arr (line-arr poly)))
(loop for i from 0 to (high-index line-arr) minimize
(distance-between
(aref line-arr i)
line))))
(defmethod distance-between ((poly geom-polygon)
(line geom-line))
(distance-between line poly))
(defmethod distance-between ((poly geom-polygon)
(point geom-point))
(let ((line-arr (line-arr poly)))
(loop for i from 0 to (high-index line-arr) minimize
(distance-between point
(aref line-arr i)))))
(defmethod distance-between ((point geom-point)
(poly geom-polygon))
(distance-between poly point))
;;;
;;;
;;;
(defmethod inside-s ((point1 geom-point) (point2 geom-point))
nil)
(defmethod inside-s ((point geom-point) (line geom-line))
nil)
(defmethod inside-s ((line geom-line) (point geom-point))
nil)
(defmethod inside-s ((line1 geom-line) (line2 geom-line))
nil)
(defmethod inside-s ((polygon geom-polygon) (point geom-point))
nil)
(defmethod inside-s ((polygon geom-polygon) (line geom-line))
nil)
(defun aget (arr n)
(aref arr
(1+ (mod n (- (first (array-dimensions arr)) 2)))))
(defmethod inside-s ((point geom-point) (polygon geom-polygon))
(when (closed polygon) ; geht nur für geschlossene Polygone
(let* ((arr (point-arr polygon))
(highindex (first (array-dimensions arr)))
(n (- highindex 2)) ; Polygon hat Start- und Endpunkt doppelt
(x (x point))
(y (y point))
(count 0)
(lp (make-geom-line
(make-geom-point 0 0)
(make-geom-point 0 0)))
(i (loop for i from 0 while (= y (y (aget arr i))) ; Startindex bestimmen
finally (return i)))
(starti i) ; Startindex merken
(lt (make-geom-line ; Teststrahl in horizontale Richtung
(make-geom-point x y)
(make-geom-point +big-int+ y))))
(loop until (= starti (- i n)) do ; einmal ganz rum
(let ((bet-found 0)
(lasti i))
(let* ((curpoint (aget arr i))
(nextpoint ; nächsten Punkt suchen, der nicht auf Teststrahl liegt
(loop
(incf i)
(let ((nowpoint (aget arr i)))
(setf (p1 lp) (aget arr (1- i)))
(setf (p2 lp) nowpoint)
(cond ((= y (y nowpoint)) ; Punkte zählen auf Teststrahl
(when (intersects lp lt :dim nil)
(incf bet-found)))
(t ; Punkte gefunden, der nicht auf Teststrahl liegt
(return nowpoint)))))))
(cond ((= (1+ lasti) i) ; keine Punkt auf Teststrahl dazwischen
(setf (p1 lp) curpoint)
(setf (p2 lp) nextpoint)
(when (intersects lp lt :dim nil)
(incf count)))
(t ; viele Punkte auf dem Teststrahl lagen dazwischen !
(when (and (not (zerop bet-found))
(or (< (y curpoint) y (y nextpoint))
(> (y curpoint) y (y nextpoint))))
(incf count)))))))
(oddp count))))
(defmethod inside-s ((poly1 geom-polygon) (poly2 geom-polygon))
(when (closed poly2)
(let* ((arr (point-arr poly1))
(ok
(dotimes (i (- (first (array-dimensions arr)) 2))
(when (not (inside-s (aref arr (1+ i)) poly2))
(return t)))))
(not ok))))
(defmethod inside-s ((line geom-line) (poly geom-polygon))
(and (not (intersects-s line poly :dim nil))
(inside-s (p1 line) poly)
(inside-s (p2 line) poly)))
;;;
;;;
;;;
(defmethod inside ((object1 geom-thing) (object2 geom-thing))
"Fuer Aussen-Benutzung"
(and (not (intersects-s object1 object2 :dim nil))
(inside-s object1 object2)))
;;;
;;;
;;;
(defmethod intersects-s ((point1 geom-point) (point2 geom-point) &key &allow-other-keys)
(values nil nil))
(defmethod intersects-s ((point geom-point) (line geom-line) &key (dim nil))
(if
(or
(zerop (ccw (p1 line) (p2 line) point))
(zerop (ccw (p2 line) (p1 line) point)))
(if dim (values t 0) t)
(if dim (values nil nil) nil)))
(defmethod intersects-s ((line geom-line) (point geom-point) &key (dim nil))
(intersects-s point line :dim dim))
(defmethod intersects-s ((l1 geom-line) (l2 geom-line) &key (dim nil)
(top-level-use t))
"Quelle: Sedgewick"
(let ((l1p1 (p1 l1))
(l2p1 (p1 l2))
(l1p2 (p2 l1))
(l2p2 (p2 l2)))
(let ((a1 (* (ccw l1p1 l1p2 l2p1)
(ccw l1p1 l1p2 l2p2)))
(a2 (* (ccw l2p1 l2p2 l1p1)
(ccw l2p1 l2p2 l1p2))))
(if (and (<= a1
0)
(<= a2
0))
(if dim
(if (parallelp l1 l2)
(let ((l1p1-on-l2 (intersects l1p1 l2 :dim nil))
(l1p2-on-l2 (intersects l1p2 l2 :dim nil))
(l2p1-on-l1 (intersects l2p1 l1 :dim nil))
(l2p2-on-l1 (intersects l2p2 l1 :dim nil)))
(if (or (and l1p1-on-l2 l1p2-on-l2)
(and l2p1-on-l1 l2p2-on-l1)
(not (or
(and (same-point l1p1 l2p1)
l1p1-on-l2
l2p1-on-l1)
(and (same-point l1p1 l2p2)
l1p1-on-l2
l2p2-on-l1)
(and (same-point l1p2 l2p1)
l1p2-on-l2
l2p1-on-l1)
(and (same-point l1p2 l2p2)
l1p2-on-l2
l2p2-on-l1))))
(values t
(if top-level-use 1 'par))
(values t 0)))
(values t 0))
t)
(if dim
(values nil nil)
nil)))))
(defun same-point (p1 p2)
(and (= (x p1) (x p2))
(= (y p1) (y p2))))
(defun point< (p1 p2)
(and (< (x p1) (x p2))
(< (y p1) (y p2))))
(defun point> (p1 p2)
(and (> (x p1) (x p2))
(> (y p1) (y p2))))
(defmethod intersects-s ((line geom-line) (poly geom-polygon) &key
(dim nil)
(recursive-descent t)
(top-level-use t))
(let* ((larr (line-arr poly))
(par))
(if dim
(let ((max-dim
(loop for i from 0 to (1- (first (array-dimensions larr)))
maximize
(multiple-value-bind (intersectsp dim)
(intersects-s (aref larr i) line :dim t :top-level-use nil)
(if intersectsp
(if (numberp dim)
dim
(progn
(setf par t)
1))
-1)))))
(if (minusp max-dim)
(values nil nil)
(if (not par)
(progn
(values t (max max-dim
(if (and (closed poly) recursive-descent)
(calculate-dim-of-intersect line poly)
-1))))
(values t
(if top-level-use 1 'par)))))
(loop for i from 0 to (1- (first (array-dimensions larr)))
thereis
(intersects-s (aref larr i) line :dim nil)))))
(defmethod intersects-s ((poly geom-polygon) (line geom-line) &key
(dim nil)
(recursive-descent t)
(top-level-use t))
(intersects-s line poly
:dim dim
:recursive-descent recursive-descent
:top-level-use top-level-use))
(defmethod calculate-dim-of-intersect ((line geom-line) (poly geom-polygon))
(if (one-part-is-inside line poly)
1
0))
(defconstant +epsilon+ 3)
(defmethod one-part-is-inside ((line geom-line) (poly geom-polygon))
(let* ((p1 (p1 line))
(p2 (p2 line))
(d (distance-between p1 p2)))
(cond ((and (inside-s p1 poly)
(inside-s p2 poly)) t)
((< d +epsilon+) nil)
(t
(let* ((middle-point (make-geom-point
(/ (+ (x p1) (x p2)) 2)
(/ (+ (y p1) (y p2)) 2)))
(l1 (make-geom-line p1 middle-point))
(l2 (make-geom-line middle-point p2)))
(or (one-part-is-inside l1 poly)
(one-part-is-inside l2 poly)))))))
(defmethod intersects-s ((poly1 geom-polygon) (poly2 geom-polygon) &key (dim nil))
(let* ((arr (line-arr poly1))
(counter 0)
(col)
(parlist))
(if dim
(let ((max-dim
(loop for i from 0 to (1- (first (array-dimensions arr)))
maximize
(multiple-value-bind (intersectsp dim)
(intersects-s (aref arr i) poly2 :dim t :top-level-use nil
:recursive-descent t)
(cond ( (eq dim 'par)
(push i parlist)
1)
( intersectsp
(push i col)
(incf counter)
dim)
(t -1))))))
(if (minusp max-dim)
(values nil nil)
(values t
(if (and (> counter 0) (closed poly1)
(loop for line in col
thereis
(let ((dim (calculate-dim-of-intersect (aref arr line) poly2)))
(= dim 1))))
2
max-dim))))
(loop for i from 0 to (1- (first (array-dimensions arr)))
thereis
(intersects-s (aref arr i) poly2 :dim nil)))))
(defmethod intersects-s ((point geom-point) (poly geom-polygon) &key (dim nil))
(let* ((arr (line-arr poly))
(ok
(dotimes (i (first (array-dimensions arr)))
(if (intersects-s point (aref arr i) :dim nil)
(return t)))))
(if ok
(if dim (values t 0) t)
(if dim (values nil nil) nil))))
(defmethod intersects-s ((poly geom-polygon) (point geom-point) &key (dim nil))
(intersects-s point poly :dim dim))
;;;
;;;
(defmethod intersects ((thing1 geom-thing) (thing2 geom-thing) &key (dim nil))
(if dim
(multiple-value-bind (ip1 dim1)
(intersects-s thing1 thing2 :dim t)
(if (not ip1)
(values nil nil)
(if (< dim1 2)
(multiple-value-bind (ip2 dim2)
(intersects-s thing2 thing1 :dim t)
(declare (ignore ip2))
(values t (max dim1 dim2)))
(values t 2))))
(intersects-s thing1 thing2 :dim nil)))
;;;
;;;
;;;
(defmethod touching-tres ((thing1 geom-thing) (thing2 geom-thing) tres)
"Arbeitet mit dem minimalen Abstand. Fuer Aussen-Benutzung"
(and
(not (intersects-s thing1 thing2 :dim nil))
(let ((d (distance-between thing1 thing2)))
(if (<= d tres) d))))
;;;
;;;
;;;
(defmethod covers-tres ((thing1 geom-thing) (thing2 geom-thing) tres)
"Fuer Aussen-Benutzung"
(and (inside-s thing2 thing1)
(touching-tres thing2 thing1 tres)))
;;;
;;;
;;;
(defun distance-and-orientation (x1 y1 x2 y2)
(let* (
(dx (- x2 x1))
(dy (- y2 y1))
(d (sqrt (+ (* dx dx) (* dy dy))))
(phi (if (zerop dx)
(if (minusp dy)
(- (/ pi 2))
(/ pi 2))
(atan (/ dy dx))))
(phi2 (if (minusp dx)
(+ phi pi)
phi)))
(values d phi2)))
;;;
;;; Master-Function
;;;
(defun inverse (relation)
(case relation
(is-inside 'contains)
(is-covered-by 'covers)
(contains 'is-inside)
(covers 'is-covered-by)
(t relation)))
(defun clear-hashtable ()
(clrhash *hash-table*))
(defun delete-object-from-cache (thing object-liste)
(dolist (elem object-liste)
(unless (eq elem thing)
(let* ((goedel1 (get-goedel thing elem))
(goedel2 (get-goedel elem thing)))
(remhash goedel1 *hash-table*)
(remhash goedel2 *hash-table*)))))
#|
(defun get-goedel (x y)
(unless (tickval x)
(setf (tickval x) (incf *tick-counter*)))
(unless (tickval y)
(setf (tickval y) (incf *tick-counter*)))
(let ((r
(* (expt 2 (tickval x))
(expt 3 (tickval y)))))
r))
|#
(defconstant +hash-table-delta+ 3000)
(defun get-goedel (x y)
(unless (tickval x)
(setf (tickval x) (incf *tick-counter*)))
(unless (tickval y)
(setf (tickval y) (incf *tick-counter*)))
(+ (* +hash-table-delta+ (tickval x))
(tickval y)))
;;;
;;;
;;;
(defun relate-obj-to-obj (thing1 thing2 tres &key (dim nil))
(or (gethash (get-goedel thing1 thing2)
*hash-table*)
(inverse
(gethash (get-goedel thing2 thing1)
*hash-table*))
(let ((relation
(if (intersects thing1 thing2 :dim nil)
(if dim
(multiple-value-bind (intersectsp dim)
(intersects thing1 thing2 :dim t)
(declare (ignore intersectsp))
(case dim
(0 'intersects-0)
(1 'intersects-1)
(2 'intersects-2)))
'intersects)
(if (inside-s thing1 thing2)
(let ((d (distance-between thing1 thing2)))
(if (<= d tres)
'is-covered-by
'is-inside))
(if (inside-s thing2 thing1)
(let ((d (distance-between thing2 thing1)))
(if (<= d tres)
'covers
'contains))
(let ((d (distance-between thing1 thing2)))
(if (<= d tres)
'touches
'is-disjoint-with)))))))
(setf (gethash (get-goedel thing1 thing2)
*hash-table*)
relation)
relation)))
| 18,767 | Common Lisp | .lisp | 601 | 24.394343 | 99 | 0.558268 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 5a3e17235503162ff04003747ee33a6ed03aeb60fcfa4bf0668e69f9910c38d6 | 11,212 | [
-1
] |
11,213 | newgeo4.lisp | lambdamikel_GenEd/src/geometry/newgeo4.lisp | ;;; -*- Mode: LISP; Syntax: Ansi-Common-Lisp; Package: GEOMETRY -*-
(in-package geometry)
(defconstant +big-int+ 10000)
(defparameter *tick-counter* 1)
(defparameter *hash-table* (make-hash-table))
;;;
;;; Topological Relations for Polygons.
;;;
;;;
;;; Konstruktoren
;;;
(defclass geom-thing ()
((tickval :initform 0 :accessor tickval :initarg :tickval)))
(defclass geom-line (geom-thing)
((p1 :initform nil :initarg :p1 :accessor p1)
(p2 :initform nil :initarg :p2 :accessor p2)))
(defclass geom-point (geom-thing)
((x :initform 0 :initarg :x :accessor x)
(y :initform 0 :initarg :y :accessor y)))
(defclass geom-polygon (geom-thing)
((point-arr :initform nil :initarg :point-arr :accessor point-arr) ; range: 1..n
(line-arr :initform nil :initarg :line-arr :accessor line-arr) ; range: 0..n/n-1
(closed :initform t :initarg :closed :accessor closed)))
;;;
;;; Basis-Funktionen
;;;
(defmethod ccw ((p0 geom-point) (p1 geom-point) (p2 geom-point))
"Quelle: Sedgewick"
(let* ((x0 (x p0))
(x1 (x p1))
(x2 (x p2))
(y0 (y p0))
(y1 (y p1))
(y2 (y p2))
(dx1 (- x1 x0))
(dy1 (- y1 y0))
(dx2 (- x2 x0))
(dy2 (- y2 y0)))
(cond ((> (* dx1 dy2) (* dy1 dx2)) 1)
((< (* dx1 dy2) (* dy1 dx2)) -1)
((or (< (* dx1 dx2) 0)
(< (* dy1 dy2) 0))
-1)
((< (+ (* dx1 dx1) (* dy1 dy1))
(+ (* dx2 dx2) (* dy2 dy2)))
1)
(t 0))))
;;;
;;; Hilfsfunktionen
;;;
(defun make-geom-polygon (point-list
&key (is-closed t)) ; Fehler: wenn &key (closed t) !
(let* ((poly
(make-instance 'geom-polygon :closed is-closed
:tickval (incf *tick-counter*))))
(setf
(point-arr poly)
(make-geom-point-arr point-list)
(line-arr poly)
(make-geom-line-arr
(point-arr poly) :closed is-closed))
poly))
(defun make-geom-point (x y)
(make-instance 'geom-point
:tickval (incf *tick-counter*)
:x x
:y y))
(defun make-geom-point-arr (liste)
(let ((arr (make-array (+ 2 (length liste))))
(i 1))
(dolist (elem liste)
(setf (aref arr i)
(make-geom-point (first elem)
(second elem)))
(incf i))
(setf (aref arr 0)
(aref arr (1- i)))
(setf (aref arr i)
(aref arr 1))
arr))
(defun make-geom-line (p1 p2)
(make-instance 'geom-line
:tickval (incf *tick-counter*)
:p1 p1
:p2 p2))
(defun make-geom-line-arr (point-arr
&key (closed t))
(let* ((dim (if closed
(- (first (array-dimensions point-arr)) 2)
(- (first (array-dimensions point-arr)) 3)))
(arr (make-array (list dim))))
(dotimes (i dim)
(setf (aref arr i)
(make-geom-line
(aref point-arr (+ i 1))
(aref point-arr (+ i 2)))))
arr))
;;;;
;;;;
;;;;
(defun high-index (arr)
(1- (first (array-dimensions arr))))
(defun calculate-bounding-box (arr)
(let* ((minx (x (aref arr 0)))
(miny (y (aref arr 0)))
(maxx minx)
(maxy miny))
(dotimes (i (1- (first (array-dimensions arr))))
(let* ((point (aref arr i))
(y (y point))
(x (x point)))
(cond ((< x minx) (setf minx x))
((> x maxx) (setf maxx x))
((< y miny) (setf miny y))
((> y maxy) (setf maxy y)))))
(values minx miny maxx maxy)))
(defun calculate-center (arr)
(multiple-value-bind (xf yf xt yt)
(calculate-bounding-box arr)
(values
(/ (+ xf xt) 2)
(/ (+ yf yt) 2))))
;;;
;;; Abstandsfunktionen
;;;
(defmethod parallelp ((thing1 geom-thing)
(thing2 geom-thing))
nil)
(defmethod parallelp ((line1 geom-line) (line2 geom-line))
(let ((dx1 (- (x (p1 line1)) (x (p2 line1))))
(dx2 (- (x (p1 line2)) (x (p2 line2))))
(dy1 (- (y (p1 line1)) (y (p2 line1))))
(dy2 (- (y (p1 line2)) (y (p2 line2)))))
(zerop (- (* dx1 dy2) (* dx2 dy1)))))
;;;
;;;
;;;
(defmethod distance-between ((point1 geom-point)
(point2 geom-point))
(let ((dx (- (x point1) (x point2)))
(dy (- (y point1) (y point2))))
(sqrt (+ (* dx dx) (* dy dy)))))
(defmethod distance-between ((line geom-line)
(point geom-point))
(distance-between point line))
(defmethod distance-between ((point geom-point)
(line geom-line))
(flet ((betw-0-and-1 (number)
(and (not (minusp number))
(<= number 1.0))))
(let* ((lp1 (p1 line))
(lp2 (p2 line))
(lx1 (x lp1))
(ly1 (y lp1))
(lx2 (x lp2))
(ly2 (y lp2))
(px (x point))
(py (y point))
(ax (- lx2 lx1))
(ay (- ly2 ly1))
(dx (- lx1 px))
(dy (- ly1 py))
(a2 (+ (* ax ax) (* ay ay)))
(scalar
(if (zerop a2)
+big-int+
(/ (+ (* ax (- dx))
(* ay (- dy)))
a2)))
(x (+ dx
(* scalar ax)))
(y (+ dy
(* scalar ay))))
(if (betw-0-and-1 scalar)
(sqrt (+ (* x x) (* y y)))
(min (distance-between point (p1 line))
(distance-between point (p2 line)))))))
(defmethod distance-between ((line1 geom-line)
(line2 geom-line))
(let* ((d1
(distance-between (p1 line1) line2))
(d2
(distance-between (p2 line1) line2))
(d3
(distance-between (p1 line2) line1))
(d4
(distance-between (p2 line2) line1)))
(min (min d1 d2 d3 d4))))
(defmethod distance-between ((poly1 geom-polygon)
(poly2 geom-polygon))
(let* (
(line-arr1 (line-arr poly1))
(line-arr2 (line-arr poly2))
(ind1 (high-index line-arr1))
(ind2 (high-index line-arr2)))
(loop for i from 0 to ind1 minimize
(loop for j from 0 to ind2 minimize
(distance-between
(aref line-arr1 i)
(aref line-arr2 j))))))
(defmethod distance-between ((line geom-line)
(poly geom-polygon))
(let (
(line-arr (line-arr poly)))
(loop for i from 0 to (high-index line-arr) minimize
(distance-between
(aref line-arr i)
line))))
(defmethod distance-between ((poly geom-polygon)
(line geom-line))
(distance-between line poly))
(defmethod distance-between ((poly geom-polygon)
(point geom-point))
(let (
(line-arr (line-arr poly)))
(loop for i from 0 to (high-index line-arr) minimize
(distance-between point
(aref line-arr i)))))
(defmethod distance-between ((point geom-point)
(poly geom-polygon))
(distance-between poly point))
;;;
;;;
;;;
(defmethod inside-s ((point1 geom-point) (point2 geom-point))
nil)
(defmethod inside-s ((point geom-point) (line geom-line))
nil)
(defmethod inside-s ((line geom-line) (point geom-point))
nil)
(defmethod inside-s ((line1 geom-line) (line2 geom-line))
nil)
(defmethod inside-s ((polygon geom-polygon) (point geom-point))
nil)
(defmethod inside-s ((polygon geom-polygon) (line geom-line))
nil)
(defmethod inside-s ((point geom-point) (polygon geom-polygon))
"Nicht ganz korrekt !!! Quelle: Sedgewick, modifiziert!"
(when (closed polygon)
(let* ((count1 0)
(count2 0)
(j 0)
(arr (point-arr polygon))
(n (- (first (array-dimensions arr)) 2))
(x (x point))
(y (y point))
(lp (make-geom-line
(make-geom-point 0 0)
(make-geom-point 0 0)))
(lt (make-geom-line
(make-geom-point x y)
(make-geom-point +big-int+ y)))) ; wegen ALIAS-Effekten!
(dotimes (m n)
(let ((i (1+ m)))
(setf (p1 lp) (aref arr i))
(when (and
(not (and (= (y (p1 lp))
(y (p1 lt)))
(>= (x (p1 lp))
(x (p1 lt)))))
(not (and (= (y (aref arr j))
(y (p1 lt)))
(>= (x (aref arr j))
(x (p1 lt))))))
(setf (p2 lp) (aref arr j))
(setf j i)
(when (intersects lp lt)
(incf count1)))))
(let ((lt (make-geom-line
(make-geom-point x y)
(make-geom-point (- +big-int+) y)))) ; wegen ALIAS-Effekten!
(dotimes (m n)
(let ((i (1+ m)))
(setf (p1 lp) (aref arr i))
(when (and
(not (and (= (y (p1 lp))
(y (p1 lt)))
(<= (x (p1 lp))
(x (p1 lt)))))
(not (and (= (y (aref arr j))
(y (p1 lt)))
(<= (x (aref arr j))
(x (p1 lt))))))
(setf (p2 lp) (aref arr j))
(setf j i)
(when (intersects lp lt)
(incf count2)))))
(or (not (zerop (mod count1 2)))
(not (zerop (mod count2 2))))))))
(defmethod inside-s ((poly1 geom-polygon) (poly2 geom-polygon))
(when (closed poly2)
(let* ((arr (point-arr poly1))
(ok
(dotimes (i (- (first (array-dimensions arr)) 2))
(when (not (inside-s (aref arr (1+ i)) poly2))
(return t)))))
(not ok))))
(defmethod inside-s ((line geom-line) (poly geom-polygon))
(and (not (intersects line poly))
(inside-s (p1 line) poly)
(inside-s (p2 line) poly)))
;;;
;;;
;;;
(defmethod inside ((object1 geom-thing) (object2 geom-thing))
"Fuer Aussen-Benutzung"
(and (not (intersects object1 object2))
(inside-s object1 object2)))
;;;
;;;
;;;
(defmethod intersects ((point1 geom-point) (point2 geom-point))
nil)
(defmethod intersects ((point geom-point) (line geom-line))
(or
(zerop (ccw (p1 line) (p2 line) point))
(zerop (ccw (p2 line) (p1 line) point))))
(defmethod intersects ((line geom-line) (point geom-point))
(intersects point line))
(defmethod intersects ((l1 geom-line) (l2 geom-line))
"Quelle: Sedgewick"
(let ((l1p1 (p1 l1))
(l2p1 (p1 l2))
(l1p2 (p2 l1))
(l2p2 (p2 l2)))
(and (<= (* (ccw l1p1 l1p2 l2p1)
(ccw l1p1 l1p2 l2p2))
0)
(<= (* (ccw l2p1 l2p2 l1p1)
(ccw l2p1 l2p2 l1p2))
0))))
(defmethod intersects ((line geom-line) (poly geom-polygon))
(let* ((arr (line-arr poly))
(ok
(dotimes (i (first (array-dimensions arr)))
(if (intersects (aref arr i) line)
(return t)))))
ok))
(defmethod intersects ((poly geom-polygon) (line geom-line))
(intersects line poly))
(defmethod intersects ((poly1 geom-polygon) (poly2 geom-polygon))
(let* ((arr (line-arr poly1))
(ok
(dotimes (i (first (array-dimensions arr)))
(if (intersects (aref arr i) poly2)
(return t)))))
ok))
(defmethod intersects ((point geom-point) (poly geom-polygon))
(let* ((arr (line-arr poly))
(ok
(dotimes (i (first (array-dimensions arr)))
(if (intersects point (aref arr i))
(return t)))))
ok))
(defmethod intersects ((poly geom-polygon) (point geom-point))
(intersects point poly))
;;;
;;;
;;;
(defmethod disjoint ((poly1 geom-thing) (poly2 geom-thing))
"Fuer Aussen-Benutzung!"
(and
(not
(inside poly1 poly2))
(not
(inside poly2 poly1))))
;;;
;;;
;;;
(defmethod touching-tres ((thing1 geom-thing) (thing2 geom-thing) tres)
"Arbeitet mit dem minimalen Abstand. Fuer Aussen-Benutzung"
(and
(not (intersects thing1 thing2))
(let ((d (distance-between thing1 thing2)))
(if (<= d tres) d))))
;;;
;;;
;;;
(defmethod covers-tres ((thing1 geom-thing) (thing2 geom-thing) tres)
"Fuer Aussen-Benutzung"
(and (inside-s thing2 thing1)
(touching-tres-s thing2 thing1 tres)))
;;;
;;;
;;;
(defun distance-and-orientation (x1 y1 x2 y2)
(let* (
(dx (- x2 x1))
(dy (- y2 y1))
(d (sqrt (+ (* dx dx) (* dy dy))))
(phi (if (zerop dx)
(if (minusp dy)
(- (/ pi 2))
(/ pi 2))
(atan (/ dy dx))))
(phi2 (if (minusp dx)
(+ phi pi)
phi)))
(values d phi2)))
;;;
;;; Master-Function
;;;
(defun inverse (relation)
(case relation
(is-inside 'contains)
(is-covered-by 'covers)
(contains 'is-inside)
(covers 'is-covered-by)
(t relation)))
(defun delete-object-from-cache (thing object-liste)
(dolist (elem object-liste)
(let* ((goedel1 (get-goedel thing elem))
(goedel2 (get-goedel elem thing)))
(remhash goedel1 *hash-table*)
(remhash goedel2 *hash-table*))))
(defun get-goedel (x y)
(* (expt 2 (tickval x))
(expt 3 (tickval y))))
;;;
;;;
;;;
(defun relate-poly-to-poly-unary-tres (thing1 thing2 tres)
(let* ((goedel (get-goedel thing1 thing2))
(hash-rel (gethash goedel
*hash-table*)))
(if hash-rel
hash-rel
(let ((relation
(if (intersects thing1 thing2)
'intersects
(if (inside-s thing1 thing2)
(let ((d (distance-between thing1 thing2)))
(if (<= d tres)
'is-covered-by
'is-inside))
(if (inside-s thing2 thing1)
(let ((d (distance-between thing2 thing1)))
(if (<= d tres)
'covers
'contains))
(let ((d (distance-between thing1 thing2)))
(if (<= d tres)
'touches
'is-disjoint-with)))))))
(setf (gethash goedel
*hash-table*)
relation)
(setf (gethash (get-goedel thing2 thing1)
*hash-table*)
(inverse relation))
relation))))
| 12,946 | Common Lisp | .lisp | 451 | 23.388027 | 93 | 0.579242 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 778b5f23695ee7f877aff6427e34035fed966f8ae2d7f3338e656ab1c9d8db9c | 11,213 | [
-1
] |
11,214 | speccom.lisp | lambdamikel_GenEd/src/specific-commands/speccom.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: GENED; Base: 10 -*-
(in-package knowledge)
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-generic-function test ((cardinality :classic)))
)
(define-method test ((ind cardinality))
(format t "~%Here we have an cardinality!"))
| 307 | Common Lisp | .lisp | 7 | 41.285714 | 74 | 0.715753 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | e900ce03850941c8eadc663b0764b6c386fa80fd29970b9fbab8d798dbfd26f8 | 11,214 | [
-1
] |
11,215 | spline.lisp | lambdamikel_GenEd/src/splines/spline.lisp |
(defclass spline-point ()
((x :initarg :x :accessor x)
(y :initarg :y :accessor y)))
(defun make-spline-point (x y)
(make-instance 'spline-point :x x :y y))
(defun make-spline (points n)
(let* ((m (1- (first (array-dimensions points))))
(first 0)
(newpoints))
(dotimes (a (- m 3))
(let* ((i (+ a 2))
(pa (aref points (- i 1)))
(pb (aref points i))
(pc (aref points (+ i 1)))
(pd (aref points (+ i 2)))
(xa (x pa))
(ya (y pa))
(xb (x pb))
(yb (y pb))
(xc (x pc))
(yc (y pc))
(xd (x pd))
(yd (y pd))
(a3 (/ (+ (- xa) (* 3.0 (- xb xc)) xd) 6.0))
(a2 (/ (+ xa (* (- 2.0) xb) xc) 2.0))
(a1 (/ (- xc xa) 2.0))
(a0 (/ (+ xa (* 4.0 xb) xc) 6.0))
(b3 (/ (+ (- ya) (* 3.0 (- yb yc)) yd) 6.0))
(b2 (/ (+ ya (* (- 2.0) yb) yc) 2.0))
(b1 (/ (- yc ya) 2.0))
(b0 (/ (+ ya (* 4.0 yb) yc) 6.0))
(j first))
(loop
(let* ((q (/ j n))
(x0 (round (+ (* (+ (* (+ (* a3 q) a2) q) a1) q) a0)))
(y0 (round (+ (* (+ (* (+ (* b3 q) b2) q) b1) q) b0))))
(incf j)
(push (list x0 y0) newpoints)
(if (= j n) (return)))))
(setf first 0))
(values (make-point-array newpoints) newpoints)))
(defun make-point-array (liste)
(let ((index 0)
(arr (make-array (length liste))))
(mapc
#'(lambda (elem)
(setf (aref arr index)
(make-spline-point (first elem) (second elem)))
(incf index))
liste)
arr))
(defun normalize-list (liste)
(let ((first (first liste))
(last (last liste)))
(append
(list* first first first liste)
last last last)))
(defun remove-dublicates (liste &optional (akku ()))
(cond ((null liste) akku)
(t (remove-dublicates
(cdr liste)
(if (member (first liste) akku :test #'equalp)
akku
(cons (first liste) akku))))))
#| Bezier-Chain streichen, SPLINE nehmen!
Struktur: Pointlist, HANDLES wie bisher,
jedoch f. "spatial reasoning" SPLINE-Punkte nehmen
mit sehr hoher Granularität! (10)
Draw-Routine: DRAW-Polygon, nimm SPLINE-Punkte.
Neues Objekt: CREATE w. Polygon, aber
Spline-Polygon nehmen (zuerst niedrige Granul., damit
schnell), dann abspeichern mit hoher Granularität!
Klasen einführen : SPLINE-Polygon!
|#
| 2,455 | Common Lisp | .lisp | 74 | 25.878378 | 67 | 0.523747 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 4ab5e16b0408dc4f154802231710b784b9a044f1c8e0d3f6f48a0cbfceebd703 | 11,215 | [
-1
] |
11,216 | spline2.lisp | lambdamikel_GenEd/src/splines/spline2.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: SPLINES; Base: 10 -*-
(in-package splines)
(defun xp (point) (first point))
(defun yp (point) (second point))
(defun make-spline (liste n)
(let* ((newpoints))
(mapc #'(lambda (pa pb pc pd)
(let* (
(xa (xp pa))
(ya (yp pa))
(xb (xp pb))
(yb (yp pb))
(xc (xp pc))
(yc (yp pc))
(xd (xp pd))
(yd (yp pd))
(a3 (/ (+ (- xa) (* 3.0 (- xb xc)) xd) 6.0))
(a2 (/ (+ xa (* (- 2.0) xb) xc) 2.0))
(a1 (/ (- xc xa) 2.0))
(a0 (/ (+ xa (* 4.0 xb) xc) 6.0))
(b3 (/ (+ (- ya) (* 3.0 (- yb yc)) yd) 6.0))
(b2 (/ (+ ya (* (- 2.0) yb) yc) 2.0))
(b1 (/ (- yc ya) 2.0))
(b0 (/ (+ ya (* 4.0 yb) yc) 6.0)))
(dotimes (j (1+ n))
(let* ((q (/ j n))
#|
(x0 (round (+ (* (+ (* (+ (* a3 q) a2) q) a1) q) a0)))
(y0 (round (+ (* (+ (* (+ (* b3 q) b2) q) b1) q) b0)))) |#
(x0 (+ (* (+ (* (+ (* a3 q) a2) q) a1) q) a0))
(y0 (+ (* (+ (* (+ (* b3 q) b2) q) b1) q) b0)))
(push (list x0 y0) newpoints)))))
liste (cdr liste) (cddr liste) (cdddr liste))
newpoints))
(defun make-spline-chain-list (liste)
(let ((first (first liste))
(last (last liste)))
(append
(list* first first first liste)
last last last)))
(defun make-spline-polygon-list (liste)
(let* ((revlist (reverse liste))
(last1 (first revlist))
(last2 (second revlist))
(last3 (third revlist)))
(append
(list last3 last2 last1)
liste)))
(defun filter-to-close-together-out (liste dist)
(let ((last-point (first liste))
(first-point (last liste))
(liste (rest (butlast liste))))
(append (list last-point)
(mapcan #'(lambda (point)
(let* ((xn (xp point))
(yn (yp point))
(xa (xp last-point))
(ya (yp last-point))
(dx (- xn xa))
(dy (- yn ya)))
(setf last-point point)
(if (< (sqrt (+ (* dx dx) (* dy dy))) dist)
nil
(list point))))
liste)
first-point)))
| 2,119 | Common Lisp | .lisp | 66 | 25.242424 | 76 | 0.471357 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 53319d5d90a2b464451694bc8960845feb0cca9d0f362678a77e4486bb8f7cef | 11,216 | [
-1
] |
11,217 | spline3.lisp | lambdamikel_GenEd/src/splines/spline3.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: SPLINES; Base: 10 -*-
(in-package splines)
(defun xp (point) (first point))
(defun yp (point) (second point))
(defun make-spline (liste n &key (polygon nil))
(let (newpoints)
(mapc #'(lambda (pa pb pc pd)
(let* ((xa (xp pa))
(ya (yp pa))
(xb (xp pb))
(yb (yp pb))
(xc (xp pc))
(yc (yp pc))
(xd (xp pd))
(yd (yp pd))
(a3 (/ (+ (- xa) (* 3.0 (- xb xc)) xd) 6.0))
(a2 (/ (+ xa (* (- 2.0) xb) xc) 2.0))
(a1 (/ (- xc xa) 2.0))
(a0 (/ (+ xa (* 4.0 xb) xc) 6.0))
(b3 (/ (+ (- ya) (* 3.0 (- yb yc)) yd) 6.0))
(b2 (/ (+ ya (* (- 2.0) yb) yc) 2.0))
(b1 (/ (- yc ya) 2.0))
(b0 (/ (+ ya (* 4.0 yb) yc) 6.0)))
(dotimes (j (1+ n))
(let* ((q (/ j n))
(x0 (+ (* (+ (* (+ (* a3 q) a2) q) a1) q) a0))
(y0 (+ (* (+ (* (+ (* b3 q) b2) q) b1) q) b0)))
(push (list x0 y0) newpoints)))))
liste (cdr liste) (cddr liste) (cdddr liste))
(let ((x (remove-duplicates newpoints :test #'equalp :from-end t)))
(if polygon
(butlast x)
x))))
(defun make-spline-chain-list (liste)
(let ((first (first liste))
(last (last liste)))
(append
(list* first first first liste)
last last last)))
(defun make-spline-polygon-list (liste)
(let* ((revlist (reverse liste))
(last1 (first revlist))
(last2 (second revlist))
(last3 (third revlist)))
(append
(list last3 last2 last1)
liste)))
(defun filter-to-close-together-out (liste dist)
(let ((last-point (first liste))
(first-point (last liste))
(liste (rest (butlast liste))))
(append (list last-point)
(mapcan #'(lambda (point)
(let* ((xn (xp point))
(yn (yp point))
(xa (xp last-point))
(ya (yp last-point))
(dx (- xn xa))
(dy (- yn ya)))
(setf last-point point)
(if (< (sqrt (+ (* dx dx) (* dy dy))) dist)
nil
(list point))))
liste)
first-point)))
| 3,065 | Common Lisp | .lisp | 65 | 25.4 | 145 | 0.328151 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 7e09ed18aedc48a11c1a7b4ff62d4e4bb52767c187d82cbf2a2d2e1729df23f6 | 11,217 | [
-1
] |
11,218 | er.lisp | lambdamikel_GenEd/src/knowledge/er.lisp |
(defmacro defprimitive (name expr)
`(define-primitive-concept ,name ,expr))
(defmacro defdisjoint (name expr grouping)
`(define-disjoint-primitive-concept ,name ,grouping ,expr))
(defmacro defconcept (name expr)
`(define-concept ,name ,expr))
(defun cl-filler (derived-object role &optional remove-elem)
(let ((fillers (remove remove-elem (cl-fillers derived-object role)
:test #'eq)))
(when (second fillers)
(cerror "Return only first filler"
"Attribute ~S holds more than 1 filler for ~S: ~S"
role derived-object fillers))
(first fillers)))
(defun find-possible-subsumees (inds)
(dolist (ind inds)
(let* ((parents (cl-ind-parents ind))
(children (delete nil (mapcar #'cl-concept-children parents))))
(when children
(format t "~&Individual ~S may be further specialized to ~S"
ind children)))))
;----------------------------------------------------------------
(defprimitive geo-thing classic-thing)
(defprimitive atleast-1d geo-thing)
(defprimitive atmost-1d geo-thing)
(defdisjoint 0d-object atmost-1d geo-objects)
(defdisjoint 1d-object (and atleast-1d atmost-1d) geo-objects)
(defdisjoint 2d-object atleast-1d geo-objects)
(cl-define-primitive-role 'view :attribute t)
(cl-define-primitive-role 'position :attribute t)
(cl-define-primitive-role 'size :attribute t)
;----------------------------------------------------------------
(cl-define-primitive-role 'spatial-relation)
(cl-define-primitive-role 'touching :parent 'spatial-relation
:inverse 'touching)
(cl-define-primitive-role 'overlapping :parent 'spatial-relation
:inverse 'overlapping)
(cl-define-primitive-role 'crossing :parent 'spatial-relation
:inverse 'crossing)
(cl-define-primitive-role 'containing :parent 'spatial-relation
:inverse 'inside
:inverse-parent 'spatial-relation)
(cl-define-primitive-role 'directly-containing :parent 'containing
:inverse 'directly-inside
:inverse-parent 'inside)
(cl-define-primitive-role 'covering :parent 'directly-containing
:inverse 'covered-by
:inverse-parent 'directly-inside)
;----------------------------------------------------------------
(defun compute-directly-inside (ind role)
(declare (ignore role))
(let* ((i-fillers (cl-fillers ind @inside))
(di-fillers (cl-fillers ind @directly-inside))
(l (1- (length i-fillers))))
(or di-fillers
(if (zerop l)
i-fillers
(list
(or
(find-if #'(lambda (x) (= l (length (cl-fillers x @inside))))
i-fillers)
(break "NIL as filler computed for directly-inside")))))))
(defconcept is-inside
(and geo-thing
(at-least 1 inside)))
(cl-add-filler-rule 'compute-directly-inside @is-inside @directly-inside
#'compute-directly-inside
:filter '(test-c cl-test-closed-roles? (inside)))
;----------------------------------------------------------------
(cl-define-primitive-role 'touching-atleast-1d :parent 'touching)
(cl-define-primitive-role 'touching-1d :parent 'touching-atleast-1d)
(cl-define-primitive-role 'touching-2d :parent 'touching-atleast-1d)
;----------------------------------------------------------------
(defconcept attached-1d
(and 1d-object
(at-least 2 touching)
(at-most 4 touching)))
(defconcept end-1d
(and attached-1d
(at-most 3 touching)
(at-most 1 touching-1d)
(some touching-atleast-1d)))
(defconcept middle-1d
(and attached-1d
(all touching atmost-1d)
(exactly 2 touching-1d)))
(defconcept simple-line
(and end-1d
(exactly 2 touching)
(all touching 2d-object)))
(defun to-end-1d* (from next)
(if (not next)
from
(to-end-1d*
next
(first (remove from (cl-fillers next @touching-1d))))))
(defun to-end-1d (from role)
(declare (ignore role))
(cond
((not (endp (cl-fillers from @to-end-1d)))
nil)
((cl-instance? from @simple-line)
(list from))
(t (list (to-end-1d*
from (first (cl-fillers from @touching-1d)))))))
(cl-define-primitive-role 'to-end-1d :inverse 'to-end-1d
:attribute t)
(cl-add-filler-rule 'find-end-1d @end-1d @to-end-1d
#'to-end-1d)
(defconcept line-handle
(and end-1d (some to-end-1d)))
(defconcept link-handle
(and line-handle
(exactly 1 touching-2d)))
(defconcept docking-2d
(and 2d-object
(some touching-1d)
(all touching-1d line-handle)))
(defun linked-2ds (from role)
(declare (ignore role))
(mapcan #'(lambda (x)
(let ((end (cl-filler x @to-end-1d)))
(when end
(let ((2d (cl-filler end @touching-2d from)))
(when 2d
(list 2d))))))
(cl-fillers from @touching-1d)))
(cl-define-primitive-role 'linked-2ds :inverse 'linked-2ds)
(cl-add-filler-rule 'find-linked-2d @docking-2d @linked-2ds
#'linked-2ds)
(defconcept linked-2d
(and 2d-object (some linked-2ds)))
(defconcept line-connector
(and link-handle (all touching-2d linked-2d)))
;----------------------------------------------------------------
(defprimitive er-thing geo-thing)
(defprimitive er-element (and er-thing atleast-1d))
;----------------------------------------------------------------
(defun cl-inv-role-name (role)
(let ((inv (cl-role-inverse (cl-named-role role))))
(when inv
(cl-role-name inv))))
(defmacro defqualifiedsubrole (role
qualification
&key
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
parent
(inverse-parent (or (cl-inv-role-name parent)
role))
break
no-rule)
`(prog1
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
,(unless no-rule
`(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-INV-FILLER-RULE"))
(cl-named-concept ',qualification)
(cl-named-role ',inv-name)
#'(lambda (ind role)
(declare (ignore role))
(when ,break
(break "in filler rule of ~A" ',inv-name))
(or
(cl-fillers ind
(cl-named-role ',inverse-parent))
(break "NIL as filler computed for ~A"
',inv-name)))
:filter
'(and (at-least 1 ,inverse-parent)
#|(test-c cl-test-closed-roles? (,role))|#)))))
;----------------------------------------------------------------
(defmacro deforconcept (concept-name parent ors)
`(prog1
(defprimitive ,concept-name ,parent)
,@(mapcar #'(lambda (or)
`(cl-add-rule (intern
(concatenate 'string "add-" (string ',or)
"-to-" (string ',concept-name)))
(cl-named-object ',or)
',concept-name))
ors)))
;----------------------------------------------------------------
(defmacro retrieve-rel (rel &optional (super @er-thing))
`(loop for di in (cl-concept-instances ,super)
for fillers = (mapcar #'cl-name (cl-fillers di ,rel))
when fillers collect (list (cl-name di) fillers)))
;----------------------------------------------------------------
(defprimitive point (and 0d-object er-thing))
(defprimitive start-point point)
(defprimitive end-point point)
(defprimitive link (and 1d-object er-element))
(defprimitive arrow (and 1d-object er-element))
(defprimitive region (and 2d-object er-element))
(defprimitive rect-region region)
(defprimitive rounded-region region)
(defprimitive oval-region region)
(defprimitive text (and 2d-object er-element))
(cl-define-primitive-role 'text-value :attribute t)
(cl-define-primitive-role 'has-parts :inverse 'part-of
:inverse-attribute t)
;----------------------------------------------------------------
(defqualifiedsubrole touching point :parent touching :no-rule t)
(defqualifiedsubrole touching start-point :parent touching-point :no-rule t)
(defqualifiedsubrole touching end-point :parent touching-point :no-rule t)
(defqualifiedsubrole touching link :parent touching-1d :no-rule t)
(defqualifiedsubrole touching arrow :parent touching-1d :no-rule t)
(defqualifiedsubrole touching region :parent touching-2d :no-rule t)
(defqualifiedsubrole touching rect-region :parent touching-region :no-rule t)
(defqualifiedsubrole touching rounded-region :parent touching-region :no-rule t)
(defqualifiedsubrole touching oval-region :parent touching-region :no-rule t)
(defqualifiedsubrole touching text :parent touching-2d :no-rule t)
(defqualifiedsubrole containing region
:parent directly-containing :inverse-parent directly-inside)
(defqualifiedsubrole containing text
:parent directly-containing :inverse-parent directly-inside)
(defqualifiedsubrole covering region :parent covering)
(cl-role-change-canonical-name 'connected @linked-2ds)
;----------------------------------------------------------------
(defconcept relationship-entity
(and link
(exactly 1 crossing)
(all crossing text)
(exactly 2 touching)
(all touching region)))
(defconcept cardinality
(and text
(exactly 1 crossing)
(all crossing relationship-entity)
(all text-value (set "1" "m" "n"))))
(defconcept 1-cardinality
(and cardinality
(is text-value "1")))
(defconcept m-cardinality
(and cardinality
(is text-value "m")))
(defconcept n-cardinality
(and cardinality
(is text-value "n")))
(defconcept 1-relationship-entity
(and relationship-entity
(all crossing 1-cardinality)))
(defconcept m-relationship-entity
(and relationship-entity
(all crossing m-cardinality)))
(defconcept n-relationship-entity
(and relationship-entity
(all crossing n-cardinality)))
(defconcept attribute-entity
(and link
(none crossing)
(exactly 2 touching)
(all touching region)))
(deforconcept attribute-or-relationship-entity link
(attribute-entity relationship-entity))
(defconcept entity
(and rect-region
(exactly 1 containing)
(all containing text)
(some touching)
(all touching attribute-or-relationship-entity)
(some connected)))
(defconcept entity-name
(and text
(exactly 1 directly-inside)
(all directly-inside entity)))
(defqualifiedsubrole touching 1-relationship-entity :parent touching-link)
(defqualifiedsubrole touching m-relationship-entity :parent touching-link)
(defqualifiedsubrole touching n-relationship-entity :parent touching-link)
(defconcept relationship
(and rounded-region
(exactly 1 containing)
(all containing text)
(exactly 2 connected)
(all connected entity)
(exactly 2 touching)
(all touching relationship-entity)
(at-most 2 touching-1-relationship-entity)
(at-most 1 touching-m-relationship-entity)
(at-most 1 touching-n-relationship-entity)))
(defconcept relationship-name
(and text
(exactly 1 directly-inside)
(all directly-inside relationship)))
(defconcept attribute
(and oval-region
(exactly 1 containing)
(all containing text)
(exactly 1 connected)
(all connected entity)))
(defconcept attribute-name
(and text
(exactly 1 directly-inside)
(all directly-inside attribute)))
;----------------------------------------------------------------
(defun close-pj-roles ()
(close-all-roles (list* @covering @covered-by
(cl-role-children @spatial-relation))
(cl-concept-instances @er-thing))
(close-all-subroles @inside :inds (cl-concept-instances @er-thing))
(close-all-subroles @containing :inds (cl-concept-instances @er-thing))
(close-all-roles (cl-role-children @touching)
(cl-concept-instances @er-thing))
(close-all-subroles @touching-atleast-1d
:inds (cl-concept-instances @er-thing))
(close-all-subroles @touching-region-inverse
:inds (cl-concept-instances @er-thing))
(close-all-roles (list @linked-2ds)
(cl-concept-instances @er-thing)))
| 13,633 | Common Lisp | .lisp | 319 | 32.827586 | 80 | 0.567541 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 91a8cbdad09c208df8db62c847e46fbc1e0047792ff5c0207ea16389fcebeb7d | 11,218 | [
-1
] |
11,219 | knowledge8.lisp | lambdamikel_GenEd/src/knowledge/knowledge8.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: Knowledge; Base: 10 -*-
(in-package knowledge)
(cl-reader-init)
(cl-clear-kb)
(cl-startup)
(setf *krss-verbose* nil)
(cl-set-classic-warn-mode t)
;----------------------------------------------------------------
#+:allegro
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun cl-filler (derived-object role &optional remove-elem)
(let ((fillers (remove remove-elem (cl-fillers derived-object role)
:test #'eq)))
(when (second fillers)
(cerror "Return only first filler"
"Attribute ~S holds more than 1 filler for ~S: ~S"
role derived-object fillers))
(first fillers)))
(defun close-all-subroles (role &key exceptions
(inds (cl-concept-instances @pj-thing)))
(unless (member role exceptions :test #'eq)
(close-all-roles (cl-role-children role) inds exceptions)
(dolist (role (cl-role-children role))
(close-all-subroles role :exceptions exceptions :inds inds))))
(defun close-all-roles (roles
&optional (inds (cl-concept-instances @pj-thing))
(exceptions nil))
(dolist (role roles)
(unless (member role exceptions :test #'eq)
(dolist (ind inds)
(unless (cl-ind-closed-role? ind role)
(cl-ind-close-role ind role))))))
(defun find-possible-subsumees (inds)
(dolist (ind inds)
(let* ((parents (cl-ind-parents ind))
(children (delete nil (mapcar #'cl-concept-children parents))))
(when children
(format t "~&Individual ~S may be further specialized to ~S"
ind children)))))
;----------------------------------------------------------------
(defun cl-inv-role-name (role)
(print role)
(let ((inv (cl-role-inverse (cl-named-role role))))
(when inv
(cl-role-name inv))))
(defmacro defqualifiedsubrole (role
qualification
&key
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
(parent role)
(inverse-parent (or (cl-inv-role-name parent)
role))
(specialized-concept t)
break)
`(progn
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-INV-FILLER-RULE"))
,(if specialized-concept
`(cl-named-concept ',qualification)
'(cl-named-concept 'classic-thing))
(cl-named-role ',inv-name)
#'(lambda (ind role)
(declare (ignore role))
(when ,break
(break "in filler rule of ~A" ',inv-name))
(or
(cl-fillers ind (cl-named-role ',inverse-parent))
(break "NIL as filler computed for ~A"
',inv-name)))
:filter
'(and (at-least 1 ,inverse-parent)
(test-c cl-test-closed-roles? (,role))))))
(defmacro def-or-concept (concept1 concept2)
(let ((or-name
(intern (concatenate 'string
(write-to-string concept1)
"-OR-"
(write-to-string concept2)))))
`(progn
(define-primitive-concept
,or-name
basic-thing)
(cl-add-rule ',(gensym)
(cl-named-concept ',concept1)
',or-name)
(cl-add-rule ',(gensym)
(cl-named-concept ',concept2)
',or-name))))
;----------------------------------------------------------------
;;; selbstinverse Basisrelationen
(cl-define-primitive-role 'spatial-relation :inverse 'spatial-relation)
(cl-define-primitive-role 'in-relation-with-objects :inverse 'in-relation-with-objects
:parent 'spatial-relation
:inverse-parent 'spatial-relation)
(cl-define-primitive-role 'disjoint-with :inverse 'disjoint-with :parent 'spatial-relation
:inverse-parent 'spatial-relation)
(cl-define-primitive-role 'touching-objects :inverse 'touching-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-objects :inverse 'intersects-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-0-objects :inverse 'intersects-0-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
(cl-define-primitive-role 'intersects-1-objects :inverse 'intersects-1-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
(cl-define-primitive-role 'intersects-2-objects :inverse 'intersects-2-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
;;;
;;; spatial-relation
;;; / \
;;; in-rel.w. disj.w.
;;; / | \
;;; / | \
;;; / | \
;;; touching inters. contains
;;; /|\ |
;;; / | \ direc.contains
;;; 0 1 2 |
;;; covers
;----------------------------------------------------------------
;;; nicht-selbstinverse Basisrelationen
(cl-define-primitive-role 'contains-objects :inverse 'contained-in-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'directly-contains-objects :inverse 'directly-contained-by-object
:parent 'contains-objects
:inverse-parent 'contained-in-objects)
(cl-define-primitive-role 'covers-objects :inverse 'covered-by-object
:parent 'directly-contains-objects
:inverse-parent 'directly-contained-by-object)
;----------------------------------------------------------------
;;;
;;; In diesen Rollen steht, mit wem das Ind. verbunden ist, und ueber welches Ende des Pfeiles:
;;;
;;; linked-over-with
;;; / \
;;; start-link.o.w. end-link.o.w. 0 ----> # : start-l.o.w.(0,#),
;;; end-l.o.w.(#,0),
;;; l.o.w.(#,0) /\ l.o.w(0,#).
(cl-define-primitive-role 'linked-over-with :inverse 'linked-over-with
:parent 'in-relation-with-objects
:inverse-parent 'linked-over-with)
(cl-define-primitive-role 'start-linked-over-with :inverse 'end-linked-over-with
:parent 'linked-over-with
:inverse-parent 'linked-over-with)
;;;
;;; Hier werden die Linker eingetragen: 0 -----> # : linker-objects(A,L), linker-objects(B,L).
;;; A L B
(cl-define-primitive-role 'linker-objects :inverse 'points-related-with
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linker-objects :inverse 'startpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
(cl-define-primitive-role 'end-linker-objects :inverse 'endpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
;;;
;;; Rollen eines Linkers: points-related-with
;;; / \ 0 ----> # : s.r.w.(L,A), e.r.w.(L,B)
;;; startpoint-rel.-w. endpoint-rel.-w. A L B
;;;
;;; Fuer Composite-Things:
;;;
(cl-define-primitive-role 'has-parts :inverse 'part-of
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
;;;
;;; Fuer Directed-Elements:
;;;
(cl-define-primitive-role 'has-points :inverse 'point-part-of
:parent 'has-parts
:inverse-parent 'part-of)
(cl-define-primitive-role 'has-startpoint :inverse 'startpoint-part-of-directed-element
:parent 'has-points
:inverse-parent 'point-part-of)
(cl-define-primitive-role 'has-endpoint :inverse 'endpoint-part-of-directed-element
:parent 'has-points
:inverse-parent 'point-part-of)
;----------------------------------------------------------------
;;;
;;;
;;;
(cl-define-primitive-role 'filled-bool :attribute t)
(cl-define-primitive-role 'radius-real :attribute t)
(cl-define-primitive-role 'text-string :attribute t)
(cl-define-primitive-role 'xtrans-integer :attribute t)
(cl-define-primitive-role 'ytrans-integer :attribute t)
(cl-define-primitive-role 'belongs-to-clos-object :attribute t)
;----------------------------------------------------------------
;;;
;;;
;;;
(define-primitive-concept gened-thing classic-thing)
(define-disjoint-primitive-concept basic-thing basic-or-comp gened-thing)
(define-disjoint-primitive-concept composite-thing basic-or-comp gened-thing)
(define-primitive-concept 0d gened-thing)
(define-primitive-concept 1d gened-thing)
(define-primitive-concept 2d gened-thing)
(define-primitive-concept at-least-1d (and 1d 2d))
(define-primitive-concept at-most-1d (and 0d 1d))
;;;
;;;
;;;
(define-primitive-concept directed-element (and 1d basic-thing))
(define-disjoint-primitive-concept g-circle type (and 2d basic-thing))
(define-disjoint-primitive-concept g-line type (and 1d basic-thing))
(define-disjoint-primitive-concept g-arrow type directed-element)
(define-disjoint-primitive-concept g-rectangle type (and 2d basic-thing))
(define-disjoint-primitive-concept g-chain type (and 1d basic-thing))
(define-disjoint-primitive-concept g-directed-chain type directed-element)
(define-disjoint-primitive-concept g-polygon type (and 2d basic-thing))
(define-disjoint-primitive-concept g-spline-polygon type (and 2d basic-thing))
(define-disjoint-primitive-concept g-spline-chain type (and 1d basic-thing))
(define-disjoint-primitive-concept g-directed-spline-chain type directed-element)
(define-disjoint-primitive-concept g-text type (and 2d basic-thing))
(define-disjoint-primitive-concept g-point type (and 0d basic-thing))
(define-disjoint-primitive-concept info-point type (and 0d basic-thing))
(define-disjoint-primitive-concept g-diamond type (and 2d basic-thing))
)
;;;
;;;
;;;
(defqualifiedsubrole intersects-objects g-text)
(defqualifiedsubrole intersects-objects info-point)
(defqualifiedsubrole points-related-with g-diamond)
(defqualifiedsubrole points-related-with g-rectangle)
(defqualifiedsubrole points-related-with g-circle)
(defqualifiedsubrole linked-over-with g-diamond)
;;;
;;;
;;;
(def-or-concept g-line g-spline-chain)
(def-or-concept g-circle g-diamond)
(def-or-concept g-diamond g-rectangle)
(def-or-concept g-circle g-rectangle)
(def-or-concept g-arrow g-directed-spline-chain)
;;;
;;; Diese Konzepte sind wohl von generellem Nutzen:
;;;
(define-concept linker-point
(and
info-point
(exactly 1 point-part-of)))
(define-concept t-linker-point
(and
linker-point
(exactly 1 touching-objects)))
(define-concept linker
(and
g-line-or-g-spline-chain
(exactly 2 points-related-with)))
(define-concept dlinker
(and
g-arrow-or-g-directed-spline-chain
(exactly 2 points-related-with)))
(define-concept tt-linker
(and
linker
(all has-points t-linker-point)))
(define-concept dtt-linker
(and
dlinker
(all has-points t-linker-point)))
;;;
;;;
;;;
(define-concept is-a-link?
(and dlinker
(all points-related-with g-rectangle)))
(define-concept relationship-entity
(and linker
(at-least 2 intersects-objects)
(at-most 3 intersects-objects)
(exactly 2 intersects-objects-info-point)
(exactly 2 touching-objects)
(all touching-objects g-diamond-or-g-rectangle)
(all points-related-with g-diamond-or-g-rectangle)
(exactly 2 points-related-with)
(exactly 1 points-related-with-g-diamond)
(exactly 1 points-related-with-g-rectangle)
(none contained-in-objects)))
(defqualifiedsubrole linker-objects relationship-entity)
(define-concept cardinality
(and g-text
(none touching-objects)
(none contained-in-objects)
(none contains-objects)
(exactly 1 intersects-objects)
(all intersects-objects relationship-entity)
(all text-string
(set "1" "m" "n"))))
(define-concept e-attribute-entity
(and linker
(exactly 2 intersects-objects)
(all intersects-objects info-point)
(exactly 2 touching-objects)
(all touching-objects g-circle-or-g-rectangle)
(all points-related-with g-circle-or-g-rectangle)
(exactly 2 points-related-with)
(exactly 1 points-related-with-g-circle)
(exactly 1 points-related-with-g-rectangle)
(none contained-in-objects)))
(define-concept r-attribute-entity
(and linker
(exactly 2 intersects-objects)
(all intersects-objects info-point)
(exactly 2 touching-objects)
(all touching-objects g-circle-or-g-diamond)
(all points-related-with g-circle-or-g-diamond)
(exactly 2 points-related-with)
(exactly 1 points-related-with-g-circle)
(exactly 1 points-related-with-g-diamond)
(none contained-in-objects)))
(def-or-concept e-attribute-entity info-point)
(def-or-concept e-attribute-entity relationship-entity)
(def-or-concept e-attribute-entity-or-relationship-entity info-point)
(def-or-concept r-attribute-entity info-point)
(def-or-concept r-attribute-entity relationship-entity)
(def-or-concept r-attribute-entity-or-relationship-entity info-point)
(define-concept named-region
(and 2d basic-thing
(exactly 1 contains-objects)
(all contains-objects g-text)))
(define-concept entity
(and g-rectangle
named-region
(all linker-objects e-attribute-entity-or-relationship-entity)
(none intersects-objects)
(none contained-in-objects)
(all touching-objects
e-attribute-entity-or-relationship-entity-or-info-point)
(all linked-over-with g-circle-or-g-diamond)
(some linked-over-with-g-diamond)))
(defqualifiedsubrole linked-over-with entity)
(define-concept e-attribute
(and g-circle
named-region
(none intersects-objects)
(none contained-in-objects)
(all linker-objects e-attribute-entity)
(all touching-objects e-attribute-entity-or-info-point)
(exactly 2 touching-objects)
(exactly 1 linked-over-with)
(all linked-over-with entity)))
(define-concept r-attribute
(and g-circle
named-region
(none intersects-objects)
(none contained-in-objects)
(all linker-objects r-attribute-entity)
(all touching-objects r-attribute-entity-or-info-point)
(exactly 2 touching-objects)
(exactly 1 linked-over-with)
(all linked-over-with g-diamond)))
(def-or-concept e-attribute entity)
(def-or-concept r-attribute entity)
(define-concept is-a-link
(and is-a-link?
(all points-related-with entity)))
(define-concept 1-cardinality
(and cardinality
(is text-string "1")))
(define-concept m-cardinality
(and cardinality
(is text-string "m")))
(define-concept n-cardinality
(and cardinality
(is text-string "n")))
(defqualifiedsubrole intersects-objects 1-cardinality)
(defqualifiedsubrole intersects-objects m-cardinality)
(defqualifiedsubrole intersects-objects n-cardinality)
(define-concept 1-relationship-entity
(and relationship-entity
(exactly 1 intersects-objects-g-text)
(some intersects-objects-1-cardinality)))
(define-concept m-relationship-entity
(and relationship-entity
(exactly 1 intersects-objects-g-text)
(some intersects-objects-m-cardinality)))
(define-concept n-relationship-entity
(and relationship-entity
(exactly 1 intersects-objects-g-text)
(some intersects-objects-n-cardinality)))
(defqualifiedsubrole linker-objects 1-relationship-entity)
(defqualifiedsubrole linker-objects m-relationship-entity)
(defqualifiedsubrole linker-objects n-relationship-entity)
(define-concept binary-relationship
(and g-diamond
named-region
(all linker-objects r-attribute-entity-or-relationship-entity)
(exactly 2 linker-objects-relationship-entity)
(none intersects-objects)
(none contained-in-objects)
(all touching-objects
r-attribute-entity-or-relationship-entity-or-info-point)
(all linked-over-with r-attribute-or-entity)
(exactly 2 linked-over-with-entity)
(at-most 2 linker-objects-1-relationship-entity)
(at-most 1 linker-objects-m-relationship-entity)
(at-most 1 linker-objects-n-relationship-entity)))
;;;
;;;
;;;
(defconstant +known-concepts+
'(linker
dlinker
tt-linker
dtt-linker
g-circle
g-line
g-rectangle
g-arrow
g-polygon
g-spline-chain
g-directed-spline-chain
g-spline-polygon
g-chain
g-directed-chain
g-text
g-point
g-diamond
composite-thing
info-point
is-a-link
relationship-entity
cardinality
e-attribute-entity
r-attribute-entity
named-region
entity
1-cardinality
m-cardinality
n-cardinality
1-relationship-entity
m-relationship-entity
n-relationship-entity
binary-relationship
e-attribute
r-attribute
))
(defconstant +library-concepts+
`(g-diamond
1-cardinality
m-cardinality
n-cardinality
binary-relationship
e-attribute
r-attribute
entity
))
(defconstant +known-roles+
'((spatial-relation ; keine Inverse
in-relation-with-objects ; keine Inverse
; disjoint-with ; selbstinvers
touching-objects ; selbstinvers
intersects-objects ; selbstinvers
intersects-0-objects ; selbstinvers
intersects-1-objects ; selbstinvers
intersects-2-objects ; selbstinvers
contains-objects
contained-in-objects
directly-contains-objects
directly-contained-by-object
covers-objects
covered-by-object
linked-over-with ; selbstinvers
start-linked-over-with
end-linked-over-with
linker-objects
points-related-with
start-linker-objects
startpoint-related-with
end-linker-objects
endpoint-related-with
has-parts
part-of
has-points
point-part-of
has-startpoint
startpoint-part-of-directed-element
has-endpoint
endpoint-part-of-directed-element
;;; Attribute
belongs-to-clos-object
filled-bool
radius-real
text-string
xtrans-integer
ytrans-integer)
(intersects-objects-g-text
intersects-objects-info-point
points-related-with-g-diamond
points-related-with-g-rectangle
points-related-with-g-circle
linked-over-with-g-diamond)
(linker-objects-relationship-entity
intersects-objects-1-cardinality
intersects-objects-m-cardinality
intersects-objects-n-cardinality
linker-objects-1-relationship-entity
linker-objects-m-relationship-entity
linker-objects-n-relationship-entity)
(linked-over-with-entity)))
| 19,643 | Common Lisp | .lisp | 520 | 31.667308 | 99 | 0.659371 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 7d8b2882c56b0d313b6870fda6be27389e93a03d89d3dca1f74a6db00f5f3580 | 11,219 | [
-1
] |
11,220 | knowledge5.lisp | lambdamikel_GenEd/src/knowledge/knowledge5.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: Knowledge; Base: 10 -*-
(in-package knowledge)
(cl-reader-init)
(cl-clear-kb)
(cl-startup)
(setf *krss-verbose* nil)
(cl-set-classic-warn-mode t)
;----------------------------------------------------------------
(defmacro defprimitive (name expr)
`(define-primitive-concept ,name ,expr))
(defmacro defdisjoint (name expr grouping)
`(define-disjoint-primitive-concept ,name ,grouping ,expr))
(defmacro defconcept (name expr)
`(define-concept ,name ,expr))
(defun cl-filler (derived-object role &optional remove-elem)
(let ((fillers (remove remove-elem (cl-fillers derived-object role)
:test #'eq)))
(when (second fillers)
(cerror "Return only first filler"
"Attribute ~S holds more than 1 filler for ~S: ~S"
role derived-object fillers))
(first fillers)))
(defun close-all-subroles (role &key exceptions
(inds (cl-concept-instances @pj-thing)))
(unless (member role exceptions :test #'eq)
(close-all-roles (cl-role-children role) inds exceptions)
(dolist (role (cl-role-children role))
(close-all-subroles role :exceptions exceptions :inds inds))))
(defun close-all-roles (roles
&optional (inds (cl-concept-instances @pj-thing))
(exceptions nil))
(dolist (role roles)
(unless (member role exceptions :test #'eq)
(dolist (ind inds)
(unless (cl-ind-closed-role? ind role)
(cl-ind-close-role ind role))))))
(defun find-possible-subsumees (inds)
(dolist (ind inds)
(let* ((parents (cl-ind-parents ind))
(children (delete nil (mapcar #'cl-concept-children parents))))
(when children
(format t "~&Individual ~S may be further specialized to ~S"
ind children)))))
;----------------------------------------------------------------
#+:allegro
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun cl-inv-role-name (role)
(let ((inv (cl-role-inverse (cl-named-role role))))
(when inv
(cl-role-name inv))))
(defmacro defqualifiedsubrole (role
qualification
&key
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
(parent role)
(inverse-parent (or (cl-inv-role-name parent)
role))
(specialized-concept t)
break)
`(progn
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-INV-FILLER-RULE"))
,(if specialized-concept
`(cl-named-concept ',qualification)
'(cl-named-concept 'classic-thing))
(cl-named-role ',inv-name)
#'(lambda (ind role)
(declare (ignore role))
(when ,break
(break "in filler rule of ~A" ',inv-name))
(or
(cl-fillers ind (cl-named-role ',inverse-parent))
(break "NIL as filler computed for ~A"
',inv-name)))
:filter
'(and (at-least 1 ,inverse-parent)
(test-c cl-test-closed-roles? (,role))))))
;----------------------------------------------------------------
;;; selbstinverse Basisrelationen
(cl-define-primitive-role 'spatial-relation :inverse 'spatial-relation)
(cl-define-primitive-role 'in-relation-with-objects :inverse 'in-relation-with-objects
:parent 'spatial-relation
:inverse-parent 'spatial-relation)
(cl-define-primitive-role 'disjoint-with :inverse 'disjoint-with
:parent 'spatial-relation
:inverse-parent 'spatial-relation)
(cl-define-primitive-role 'touching-objects :inverse 'touching-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-objects :inverse 'intersects-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-0-objects :inverse 'intersects-0-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
(cl-define-primitive-role 'intersects-1-objects :inverse 'intersects-1-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
(cl-define-primitive-role 'intersects-2-objects :inverse 'intersects-2-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
;;;
;;; spatial-relation
;;; / \
;;; in-rel.w. disj.w.
;;; / | \
;;; / | \
;;; / | \
;;; touching inters. contains
;;; /|\ |
;;; / | \ direc.contains
;;; 0 1 2 |
;;; covers
;----------------------------------------------------------------
;;; nicht-selbstinverse Basisrelationen
(cl-define-primitive-role 'contains-objects :inverse 'contained-in-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'directly-contains-objects :inverse 'directly-contained-by-object
:parent 'contains-objects
:inverse-parent 'contained-in-objects)
(cl-define-primitive-role 'covers-objects :inverse 'covered-by-object
:parent 'directly-contains-objects
:inverse-parent 'directly-contained-by-object)
;----------------------------------------------------------------
;;;
;;; In diesen Rollen steht, mit wem das Ind. verbunden ist, und ueber welches Ende des Pfeiles:
;;;
;;; linked-over-with
;;; / \
;;; start-link.o.w. end-link.o.w. 0 ----> # : start-l.o.w.(0,#),
;;; end-l.o.w.(#,0),
;;; l.o.w.(#,0) /\ l.o.w(0,#).
(cl-define-primitive-role 'linked-over-with :inverse 'linked-over-with
:parent 'in-relation-with-objects
:inverse-parent 'linked-over-with)
(cl-define-primitive-role 'start-linked-over-with :inverse 'end-linked-over-with
:parent 'linked-over-with
:inverse-parent 'linked-over-with)
;;;
;;; Hier werden die Linker eingetragen: 0 -----> # : linker-objects(A,L), linker-objects(B,L).
;;; A L B
(cl-define-primitive-role 'linker-objects :inverse 'points-related-with
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linker-objects :inverse 'startpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
(cl-define-primitive-role 'end-linker-objects :inverse 'endpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
;;;
;;; Rollen eines Linkers: points-related-with
;;; / \ 0 ----> # : s.r.w.(L,A), e.r.w.(L,B)
;;; startpoint-rel.-w. endpoint-rel.-w. A L B
;;;
;;; Fuer Composite-Things:
;;;
(cl-define-primitive-role 'has-parts :inverse 'part-of
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
;;;
;;; Fuer Directed-Elements:
;;;
(cl-define-primitive-role 'has-points :inverse 'point-part-of
:parent 'has-parts
:inverse-parent 'part-of)
(cl-define-primitive-role 'has-startpoint :inverse 'startpoint-part-of-directed-element
:parent 'has-points
:inverse-parent 'point-part-of)
(cl-define-primitive-role 'has-endpoint :inverse 'endpoint-part-of-directed-element
:parent 'has-points
:inverse-parent 'point-part-of)
;----------------------------------------------------------------
;;;
;;;
;;;
(cl-define-primitive-role 'filled-bool :attribute t)
(cl-define-primitive-role 'radius-real :attribute t)
(cl-define-primitive-role 'text-string :attribute t)
(cl-define-primitive-role 'xtrans-integer :attribute t)
(cl-define-primitive-role 'ytrans-integer :attribute t)
(cl-define-primitive-role 'belongs-to-clos-object :attribute t)
;----------------------------------------------------------------
;;;
;;;
;;;
(cl-define-primitive-concept 'gened-thing 'classic-thing)
(cl-define-disjoint-primitive-concept 'basic-thing 'gened-thing 'basic-or-comp)
(cl-define-disjoint-primitive-concept 'composite-thing 'gened-thing 'basic-or-comp)
(cl-define-primitive-concept '0d 'gened-thing)
(cl-define-primitive-concept '1d 'gened-thing)
(cl-define-primitive-concept '2d 'gened-thing)
(cl-define-primitive-concept 'at-least-1d '(and 1d 2d))
(cl-define-primitive-concept 'at-most-1d '(and 0d 1d))
;;;
;;;
;;;
(cl-define-primitive-concept 'directed-element '(and 1d basic-thing))
(cl-define-disjoint-primitive-concept 'g-circle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-line '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-arrow 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-rectangle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-spline-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-text '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-point '(and 0d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'info-point '(and 0d basic-thing) 'type)
)
;;;
;;;
;;;
(defqualifiedsubrole has-parts g-rectangle)
(defqualifiedsubrole has-parts directed-element)
(defqualifiedsubrole touching-objects directed-element)
;;;
;;; Diese Konzepte sind wohl von generellem Nutzen:
;;;
(define-concept nur-beruehrende-objekte
(and
basic-thing
(none contained-in-objects)
(some touching-objects)
(none has-parts)))
(define-concept verbinder-punkt
(and
info-point
(exactly 1 point-part-of)))
(define-concept t-verbinder-punkt
(and
verbinder-punkt
(at-least 1 touching-objects))) ;eigentlich (exactly 1 touching-objects) -> Error in Splines!
(define-concept c-verbinder-punkt
(and
verbinder-punkt
(exactly 1 covered-by-object)))
(define-concept i-verbinder-punkt
(and
verbinder-punkt
(exactly 1 directly-contained-by-object)))
(define-concept verbinder
(and
directed-element
(exactly 2 points-related-with)))
(define-concept tt-verbinder
(and
verbinder
(all has-points t-verbinder-punkt)))
(define-concept ii-verbinder
(and
verbinder
(all has-points i-verbinder-punkt)))
(define-concept it-verbinder
(and
verbinder
(all has-startpoint i-verbinder-punkt)
(all has-endpoint t-verbinder-punkt)))
(define-concept ti-verbinder
(and
verbinder
(all has-startpoint t-verbinder-punkt)
(all has-endpoint i-verbinder-punkt)))
(define-concept ct-verbinder
(and
verbinder
(all has-startpoint c-verbinder-punkt)
(all has-endpoint t-verbinder-punkt)))
(define-concept tc-verbinder
(and
verbinder
(all has-startpoint t-verbinder-punkt)
(all has-endpoint c-verbinder-punkt)))
(define-concept ci-verbinder
(and
verbinder
(all has-startpoint c-verbinder-punkt)
(all has-endpoint i-verbinder-punkt)))
(define-concept ic-verbinder
(and
verbinder
(all has-startpoint i-verbinder-punkt)
(all has-endpoint c-verbinder-punkt)))
;;;;
;;;;
;;;;
(defun string-is-integer-p (string)
(integerp
(read-from-string string)))
(cl-define-concept 'kapazitaets-label
'(and
g-text
(at-least 1 intersects-objects)
(all text-string
(and (test-h string-is-integer-p)))))
(defqualifiedsubrole intersects-objects kapazitaets-label)
;;;
;;;
;;;
(define-concept stelle-oder-transition
(and
nur-beruehrende-objekte
(all touching-objects-directed-element tt-verbinder)))
(define-concept stelle?
(and
g-circle
stelle-oder-transition))
(define-concept transition?
(and
g-rectangle
stelle-oder-transition))
;;;
;;;
;;;
(define-concept stelle
(and
stelle?
(all linked-over-with transition?)))
(defqualifiedsubrole has-parts stelle)
(define-concept konflikt-stelle
(and
stelle
(at-least 2 end-linked-over-with)))
(define-concept start-stelle
(and
stelle
(none start-linked-over-with)))
(define-concept end-stelle
(and
stelle
(none end-linked-over-with)))
(define-concept normale-stelle
(and
stelle
(some start-linked-over-with)
(some end-linked-over-with)))
(define-concept stelle-mit-kapazitaet
(and
stelle
(exactly 1 intersects-objects-kapazitaets-label)))
(cl-define-concept 'marke
'(and
g-circle
(all contained-in-objects stelle)
(fills filled-bool t)
(all radius-real
(and number
(min 2.0)
(max 10.0)))))
(define-concept stelle-mit-marken
(and
stelle
(some contains-objects)
(all contains-objects marke)))
(defqualifiedsubrole has-parts stelle-mit-marken)
(defun ueberlaufene-stelle? (ind)
(let* ((marken-rolle (cl-named-role 'contains-objects))
(marken (length (cl-fillers ind marken-rolle)))
(label-rolle (cl-named-role 'intersects-objects-kapazitaets-label))
(text-ind (first (cl-fillers ind label-rolle)))
(number (read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))))
(> marken number)))
(defun label-kleiner-1? (ind)
(let* ((rolle (cl-named-role 'intersects-objects-kapazitaets-label))
(text-ind (first (cl-fillers ind rolle)))
(kap
(if text-ind
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))
1)))
(<= kap 1)))
(cl-define-concept 'ueberlaufene-stelle!!!
'(and
stelle-mit-marken
stelle-mit-kapazitaet
(test-c cl-test-closed-roles? (contains-objects intersects-objects-kapazitaets-label))
(test-c ueberlaufene-stelle?)))
(cl-define-concept 'b/e-stelle
'(and
stelle
(test-c cl-test-closed-roles?
(intersects-objects-kapazitaets-label))
(test-c label-kleiner-1?)))
;;;
;;;
;;;
(define-concept transition
(and
transition?
(at-least 2 linked-over-with)
(at-least 1 start-linker-objects)
(at-least 1 end-linker-objects)
(all linked-over-with stelle?)))
(define-concept netz-kante
(and
tt-verbinder
(all touching-objects stelle-oder-transition)))
(define-concept netz-kante-mit-kapazitaet
(and
netz-kante
(exactly 1 intersects-objects-kapazitaets-label)))
(cl-define-concept 'b/e-netz-kante
'(and
netz-kante
(test-c cl-test-closed-roles? (intersects-objects-kapazitaets-label))
(test-c label-kleiner-1?)))
;;;
;;;
;;;
(defun genug-input-marken? (ind)
(let* ((end-linker (cl-named-role 'end-linker-objects))
(flag nil))
(or
(every #'(lambda (end-linker)
(let* ((text-ind
(first
(cl-fillers
end-linker
(cl-named-role 'intersects-objects-kapazitaets-label))))
(stelle
(first
(cl-fillers
end-linker
(cl-named-role 'startpoint-related-with))))
(kap
(if text-ind
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))
1)) ; Kante hat sonst Kap. 1 (wie bei BE-Netzen)
(marken
(length
(cl-fillers
stelle
(cl-named-role 'contains-objects)))))
(if (and marken kap)
(not (minusp (- marken kap)))
(progn
(setf flag '?)
nil))))
(cl-fillers ind end-linker))
flag)))
(defun genug-output-marken? (ind)
(let* ((start-linker (cl-named-role 'start-linker-objects))
(flag nil))
(or
(every #'(lambda (start-linker)
(let* ((text-ind
(first
(cl-fillers
start-linker
(cl-named-role 'intersects-objects-kapazitaets-label))))
(stelle
(first
(cl-fillers
start-linker
(cl-named-role 'endpoint-related-with))))
(kap
(if text-ind
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))
1))
(marken
(length
(cl-fillers
stelle
(cl-named-role 'contains-objects))))
(stellen-text-ind
(first
(cl-fillers
stelle
(cl-named-role 'intersects-objects-kapazitaets-label))))
(stellen-kap
(if stellen-text-ind
(read-from-string
(first
(cl-fillers
stellen-text-ind
(cl-named-role 'text-string))))
10000))) ; kein Label -> Kap. unbegrenzt ! (w)
(if (and stellen-kap kap marken)
(<= (+ marken kap) stellen-kap)
(progn
(setf flag '?)
nil))))
(cl-fillers ind start-linker))
flag)))
(cl-define-concept 'l-aktive-transition
'(and
transition
(all start-linked-over-with
stelle-mit-marken)
(all end-linker-objects netz-kante)
(test-c cl-test-closed-roles? (end-linker-objects start-linked-over-with))
(test-c genug-input-marken?)))
(cl-define-concept 'r-aktive-transition
'(and
transition
(all end-linked-over-with
stelle)
(all start-linker-objects netz-kante)
(test-c cl-test-closed-roles? (start-linker-objects end-linked-over-with))
(test-c genug-output-marken?)))
(cl-define-concept 'aktive-transition
'(and
l-aktive-transition
r-aktive-transition))
;;;
;;;
;;;
(define-concept petri-netz
(and
composite-thing
(at-least 5 has-parts)
(some has-parts-stelle)
(all has-parts-g-rectangle transition)
(all has-parts-directed-element netz-kante)))
(define-concept s/t-petri-netz
(and
petri-netz
(some has-parts-stelle-mit-marken)))
(define-concept b/e-petri-netz
(and
s/t-petri-netz
(all has-parts-stelle b/e-stelle)
(all has-parts-directed-element b/e-netz-kante)))
;;;
;;;
;;;
(defconstant +known-concepts+
'(verbinder
tt-verbinder
ii-verbinder
ti-verbinder
it-verbinder
ci-verbinder
ic-verbinder
tc-verbinder
ct-verbinder
stelle transition netz-kante
l-aktive-transition
r-aktive-transition
aktive-transition
netz-kante-mit-kapazitaet
marke
konflikt-stelle
ueberlaufene-stelle!!!
start-stelle end-stelle normale-stelle
b/e-stelle
b/e-netz-kante
kapazitaets-label
stelle-mit-kapazitaet
stelle-mit-marken
petri-netz
s/t-petri-netz
b/e-petri-netz
g-circle
g-line
g-rectangle
g-arrow
g-polygon
g-spline-chain
g-directed-spline-chain
g-spline-polygon
g-chain
g-directed-chain
g-text
g-point
composite-thing
info-point
))
(defconstant +library-concepts+
`(verbinder
kapazitaets-label
stelle
start-stelle
normale-stelle
end-stelle
stelle-mit-marken
stelle-mit-kapazitaet
marke
transition))
(defconstant +known-roles+
'((
spatial-relation ; keine Inverse
in-relation-with-objects ; keine Inverse
disjoint-with ; selbstinvers
touching-objects ; selbstinvers
intersects-objects ; selbstinvers
intersects-0-objects ; selbstinvers
intersects-1-objects ; selbstinvers
intersects-2-objects ; selbstinvers
contains-objects
contained-in-objects
directly-contains-objects
directly-contained-by-object
covers-objects
covered-by-object
linked-over-with ; selbstinvers
start-linked-over-with
end-linked-over-with
linker-objects
points-related-with
start-linker-objects
startpoint-related-with
end-linker-objects
endpoint-related-with
has-parts
part-of
has-points
point-part-of
has-startpoint
startpoint-part-of-directed-element
has-endpoint
endpoint-part-of-directed-element
;;; Attribute
belongs-to-clos-object
filled-bool
radius-real
text-string
xtrans-integer
ytrans-integer)
(has-parts-g-rectangle
has-parts-g-rectangle-inverse
has-parts-directed-element
has-parts-directed-element-inverse
touching-objects-directed-element
touching-objects-directed-element-inverse
intersects-objects-kapazitaets-label
intersects-objects-kapazitaets-label-inverse
has-parts-stelle
has-parts-stelle-inverse
has-parts-stelle-mit-marken
has-parts-stelle-mit-marken-inverse)))
| 22,578 | Common Lisp | .lisp | 661 | 26.939486 | 98 | 0.611487 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | eb8835046cac5b1d64c20428f35dfcb9791a2d3af8c1342e7405daa061fb16e9 | 11,220 | [
-1
] |
11,221 | knowledge.lisp | lambdamikel_GenEd/src/knowledge/knowledge.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: Knowledge; Base: 10 -*-
(in-package knowledge)
(cl-reader-init)
(cl-startup)
(setf *krss-verbose* nil)
(cl-set-classic-warn-mode t)
;----------------------------------------------------------------
;----------------------------------------------------------------
(defmacro defprimitive (name expr)
`(define-primitive-concept ,name ,expr))
(defmacro defdisjoint (name expr grouping)
`(define-disjoint-primitive-concept ,name ,grouping ,expr))
(defmacro defconcept (name expr)
`(define-concept ,name ,expr))
(defun cl-filler (derived-object role &optional remove-elem)
(let ((fillers (remove remove-elem (cl-fillers derived-object role)
:test #'eq)))
(when (second fillers)
(cerror "Return only first filler"
"Attribute ~S holds more than 1 filler for ~S: ~S"
role derived-object fillers))
(first fillers)))
(defun close-all-subroles (role &key exceptions
(inds (cl-concept-instances @pj-thing)))
(unless (member role exceptions :test #'eq)
(close-all-roles (cl-role-children role) inds exceptions)
(dolist (role (cl-role-children role))
(close-all-subroles role :exceptions exceptions :inds inds))))
(defun close-all-roles (roles
&optional (inds (cl-concept-instances @pj-thing))
(exceptions nil))
(dolist (role roles)
(unless (member role exceptions :test #'eq)
(dolist (ind inds)
(unless (cl-ind-closed-role? ind role)
(cl-ind-close-role ind role))))))
(defun find-possible-subsumees (inds)
(dolist (ind inds)
(let* ((parents (cl-ind-parents ind))
(children (delete nil (mapcar #'cl-concept-children parents))))
(when children
(format t "~&Individual ~S may be further specialized to ~S"
ind children)))))
;----------------------------------------------------------------
;;;
;;;
;;;
(defun cl-inv-role-name (role)
(let ((inv (cl-role-inverse (cl-named-role role))))
(when inv
(cl-role-name inv))))
(defmacro defqualifiedsubrole (role
qualification
&key
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
(parent role)
(inverse-parent (or (cl-inv-role-name parent)
role))
break)
`(progn
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-INV-FILLER-RULE"))
(cl-named-concept ',qualification)
(cl-named-role ',inv-name)
#'(lambda (ind role)
(declare (ignore role))
(when ,break
(break "in filler rule of ~A" ',inv-name))
(or
(cl-fillers ind (cl-named-role ',inverse-parent))
(break "NIL as filler computed for ~A"
',inv-name)))
:filter
'(and (at-least 1 ,inverse-parent)
(test-c cl-test-closed-roles? (,role))))))
;;;
;;;
;;;
;----------------------------------------------------------------
(cl-define-primitive-role 'spatial-relation)
(cl-define-primitive-role 'in-relation-with-objects
:parent 'spatial-relation)
(cl-define-primitive-role 'disjoint-with
:parent 'spatial-relation)
(cl-define-primitive-role 'touching-objects :inverse 'touching-objects
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-objects :inverse 'intersects-objects
:parent 'in-relation-with-objects)
;;; spatial-relation
;;; / \
;;; in-rel.w. disj.w.
;;; / | \
;;; / | \
;;; / | \
;;; touching inters. contains
;;; |
;;; direc.contains
;;; |
;;; covers
(cl-define-primitive-role 'contains-objects :inverse 'contained-in-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'directly-contains-objects :inverse 'directly-contained-by-object
:parent 'contains-objects
:inverse-parent 'contained-in-objects)
(cl-define-primitive-role 'covers-objects :inverse 'covered-by-object
:parent 'directly-contains-objects
:inverse-parent 'directly-contained-by-object)
;;;
;;; In diesen Rollen steht, mit wem das Ind. verbunden ist, und ueber welches Ende des Pfeiles:
;;;
;;; linked-over-with
;;; / \
;;; start-link.o.w. end-link.o.w. 0 ----> # : start-l.o.w.(0,#),
;;; end-l.o.w.(#,0),
;;; l.o.w.(#,0) /\ l.o.w(0,#).
(cl-define-primitive-role 'linked-over-with :inverse 'linked-over-with
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linked-over-with :inverse 'end-linked-over-with
:parent 'linked-over-with
:inverse-parent 'linked-over-with)
;;;
;;; Hier werden die Linker eingetragen: 0 -----> # : linker-objects(A,L), linker-objects(B,L).
;;; A L B
(cl-define-primitive-role 'linker-objects :inverse 'points-related-with
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linker-objects :inverse 'startpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
(cl-define-primitive-role 'end-linker-objects :inverse 'endpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
;;;
;;;
;;;
;;; Rollen eines Linkers: points-related-with
;;; / \ 0 ----> # : s.r.w.(L,A), e.r.w.(L,B)
;;; startpoint-rel.-w. endpoint-rel.-w. A L B
#|
(cl-define-primitive-role 'points-related-with :inverse 'linker-objects
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'startpoint-related-with :inverse 'endpoint-related-with
:parent 'points-related-with
:inverse-parent 'points-related-with)
|#
;;;
;;; Fuer Composite-Things:
;;;
(cl-define-primitive-role 'has-parts :inverse 'part-of
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
;;;
;;;
;;;
(cl-define-primitive-role 'filled-bool :attribute t)
(cl-define-primitive-role 'radius-real :attribute t)
(cl-define-primitive-role 'text-string :attribute t)
;;;
;;;
;;;
(cl-define-primitive-concept 'gened-thing 'classic-thing)
(cl-define-disjoint-primitive-concept 'basic-thing 'gened-thing 'basic-or-comp)
(cl-define-disjoint-primitive-concept 'composite-thing 'gened-thing 'basic-or-comp)
(cl-define-primitive-concept '0d 'gened-thing)
(cl-define-primitive-concept '1d 'gened-thing)
(cl-define-primitive-concept '2d 'gened-thing)
(cl-define-primitive-concept 'at-least-1d '(and 1d 2d))
(cl-define-primitive-concept 'at-most-1d '(and 0d 1d))
;;;
;;;
;;;
(cl-define-primitive-concept 'directed-element '(and 1d basic-thing))
(cl-define-disjoint-primitive-concept 'g-circle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-line '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-arrow 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-rectangle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-spline-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-text '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-point '(and 0d basic-thing) 'type)
;;;
;;;
;;;
(defqualifiedsubrole linked-over-with g-circle
:parent linked-over-with :inverse-parent linked-over-with)
(defqualifiedsubrole linked-over-with g-rectangle
:parent linked-over-with :inverse-parent linked-over-with)
(defqualifiedsubrole has-parts g-circle
:parent has-parts :inverse-parent part-of)
(defqualifiedsubrole has-parts g-rectangle
:parent has-parts :inverse-parent part-of)
(defqualifiedsubrole has-parts g-arrow
:parent has-parts :inverse-parent part-of)
;;;
;;; Diese Konzepte sind wohl von generellem Nutzen:
;;;
(define-concept nur-beruehrende-objekte
(and
basic-thing
(none contained-in-objects)
(some touching-objects)
(none has-parts)))
(define-concept verbinder
(and
directed-element
(exactly 2 points-related-with)))
(defun subset? (ind sym1 sym2)
(let* ((role1 (cl-named-role sym1))
(role2 (cl-named-role sym2))
(fillers1 (cl-fillers ind role1))
(fillers2 (cl-fillers ind role2)))
(if (and (cl-ind-closed-role? ind role1)
(cl-ind-closed-role? ind role2))
(null (set-difference
fillers2 fillers1))
'?)))
(defun member? (ind sym1 sym2)
(let* ((role1 (cl-named-role sym1))
(role2 (cl-named-role sym2))
(fillers1 (cl-fillers ind role1))
(fillers2 (cl-fillers ind role2)))
(if (and (cl-ind-closed-role? ind role1)
(cl-ind-closed-role? ind role2))
(if (> (length fillers1) 1)
nil
(member (first fillers1) fillers2))
'?)))
(defun not-member? (ind sym1 sym2)
(let ((member (member? ind sym1 sym2)))
(case member
(? '?)
(t nil)
(nil t))))
(cl-define-concept 'tt-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with
touching-objects)
(test-c member?
endpoint-related-with
touching-objects)))
(cl-define-concept 'it-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with
intersects-objects)
(test-c member?
endpoint-related-with
touching-objects)))
(cl-define-concept 'ti-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with
touching-objects)
(test-c member?
endpoint-related-with
intersects-objects)))
(cl-define-concept 'ii-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with intersects-objects)
(test-c member?
endpoint-related-with intersects-objects)))
(cl-define-concept 'ct-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with covered-by-object)
(test-c member?
endpoint-related-with touching-objects)))
(cl-define-concept 'tc-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with touching-objects)
(test-c member?
endpoint-related-with covered-by-object)))
(cl-define-concept 'ci-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with covered-by-object)
(test-c member?
endpoint-related-with intersects-objects)
(test-c not-member?
endpoint-related-with touching-objects)))
(cl-define-concept 'ic-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with intersects-objects)
(test-c member?
endpoint-related-with covered-by-object)))
;;;;
;;;;
;;;;
(define-concept stelle-oder-transition
(and
nur-beruehrende-objekte
(all touching-objects verbinder)))
(define-concept stelle*
(and
g-circle
stelle-oder-transition))
(define-concept transition*
(and
g-rectangle
stelle-oder-transition))
(define-concept stelle
(and
stelle*
(all linked-over-with transition*)))
(define-concept konflikt-stelle
(and
stelle
(at-least 2 end-linked-over-with)))
(define-concept start-stelle
(and
stelle
(none start-linked-over-with)))
(define-concept end-stelle
(and
stelle
(none end-linked-over-with)))
(define-concept normale-stelle
(and
stelle
(some start-linked-over-with)
(some end-linked-over-with)))
(define-concept stelle-mit-kapazitaet
(and
stelle
(exactly 1 intersects-objects)
(all intersects-objects g-text)))
(define-concept marke
(and
g-circle
(some filled-bool)))
(define-concept stelle-mit-marken
(and
stelle
(some contains-objects)
(all contains-objects marke)))
(define-concept transition
(and
transition*
(at-least 2 linked-over-with)
(all linked-over-with stelle*)))
(define-concept netz-kante
(and
verbinder
(all touching-objects stelle-oder-transition)))
(define-concept netz-kante-mit-kapazitaet
(and
netz-kante
(exactly 1 intersects-objects)
(all intersects-objects g-text)))
(define-concept petri-netz
(and
composite-thing
(at-least 5 has-parts) ; kleinstes Netz: 0 -> # -> 0
(all has-parts-g-circle stelle)
(all has-parts-g-rectangle transition)
(all has-parts-g-arrow verbinder)))
;;;
;;;
;;;
(defconstant +known-concepts+
'(verbinder
tt-verbinder
it-verbinder
ti-verbinder
ii-verbinder
ci-verbinder
ic-verbinder
ct-verbinder
tc-verbinder
stelle transition netz-kante
netz-kante-mit-kapazitaet
konflikt-stelle
start-stelle end-stelle normale-stelle
stelle-mit-kapazitaet
petri-netz
g-circle
g-line
g-rectangle
g-arrow
g-polygon
g-spline-chain
g-directed-spline-chain
g-spline-polygon
g-chain
g-directed-chain
g-text
g-point
))
(defconstant +known-roles+
'(
spatial-relation
in-relation-with-objects
disjoint-with
touching-objects
intersects-objects
covers-objects
covered-by-object
contains-objects
contained-in-objects
directly-contains-objects
directly-contained-by-object
linked-over-with
start-linked-over-with
end-linked-over-with
points-related-with
startpoint-related-with
endpoint-related-with
linker-objects
start-linker-objects
end-linker-objects
has-parts
has-parts-g-circle
has-parts-g-rectangle
has-parts-g-arrow
part-of
filled-bool
radius-real
text-string
))
| 15,809 | Common Lisp | .lisp | 448 | 27.941964 | 98 | 0.59595 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 69600118510275ed049f18f67c49272739b66dbc18f165c28e07de99af27bccd | 11,221 | [
-1
] |
11,222 | haarslev1.lisp | lambdamikel_GenEd/src/knowledge/haarslev1.lisp | ;;;-*- Mode: Lisp; Package: PJ -*-
(in-package :pj)
(cl-startup)
(setf *krss-verbose* nil)
;----------------------------------------------------------------
(defmacro defprimitive (name expr)
`(define-primitive-concept ,name ,expr))
(defmacro defdisjoint (name expr grouping)
`(define-disjoint-primitive-concept ,name ,grouping ,expr))
(defmacro defconcept (name expr)
`(define-concept ,name ,expr))
(defun cl-filler (derived-object role &optional remove-elem)
(let ((fillers (remove remove-elem (cl-fillers derived-object role)
:test #'eq)))
(when (second fillers)
(cerror "Return only first filler"
"Attribute ~S holds more than 1 filler for ~S: ~S"
role derived-object fillers))
(first fillers)))
(defun close-all-subroles (role &key exceptions
(inds (cl-concept-instances @pj-thing)))
(unless (member role exceptions :test #'eq)
(close-all-roles (cl-role-children role) inds exceptions)
(dolist (role (cl-role-children role))
(close-all-subroles role :exceptions exceptions :inds inds))))
(defun close-all-roles (roles
&optional (inds (cl-concept-instances @pj-thing))
(exceptions nil))
(dolist (role roles)
(unless (member role exceptions :test #'eq)
(dolist (ind inds)
(unless (cl-ind-closed-role? ind role)
(cl-ind-close-role ind role))))))
(defun find-possible-subsumees (inds)
(dolist (ind inds)
(let* ((parents (cl-ind-parents ind))
(children (delete nil (mapcar #'cl-concept-children parents))))
(when children
(format t "~&Individual ~S may be further specialized to ~S"
ind children)))))
;----------------------------------------------------------------
(defprimitive geo-thing classic-thing)
(defprimitive atleast-1d geo-thing)
(defprimitive atmost-1d geo-thing)
(defdisjoint 0d-object atmost-1d geo-objects)
(defdisjoint 1d-object (and atleast-1d atmost-1d) geo-objects)
(defdisjoint 2d-object atleast-1d geo-objects)
(cl-define-primitive-role 'view :attribute t)
(cl-define-primitive-role 'position :attribute t)
(cl-define-primitive-role 'size :attribute t)
;----------------------------------------------------------------
(cl-define-primitive-role 'spatial-relation)
(cl-define-primitive-role 'touching :parent 'spatial-relation
:inverse 'touching)
(cl-define-primitive-role 'overlapping :parent 'spatial-relation
:inverse 'overlapping)
(cl-define-primitive-role 'crossing :parent 'spatial-relation
:inverse 'crossing)
(cl-define-primitive-role 'containing :parent 'spatial-relation
:inverse 'inside
:inverse-parent 'spatial-relation)
(cl-define-primitive-role 'directly-containing :parent 'containing
:inverse 'directly-inside
:inverse-parent 'inside)
(cl-define-primitive-role 'covering :parent 'directly-containing
:inverse 'covered-by
:inverse-parent 'directly-inside)
;----------------------------------------------------------------
(defun compute-directly-inside (ind role)
(declare (ignore role))
(let* ((i-fillers (cl-fillers ind @inside))
(di-fillers (cl-fillers ind @directly-inside))
(l (1- (length i-fillers))))
(or di-fillers
(if (zerop l)
i-fillers
(list
(or
(find-if #'(lambda (x) (= l (length (cl-fillers x @inside))))
i-fillers)
(break "NIL as filler computed for directly-inside")))))))
(cl-add-filler-rule 'compute-directly-inside @geo-thing @directly-inside
#'compute-directly-inside
:filter '(and (at-least 1 inside)
(test-c cl-test-closed-roles? (inside))))
;----------------------------------------------------------------
(cl-define-primitive-role 'touching-atleast-1d :parent 'touching)
(cl-define-primitive-role 'touching-1d :parent 'touching-atleast-1d)
(cl-define-primitive-role 'touching-2d :parent 'touching-atleast-1d)
;----------------------------------------------------------------
(defconcept attached-1d
(and 1d-object
(at-least 2 touching)
(at-most 4 touching)))
(defconcept end-1d
(and attached-1d
(at-most 3 touching)
(at-most 1 touching-1d)
(some touching-atleast-1d)))
(defconcept middle-1d
(and attached-1d
(all touching atmost-1d)
(exactly 2 touching-1d)))
(defconcept simple-line
(and end-1d
(exactly 2 touching)
(all touching 2d-object)))
(defun to-end-1d* (from next)
(if (not next)
from
(to-end-1d*
next
(first (remove from (cl-fillers next @touching-1d))))))
(defun to-end-1d (from role)
(declare (ignore role))
(cond
((not (endp (cl-fillers from @to-end-1d)))
nil)
((cl-instance? from @simple-line)
(list from))
(t (list (to-end-1d*
from (first (cl-fillers from @touching-1d)))))))
(cl-define-primitive-role 'to-end-1d :inverse 'to-end-1d
:attribute t)
(cl-add-filler-rule 'find-end-1d @end-1d @to-end-1d
#'to-end-1d)
(defconcept line-handle
(and end-1d (some to-end-1d)))
(defconcept link-handle
(and line-handle
(exactly 1 touching-2d)))
(defconcept docking-2d
(and 2d-object
(some touching-1d)
(all touching-1d line-handle)))
(defun linked-2ds (from role)
(declare (ignore role))
(mapcan #'(lambda (x)
(let ((end (cl-filler x @to-end-1d)))
(when end
(let ((2d (cl-filler end @touching-2d from)))
(when 2d
(list 2d))))))
(cl-fillers from @touching-1d)))
(cl-define-primitive-role 'linked-2ds :inverse 'linked-2ds)
(cl-add-filler-rule 'find-linked-2d @docking-2d @linked-2ds
#'linked-2ds)
(defconcept linked-2d
(and 2d-object (some linked-2ds)))
(defconcept line-connector
(and link-handle (all touching-2d linked-2d)))
#|
(cl-clear-kb)
(mapc #'(lambda (x) (cl-create-ind x '2d-object)) '(r1 r2))
(mapc #'(lambda (x) (cl-create-ind x '1d-object)) '(l1 l2 l3))
(cl-ind-add @r1 '(and 2d-object
(fills touching-1d l1)))
(cl-ind-add @r2 '(and 2d-object
(fills touching-1d l3)))
(cl-ind-add @l1
'(and 1d-object
(fills touching-2d r1)
(fills touching-1d l2)))
(cl-ind-add @l2
'(and 1d-object
(fills touching-1d l1)
(fills touching-1d l3)))
(cl-ind-add @l3
'(and 1d-object
(fills touching-2d r2)
(fills touching-1d l2)))
(close-all-subroles (list @l1 @l2 @l3 @r1 @r2) @touching)
(mapcar #'(lambda (x) (list x (cl-ind-parents (cl-named-ind x))))
'(r1 r2 l1 l2 l3))
(mapc #'(lambda (x) (cl-create-ind x '2d-object)) '(r3 r4))
(cl-create-ind 'l4 '1d-object)
(cl-ind-add @r3 '(and 2d-object (fills touching-1d l4)))
(cl-ind-add @r4 '(and 2d-object (fills touching-1d l4)))
(cl-ind-add @l4 '(and 1d-object
(fills touching-2d r3)
(fills touching-2d r4)))
(close-all-subroles (list @l4 @r3 @r4) @touching)
(mapcar #'(lambda (x) (list x (cl-ind-parents (cl-named-ind x))))
'(r3 r4 l4))
(cl-exp-subsumes-ind @linked-2d @r1)
|#
| 7,546 | Common Lisp | .lisp | 186 | 32.768817 | 74 | 0.5783 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 1af492d0e6e3528370e10703bb1729aa1472d82030b3711d311cad6b04338e92 | 11,222 | [
-1
] |
11,223 | haarslev2.lisp | lambdamikel_GenEd/src/knowledge/haarslev2.lisp | ;;;-*- Mode: Lisp; Package: pj -*-
(in-package :pj)
;(load "pj:cl-geometry-db-5.lisp")
(defprimitive pj-thing geo-thing)
(defprimitive pj-element (and pj-thing atleast-1d))
;----------------------------------------------------------------
(defun cl-inv-role-name (role)
(let ((inv (cl-role-inverse (cl-named-role role))))
(when inv
(cl-role-name inv))))
(defmacro defqualifiedsubrole (role
qualification
&key
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
parent
(inverse-parent (or (cl-inv-role-name parent)
role))
break)
`(progn
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-INV-FILLER-RULE"))
(cl-named-concept ',qualification)
(cl-named-role ',inv-name)
#'(lambda (ind role)
(declare (ignore role))
(when ,break
(break "in filler rule of ~A" ',inv-name))
(or
(cl-fillers ind (cl-named-role ',inverse-parent))
(break "NIL as filler computed for ~A"
',inv-name)))
:filter
'(and (at-least 1 ,inverse-parent)
(test-c cl-test-closed-roles? (,role))))))
;----------------------------------------------------------------
(defmacro retrieve-rel (rel)
`(loop for di in (cl-concept-instances @pj-thing)
for fillers = (mapcar #'cl-name (cl-fillers di ,rel))
when fillers collect (list (cl-name di) fillers)))
;----------------------------------------------------------------
(defprimitive point (and 0d-object pj-thing))
(defprimitive start-point point)
(defprimitive end-point point)
(defprimitive link (and 1d-object pj-element))
(defprimitive arrow (and 1d-object pj-element))
(defprimitive region (and 2d-object pj-element))
(defprimitive text (and 2d-object pj-element))
(cl-define-primitive-role 'text-value :attribute t)
(cl-define-primitive-role 'has-parts :inverse 'part-of
:inverse-attribute t)
;----------------------------------------------------------------
(defqualifiedsubrole touching point :parent touching)
(defqualifiedsubrole touching link :parent touching-1d)
;(defqualifiedsubrole touching arrow :parent touching-1d)
(defqualifiedsubrole touching region :parent touching-2d)
(defqualifiedsubrole touching text :parent touching-2d)
(defqualifiedsubrole containing region
:parent directly-containing :inverse-parent directly-inside)
(defqualifiedsubrole containing text
:parent directly-containing :inverse-parent directly-inside)
(defqualifiedsubrole covering region :parent covering)
;----------------------------------------------------------------
(defun cl-ind-add-hook-vh (ind)
(when (cl-ind-closed-role? ind @touching)
(cl-fillers ind @touching)))
;----------------------------------------------------------------
(defconcept empty-region
(and region (none containing)))
(defconcept port
(and empty-region (at-most 1 touching-region)))
(defconcept term
(and region
(none covered-by)
(all touching-region port)
(all touching-1d arrow)
(all touching-point end-point)))
(defconcept reference-port
(and port
(exactly 1 covered-by)
(all covered-by term)
(at-most 2 touching)
(none touching-region)
(at-most 1 touching-link)
(at-most 1 touching-point)))
(defconcept argument-port
(and port
(none covered-by)
(exactly 1 touching-region)
(all touching-region term)))
(defconcept single-port
(and port
(none covered-by)
(none touching-region)))
(defconcept empty-port
(and argument-port (none touching-link)))
(defconcept linked-port
(and port linked-2d))
(defconcept linked-argument-port
(and linked-port argument-port))
(defconcept data-term
(and term
(exactly 1 covering)
(all covering reference-port)
(none touching-1d)
(none touching-point)))
(defconcept constant
(and data-term
(at-most 1 containing-region)
(exactly 1 containing-text)
(none touching)))
(defconcept term-string
(and text
(some directly-inside)
(all directly-inside term)))
(defconcept value-text
(and term-string
(exactly 1 directly-inside)
(all directly-inside data-term)))
(defconcept term-list
(and data-term
(at-most 2 touching-region)
(at-most 1 containing-text)
(all containing-text value-text)
(at-most 1 containing-region)))
(defconcept empty-term-list
(and term-list
(none touching-region)
(none containing-text)))
(defconcept label
(and region
(exactly 1 containing)
(all containing text)
(none touching)))
(defconcept label-text
(and text
(some directly-inside)
(all directly-inside label)))
(defqualifiedsubrole containing label :parent containing-region)
(defconcept labeled-term
(and term
(exactly 1 containing-label)
(some touching-region)
(all touching-region argument-port)))
(defconcept rule-term
(and term (none covering-region)))
(defconcept primitive-relation
(and rule-term
labeled-term
(exactly 2 containing)))
(defconcept rule-body
(and rule-term
(all touching-region argument-port)
(some touching-region)))
(defconcept body-arg-port
(and argument-port
(all touching-region rule-body)))
(defconcept rule
(and rule-body
(exactly 1 inside)
(all inside rule-body)
#|(all has-asks asker-port)|#))
(defconcept function-term
(and data-term
labeled-term
(exactly 3 containing)
(exactly 1 directly-inside)
(all directly-inside rule)))
(defqualifiedsubrole crossing rule :parent crossing)
(defconcept call-arrow
(and arrow
(some crossing-rule)))
(defconcept start-of-call-arrow
(and start-point
(some part-of)
(all part-of call-arrow)))
(defconcept agent-call
(and rule-body
(exactly 1 directly-inside)
(all directly-inside rule)
(exactly 1 crossing)
(all crossing call-arrow)
(exactly 1 containing)
(all containing start-of-call-arrow)))
(defqualifiedsubrole containing rule :parent containing-region)
(defconcept agent
(and rule-body
(some containing-rule)
(none inside)
(at-most 1 touching-text)))
(defconcept agent-name
(and text
(exactly 1 touching)
(all touching agent)))
(defconcept guard-test
(and primitive-relation
(exactly 1 inside)
(all inside agent)))
(defconcept recursive-call-arrow
(and call-arrow
(exactly 1 covered-by)
(all covered-by agent)))
(defconcept other-call-arrow
(and call-arrow
(exactly 1 touching)
(all touching agent)))
(defqualifiedsubrole touching argument-port
:name touching-arg-port :parent touching-region)
(defconcept channel
(and arrow
(exactly 2 touching)
(all touching port)
(some touching-arg-port)
(all touching-arg-port argument-port)))
(defconcept end-of-channel
(and end-point
(some part-of)
(all part-of channel)))
(defconcept attached-port
(and port
(some touching-point)
(all touching-point end-of-channel)))
;----------------------------------------------------------------
(defun reaching-to* (from next &optional (fillers nil))
(cond
((cl-instance? next @reference-port)
(or
(mapcan #'(lambda (arg) (reaching-to* next arg (list* next fillers)))
(cl-fillers (cl-filler next @covered-by) @touching-region))
(list* next fillers)))))
(defun reaching-to (from role)
(declare (ignore role))
(let ((linked-ports (cl-fillers from @linked-2ds)))
(mapcan #'(lambda (next) (reaching-to* from next)) linked-ports)))
#| (cond
((and (not (rest linked-ports))
(cl-instance? (first linked-ports) @reference-port)
((cl-instance? from @simple-line)
(list from))
(t (list (to-end-1d*
from (first (cl-fillers from @touching-1d)))))))|#
(cl-define-primitive-role 'reaching-to :inverse 'reachable-from)
(cl-add-filler-rule 'find-reaching-to @linked-argument-port @reaching-to
#'reaching-to)
;----------------------------------------------------------------
(defconcept reachable-ref-port
(and linked-port
reference-port
(exactly 1 reachable-from)
(all reachable-from body-arg-port)))
(defqualifiedsubrole touching attached-port :parent touching-region)
(defconcept ask-channel
(and channel
(some touching-arg-port)
(all touching-arg-port argument-port)
(some touching-attached-port)
(all touching-attached-port attached-port)))
(defprimitive attached-or-linked-port port)
(cl-add-rule 'add-attached-or-port @attached-port 'attached-or-linked-port)
(cl-add-rule 'add-linked-or-port @linked-port 'attached-or-linked-port)
(defconcept ask-data-term
(and data-term
(exactly 1 inside)
(all inside rule-body)
(all covering reachable-ref-port)
(all touching-region attached-or-linked-port)))
(defconcept data-asking-arg-port
(and linked-port
argument-port
(some reaching-to)
(all reaching-to reachable-ref-port)))
(defconcept start-of-channel
(and start-point
(some part-of)
(all part-of channel)))
(defconcept tell-asking-arg-port
(and argument-port
(some touching-point)
(all touching-point start-of-channel)))
(defprimitive asking-arg-port argument-port)
(cl-add-rule 'add-data-asking-arg-port
@data-asking-arg-port 'asking-arg-port)
(cl-add-rule 'add-tell-asking-arg-port
@tell-asking-arg-port 'asking-arg-port)
;----------------------------------------------------------------
(defun close-pj-roles ()
(close-all-roles (list* @covering @covered-by
(cl-role-children @spatial-relation)))
(close-all-subroles @inside :exceptions (list @containing-rule-inverse))
(close-all-subroles @containing :exceptions (list @containing-rule))
(close-all-roles (cl-role-children @touching))
(close-all-subroles @touching-atleast-1d
:exceptions (list @touching-attached-port))
(close-all-subroles @touching-region-inverse
:exceptions (list @touching-attached-port-inverse))
(close-all-roles (list @touching-attached-port
@touching-attached-port-inverse))
(close-all-subroles @crossing)
(close-all-roles (list @containing-rule @containing-rule-inverse))
(close-all-roles (list @reachable-from @reaching-to)))
#|
(defun set-subroles1 ()
(compute-directly-inside-fillers)
(dolist (ind (cl-concept-instances @pj-thing))
(set-touching-subroles ind (cl-fillers ind @touching))
(set-containing-subroles ind (cl-fillers ind @directly-containing))
(set-covering-subroles ind (cl-fillers ind @covering))))
(defun compute-directly-inside-fillers ()
(dolist (ind (cl-concept-instances
(cl-normalize-concept
(cl-parse-expression '(and pj-thing (at-least 1 inside))))))
(let ((fillers (cl-fillers ind @inside)))
(unless (cl-fillers ind @directly-inside)
(add-directly-inside
(sort (list* ind (copy-list fillers)) #'>
:key #'(lambda (x) (length (cl-fillers x @inside)))))))))
(defun add-directly-inside (chain)
(mapl #'(lambda (l)
(let ((a (first l))
(b (second l)))
(when (and b (not (cl-fillers a @directly-inside)))
(classic:cl-ind-add
a `(fills directly-inside ,(classic:cl-ind-name b))))))
chain))
(defun set-touching-subroles (ind fillers)
(dolist (filler fillers)
(let ((fname (cl-ind-name filler)))
(cond ((cl-instance? filler @point)
(cl-ind-add ind `(fills touching-point ,fname)))
((cl-instance? filler @link)
(cl-ind-add ind `(fills touching-link ,fname)))
((cl-instance? filler @region)
(cl-ind-add ind `(fills touching-region ,fname))
(when (cl-instance? filler @argument-port)
(cl-ind-add ind `(fills touching-arg-port ,fname)))
(when (cl-instance? filler @attached-port)
(cl-ind-add ind `(fills touching-attached-port ,fname))))
((cl-instance? filler @text)
(cl-ind-add ind `(fills touching-text ,fname)))))))
(defun set-containing-subroles (ind fillers)
(dolist (filler fillers)
(let ((fname (cl-ind-name filler)))
(cond ((cl-instance? filler @region)
(cl-ind-add ind `(fills containing-region ,fname)))
((cl-instance? filler @text)
(cl-ind-add ind `(fills containing-text ,fname)))
((cl-instance? filler @label)
(cl-ind-add ind `(fills containing-label ,fname)))))))
(defun set-covering-subroles (ind fillers)
(dolist (filler fillers)
(let ((fname (cl-ind-name filler)))
(cond ((cl-instance? filler @region)
(cl-ind-add ind `(fills covering-region ,fname)))))))
(defun set-subroles2 ()
(dolist (ind (cl-concept-instances @pj-thing))
(set-containing-subroles2 ind (cl-fillers ind @directly-containing))
(set-crossing-subroles ind (cl-fillers ind @crossing))))
(defun set-containing-subroles2 (ind fillers)
(dolist (filler fillers)
(let ((fname (cl-ind-name filler)))
(cond ((cl-instance? filler @rule)
(cl-ind-add ind `(fills containing-rule ,fname)))))))
(defun set-crossing-subroles (ind fillers)
(dolist (filler fillers)
(let ((fname (cl-ind-name filler)))
(cond ((cl-instance? filler @rule)
(cl-ind-add ind `(fills crossing-rule ,fname)))))))
|#
| 14,822 | Common Lisp | .lisp | 379 | 30.894459 | 79 | 0.598049 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | c76598787842f22e38210e3a3c5985b0f75ad44f450a47f1d7a757f98273fd42 | 11,223 | [
-1
] |
11,224 | knowledge2.lisp | lambdamikel_GenEd/src/knowledge/knowledge2.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: Knowledge; Base: 10 -*-
(in-package knowledge)
(cl-reader-init)
(cl-clear-kb)
(cl-startup)
(setf *krss-verbose* nil)
(cl-set-classic-warn-mode t)
;----------------------------------------------------------------
;----------------------------------------------------------------
(defmacro defprimitive (name expr)
`(define-primitive-concept ,name ,expr))
(defmacro defdisjoint (name expr grouping)
`(define-disjoint-primitive-concept ,name ,grouping ,expr))
(defmacro defconcept (name expr)
`(define-concept ,name ,expr))
(defun cl-filler (derived-object role &optional remove-elem)
(let ((fillers (remove remove-elem (cl-fillers derived-object role)
:test #'eq)))
(when (second fillers)
(cerror "Return only first filler"
"Attribute ~S holds more than 1 filler for ~S: ~S"
role derived-object fillers))
(first fillers)))
(defun close-all-subroles (role &key exceptions
(inds (cl-concept-instances @pj-thing)))
(unless (member role exceptions :test #'eq)
(close-all-roles (cl-role-children role) inds exceptions)
(dolist (role (cl-role-children role))
(close-all-subroles role :exceptions exceptions :inds inds))))
(defun close-all-roles (roles
&optional (inds (cl-concept-instances @pj-thing))
(exceptions nil))
(dolist (role roles)
(unless (member role exceptions :test #'eq)
(dolist (ind inds)
(unless (cl-ind-closed-role? ind role)
(cl-ind-close-role ind role))))))
(defun find-possible-subsumees (inds)
(dolist (ind inds)
(let* ((parents (cl-ind-parents ind))
(children (delete nil (mapcar #'cl-concept-children parents))))
(when children
(format t "~&Individual ~S may be further specialized to ~S"
ind children)))))
;----------------------------------------------------------------
;;;
;;;
;;;
(defun cl-inv-role-name (role)
(let ((inv (cl-role-inverse (cl-named-role role))))
(when inv
(cl-role-name inv))))
(defmacro defqualifiedsubrole (role
qualification
&key
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
(parent role)
(inverse-parent (or (cl-inv-role-name parent)
role))
break)
`(progn
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-INV-FILLER-RULE"))
(cl-named-concept ',qualification)
(cl-named-role ',inv-name)
#'(lambda (ind role)
(declare (ignore role))
(when ,break
(break "in filler rule of ~A" ',inv-name))
(or
(cl-fillers ind (cl-named-role ',inverse-parent))
(break "NIL as filler computed for ~A"
',inv-name)))
:filter
'(and (at-least 1 ,inverse-parent)
(test-c cl-test-closed-roles? (,role))))))
;;;
;;;
;;;
;----------------------------------------------------------------
(cl-define-primitive-role 'spatial-relation)
(cl-define-primitive-role 'in-relation-with-objects
:parent 'spatial-relation)
(cl-define-primitive-role 'disjoint-with :inverse 'disjoint-with
:parent 'spatial-relation)
(cl-define-primitive-role 'touching-objects :inverse 'touching-objects
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-objects :inverse 'intersects-objects
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-0-objects :inverse 'intersects-0-objects
:parent 'intersects-objects)
(cl-define-primitive-role 'intersects-1-objects :inverse 'intersects-1-objects
:parent 'intersects-objects)
(cl-define-primitive-role 'intersects-2-objects :inverse 'intersects-2-objects
:parent 'intersects-objects)
;;; spatial-relation
;;; / \
;;; in-rel.w. disj.w.
;;; / | \
;;; / | \
;;; / | \
;;; touching inters. contains
;;; /|\ |
;;; / | \ direc.contains
;;; 0 1 2 |
;;; covers
(cl-define-primitive-role 'contains-objects :inverse 'contained-in-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'directly-contains-objects :inverse 'directly-contained-by-object
:parent 'contains-objects
:inverse-parent 'contained-in-objects)
(cl-define-primitive-role 'covers-objects :inverse 'covered-by-object
:parent 'directly-contains-objects
:inverse-parent 'directly-contained-by-object)
;;;
;;; In diesen Rollen steht, mit wem das Ind. verbunden ist, und ueber welches Ende des Pfeiles:
;;;
;;; linked-over-with
;;; / \
;;; start-link.o.w. end-link.o.w. 0 ----> # : start-l.o.w.(0,#),
;;; end-l.o.w.(#,0),
;;; l.o.w.(#,0) /\ l.o.w(0,#).
(cl-define-primitive-role 'linked-over-with :inverse 'linked-over-with
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linked-over-with :inverse 'end-linked-over-with
:parent 'linked-over-with
:inverse-parent 'linked-over-with)
;;;
;;; Hier werden die Linker eingetragen: 0 -----> # : linker-objects(A,L), linker-objects(B,L).
;;; A L B
(cl-define-primitive-role 'linker-objects :inverse 'points-related-with
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linker-objects :inverse 'startpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
(cl-define-primitive-role 'end-linker-objects :inverse 'endpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
;;;
;;;
;;;
;;; Rollen eines Linkers: points-related-with
;;; / \ 0 ----> # : s.r.w.(L,A), e.r.w.(L,B)
;;; startpoint-rel.-w. endpoint-rel.-w. A L B
#|
(cl-define-primitive-role 'points-related-with :inverse 'linker-objects
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'startpoint-related-with :inverse 'endpoint-related-with
:parent 'points-related-with
:inverse-parent 'points-related-with)
|#
;;;
;;; Fuer Composite-Things:
;;;
(cl-define-primitive-role 'has-parts :inverse 'part-of
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
;;;
;;; Fuer Directed-Elements:
;;;
(cl-define-primitive-role 'has-points
:parent 'has-parts
:inverse 'part-of-directed-element
:inverse-parent 'part-of)
(cl-define-primitive-role 'has-startpoint
:parent 'has-points
:inverse 'startpoint-part-of-directed-element
:inverse-parent 'part-of-directed-element)
(cl-define-primitive-role 'has-endpoint
:parent 'has-points
:inverse 'endpoint-part-of-directed-element
:inverse-parent 'part-of-directed-element)
;;;
;;;
;;;
(cl-define-primitive-role 'filled-bool :attribute t)
(cl-define-primitive-role 'radius-real :attribute t)
(cl-define-primitive-role 'text-string :attribute t)
(cl-define-primitive-role 'belongs-to-clos-object :attribute t)
;;;
;;;
;;;
(cl-define-primitive-concept 'gened-thing 'classic-thing)
(cl-define-disjoint-primitive-concept 'basic-thing 'gened-thing 'basic-or-comp)
(cl-define-disjoint-primitive-concept 'composite-thing 'gened-thing 'basic-or-comp)
(cl-define-primitive-concept '0d 'gened-thing)
(cl-define-primitive-concept '1d 'gened-thing)
(cl-define-primitive-concept '2d 'gened-thing)
(cl-define-primitive-concept 'at-least-1d '(and 1d 2d))
(cl-define-primitive-concept 'at-most-1d '(and 0d 1d))
;;;
;;;
;;;
(cl-define-primitive-concept 'directed-element '(and 1d basic-thing))
(cl-define-disjoint-primitive-concept 'g-circle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-line '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-arrow 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-rectangle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-spline-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-text '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-point '(and 0d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'info-point '(and 0d basic-thing) 'type)
;;;
;;;
;;;
(defqualifiedsubrole linked-over-with g-circle
:parent linked-over-with :inverse-parent linked-over-with)
(defqualifiedsubrole linked-over-with g-rectangle
:parent linked-over-with :inverse-parent linked-over-with)
(defqualifiedsubrole has-parts g-circle
:parent has-parts :inverse-parent part-of)
(defqualifiedsubrole has-parts g-rectangle
:parent has-parts :inverse-parent part-of)
(defqualifiedsubrole has-parts g-arrow
:parent has-parts :inverse-parent part-of)
(defqualifiedsubrole touching-objects directed-element
:parent touching-objects :inverse-parent touching-objects)
;;;
;;; Diese Konzepte sind wohl von generellem Nutzen:
;;;
(define-concept nur-beruehrende-objekte
(and
basic-thing
(none contained-in-objects)
(some touching-objects)
(none has-parts)))
#|
(define-concept verbinder
(and
directed-element
(exactly 2 points-related-with)))
(defun subset? (ind sym1 sym2)
(let* ((role1 (cl-named-role sym1))
(role2 (cl-named-role sym2))
(fillers1 (cl-fillers ind role1))
(fillers2 (cl-fillers ind role2)))
(if (and (cl-ind-closed-role? ind role1)
(cl-ind-closed-role? ind role2))
(null (set-difference
fillers2 fillers1))
'?)))
(defun member? (ind sym1 sym2)
(let* ((role1 (cl-named-role sym1))
(role2 (cl-named-role sym2))
(fillers1 (cl-fillers ind role1))
(fillers2 (cl-fillers ind role2)))
(if (and (cl-ind-closed-role? ind role1)
(cl-ind-closed-role? ind role2))
(if (> (length fillers1) 1)
nil
(member (first fillers1) fillers2))
'?)))
(defun not-member? (ind sym1 sym2)
(let ((member (member? ind sym1 sym2)))
(case member
(? '?)
(t nil)
(nil t))))
(cl-define-concept 'tt-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with
touching-objects)
(test-c member?
endpoint-related-with
touching-objects)))
(cl-define-concept 'it-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with
intersects-objects)
(test-c member?
endpoint-related-with
touching-objects)))
(cl-define-concept 'ti-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with
touching-objects)
(test-c member?
endpoint-related-with
intersects-objects)))
(cl-define-concept 'ii-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with intersects-objects)
(test-c member?
endpoint-related-with intersects-objects)))
(cl-define-concept 'ct-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with covered-by-object)
(test-c member?
endpoint-related-with touching-objects)))
(cl-define-concept 'tc-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with touching-objects)
(test-c member?
endpoint-related-with covered-by-object)))
(cl-define-concept 'ci-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with covered-by-object)
(test-c member?
endpoint-related-with intersects-objects)
(test-c not-member?
endpoint-related-with touching-objects)))
(cl-define-concept 'ic-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with intersects-objects)
(test-c member?
endpoint-related-with covered-by-object)))
|#
(define-concept verbinder-punkt
(and
info-point
(exactly 1 part-of-directed-element)))
(define-concept t-verbinder-punkt
(and
verbinder-punkt
(exactly 1 touching-objects)))
(define-concept c-verbinder-punkt
(and
verbinder-punkt
(exactly 1 covered-by-object)))
(define-concept i-verbinder-punkt
(and
verbinder-punkt
(exactly 1 directly-contained-by-object)))
(define-concept verbinder
(and
directed-element
(exactly 2 points-related-with)))
(define-concept tt-verbinder
(and
verbinder
(all has-points t-verbinder-punkt)))
(define-concept ii-verbinder
(and
verbinder
(all has-points i-verbinder-punkt)))
(define-concept it-verbinder
(and
verbinder
(all has-startpoint i-verbinder-punkt)
(all has-endpoint t-verbinder-punkt)))
(define-concept ti-verbinder
(and
verbinder
(all has-startpoint t-verbinder-punkt)
(all has-endpoint i-verbinder-punkt)))
(define-concept ct-verbinder
(and
verbinder
(all has-startpoint c-verbinder-punkt)
(all has-endpoint t-verbinder-punkt)))
(define-concept tc-verbinder
(and
verbinder
(all has-startpoint t-verbinder-punkt)
(all has-endpoint c-verbinder-punkt)))
(define-concept ci-verbinder
(and
verbinder
(all has-startpoint c-verbinder-punkt)
(all has-endpoint i-verbinder-punkt)))
(define-concept ic-verbinder
(and
verbinder
(all has-startpoint i-verbinder-punkt)
(all has-endpoint c-verbinder-punkt)))
;;;;
;;;;
;;;;
#|
(defun string-is-integer-p (string)
(let ((liste (coerce string 'list)))
(every #'(lambda (char)
(and (char<= char #\9)
(char>= char #\0)))
liste)))
|#
(defun string-is-integer-p (string)
(integerp
(read-from-string string)))
(cl-define-concept 'kapazitaets-label
'(and
g-text
(at-least 1 intersects-objects)
(all text-string
(and (test-h string-is-integer-p)))))
(defqualifiedsubrole intersects-objects kapazitaets-label
:inv-name intersects-objects-kapazitaets-label
:parent intersects-objects :inverse-parent intersects-objects)
;;;
;;;
;;;
(define-concept stelle-oder-transition
(and
nur-beruehrende-objekte
(all touching-objects-directed-element tt-verbinder)))
(define-concept stelle?
(and
g-circle
stelle-oder-transition))
(define-concept transition?
(and
g-rectangle
stelle-oder-transition))
;;;
;;;
;;;
(define-concept stelle
(and
stelle?
(all linked-over-with transition?)))
(define-concept konflikt-stelle
(and
stelle
(at-least 2 end-linked-over-with)))
(define-concept start-stelle
(and
stelle
(none start-linked-over-with)))
(define-concept end-stelle
(and
stelle
(none end-linked-over-with)))
(define-concept normale-stelle
(and
stelle
(some start-linked-over-with)
(some end-linked-over-with)))
(define-concept stelle-mit-kapazitaet
(and
stelle
(exactly 1 intersects-objects-kapazitaets-label)))
(cl-define-concept 'marke
'(and
g-circle
(all contained-in-objects stelle)
(fills filled-bool t)
(all radius-real
(and number
(min 2.0)
(max 10.0)))))
(define-concept stelle-mit-marken
(and
stelle
(some contains-objects)
(all contains-objects marke)))
(define-concept transition
(and
transition?
(at-least 2 linked-over-with)
(all linked-over-with stelle?)))
(define-concept netz-kante
(and
tt-verbinder
(all touching-objects stelle-oder-transition)))
(define-concept netz-kante-mit-kapazitaet
(and
netz-kante
(exactly 1 intersects-objects-kapazitaets-label)))
;;;
;;;
;;;
(defun genug-input-marken? (ind)
(let* ((end-linker (cl-named-role 'end-linker-objects)))
(every #'(lambda (end-linker)
(let* ((text-ind
(first
(cl-fillers
end-linker
(cl-named-role 'intersects-objects-kapazitaets-label))))
(stelle
(first
(cl-fillers
end-linker
(cl-named-role 'startpoint-related-with))))
(kap
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string)))))
(marken
(length
(cl-fillers
stelle
(cl-named-role 'contains-objects)))))
(not (minusp (- marken kap)))))
(cl-fillers ind end-linker))))
(defun genug-output-marken? (ind)
(let* ((start-linker (cl-named-role 'start-linker-objects)))
(every #'(lambda (start-linker)
(let* ((text-ind
(first
(cl-fillers
start-linker
(cl-named-role 'intersects-objects-kapazitaets-label))))
(stelle
(first
(cl-fillers
start-linker
(cl-named-role 'endpoint-related-with))))
(kap
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string)))))
(marken
(length
(cl-fillers
stelle
(cl-named-role 'contains-objects))))
(stellen-text-ind
(first
(cl-fillers
stelle
(cl-named-role 'intersects-objects-kapazitaets-label))))
(stellen-kap
(read-from-string
(first
(cl-fillers
stellen-text-ind
(cl-named-role 'text-string))))))
(<= (+ marken kap) stellen-kap)))
(cl-fillers ind start-linker))))
(cl-define-concept 'l-aktive-transition
'(and
transition
(all start-linked-over-with
(and
stelle-mit-marken
stelle-mit-kapazitaet))
(all end-linker-objects netz-kante-mit-kapazitaet)
(test-c cl-test-closed-roles? (end-linker-objects start-linked-over-with))
(test-c genug-input-marken?)))
(cl-define-concept 'r-aktive-transition
'(and
transition
(all end-linked-over-with
(and
stelle-mit-marken
stelle-mit-kapazitaet))
(all start-linker-objects netz-kante-mit-kapazitaet)
(test-c cl-test-closed-roles? (start-linker-objects end-linked-over-with))
(test-c genug-output-marken?)))
(cl-define-concept 'aktive-transition
'(and
l-aktive-transition
r-aktive-transition))
;;;
;;;
;;;
(define-concept petri-netz
(and
composite-thing
(at-least 5 has-parts) ; kleinstes Netz: 0 -> # -> 0
(all has-parts-g-circle stelle)
(all has-parts-g-rectangle transition)
(all has-parts-g-arrow verbinder)))
;;;
;;;
;;;
(defconstant +known-concepts+
'(verbinder
tt-verbinder
ii-verbinder
ti-verbinder
it-verbinder
ci-verbinder
ic-verbinder
tc-verbinder
ct-verbinder
stelle transition netz-kante
l-aktive-transition
r-aktive-transition
aktive-transition
netz-kante-mit-kapazitaet
marke
konflikt-stelle
start-stelle end-stelle normale-stelle
kapazitaets-label
stelle-mit-kapazitaet
stelle-mit-marken
petri-netz
g-circle
g-line
g-rectangle
g-arrow
g-polygon
g-spline-chain
g-directed-spline-chain
g-spline-polygon
g-chain
g-directed-chain
g-text
g-point
info-point
))
(defconstant +library-concepts+
`(verbinder
tt-verbinder
ii-verbinder
ti-verbinder
it-verbinder
ci-verbinder
ic-verbinder
tc-verbinder
ct-verbinder
stelle
start-stelle
normale-stelle
end-stelle
marke
transition))
(defconstant +known-roles+
'((
belongs-to-clos-object
spatial-relation
in-relation-with-objects
disjoint-with
touching-objects
intersects-objects
intersects-0-objects
intersects-1-objects
intersects-2-objects
contains-objects
contained-in-objects
directly-contains-objects
directly-contained-by-object
covers-objects
covered-by-object
linked-over-with
start-linked-over-with
end-linked-over-with
points-related-with
startpoint-related-with
endpoint-related-with
linker-objects
start-linker-objects
end-linker-objects
has-points
has-startpoint
has-endpoint
has-parts
part-of
part-of-directed-element
startpoint-part-of-directed-element
endpoint-part-of-directed-element
filled-bool
radius-real
text-string)
(
has-parts-g-circle
has-parts-g-rectangle
has-parts-g-arrow
touching-objects-directed-element-inverse
touching-objects-directed-element
intersects-objects-kapazitaets-label
)))
| 22,896 | Common Lisp | .lisp | 693 | 25.900433 | 98 | 0.615041 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 9cda1ad419354b80117133570bf59df54a60d98a98bdfe6f9003ef4e751ba268 | 11,224 | [
-1
] |
11,225 | knowledge5eng.lisp | lambdamikel_GenEd/src/knowledge/knowledge5eng.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: Knowledge; Base: 10 -*-
(in-package knowledge)
(cl-reader-init)
(cl-clear-kb)
(cl-startup)
(setf *krss-verbose* nil)
(cl-set-classic-warn-mode t)
;----------------------------------------------------------------
(defmacro defprimitive (name expr)
`(define-primitive-concept ,name ,expr))
(defmacro defdisjoint (name expr grouping)
`(define-disjoint-primitive-concept ,name ,grouping ,expr))
(defmacro defconcept (name expr)
`(define-concept ,name ,expr))
(defun cl-filler (derived-object role &optional remove-elem)
(let ((fillers (remove remove-elem (cl-fillers derived-object role)
:test #'eq)))
(when (second fillers)
(cerror "Return only first filler"
"Attribute ~S holds more than 1 filler for ~S: ~S"
role derived-object fillers))
(first fillers)))
(defun close-all-subroles (role &key exceptions
(inds (cl-concept-instances @pj-thing)))
(unless (member role exceptions :test #'eq)
(close-all-roles (cl-role-children role) inds exceptions)
(dolist (role (cl-role-children role))
(close-all-subroles role :exceptions exceptions :inds inds))))
(defun close-all-roles (roles
&optional (inds (cl-concept-instances @pj-thing))
(exceptions nil))
(dolist (role roles)
(unless (member role exceptions :test #'eq)
(dolist (ind inds)
(unless (cl-ind-closed-role? ind role)
(cl-ind-close-role ind role))))))
(defun find-possible-subsumees (inds)
(dolist (ind inds)
(let* ((parents (cl-ind-parents ind))
(children (delete nil (mapcar #'cl-concept-children parents))))
(when children
(format t "~&Individual ~S may be further specialized to ~S"
ind children)))))
;----------------------------------------------------------------
#+:allegro
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun cl-inv-role-name (role)
(let ((inv (cl-role-inverse (cl-named-role role))))
(when inv
(cl-role-name inv))))
(defmacro defqualifiedsubrole (role
qualification
&key
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
(parent role)
(inverse-parent (or (cl-inv-role-name parent)
role))
(specialized-concept t)
break)
`(progn
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-INV-FILLER-RULE"))
,(if specialized-concept
`(cl-named-concept ',qualification)
'(cl-named-concept 'classic-thing))
(cl-named-role ',inv-name)
#'(lambda (ind role)
(declare (ignore role))
(when ,break
(break "in filler rule of ~A" ',inv-name))
(or
(cl-fillers ind (cl-named-role ',inverse-parent))
(break "NIL as filler computed for ~A"
',inv-name)))
:filter
'(and (at-least 1 ,inverse-parent)
(test-c cl-test-closed-roles? (,role))))))
;----------------------------------------------------------------
;;; selbstinverse Basisrelationen
(cl-define-primitive-role 'spatial-relation :inverse 'spatial-relation)
(cl-define-primitive-role 'in-relation-with-objects :inverse 'in-relation-with-objects
:parent 'spatial-relation
:inverse-parent 'spatial-relation)
(cl-define-primitive-role 'disjoint-with :inverse 'disjoint-with
:parent 'spatial-relation
:inverse-parent 'spatial-relation)
(cl-define-primitive-role 'touching-objects :inverse 'touching-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-objects :inverse 'intersects-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-0-objects :inverse 'intersects-0-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
(cl-define-primitive-role 'intersects-1-objects :inverse 'intersects-1-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
(cl-define-primitive-role 'intersects-2-objects :inverse 'intersects-2-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
;;;
;;; spatial-relation
;;; / \
;;; in-rel.w. disj.w.
;;; / | \
;;; / | \
;;; / | \
;;; touching inters. contains
;;; /|\ |
;;; / | \ direc.contains
;;; 0 1 2 |
;;; covers
;----------------------------------------------------------------
;;; nicht-selbstinverse Basisrelationen
(cl-define-primitive-role 'contains-objects :inverse 'contained-in-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'directly-contains-objects :inverse 'directly-contained-by-object
:parent 'contains-objects
:inverse-parent 'contained-in-objects)
(cl-define-primitive-role 'covers-objects :inverse 'covered-by-object
:parent 'directly-contains-objects
:inverse-parent 'directly-contained-by-object)
;----------------------------------------------------------------
;;;
;;; In diesen Rollen steht, mit wem das Ind. verbunden ist, und ueber welches Ende des Pfeiles:
;;;
;;; linked-over-with
;;; / \
;;; start-link.o.w. end-link.o.w. 0 ----> # : start-l.o.w.(0,#),
;;; end-l.o.w.(#,0),
;;; l.o.w.(#,0) /\ l.o.w(0,#).
(cl-define-primitive-role 'linked-over-with :inverse 'linked-over-with
:parent 'in-relation-with-objects
:inverse-parent 'linked-over-with)
(cl-define-primitive-role 'start-linked-over-with :inverse 'end-linked-over-with
:parent 'linked-over-with
:inverse-parent 'linked-over-with)
;;;
;;; Hier werden die Linker eingetragen: 0 -----> # : linker-objects(A,L), linker-objects(B,L).
;;; A L B
(cl-define-primitive-role 'linker-objects :inverse 'points-related-with
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linker-objects :inverse 'startpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
(cl-define-primitive-role 'end-linker-objects :inverse 'endpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
;;;
;;; Rollen eines Linkers: points-related-with
;;; / \ 0 ----> # : s.r.w.(L,A), e.r.w.(L,B)
;;; startpoint-rel.-w. endpoint-rel.-w. A L B
;;;
;;; Fuer Composite-Things:
;;;
(cl-define-primitive-role 'has-parts :inverse 'part-of
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
;;;
;;; Fuer Directed-Elements:
;;;
(cl-define-primitive-role 'has-points :inverse 'point-part-of
:parent 'has-parts
:inverse-parent 'part-of)
(cl-define-primitive-role 'has-startpoint :inverse 'startpoint-part-of-directed-element
:parent 'has-points
:inverse-parent 'point-part-of)
(cl-define-primitive-role 'has-endpoint :inverse 'endpoint-part-of-directed-element
:parent 'has-points
:inverse-parent 'point-part-of)
;----------------------------------------------------------------
;;;
;;;
;;;
(cl-define-primitive-role 'filled-bool :attribute t)
(cl-define-primitive-role 'radius-real :attribute t)
(cl-define-primitive-role 'text-string :attribute t)
(cl-define-primitive-role 'xtrans-integer :attribute t)
(cl-define-primitive-role 'ytrans-integer :attribute t)
(cl-define-primitive-role 'belongs-to-clos-object :attribute t)
;----------------------------------------------------------------
;;;
;;;
;;;
(cl-define-primitive-concept 'gened-thing 'classic-thing)
(cl-define-disjoint-primitive-concept 'basic-thing 'gened-thing 'basic-or-comp)
(cl-define-disjoint-primitive-concept 'composite-thing 'gened-thing 'basic-or-comp)
(cl-define-primitive-concept '0d 'gened-thing)
(cl-define-primitive-concept '1d 'gened-thing)
(cl-define-primitive-concept '2d 'gened-thing)
(cl-define-primitive-concept 'at-least-1d '(and 1d 2d))
(cl-define-primitive-concept 'at-most-1d '(and 0d 1d))
;;;
;;;
;;;
(cl-define-primitive-concept 'directed-element '(and 1d basic-thing))
(cl-define-disjoint-primitive-concept 'g-circle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-line '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-arrow 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-rectangle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-spline-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-text '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-point '(and 0d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'info-point '(and 0d basic-thing) 'type)
)
;;;
;;;
;;;
(defqualifiedsubrole has-parts g-rectangle)
(defqualifiedsubrole has-parts directed-element)
(defqualifiedsubrole touching-objects directed-element)
;;;
;;; Diese Konzepte sind wohl von generellem Nutzen:
;;;
(define-concept only-touching-objects
(and
basic-thing
(none contained-in-objects)
(some touching-objects)
(none has-parts)))
(define-concept linker-point
(and
info-point
(exactly 1 point-part-of)))
(define-concept t-linker-point
(and
linker-point
(at-least 1 touching-objects))) ;eigentlich (exactly 1 touching-objects) -> Error in Splines!
(define-concept c-linker-point
(and
linker-point
(exactly 1 covered-by-object)))
(define-concept i-linker-point
(and
linker-point
(exactly 1 directly-contained-by-object)))
(define-concept linker
(and
directed-element
(exactly 2 points-related-with)))
(define-concept tt-linker
(and
linker
(all has-points t-linker-point)))
(define-concept ii-linker
(and
linker
(all has-points i-linker-point)))
(define-concept it-linker
(and
linker
(all has-startpoint i-linker-point)
(all has-endpoint t-linker-point)))
(define-concept ti-linker
(and
linker
(all has-startpoint t-linker-point)
(all has-endpoint i-linker-point)))
(define-concept ct-linker
(and
linker
(all has-startpoint c-linker-point)
(all has-endpoint t-linker-point)))
(define-concept tc-linker
(and
linker
(all has-startpoint t-linker-point)
(all has-endpoint c-linker-point)))
(define-concept ci-linker
(and
linker
(all has-startpoint c-linker-point)
(all has-endpoint i-linker-point)))
(define-concept ic-linker
(and
linker
(all has-startpoint i-linker-point)
(all has-endpoint c-linker-point)))
;;;;
;;;;
;;;;
(defun string-is-integer-p (string)
(integerp
(read-from-string string)))
(cl-define-concept 'capacity-label
'(and
g-text
(at-least 1 intersects-objects)
(all text-string
(and (test-h string-is-integer-p)))))
(defqualifiedsubrole intersects-objects capacity-label)
;;;
;;;
;;;
(define-concept place-or-transition
(and
only-touching-objects
(all touching-objects-directed-element tt-linker)))
(define-concept place?
(and
g-circle
place-or-transition))
(define-concept transition?
(and
g-rectangle
place-or-transition))
;;;
;;;
;;;
(define-concept place
(and
place?
(all linked-over-with transition?)))
(defqualifiedsubrole has-parts place)
(define-concept conflict-place
(and
place
(at-least 2 end-linked-over-with)))
(define-concept start-place
(and
place
(none start-linked-over-with)))
(define-concept end-place
(and
place
(none end-linked-over-with)))
(define-concept normal-place
(and
place
(some start-linked-over-with)
(some end-linked-over-with)))
(define-concept place-with-capacity
(and
place
(exactly 1 intersects-objects-capacity-label)))
(cl-define-concept 'token
'(and
g-circle
(all contained-in-objects place)
(fills filled-bool t)
(all radius-real
(and number
(min 2.0)
(max 10.0)))))
(define-concept place-with-tokens
(and
place
(some contains-objects)
(all contains-objects token)))
(defqualifiedsubrole has-parts place-with-tokens)
(defun overfilled-place? (ind)
(let* ((tokens-rolle (cl-named-role 'contains-objects))
(tokens (length (cl-fillers ind tokens-rolle)))
(label-rolle (cl-named-role 'intersects-objects-capacity-label))
(text-ind (first (cl-fillers ind label-rolle)))
(number (read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))))
(> tokens number)))
(defun label-kleiner-1? (ind)
(let* ((rolle (cl-named-role 'intersects-objects-capacity-label))
(text-ind (first (cl-fillers ind rolle)))
(kap
(if text-ind
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))
1)))
(<= kap 1)))
(cl-define-concept 'overfilled-place!!!
'(and
place-with-tokens
place-with-capacity
(test-c cl-test-closed-roles? (contains-objects intersects-objects-capacity-label))
(test-c overfilled-place?)))
(cl-define-concept 'c/e-place
'(and
place
(test-c cl-test-closed-roles?
(intersects-objects-capacity-label))
(test-c label-kleiner-1?)))
;;;
;;;
;;;
(define-concept transition
(and
transition?
(at-least 2 linked-over-with)
(at-least 1 start-linker-objects)
(at-least 1 end-linker-objects)
(all linked-over-with place?)))
(define-concept edge
(and
tt-linker
(all touching-objects place-or-transition)))
(define-concept edge-with-capacity
(and
edge
(exactly 1 intersects-objects-capacity-label)))
(cl-define-concept 'c/e-edge
'(and
edge
(test-c cl-test-closed-roles? (intersects-objects-capacity-label))
(test-c label-kleiner-1?)))
;;;
;;;
;;;
(defun genug-input-tokens? (ind)
(let* ((end-linker (cl-named-role 'end-linker-objects))
(flag nil))
(or
(every #'(lambda (end-linker)
(let* ((text-ind
(first
(cl-fillers
end-linker
(cl-named-role 'intersects-objects-capacity-label))))
(place
(first
(cl-fillers
end-linker
(cl-named-role 'startpoint-related-with))))
(kap
(if text-ind
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))
1)) ; Kante hat sonst Kap. 1 (wie bei BE-Neten)
(tokens
(length
(cl-fillers
place
(cl-named-role 'contains-objects)))))
(if (and tokens kap)
(not (minusp (- tokens kap)))
(progn
(setf flag '?)
nil))))
(cl-fillers ind end-linker))
flag)))
(defun genug-output-tokens? (ind)
(let* ((start-linker (cl-named-role 'start-linker-objects))
(flag nil))
(or
(every #'(lambda (start-linker)
(let* ((text-ind
(first
(cl-fillers
start-linker
(cl-named-role 'intersects-objects-capacity-label))))
(place
(first
(cl-fillers
start-linker
(cl-named-role 'endpoint-related-with))))
(kap
(if text-ind
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))
1))
(tokens
(length
(cl-fillers
place
(cl-named-role 'contains-objects))))
(placen-text-ind
(first
(cl-fillers
place
(cl-named-role 'intersects-objects-capacity-label))))
(placen-kap
(if placen-text-ind
(read-from-string
(first
(cl-fillers
placen-text-ind
(cl-named-role 'text-string))))
10000))) ; kein Label -> Kap. unbegrenzt ! (w)
(if (and placen-kap kap tokens)
(<= (+ tokens kap) placen-kap)
(progn
(setf flag '?)
nil))))
(cl-fillers ind start-linker))
flag)))
(cl-define-concept 'l-activated-transition
'(and
transition
(all start-linked-over-with
place-with-tokens)
(all end-linker-objects edge)
(test-c cl-test-closed-roles? (end-linker-objects start-linked-over-with))
(test-c genug-input-tokens?)))
(cl-define-concept 'r-activated-transition
'(and
transition
(all end-linked-over-with
place)
(all start-linker-objects edge)
(test-c cl-test-closed-roles? (start-linker-objects end-linked-over-with))
(test-c genug-output-tokens?)))
(cl-define-concept 'activated-transition
'(and
l-activated-transition
r-activated-transition))
;;;
;;;
;;;
(define-concept petri-net
(and
composite-thing
(at-least 5 has-parts)
(some has-parts-place)
(all has-parts-g-rectangle transition)
(all has-parts-directed-element edge)))
(define-concept p/t-petri-net
(and
petri-net
(some has-parts-place-with-tokens)))
(define-concept c/e-petri-net
(and
p/t-petri-net
(all has-parts-place c/e-place)
(all has-parts-directed-element c/e-edge)))
;;;
;;;
;;;
(defconstant +known-concepts+
'(linker
tt-linker
ii-linker
ti-linker
it-linker
ci-linker
ic-linker
tc-linker
ct-linker
place transition edge
l-activated-transition
r-activated-transition
activated-transition
edge-with-capacity
token
conflict-place
overfilled-place!!!
start-place end-place normal-place
c/e-place
c/e-edge
capacity-label
place-with-capacity
place-with-tokens
petri-net
p/t-petri-net
c/e-petri-net
g-circle
g-line
g-rectangle
g-arrow
g-polygon
g-spline-chain
g-directed-spline-chain
g-spline-polygon
g-chain
g-directed-chain
g-text
g-point
composite-thing
info-point
))
(defconstant +library-concepts+
`(
capacity-label
token
place
place-with-tokens
place-with-capacity
transition))
(defconstant +known-roles+
'((
spatial-relation ; keine Inverse
in-relation-with-objects ; keine Inverse
disjoint-with ; selbstinvers
touching-objects ; selbstinvers
intersects-objects ; selbstinvers
intersects-0-objects ; selbstinvers
intersects-1-objects ; selbstinvers
intersects-2-objects ; selbstinvers
contains-objects
contained-in-objects
directly-contains-objects
directly-contained-by-object
covers-objects
covered-by-object
linked-over-with ; selbstinvers
start-linked-over-with
end-linked-over-with
linker-objects
points-related-with
start-linker-objects
startpoint-related-with
end-linker-objects
endpoint-related-with
has-parts
part-of
has-points
point-part-of
has-startpoint
startpoint-part-of-directed-element
has-endpoint
endpoint-part-of-directed-element
;;; Attribute
belongs-to-clos-object
filled-bool
radius-real
text-string
xtrans-integer
ytrans-integer)
(has-parts-g-rectangle
has-parts-g-rectangle-inverse
has-parts-directed-element
has-parts-directed-element-inverse
touching-objects-directed-element
touching-objects-directed-element-inverse
intersects-objects-capacity-label
intersects-objects-capacity-label-inverse
has-parts-place
has-parts-place-inverse
has-parts-place-with-tokens
has-parts-place-with-tokens-inverse)))
| 22,196 | Common Lisp | .lisp | 658 | 26.486322 | 98 | 0.605373 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | c84b633d8a2f7923ca206fb50a9c69075d54c7fa59849ccb5cd4c9edeb2ff032 | 11,225 | [
-1
] |
11,226 | knowledge3.lisp | lambdamikel_GenEd/src/knowledge/knowledge3.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: Knowledge; Base: 10 -*-
(in-package knowledge)
(cl-reader-init)
(cl-clear-kb)
(cl-startup)
(setf *krss-verbose* nil)
(cl-set-classic-warn-mode t)
;----------------------------------------------------------------
;----------------------------------------------------------------
(defmacro defprimitive (name expr)
`(define-primitive-concept ,name ,expr))
(defmacro defdisjoint (name expr grouping)
`(define-disjoint-primitive-concept ,name ,grouping ,expr))
(defmacro defconcept (name expr)
`(define-concept ,name ,expr))
(defun cl-filler (derived-object role &optional remove-elem)
(let ((fillers (remove remove-elem (cl-fillers derived-object role)
:test #'eq)))
(when (second fillers)
(cerror "Return only first filler"
"Attribute ~S holds more than 1 filler for ~S: ~S"
role derived-object fillers))
(first fillers)))
(defun close-all-subroles (role &key exceptions
(inds (cl-concept-instances @pj-thing)))
(unless (member role exceptions :test #'eq)
(close-all-roles (cl-role-children role) inds exceptions)
(dolist (role (cl-role-children role))
(close-all-subroles role :exceptions exceptions :inds inds))))
(defun close-all-roles (roles
&optional (inds (cl-concept-instances @pj-thing))
(exceptions nil))
(dolist (role roles)
(unless (member role exceptions :test #'eq)
(dolist (ind inds)
(unless (cl-ind-closed-role? ind role)
(cl-ind-close-role ind role))))))
(defun find-possible-subsumees (inds)
(dolist (ind inds)
(let* ((parents (cl-ind-parents ind))
(children (delete nil (mapcar #'cl-concept-children parents))))
(when children
(format t "~&Individual ~S may be further specialized to ~S"
ind children)))))
;----------------------------------------------------------------
;;;
;;;
;;;
(defun cl-inv-role-name (role)
(let ((inv (cl-role-inverse (cl-named-role role))))
(when inv
(cl-role-name inv))))
(defmacro defqualifiedsubrole (role
qualification
&key
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
(parent role)
(inverse-parent (or (cl-inv-role-name parent)
role)))
`(progn
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-FILLER-RULE"))
#| (cl-named-concept ',qualification) ; Antetecedent |#
(cl-named-concept 'gened-thing)
(cl-named-role ',name) ; Rolle, die gefuellt wird
#'(lambda (ind role)
(remove-if-not #'(lambda (ind)
(cl-instance? ind
(cl-named-concept ',qualification)))
(cl-fillers ind (cl-named-role ',parent))))
:filter
'(and
(at-least 1 ,parent)
(test-c cl-test-closed-roles? (,role))))))
#|
;;; Haarslev:
(defmacro defqualifiedsubrole (role
qualification
&key
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
(parent role)
(inverse-parent (or (cl-inv-role-name parent)
role))
break)
`(progn
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-INV-FILLER-RULE"))
(cl-named-concept ',qualification)
(cl-named-role ',inv-name)
#'(lambda (ind role)
(declare (ignore role))
(when ,break
(break "in filler rule of ~A" ',inv-name))
(or
(cl-fillers ind (cl-named-role ',inverse-parent))
(break "NIL as filler computed for ~A"
',inv-name)))
:filter
'(and (at-least 1 ,inverse-parent)
(test-c cl-test-closed-roles? (,role))))))
|#
;;;
;;;
;;;
;----------------------------------------------------------------
(cl-define-primitive-role 'spatial-relation)
(cl-define-primitive-role 'in-relation-with-objects
:parent 'spatial-relation)
(cl-define-primitive-role 'disjoint-with :inverse 'disjoint-with
:parent 'spatial-relation)
(cl-define-primitive-role 'touching-objects :inverse 'touching-objects
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-objects :inverse 'intersects-objects
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-0-objects :inverse 'intersects-0-objects
:parent 'intersects-objects)
(cl-define-primitive-role 'intersects-1-objects :inverse 'intersects-1-objects
:parent 'intersects-objects)
(cl-define-primitive-role 'intersects-2-objects :inverse 'intersects-2-objects
:parent 'intersects-objects)
;;; spatial-relation
;;; / \
;;; in-rel.w. disj.w.
;;; / | \
;;; / | \
;;; / | \
;;; touching inters. contains
;;; /|\ |
;;; / | \ direc.contains
;;; 0 1 2 |
;;; covers
(cl-define-primitive-role 'contains-objects :inverse 'contained-in-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'directly-contains-objects :inverse 'directly-contained-by-object
:parent 'contains-objects
:inverse-parent 'contained-in-objects)
(cl-define-primitive-role 'covers-objects :inverse 'covered-by-object
:parent 'directly-contains-objects
:inverse-parent 'directly-contained-by-object)
;;;
;;; In diesen Rollen steht, mit wem das Ind. verbunden ist, und ueber welches Ende des Pfeiles:
;;;
;;; linked-over-with
;;; / \
;;; start-link.o.w. end-link.o.w. 0 ----> # : start-l.o.w.(0,#),
;;; end-l.o.w.(#,0),
;;; l.o.w.(#,0) /\ l.o.w(0,#).
(cl-define-primitive-role 'linked-over-with :inverse 'linked-over-with
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linked-over-with :inverse 'end-linked-over-with
:parent 'linked-over-with
:inverse-parent 'linked-over-with)
;;;
;;; Hier werden die Linker eingetragen: 0 -----> # : linker-objects(A,L), linker-objects(B,L).
;;; A L B
(cl-define-primitive-role 'linker-objects :inverse 'points-related-with
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linker-objects :inverse 'startpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
(cl-define-primitive-role 'end-linker-objects :inverse 'endpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
;;;
;;;
;;;
;;; Rollen eines Linkers: points-related-with
;;; / \ 0 ----> # : s.r.w.(L,A), e.r.w.(L,B)
;;; startpoint-rel.-w. endpoint-rel.-w. A L B
#|
(cl-define-primitive-role 'points-related-with :inverse 'linker-objects
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'startpoint-related-with :inverse 'endpoint-related-with
:parent 'points-related-with
:inverse-parent 'points-related-with)
|#
;;;
;;; Fuer Composite-Things:
;;;
(cl-define-primitive-role 'has-parts :inverse 'part-of
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
;;;
;;; Fuer Directed-Elements:
;;;
(cl-define-primitive-role 'has-points
:parent 'has-parts
:inverse 'point-part-of
:inverse-parent 'part-of)
(cl-define-primitive-role 'has-startpoint
:parent 'has-points
:inverse 'startpoint-part-of-directed-element
:inverse-parent 'part-of-directed-element)
(cl-define-primitive-role 'has-endpoint
:parent 'has-points
:inverse 'endpoint-part-of-directed-element
:inverse-parent 'part-of-directed-element)
;;;
;;;
;;;
(cl-define-primitive-role 'filled-bool :attribute t)
(cl-define-primitive-role 'radius-real :attribute t)
(cl-define-primitive-role 'text-string :attribute t)
(cl-define-primitive-role 'xtrans-integer :attribute t)
(cl-define-primitive-role 'ytrans-integer :attribute t)
(cl-define-primitive-role 'belongs-to-clos-object :attribute t)
;;;
;;;
;;;
(cl-define-primitive-concept 'gened-thing 'classic-thing)
(cl-define-disjoint-primitive-concept 'basic-thing 'gened-thing 'basic-or-comp)
(cl-define-disjoint-primitive-concept 'composite-thing 'gened-thing 'basic-or-comp)
(cl-define-primitive-concept '0d 'gened-thing)
(cl-define-primitive-concept '1d 'gened-thing)
(cl-define-primitive-concept '2d 'gened-thing)
(cl-define-primitive-concept 'at-least-1d '(and 1d 2d))
(cl-define-primitive-concept 'at-most-1d '(and 0d 1d))
;;;
;;;
;;;
(cl-define-primitive-concept 'directed-element '(and 1d basic-thing))
(cl-define-disjoint-primitive-concept 'g-circle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-line '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-arrow 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-rectangle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-spline-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-text '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-point '(and 0d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'info-point '(and 0d basic-thing) 'type)
;;;
;;;
;;;
(defqualifiedsubrole linked-over-with g-circle
:parent linked-over-with :inverse-parent linked-over-with)
(defqualifiedsubrole linked-over-with g-rectangle
:parent linked-over-with :inverse-parent linked-over-with)
(defqualifiedsubrole has-parts g-circle
:parent has-parts :inverse-parent part-of)
(defqualifiedsubrole has-parts g-rectangle
:parent has-parts :inverse-parent part-of)
(defqualifiedsubrole has-parts g-arrow
:parent has-parts :inverse-parent part-of)
(defqualifiedsubrole touching-objects directed-element
:parent touching-objects :inverse-parent touching-objects)
;;;
;;; Diese Konzepte sind wohl von generellem Nutzen:
;;;
(define-concept nur-beruehrende-objekte
(and
basic-thing
(none contained-in-objects)
(some touching-objects)
(none has-parts)))
#|
(define-concept verbinder
(and
directed-element
(exactly 2 points-related-with)))
(defun subset? (ind sym1 sym2)
(let* ((role1 (cl-named-role sym1))
(role2 (cl-named-role sym2))
(fillers1 (cl-fillers ind role1))
(fillers2 (cl-fillers ind role2)))
(if (and (cl-ind-closed-role? ind role1)
(cl-ind-closed-role? ind role2))
(null (set-difference
fillers2 fillers1))
'?)))
(defun member? (ind sym1 sym2)
(let* ((role1 (cl-named-role sym1))
(role2 (cl-named-role sym2))
(fillers1 (cl-fillers ind role1))
(fillers2 (cl-fillers ind role2)))
(if (and (cl-ind-closed-role? ind role1)
(cl-ind-closed-role? ind role2))
(if (> (length fillers1) 1)
nil
(member (first fillers1) fillers2))
'?)))
(defun not-member? (ind sym1 sym2)
(let ((member (member? ind sym1 sym2)))
(case member
(? '?)
(t nil)
(nil t))))
(cl-define-concept 'tt-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with
touching-objects)
(test-c member?
endpoint-related-with
touching-objects)))
(cl-define-concept 'it-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with
intersects-objects)
(test-c member?
endpoint-related-with
touching-objects)))
(cl-define-concept 'ti-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with
touching-objects)
(test-c member?
endpoint-related-with
intersects-objects)))
(cl-define-concept 'ii-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with intersects-objects)
(test-c member?
endpoint-related-with intersects-objects)))
(cl-define-concept 'ct-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with covered-by-object)
(test-c member?
endpoint-related-with touching-objects)))
(cl-define-concept 'tc-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with touching-objects)
(test-c member?
endpoint-related-with covered-by-object)))
(cl-define-concept 'ci-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with covered-by-object)
(test-c member?
endpoint-related-with intersects-objects)
(test-c not-member?
endpoint-related-with touching-objects)))
(cl-define-concept 'ic-verbinder
'(and
verbinder
(test-c member?
startpoint-related-with intersects-objects)
(test-c member?
endpoint-related-with covered-by-object)))
|#
(define-concept verbinder-punkt
(and
info-point
(exactly 1 part-of-directed-element)))
(define-concept t-verbinder-punkt
(and
verbinder-punkt
(exactly 1 touching-objects)))
(define-concept c-verbinder-punkt
(and
verbinder-punkt
(exactly 1 covered-by-object)))
(define-concept i-verbinder-punkt
(and
verbinder-punkt
(exactly 1 directly-contained-by-object)))
(define-concept verbinder
(and
directed-element
(exactly 2 points-related-with)))
(define-concept tt-verbinder
(and
verbinder
(all has-points t-verbinder-punkt)))
(define-concept ii-verbinder
(and
verbinder
(all has-points i-verbinder-punkt)))
(define-concept it-verbinder
(and
verbinder
(all has-startpoint i-verbinder-punkt)
(all has-endpoint t-verbinder-punkt)))
(define-concept ti-verbinder
(and
verbinder
(all has-startpoint t-verbinder-punkt)
(all has-endpoint i-verbinder-punkt)))
(define-concept ct-verbinder
(and
verbinder
(all has-startpoint c-verbinder-punkt)
(all has-endpoint t-verbinder-punkt)))
(define-concept tc-verbinder
(and
verbinder
(all has-startpoint t-verbinder-punkt)
(all has-endpoint c-verbinder-punkt)))
(define-concept ci-verbinder
(and
verbinder
(all has-startpoint c-verbinder-punkt)
(all has-endpoint i-verbinder-punkt)))
(define-concept ic-verbinder
(and
verbinder
(all has-startpoint i-verbinder-punkt)
(all has-endpoint c-verbinder-punkt)))
;;;;
;;;;
;;;;
#|
(defun string-is-integer-p (string)
(let ((liste (coerce string 'list)))
(every #'(lambda (char)
(and (char<= char #\9)
(char>= char #\0)))
liste)))
|#
(defun string-is-integer-p (string)
(integerp
(read-from-string string)))
(cl-define-concept 'kapazitaets-label
'(and
g-text
(at-least 1 intersects-objects)
(all text-string
(and (test-h string-is-integer-p)))))
(defqualifiedsubrole intersects-objects kapazitaets-label
:inv-name intersects-objects-kapazitaets-label
:parent intersects-objects :inverse-parent intersects-objects)
;;;
;;;
;;;
(define-concept stelle-oder-transition
(and
nur-beruehrende-objekte
(all touching-objects-directed-element tt-verbinder)))
(define-concept stelle?
(and
g-circle
stelle-oder-transition))
(define-concept transition?
(and
g-rectangle
stelle-oder-transition))
;;;
;;;
;;;
(define-concept stelle
(and
stelle?
(all linked-over-with transition?)))
(define-concept konflikt-stelle
(and
stelle
(at-least 2 end-linked-over-with)))
(define-concept start-stelle
(and
stelle
(none start-linked-over-with)))
(define-concept end-stelle
(and
stelle
(none end-linked-over-with)))
(define-concept normale-stelle
(and
stelle
(some start-linked-over-with)
(some end-linked-over-with)))
(define-concept stelle-mit-kapazitaet
(and
stelle
(exactly 1 intersects-objects-kapazitaets-label)))
(cl-define-concept 'marke
'(and
g-circle
(all contained-in-objects stelle)
(fills filled-bool t)
(all radius-real
(and number
(min 2.0)
(max 10.0)))))
(define-concept stelle-mit-marken
(and
stelle
(some contains-objects)
(all contains-objects marke)))
(define-concept transition
(and
transition?
(at-least 2 linked-over-with)
(at-least 1 start-linker-objects)
(at-least 1 end-linker-objects)
(all linked-over-with stelle?)))
(define-concept netz-kante
(and
tt-verbinder
(all touching-objects stelle-oder-transition)))
(define-concept netz-kante-mit-kapazitaet
(and
netz-kante
(exactly 1 intersects-objects-kapazitaets-label)))
;;;
;;;
;;;
(defun genug-input-marken? (ind)
(let* ((end-linker (cl-named-role 'end-linker-objects))
(flag nil))
(or
(every #'(lambda (end-linker)
(let* ((text-ind
(first
(cl-fillers
end-linker
(cl-named-role 'intersects-objects-kapazitaets-label))))
(stelle
(first
(cl-fillers
end-linker
(cl-named-role 'startpoint-related-with))))
(kap
(if text-ind
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))))
(marken
(if stelle
(length
(cl-fillers
stelle
(cl-named-role 'contains-objects))))))
(if (and marken kap)
(not (minusp (- marken kap)))
(progn
(setf flag '?)
nil))))
(cl-fillers ind end-linker))
flag)))
(defun genug-output-marken? (ind)
(let* ((start-linker (cl-named-role 'start-linker-objects))
(flag nil))
(or
(every #'(lambda (start-linker)
(let* ((text-ind
(first
(cl-fillers
start-linker
(cl-named-role 'intersects-objects-kapazitaets-label))))
(stelle
(first
(cl-fillers
start-linker
(cl-named-role 'endpoint-related-with))))
(kap
(if text-ind
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))))
(marken
(if stelle
(length
(cl-fillers
stelle
(cl-named-role 'contains-objects)))))
(stellen-text-ind
(first
(cl-fillers
stelle
(cl-named-role 'intersects-objects-kapazitaets-label))))
(stellen-kap
(if stellen-text-ind
(read-from-string
(first
(cl-fillers
stellen-text-ind
(cl-named-role 'text-string)))))))
(if (and stellen-kap kap marken)
(<= (+ marken kap) stellen-kap)
(progn
(setf flag '?)
nil))))
(cl-fillers ind start-linker))
flag)))
(cl-define-concept 'l-aktive-transition
'(and
transition
(all start-linked-over-with
(and
stelle-mit-marken
stelle-mit-kapazitaet))
(all end-linker-objects netz-kante-mit-kapazitaet)
(test-c cl-test-closed-roles? (end-linker-objects start-linked-over-with))
(test-c genug-input-marken?)))
(cl-define-concept 'r-aktive-transition
'(and
transition
(all end-linked-over-with
(and
stelle-mit-marken
stelle-mit-kapazitaet))
(all start-linker-objects netz-kante-mit-kapazitaet)
(test-c cl-test-closed-roles? (start-linker-objects end-linked-over-with))
(test-c genug-output-marken?)))
(cl-define-concept 'aktive-transition
'(and
l-aktive-transition
r-aktive-transition))
;;;
;;;
;;;
(define-concept petri-netz
(and
composite-thing
(at-least 5 has-parts) ; kleinstes Netz: 0 -> # -> 0
(all has-parts-g-circle stelle)
(all has-parts-g-rectangle transition)
(all has-parts-g-arrow verbinder)))
;;;
;;;
;;;
(defconstant +known-concepts+
'(verbinder
tt-verbinder
ii-verbinder
ti-verbinder
it-verbinder
ci-verbinder
ic-verbinder
tc-verbinder
ct-verbinder
stelle transition netz-kante
l-aktive-transition
r-aktive-transition
aktive-transition
netz-kante-mit-kapazitaet
marke
konflikt-stelle
start-stelle end-stelle normale-stelle
kapazitaets-label
stelle-mit-kapazitaet
stelle-mit-marken
petri-netz
g-circle
g-line
g-rectangle
g-arrow
g-polygon
g-spline-chain
g-directed-spline-chain
g-spline-polygon
g-chain
g-directed-chain
g-text
g-point
composite-thing
info-point
))
(defconstant +library-concepts+
`(verbinder
kapazitaets-label
stelle
start-stelle
normale-stelle
end-stelle
stelle-mit-marken
stelle-mit-kapazitaet
marke
transition))
(defconstant +known-roles+
'((
belongs-to-clos-object
spatial-relation
in-relation-with-objects
disjoint-with
touching-objects
intersects-objects
intersects-0-objects
intersects-1-objects
intersects-2-objects
contains-objects
contained-in-objects
directly-contains-objects
directly-contained-by-object
covers-objects
covered-by-object
linked-over-with
start-linked-over-with
end-linked-over-with
points-related-with
startpoint-related-with
endpoint-related-with
linker-objects
start-linker-objects
end-linker-objects
has-points
has-startpoint
has-endpoint
has-parts
part-of
point-part-of
part-of-directed-element
startpoint-part-of-directed-element
endpoint-part-of-directed-element
filled-bool
radius-real
text-string
xtrans-integer
ytrans-integer)
(
has-parts-g-circle
has-parts-g-rectangle
has-parts-g-arrow
touching-objects-directed-element-inverse
touching-objects-directed-element
intersects-objects-kapazitaets-label
)))
| 25,211 | Common Lisp | .lisp | 752 | 25.462766 | 98 | 0.594693 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 51de3e3fd787fa42d4a80bcf7ad86226d682289f475c2c77f07410bd273ba322 | 11,226 | [
-1
] |
11,227 | knowledge7.lisp | lambdamikel_GenEd/src/knowledge/knowledge7.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: Knowledge; Base: 10 -*-
(in-package knowledge)
(cl-reader-init)
(cl-clear-kb)
(cl-startup)
(setf *krss-verbose* nil)
(cl-set-classic-warn-mode t)
;----------------------------------------------------------------
#+:allegro
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun cl-filler (derived-object role &optional remove-elem)
(let ((fillers (remove remove-elem (cl-fillers derived-object role)
:test #'eq)))
(when (second fillers)
(cerror "Return only first filler"
"Attribute ~S holds more than 1 filler for ~S: ~S"
role derived-object fillers))
(first fillers)))
(defun close-all-subroles (role &key exceptions
(inds (cl-concept-instances @pj-thing)))
(unless (member role exceptions :test #'eq)
(close-all-roles (cl-role-children role) inds exceptions)
(dolist (role (cl-role-children role))
(close-all-subroles role :exceptions exceptions :inds inds))))
(defun close-all-roles (roles
&optional (inds (cl-concept-instances @pj-thing))
(exceptions nil))
(dolist (role roles)
(unless (member role exceptions :test #'eq)
(dolist (ind inds)
(unless (cl-ind-closed-role? ind role)
(cl-ind-close-role ind role))))))
(defun find-possible-subsumees (inds)
(dolist (ind inds)
(let* ((parents (cl-ind-parents ind))
(children (delete nil (mapcar #'cl-concept-children parents))))
(when children
(format t "~&Individual ~S may be further specialized to ~S"
ind children)))))
;----------------------------------------------------------------
(defun cl-inv-role-name (role)
(print role)
(let ((inv (cl-role-inverse (cl-named-role role))))
(when inv
(cl-role-name inv))))
(defmacro defqualifiedsubrole (role
qualification
&key
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
(parent role)
(inverse-parent (or (cl-inv-role-name parent)
role))
(specialized-concept t)
break)
`(progn
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-INV-FILLER-RULE"))
,(if specialized-concept
`(cl-named-concept ',qualification)
'(cl-named-concept 'classic-thing))
(cl-named-role ',inv-name)
#'(lambda (ind role)
(declare (ignore role))
(when ,break
(break "in filler rule of ~A" ',inv-name))
(or
(cl-fillers ind (cl-named-role ',inverse-parent))
(break "NIL as filler computed for ~A"
',inv-name)))
:filter
'(and (at-least 1 ,inverse-parent)
(test-c cl-test-closed-roles? (,role))))))
(defmacro def-or-concept (concept1 concept2)
(let ((or-name
(intern (concatenate 'string
(write-to-string concept1)
"-OR-"
(write-to-string concept2)))))
`(progn
(cl-define-primitive-concept
',or-name
'basic-thing)
(cl-add-rule ',(gensym)
(cl-named-concept ',concept1)
',or-name)
(cl-add-rule ',(gensym)
(cl-named-concept ',concept2)
',or-name))))
;----------------------------------------------------------------
;;; selbstinverse Basisrelationen
(cl-define-primitive-role 'spatial-relation :inverse 'spatial-relation)
(cl-define-primitive-role 'in-relation-with-objects :inverse 'in-relation-with-objects
:parent 'spatial-relation
:inverse-parent 'spatial-relation)
(cl-define-primitive-role 'disjoint-with :inverse 'disjoint-with :parent 'spatial-relation
:inverse-parent 'spatial-relation)
(cl-define-primitive-role 'touching-objects :inverse 'touching-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-objects :inverse 'intersects-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-0-objects :inverse 'intersects-0-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
(cl-define-primitive-role 'intersects-1-objects :inverse 'intersects-1-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
(cl-define-primitive-role 'intersects-2-objects :inverse 'intersects-2-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
;;;
;;; spatial-relation
;;; / \
;;; in-rel.w. disj.w.
;;; / | \
;;; / | \
;;; / | \
;;; touching inters. contains
;;; /|\ |
;;; / | \ direc.contains
;;; 0 1 2 |
;;; covers
;----------------------------------------------------------------
;;; nicht-selbstinverse Basisrelationen
(cl-define-primitive-role 'contains-objects :inverse 'contained-in-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'directly-contains-objects :inverse 'directly-contained-by-object
:parent 'contains-objects
:inverse-parent 'contained-in-objects)
(cl-define-primitive-role 'covers-objects :inverse 'covered-by-object
:parent 'directly-contains-objects
:inverse-parent 'directly-contained-by-object)
;----------------------------------------------------------------
;;;
;;; In diesen Rollen steht, mit wem das Ind. verbunden ist, und ueber welches Ende des Pfeiles:
;;;
;;; linked-over-with
;;; / \
;;; start-link.o.w. end-link.o.w. 0 ----> # : start-l.o.w.(0,#),
;;; end-l.o.w.(#,0),
;;; l.o.w.(#,0) /\ l.o.w(0,#).
(cl-define-primitive-role 'linked-over-with :inverse 'linked-over-with
:parent 'in-relation-with-objects
:inverse-parent 'linked-over-with)
(cl-define-primitive-role 'start-linked-over-with :inverse 'end-linked-over-with
:parent 'linked-over-with
:inverse-parent 'linked-over-with)
;;;
;;; Hier werden die Linker eingetragen: 0 -----> # : linker-objects(A,L), linker-objects(B,L).
;;; A L B
(cl-define-primitive-role 'linker-objects :inverse 'points-related-with
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linker-objects :inverse 'startpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
(cl-define-primitive-role 'end-linker-objects :inverse 'endpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
;;;
;;; Rollen eines Linkers: points-related-with
;;; / \ 0 ----> # : s.r.w.(L,A), e.r.w.(L,B)
;;; startpoint-rel.-w. endpoint-rel.-w. A L B
;;;
;;; Fuer Composite-Things:
;;;
(cl-define-primitive-role 'has-parts :inverse 'part-of
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
;;;
;;; Fuer Directed-Elements:
;;;
(cl-define-primitive-role 'has-points :inverse 'point-part-of
:parent 'has-parts
:inverse-parent 'part-of)
(cl-define-primitive-role 'has-startpoint :inverse 'startpoint-part-of-directed-element
:parent 'has-points
:inverse-parent 'point-part-of)
(cl-define-primitive-role 'has-endpoint :inverse 'endpoint-part-of-directed-element
:parent 'has-points
:inverse-parent 'point-part-of)
;----------------------------------------------------------------
;;;
;;;
;;;
(cl-define-primitive-role 'filled-bool :attribute t)
(cl-define-primitive-role 'radius-real :attribute t)
(cl-define-primitive-role 'text-string :attribute t)
(cl-define-primitive-role 'xtrans-integer :attribute t)
(cl-define-primitive-role 'ytrans-integer :attribute t)
(cl-define-primitive-role 'belongs-to-clos-object :attribute t)
;----------------------------------------------------------------
;;;
;;;
;;;
(cl-define-primitive-concept 'gened-thing 'classic-thing)
(cl-define-disjoint-primitive-concept 'basic-thing 'gened-thing 'basic-or-comp)
(cl-define-disjoint-primitive-concept 'composite-thing 'gened-thing 'basic-or-comp)
(cl-define-primitive-concept '0d 'gened-thing)
(cl-define-primitive-concept '1d 'gened-thing)
(cl-define-primitive-concept '2d 'gened-thing)
(cl-define-primitive-concept 'at-least-1d '(and 1d 2d))
(cl-define-primitive-concept 'at-most-1d '(and 0d 1d))
;;;
;;;
;;;
(cl-define-primitive-concept 'directed-element '(and 1d basic-thing))
(cl-define-disjoint-primitive-concept 'g-circle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-line '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-arrow 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-rectangle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-spline-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-text '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-point '(and 0d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'info-point '(and 0d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-diamond '(and 2d basic-thing) 'type)
)
;;;
;;;
;;;
(defqualifiedsubrole intersects-objects g-text)
(defqualifiedsubrole intersects-objects info-point)
(defqualifiedsubrole points-related-with g-diamond)
(defqualifiedsubrole points-related-with g-rectangle)
(defqualifiedsubrole points-related-with g-circle)
(defqualifiedsubrole linked-over-with g-diamond)
;;;
;;;
;;;
(def-or-concept g-line g-spline-chain)
(def-or-concept g-circle g-diamond)
(def-or-concept g-diamond g-rectangle)
(def-or-concept g-circle g-rectangle)
(def-or-concept g-arrow g-directed-spline-chain)
;;;
;;; Diese Konzepte sind wohl von generellem Nutzen:
;;;
(define-concept linker-point
(and
info-point
(exactly 1 point-part-of)))
(define-concept t-linker-point
(and
linker-point
(exactly 1 touching-objects)))
(define-concept linker
(and
g-line-or-g-spline-chain
(exactly 2 points-related-with)))
(define-concept dlinker
(and
g-arrow-or-g-directed-spline-chain
(exactly 2 points-related-with)))
(define-concept tt-linker
(and
linker
(all has-points t-linker-point)))
(define-concept dtt-linker
(and
dlinker
(all has-points t-linker-point)))
;;;
;;;
;;;
(define-concept is-a-link?
(and dlinker
(all points-related-with g-rectangle)))
(define-concept relationship-entity
(and linker
(at-least 2 intersects-objects)
(at-most 3 intersects-objects)
(exactly 2 intersects-objects-info-point)
(exactly 2 touching-objects)
(all touching-objects g-diamond-or-g-rectangle)
(all points-related-with g-diamond-or-g-rectangle)
(exactly 2 points-related-with)
(exactly 1 points-related-with-g-diamond)
(exactly 1 points-related-with-g-rectangle)
(none contained-in-objects)))
(defqualifiedsubrole linker-objects relationship-entity)
(define-concept cardinality
(and g-text
(none touching-objects)
(none contained-in-objects)
(none contains-objects)
(exactly 1 intersects-objects)
(all intersects-objects relationship-entity)
(all text-string
(set "1" "m" "n"))))
(define-concept e-attribute-entity
(and linker
(exactly 2 intersects-objects)
(all intersects-objects info-point)
(exactly 2 touching-objects)
(all touching-objects g-circle-or-g-rectangle)
(all points-related-with g-circle-or-g-rectangle)
(exactly 2 points-related-with)
(exactly 1 points-related-with-g-circle)
(exactly 1 points-related-with-g-rectangle)
(none contained-in-objects)))
(define-concept r-attribute-entity
(and linker
(exactly 2 intersects-objects)
(all intersects-objects info-point)
(exactly 2 touching-objects)
(all touching-objects g-circle-or-g-diamond)
(all points-related-with g-circle-or-g-diamond)
(exactly 2 points-related-with)
(exactly 1 points-related-with-g-circle)
(exactly 1 points-related-with-g-diamond)
(none contained-in-objects)))
(def-or-concept e-attribute-entity info-point)
(def-or-concept e-attribute-entity relationship-entity)
(def-or-concept e-attribute-entity-or-relationship-entity info-point)
(def-or-concept r-attribute-entity info-point)
(def-or-concept r-attribute-entity relationship-entity)
(def-or-concept r-attribute-entity-or-relationship-entity info-point)
(define-concept named-region
(and 2d basic-thing
(exactly 1 contains-objects)
(all contains-objects g-text)))
(define-concept entity
(and g-rectangle
named-region
(all linker-objects e-attribute-entity-or-relationship-entity)
(none intersects-objects)
(none contained-in-objects)
(all touching-objects
e-attribute-entity-or-relationship-entity-or-info-point)
(all linked-over-with g-circle-or-g-diamond)
(some linked-over-with-g-diamond)))
(defqualifiedsubrole linked-over-with entity)
(define-concept e-attribute
(and g-circle
named-region
(none intersects-objects)
(none contained-in-objects)
(all linker-objects e-attribute-entity)
(all touching-objects e-attribute-entity-or-info-point)
(exactly 2 touching-objects)
(exactly 1 linked-over-with)
(all linked-over-with entity)))
(define-concept r-attribute
(and g-circle
named-region
(none intersects-objects)
(none contained-in-objects)
(all linker-objects r-attribute-entity)
(all touching-objects r-attribute-entity-or-info-point)
(exactly 2 touching-objects)
(exactly 1 linked-over-with)
(all linked-over-with g-diamond)))
(def-or-concept e-attribute entity)
(def-or-concept r-attribute entity)
(define-concept is-a-link
(and is-a-link?
(all points-related-with entity)))
(define-concept 1-cardinality
(and cardinality
(is text-string "1")))
(define-concept m-cardinality
(and cardinality
(is text-string "m")))
(define-concept n-cardinality
(and cardinality
(is text-string "n")))
(defqualifiedsubrole intersects-objects 1-cardinality)
(defqualifiedsubrole intersects-objects m-cardinality)
(defqualifiedsubrole intersects-objects n-cardinality)
(define-concept 1-relationship-entity
(and relationship-entity
(exactly 1 intersects-objects-g-text)
(some intersects-objects-1-cardinality)))
(define-concept m-relationship-entity
(and relationship-entity
(exactly 1 intersects-objects-g-text)
(some intersects-objects-m-cardinality)))
(define-concept n-relationship-entity
(and relationship-entity
(exactly 1 intersects-objects-g-text)
(some intersects-objects-n-cardinality)))
(defqualifiedsubrole linker-objects 1-relationship-entity)
(defqualifiedsubrole linker-objects m-relationship-entity)
(defqualifiedsubrole linker-objects n-relationship-entity)
(define-concept binary-relationship
(and g-diamond
named-region
(all linker-objects r-attribute-entity-or-relationship-entity)
(exactly 2 linker-objects-relationship-entity)
(none intersects-objects)
(none contained-in-objects)
(all touching-objects
r-attribute-entity-or-relationship-entity-or-info-point)
(all linked-over-with r-attribute-or-entity)
(exactly 2 linked-over-with-entity)
(at-most 2 linker-objects-1-relationship-entity)
(at-most 1 linker-objects-m-relationship-entity)
(at-most 1 linker-objects-n-relationship-entity)))
;;;
;;;
;;;
(defconstant +known-concepts+
'(linker
dlinker
tt-linker
dtt-linker
g-circle
g-line
g-rectangle
g-arrow
g-polygon
g-spline-chain
g-directed-spline-chain
g-spline-polygon
g-chain
g-directed-chain
g-text
g-point
g-diamond
composite-thing
info-point
is-a-link
relationship-entity
cardinality
e-attribute-entity
r-attribute-entity
named-region
entity
1-cardinality
m-cardinality
n-cardinality
1-relationship-entity
m-relationship-entity
n-relationship-entity
binary-relationship
e-attribute
r-attribute
))
(defconstant +library-concepts+
`(g-diamond
1-cardinality
m-cardinality
n-cardinality
binary-relationship
e-attribute
r-attribute
entity
))
(defconstant +known-roles+
'((spatial-relation ; keine Inverse
in-relation-with-objects ; keine Inverse
; disjoint-with ; selbstinvers
touching-objects ; selbstinvers
intersects-objects ; selbstinvers
intersects-0-objects ; selbstinvers
intersects-1-objects ; selbstinvers
intersects-2-objects ; selbstinvers
contains-objects
contained-in-objects
directly-contains-objects
directly-contained-by-object
covers-objects
covered-by-object
linked-over-with ; selbstinvers
start-linked-over-with
end-linked-over-with
linker-objects
points-related-with
start-linker-objects
startpoint-related-with
end-linker-objects
endpoint-related-with
has-parts
part-of
has-points
point-part-of
has-startpoint
startpoint-part-of-directed-element
has-endpoint
endpoint-part-of-directed-element
;;; Attribute
belongs-to-clos-object
filled-bool
radius-real
text-string
xtrans-integer
ytrans-integer)
(intersects-objects-g-text
intersects-objects-info-point
points-related-with-g-diamond
points-related-with-g-rectangle
points-related-with-g-circle
linked-over-with-g-diamond)
(linker-objects-relationship-entity
intersects-objects-1-cardinality
intersects-objects-m-cardinality
intersects-objects-n-cardinality
linker-objects-1-relationship-entity
linker-objects-m-relationship-entity
linker-objects-n-relationship-entity)
(linked-over-with-entity)))
| 19,777 | Common Lisp | .lisp | 520 | 31.928846 | 99 | 0.657216 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 7c460c460b7944b016771b2ca7cae79172bda93513d2d3dd69a13bcc22f327cd | 11,227 | [
-1
] |
11,228 | knowledge4.lisp | lambdamikel_GenEd/src/knowledge/knowledge4.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: Knowledge; Base: 10 -*-
(in-package knowledge)
(cl-reader-init)
(cl-clear-kb)
(cl-startup)
(setf *krss-verbose* nil)
(cl-set-classic-warn-mode t)
;----------------------------------------------------------------
(defmacro defprimitive (name expr)
`(define-primitive-concept ,name ,expr))
(defmacro defdisjoint (name expr grouping)
`(define-disjoint-primitive-concept ,name ,grouping ,expr))
(defmacro defconcept (name expr)
`(define-concept ,name ,expr))
(defun cl-filler (derived-object role &optional remove-elem)
(let ((fillers (remove remove-elem (cl-fillers derived-object role)
:test #'eq)))
(when (second fillers)
(cerror "Return only first filler"
"Attribute ~S holds more than 1 filler for ~S: ~S"
role derived-object fillers))
(first fillers)))
(defun close-all-subroles (role &key exceptions
(inds (cl-concept-instances @pj-thing)))
(unless (member role exceptions :test #'eq)
(close-all-roles (cl-role-children role) inds exceptions)
(dolist (role (cl-role-children role))
(close-all-subroles role :exceptions exceptions :inds inds))))
(defun close-all-roles (roles
&optional (inds (cl-concept-instances @pj-thing))
(exceptions nil))
(dolist (role roles)
(unless (member role exceptions :test #'eq)
(dolist (ind inds)
(unless (cl-ind-closed-role? ind role)
(cl-ind-close-role ind role))))))
(defun find-possible-subsumees (inds)
(dolist (ind inds)
(let* ((parents (cl-ind-parents ind))
(children (delete nil (mapcar #'cl-concept-children parents))))
(when children
(format t "~&Individual ~S may be further specialized to ~S"
ind children)))))
;----------------------------------------------------------------
;;;
;;;
;;;
(defun cl-inv-role-name (role)
(let ((inv (cl-role-inverse (cl-named-role role))))
(when inv
(cl-role-name inv))))
(defmacro defqualifiedsubrole (role
qualification
&key
(specialized-concept t) ;;; funktioniert eigentlich nur bei nil korrekt! (default t ?)
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
(parent role)
(inverse-parent (or (cl-inv-role-name parent)
role)))
`(progn
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-FILLER-RULE"))
,(if specialized-concept
`(cl-named-concept ',qualification)
'(cl-named-concept 'classic-thing))
(cl-named-role ',name) ; Rolle, die gefuellt wird
#'(lambda (ind role)
(remove-if-not #'(lambda (ind)
(cl-instance? ind
(cl-named-concept ',qualification)))
(cl-fillers ind (cl-named-role ',parent))))
:filter
'(and
(at-least 1 ,parent)
(test-c cl-test-closed-roles? (,role))))))
#|
;;; Haarslev:
(defmacro defqualifiedsubrole (role
qualification
&key
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
(parent role)
(inverse-parent (or (cl-inv-role-name parent)
role))
(specialized-concept t)
break)
`(progn
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-INV-FILLER-RULE"))
,(if specialized-concept
`(cl-named-concept ',qualification)
'(cl-named-concept 'classic-thing))
(cl-named-role ',inv-name)
#'(lambda (ind role)
(declare (ignore role))
(when ,break
(break "in filler rule of ~A" ',inv-name))
(or
(cl-fillers ind (cl-named-role ',inverse-parent))
(break "NIL as filler computed for ~A"
',inv-name)))
:filter
'(and (at-least 1 ,inverse-parent)
(test-c cl-test-closed-roles? (,role))))))
|#
;;;
;;;
;;;
;----------------------------------------------------------------
(cl-define-primitive-role 'spatial-relation)
(cl-define-primitive-role 'in-relation-with-objects :inverse 'in-relation-with-objects
:parent 'spatial-relation)
(cl-define-primitive-role 'disjoint-with :inverse 'disjoint-with
:parent 'spatial-relation)
(cl-define-primitive-role 'touching-objects :inverse 'touching-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-objects :inverse 'intersects-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-0-objects :inverse 'intersects-0-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
(cl-define-primitive-role 'intersects-1-objects :inverse 'intersects-1-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
(cl-define-primitive-role 'intersects-2-objects :inverse 'intersects-2-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
;;; spatial-relation
;;; / \
;;; in-rel.w. disj.w.
;;; / | \
;;; / | \
;;; / | \
;;; touching inters. contains
;;; /|\ |
;;; / | \ direc.contains
;;; 0 1 2 |
;;; covers
(cl-define-primitive-role 'contains-objects :inverse 'contained-in-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'directly-contains-objects :inverse 'directly-contained-by-object
:parent 'contains-objects
:inverse-parent 'contained-in-objects)
(cl-define-primitive-role 'covers-objects :inverse 'covered-by-object
:parent 'directly-contains-objects
:inverse-parent 'directly-contained-by-object)
;;;
;;; In diesen Rollen steht, mit wem das Ind. verbunden ist, und ueber welches Ende des Pfeiles:
;;;
;;; linked-over-with
;;; / \
;;; start-link.o.w. end-link.o.w. 0 ----> # : start-l.o.w.(0,#),
;;; end-l.o.w.(#,0),
;;; l.o.w.(#,0) /\ l.o.w(0,#).
(cl-define-primitive-role 'linked-over-with :inverse 'linked-over-with
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linked-over-with :inverse 'end-linked-over-with
:parent 'linked-over-with
:inverse-parent 'linked-over-with)
;;;
;;; Hier werden die Linker eingetragen: 0 -----> # : linker-objects(A,L), linker-objects(B,L).
;;; A L B
(cl-define-primitive-role 'linker-objects :inverse 'points-related-with
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linker-objects :inverse 'startpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
(cl-define-primitive-role 'end-linker-objects :inverse 'endpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
;;;
;;;
;;;
;;; Rollen eines Linkers: points-related-with
;;; / \ 0 ----> # : s.r.w.(L,A), e.r.w.(L,B)
;;; startpoint-rel.-w. endpoint-rel.-w. A L B
#|
(cl-define-primitive-role 'points-related-with :inverse 'linker-objects
:parent 'in-relation-with-objects)
(cl-define-primitive-role 'startpoint-related-with :inverse 'endpoint-related-with
:parent 'points-related-with
:inverse-parent 'points-related-with)
|#
;;;
;;; Fuer Composite-Things:
;;;
(cl-define-primitive-role 'has-parts :inverse 'part-of
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
;;;
;;; Fuer Directed-Elements:
;;;
(cl-define-primitive-role 'has-points
:parent 'has-parts
:inverse 'point-part-of
:inverse-parent 'part-of)
(cl-define-primitive-role 'has-startpoint
:parent 'has-points
:inverse 'startpoint-part-of-directed-element
:inverse-parent 'point-part-of)
(cl-define-primitive-role 'has-endpoint
:parent 'has-points
:inverse 'endpoint-part-of-directed-element
:inverse-parent 'point-part-of)
;;;
;;;
;;;
(cl-define-primitive-role 'filled-bool :attribute t)
(cl-define-primitive-role 'radius-real :attribute t)
(cl-define-primitive-role 'text-string :attribute t)
(cl-define-primitive-role 'xtrans-integer :attribute t)
(cl-define-primitive-role 'ytrans-integer :attribute t)
(cl-define-primitive-role 'belongs-to-clos-object :attribute t)
;;;
;;;
;;;
(cl-define-primitive-concept 'gened-thing 'classic-thing)
(cl-define-disjoint-primitive-concept 'basic-thing 'gened-thing 'basic-or-comp)
(cl-define-disjoint-primitive-concept 'composite-thing 'gened-thing 'basic-or-comp)
(cl-define-primitive-concept '0d 'gened-thing)
(cl-define-primitive-concept '1d 'gened-thing)
(cl-define-primitive-concept '2d 'gened-thing)
(cl-define-primitive-concept 'at-least-1d '(and 1d 2d))
(cl-define-primitive-concept 'at-most-1d '(and 0d 1d))
;;;
;;;
;;;
(cl-define-primitive-concept 'directed-element '(and 1d basic-thing))
(cl-define-disjoint-primitive-concept 'g-circle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-line '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-arrow 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-rectangle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-spline-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-text '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-point '(and 0d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'info-point '(and 0d basic-thing) 'type)
;;;
;;;
;;;
(defqualifiedsubrole linked-over-with g-circle
:parent linked-over-with :inverse-parent linked-over-with)
(defqualifiedsubrole linked-over-with g-rectangle
:parent linked-over-with :inverse-parent linked-over-with)
;;; diese Rolle laesst sich nur definieren, wenn die Regel auf gened-thing feuert,
;;; da stelle noch gar nicht definiert ist! ansonsten muesste sie spaeter nach stelle definiert werden!
;;; allgemeiner Regeltrigger -> weniger DAG-Abhaengigkeiten
;;; deswegen: specialized-concept nil (default ist t)
(defqualifiedsubrole has-parts stelle
:parent has-parts :inverse-parent part-of :specialized-concept nil)
;;;
;;; das gleiche gilt fuer diese
;;;
(defqualifiedsubrole has-parts stelle-mit-marken
:parent has-parts :inverse-parent part-of :specialized-concept nil)
;;;
;;; diese sind unkritisch, da die Konzepte bereits definiert sind
;;;
(defqualifiedsubrole has-parts g-rectangle
:parent has-parts :inverse-parent part-of)
(defqualifiedsubrole has-parts directed-element
:parent has-parts :inverse-parent part-of)
(defqualifiedsubrole touching-objects directed-element
:parent touching-objects :inverse-parent touching-objects)
;;;
;;; Diese Konzepte sind wohl von generellem Nutzen:
;;;
(define-concept nur-beruehrende-objekte
(and
basic-thing
(none contained-in-objects)
(some touching-objects)
(none has-parts)))
(define-concept verbinder-punkt
(and
info-point
(exactly 1 point-part-of)))
(define-concept t-verbinder-punkt
(and
verbinder-punkt
(at-least 1 touching-objects))) ;eigentlich (exactly 1 touching-objects) -> Error in Splines!
(define-concept c-verbinder-punkt
(and
verbinder-punkt
(exactly 1 covered-by-object)))
(define-concept i-verbinder-punkt
(and
verbinder-punkt
(exactly 1 directly-contained-by-object)))
(define-concept verbinder
(and
directed-element
(exactly 2 points-related-with)))
(define-concept tt-verbinder
(and
verbinder
(all has-points t-verbinder-punkt)))
(define-concept ii-verbinder
(and
verbinder
(all has-points i-verbinder-punkt)))
(define-concept it-verbinder
(and
verbinder
(all has-startpoint i-verbinder-punkt)
(all has-endpoint t-verbinder-punkt)))
(define-concept ti-verbinder
(and
verbinder
(all has-startpoint t-verbinder-punkt)
(all has-endpoint i-verbinder-punkt)))
(define-concept ct-verbinder
(and
verbinder
(all has-startpoint c-verbinder-punkt)
(all has-endpoint t-verbinder-punkt)))
(define-concept tc-verbinder
(and
verbinder
(all has-startpoint t-verbinder-punkt)
(all has-endpoint c-verbinder-punkt)))
(define-concept ci-verbinder
(and
verbinder
(all has-startpoint c-verbinder-punkt)
(all has-endpoint i-verbinder-punkt)))
(define-concept ic-verbinder
(and
verbinder
(all has-startpoint i-verbinder-punkt)
(all has-endpoint c-verbinder-punkt)))
;;;;
;;;;
;;;;
(defun string-is-integer-p (string)
(integerp
(read-from-string string)))
(cl-define-concept 'kapazitaets-label
'(and
g-text
(at-least 1 intersects-objects)
(all text-string
(and (test-h string-is-integer-p)))))
;;; diese Regel feuert auf Konzept, das bereits definiert ist und wird auch
;;; nicht vorher verwendet -> specialized-concept t (default)
(defqualifiedsubrole intersects-objects kapazitaets-label
#| :inv-name intersects-objects-kapazitaets-label |#
:parent intersects-objects :inverse-parent intersects-objects)
;;;
;;;
;;;
(define-concept stelle-oder-transition
(and
nur-beruehrende-objekte
(all touching-objects-directed-element tt-verbinder)))
(define-concept stelle?
(and
g-circle
stelle-oder-transition))
(define-concept transition?
(and
g-rectangle
stelle-oder-transition))
;;;
;;;
;;;
(define-concept stelle
(and
stelle?
(all linked-over-with transition?)))
(define-concept konflikt-stelle
(and
stelle
(at-least 2 end-linked-over-with)))
(define-concept start-stelle
(and
stelle
(none start-linked-over-with)))
(define-concept end-stelle
(and
stelle
(none end-linked-over-with)))
(define-concept normale-stelle
(and
stelle
(some start-linked-over-with)
(some end-linked-over-with)))
(define-concept stelle-mit-kapazitaet
(and
stelle
(exactly 1 intersects-objects-kapazitaets-label)))
(cl-define-concept 'marke
'(and
g-circle
(all contained-in-objects stelle)
(fills filled-bool t)
(all radius-real
(and number
(min 2.0)
(max 10.0)))))
(define-concept stelle-mit-marken
(and
stelle
(some contains-objects)
(all contains-objects marke)))
(defun ueberlaufene-stelle? (ind)
(let* ((marken-rolle (cl-named-role 'contains-objects))
(marken (length (cl-fillers ind marken-rolle)))
(label-rolle (cl-named-role 'intersects-objects-kapazitaets-label))
(text-ind (first (cl-fillers ind label-rolle)))
(number (read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))))
(> marken number)))
(defun label-kleiner-1? (ind)
(let* ((rolle (cl-named-role 'intersects-objects-kapazitaets-label))
(text-ind (first (cl-fillers ind rolle)))
(kap
(if text-ind
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))
1)))
(<= kap 1)))
(cl-define-concept 'ueberlaufene-stelle!!!
'(and
stelle-mit-marken
stelle-mit-kapazitaet
(test-c cl-test-closed-roles? (contains-objects intersects-objects-kapazitaets-label))
(test-c ueberlaufene-stelle?)))
(cl-define-concept 'b/e-stelle
'(and
stelle
(test-c cl-test-closed-roles?
(intersects-objects-kapazitaets-label))
(test-c label-kleiner-1?)))
;;;
;;;
;;;
(define-concept transition
(and
transition?
(at-least 2 linked-over-with)
(at-least 1 start-linker-objects)
(at-least 1 end-linker-objects)
(all linked-over-with stelle?)))
(define-concept netz-kante
(and
tt-verbinder
(all touching-objects stelle-oder-transition)))
(define-concept netz-kante-mit-kapazitaet
(and
netz-kante
(exactly 1 intersects-objects-kapazitaets-label)))
(cl-define-concept 'b/e-netz-kante
'(and
netz-kante
(test-c cl-test-closed-roles? (intersects-objects-kapazitaets-label))
(test-c label-kleiner-1?)))
;;;
;;;
;;;
(defun genug-input-marken? (ind)
(let* ((end-linker (cl-named-role 'end-linker-objects))
(flag nil))
(or
(every #'(lambda (end-linker)
(let* ((text-ind
(first
(cl-fillers
end-linker
(cl-named-role 'intersects-objects-kapazitaets-label))))
(stelle
(first
(cl-fillers
end-linker
(cl-named-role 'startpoint-related-with))))
(kap
(if text-ind
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))
1)) ; Kante hat sonst Kap. 1 (wie bei BE-Netzen)
(marken
(length
(cl-fillers
stelle
(cl-named-role 'contains-objects)))))
(if (and marken kap)
(not (minusp (- marken kap)))
(progn
(setf flag '?)
nil))))
(cl-fillers ind end-linker))
flag)))
(defun genug-output-marken? (ind)
(let* ((start-linker (cl-named-role 'start-linker-objects))
(flag nil))
(or
(every #'(lambda (start-linker)
(let* ((text-ind
(first
(cl-fillers
start-linker
(cl-named-role 'intersects-objects-kapazitaets-label))))
(stelle
(first
(cl-fillers
start-linker
(cl-named-role 'endpoint-related-with))))
(kap
(if text-ind
(read-from-string
(first
(cl-fillers
text-ind
(cl-named-role 'text-string))))
1))
(marken
(length
(cl-fillers
stelle
(cl-named-role 'contains-objects))))
(stellen-text-ind
(first
(cl-fillers
stelle
(cl-named-role 'intersects-objects-kapazitaets-label))))
(stellen-kap
(if stellen-text-ind
(read-from-string
(first
(cl-fillers
stellen-text-ind
(cl-named-role 'text-string))))
10000))) ; kein Label -> Kap. unbegrenzt ! (w)
(if (and stellen-kap kap marken)
(<= (+ marken kap) stellen-kap)
(progn
(setf flag '?)
nil))))
(cl-fillers ind start-linker))
flag)))
(cl-define-concept 'l-aktive-transition
'(and
transition
(all start-linked-over-with
stelle-mit-marken)
(all end-linker-objects netz-kante)
(test-c cl-test-closed-roles? (end-linker-objects start-linked-over-with))
(test-c genug-input-marken?)))
(cl-define-concept 'r-aktive-transition
'(and
transition
(all end-linked-over-with
stelle)
(all start-linker-objects netz-kante)
(test-c cl-test-closed-roles? (start-linker-objects end-linked-over-with))
(test-c genug-output-marken?)))
(cl-define-concept 'aktive-transition
'(and
l-aktive-transition
r-aktive-transition))
;;;
;;;
;;;
(define-concept petri-netz
(and
composite-thing
(at-least 5 has-parts)
(some has-parts-stelle)
(all has-parts-g-rectangle transition)
(all has-parts-directed-element netz-kante)))
(define-concept s/t-petri-netz
(and
petri-netz
(some has-parts-stelle-mit-marken)))
(define-concept b/e-petri-netz
(and
s/t-petri-netz
(all has-parts-stelle b/e-stelle)
(all has-parts-directed-element b/e-netz-kante)))
;;;
;;;
;;;
(defconstant +known-concepts+
'(verbinder
tt-verbinder
ii-verbinder
ti-verbinder
it-verbinder
ci-verbinder
ic-verbinder
tc-verbinder
ct-verbinder
stelle transition netz-kante
l-aktive-transition
r-aktive-transition
aktive-transition
netz-kante-mit-kapazitaet
marke
konflikt-stelle
ueberlaufene-stelle!!!
start-stelle end-stelle normale-stelle
b/e-stelle
b/e-netz-kante
kapazitaets-label
stelle-mit-kapazitaet
stelle-mit-marken
petri-netz
s/t-petri-netz
b/e-petri-netz
g-circle
g-line
g-rectangle
g-arrow
g-polygon
g-spline-chain
g-directed-spline-chain
g-spline-polygon
g-chain
g-directed-chain
g-text
g-point
composite-thing
info-point
))
(defconstant +library-concepts+
`(verbinder
kapazitaets-label
stelle
start-stelle
normale-stelle
end-stelle
stelle-mit-marken
stelle-mit-kapazitaet
marke
transition))
(defconstant +known-roles+
'((
belongs-to-clos-object
spatial-relation
in-relation-with-objects
disjoint-with
touching-objects
intersects-objects
intersects-0-objects
intersects-1-objects
intersects-2-objects
contains-objects
contained-in-objects
directly-contains-objects
directly-contained-by-object
covers-objects
covered-by-object
linked-over-with
start-linked-over-with
end-linked-over-with
points-related-with
startpoint-related-with
endpoint-related-with
linker-objects
start-linker-objects
end-linker-objects
has-points
has-startpoint
has-endpoint
has-parts
part-of
point-part-of
startpoint-part-of-directed-element
endpoint-part-of-directed-element
filled-bool
radius-real
text-string
xtrans-integer
ytrans-integer)
(
has-parts-stelle
has-parts-g-rectangle
has-parts-directed-element
has-parts-stelle-mit-marken
touching-objects-directed-element-inverse
touching-objects-directed-element
intersects-objects-kapazitaets-label
)))
| 24,528 | Common Lisp | .lisp | 724 | 26.63674 | 103 | 0.617433 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 47d4c625050bed8f3605b14d6b504311478489eb876ac0765e2a15cfc6f7ad84 | 11,228 | [
-1
] |
11,229 | knowledge6.lisp | lambdamikel_GenEd/src/knowledge/knowledge6.lisp | ;;; -*- Mode: Lisp; Syntax: Ansi-Common-Lisp; Package: Knowledge; Base: 10 -*-
(in-package knowledge)
(cl-reader-init)
(cl-clear-kb)
(cl-startup)
(setf *krss-verbose* nil)
(cl-set-classic-warn-mode t)
;----------------------------------------------------------------
(defun cl-filler (derived-object role &optional remove-elem)
(let ((fillers (remove remove-elem (cl-fillers derived-object role)
:test #'eq)))
(when (second fillers)
(cerror "Return only first filler"
"Attribute ~S holds more than 1 filler for ~S: ~S"
role derived-object fillers))
(first fillers)))
(defun close-all-subroles (role &key exceptions
(inds (cl-concept-instances @pj-thing)))
(unless (member role exceptions :test #'eq)
(close-all-roles (cl-role-children role) inds exceptions)
(dolist (role (cl-role-children role))
(close-all-subroles role :exceptions exceptions :inds inds))))
(defun close-all-roles (roles
&optional (inds (cl-concept-instances @pj-thing))
(exceptions nil))
(dolist (role roles)
(unless (member role exceptions :test #'eq)
(dolist (ind inds)
(unless (cl-ind-closed-role? ind role)
(cl-ind-close-role ind role))))))
(defun find-possible-subsumees (inds)
(dolist (ind inds)
(let* ((parents (cl-ind-parents ind))
(children (delete nil (mapcar #'cl-concept-children parents))))
(when children
(format t "~&Individual ~S may be further specialized to ~S"
ind children)))))
;----------------------------------------------------------------
#+:allegro
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun cl-inv-role-name (role)
(print role)
(let ((inv (cl-role-inverse (cl-named-role role))))
(when inv
(cl-role-name inv))))
(defmacro defqualifiedsubrole (role
qualification
&key
(name
(intern
(concatenate 'string
(string role)
"-"
(string qualification))))
(inv-name
(intern
(concatenate 'string
(string name) "-INVERSE")))
(parent role)
(inverse-parent (or (cl-inv-role-name parent)
role))
(specialized-concept t)
break)
`(progn
(cl-define-primitive-role ',name :inverse ',inv-name
:parent ',parent
:inverse-parent ',inverse-parent)
(cl-add-filler-rule ',(intern (concatenate 'string (string name)
"-INV-FILLER-RULE"))
,(if specialized-concept
`(cl-named-concept ',qualification)
'(cl-named-concept 'classic-thing))
(cl-named-role ',inv-name)
#'(lambda (ind role)
(declare (ignore role))
(when ,break
(break "in filler rule of ~A" ',inv-name))
(or
(cl-fillers ind (cl-named-role ',inverse-parent))
(break "NIL as filler computed for ~A"
',inv-name)))
:filter
'(and (at-least 1 ,inverse-parent)
(test-c cl-test-closed-roles? (,role))))))
(defmacro def-or-concept (concept1 concept2)
(let ((or-name
(intern (concatenate 'string
(write-to-string concept1)
"-OR-"
(write-to-string concept2)))))
`(progn
(cl-define-primitive-concept
',or-name
'basic-thing)
(cl-add-rule ',(gensym)
(cl-named-concept ',concept1)
',or-name)
(cl-add-rule ',(gensym)
(cl-named-concept ',concept2)
',or-name))))
;----------------------------------------------------------------
;;; selbstinverse Basisrelationen
(cl-define-primitive-role 'spatial-relation :inverse 'spatial-relation)
(cl-define-primitive-role 'in-relation-with-objects :inverse 'in-relation-with-objects
:parent 'spatial-relation
:inverse-parent 'spatial-relation)
(cl-define-primitive-role 'disjoint-with :inverse 'disjoint-with :parent 'spatial-relation
:inverse-parent 'spatial-relation)
(cl-define-primitive-role 'touching-objects :inverse 'touching-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-objects :inverse 'intersects-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'intersects-0-objects :inverse 'intersects-0-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
(cl-define-primitive-role 'intersects-1-objects :inverse 'intersects-1-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
(cl-define-primitive-role 'intersects-2-objects :inverse 'intersects-2-objects
:parent 'intersects-objects
:inverse-parent 'intersects-objects)
;;;
;;; spatial-relation
;;; / \
;;; in-rel.w. disj.w.
;;; / | \
;;; / | \
;;; / | \
;;; touching inters. contains
;;; /|\ |
;;; / | \ direc.contains
;;; 0 1 2 |
;;; covers
;----------------------------------------------------------------
;;; nicht-selbstinverse Basisrelationen
(cl-define-primitive-role 'contains-objects :inverse 'contained-in-objects
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'directly-contains-objects :inverse 'directly-contained-by-object
:parent 'contains-objects
:inverse-parent 'contained-in-objects)
(cl-define-primitive-role 'covers-objects :inverse 'covered-by-object
:parent 'directly-contains-objects
:inverse-parent 'directly-contained-by-object)
;----------------------------------------------------------------
;;;
;;; In diesen Rollen steht, mit wem das Ind. verbunden ist, und ueber welches Ende des Pfeiles:
;;;
;;; linked-over-with
;;; / \
;;; start-link.o.w. end-link.o.w. 0 ----> # : start-l.o.w.(0,#),
;;; end-l.o.w.(#,0),
;;; l.o.w.(#,0) /\ l.o.w(0,#).
(cl-define-primitive-role 'linked-over-with :inverse 'linked-over-with
:parent 'in-relation-with-objects
:inverse-parent 'linked-over-with)
(cl-define-primitive-role 'start-linked-over-with :inverse 'end-linked-over-with
:parent 'linked-over-with
:inverse-parent 'linked-over-with)
;;;
;;; Hier werden die Linker eingetragen: 0 -----> # : linker-objects(A,L), linker-objects(B,L).
;;; A L B
(cl-define-primitive-role 'linker-objects :inverse 'points-related-with
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
(cl-define-primitive-role 'start-linker-objects :inverse 'startpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
(cl-define-primitive-role 'end-linker-objects :inverse 'endpoint-related-with
:parent 'linker-objects
:inverse-parent 'points-related-with)
;;;
;;; Rollen eines Linkers: points-related-with
;;; / \ 0 ----> # : s.r.w.(L,A), e.r.w.(L,B)
;;; startpoint-rel.-w. endpoint-rel.-w. A L B
;;;
;;; Fuer Composite-Things:
;;;
(cl-define-primitive-role 'has-parts :inverse 'part-of
:parent 'in-relation-with-objects
:inverse-parent 'in-relation-with-objects)
;;;
;;; Fuer Directed-Elements:
;;;
(cl-define-primitive-role 'has-points :inverse 'point-part-of
:parent 'has-parts
:inverse-parent 'part-of)
(cl-define-primitive-role 'has-startpoint :inverse 'startpoint-part-of-directed-element
:parent 'has-points
:inverse-parent 'point-part-of)
(cl-define-primitive-role 'has-endpoint :inverse 'endpoint-part-of-directed-element
:parent 'has-points
:inverse-parent 'point-part-of)
;----------------------------------------------------------------
;;;
;;;
;;;
(cl-define-primitive-role 'filled-bool :attribute t)
(cl-define-primitive-role 'radius-real :attribute t)
(cl-define-primitive-role 'text-string :attribute t)
(cl-define-primitive-role 'xtrans-integer :attribute t)
(cl-define-primitive-role 'ytrans-integer :attribute t)
(cl-define-primitive-role 'belongs-to-clos-object :attribute t)
;----------------------------------------------------------------
;;;
;;;
;;;
(cl-define-primitive-concept 'gened-thing 'classic-thing)
(cl-define-disjoint-primitive-concept 'basic-thing 'gened-thing 'basic-or-comp)
(cl-define-disjoint-primitive-concept 'composite-thing 'gened-thing 'basic-or-comp)
(cl-define-primitive-concept '0d 'gened-thing)
(cl-define-primitive-concept '1d 'gened-thing)
(cl-define-primitive-concept '2d 'gened-thing)
(cl-define-primitive-concept 'at-least-1d '(and 1d 2d))
(cl-define-primitive-concept 'at-most-1d '(and 0d 1d))
;;;
;;;
;;;
(cl-define-primitive-concept 'directed-element '(and 1d basic-thing))
(cl-define-disjoint-primitive-concept 'g-circle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-line '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-arrow 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-rectangle '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-polygon '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-spline-chain '(and 1d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-directed-spline-chain 'directed-element 'type)
(cl-define-disjoint-primitive-concept 'g-text '(and 2d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-point '(and 0d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'info-point '(and 0d basic-thing) 'type)
(cl-define-disjoint-primitive-concept 'g-diamond '(and 2d basic-thing) 'type)
)
;;;
;;;
;;;
(defqualifiedsubrole intersects-objects g-text)
(defqualifiedsubrole touching-objects g-line)
(defqualifiedsubrole touching-objects g-rectangle)
(defqualifiedsubrole touching-objects g-diamond)
(defqualifiedsubrole touching-objects g-circle)
(def-or-concept g-line g-spline-chain)
(defqualifiedsubrole touching-objects g-line-or-g-spline-chain)
;;;
;;; Diese Konzepte sind wohl von generellem Nutzen:
;;;
(define-concept linker-point
(and
info-point
(exactly 1 point-part-of)))
(define-concept t-linker-point
(and
linker-point
(exactly 1 touching-objects)))
(define-concept linker
(and
g-line-or-g-spline-chain
(exactly 2 points-related-with)))
(define-concept tt-linker
(and
linker
(all has-points t-linker-point)))
;;;
;;;
;;;
(def-or-concept g-rectangle g-diamond)
(defqualifiedsubrole touching-objects g-rectangle-or-g-diamond)
(cl-define-concept 'relationship-entity
'(and linker
(at-least 2 touching-objects)
(at-most 2 touching-objects)
(at-least 1 intersects-objects-g-text)
(at-most 1 intersects-objects-g-text)
(at-least 2 touching-objects-g-rectangle-or-g-diamond)
(at-most 2 touching-objects-g-rectangle-or-g-diamond)
(at-least 1 touching-objects-g-rectangle)
(at-most 1 touching-objects-g-rectangle)
(at-least 1 touching-objects-g-diamond)
(at-most 1 touching-objects-g-diamond)))
(defqualifiedsubrole touching-objects relationship-entity)
(cl-define-concept 'cardinality
'(and g-text
(at-least 1 intersects-objects)
(all intersects-objects relationship-entity)
(all text-string
(one-of "1" "m" "n"))))
(def-or-concept g-circle g-rectangle)
(cl-define-concept 'attribute-entity
'(and linker
(at-least 2 touching-objects)
(at-most 2 touching-objects)
(at-most 0 intersects-objects-g-text)
(all touching-objects g-circle-or-g-rectangle)
(at-least 1 touching-objects-g-rectangle)
(at-most 1 touching-objects-g-rectangle)
(at-least 1 touching-objects-g-circle)
(at-most 1 touching-objects-g-circle)))
(def-or-concept attribute-entity relationship-entity)
(cl-define-concept 'named-region
'(and 2d basic-thing
(at-least 1 contains-objects)
(at-most 1 contains-objects)
(all contains-objects g-text)))
(defqualifiedsubrole linked-over-with g-diamond)
(def-or-concept g-circle g-diamond)
(cl-define-concept 'entity
'(and g-rectangle named-region
(at-least 1 touching-objects-relationship-entity)
(at-most 1 touching-objects-relationship-entity)
(all touching-objects-g-line-or-g-spline-chain
attribute-entity-or-relationship-entity)
(at-least 1 linked-over-with-g-diamond)
(at-most 1 linked-over-with-g-diamond)
(all linked-over-with g-circle-or-g-diamond)))
(cl-define-concept '1-cardinality
'(and cardinality
(all text-string (one-of "1"))))
(cl-define-concept 'm-cardinality
'(and cardinality
(all text-string (one-of "m"))))
(cl-define-concept 'n-cardinality
'(and cardinality
(all text-string (one-of "n"))))
(cl-define-concept '1-relationship-entity
'(and relationship-entity
(all intersects-objects 1-cardinality)))
(cl-define-concept 'm-relationship-entity
'(and relationship-entity
(all intersects-objects m-cardinality)))
(cl-define-concept 'n-relationship-entity
'(and relationship-entity
(all intersects-objects n-cardinality)))
(defqualifiedsubrole touching-objects 1-relationship-entity)
(defqualifiedsubrole touching-objects m-relationship-entity)
(defqualifiedsubrole touching-objects n-relationship-entity)
(cl-define-concept 'relationship
'(and g-diamond named-region
(at-least 2 linked-over-with)
(at-most 2 linked-over-with)
(all linked-over-with entity)
(at-least 2 touching-objects-g-line-or-g-spline-chain)
(at-most 2 touching-objects-g-line-or-g-spline-chain)
(all touching-objects-g-line-or-g-spline-chain relationship-entity)
(at-most 2 touching-objects-1-relationship-entity)
(at-most 1 touching-objects-m-relationship-entity)
(at-most 1 touching-objects-n-relationship-entity)))
(cl-define-concept 'attribute
'(and g-circle named-region
(at-least 1 linked-over-with)
(at-most 1 linked-over-with)
(all linked-over-with entity)))
;;;
;;;
;;;
(defconstant +known-concepts+
'(linker
tt-linker
g-circle
g-line
g-rectangle
g-arrow
g-polygon
g-spline-chain
g-directed-spline-chain
g-spline-polygon
g-chain
g-directed-chain
g-text
g-point
g-diamond
composite-thing
info-point
relationship-entity
cardinality
attribute-entity
named-region
entity
1-cardinality
m-cardinality
n-cardinality
1-relationship-entity
m-relationship-entity
n-relationship-entity
relationship
attribute
))
(defconstant +library-concepts+
`(g-diamond
1-cardinality
m-cardinality
n-cardinality
relationship
attribute
entity
))
(defconstant +known-roles+
'((
spatial-relation ; keine Inverse
in-relation-with-objects ; keine Inverse
disjoint-with ; selbstinvers
touching-objects ; selbstinvers
intersects-objects ; selbstinvers
intersects-0-objects ; selbstinvers
intersects-1-objects ; selbstinvers
intersects-2-objects ; selbstinvers
contains-objects
contained-in-objects
directly-contains-objects
directly-contained-by-object
covers-objects
covered-by-object
linked-over-with ; selbstinvers
start-linked-over-with
end-linked-over-with
linker-objects
points-related-with
start-linker-objects
startpoint-related-with
end-linker-objects
endpoint-related-with
has-parts
part-of
has-points
point-part-of
has-startpoint
startpoint-part-of-directed-element
has-endpoint
endpoint-part-of-directed-element
;;; Attribute
belongs-to-clos-object
filled-bool
radius-real
text-string
xtrans-integer
ytrans-integer)
(
intersects-objects-g-text
touching-objects-g-line
touching-objects-g-rectangle
touching-objects-g-diamond
touching-objects-g-circle)
(touching-objects-g-line-or-g-spline-chain
touching-objects-g-rectangle-or-g-diamond
linked-over-with-g-diamond)
(
touching-objects-relationship-entity
touching-objects-1-relationship-entity
touching-objects-m-relationship-entity
touching-objects-n-relationship-entity
)))
| 17,990 | Common Lisp | .lisp | 453 | 32.604857 | 99 | 0.631375 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | d6a5a0e40f2e31bdd18db46ebad265b3b3eb56e532b8b1a26e069892ebc9f80d | 11,229 | [
-1
] |
11,237 | er-pilot2-class | lambdamikel_GenEd/src/scenes/er-pilot2-class | GENED::SCENE-DATA
14
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
129/2
75/2
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::ENTITY)
(KNOWLEDGE:G-RECTANGLE)
503
246
NIL
GENED::SCALEABLE-THING
1.0
1.0
131
77
GENED::ROTATEABLE-THING
0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
129/2
75/2
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::ENTITY)
(KNOWLEDGE:G-RECTANGLE)
76
251
NIL
GENED::SCALEABLE-THING
1.0
1.0
131
77
GENED::ROTATEABLE-THING
0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
61
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
455
72
NIL
GENED::SCALEABLE-THING
1.0
1.0
124
124
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
61
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
458
458
NIL
GENED::SCALEABLE-THING
1.0
1.0
124
124
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
137/2
137/2
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::BINARY-RELATIONSHIP)
(KNOWLEDGE::G-DIAMOND)
281
250
NIL
GENED::SCALEABLE-THING
-97/139
-99/139
139
139
GENED::ROTATEABLE-THING
0.7853981633974483d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
353/2
250
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
69/2
0
GENED::UNFIXED-START-HANDLE
-69/2
0
GENED::LINESEGMENT
(-69/2 0)
(69/2 0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
787/2
249
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
85/2
0
GENED::UNFIXED-START-HANDLE
-85/2
0
GENED::LINESEGMENT
(-85/2 0)
(85/2 0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
481
170
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
25
35
GENED::UNFIXED-START-HANDLE
-25
-35
GENED::LINESEGMENT
(-25 -35)
(25 35)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
483
340
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-24
55
GENED::UNFIXED-START-HANDLE
24
-55
GENED::LINESEGMENT
(24 -55)
(-24 55)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"flies"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
257
272
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"pilot"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
478
263
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"age"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
436
96
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"salary"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
423
480
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"aircraft"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
36
259
NIL
GENED::INK-MIXIN
0.4
| 4,267 | Common Lisp | .cl | 326 | 12.088957 | 70 | 0.846993 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | e87dbf36c74423aef8b66bc78ca302c1383ffc99354a95e4582f98981efd6f05 | 11,237 | [
-1
] |
11,285 | label-object | lambdamikel_GenEd/src/objects/label-object | GENED::OBJECT-DATA
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
4
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-LINE)
NIL
164.0
214.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
59.0
0.0
GENED::UNFIXED-START-HANDLE
-59.0
0.0
GENED::LINESEGMENT
(-59.0 0.0)
(59.0 0.0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.8
GENED::LINETHICKNESS-MIXIN
3
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"Gened -"
:ITALIC
:SERIF
:HUGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
108
249
NIL
GENED::INK-MIXIN
0.9
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"The Generic Graphic Editor"
:ITALIC
:SERIF
:NORMAL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
127
272
NIL
GENED::INK-MIXIN
0.6
KNOWLEDGE:G-SPLINE-CHAIN
KNOWLEDGE:G-SPLINE-CHAIN
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-SPLINE-CHAIN)
NIL
218.0
289.5
NIL
GENED::SPLINE-OBJECT
(-93.0 8.5 -85.953125 6.2682295 -81.54167 4.9375 -76.44271 3.513021 -71.0 2.166667 -65.49219 1.0312501 -59.9375 0.08333349 -54.289062 -0.73958325 -48.5 -1.5 -42.528645 -2.2473958 -36.354168 -2.9791665 -29.960937 -3.6796875 -23.333334 -4.333333 -16.484375 -4.9296875 -9.541667 -5.479167 -2.661459 -5.997396 4.0 -6.5 10.322916 -6.9921875 16.333332 -7.4375 22.09375 -7.7890625 27.666666 -8.0 33.098957 -8.041667 38.375 -7.9583335 43.46354 -7.8125 48.333332 -7.6666665 52.99479 -7.5625 57.625 -7.458333 62.442707 -7.2916665 67.666664 -7.0 73.38281 -6.546875 79.14583 -6.0 84.3776 -5.453125 88.5 -5.0 93.0 -4.5)
GENED::ROTATEABLE-THING
0
GENED::POINTLIST-OBJECT
9
93.0
-4.5
66.0
-7.5
49.0
-7.5
28.0
-8.5
5.0
-6.5
-24.0
-4.5
-49.0
-1.5
-71.0
1.5
-93.0
8.5
GENED::OBJECT-WITH-HANDLES
9
GENED::UNFIXED-END-HANDLE
93.0
-4.5
GENED::UNFIXED-OBJECT-HANDLE
66.0
-7.5
GENED::UNFIXED-OBJECT-HANDLE
49.0
-7.5
GENED::UNFIXED-OBJECT-HANDLE
28.0
-8.5
GENED::UNFIXED-OBJECT-HANDLE
5.0
-6.5
GENED::UNFIXED-OBJECT-HANDLE
-24.0
-4.5
GENED::UNFIXED-OBJECT-HANDLE
-49.0
-1.5
GENED::UNFIXED-OBJECT-HANDLE
-71.0
1.5
GENED::UNFIXED-START-HANDLE
-93.0
8.5
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.9
GENED::LINETHICKNESS-MIXIN
3
THING
(KNOWLEDGE:COMPOSITE-THING)
NIL
208
256
NIL
| 2,198 | Common Lisp | .l | 140 | 14.7 | 606 | 0.791545 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | c3ae0b6b7e19e07fe3af051d0435842f9274eb75d70f155482ea26c400beab66 | 11,285 | [
-1
] |
11,286 | label-shadow-object | lambdamikel_GenEd/src/objects/label-shadow-object | GENED::OBJECT-DATA
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
4
KNOWLEDGE:G-SPLINE-CHAIN
KNOWLEDGE:G-SPLINE-CHAIN
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-SPLINE-CHAIN)
NIL
218.0
289.5
NIL
GENED::SPLINE-OBJECT
(-93.0 8.5 -85.953125 6.2682295 -81.54167 4.9375 -76.44271 3.513021 -71.0 2.166667 -65.49219 1.0312501 -59.9375 0.08333349 -54.289062 -0.73958325 -48.5 -1.5 -42.528645 -2.2473958 -36.354168 -2.9791665 -29.960937 -3.6796875 -23.333334 -4.333333 -16.484375 -4.9296875 -9.541667 -5.479167 -2.661459 -5.997396 4.0 -6.5 10.322916 -6.9921875 16.333332 -7.4375 22.09375 -7.7890625 27.666666 -8.0 33.098957 -8.041667 38.375 -7.9583335 43.46354 -7.8125 48.333332 -7.6666665 52.99479 -7.5625 57.625 -7.458333 62.442707 -7.2916665 67.666664 -7.0 73.38281 -6.546875 79.14583 -6.0 84.3776 -5.453125 88.5 -5.0 93.0 -4.5)
GENED::ROTATEABLE-THING
0
GENED::POINTLIST-OBJECT
9
93.0
-4.5
66.0
-7.5
49.0
-7.5
28.0
-8.5
5.0
-6.5
-24.0
-4.5
-49.0
-1.5
-71.0
1.5
-93.0
8.5
GENED::OBJECT-WITH-HANDLES
9
GENED::UNFIXED-END-HANDLE
93.0
-4.5
GENED::UNFIXED-OBJECT-HANDLE
66.0
-7.5
GENED::UNFIXED-OBJECT-HANDLE
49.0
-7.5
GENED::UNFIXED-OBJECT-HANDLE
28.0
-8.5
GENED::UNFIXED-OBJECT-HANDLE
5.0
-6.5
GENED::UNFIXED-OBJECT-HANDLE
-24.0
-4.5
GENED::UNFIXED-OBJECT-HANDLE
-49.0
-1.5
GENED::UNFIXED-OBJECT-HANDLE
-71.0
1.5
GENED::UNFIXED-START-HANDLE
-93.0
8.5
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
3
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"The Generic Graphic Editor"
:ITALIC
:SERIF
:NORMAL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
127
272
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"Gened -"
:ITALIC
:SERIF
:HUGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
108
249
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-LINE)
NIL
164.0
214.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
59.0
0.0
GENED::UNFIXED-START-HANDLE
-59.0
0.0
GENED::LINESEGMENT
(-59.0 0.0)
(59.0 0.0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
3
THING
(KNOWLEDGE:COMPOSITE-THING)
NIL
208
256
NIL
| 2,198 | Common Lisp | .l | 140 | 14.7 | 606 | 0.791545 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | b9cca50bd3c39f2efb7afc00fa9de8f53abbd08393fea02799abef2ea83f0dcb | 11,286 | [
-1
] |
11,300 | er-lib | lambdamikel_GenEd/src/libraries/er-lib | GENED::LIBRARY-DATA
8
KNOWLEDGE::RELATIONSHIP
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
2
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
20
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP)
NIL
127
325/2
NIL
GENED::SCALEABLE-THING
1.0
1.0
46
41
GENED::ROTATEABLE-THING
0.7853981633974483d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"flies"
:BOLD
:SANS-SERIF
:VERY-SMALL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
117
165
NIL
GENED::INK-MIXIN
0.4
THING
(KNOWLEDGE::RELATIONSHIP KNOWLEDGE:COMPOSITE-THING)
NIL
127
162
NIL
KNOWLEDGE::ENTITY
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
2
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
30
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::ENTITY)
NIL
79
292
NIL
GENED::SCALEABLE-THING
1.0
1.0
56
51
GENED::ROTATEABLE-THING
0.0d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"aircraft"
:BOLD
:SANS-SERIF
:VERY-SMALL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
62
300
NIL
GENED::INK-MIXIN
0.4
THING
(KNOWLEDGE::ENTITY KNOWLEDGE:COMPOSITE-THING)
NIL
79
292
NIL
KNOWLEDGE::1-CARDINALITY
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"1"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::1-CARDINALITY)
NIL
97
258
NIL
GENED::INK-MIXIN
0.8
KNOWLEDGE::ATTRIBUTE
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
2
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::ATTRIBUTE)
NIL
340
272
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"salary"
:BOLD
:SANS-SERIF
:VERY-SMALL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
326
277
NIL
GENED::INK-MIXIN
0.4
THING
(KNOWLEDGE::ATTRIBUTE KNOWLEDGE:COMPOSITE-THING)
NIL
340
272
NIL
KNOWLEDGE::G-DIAMOND
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
20
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::G-DIAMOND)
NIL
69
98
NIL
GENED::SCALEABLE-THING
1.0
1.0
58
58
GENED::ROTATEABLE-THING
0.7853981633974483d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE::M-CARDINALITY
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"m"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::M-CARDINALITY)
NIL
200
280
NIL
GENED::INK-MIXIN
0.8
KNOWLEDGE::N-CARDINALITY
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"n"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::N-CARDINALITY)
NIL
200
280
NIL
GENED::INK-MIXIN
0.8
KNOWLEDGE::RELATIONSHIP
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"flies"
:BOLD
:SANS-SERIF
:VERY-SMALL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
193
213
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
20
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::G-DIAMOND)
NIL
203
211
NIL
GENED::SCALEABLE-THING
1.0
1.0
58
58
GENED::ROTATEABLE-THING
0.7853981633974483d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-LINE)
NIL
151.0
212.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-24.0
0.0
GENED::UNFIXED-START-HANDLE
24.0
0.0
GENED::LINESEGMENT
(24.0 0.0)
(-24.0 0.0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-LINE)
NIL
257.0
211.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-24.0
0.0
GENED::UNFIXED-START-HANDLE
24.0
0.0
GENED::LINESEGMENT
(24.0 0.0)
(-24.0 0.0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
THING
(KNOWLEDGE::RELATIONSHIP KNOWLEDGE:COMPOSITE-THING)
NIL
204
211
NIL
| 4,019 | Common Lisp | .l | 343 | 10.717201 | 51 | 0.864255 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | d71eb1c102f1e5f46fbee44798b6344e4db21ba3b2f286d9cecb3b7366f48e42 | 11,300 | [
-1
] |
11,301 | petri-lib | lambdamikel_GenEd/src/libraries/petri-lib | GENED::LIBRARY-DATA
16
KNOWLEDGE::STELLE-MIT-MARKEN
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
5
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
38
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::STELLE-MIT-MARKEN KNOWLEDGE::STELLE-MIT-KAPAZITAET KNOWLEDGE::START-STELLE)
NIL
103
185
NIL
GENED::SCALEABLE-THING
1.0
1.0
77
77
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
5
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::MARKE)
NIL
85
174
NIL
GENED::SCALEABLE-THING
1.0
1.0
11
11
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
T
0.4
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
5
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::MARKE)
NIL
88
201
NIL
GENED::SCALEABLE-THING
1.0
1.0
11
11
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
T
0.4
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
5
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::MARKE)
NIL
111
207
NIL
GENED::SCALEABLE-THING
1.0
1.0
11
11
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
T
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"3"
NIL
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::KAPAZITAETS-LABEL)
NIL
119
235
NIL
GENED::INK-MIXIN
0.6
THING
(KNOWLEDGE::STELLE-MIT-MARKEN KNOWLEDGE:COMPOSITE-THING)
NIL
104
194
NIL
KNOWLEDGE::TRANSITION
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
34
32
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::TRANSITION KNOWLEDGE:G-RECTANGLE)
NIL
224
200
NIL
GENED::SCALEABLE-THING
1.0
1.0
69
65
GENED::ROTATEABLE-THING
0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE::KAPAZITAETS-LABEL
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"2"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::KAPAZITAETS-LABEL KNOWLEDGE:G-TEXT)
NIL
180
330
NIL
GENED::INK-MIXIN
0.6
KNOWLEDGE::KAPAZITAETS-LABEL
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"3"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::KAPAZITAETS-LABEL KNOWLEDGE:G-TEXT)
NIL
219
313
NIL
GENED::INK-MIXIN
0.6
KNOWLEDGE::KAPAZITAETS-LABEL
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"1"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::KAPAZITAETS-LABEL KNOWLEDGE:G-TEXT)
NIL
144
344
NIL
GENED::INK-MIXIN
0.6
KNOWLEDGE::MARKE
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
5
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::MARKE)
NIL
88
201
NIL
GENED::SCALEABLE-THING
1.0
1.0
11
11
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
T
0.4
KNOWLEDGE::STELLE-MIT-KAPAZITAET
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
2
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"1"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::KAPAZITAETS-LABEL KNOWLEDGE:G-TEXT)
NIL
124
196
NIL
GENED::INK-MIXIN
0.6
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
38
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::STELLE-MIT-KAPAZITAET KNOWLEDGE:G-CIRCLE)
NIL
100
155
NIL
GENED::SCALEABLE-THING
1.0
1.0
77
77
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
NIL
0.8
THING
(KNOWLEDGE::STELLE-MIT-KAPAZITAET KNOWLEDGE:COMPOSITE-THING)
NIL
100
159
NIL
KNOWLEDGE::STELLE-MIT-KAPAZITAET
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
2
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"2"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::KAPAZITAETS-LABEL KNOWLEDGE:G-TEXT)
NIL
152
193
NIL
GENED::INK-MIXIN
0.6
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
38
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::STELLE-MIT-KAPAZITAET KNOWLEDGE:G-CIRCLE)
NIL
127
153
NIL
GENED::SCALEABLE-THING
1.0
1.0
77
77
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
NIL
0.8
THING
(KNOWLEDGE::STELLE-MIT-KAPAZITAET KNOWLEDGE:COMPOSITE-THING)
NIL
128
156
NIL
KNOWLEDGE::STELLE-MIT-KAPAZITAET
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
2
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"3"
NIL
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::KAPAZITAETS-LABEL)
NIL
153
192
NIL
GENED::INK-MIXIN
0.6
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
38
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::STELLE-MIT-KAPAZITAET KNOWLEDGE:G-CIRCLE)
NIL
127
153
NIL
GENED::SCALEABLE-THING
1.0
1.0
77
77
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
NIL
0.8
THING
(KNOWLEDGE::STELLE-MIT-KAPAZITAET KNOWLEDGE:COMPOSITE-THING)
NIL
128
156
NIL
KNOWLEDGE::START-STELLE
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
2
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
38
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::START-STELLE KNOWLEDGE:G-CIRCLE)
NIL
97
152
NIL
GENED::SCALEABLE-THING
1.0
1.0
77
77
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-ARROW)
NIL
177.75
152.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
41.75
0.0
GENED::UNFIXED-START-HANDLE
-41.75
0.0
GENED::LINESEGMENT
(-41.75 0.0)
(41.75 0.0)
GENED::OBJECT-WITH-HEAD
T
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
THING
(KNOWLEDGE::START-STELLE KNOWLEDGE:COMPOSITE-THING)
NIL
140
152
NIL
KNOWLEDGE::END-STELLE
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
2
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
38
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::END-STELLE KNOWLEDGE:G-CIRCLE)
NIL
97
152
NIL
GENED::SCALEABLE-THING
1.0
1.0
77
77
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-ARROW)
NIL
17.625
152.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
41.375
0.0
GENED::UNFIXED-START-HANDLE
-41.375
0.0
GENED::LINESEGMENT
(-41.375 0.0)
(41.375 0.0)
GENED::OBJECT-WITH-HEAD
T
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
THING
(KNOWLEDGE::END-STELLE KNOWLEDGE:COMPOSITE-THING)
NIL
56
152
NIL
KNOWLEDGE::STELLE
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
38
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::STELLE KNOWLEDGE:G-CIRCLE)
NIL
119
193
NIL
GENED::SCALEABLE-THING
1.0
1.0
77
77
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE::NORMALE-STELLE
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
3
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
38
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::NORMALE-STELLE KNOWLEDGE:G-CIRCLE)
NIL
119
193
NIL
GENED::SCALEABLE-THING
1.0
1.0
77
77
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-ARROW)
NIL
199.375
192.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
42.375
0.0
GENED::UNFIXED-START-HANDLE
-42.375
0.0
GENED::LINESEGMENT
(-42.375 0.0)
(42.375 0.0)
GENED::OBJECT-WITH-HEAD
T
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-ARROW)
NIL
39.625
192.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
41.375
0.0
GENED::UNFIXED-START-HANDLE
-41.375
0.0
GENED::LINESEGMENT
(-41.375 0.0)
(41.375 0.0)
GENED::OBJECT-WITH-HEAD
T
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
THING
(KNOWLEDGE::NORMALE-STELLE KNOWLEDGE:COMPOSITE-THING)
NIL
120
194
NIL
KNOWLEDGE::STELLE-MIT-MARKEN
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
3
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
38
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::STELLE-MIT-MARKEN KNOWLEDGE::STELLE-MIT-KAPAZITAET KNOWLEDGE::START-STELLE)
NIL
369
218
NIL
GENED::SCALEABLE-THING
1.0
1.0
77
77
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
5
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::MARKE)
NIL
351
207
NIL
GENED::SCALEABLE-THING
1.0
1.0
11
11
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
T
0.4
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
5
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::MARKE)
NIL
377
240
NIL
GENED::SCALEABLE-THING
1.0
1.0
11
11
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
T
0.4
THING
(KNOWLEDGE::STELLE-MIT-MARKEN KNOWLEDGE:COMPOSITE-THING)
NIL
370
219
NIL
KNOWLEDGE::STELLE-MIT-MARKEN
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
6
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
38
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::STELLE-MIT-MARKEN KNOWLEDGE::STELLE-MIT-KAPAZITAET KNOWLEDGE::START-STELLE)
NIL
395
335
NIL
GENED::SCALEABLE-THING
1.0
1.0
77
77
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
5
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::MARKE)
NIL
377
324
NIL
GENED::SCALEABLE-THING
1.0
1.0
11
11
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
T
0.4
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
5
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::MARKE)
NIL
380
351
NIL
GENED::SCALEABLE-THING
1.0
1.0
11
11
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
T
0.4
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
5
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::MARKE)
NIL
403
357
NIL
GENED::SCALEABLE-THING
1.0
1.0
11
11
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
T
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"1"
NIL
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::KAPAZITAETS-LABEL)
NIL
411
385
NIL
GENED::INK-MIXIN
0.6
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
5
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::MARKE)
NIL
410
323
NIL
GENED::SCALEABLE-THING
1.0
1.0
11
11
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
T
0.4
THING
(KNOWLEDGE::STELLE-MIT-MARKEN KNOWLEDGE:COMPOSITE-THING)
NIL
396
344
NIL
KNOWLEDGE::STELLE-MIT-MARKEN
KNOWLEDGE:COMPOSITE-THING
KNOWLEDGE:COMPOSITE-THING
2
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
38
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::STELLE-MIT-MARKEN KNOWLEDGE::STELLE-MIT-KAPAZITAET KNOWLEDGE::START-STELLE)
NIL
276
311
NIL
GENED::SCALEABLE-THING
1.0
1.0
77
77
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
5
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::MARKE)
NIL
258
300
NIL
GENED::SCALEABLE-THING
1.0
1.0
11
11
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.6
GENED::LINETHICKNESS-MIXIN
1
GENED::FILLED-MIXIN
T
0.4
THING
(KNOWLEDGE::STELLE-MIT-MARKEN KNOWLEDGE:COMPOSITE-THING)
NIL
277
312
NIL
| 10,873 | Common Lisp | .l | 903 | 11.040975 | 87 | 0.864293 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 27dd53f9ecf823153a5ed101c89cad45b913ada0c607255fbb1a2d494070d040 | 11,301 | [
-1
] |
11,306 | class-er-test | lambdamikel_GenEd/src/scenes/class-er-test | GENED::SCENE-DATA
23
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::R-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
69
104
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
20
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::BINARY-RELATIONSHIP)
(KNOWLEDGE::G-DIAMOND)
127
325/2
NIL
GENED::SCALEABLE-THING
1.0
1.0
46
41
GENED::ROTATEABLE-THING
0.7853981633974483d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
342
160
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::M-RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
357/2
161
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
43/2
0
GENED::UNFIXED-START-HANDLE
-43/2
0
GENED::LINESEGMENT
(-43/2 0)
(43/2 0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
581/2
162
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
49/2
0
GENED::UNFIXED-START-HANDLE
-49/2
0
GENED::LINESEGMENT
(-49/2 0)
(49/2 0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"entity"
:BOLD
:SANS-SERIF
:NORMAL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
215
168
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"attribute"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
327
165
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"m"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::M-CARDINALITY)
(KNOWLEDGE:G-TEXT)
168
166
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"entity"
:BOLD
:SANS-SERIF
:NORMAL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
111
302
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
30
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::ENTITY)
(KNOWLEDGE:G-RECTANGLE)
233
319/2
NIL
GENED::SCALEABLE-THING
1.0
1.0
56
51
GENED::ROTATEABLE-THING
0.0d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
30
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::ENTITY)
(KNOWLEDGE:G-RECTANGLE)
124
289
NIL
GENED::SCALEABLE-THING
1.0
1.0
56
51
GENED::ROTATEABLE-THING
0.0d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::1-RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
255/2
231
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
1/2
37
GENED::UNFIXED-START-HANDLE
-1/2
-37
GENED::LINESEGMENT
(-1/2 -37)
(1/2 37)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"rel"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
121
170
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"1"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::1-CARDINALITY)
(KNOWLEDGE:G-TEXT)
117
244
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::R-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
98.0
137.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
12.5
12.0
GENED::UNFIXED-START-HANDLE
-12.5
-12.0
GENED::LINESEGMENT
(-12.5 -12.0)
(12.5 12.0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"attribute"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
52
110
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
20
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::BINARY-RELATIONSHIP)
(KNOWLEDGE::G-DIAMOND)
235
247
NIL
GENED::SCALEABLE-THING
1.0
1.0
46
41
GENED::ROTATEABLE-THING
0.7853981633974483d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"rel"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
230
252
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
234
198
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
1
17
GENED::UNFIXED-START-HANDLE
-1
-17
GENED::LINESEGMENT
(-1 -17)
(1 17)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
375/2
553/2
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-63/2
27/2
GENED::UNFIXED-START-HANDLE
63/2
-27/2
GENED::LINESEGMENT
(63/2 -27/2)
(-63/2 27/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::R-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
177/2
379/2
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-45/2
25/2
GENED::UNFIXED-START-HANDLE
45/2
-25/2
GENED::LINESEGMENT
(45/2 -25/2)
(-45/2 25/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::R-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
40
211
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"attribute"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
21
215
NIL
GENED::INK-MIXIN
0.4
| 6,985 | Common Lisp | .l | 527 | 12.254269 | 72 | 0.842831 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 4780a33a3c6ecb608e1e49b81af430ad3e2148c2d6ff4a92787e828cea03a904 | 11,306 | [
-1
] |
11,307 | er-pilot | lambdamikel_GenEd/src/scenes/er-pilot | GENED::SCENE-DATA
16
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-CIRCLE)
NIL
335
280
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
30
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-RECTANGLE)
NIL
233
319/2
NIL
GENED::SCALEABLE-THING
1.0
1.0
56
51
GENED::ROTATEABLE-THING
0.0d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
20
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::G-DIAMOND)
NIL
127
325/2
NIL
GENED::SCALEABLE-THING
1.0
1.0
46
41
GENED::ROTATEABLE-THING
0.7853981633974483d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-CIRCLE)
NIL
342
160
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-LINE)
NIL
179.0
161.5
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::FIXED-END-HANDLE
23.0
-0.5
GENED::FIXED-START-HANDLE
-23.0
0.5
GENED::LINESEGMENT
(-23.0 0.5)
(23.0 -0.5)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-LINE)
NIL
290.5
162.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::FIXED-END-HANDLE
26.5
0.0
GENED::FIXED-START-HANDLE
-26.5
0.0
GENED::LINESEGMENT
(-26.5 0.0)
(26.5 0.0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"pilot"
:BOLD
:SANS-SERIF
:VERY-SMALL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
222
163
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"age"
:BOLD
:SANS-SERIF
:VERY-SMALL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
339
170
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"1"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
174
166
NIL
GENED::INK-MIXIN
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-LINE)
NIL
106.5
237.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-19.5
46.0
GENED::FIXED-START-HANDLE
19.5
-46.0
GENED::LINESEGMENT
(19.5 -46.0)
(-19.5 46.0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"1"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
97
258
NIL
GENED::INK-MIXIN
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-LINE)
NIL
274.0
224.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
37.5
42.5
GENED::UNFIXED-START-HANDLE
-37.5
-42.5
GENED::LINESEGMENT
(-37.5 -42.5)
(37.5 42.5)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"flies"
:BOLD
:SANS-SERIF
:VERY-SMALL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
117
165
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"salary"
:BOLD
:SANS-SERIF
:VERY-SMALL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
322
284
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
30
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-RECTANGLE)
NIL
97
305
NIL
GENED::SCALEABLE-THING
1.0
1.0
56
51
GENED::ROTATEABLE-THING
0.0d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"aircraft"
:BOLD
:SANS-SERIF
:VERY-SMALL
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
80
313
NIL
GENED::INK-MIXIN
0.4
| 4,004 | Common Lisp | .l | 356 | 10.247191 | 27 | 0.848684 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 4cef4d8fe8d4465c095c84eb41f7bafcf3716b198a282a1f8cfc0cc030ffbff4 | 11,307 | [
-1
] |
11,308 | er-pilot2 | lambdamikel_GenEd/src/scenes/er-pilot2 | GENED::SCENE-DATA
14
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
129/2
75/2
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-RECTANGLE)
NIL
503
246
NIL
GENED::SCALEABLE-THING
1.0
1.0
131
77
GENED::ROTATEABLE-THING
0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
129/2
75/2
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-RECTANGLE)
NIL
76
251
NIL
GENED::SCALEABLE-THING
1.0
1.0
131
77
GENED::ROTATEABLE-THING
0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
61
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-CIRCLE)
NIL
455
72
NIL
GENED::SCALEABLE-THING
1.0
1.0
124
124
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
61
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-CIRCLE)
NIL
458
458
NIL
GENED::SCALEABLE-THING
1.0
1.0
124
124
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
137/2
137/2
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::G-DIAMOND)
NIL
281
250
NIL
GENED::SCALEABLE-THING
-97/139
-99/139
139
139
GENED::ROTATEABLE-THING
0.7853981633974483d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-LINE)
NIL
353/2
250
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
69/2
0
GENED::UNFIXED-START-HANDLE
-69/2
0
GENED::LINESEGMENT
(-69/2 0)
(69/2 0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-LINE)
NIL
787/2
249
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
85/2
0
GENED::UNFIXED-START-HANDLE
-85/2
0
GENED::LINESEGMENT
(-85/2 0)
(85/2 0)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-LINE)
NIL
481
170
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
25
35
GENED::UNFIXED-START-HANDLE
-25
-35
GENED::LINESEGMENT
(-25 -35)
(25 35)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-LINE)
NIL
483
340
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-24
55
GENED::UNFIXED-START-HANDLE
24
-55
GENED::LINESEGMENT
(24 -55)
(-24 55)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"flies"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
257
272
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"pilot"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
478
263
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"age"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
436
96
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"salary"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
423
480
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"aircraft"
:BOLD
:SANS-SERIF
:VERY-LARGE
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
NIL
36
259
NIL
GENED::INK-MIXIN
0.4
| 3,667 | Common Lisp | .l | 326 | 10.248466 | 27 | 0.855732 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | b08d8f4cb0e545b79f5e44323219796e337edd196fb8af3c93cfdeff33d93632 | 11,308 | [
-1
] |
11,309 | class-er-test2 | lambdamikel_GenEd/src/scenes/class-er-test2 | GENED::SCENE-DATA
80
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
126
74
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
30
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::ENTITY)
(KNOWLEDGE:G-RECTANGLE)
220
176
NIL
GENED::SCALEABLE-THING
1.0
1.0
56
51
GENED::ROTATEABLE-THING
0.0d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
20
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::BINARY-RELATIONSHIP)
(KNOWLEDGE::G-DIAMOND)
220
281
NIL
GENED::SCALEABLE-THING
1.0
1.0
46
41
GENED::ROTATEABLE-THING
0.7853981633974483d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
218
76
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
314
72
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
30
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::ENTITY)
(KNOWLEDGE:G-RECTANGLE)
224
388
NIL
GENED::SCALEABLE-THING
1.0
1.0
56
51
GENED::ROTATEABLE-THING
0.0d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
182
478
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
274
478
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
20
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::BINARY-RELATIONSHIP)
(KNOWLEDGE::G-DIAMOND)
58
482
NIL
GENED::SCALEABLE-THING
1.0
1.0
46
41
GENED::ROTATEABLE-THING
0.7853981633974483d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
30
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::ENTITY)
(KNOWLEDGE:G-RECTANGLE)
223
594
NIL
GENED::SCALEABLE-THING
1.0
1.0
56
51
GENED::ROTATEABLE-THING
0.0d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
324
530
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
192
702
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
134
654
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
275
701
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
320
640
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
20
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::BINARY-RELATIONSHIP)
(KNOWLEDGE::G-DIAMOND)
418
316
NIL
GENED::SCALEABLE-THING
1.0
1.0
46
41
GENED::ROTATEABLE-THING
0.7853981633974483d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
30
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::ENTITY)
(KNOWLEDGE:G-RECTANGLE)
630
180
NIL
GENED::SCALEABLE-THING
1.0
1.0
56
51
GENED::ROTATEABLE-THING
0.0d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
20
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::BINARY-RELATIONSHIP)
(KNOWLEDGE::G-DIAMOND)
628
334
NIL
GENED::SCALEABLE-THING
1.0
1.0
46
41
GENED::ROTATEABLE-THING
0.7853981633974483d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-RECTANGLE
KNOWLEDGE:G-RECTANGLE
30
20
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::ENTITY)
(KNOWLEDGE:G-RECTANGLE)
632
464
NIL
GENED::SCALEABLE-THING
1.0
1.0
56
51
GENED::ROTATEABLE-THING
0.0d0
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
575
581
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
690
578
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
542
116
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
622
62
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
702
64
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
756
136
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
776
232
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
605
522
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-17
34
GENED::UNFIXED-START-HANDLE
17
-34
GENED::LINESEGMENT
(17 -34)
(-17 34)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
665
519
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
21
33
GENED::UNFIXED-START-HANDLE
-21
-33
GENED::LINESEGMENT
(-21 -33)
(21 33)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
174.0
122.0
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
27.5
30.5
GENED::UNFIXED-START-HANDLE
-27.5
-30.5
GENED::LINESEGMENT
(-27.5 -30.5)
(27.5 30.5)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
441/2
255/2
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
1/2
49/2
GENED::UNFIXED-START-HANDLE
-1/2
-49/2
GENED::LINESEGMENT
(-1/2 -49/2)
(1/2 49/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
553/2
251/2
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-73/2
53/2
GENED::UNFIXED-START-HANDLE
73/2
-53/2
GENED::LINESEGMENT
(73/2 -53/2)
(-73/2 53/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
441/2
225
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
1/2
26
GENED::UNFIXED-START-HANDLE
-1/2
-26
GENED::LINESEGMENT
(-1/2 -26)
(1/2 26)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-CIRCLE
KNOWLEDGE:G-CIRCLE
25
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::R-ATTRIBUTE)
(KNOWLEDGE:G-CIRCLE)
121
327
NIL
GENED::SCALEABLE-THING
1.0
1.0
50
50
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
GENED::FILLED-MIXIN
NIL
0.8
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::R-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
353/2
623/2
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-55/2
31/2
GENED::UNFIXED-START-HANDLE
55/2
-31/2
GENED::LINESEGMENT
(55/2 -31/2)
(-55/2 31/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
397/2
430
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-23/2
20
GENED::UNFIXED-START-HANDLE
23/2
-20
GENED::LINESEGMENT
(23/2 -20)
(-23/2 20)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
513/2
430
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
27/2
20
GENED::UNFIXED-START-HANDLE
-27/2
-20
GENED::LINESEGMENT
(-27/2 -20)
(27/2 20)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
135
857/2
NIL
GENED::ROTATEABLE-THING
0.0d0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-57
81/2
GENED::UNFIXED-START-HANDLE
57
-81/2
GENED::LINESEGMENT
(57 -81/2)
(-57 81/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
131
544
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
60
44
GENED::UNFIXED-START-HANDLE
-60
-44
GENED::LINESEGMENT
(-60 -44)
(60 44)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
280
571
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
24
-23
GENED::UNFIXED-START-HANDLE
-24
23
GENED::LINESEGMENT
(-24 23)
(24 -23)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
277
612
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
21
10
GENED::UNFIXED-START-HANDLE
-21
-10
GENED::LINESEGMENT
(-21 -10)
(21 10)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
253
1295/2
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
10
61/2
GENED::UNFIXED-START-HANDLE
-10
-61/2
GENED::LINESEGMENT
(-10 -61/2)
(10 61/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
417/2
646
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-17/2
30
GENED::UNFIXED-START-HANDLE
17/2
-30
GENED::LINESEGMENT
(17/2 -30)
(-17/2 30)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
345/2
1233/2
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-37/2
35/2
GENED::UNFIXED-START-HANDLE
37/2
-35/2
GENED::LINESEGMENT
(37/2 -35/2)
(-37/2 35/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
1257/2
402
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
1/2
38
GENED::UNFIXED-START-HANDLE
-1/2
-38
GENED::LINESEGMENT
(-1/2 -38)
(1/2 38)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
585
291/2
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
22
25/2
GENED::UNFIXED-START-HANDLE
-22
-25/2
GENED::LINESEGMENT
(-22 -25/2)
(22 25/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
1237/2
245/2
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-1/2
67/2
GENED::UNFIXED-START-HANDLE
1/2
-67/2
GENED::LINESEGMENT
(1/2 -67/2)
(-1/2 67/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
1327/2
121
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-45/2
35
GENED::UNFIXED-START-HANDLE
45/2
-35
GENED::LINESEGMENT
(45/2 -35)
(-45/2 35)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
699
329/2
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-37
23/2
GENED::UNFIXED-START-HANDLE
37
-23/2
GENED::LINESEGMENT
(37 -23/2)
(-37 23/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::E-ATTRIBUTE-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
705
209
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
43
22
GENED::UNFIXED-START-HANDLE
-43
-22
GENED::LINESEGMENT
(-43 -22)
(43 22)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
518
487/2
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-80
123/2
GENED::UNFIXED-START-HANDLE
80
-123/2
GENED::LINESEGMENT
(80 -123/2)
(-80 123/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
657/2
717/2
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-145/2
57/2
GENED::UNFIXED-START-HANDLE
145/2
-57/2
GENED::LINESEGMENT
(145/2 -57/2)
(-145/2 57/2)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
441/2
338
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
-1/2
27
GENED::UNFIXED-START-HANDLE
1/2
-27
GENED::LINESEGMENT
(1/2 -27)
(-1/2 27)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-ARROW
KNOWLEDGE:G-ARROW
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE::RELATIONSHIP-ENTITY KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER)
(KNOWLEDGE:G-LINE KNOWLEDGE::TT-LINKER KNOWLEDGE::LINKER)
1255/2
253
NIL
GENED::ROTATEABLE-THING
0
GENED::OBJECT-WITH-HANDLES
2
GENED::UNFIXED-END-HANDLE
1/2
51
GENED::UNFIXED-START-HANDLE
-1/2
-51
GENED::LINESEGMENT
(-1/2 -51)
(1/2 51)
GENED::OBJECT-WITH-HEAD
NIL
GENED::LINESTYLE-MIXIN
NIL
GENED::INK-MIXIN
0.4
GENED::LINETHICKNESS-MIXIN
2
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"name"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
113
78
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"adresse"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
200
80
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"tel-nr."
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
300
77
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"passagier"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
197
181
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"geb.-f."
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
206
285
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"rb-nr."
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
105
333
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"abflug"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
209
395
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"ist-ein"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
46
487
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"datum"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
166
481
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"flugnr."
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
258
484
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"flug"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
219
597
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"ank.zeit"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
305
534
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"abfl.ort"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
305
644
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"ank.ort"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
120
653
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"flugnr."
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
180
704
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"abfl.zeit"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
256
704
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"pilot"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
617
184
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"name"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
529
121
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"adresse"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
603
65
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"pers.nr."
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
683
71
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"gehalt"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
740
142
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"flugstd."
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
758
237
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"fliegt"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
616
338
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"modell"
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
612
466
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"herstl."
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
561
585
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"mod-nr."
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
673
583
NIL
GENED::INK-MIXIN
0.4
KNOWLEDGE:G-TEXT
KNOWLEDGE:G-TEXT
"einges."
:BOLD
:SANS-SERIF
:TINY
KNOWLEDGE:BASIC-THING
THING
(KNOWLEDGE:G-TEXT)
(KNOWLEDGE:G-TEXT)
403
320
NIL
GENED::INK-MIXIN
0.4
| 24,678 | Common Lisp | .l | 1,862 | 12.253491 | 70 | 0.84226 | lambdamikel/GenEd | 18 | 3 | 0 | GPL-3.0 | 9/19/2024, 11:26:41 AM (Europe/Amsterdam) | 447eaf79dce59eb3b0f791f5133e9e2730b41d1e19658f026d487f005b0c4db9 | 11,309 | [
-1
] |
11,337 | savemem.lisp | ufasoft_lisp/clisp/savemem.lisp | ;;;; Saving memory images
(in-package "EXT")
(export '(saveinitmem *command-index*))
(in-package "SYSTEM")
;;---------------------------------------------------------------------------
;; Stores the current memory contents as "lispimag.mem", omitting garbage
;; collectible objects.
;; This function does not take arguments and has no local variables, since
;; otherwise in the interpreted mode the values of the variables are stored.
(defun %saveinitmem ()
(do-all-symbols (sym) (remprop sym 'sys::definition))
(when (fboundp 'clos::install-dispatch)
(do-all-symbols (sym)
(when (and (fboundp sym)
(typep (symbol-function sym) clos::<standard-generic-function>))
(let ((gf (symbol-function sym)))
(when (clos::gf-never-called-p gf)
(clos::install-dispatch gf)
) ) ) ) )
(setq - nil + nil ++ nil +++ nil * nil ** nil *** nil / nil // nil /// nil)
(savemem "lispimag.mem" nil)
(room nil)
)
;; Saves the current memory contents.
;; This function works only when compiled!
(defvar *saveinitmem-verbose* t
"The default value for the :VERBOSE argument of SAVEINITMEM.")
(defun saveinitmem (&optional (filename "lispinit.mem")
&key ((:quiet *quiet*) nil)
(init-function nil init-function-p)
((:verbose *saveinitmem-verbose*) *saveinitmem-verbose*)
((:norc *norc*) nil)
((:documentation *image-doc*)
(documentation init-function 'function))
((:script *script*) (null init-function))
keep-global-handlers (start-package *package*)
(locked-packages *system-package-list*) executable)
(let* ((old-driver *driver*) old-global-handlers file-size
(*package* (sys::%find-package start-package))
(active-restarts *active-restarts*)
(condition-restarts *condition-restarts*)
(fn (if (not executable)
(merge-pathnames filename #.(make-pathname :type "mem"))
;; win32 executables require "exe" extension
#+(or win32 cygwin)
(make-pathname :type "exe" :defaults filename)
#-(or win32 cygwin) filename)))
;; use setq in order not to create local per thread binding that will
;; not survive the savemem/loadmem. actually we need two new functions:
;; sys::symbol-global-value and sys::symbol-thread-value. will be added
(setq *driver*
#'(lambda ()
;;(declare (special *command-index* *home-package*))
;; Reset a few special variables. This must happen in the
;; fresh session, not in the old session, because that would
;; temporarily disable error handling in the old session.
;; Note: For GC purposes, neither is better: during savemem's
;; GC the old values are accessible anyway and thus not garbage
;; collected.
(setq - nil
+ nil
++ nil
+++ nil
* nil
** nil
*** nil
/ nil
// nil
/// nil
*command-index* 0
*home-package* nil
;; must make sure that the user can get clisp repl back
;; from an executable image:
;; ./clisp -K boot -q -norc -x '(saveinitmem "x" :executable 0 :init-function (lambda () (print *args*) (exit)))'
;; ./x --clisp-x '(ext:saveinitmem "myclisp" :executable t :init-function nil)'
;; ./myclisp => [1]> ...
*driver* (if (and init-function-p (null init-function))
#'sys::main-loop old-driver))
(when init-function (funcall init-function))
(funcall *driver*)))
(unless keep-global-handlers
(setq old-global-handlers ; disable and save all global handlers
(ext::set-global-handler nil nil)))
(setf (package-lock locked-packages) t)
;; set global not per thread ones (hopefully novody has bound them above us)
(setq *active-restarts* nil
*condition-restarts* nil)
;; we used to set *ACTIVE-RESTARTS* & *CONDITION-RESTARTS* above in the
;; *DRIVER* binding, but that caused mutiple ABORT restarts, bug
;; http://sourceforge.net/tracker/index.php?func=detail&aid=1877497&group_id=1355&atid=101355
(setq file-size (savemem fn executable))
;; restore old driver
(setq *driver* old-driver)
;; restore restarts
(setq *active-restarts* active-restarts
*condition-restarts* condition-restarts)
(when old-global-handlers ; re-install all global handlers
(ext::set-global-handler old-global-handlers nil))
(when *saveinitmem-verbose*
(let ((*load-level* 1)) ; proper indentation
(loading-message (TEXT "Wrote the memory image into ~A (~:D byte~:P)")
fn file-size))))
(room nil))
| 5,124 | Common Lisp | .lisp | 103 | 38.572816 | 134 | 0.573735 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 61252cb63b8e40851946722bc39be2d537d86c9e13dd1f82ff9a49b28fdc888a | 11,337 | [
-1
] |
11,338 | clos-genfun1.lisp | ufasoft_lisp/clisp/clos-genfun1.lisp | ;;;; Common Lisp Object System for CLISP: Generic Functions
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004, 2007
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
;; ============================================================================
(defparameter <funcallable-standard-class>
(defclass funcallable-standard-class (semi-standard-class)
()
(:fixed-slot-locations t)))
(defparameter *<funcallable-standard-class>-class-version*
(class-current-version <funcallable-standard-class>))
(defconstant *<funcallable-standard-class>-instance-size* 28)
;; For DEFCLASS macro expansions.
(defconstant *<funcallable-standard-class>-valid-initialization-keywords* ; ABI
*<standard-class>-valid-initialization-keywords*)
(defun make-instance-<funcallable-standard-class> (metaclass &rest args
&key name
(direct-superclasses '())
(direct-slots '())
(direct-default-initargs '())
&allow-other-keys)
;; metaclass = <funcallable-standard-class>
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'make-instance later.
(declare (ignore metaclass name direct-superclasses direct-slots
direct-default-initargs))
(let ((class (allocate-metaobject-instance *<funcallable-standard-class>-class-version*
*<funcallable-standard-class>-instance-size*)))
(apply #'initialize-instance-<funcallable-standard-class> class args)))
(defun initialize-instance-<funcallable-standard-class> (class &rest args
&key &allow-other-keys)
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'initialize-instance later.
(apply #'shared-initialize-<funcallable-standard-class> class 't args)
(install-class-direct-accessors class)
class)
(defun shared-initialize-<funcallable-standard-class> (class situation &rest args
&key (direct-superclasses '() direct-superclasses-p)
((:direct-slots direct-slots-as-lists) '() direct-slots-as-lists-p)
((direct-slots direct-slots-as-metaobjects) '() direct-slots-as-metaobjects-p)
(direct-default-initargs '() direct-default-initargs-p)
(documentation nil documentation-p)
(generic-accessors t generic-accessors-p)
(fixed-slot-locations nil fixed-slot-locations-p)
&allow-other-keys)
(declare (ignore direct-superclasses direct-superclasses-p
direct-slots-as-lists direct-slots-as-lists-p
direct-slots-as-metaobjects direct-slots-as-metaobjects-p
direct-default-initargs direct-default-initargs-p
documentation documentation-p generic-accessors
generic-accessors-p fixed-slot-locations
fixed-slot-locations-p))
(apply #'shared-initialize-<semi-standard-class> class situation args)
class)
;; ----------------------------------------------------------------------------
;; Low-level representation of funcallable instances:
;; Funcallable instances are Closures with a certain bit set in the
;; closure_flags. They always the following shape:
;; - recdata[0] = clos_name_or_class_version is a semi-class-version,
;; like for instances,
;; - recdata[1] = clos_codevec is a simple-8bit-vector, like for compiled
;; functions,
;; - recdata[2] = clos_venv is reserved,
;; - recdata[3] is the first slot, the name,
;; - then come additional slots, as described by the class.
(defparameter <funcallable-standard-object>
(ext:compiler-let ((*allow-mixing-metaclasses* t))
(let ((*allow-mixing-metaclasses* t))
(defclass funcallable-standard-object (function standard-object)
;; The MOP p. 7 specifies a superclass list (standard-object function),
;; but then generic-function and standard-generic-function would have a
;; class-precedence-list that contains standard-object before function,
;; which contradicts the last sentence of ANSI CL 4.2.2. Possible
;; workarounds are: 1. reversed order (function standard-object),
;; 2. use a twin superclass or subclass of standard-object instead of
;; standard-object itself, 3. override compute-class-precedence-list
;; for this class. We choose solution 1 because it is the one a user
;; will most easily understand.
(($name ; The function name is present as first CLOS slot. The macro
; Closure_name in lispbibl.d refers to it. Therefore this slot
; must not be changed after initialization, since this could
; interfere with the forwarded-instance mechanism.
:accessor funcallable-name))
(:metaclass funcallable-standard-class)
(:fixed-slot-locations t)
(:generic-accessors nil)))))
(defun print-object-<funcallable-standard-object> (object stream)
(print-unreadable-object (object stream :type t)
(write (funcallable-name object) :stream stream)))
;; Preliminary.
;; Now we can at least print classes and generic-functions.
(predefun print-object (object stream)
(cond ((potential-class-p object) (format stream "#<CLASS ~S>" (class-classname object)))
((funcallable-instance-p object) (print-object-<funcallable-standard-object> object stream))
(t (write-string "#<UNKNOWN>" stream))))
;; ============================================================================
;; low-level-representation:
;; Compiled functions (Cclosures), for which a certain bit is set in
;; the flag-byte of the code-vector.
;; The compiler uses (at GENERIC-FLET, GENERIC-LABELS) and the evaluator
;; presupposes likewise, that a generic function does not change its
;; calling convention.
;; A generic function with signature (reqnum optnum restp keywords allowp)
;; is from the very beginning (!) a compiled function with
;; reqnum required parameters
;; 0 optional parameters
;; &rest if and only if (or (> optnum 0) restp),
;; without &key.
(defun callinfo (reqnum optnum restp keywords allowp)
(declare (ignore keywords allowp))
(list reqnum 0 (or (> optnum 0) restp) nil nil nil))
;; ----------------------------------------------------------------------------
(defparameter <generic-function>
(defclass generic-function (metaobject funcallable-standard-object)
(($listeners ; list of objects to be notified upon a change
:type list
:accessor gf-listeners))
(:metaclass funcallable-standard-class)
(:fixed-slot-locations t)
(:generic-accessors nil)))
;; Initialization of a <generic-function> instance.
(defun shared-initialize-<generic-function> (gf situation &rest args
&key (name nil name-p)
&allow-other-keys)
(when *classes-finished*
(apply #'%shared-initialize gf situation args)) ; == (call-next-method)
(when (or (eq situation 't) name-p)
(setf (funcallable-name gf) name))
(when (eq situation 't)
(setf (gf-listeners gf) nil))
gf)
;; ----------------------------------------------------------------------------
(defparameter <standard-generic-function>
(defclass standard-generic-function (generic-function)
(($signature ; a signature struct
:type (simple-vector 6)
:accessor std-gf-signature)
($argorder ; the argument-precedence-order, as a list of
; numbers from 0 to reqnum-1,
:type list
:accessor std-gf-argorder)
($methods ; the list of all methods
:type list
:accessor std-gf-methods)
($method-combination ; a method-combination object
:type method-combination
:accessor std-gf-method-combination)
($default-method-class ; default class for newly added methods
:type class
:accessor std-gf-default-method-class)
($lambda-list ; a redundant non-canonical encoding of the
; signature
:type list
:accessor std-gf-lambda-list)
($documentation
:type (or null string)
:accessor std-gf-documentation)
($declspecs ; a list of declaration-specifiers
:type list
:accessor std-gf-declspecs)
($effective-method-cache ; an alist mapping a list of methods to the
; effective method as function
:type list
:accessor std-gf-effective-method-cache)
($initialized ; true if an instance has already been created
:type boolean
:accessor std-gf-initialized))
(:metaclass funcallable-standard-class)
(:fixed-slot-locations t)
(:generic-accessors nil)))
(defun std-gf-undeterminedp (gf) (eq (sys::%unbound) (std-gf-signature gf)))
;; Preliminary.
;; During bootstrapping, only <standard-generic-function> instances are used.
(predefun generic-function-methods (gf)
(std-gf-methods gf))
(predefun generic-function-method-class (gf)
(std-gf-default-method-class gf))
(predefun generic-function-signature (gf)
(std-gf-signature gf))
(predefun generic-function-undeterminedp (gf)
(std-gf-undeterminedp gf))
(predefun generic-function-method-combination (gf)
(std-gf-method-combination gf))
(predefun generic-function-argorder (gf)
(std-gf-argorder gf))
(predefun generic-function-declarations (gf)
(std-gf-declspecs gf))
;; ============================================================================
| 10,266 | Common Lisp | .lisp | 189 | 44.333333 | 138 | 0.608735 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 28a484ba404e38577ff3fffe7f459c37b6b1a7e323fc08ce4727eba2b2c5f0a1 | 11,338 | [
-1
] |
11,339 | defseq.lisp | ufasoft_lisp/clisp/defseq.lisp | ;; Definitions for the standard sequence types
;; (in conjunction with SEQUENCE.D)
;; Bruno Haible 9.7.1989, 1.8.1989, 2.8.1989
(in-package "SYSTEM")
(%defseq
(vector
'LIST
#'identity
#'list-upd
#'list-endtest
#'list-fe-init
#'list-upd
#'list-endtest
#'list-access
#'list-access-set
#'identity
#'ext::list-length-proper
#'make-list
#'list-elt
#'list-set-elt
#'list-init-start
#'list-fe-init-end
) )
(%defseq ; VECTOR stands for GENERAL-VECTOR
(vector
'VECTOR
#'vector-init
#'vector-upd
#'vector-endtest
#'vector-fe-init
#'vector-fe-upd
#'vector-fe-endtest
#'aref
#'sys::store
#'identity
#'vector-length
#'make-array
#'aref
#'sys::store
#'vector-init-start
#'vector-fe-init-end
) )
(%defseq
(vector
'STRING
#'vector-init
#'vector-upd
#'vector-endtest
#'vector-fe-init
#'vector-fe-upd
#'vector-fe-endtest
#'char
#'sys::store
#'identity
#'vector-length
#'make-string
#'char
#'sys::store
#'vector-init-start
#'vector-fe-init-end
) )
(mapc
#'(lambda (n &aux (eltype (list 'UNSIGNED-BYTE n)))
(%defseq
(vector
n ; n stands for `(VECTOR (UNSIGNED-BYTE ,n))
#'vector-init
#'vector-upd
#'vector-endtest
#'vector-fe-init
#'vector-fe-upd
#'vector-fe-endtest
(if (= n 1) #'bit #'aref)
#'sys::store
#'identity
#'vector-length
(if (= n 1)
#'make-bit-vector
#'(lambda (length) (make-array length :element-type eltype)))
(if (= n 1) #'bit #'aref)
#'sys::store
#'vector-init-start
#'vector-fe-init-end
) ) )
'(1 2 4 8 16 32)
)
(%defseq ; (VECTOR NIL)
(vector
0
#'vector-init
#'vector-upd
#'vector-endtest
#'vector-fe-init
#'vector-fe-upd
#'vector-fe-endtest
#'aref
#'sys::store
#'identity
#'vector-length
#'(lambda (length) (make-array length :element-type nil))
#'aref
#'sys::store
#'vector-init-start
#'vector-fe-init-end))
| 2,185 | Common Lisp | .lisp | 104 | 15.432692 | 73 | 0.560482 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 58304d134217e83e1c1f750e3c3816e11f3d1c4fbf846f7a8b3258f1b7ae24eb | 11,339 | [
-1
] |
11,340 | clos-methcomb1.lisp | ufasoft_lisp/clisp/clos-methcomb1.lisp | ;;;; Common Lisp Object System for CLISP: Method Combination
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004
;;;; German comments translated into English: Stefan Kain 2002-04-08
;;;; James Anderson 2003
(in-package "CLOS")
;;; ===========================================================================
;;; Global management of method-combinations and their names:
;; Mapping from name, a symbol, to method-combination instance.
;; If the caller is non-nil, an error is signalled if the method-combination
;; does not exist. Otherwise nil is returned.
;; All method-combination objects used here have an empty options list;
;; method-combination objects with options are stored in generic functions.
(defun get-method-combination (name caller)
(or (get name '%method-combination)
(and caller
(error (TEXT "~S: The method combination ~S is not defined.")
caller name))))
(defun (setf get-method-combination) (new-value name)
(setf (get name '%method-combination) new-value))
;;; ===========================================================================
;;; The method-combination class definition.
;; A method-combination is used 1) without options when defined and attached
;; to a symbol, 2) with options when applied to a particular generic function.
;; Strange design... but ANSI CL specifies it this way.
;; A structure definition is to be preferred, otherwise the compiled
;; load fails on type tests as the class can't be defined early enough
;; in the file.
(defparameter <method-combination>
(defclass method-combination (metaobject)
((name ; a symbol naming the method combination
:type symbol
:accessor method-combination-name)
(documentation ; an optional documentation string
:type (or null string)
:accessor method-combination-documentation)
(check-options ; A function of 3 arguments
; (function-name method-combination options)
; that checks the syntax of arguments to the
; method combination
:type function
:accessor method-combination-check-options)
(expander ; A function of 4 arguments
; (function method-combination options methods)
; which computes two values: 1. the inner body
; of the effective method, as a form containing
; (CALL-METHOD ...) forms, 2. a list of
; options describing the wrapper, such as
; (:ARGUMENTS ...) or (:GENERIC-FUNCTION ...).
:type function
:accessor method-combination-expander)
(check-method-qualifiers ; A function of 3 arguments
; (function method-combination method)
; that checks whether the method's qualifiers
; are compatible with the method-combination.
:type function
:accessor method-combination-check-method-qualifiers)
(call-next-method-allowed ; A function of 3 arguments
; (function method-combination method)
; telling whether call-next-method is allowed
; in the particular method.
:type function
:accessor method-combination-call-next-method-allowed)
(declarations ; list to be prepended to the effective method
; body
:type list
:accessor method-combination-declarations)
;; The following slots apply only to standard and short form
;; method-combination.
(qualifiers ; the allowed list of qualifiers
:type list
:accessor method-combination-qualifiers)
;; The following slots apply only to short form method-combination.
(operator ; a symbol
:type symbol
:accessor method-combination-operator)
(identity-with-one-argument ; true if `(operator ,x) should be replaced
; with x
:type boolean
:accessor method-combination-identity-with-one-argument)
;; The following slots apply only to long form method-combination.
(long-expander ; A function of 2+n variables
; (function methods . options)
; which computes the inner body of the effective
; method, as a form containing (CALL-METHOD ...)
; forms
:type function
:accessor method-combination-long-expander)
(arguments-lambda-list ; The :arguments option of the defined method
; combination for inclusion in the effective
; method function.
:type list
:accessor method-combination-arguments-lambda-list)
;; The following slots depend on the particular generic function.
(options ; arguments for the method combination
:type list
:accessor method-combination-options))
(:fixed-slot-locations t)
(:generic-accessors nil)))
(defun initialize-instance-<method-combination> (combination &rest args
&key name
(documentation nil)
check-options
expander
check-method-qualifiers
call-next-method-allowed
(declarations '())
qualifiers
operator
(identity-with-one-argument nil)
long-expander
arguments-lambda-list
(options '()))
(when *classes-finished*
(apply #'%initialize-instance combination args)) ; == (call-next-method)
(setf (method-combination-name combination) name)
(setf (method-combination-documentation combination) documentation)
(setf (method-combination-check-options combination) check-options)
(setf (method-combination-expander combination) expander)
(setf (method-combination-check-method-qualifiers combination) check-method-qualifiers)
(setf (method-combination-call-next-method-allowed combination) call-next-method-allowed)
(setf (method-combination-declarations combination) declarations)
(setf (method-combination-qualifiers combination) qualifiers)
(setf (method-combination-operator combination) operator)
(setf (method-combination-identity-with-one-argument combination) identity-with-one-argument)
(setf (method-combination-long-expander combination) long-expander)
(setf (method-combination-arguments-lambda-list combination) arguments-lambda-list)
(setf (method-combination-options combination) options)
combination)
(defun make-instance-<method-combination> (class &rest args
&key &allow-other-keys)
;; class = <method-combination>
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'make-instance later.
(declare (ignore class))
(let ((combination (%allocate-instance <method-combination>)))
(apply #'initialize-instance-<method-combination> combination args)))
(defun copy-method-combination (combination)
(make-instance-<method-combination> <method-combination>
:name (method-combination-name combination)
:documentation (method-combination-documentation combination)
:check-options (method-combination-check-options combination)
:expander (method-combination-expander combination)
:check-method-qualifiers (method-combination-check-method-qualifiers combination)
:call-next-method-allowed (method-combination-call-next-method-allowed combination)
:declarations (method-combination-declarations combination)
:qualifiers (method-combination-qualifiers combination)
:operator (method-combination-operator combination)
:identity-with-one-argument (method-combination-identity-with-one-argument combination)
:long-expander (method-combination-long-expander combination)
:arguments-lambda-list (method-combination-arguments-lambda-list combination)
:options (method-combination-options combination)))
(defun print-object-<method-combination> (object stream)
(print-unreadable-object (object stream :identity t :type t)
(write (method-combination-name object) :stream stream)))
| 9,040 | Common Lisp | .lisp | 155 | 44.941935 | 95 | 0.607666 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | d8f1ba131e2581f61b80e130425c348144b73e9b7cc96f29a497604b2c4c4720 | 11,340 | [
-1
] |
11,341 | clos-stablehash2.lisp | ufasoft_lisp/clisp/clos-stablehash2.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Objects with stable hash code
;;;; Part 2: Final class definition, make/initialize-instance methods.
;;;; Bruno Haible 2004-05-15
(in-package "CLOS")
;;; ===========================================================================
;;; Lift the initialization protocol.
(defmethod shared-initialize ((object standard-stablehash) situation &rest args
&key)
(apply #'shared-initialize-<standard-stablehash> object situation args))
;;; ===========================================================================
;; Definition of <structure-stablehash>.
;; Used for (make-hash-table :test 'stablehash-eq).
(defstruct (structure-stablehash (:predicate nil) (:copier nil))
(hashcode (sys::random-posfixnum))) ; GC invariant hash code
;;; ===========================================================================
| 893 | Common Lisp | .lisp | 16 | 52.25 | 79 | 0.526437 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 52be595d5828b7bc6feadc7d00b96fa12d0ccbaafa07ccb87db7b11305b90e14 | 11,341 | [
-1
] |
11,342 | fill-out.lisp | ufasoft_lisp/clisp/fill-out.lisp | ;;; filling/indenting stream
;;;
;;; Copyright (C) 2004-2008 by Sam Steingold
;;; Copyright (C) 2004 by Bruno Haible
;;; This is Free Software, covered by the GNU GPL (v2)
;;; See http://www.gnu.org/copyleft/gpl.html
(in-package "EXT")
(export '(custom::*fill-indent-sexp*) "CUSTOM")
(export '(fill-stream with-fill-stream custom:*fill-indent-sexp*))
(import '(fill-stream with-fill-stream) "SYS")
(in-package "SYSTEM")
(defvar *fill-indent-sexp* #'1+
"The default indentation of new FILL-STREAMs inside SEXPs.
This should be a number (the actual indentation),
a function of one argument (the text indentation),
NIL (no indentation) or
T (same indentation as the text, i.e., the same effect as #'IDENTITY).")
(declaim (inline right-margin))
(defun right-margin () (or *print-right-margin* sys::*prin-linelength*))
(defclass fill-stream (fundamental-character-output-stream)
((target-stream :initarg :stream :type stream)
(buffer :type string :initform
(make-array (right-margin) :element-type 'character
:fill-pointer 0 :adjustable t))
(inside-sexp :initform nil :type boolean)
(sexp-indent :initarg :sexp-indent :initform *fill-indent-sexp*
:type (or symbol integer function))
;; the indentation level variable or number:
(indent-var :initarg :text-indent :initform 0 :type (or symbol integer))
(pending-space :initform nil :type boolean)
(current-indent :initform 0 :type integer) ; current line indentation
(pending-indent :initform nil :type (or null integer))))
(defun fill-stream-line-position (fill-stream)
(with-slots (target-stream buffer pending-space) fill-stream
(let ((pos (sys::line-position target-stream)))
(if pos
(+ pos (if pending-space 1 0) (string-width buffer))
nil))))
(defun fill-stream-text-indent (stream)
(let ((text-indent-raw (slot-value stream 'indent-var)))
(etypecase text-indent-raw
(number text-indent-raw)
(symbol (symbol-value text-indent-raw)))))
(defun fill-stream-sexp-indent (stream)
(let* ((sexp-indent-raw (slot-value stream 'sexp-indent))
(text-indent (fill-stream-text-indent stream))
(sexp-indent-value
(etypecase sexp-indent-raw
(number sexp-indent-raw)
(symbol (symbol-value sexp-indent-raw))
(function (funcall sexp-indent-raw text-indent)))))
(case sexp-indent-value
((nil) 0)
((t) text-indent)
(t sexp-indent-value))))
;; SEXP is either a single line, then it is formatted inline as a word,
;; or it takes several lines, then it is formatted as an indented block
;; flush the buffer and print a newline (when NEWLINE-P is non-NIL)
(defun fill-stream-flush-buffer (stream newline-p &aux sexp-block-p)
(with-slots (target-stream buffer pending-indent current-indent
pending-space inside-sexp)
stream
(flet ((newline () ; terpri
(setq current-indent (fill-stream-text-indent stream)
pending-indent current-indent)
(terpri target-stream)))
(when (plusp (length buffer)) ; something in the buffer to flush
;; fill: if the buffer does not fit on the line, TERPRI
(let ((pos (fill-stream-line-position stream)))
(when (and pos (<= (right-margin) pos)) ; does not fit on this line
(setq sexp-block-p (find #\newline buffer)) ; only inside sexp
(unless sexp-block-p (newline))
(when inside-sexp ; just finished an S-expression
(setq newline-p (or newline-p sexp-block-p)))))
(unless sexp-block-p ; S-expression in a block
(cond (pending-indent ; do the indent
(sys::write-spaces pending-indent target-stream)
(setq pending-indent nil))
(pending-space
(write-char #\Space target-stream))))
(setq pending-space nil)
(if sexp-block-p
(do* ((indent (fill-stream-sexp-indent stream))
(beg 0 (1+ end))
(end (position #\Newline buffer)
(position #\Newline buffer :start beg)))
((null end)
(write-char-sequence buffer target-stream :start beg))
(write-char-sequence buffer target-stream :start beg :end end)
(terpri target-stream)
(sys::write-spaces indent target-stream))
(write-char-sequence buffer target-stream))
(setf (fill-pointer buffer) 0))
(when newline-p (newline)))))
(progn
(defmethod stream-write-char ((stream fill-stream) ch)
(with-slots #1=(buffer pending-space inside-sexp) stream
#2=
(if inside-sexp
(vector-push-extend ch buffer)
(case ch
(#\Newline (fill-stream-flush-buffer stream t))
((#\Space #\Tab)
(when (plusp (length buffer))
(fill-stream-flush-buffer stream nil))
(setq pending-space t))
(t (vector-push-extend ch buffer))))))
(defmethod stream-write-char-sequence ((stream fill-stream) sequence
&optional (start 0) (end nil))
(with-slots #1# stream
;; make sure that the buffer can accommodate the sequence
(let ((new-size (+ (length sequence) (length buffer))))
(when (> new-size (array-dimension buffer 0))
(adjust-array buffer new-size)))
;; Same body as in stream-write-char.
(count-if (lambda (ch) #2#) sequence :start start :end end))
sequence))
(defmethod stream-line-column ((stream fill-stream))
(let ((pos (fill-stream-line-position stream)))
(if pos (max (- pos (slot-value stream 'current-indent)) 0) nil)))
(defmethod stream-start-line-p ((stream fill-stream))
(let ((pos (fill-stream-line-position stream)))
(if pos (<= pos (slot-value stream 'current-indent)) nil)))
(defmethod stream-finish-output ((stream fill-stream))
(fill-stream-flush-buffer stream nil)
(finish-output (slot-value stream 'target-stream)))
(defmethod stream-force-output ((stream fill-stream))
(fill-stream-flush-buffer stream nil)
(force-output (slot-value stream 'target-stream)))
(defmethod stream-clear-output ((stream fill-stream))
(with-slots (target-stream buffer pending-indent pending-space) stream
(setq pending-indent nil pending-space nil)
(setf (fill-pointer buffer) 0)
(clear-output target-stream)))
(defmacro with-fill-stream ((stream-var target-stream &rest opts) &body body)
(multiple-value-bind (body-rest declarations) (parse-body body)
`(LET ((,stream-var (MAKE-INSTANCE 'fill-stream :STREAM ,target-stream
,@opts)))
(DECLARE (READ-ONLY ,stream-var) ,@declarations)
(UNWIND-PROTECT (PROGN ,@body-rest)
(FORCE-OUTPUT ,stream-var)))))
;;; for format, see `format-s-expression'
(fmakunbound 'stream-start-s-expression)
(fmakunbound 'stream-end-s-expression)
(defgeneric stream-start-s-expression (stream)
(:documentation "Return the new binding for *PRINT-RIGHT-MARGIN*.")
(:method ((stream t)) (declare (ignore stream)) *print-right-margin*)
(:method ((stream fill-stream))
(fill-stream-flush-buffer stream nil)
(setf (slot-value stream 'inside-sexp) t)
(- (right-margin) (fill-stream-sexp-indent stream))))
(defgeneric stream-end-s-expression (stream)
(:method ((stream t)) (declare (ignore stream)))
(:method ((stream fill-stream))
(fill-stream-flush-buffer stream nil)
(setf (slot-value stream 'inside-sexp) nil)))
(defmacro with-stream-s-expression ((stream) &body body)
`(let ((*print-right-margin* (stream-start-s-expression ,stream)))
,@body
(stream-end-s-expression ,stream)))
| 7,713 | Common Lisp | .lisp | 160 | 41.2875 | 77 | 0.657647 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 3f75cb6b819a55c63b398d56f63c70e9664a92f7c01eb18b94bc54354655ab74 | 11,342 | [
-1
] |
11,343 | places.lisp | ufasoft_lisp/clisp/places.lisp | ;;; CLISP - PLACES.LSP
;;; CLISP-specific: string-concat, %rplaca, %rplacd, store, setelt, ...
(in-package "SYSTEM")
;;;----------------------------------------------------------------------------
;;; Functions to define and deal with places
;;;----------------------------------------------------------------------------
;;; Return a symbol for SYSTEM::SETF-FUNCTION
;;; the returned symbol will be interned iff the argument is.
(defun setf-symbol (symbol)
(let* ((pack (symbol-package symbol))
(name (string-concat "(SETF " (if pack (package-name pack) "#") ":"
(symbol-name symbol) ")")))
(if pack
(intern name pack)
(make-symbol name))))
;;;----------------------------------------------------------------------------
;;; Returns the symbol which is on the property list at SYSTEM::SETF-FUNCTION
(defun get-setf-symbol (symbol) ; ABI
(or (get symbol 'SYSTEM::SETF-FUNCTION)
(progn
(when (get symbol 'SYSTEM::SETF-EXPANDER)
(warn (TEXT "The function (~S ~S) is hidden by a SETF expander.")
'setf symbol))
(setf (get symbol 'SYSTEM::SETF-FUNCTION) (setf-symbol symbol)))))
;;;----------------------------------------------------------------------------
;;; Returns 5 values:
;;; SM1 temps variables to bind
;;; SM2 subforms values to bind to
;;; SM3 stores variables whose values are used by the setter form
;;; SM4 setterform setter form
;;; SM5 getterform getter form
(defun get-setf-expansion (form &optional env)
(unless env ; user may pass env=NIL to mean "null lexical environment"
(setq env (vector nil nil)))
(loop
;; 1st step: search for global SETF definitions:
(when (and (consp form) (symbolp (car form)))
(when (global-in-fenv-p (car form) (svref env 1))
;; Operator not defined locally
(let ((plist-info (get (first form) 'SYSTEM::SETF-EXPANDER)))
(when plist-info
(return-from get-setf-expansion
(if (symbolp plist-info) ; Symbol comes from a short DEFSETF
(do* ((storevar (gensym "NEW-"))
(tempvars nil (cons (gensym "TEMP-") tempvars))
(tempforms nil (cons (car formr) tempforms))
(formr (cdr form) (cdr formr)))
((endp formr)
(setq tempforms (nreverse tempforms))
(values tempvars
tempforms
`(,storevar)
`(,plist-info ,@tempvars ,storevar)
`(,(first form) ,@tempvars))))
(let ((argcount (car plist-info)))
(if (eql argcount -5)
;; (-5 . fun) comes from DEFINE-SETF-METHOD
(funcall (cdr plist-info) form env)
;; (argcount storevarcount . fun) comes from a long DEFSETF
(let ((access-form form)
(tempvars '())
(tempforms '())
(new-access-form '()))
(let ((i 0)) ; argument counter
;; argcount = -1 if no keyword arguments exist
;; resp. = number of the arguments before &KEY,
;; = nil after these are processed.
(dolist (argform (cdr access-form))
(when (eql i argcount) (setq argcount nil i 0))
(if (and (null argcount) (evenp i))
(if (keywordp argform)
(push argform new-access-form)
(error-of-type 'source-program-error
:form form
:detail argform
(TEXT "The argument ~S to ~S should be a keyword.")
argform (car access-form)))
(let ((tempvar (gensym)))
(push tempvar tempvars)
(push argform tempforms)
(push tempvar new-access-form)))
(incf i)))
(setq new-access-form (nreverse new-access-form))
(let ((newval-vars (gensym-list (cadr plist-info))))
(values
(nreverse tempvars)
(nreverse tempforms)
newval-vars
(apply (cddr plist-info) env
(append newval-vars new-access-form))
(cons (car access-form) new-access-form))))))))))))
;; 2nd step: macroexpand
(when (eq form (setq form (macroexpand-1 form env)))
(return)))
;; 3rd step: default SETF methods
(cond ((symbolp form)
(return-from get-setf-expansion
(let ((storevar (gensym "NEW-")))
(values nil
nil
`(,storevar)
`(SETQ ,form ,storevar)
`,form))))
((and (consp form) (symbolp (car form)))
(return-from get-setf-expansion
(do* ((storevar (gensym "NEW-"))
(tempvars nil (cons (gensym "TEMP-") tempvars))
(tempforms nil (cons (car formr) tempforms))
(formr (cdr form) (cdr formr)))
((endp formr)
(setq tempforms (nreverse tempforms))
(values tempvars
tempforms
`(,storevar)
;; this is identical to CLISP-specific
;; ((SETF ,(first form)) ,storevar ,@tempvars)
;; but the we will return the form
;; that will not confuse 3rd party code walkers
`(FUNCALL #'(SETF ,(first form)) ,storevar ,@tempvars)
`(,(first form) ,@tempvars))))))
(t (error-of-type 'source-program-error
:form form
:detail form
(TEXT "~S: Argument ~S is not a SETF place.")
'get-setf-expansion form))))
;;;----------------------------------------------------------------------------
(defun get-setf-method (form &optional (env (vector nil nil)))
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion form env)
(unless (and (consp stores) (null (cdr stores)))
(error-of-type 'source-program-error
:form form :detail form
(TEXT "SETF place ~S should produce exactly one store variable.")
form))
(values temps subforms stores setterform getterform)))
;;;----------------------------------------------------------------------------
;;; Auxiliary functions for simplifying bindings and setterforms.
;;; Like (subst newitem olditem form), except that it works on forms and
;;; doesn't look inside quoted literals.
;;; FIXME: This is still not correct: The form can contain macros or THE.
(defun subst-in-form (newitem olditem form)
;; Don't use subst here, since a form can contain circular lists
;; hidden behind QUOTE.
(if (atom form)
(if (eql form olditem) newitem form)
(if (eq (car form) 'QUOTE)
form
(let ((modified nil)
(new-form-reversed '()))
(do ((formr form (cdr formr)))
((atom formr)
(unless (eql formr (setq formr (subst-in-form newitem olditem
formr)))
(setq modified t))
(if modified (nreconc new-form-reversed formr) form))
(let ((new-subform (subst-in-form newitem olditem (car formr))))
(unless (eql (car formr) new-subform)
(setq modified t))
(setq new-form-reversed (cons new-subform new-form-reversed))))))))
;;; Like (sublis alist form), except that it works on forms and
;;; doesn't look inside quoted literals.
;;; FIXME: This is still not correct: The form can contain macros or THE.
(defun sublis-in-form (alist form)
;; Don't use sublis here, since a form can contain circular lists
;; hidden behind QUOTE.
(if (atom form)
(let ((h (assoc form alist))) (if h (cdr h) form))
(if (eq (car form) 'QUOTE)
form
(let ((modified nil)
(new-form-reversed '()))
(do ((formr form (cdr formr)))
((atom formr)
(unless (eql formr (setq formr (sublis-in-form alist formr)))
(setq modified t))
(if modified (nreconc new-form-reversed formr) form))
(let ((new-subform (sublis-in-form alist (car formr))))
(unless (eql (car formr) new-subform)
(setq modified t))
(setq new-form-reversed (cons new-subform new-form-reversed))))))))
;;; An empty binding list can be optimized away.
(defun wrap-let* (bindlist form)
(if (and (null bindlist)
;; But don't optimize the LET* away if the form is a PROGN form,
;; because when it occurs as a top-level form in a file and refers
;; to uninterned symbols, compiling the elements of the PROGN
;; separately leads to problems.
(not (and (consp form) (eq (first form) 'PROGN))))
form
`(LET* ,bindlist ,form)))
;;; In simple assignments like (SETQ foo #:G0) the #:G0 can be replaced
;;; directly.
(defun simple-assignment-p (env store-form stores)
(and (= (length stores) 1)
(consp store-form)
(eq (first store-form) 'SETQ)
(= (length store-form) 3)
(symbolp (second store-form))
(not (nth-value 1 (macroexpand-1 (second store-form) env)))
(simple-use-p (third store-form) (first stores))))
(defun simple-use-p (form var)
(or (eq form var)
(and (consp form) (eq (first form) 'THE) (= (length form) 3)
(simple-use-p (third form) var))))
;;; Tests whether a variable (a gensym) occurs in the given form.
;;; FIXME: This is still not correct: The form can contain macros or THE.
(defun occurs-in-p (form var)
;; Don't use (tree-equal form form ...) here, since a form can contain
;; circular lists hidden behind QUOTE.
(if (atom form)
(eq form var)
(if (eq (car form) 'QUOTE)
nil
(do ((formr form (cdr formr)))
((atom formr) (eq formr var))
(when (occurs-in-p (car formr) var) (return t))))))
;;; Tests whether two forms are guaranteed to commute. The first is assumed to
;;; be a symbol, the second one can be more complex.
(defun commuting-forms-p (var form env)
(and (symbolp var)
(not (nth-value 1 (macroexpand-1 var env)))
(not (nth-value 1 (macroexpand-1 form env)))
(if (atom form)
(not (eq form var))
(let ((funname (first form))
(argforms (rest form)))
(and (function-name-p funname) ; we don't handle LAMBDAs here
(if (symbolp funname)
(and (not (special-operator-p funname))
(null (macro-function funname env)))
t)
(not (sys::fenv-search funname (and env (svref env 1))))
(every #'(lambda (argform) (commuting-forms-p var argform env))
argforms))))))
;;; For bootstrapping.
(predefun sys::fenv-search (funname fenv)
(declare (ignore funname fenv))
nil)
;;; In simple function calls like (SYSTEM::%RPLACA foo #:G0) the #:G0 can be
;;; replaced directly if it occurs only once, as an argument, and the earlier
;;; arguments commute with the value.
(defun simple-occurrence-in-basic-block-p (env form var valform)
(if (atom form)
(eq form var)
(case (first form)
(SETQ
(and (= (length form) 3)
(symbolp (second form))
(not (nth-value 1 (macroexpand-1 (second form) env)))
(not (eq (second form) var))
(simple-occurrence-in-basic-block-p env (third form) var valform)))
(THE
(and (= (length form) 3)
(simple-occurrence-in-basic-block-p env (third form) var valform)))
(t
(let ((funname (first form))
(argforms (rest form)))
(and (function-name-p funname) ; we don't handle LAMBDAs here
(if (symbolp funname)
(and (not (special-operator-p funname))
(null (macro-function funname env)))
t)
;; At this point we know it's a function call.
;; We assume the value to be put in for var does not change
;; funname's function definition,
(do ((earlier-argforms (reverse argforms)
(cdr earlier-argforms)))
((null earlier-argforms) nil)
(when (occurs-in-p (car earlier-argforms) var)
;; Found the last argument form that refers to var.
(return
(and (simple-occurrence-in-basic-block-p
env (car earlier-argforms) var valform)
(every #'(lambda (argform)
(and (symbolp argform)
(not (nth-value 1 (macroexpand-1
argform env)))
(not (ext:special-variable-p
argform env))
(not (eq argform var))
(commuting-forms-p argform valform
env)))
(cdr earlier-argforms))))))))))))
(defun optimized-wrap-let* (env bindlist form) ; ABI
(if (null bindlist)
form
(let* ((last-binding (car (last bindlist)))
(last-var (first last-binding))
(last-valform (second last-binding)))
(if (simple-occurrence-in-basic-block-p env form last-var last-valform)
(optimized-wrap-let* env (butlast bindlist)
(subst-in-form last-valform last-var form))
(wrap-let* bindlist form)))))
(defun optimized-wrap-multiple-value-bind (env varlist valuesform form)
(cond ((null varlist)
`(PROGN ,valuesform ,form))
((null (cdr varlist))
(optimized-wrap-let* env (list (list (car varlist) valuesform)) form))
(t `(MULTIPLE-VALUE-BIND ,varlist ,valuesform ,form))))
;;;----------------------------------------------------------------------------
(defmacro push (item place &environment env)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion place env)
(let ((itemtemps (gensym-list (length stores)))
(bindlist (mapcar #'list temps subforms))
(oldtemps (gensym-list (length stores))))
(optimized-wrap-multiple-value-bind env itemtemps item
(wrap-let* bindlist
(optimized-wrap-multiple-value-bind env oldtemps getterform
;; We're not blindly optimizing this to
;; (sublis-in-form
;; (mapcar #'(lambda (storevar itemvar oldvar)
;; (cons storevar `(CONS ,itemvar ,oldvar)))
;; stores itemtemps oldtemps)
;; setterform)
;; because we don't want the CONS forms to be evaluated multiple
;; times. Instead we rely on simple-occurrence-in-basic-block-p for
;; doing the analysis.
(optimized-wrap-let* env
(mapcar #'(lambda (storevar itemvar oldvar)
(list storevar `(CONS ,itemvar ,oldvar)))
stores itemtemps oldtemps)
setterform)))))))
;;;----------------------------------------------------------------------------
(eval-when (load compile eval)
(defun check-accessor-name (accessfn whole-form)
(unless (symbolp accessfn)
(error-of-type 'source-program-error
:form whole-form
:detail accessfn
(TEXT "The name of the accessor must be a symbol, not ~S")
accessfn))))
(defmacro define-setf-expander (&whole whole-form
accessfn lambdalist &body body)
(check-accessor-name accessfn whole-form)
(multiple-value-bind (body-rest declarations docstring)
(system::parse-body body t)
(if (null body-rest) (setq body-rest '(NIL)))
(let ((name (make-symbol (string-concat "SETF-" (symbol-name accessfn))))
(SYSTEM::%WHOLE-FORM whole-form)
(SYSTEM::%PROPER-LIST-P t))
(multiple-value-bind (newlambdalist envvar)
(remove-env-arg lambdalist name)
(let ((SYSTEM::%ARG-COUNT 0)
(SYSTEM::%MIN-ARGS 0)
(SYSTEM::%RESTP nil)
(SYSTEM::%NULL-TESTS nil)
(SYSTEM::%LET-LIST nil)
(SYSTEM::%KEYWORD-TESTS nil)
(SYSTEM::%DEFAULT-FORM nil))
(SYSTEM::ANALYZE1 newlambdalist '(CDR SYSTEM::%LAMBDA-LIST)
name 'SYSTEM::%LAMBDA-LIST)
(if (null newlambdalist)
(push `(IGNORE SYSTEM::%LAMBDA-LIST) declarations))
(let ((lengthtest (sys::make-length-test 'SYSTEM::%LAMBDA-LIST 1))
(mainform
`(LET* ,(nreverse SYSTEM::%LET-LIST)
,@(if declarations `(,(cons 'DECLARE declarations)))
,@(nreverse SYSTEM::%NULL-TESTS)
,@(nreverse SYSTEM::%KEYWORD-TESTS)
(BLOCK ,accessfn ,@body-rest))))
(if lengthtest
(setq mainform
`(IF ,lengthtest
(ERROR-OF-TYPE 'PROGRAM-ERROR
(TEXT "The SETF expander for ~S may not be called with ~S arguments.")
(QUOTE ,accessfn) (1- (LENGTH SYSTEM::%LAMBDA-LIST)))
,mainform)))
`(EVAL-WHEN (LOAD COMPILE EVAL)
(LET ()
(REMPROP ',accessfn 'SYSTEM::DEFSTRUCT-WRITER)
(DEFUN ,name (SYSTEM::%LAMBDA-LIST ,(or envvar 'SYSTEM::ENV))
,@(if envvar '() '((DECLARE (IGNORE SYSTEM::ENV))))
,mainform)
(sys::check-redefinition
',accessfn 'define-setf-expander
(and (get ',accessfn 'SYSTEM::SETF-EXPANDER)
(TEXT "SETF expander")))
(SYSTEM::%PUT ',accessfn 'SYSTEM::SETF-EXPANDER
(CONS -5 (FUNCTION ,name)))
(SYSTEM::%SET-DOCUMENTATION ',accessfn 'SETF ',docstring)
',accessfn))))))))
;;;----------------------------------------------------------------------------
(defmacro defsetf (&whole whole-form
accessfn &rest args)
(check-accessor-name accessfn whole-form)
(cond ((and (consp args) (not (listp (first args))) (symbolp (first args)))
`(EVAL-WHEN (LOAD COMPILE EVAL)
(LET ()
(REMPROP ',accessfn 'SYSTEM::DEFSTRUCT-WRITER)
(SYS::CHECK-REDEFINITION
',accessfn 'DEFSETF
(and (get ',accessfn 'SYSTEM::SETF-EXPANDER)
(TEXT "SETF expander")))
(SYSTEM::%PUT ',accessfn 'SYSTEM::SETF-EXPANDER ',(first args))
(SYSTEM::%SET-DOCUMENTATION ',accessfn 'SETF
,(if (and (null (cddr args))
(or (null (second args)) (stringp (second args))))
(second args)
(if (cddr args)
(error-of-type 'source-program-error
:form whole-form
:detail (cdr args)
(TEXT "~S: Too many arguments: ~S")
'defsetf (cdr args))
(error-of-type 'source-program-error
:form whole-form
:detail (second args)
(TEXT "~S: The documentation string must be a string: ~S")
'defsetf (second args)))))
',accessfn)))
((and (consp args) (listp (first args)) (consp (cdr args))
(listp (second args)))
(multiple-value-bind (body-rest declarations docstring)
(system::parse-body (cddr args) t)
(let* ((storevars (second args))
arg-count
(setter
(let ((lambdalist (first args)))
(multiple-value-bind (reqvars optvars optinits optsvars
rest keyp keywords keyvars keyinits
keysvars allowp env)
(analyze-defsetf-lambdalist lambdalist
#'(lambda (lalist detail errorstring &rest arguments)
(declare (ignore lalist));use WHOLE-FORM instead
(lambda-list-error whole-form detail
(TEXT "~S ~S: invalid ~S lambda-list: ~A")
'defsetf accessfn 'defsetf
(apply #'format nil errorstring arguments))))
(declare (ignore optinits optsvars rest keywords keyvars
keyinits keysvars allowp))
(setq arg-count (if keyp (+ (length reqvars)
(length optvars)) -1))
(if (eql env 0)
(setq env (gensym "IG")
declarations (cons `(IGNORE ,env) declarations))
(setq lambdalist
(let ((lr (memq '&ENVIRONMENT lambdalist)))
(append (ldiff lambdalist lr) (cddr lr)))))
(when declarations
(setq declarations `((DECLARE ,@declarations))))
`(LAMBDA (,env ,@storevars ,@lambdalist)
,@declarations
(BLOCK ,accessfn ,@body-rest))))))
`(EVAL-WHEN (LOAD COMPILE EVAL)
(LET ()
(REMPROP ',accessfn 'SYSTEM::DEFSTRUCT-WRITER)
(SYS::CHECK-REDEFINITION
',accessfn 'DEFSETF
(AND (GET ',accessfn 'SYSTEM::SETF-EXPANDER)
(TEXT "SETF expander")))
(SYSTEM::%PUT ',accessfn 'SYSTEM::SETF-EXPANDER
(LIST* ,arg-count ,(length storevars)
(FUNCTION ,(concat-pnames "SETF-" accessfn)
,setter)))
(SYSTEM::%SET-DOCUMENTATION ',accessfn 'SETF ,docstring)
',accessfn)))))
(t (error-of-type 'source-program-error
:form whole-form
:detail args
(TEXT "(~S ~S): Illegal syntax.")
'defsetf accessfn))))
;;;----------------------------------------------------------------------------
;;; Redirects #'(SETF accessfn) to be the same as setterfn.
(defmacro def-setf-alias (accessfn setterfn)
`(SYSTEM::%PUT ',accessfn 'SYSTEM::SETF-FUNCTION ',setterfn))
;;;----------------------------------------------------------------------------
;;; Definition of places:
;;;----------------------------------------------------------------------------
(def-setf-alias system::package-documentation SYSTEM::|(SETF PACKAGE-DOCUMENTATION)|)
(def-setf-alias package-case-inverted-p SYSTEM::|(SETF PACKAGE-CASE-INVERTED-P)|)
(def-setf-alias package-case-sensitive-p SYSTEM::|(SETF PACKAGE-CASE-SENSITIVE-P)|)
(def-setf-alias package-lock SYSTEM::|(SETF PACKAGE-LOCK)|)
(def-setf-alias hash-table-weak-p SYSTEM::|(SETF HASH-TABLE-WEAK-P)|)
(def-setf-alias hash-table-warn-if-needs-rehash-after-gc SYSTEM::|(SETF HASH-TABLE-WARN-IF-NEEDS-REHASH-AFTER-GC)|)
(def-setf-alias weak-pointer-value SYSTEM::|(SETF WEAK-POINTER-VALUE)|)
(def-setf-alias weak-list-list SYSTEM::|(SETF WEAK-LIST-LIST)|)
(def-setf-alias weak-mapping-value SYSTEM::|(SETF WEAK-MAPPING-VALUE)|)
(def-setf-alias weak-and-mapping-value SYSTEM::|(SETF WEAK-AND-MAPPING-VALUE)|)
(def-setf-alias weak-or-mapping-value SYSTEM::|(SETF WEAK-OR-MAPPING-VALUE)|)
(def-setf-alias weak-alist-contents SYSTEM::|(SETF WEAK-ALIST-CONTENTS)|)
(def-setf-alias weak-alist-value SYSTEM::|(SETF WEAK-ALIST-VALUE)|)
;;;----------------------------------------------------------------------------
(defsetf aref (array &rest indices) (value)
`(SYSTEM::STORE ,array ,@indices ,value))
;;;----------------------------------------------------------------------------
(defun SYSTEM::%SETNTH (index list value) ; ABI
(let ((pointer (nthcdr index list)))
(if (null pointer)
(error-of-type 'error
(TEXT "~S: index ~S is too large for ~S")
'(setf nth) index list)
(rplaca pointer value))
value))
(defsetf nth SYSTEM::%SETNTH)
;;;----------------------------------------------------------------------------
(def-setf-alias elt SYSTEM::|(SETF ELT)|)
;;;----------------------------------------------------------------------------
(defsetf rest SYSTEM::%RPLACD)
(defsetf first SYSTEM::%RPLACA)
(defsetf second (list) (value) `(SYSTEM::%RPLACA (CDR ,list) ,value))
(defsetf third (list) (value) `(SYSTEM::%RPLACA (CDDR ,list) ,value))
(defsetf fourth (list) (value) `(SYSTEM::%RPLACA (CDDDR ,list) ,value))
(defsetf fifth (list) (value) `(SYSTEM::%RPLACA (CDDDDR ,list) ,value))
(defsetf sixth (list) (value) `(SYSTEM::%RPLACA (CDR (CDDDDR ,list)) ,value))
(defsetf seventh (list) (value) `(SYSTEM::%RPLACA (CDDR (CDDDDR ,list)) ,value))
(defsetf eighth (list) (value) `(SYSTEM::%RPLACA (CDDDR (CDDDDR ,list)) ,value))
(defsetf ninth (list) (value) `(SYSTEM::%RPLACA (CDDDDR (CDDDDR ,list)) ,value))
(defsetf tenth (list) (value) `(SYSTEM::%RPLACA (CDR (CDDDDR (CDDDDR ,list))) ,value))
(defsetf car SYSTEM::%RPLACA)
(defsetf cdr SYSTEM::%RPLACD)
(defsetf caar (list) (value) `(SYSTEM::%RPLACA (CAR ,list) ,value))
(defsetf cadr (list) (value) `(SYSTEM::%RPLACA (CDR ,list) ,value))
(defsetf cdar (list) (value) `(SYSTEM::%RPLACD (CAR ,list) ,value))
(defsetf cddr (list) (value) `(SYSTEM::%RPLACD (CDR ,list) ,value))
(defsetf caaar (list) (value) `(SYSTEM::%RPLACA (CAAR ,list) ,value))
(defsetf caadr (list) (value) `(SYSTEM::%RPLACA (CADR ,list) ,value))
(defsetf cadar (list) (value) `(SYSTEM::%RPLACA (CDAR ,list) ,value))
(defsetf caddr (list) (value) `(SYSTEM::%RPLACA (CDDR ,list) ,value))
(defsetf cdaar (list) (value) `(SYSTEM::%RPLACD (CAAR ,list) ,value))
(defsetf cdadr (list) (value) `(SYSTEM::%RPLACD (CADR ,list) ,value))
(defsetf cddar (list) (value) `(SYSTEM::%RPLACD (CDAR ,list) ,value))
(defsetf cdddr (list) (value) `(SYSTEM::%RPLACD (CDDR ,list) ,value))
(defsetf caaaar (list) (value) `(SYSTEM::%RPLACA (CAAAR ,list) ,value))
(defsetf caaadr (list) (value) `(SYSTEM::%RPLACA (CAADR ,list) ,value))
(defsetf caadar (list) (value) `(SYSTEM::%RPLACA (CADAR ,list) ,value))
(defsetf caaddr (list) (value) `(SYSTEM::%RPLACA (CADDR ,list) ,value))
(defsetf cadaar (list) (value) `(SYSTEM::%RPLACA (CDAAR ,list) ,value))
(defsetf cadadr (list) (value) `(SYSTEM::%RPLACA (CDADR ,list) ,value))
(defsetf caddar (list) (value) `(SYSTEM::%RPLACA (CDDAR ,list) ,value))
(defsetf cadddr (list) (value) `(SYSTEM::%RPLACA (CDDDR ,list) ,value))
(defsetf cdaaar (list) (value) `(SYSTEM::%RPLACD (CAAAR ,list) ,value))
(defsetf cdaadr (list) (value) `(SYSTEM::%RPLACD (CAADR ,list) ,value))
(defsetf cdadar (list) (value) `(SYSTEM::%RPLACD (CADAR ,list) ,value))
(defsetf cdaddr (list) (value) `(SYSTEM::%RPLACD (CADDR ,list) ,value))
(defsetf cddaar (list) (value) `(SYSTEM::%RPLACD (CDAAR ,list) ,value))
(defsetf cddadr (list) (value) `(SYSTEM::%RPLACD (CDADR ,list) ,value))
(defsetf cdddar (list) (value) `(SYSTEM::%RPLACD (CDDAR ,list) ,value))
(defsetf cddddr (list) (value) `(SYSTEM::%RPLACD (CDDDR ,list) ,value))
;;;----------------------------------------------------------------------------
(defsetf svref SYSTEM::SVSTORE)
(defsetf row-major-aref system::row-major-store)
;;;----------------------------------------------------------------------------
;;; Simplify a form, when its values are not needed, only its side effects.
;;; Returns a list of subforms.
;;; (values x y z) --> (x y z)
;;; x --> (x)
(defun devalue-form (form)
(if (eq (car form) 'VALUES) (cdr form) (list form)))
;;;----------------------------------------------------------------------------
(defmacro pop (place &environment env)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion place env)
;; Be sure to call the CARs before the CDRs - it matters in case
;; not all of the places evaluate to lists.
(let* ((bindlist (mapcar #'list temps subforms))
(oldtemps (gensym-list (length stores)))
(advance-and-set-form
;; We're not blindly optimizing this to
;; (sublis-in-form
;; (mapcar #'(lambda (storevar oldvar) (cons storevar `(CDR ,oldvar)))
;; stores oldtemps)
;; setterform)
;; because some part of the setterform could make side-effects that
;; affect the value of the CDRs. Instead we rely on
;; simple-occurrence-in-basic-block-p for doing the analysis.
(optimized-wrap-let* env
(mapcar #'(lambda (storevar oldvar)
(list storevar `(CDR ,oldvar)))
stores oldtemps)
setterform)))
(if (= (length stores) 1)
(let ((prog1-form
`(PROG1
(CAR ,(car oldtemps))
,@(devalue-form advance-and-set-form))))
(if (and (symbolp getterform)
(not (nth-value 1 (macroexpand-1 getterform env)))
(simple-occurrence-in-basic-block-p env advance-and-set-form
(car oldtemps) getterform))
;; getterform can be evaluated multiple times instead of once,
;; and nothing in the setterform interferes with its value.
;; => Optimize away the binding of the oldtemps.
(optimized-wrap-let* env bindlist
(subst-in-form getterform (car oldtemps)
prog1-form))
(optimized-wrap-let*
env (nconc bindlist (list (list (car oldtemps) getterform)))
prog1-form)))
(optimized-wrap-let* env bindlist
(optimized-wrap-multiple-value-bind env oldtemps getterform
`(MULTIPLE-VALUE-PROG1
(VALUES ,@(mapcar #'(lambda (oldvar) `(CAR ,oldvar)) oldtemps))
,@(devalue-form advance-and-set-form))))))))
;----------------------------------------------------------------------------
(defmacro psetf (&whole whole-form
&rest args &environment env)
(labels ((recurse (args)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion (car args) env)
(declare (ignore getterform))
(when (atom (cdr args))
(error-of-type 'source-program-error
:form whole-form
:detail whole-form
(TEXT "~S called with an odd number of arguments: ~S")
'psetf whole-form))
(wrap-let* (mapcar #'list temps subforms)
`(MULTIPLE-VALUE-BIND ,stores ,(second args)
,@(when (cddr args) (list (recurse (cddr args))))
,@(devalue-form setterform))))))
(when args `(,@(recurse args) NIL))))
;;;----------------------------------------------------------------------------
(defmacro pushnew (item place &rest keylist &environment env)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion place env)
(let ((itemtemps (gensym-list (length stores)))
(bindlist (mapcar #'list temps subforms))
(oldtemps (gensym-list (length stores))))
(optimized-wrap-multiple-value-bind env itemtemps item
(wrap-let* bindlist
(optimized-wrap-multiple-value-bind env oldtemps getterform
;; We're not blindly optimizing this to
;; (sublis-in-form
;; (mapcar #'(lambda (storevar itemvar oldvar)
;; (cons storevar `(ADJOIN ,itemvar ,oldvar ,@keylist)))
;; stores itemtemps oldtemps)
;; setterform)
;; because we don't want the ADJOIN forms to be evaluated multiple
;; times. Instead we rely on simple-occurrence-in-basic-block-p for
;; doing the analysis.
(optimized-wrap-let* env
(mapcar #'(lambda (storevar itemvar oldvar)
(list storevar `(ADJOIN ,itemvar ,oldvar ,@keylist)))
stores itemtemps oldtemps)
setterform)))))))
;;;----------------------------------------------------------------------------
(defmacro remf (place indicator &environment env)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-method place env)
(let* ((indicatorvar (gensym "INDICATOR-"))
(oldtemps (gensym-list (length stores)))
(bindlist
;; The order of the bindings is a not strictly left-to-right here,
;; but that's how ANSI CL 5.1.3 specifies it.
`(,@(mapcar #'list temps subforms)
(,indicatorvar ,indicator)
(,(first oldtemps) ,getterform)))
(removed-p (gensym)))
(wrap-let* bindlist
`(MULTIPLE-VALUE-BIND (,(first stores) ,removed-p)
(SYSTEM::%REMF ,(first oldtemps) ,indicatorvar)
(WHEN (AND ,removed-p (ATOM ,(first stores)))
,setterform)
,removed-p)))))
;;;----------------------------------------------------------------------------
(export 'ext::remove-plist "EXT")
;;; Remove the keys from the plist.
;;; Useful for re-using the &REST arg after removing some options.
(defun remove-plist (plist &rest keys)
;; This implementation is
;; 1. minimal-consing, non-consing if possible,
;; 2. O(L*K) where L = (length plist), K = (length keys).
;; Remove the first occurring key first, then the second occurring key, etc.
;; This allows us to use the built-in GET-PROPERTIES function.
;; Another O(L*K) algorithm is remove the keys in the order in which they
;; occur in keys, keeping track how much of the list has already been copied.
(do ((copy '()))
(nil)
(let ((rest (nth-value 2 (get-properties plist keys))))
(unless rest (return (nreconc copy plist)))
(setq copy (nreconc (ldiff plist rest) copy))
(setq plist (cddr rest)))))
;;;----------------------------------------------------------------------------
(defmacro rotatef (&rest args &environment env)
(when (null args) (return-from rotatef NIL))
(when (null (cdr args)) (return-from rotatef `(PROGN ,(car args) NIL)))
(do* ((arglist args (cdr arglist))
(res (list 'LET* nil nil))
last-setterform
(tail (cdr res))
(bindlist '())
(all-stores '())
last-stores
first-stores)
((null arglist)
(setf (second res) (nreverse bindlist)
(second (third res)) last-stores
(cdr tail) (nconc (nreverse all-stores)
(devalue-form last-setterform))
(cdr (last res)) (list nil))
res)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion (first arglist) env)
(setq bindlist (nreconc (mapcar #'list temps subforms) bindlist))
(setf (cadr tail) (list 'MULTIPLE-VALUE-BIND last-stores getterform nil))
(setq tail (cddadr tail))
(if (null first-stores)
(setq first-stores stores)
(setq all-stores (revappend (devalue-form last-setterform) all-stores)))
(setq last-stores stores last-setterform setterform))))
;;;----------------------------------------------------------------------------
(defmacro define-modify-macro (&whole whole-form
name lambdalist function &optional docstring)
(multiple-value-bind (reqvars optvars optinits optsvars rest)
(analyze-modify-macro-lambdalist lambdalist
#'(lambda (lalist detail errorstring &rest arguments)
(declare (ignore lalist)) ; use WHOLE-FORM instead
(lambda-list-error whole-form detail
(TEXT "~S ~S: invalid ~S lambda-list: ~A")
'define-modify-macro name 'define-modify-macro
(apply #'format nil errorstring arguments))))
(declare (ignore optinits optsvars))
(let ((varlist (append reqvars optvars))
(restvar (if (not (eql rest 0)) rest nil)))
`(DEFMACRO ,name (PLACE ,@lambdalist &ENVIRONMENT ENV) ,docstring
(MULTIPLE-VALUE-BIND (TEMPS SUBFORMS STORES SETTERFORM GETTERFORM)
(GET-SETF-METHOD PLACE ENV)
;; ANSI CL 5.1.3. mandates the following evaluation order:
;; First the SUBFORMS,
;; then the varlist and restvar, then the GETTERFORM,
;; then the SETTERFORM.
(LET ((LET-LIST (MAPCAR #'LIST TEMPS SUBFORMS)))
(IF (AND ,@(mapcar #'(lambda (var) `(CONSTANTP ,var)) varlist)
,@(when restvar `((EVERY #'CONSTANTP ,restvar))))
;; The varlist and restvar forms are constant forms, therefore
;; may be evaluated after the GETTER instead of before.
(LET ((FUNCTION-APPLICATION
(LIST* ',function GETTERFORM ,@varlist ,restvar)))
(OPTIMIZED-WRAP-LET* ENV
(NCONC LET-LIST
(LIST (LIST (CAR STORES) FUNCTION-APPLICATION)))
SETTERFORM))
;; General case.
(LET* ((ARGVARS
(MAPCAR #'(LAMBDA (VAR) (DECLARE (IGNORE VAR)) (GENSYM))
(LIST* ,@varlist ,restvar)))
(FUNCTION-APPLICATION
(LIST* ',function GETTERFORM ARGVARS)))
(OPTIMIZED-WRAP-LET* ENV
(NCONC LET-LIST
(MAPCAR #'LIST ARGVARS (LIST* ,@varlist ,restvar))
(LIST (LIST (CAR STORES) FUNCTION-APPLICATION)))
SETTERFORM)))))))))
;;;----------------------------------------------------------------------------
(define-modify-macro decf (&optional (delta 1)) -)
;;;----------------------------------------------------------------------------
(define-modify-macro incf (&optional (delta 1)) +)
;;;----------------------------------------------------------------------------
(defmacro setf (&whole whole-form
&rest args &environment env)
(let ((argcount (length args)))
(cond ((eql argcount 2)
(let* ((place (first args))
(value (second args)))
(loop
;; 1st step: search for global SETF definitions:
(when (and (consp place) (symbolp (car place)))
(when (global-in-fenv-p (car place) (svref env 1))
;; operator not locally defined
(if (and (eq (first place) 'VALUES-LIST) (eql (length place) 2))
(return-from setf
`(VALUES-LIST
(SETF ,(second place) (MULTIPLE-VALUE-LIST ,value))))
(let ((plist-info (get (first place) 'SYSTEM::SETF-EXPANDER)))
(when plist-info
(return-from setf
(cond ((symbolp plist-info) ; Symbol comes from a short DEFSETF
`(,plist-info ,@(cdr place) ,value))
((and (eq (first place) 'THE) (eql (length place) 3))
`(SETF ,(third place) (THE ,(second place) ,value)))
(t
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion place env)
(declare (ignore getterform))
(let ((bindlist (mapcar #'list temps subforms)))
(if (= (length stores) 1)
;; 1 store variable
(wrap-let* (nconc bindlist
(list `(,(first stores) ,value)))
setterform)
;; multiple store variables
(if ;; is setterform like
;; (VALUES (SETQ v1 store1) ...) ?
(and (consp setterform)
(eq (car setterform) 'VALUES)
(do ((str stores (cdr str))
(sqr (cdr setterform) (cdr sqr)))
((or (null str) (null sqr))
(and (null str) (null sqr)))
(unless (simple-assignment-p env (car sqr) (list (car str)))
(return nil))))
(let ((vlist (mapcar #'second (rest setterform))))
`(LET* ,bindlist
(MULTIPLE-VALUE-SETQ ,vlist ,value)
(VALUES ,@vlist)))
(wrap-let* bindlist
`(MULTIPLE-VALUE-BIND ,stores ,value
,setterform))))))))))))))
;; 2nd step: macroexpand
(when (eq place (setq place (macroexpand-1 place env)))
(return)))
;; 3rd step: default SETF methods
(cond ((symbolp place)
`(SETQ ,place ,value))
((and (consp place) (symbolp (car place)))
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion place env)
(declare (ignore getterform))
;; setterform probably looks like
;; `((SETF ,(first place)) ,@stores ,@temps).
;; stores are probably superfluous and get optimized away.
(optimized-wrap-let* env
(nconc (mapcar #'list temps subforms)
(list (list (first stores) value)))
setterform)))
(t (error-of-type 'source-program-error
:form whole-form
:detail (first args)
(TEXT "~S: Illegal place: ~S")
'setf (first args))))))
((oddp argcount)
(error-of-type 'source-program-error
:form whole-form
:detail whole-form
(TEXT "~S called with an odd number of arguments: ~S")
'setf whole-form))
(t (do* ((arglist args (cddr arglist))
(L nil))
((null arglist) `(LET () (PROGN ,@(nreverse L))))
(push `(SETF ,(first arglist) ,(second arglist)) L))))))
;;;----------------------------------------------------------------------------
(defmacro shiftf (&whole whole-form
&rest args &environment env)
(when (< (length args) 2)
(error-of-type 'source-program-error
:form whole-form
:detail args
(TEXT "~S: too few arguments: ~S")
'shiftf whole-form))
(do* ((arglist args (cdr arglist))
(res (list 'LET* nil nil))
last-setterform
first-getterform
(tail (cdr res))
(bindlist '())
(all-stores '())
last-stores
first-stores)
((null (cdr arglist))
(setf (second res) (nreverse bindlist)
(cadr tail) (list 'MULTIPLE-VALUE-BIND last-stores
(car (last args)) nil)
tail (cddadr tail)
(cdr tail) (nconc (nreverse all-stores)
(devalue-form last-setterform))
(third res) (list 'MULTIPLE-VALUE-BIND first-stores
first-getterform (third res)
(cons 'values first-stores)))
res)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion (first arglist) env)
(setq bindlist (nreconc (mapcar #'list temps subforms) bindlist))
(if first-stores
(setf all-stores (revappend (devalue-form last-setterform) all-stores)
(cadr tail) (list 'MULTIPLE-VALUE-BIND last-stores getterform nil)
tail (cddadr tail))
(setq first-stores stores first-getterform getterform))
(setq last-stores stores last-setterform setterform))))
;;;----------------------------------------------------------------------------
;;; more places
;;;----------------------------------------------------------------------------
(defsetf GET (symbol indicator &optional default) (value)
(let ((storeform `(SYSTEM::%PUT ,symbol ,indicator ,value)))
(if default
`(PROGN ,default ,storeform) ; quasi-evaluate default, only feignedly
`,storeform)))
;;;----------------------------------------------------------------------------
;;; Sets to a certain indicator a value into a given property list.
;;; Return NIL if successful, or the new (enhanced) property list.
(define-setf-expander getf (place indicator &optional default &environment env)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-method place env)
(let* ((storevar (gensym "NEW-"))
(indicatorvar (gensym "INDICATOR-"))
(defaultvar-list (if default (list (gensym "IG")) `())))
(values
`(,@temps ,indicatorvar ,@defaultvar-list)
`(,@subforms ,indicator ,@(if default `(,default) `()))
`(,storevar)
`(LET ((,(first stores)
(SYS::%PUTF ,getterform ,indicatorvar ,storevar)))
,@defaultvar-list ; quasi-evalute defaultvar
(WHEN ,(first stores) ,setterform)
,storevar)
`(GETF ,getterform ,indicatorvar ,@defaultvar-list)))))
;;;----------------------------------------------------------------------------
(defsetf GETHASH (key hashtable &optional default) (value)
(let ((storeform `(SYSTEM::PUTHASH ,key ,hashtable ,value)))
(if default
`(PROGN ,default ,storeform) ; quasi-evalute default
`,storeform)))
;;;----------------------------------------------------------------------------
(defsetf fill-pointer SYSTEM::SET-FILL-POINTER)
;;;----------------------------------------------------------------------------
(defsetf readtable-case SYSTEM::SET-READTABLE-CASE)
;;;----------------------------------------------------------------------------
(defsetf SYMBOL-VALUE SYSTEM::SET-SYMBOL-VALUE)
(sys::%putd 'SET #'SYSTEM::SET-SYMBOL-VALUE) ; deprecated alias
;;;----------------------------------------------------------------------------
(defsetf SYMBOL-FUNCTION SYSTEM::%PUTD)
;;;----------------------------------------------------------------------------
(defsetf SYMBOL-PLIST SYSTEM::%PUTPLIST)
;;;----------------------------------------------------------------------------
(defun SYSTEM::SET-FDEFINITION (name value) ; ABI
(setf (symbol-function (get-funname-symbol name)) value))
(defsetf FDEFINITION SYSTEM::SET-FDEFINITION)
;;;----------------------------------------------------------------------------
(defsetf MACRO-FUNCTION (symbol &optional env) (value)
(declare (ignore env))
`(PROGN
(SETF (SYMBOL-FUNCTION ,symbol) (SYSTEM::MAKE-MACRO ,value 0))
(REMPROP ,symbol 'SYSTEM::MACRO)
,value))
;;;----------------------------------------------------------------------------
(defsetf CHAR SYSTEM::STORE-CHAR)
(defsetf SCHAR SYSTEM::STORE-SCHAR)
(defsetf BIT SYSTEM::STORE)
(defsetf SBIT SYSTEM::STORE)
(defsetf SUBSEQ (sequence start &optional end) (value)
`(PROGN (REPLACE ,sequence ,value :START1 ,start :END1 ,end) ,value))
;;;----------------------------------------------------------------------------
(define-setf-expander char-bit (char name &environment env)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-method char env)
(let* ((namevar (gensym))
(storevar (gensym "NEW-")))
(values `(,@temps ,namevar)
`(,@subforms ,name)
`(,storevar)
`(LET ((,(first stores)
(SET-CHAR-BIT ,getterform ,namevar ,storevar)))
,setterform
,storevar)
`(CHAR-BIT ,getterform ,namevar)))))
;;;----------------------------------------------------------------------------
(define-setf-expander LDB (bytespec integer &environment env)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-method integer env)
(let* ((bytespecvar (gensym "BYTESPEC-"))
(storevar (gensym "NEW-")))
(values (cons bytespecvar temps)
(cons bytespec subforms)
`(,storevar)
`(LET ((,(first stores) (DPB ,storevar ,bytespecvar ,getterform)))
,setterform
,storevar)
`(LDB ,bytespecvar ,getterform)))))
;;;----------------------------------------------------------------------------
(define-setf-expander MASK-FIELD (bytespec integer &environment env)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-method integer env)
(let* ((bytespecvar (gensym "BYTESPEC-"))
(storevar (gensym "NEW-")))
(values (cons bytespecvar temps)
(cons bytespec subforms)
`(,storevar)
`(LET ((,(first stores) (DEPOSIT-FIELD ,storevar ,bytespecvar ,getterform)))
,setterform
,storevar)
`(MASK-FIELD ,bytespecvar ,getterform)))))
;;;----------------------------------------------------------------------------
(define-setf-expander THE (type place &environment env)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion place env)
(values temps subforms stores
(sublis-in-form (mapcar #'(lambda (storevar simpletype)
(cons storevar
`(THE ,simpletype ,storevar)))
stores
(if (and (consp type)
(eq (car type) 'VALUES))
(cdr type)
(list type)))
setterform)
`(THE ,type ,getterform))))
;;;----------------------------------------------------------------------------
(define-setf-expander APPLY (&whole whole-form
fun &rest args &environment env)
(if (and (listp fun)
(eq (list-length fun) 2)
(eq (first fun) 'FUNCTION)
(symbolp (second fun)))
(setq fun (second fun))
(error-of-type 'source-program-error
:form whole-form
:detail fun
(TEXT "~S is only defined for functions of the form #'symbol.")
'(setf apply)))
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion (cons fun args) env)
(unless (eq (car (last args)) (car (last subforms)))
(error-of-type 'source-program-error
:form whole-form
:detail (cons fun args)
(TEXT "~S on ~S is not a SETF place.")
'apply fun))
(let ((item (car (last temps)))) ; 'item' stands for an argument list!
(labels ((splice (arglist)
;; If we would want in (LIST . arglist) the 'item' not
;; as one element, but spliced, as ',@item', so we
;; would need the form, which returns (splice arglist).
(if (endp arglist)
'NIL
(let ((rest (splice (cdr arglist))))
(if (eql (car arglist) item)
;; push an (APPEND item ...) to the front, as
;; with backquote
(backquote-append item rest)
;; push a (CONS (car arglist) ...) to the front,
;; as with backquote
(backquote-cons (car arglist) rest))))))
(flet ((call-splicing (form)
;; replaces the function call form with one, where 'item'
;; does not return one argument, but an argument list.
(let ((fun (first form))
(argform (splice (rest form))))
;; (APPLY #'fun argform) simplified:
;; (APPLY #'fun NIL) --> (fun)
;; (APPLY #'fun (LIST ...)) --> (fun ...)
;; (APPLY #'fun (CONS x y)) --> (APPLY #'fun x y)
;; (APPLY #'fun (LIST* ... z)) --> (APPLY #'fun ... z)
(if (or (null argform)
(and (consp argform) (eq (car argform) 'LIST)))
(cons fun (cdr argform))
(list* 'APPLY
(list 'FUNCTION fun)
(if (and (consp argform)
(or (eq (car argform) 'LIST*)
(eq (car argform) 'CONS)))
(cdr argform)
(list argform)))))))
(values temps subforms stores
(call-splicing setterform)
(call-splicing getterform)))))))
;;;----------------------------------------------------------------------------
;;; More places definitions
;;;----------------------------------------------------------------------------
(define-setf-expander funcall (&whole whole-form
fun &rest args &environment env)
(unless (and (listp fun)
(eq (list-length fun) 2)
(let ((fun1 (first fun)))
(or (eq fun1 'FUNCTION) (eq fun1 'QUOTE)))
(symbolp (second fun))
(setq fun (second fun)))
(error-of-type 'source-program-error
:form whole-form
:detail (cons fun args)
(TEXT "~S is only defined for functions of the form #'symbol.")
'(setf funcall)))
(get-setf-expansion (cons fun args) env))
;;;----------------------------------------------------------------------------
(define-setf-expander PROGN (&rest forms &environment env)
(let ((last (last forms)))
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion (car last) env)
(if (eq forms last)
(values temps subforms stores setterform getterform)
(let ((dummyvar (gensym "IG")))
(values
`(,dummyvar ,@temps)
`((PROGN ,@(ldiff forms last)) ,@subforms)
stores
`(PROGN
,dummyvar ; avoid warning about unused temporary variable
,setterform)
getterform))))))
;;;----------------------------------------------------------------------------
(define-setf-expander LOCALLY (&rest body &environment env)
(multiple-value-bind (body-rest declspecs) (system::parse-body body)
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion `(PROGN ,@body-rest) env)
(if declspecs
(let ((declarations `(DECLARE ,@declspecs)))
(values
temps
(mapcar #'(lambda (x) `(LOCALLY ,declarations ,x)) subforms)
stores
`(LOCALLY ,declarations ,setterform)
`(LOCALLY ,declarations ,getterform)))
(values temps subforms stores setterform getterform)))))
;;;----------------------------------------------------------------------------
(define-setf-expander IF (&whole whole-form
condition t-form f-form &environment env)
(let ((conditionvar (gensym "COND-")))
(multiple-value-bind (T-temps T-subforms T-stores T-setterform T-getterform)
(get-setf-expansion t-form env)
(multiple-value-bind (F-temps F-subforms F-stores F-setterform F-getterform)
(get-setf-expansion f-form env)
(unless (eql (length T-stores) (length F-stores))
(error-of-type 'source-program-error
:form whole-form
:detail whole-form
(TEXT "SETF place ~S expects different numbers of values in the true and false branches (~D vs. ~D values).")
(list 'IF condition t-form f-form) (length T-stores)
(length F-stores)))
(values
`(,conditionvar
,@T-temps
,@F-temps)
`(,condition
,@(mapcar #'(lambda (x) `(IF ,conditionvar ,x)) T-subforms)
,@(mapcar #'(lambda (x) `(IF (NOT ,conditionvar) ,x)) F-subforms))
T-stores
`(IF ,conditionvar ,T-setterform
,(sublis-in-form (mapcar #'cons F-stores T-stores) F-setterform))
`(IF ,conditionvar ,T-getterform ,F-getterform))))))
;;;----------------------------------------------------------------------------
(defsetf GET-DISPATCH-MACRO-CHARACTER
(disp-char sub-char &optional (readtable '*READTABLE*)) (value)
`(PROGN (SET-DISPATCH-MACRO-CHARACTER ,disp-char ,sub-char ,value ,readtable) ,value))
;;;----------------------------------------------------------------------------
(def-setf-alias long-float-digits SYSTEM::|(SETF LONG-FLOAT-DIGITS)|)
;;;----------------------------------------------------------------------------
(defsetf system::%record-ref system::%record-store)
(defsetf system::%structure-ref system::%structure-store)
(defsetf system::closure-const (closure n) (value)
`(system::set-closure-const ,value ,closure ,n))
;;;----------------------------------------------------------------------------
(def-setf-alias clos::standard-instance-access CLOS::|(SETF STANDARD-INSTANCE-ACCESS)|)
;;;----------------------------------------------------------------------------
(def-setf-alias system::closure-name SYSTEM::|(SETF CLOSURE-NAME)|)
;;;----------------------------------------------------------------------------
#+LOGICAL-PATHNAMES
(defsetf logical-pathname-translations set-logical-pathname-translations)
;;;----------------------------------------------------------------------------
(defsetf stream-external-format (stream &optional direction) (encoding)
`(system::set-stream-external-format ,stream ,encoding ,direction))
;;;----------------------------------------------------------------------------
;;; How to handle (SETF (VALUES place1 ... placek) form)
;;; --> (MULTIPLE-VALUE-BIND (dummy1 ... dummyk) form
;;; (SETF place1 dummy1 ... placek dummyk)
;;; (VALUES dummy1 ... dummyk)
;;;)
(define-setf-expander values (&rest subplaces &environment env)
(multiple-value-bind (temps subforms stores setterforms getterforms)
(setf-VALUES-aux subplaces env)
(values temps
subforms
stores
`(VALUES ,@setterforms)
`(VALUES ,@getterforms))))
(defun setf-VALUES-aux (places env)
(do ((temps nil)
(subforms nil)
(stores nil)
(setterforms nil)
(getterforms nil)
(placesr places))
((endp placesr)
(setq temps (nreverse temps))
(setq subforms (nreverse subforms))
(setq stores (nreverse stores))
(setq setterforms (nreverse setterforms))
(setq getterforms (nreverse getterforms))
(values temps subforms stores setterforms getterforms))
(multiple-value-bind (SM-temps SM-subforms SM-stores SM-setterform
SM-getterform)
(get-setf-expansion (pop placesr) env)
(setq temps (revappend SM-temps temps))
(setq subforms (revappend SM-subforms subforms))
(when SM-stores
;; See ANSI CL 5.1.2.3.
(dolist (extra-store (rest SM-stores))
(push extra-store temps)
(push 'NIL subforms))
(push (first SM-stores) stores))
(setq setterforms (cons SM-setterform setterforms))
(setq getterforms (cons SM-getterform getterforms)))))
;;;----------------------------------------------------------------------------
;;; Analog to (MULTIPLE-VALUE-SETQ (var1 ... vark) form) :
;;; (MULTIPLE-VALUE-SETF (place1 ... placek) form)
;;; --> (VALUES (SETF (VALUES place1 ... placek) form))
;;; --> (MULTIPLE-VALUE-BIND (dummy1 ... dummyk) form
;;; (SETF place1 dummy1 ... placek dummyk)
;;; dummy1
;;;)
(defmacro multiple-value-setf (places form &environment env)
(multiple-value-bind (temps subforms stores setterforms getterforms)
(setf-VALUES-aux places env)
(declare (ignore getterforms))
(wrap-let* (mapcar #'list temps subforms)
`(MULTIPLE-VALUE-BIND ,stores ,form
,@setterforms
,(first stores))))) ; (null stores) -> NIL -> Return value NIL
;;;----------------------------------------------------------------------------
;;; Symbol-macros
(define-symbol-macro *ansi* (sys::ansi))
(defsetf sys::ansi sys::set-ansi)
(system::%set-documentation '*ansi* 'variable
"This symbol-macro modifies some variables for maximum ANSI CL compliance.
Variables affected: `custom:*floating-point-contagion-ansi*',
`custom:*floating-point-rational-contagion-ansi*', `custom:*phase-ansi*',
`custom:*merge-pathnames-ansi*', `custom:*print-pathnames-ansi*',
`custom:*print-space-char-ansi*', `custom:*parse-namestring-ansi*',
`custom:*print-empty-arrays-ansi*', `custom:*print-unreadable-ansi*',
`custom:*sequence-count-ansi*', `custom:*coerce-fixnum-char-ansi*',
`custom:*defun-accept-specialized-lambda-list*', `custom:*loop-ansi*'.
Invoking CLISP with `-ansi' sets this to T.
Invoking CLISP with `-traditional' sets this to NIL.")
(define-symbol-macro *current-language* (sys::current-language))
(defsetf sys::current-language sys::set-current-language)
(system::%set-documentation '*current-language* 'variable
"This symbol-macro determines the current language used for UI.")
(define-symbol-macro *lib-directory* (sys::lib-directory))
(defsetf sys::lib-directory sys::set-lib-directory)
(system::%set-documentation '*lib-directory* 'variable
"This symbol-macro determines the location where CLISP finds its data files.")
(define-symbol-macro *default-file-encoding*
(system::default-file-encoding))
(defsetf system::default-file-encoding system::set-default-file-encoding)
#+UNICODE
(progn
(define-symbol-macro *pathname-encoding* (system::pathname-encoding))
(defsetf system::pathname-encoding system::set-pathname-encoding)
(define-symbol-macro *terminal-encoding* (system::terminal-encoding))
(defsetf system::terminal-encoding system::set-terminal-encoding)
(define-symbol-macro *misc-encoding* (system::misc-encoding))
(defsetf system::misc-encoding system::set-misc-encoding))
(when (fboundp 'sys::setenv)
(defsetf ext:getenv sys::setenv))
| 64,099 | Common Lisp | .lisp | 1,232 | 39.668019 | 121 | 0.513198 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 9d6b846e75aee668297e6891ba282d5934667a445a118644419a67861e9d1039 | 11,343 | [
-1
] |
11,344 | documentation.lisp | ufasoft_lisp/clisp/documentation.lisp | ;;;; Generic documentation
;;;; Sam Steingold 2002 - 2006
;;;; Bruno Haible 2004
(in-package "CLOS")
(defun function-documentation (x &aux name)
(cond ((typep-class x <standard-generic-function>)
(std-gf-documentation x))
((eq (type-of x) 'FUNCTION) ; interpreted function?
(sys::%record-ref x 2))
#+FFI ((eq (type-of x) 'ffi::foreign-function)
(getf (sys::%record-ref x 5) :documentation))
((sys::closurep x) (sys::closure-documentation x))
((setq name (sys::subr-info x)) (get :documentation name)) ; subr
(t (get :documentation (sys::%record-ref x 0)))))
;;; documentation
(defgeneric documentation (x doc-type)
(:argument-precedence-order doc-type x)
(:method ((x function) (doc-type (eql 't)))
(function-documentation x))
(:method ((x function) (doc-type (eql 'function)))
(function-documentation x))
(:method ((x cons) (doc-type (eql 'function)))
(setq x (check-function-name x 'documentation))
(and (fboundp x) (function-documentation (sys::unwrapped-fdefinition x))))
(:method ((x cons) (doc-type (eql 'compiler-macro)))
(setq x (check-function-name x 'documentation))
(if (symbolp x)
(documentation x 'compiler-macro)
(documentation (second x) 'setf-compiler-macro)))
(:method ((x symbol) (doc-type (eql 'function)))
(and (fboundp x) (function-documentation (sys::unwrapped-fdefinition x))))
(:method ((x symbol) (doc-type symbol))
;; doc-type = `compiler-macro', `setf', `variable', `type',
;; `setf-compiler-macro'
(getf (get x 'sys::doc) doc-type))
(:method ((x symbol) (doc-type (eql 'type)))
(let ((class (find-class x nil)))
(if class
(documentation class 't)
(call-next-method))))
(:method ((x symbol) (doc-type (eql 'structure))) ; structure --> type
(documentation x 'type))
(:method ((x symbol) (doc-type (eql 'class))) ; class --> type
(documentation x 'type))
(:method ((x method-combination) (doc-type (eql 't)))
(method-combination-documentation x))
(:method ((x method-combination) (doc-type (eql 'method-combination)))
(method-combination-documentation x))
(:method ((x symbol) (doc-type (eql 'method-combination)))
(method-combination-documentation (get-method-combination x 'documentation)))
(:method ((x standard-method) (doc-type (eql 't)))
(std-method-documentation x))
(:method ((x package) (doc-type (eql 't)))
(let ((doc (sys::package-documentation x)))
(if (consp doc) (first doc) doc)))
(:method ((x standard-class) (doc-type (eql 't)))
(class-documentation x))
(:method ((x standard-class) (doc-type (eql 'type)))
(class-documentation x))
(:method ((x structure-class) (doc-type (eql 't)))
(class-documentation x))
(:method ((x structure-class) (doc-type (eql 'type)))
(class-documentation x))
;;; The following are CLISP extensions.
(:method ((x standard-object) (doc-type (eql 't)))
(documentation (class-of x) 'type))
(:method ((x standard-object) (doc-type (eql 'type)))
(documentation (class-of x) 'type))
(:method ((x structure-object) (doc-type (eql 't)))
(documentation (class-of x) 'type))
(:method ((x structure-object) (doc-type (eql 'type)))
(documentation (class-of x) 'type))
(:method ((x defined-class) (doc-type (eql 't)))
(class-documentation x))
(:method ((x defined-class) (doc-type (eql 'type)))
(class-documentation x))
(:method ((x slot-definition) (doc-type (eql 't)))
(slot-definition-documentation x)))
(defun set-function-documentation (x new-value &aux name)
(cond ((typep-class x <standard-generic-function>)
(setf (std-gf-documentation x) new-value))
((eq (type-of x) 'FUNCTION) ; interpreted function?
(setf (sys::%record-ref x 2) new-value))
#+FFI ((eq (type-of x) 'ffi::foreign-function)
(setf (getf (sys::%record-ref x 5) :documentation) new-value))
((sys::closurep x) (sys::closure-set-documentation x new-value))
((setq name (sys::subr-info x)) ; subr
(setf (get :documentation name) new-value))
(t ; fsubr
(setf (get :documentation (sys::%record-ref x 0)) new-value))))
(defgeneric (setf documentation) (new-value x doc-type)
(:argument-precedence-order doc-type x new-value)
(:method (new-value (x function) (doc-type (eql 't)))
(set-function-documentation x new-value))
(:method (new-value (x function) (doc-type (eql 'function)))
(set-function-documentation x new-value))
(:method (new-value (x cons) (doc-type (eql 'function)))
(setq x (check-function-name x '(setf documentation)))
(and (fboundp x)
(set-function-documentation (sys::unwrapped-fdefinition x) new-value)))
(:method (new-value (x cons) (doc-type (eql 'compiler-macro)))
(setq x (check-function-name x '(setf documentation)))
(if (symbolp x)
(sys::%set-documentation x 'compiler-macro new-value)
(sys::%set-documentation (second x) 'setf-compiler-macro new-value)))
(:method (new-value (x symbol) (doc-type (eql 'function)))
(and (fboundp x)
(set-function-documentation (sys::unwrapped-fdefinition x) new-value)))
(:method (new-value (x symbol) (doc-type symbol))
;; doc-type = `compiler-macro', `setf', `variable', `type',
;; `setf-compiler-macro'
(sys::%set-documentation x doc-type new-value))
(:method (new-value (x symbol) (doc-type (eql 'type)))
(let ((class (find-class x nil)))
(if class
(setf (documentation class 't) new-value)
(call-next-method))))
(:method (new-value (x symbol) (doc-type (eql 'structure)))
(sys::%set-documentation x 'type new-value))
(:method (new-value (x symbol) (doc-type (eql 'class)))
(sys::%set-documentation x 'type new-value))
(:method (new-value (x method-combination) (doc-type (eql 't)))
(setf (method-combination-documentation x) new-value))
(:method
(new-value (x method-combination) (doc-type (eql 'method-combination)))
(setf (method-combination-documentation x) new-value))
(:method (new-value (x symbol) (doc-type (eql 'method-combination)))
(setf (method-combination-documentation (get-method-combination x '(setf documentation)))
new-value))
(:method (new-value (x standard-method) (doc-type (eql 't)))
(setf (std-method-documentation x) new-value))
(:method (new-value (x package) (doc-type (eql 't)))
(let ((doc (sys::package-documentation x)))
(if (consp doc)
(setf (first doc) new-value)
(setf (sys::package-documentation x) new-value))))
(:method (new-value (x standard-class) (doc-type (eql 't)))
(setf (class-documentation x) new-value))
(:method (new-value (x standard-class) (doc-type (eql 'type)))
(setf (class-documentation x) new-value))
(:method (new-value (x structure-class) (doc-type (eql 't)))
(setf (class-documentation x) new-value))
(:method (new-value (x structure-class) (doc-type (eql 'type)))
(setf (class-documentation x) new-value))
;;; The following are CLISP extensions.
(:method (new-value (x standard-object) (doc-type (eql 't)))
(sys::%set-documentation (class-of x) 'type new-value))
(:method (new-value (x standard-object) (doc-type (eql 'type)))
(sys::%set-documentation (class-of x) 'type new-value))
(:method (new-value (x structure-object) (doc-type (eql 't)))
(sys::%set-documentation (class-of x) 'type new-value))
(:method (new-value (x structure-object) (doc-type (eql 'type)))
(sys::%set-documentation (class-of x) 'type new-value))
(:method (new-value (x defined-class) (doc-type (eql 't)))
(setf (class-documentation x) new-value))
(:method (new-value (x defined-class) (doc-type (eql 'type)))
(setf (class-documentation x) new-value))
(:method (new-value (x slot-definition) (doc-type (eql 't)))
(setf (slot-definition-documentation x) new-value)))
| 7,952 | Common Lisp | .lisp | 159 | 44.943396 | 93 | 0.647791 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 649627898f42726c0f24d1c16d6a5e3a9817ebc6bf045e1d3ab5000bb13fed51 | 11,344 | [
-1
] |
11,345 | clos-genfun5.lisp | ufasoft_lisp/clisp/clos-genfun5.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Generic Functions
;;;; Part n-1: Generic functions specified in the MOP.
;;;; Bruno Haible 2004-06-13
(in-package "CLOS")
;; Make creation of <standard-generic-function> instances customizable.
(setf (fdefinition 'make-instance-<standard-generic-function>) #'make-instance)
;; Make creation of generic-function instances customizable.
(setf (fdefinition 'allocate-generic-function-instance) #'allocate-instance) ; ABI
(setf (fdefinition 'make-generic-function-instance) #'make-instance) ; ABI
;;; ===========================================================================
;;; Generic function definition customization
;; MOP p. 50
(defgeneric ensure-generic-function-using-class (gf funname
&key generic-function-class
lambda-list
argument-precedence-order
method-class
method-combination
documentation
declarations
declare
environment
&allow-other-keys)
(:method ((gf generic-function) funname &rest args)
(apply #'ensure-generic-function-using-class-<t> gf funname args))
(:method ((gf null) funname &rest args)
(apply #'ensure-generic-function-using-class-<t> gf funname args)))
| 1,678 | Common Lisp | .lisp | 28 | 39.321429 | 82 | 0.492392 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 734252e7221730a9188fba9d009d8b5c95ea23c840b6f7f3a30a30b75971da5c | 11,345 | [
-1
] |
11,346 | backquote.lisp | ufasoft_lisp/clisp/backquote.lisp | ;;; Backquote Implementation for CLISP
;;; Parts of this file
;;; Copyright 2003 Kaz Kylheku <[email protected]>
;;; Dedicated to Pei-Yin Lin
;;;
;;; LIBERAL FREEWARE LICENSE: This Lisp source code document may be used
;;; by anyone for any purpose, and freely redistributed alone or in
;;; combination with other software, provided that the license is not
;;; violated. The only possible way to violate the license is to
;;; redistribute this code in source form, with the copyright notice or
;;; license removed or altered. This license applies to this document
;;; only, not any other software that it is combined with.
;;; Parts of this file
;;; Copyright (C) 1988, 1989, 1992-2004 Michael Stoll, Bruno Haible
;;; Copyright (C) 2002-2003, 2005 Sam Steingold
;;; This is Free Software, covered by the GNU GPL.
(in-package "SYSTEM")
;;; ============================== Reader Macro ==============================
;;; At this level, we do only parsing, not simplification, so that things
;;; like `,A print as they were input. Parsing returns
;;; the following for
;;; (BACKQUOTE x) `x
;;; (UNQUOTE x) ,x
;;; (SPLICE x) ,@x
;;; (NSPLICE x) ,.x
;;; *unquote-occurred* flips to T when a sub-reader encounters the unquote
;;; syntax. This variable is the basis for a trick by which we diagnose uses of
;;; the unquote syntax inside forms which are not vectors or lists, such as:
;;; #`#s(foo-structure :bar #,z) without an cooperation from the readers of
;;; these forms. In some cases, however, such unquote syntax will cause the
;;; reader of the subform to raise an error before we catch it.
(proclaim '(special *unquote-occurred*))
;;; *backquote-level* measures the level of backquote nesting that the reader
;;; is entangled in. It increases by one when reading the backquoted object,
;;; and decreases by one over reading an unquoted form.
(proclaim '(special *backquote-level*))
;;; *reading-array* is normally unbound. When the reader is running, it
;;; is dynamically bound to NIL, and when a #A array is being read,
;;; it is bound to T. This lets the comma-reader signal an error when
;;; unquotes occur in an array.
(proclaim '(special *reading-array*))
;;; *reading-struct* is analogous to *reading-array*, but for structs.
(proclaim '(special *reading-struct*))
;;; Handle the ` read syntax.
(defun backquote-reader (stream char)
(declare (ignore char))
(let* ((*unquote-occurred* nil)
(*reading-array* nil)
(*reading-struct* nil)
(*backquote-level* (1+ (or *backquote-level* 0)))
(object (read stream t nil t)))
(unless (or (and (vectorp object) (eq (array-element-type object) 'T))
(listp object))
(when *unquote-occurred*
(error-of-type 'reader-error
:stream stream
(TEXT "~S: unquotes may occur only in (...) or #(...) forms")
'read)))
(when (consp object)
(let ((head (first object)))
(when (or (eq head 'SPLICE) (eq head 'NSPLICE))
(bq-non-list-splice-error head stream)))
(when (bq-member 'SPLICE object)
(bq-dotted-splice-error 'SPLICE stream))
(when (bq-member 'NSPLICE object)
(bq-dotted-splice-error 'NSPLICE stream)))
(list 'BACKQUOTE object)))
;;; Handle the read syntax ,
(defun comma-reader (stream char)
(declare (ignore char))
(when (null *backquote-level*)
(error-of-type 'reader-error
:stream stream
(TEXT "~S: comma is illegal outside of backquote")
'read))
(when (zerop *backquote-level*)
(error-of-type 'reader-error
:stream stream
(TEXT "~S: more commas out than backquotes in, is illegal")
'read))
(when *reading-struct*
(error-of-type 'reader-error
:stream stream
(TEXT "~S: unquotes may not occur in structures")
'read))
(when *reading-array*
(error-of-type 'reader-error
:stream stream
(TEXT "~S: unquotes may not occur in arrays")
'read))
(setq *unquote-occurred* t)
(let ((*backquote-level* (1- *backquote-level*))
(next (peek-char nil stream)))
(cond ((char= next #\@)
(read-char stream)
(list 'SPLICE (read stream t nil t)))
((char= next #\.)
(read-char stream)
(list 'NSPLICE (read stream t nil t)))
(t (list 'UNQUOTE (read stream t nil t))))))
;;; Like MEMBER but handles improper lists without error.
(defun bq-member (elem list &key (test #'eql))
(do ((list list (rest list)))
((atom list) nil)
(when (funcall test (first list) elem)
(return list))))
;;; ----------------------------- Error Messages -----------------------------
;;; Used by the Reader Macro and the Macroexpander.
;;; Signal error for `,.form or `,@form.
;;; It's undefined behaviour; we signal an error for it.
;;; If stream is non-NIL, then add the prefix "READ: ", to flag the error as
;;; coming from the reader.
(defun bq-non-list-splice-error (sym &optional stream)
(let ((errmsg
(if (eq sym 'SPLICE)
(TEXT "the syntax `,@form is invalid")
(TEXT "the syntax `,.form is invalid"))))
(if stream
(error-of-type 'reader-error
:stream stream
(TEXT "READ: ~@?")
errmsg)
(error-of-type 'error
"~@?"
errmsg))))
;;; Signal error for `(... . ,@form) or `(... . ,.form).
;;; It's undefined behaviour; we signal an error for it.
(defun bq-dotted-splice-error (sym &optional stream)
(let ((errmsg
(if (eq sym 'SPLICE)
(TEXT "the syntax `( ... . ,@form) is invalid")
(TEXT "the syntax `( ... . ,.form) is invalid"))))
(if stream
(error-of-type 'reader-error
:stream stream
(TEXT "READ: ~@?")
errmsg)
(error-of-type 'error
"~@?"
errmsg))))
;;; ============================== Macroexpander ==============================
;;; The macroexpander consists of three parts:
;;; - The backquote macro: the entry point, taking the form as provided by
;;; the reader, and producing an evaluatable form.
;;; - The recursive expansion engine. Its behaviour is dictated by the
;;; HyperSpec's general description of backquote.
;;; - The expansion optimizer. Its purpose is to use the Lisp's list/vector
;;; construction primitives as efficiently as possible. It can run in a
;;; non-optimized mode, where lists are always constructed through LIST and
;;; APPEND; or optimization can be performed that reduce run-time consing or
;;; otherwise simplify the macroexpansion.
;;; ------------------------------ Entry-points ------------------------------
;; The BACKQUOTE macro just calls the backquote expander on its argument.
(sys::%putd 'BACKQUOTE
(sys::make-macro
(function BACKQUOTE
(lambda (form env)
(declare (ignore env))
(bq-expand (second form))))
'(form)))
;;; ----------------------- Recursive Expansion Engine -----------------------
;;; Top level cases
;;;
;;; `() --> ()
;;; `cons --> result of (bq-expand-cons cons)
;;; `#( ... ) --> result of (bq-expand-vector #( ... ))
;;; other --> 'other
(defun bq-expand (form)
;; we don't have TYPECASE at this stage
(cond
((null form) nil)
((consp form)
;; Handle base cases as described by HyperSpec, plus nested backquote:
;;
;; `,form --> form
;; `,@form --> error
;; ``form --> `form-expanded
;; list-form --> (append f1 f2 f3 ...) where (f1 f2 f3 ...)
;; is the output of (bq-expand-list list-form).
(case (first form)
((UNQUOTE)
(second form))
((SPLICE NSPLICE)
(bq-non-list-splice-error (second form)))
((BACKQUOTE)
(list 'BACKQUOTE (bq-expand (second form))))
(otherwise
(let ((expansion (bq-expand-list form)))
(bq-append-multiple expansion)))))
((and (vectorp form) (eq (array-element-type form) 'T))
;; Handle vector expansion, along the lines suggested by HyperSpec.
(let ((expansion (bq-expand-list (map 'list #'identity form))))
(bq-optimize-for-vector expansion (bq-append-multiple expansion))))
(t (list 'quote form))))
;;; Handle the transformation of `(x1 x2 x3 ...) as described by HyperSpec
;;; to produce a list of forms that can be combined into an APPEND form.
;;; There is one deviation from the HyperSpec: namely, in the case
;;; `(x1 x2 ... xn . atom) the atom is translated to (BACKQUOTE atom)
;;; rather than (QUOTE atom). This allows for the atom to be a vector
;;; with embedded unquotes, an apparently common extension.
(defun bq-expand-list (forms)
(let ((expanded '())) ; reversed list of expanded forms to be APPENDed
(do ()
((null forms))
(let ((expanded-car (bq-transform (first forms))))
(setq expanded (cons expanded-car expanded)))
(let ((tail (rest forms)))
(cond ((null tail) (return-from nil))
((consp tail)
(case (first tail)
;; well-defined dotted unquote `( ... . ,form)
((UNQUOTE)
(setq expanded (cons (second tail) expanded))
(return-from nil))
;; undefined dotted splice: `( ... . ,@form)
((SPLICE NSPLICE)
(bq-dotted-splice-error (first tail)))
(otherwise
(setq forms tail))))
(t (setq expanded (cons (list 'BACKQUOTE tail) expanded))
(return-from nil)))))
(nreverse expanded)))
;;; Handle the transformation of [x1] [x2] ... forms as described
;;; in the HyperSpec. In addition, nested backquotes are handled here.
(defun bq-transform (form)
(if (consp form)
(case (first form)
((UNQUOTE) (bq-list (second form)))
((SPLICE) (second form))
;; (BQ-NCONCABLE FORM) serves as a parse tree annotation which
;; tells the optimizer that FORM may be destructively manipulated.
((NSPLICE) (list 'BQ-NCONCABLE (second form)))
((BACKQUOTE) (bq-list (list 'BACKQUOTE (bq-expand (second form)))))
(otherwise (bq-list (bq-expand form))))
(bq-list (bq-expand form))))
;;; --------------------------- Expansion Optimizer ---------------------------
;;; Naive expansion produces inefficient construction forms, e.g.
;;; `(,(foo) ,(bar)) => (APPEND (LIST (foo)) (LIST (bar)))
;;; instead of (LIST (foo) (bar))
;;; Backquote expansion optimizers are enabled by default, but can be turned
;;; off for debugging.
(proclaim '(special *backquote-optimize-cons*))
(setq *backquote-optimize-cons* t)
(proclaim '(special *backquote-optimize-list*))
(setq *backquote-optimize-list* t)
(proclaim '(special *backquote-optimize-append*))
(setq *backquote-optimize-append* t)
(proclaim '(special *backquote-optimize-nconc*))
(setq *backquote-optimize-nconc* t)
(proclaim '(special *backquote-optimize-vector*))
(setq *backquote-optimize-vector* t)
;;; This simplifies CONS, LIST, APPEND, NCONC calls that are emitted by the
;;; backquote expander. We are *not* allowed to collapse CONS or LIST calls
;;; given by the user.
;;; E.g. `((,a ,b 3) (,a ,@(list b 3)))
;;; can be simplified to (LIST (LIST* A B '(3)) (LIST A B 3))
;;; but not to (LIST (LIST* A B '(3)) (LIST* A B '(3))).
;;; The set of simplifications has been chosen in a minimal way, to satisfy
;;; the testsuite. Don't add additional simplifications if the testsuite
;;; doesn't show a need for it - otherwise such simplifications would just
;;; be no-ops that slow down the macroexpander.
;;; Some optimizations have to be inhibited on splicing forms because while
;;; primitives LIST and APPEND handle splicing automatically correctly,
;;; primitives like CONS and QUOTE don't.
;;; Tests whether the given form may yield multiple list elements.
;;; Not only ,@x and ,.x are splicing, but also ,,@x !
(defun bq-splicing-p (form)
(and (consp form)
(case (first form)
((UNQUOTE) (bq-splicing-p (second form)))
((SPLICE NSPLICE) t)
(t nil))))
;;; To convert a splicing form to a non-splicing one.
(defun bq-non-splicing (form)
(if (bq-splicing-p form) (list 'APPEND form) form))
;;; BQ-CONS returns a form that returns a CONS of the results of the two
;;; given forms. Assumes that form2 is not splicing.
(defun bq-cons (form1 form2)
(let ((operator (if (bq-splicing-p form1) 'LIST* 'CONS)))
(if *backquote-optimize-cons*
; Simplify `(CONS ,form1 ,form2) or `(LIST* ,form1... ,form2):
(cond #|
((and (not (bq-splicing-p form1)) (constantp form1)
(constantp form2))
; Both parts constant -> combine immediately.
(list 'QUOTE (cons (eval form1) (eval form2))))
((null form2)
; (CONS form1 NIL) -> (LIST form1)
; (LIST* form1... NIL) -> (LIST form1...)
(list 'LIST form1))
|#
((atom form2)
; Cannot simplify.
(list operator form1 form2))
((eq (first form2) 'LIST)
; (CONS form1 (LIST . more)) -> (LIST form1 . more)
; (LIST* form1... (LIST . more)) -> (LIST form1... . more)
; Test case: `(,(f1) ,(f2))
(list* 'LIST form1 (rest form2)))
#|
((or (eq (first form2) 'LIST*) (eq (first form2) 'CONS))
; (CONS form1 (LIST* . more)) -> (LIST* form1 . more)
; (CONS form1 (CONS . more)) -> (LIST* form1 . more)
; (LIST* form1... (LIST* . more)) -> (LIST* form1... . more)
; (LIST* form1... (CONS . more)) -> (LIST* form1... . more)
(list 'LIST* form1 (rest form2)))
|#
((and (consp form2) (eq (first form2) 'QUOTE)
(consp (cdr form2)) (null (cddr form2))
(not (bq-splicing-p (second form2)))
(consp form1) (eq (first form1) 'QUOTE)
(consp (cdr form1)) (null (cddr form1))
(not (bq-splicing-p (second form1))))
; Test case: `(c1 c2)
(list 'QUOTE (cons (second form1) (second form2))))
(t (list operator form1 form2)))
(list operator form1 form2))))
;;; BQ-LIST returns a form that returns a list of the result of the given form.
(defun bq-list (form1)
; Equivalent to (bq-cons form1 'NIL).
(if *backquote-optimize-list*
(cond ((and (not (bq-splicing-p form1)) (constantp form1))
; Test case: `(c1)
(list 'QUOTE (list (eval form1))))
(t (list 'LIST form1)))
(list 'LIST form1)))
;;; BQ-APPEND returns a form that returns the nondestructive concatenation of
;;; the results of the given forms.
(defun bq-append (form1 form2)
(if *backquote-optimize-append*
; Simplify `(APPEND ,form1 ,form2):
(cond ((null form1)
; (APPEND NIL form2) -> (APPEND form2) -> form2
; Test case: `(,@() ,@(f1))
form2)
((null form2)
; (APPEND form1 NIL) -> (APPEND form1) -> form1
; Test case: `(,@(f1) ,@())
form1)
((and (consp form1) (eq (first form1) 'LIST)
(null (cdr (last form1))))
; (APPEND (LIST x1 ... xn) form2) -> (LIST* x1 ... xn form2),
; or (CONS x1 form2) if n = 1, or form2 if n = 0.
; Test cases: `(,(f1) c2) and `(,(f1) ,(f2))
(setq form2 (bq-non-splicing form2))
(cond ((null (cdr form1)) form2)
((null (cddr form1)) (bq-cons (second form1) form2))
(t (cons 'LIST* (append (rest form1) (list form2))))))
((and (consp form1) (eq (first form1) 'QUOTE)
(consp (cdr form1)) (null (cddr form1))
(not (bq-splicing-p (second form1))) ; too hairy
; Cannot append to l if l is not a proper list.
(listp (second form1)) (null (cdr (last (second form1))))
; Cannot append to l if l starts with UNQUOTE, because
; UNQUOTE expects exactly one argument.
(not (eq (first (second form1)) 'UNQUOTE)))
; (APPEND (QUOTE l) form2) -> (LIST* ... form2)
; Test cases: `(c1 c2) and `(c1 ,(f2))
(setq form2 (bq-non-splicing form2))
(let ((result form2))
(do ((l (reverse (second form1)) (cdr l)))
((endp l))
(setq result (bq-cons (list 'QUOTE (car l)) result)))
result))
((and (consp form2) (eq (first form2) 'APPEND))
; (APPEND form1 (APPEND . more)) -> (APPEND form1 . more)
; Test case: `(,@(f1) ,@(f2) ,@(f3))
(list* 'APPEND form1 (rest form2)))
(t (list 'APPEND form1 form2)))
(list 'APPEND form1 form2)))
;;; BQ-NCONC returns a form that returns the destructive concatenation of the
;;; results of the given forms.
(defun bq-nconc (form1 form2)
(if *backquote-optimize-nconc*
; Simplify `(NCONC ,form1 ,form2):
(cond ((null form1)
; (NCONC NIL form2) -> (NCONC form2) -> form2
; Test case: `(,.() ,.(f1))
form2)
((null form2)
; (NCONC form1 NIL) -> (NCONC form1) -> form1
; Test case: `(,.(f1) ,.())
form1)
((and (consp form2) (eq (first form2) 'NCONC))
; (NCONC form1 (NCONC . more)) -> (NCONC form1 . more)
; Test case: `(,.(f1) ,.(f2) ,@(f3))
(list* 'NCONC form1 (rest form2)))
(t (list 'NCONC form1 form2)))
(list 'NCONC form1 form2)))
;;; BQ-APPEND-MULTIPLE returns a form that returns the concatenation of the
;;; results of the given forms. It uses destructive concatenation for forms
;;; that start with BQ-NCONCABLE.
(defun bq-append-multiple (forms)
(setq forms (reverse forms))
(if (endp forms)
'NIL
(let (result nconcable)
(let ((form (car forms)))
(if (and (consp form) (eq (first form) 'BQ-NCONCABLE))
(setq result (second form) nconcable t)
(setq result form nconcable nil)))
(setq forms (cdr forms))
(do ()
((endp forms))
(let ((form (car forms)))
(setq result
(if (and (consp form) (eq (first form) 'BQ-NCONCABLE))
; Must wrap the already constructed result in an APPEND to
; prevent it from splicing, since destructive modifications
; are allowed on form, but not on result.
(bq-nconc (second form)
(if (and (bq-splicing-p result) (not nconcable))
(list 'APPEND result)
result))
(bq-append form
(if (and (bq-splicing-p result) nconcable)
(list 'NCONC result)
result))))
(setq nconcable nil))
(setq forms (cdr forms)))
;; The caller cannot handle a naked (SPLICE ...) or (NSPLICE ...) form,
;; so wrap it in an APPEND.
(bq-non-splicing result))))
;;; BQ-OPTIMIZE-FOR-VECTOR generates a better translation for a backquoted
;;; vector. The vector has been already converted to a list, which
;;; was subject to unoptimized backquote expansion. That resulting
;;; list of append arguments is what is passed to this function.
;;; The expansion is optimized and then converted to a vector
;;; form according to these rules:
;;;
;;; '(...) -> #(...)
;;; (list ...) -> (vector ...)
;;; (append ...) -> (multiple-value-call #'vector ...)
;;;
;;; The (append ...) case is based on the original unoptimized
;;; append args. The arguments are each treated as follows:
;;;
;;; (list ...) -> (values ...)
;;; (splice ...) -> (values-list (append ...))
;;; (nsplice ...) -> (values-list (nconc ...))
;;; other -> (values-list other)
(defun bq-optimize-for-vector (unoptimized optimized)
(if *backquote-optimize-vector*
(cond ((or (eq optimized 'NIL)
(and (consp optimized) (eq (first optimized) 'QUOTE)
(consp (cdr optimized)) (null (cddr optimized))
(not (bq-splicing-p (second optimized)))))
; Create the vector at macroexpansion time.
(apply #'vector (eval optimized)))
((not (consp optimized))
(list 'APPLY '#'VECTOR optimized))
((eq (first optimized) 'LIST)
; Test cases: `#(,(f1) ,(f2)) and ``#(,,@(f1) ,,@(f2))
(cons 'VECTOR (rest optimized)))
(t (list* 'MULTIPLE-VALUE-CALL '#'VECTOR
(mapcan #'(lambda (form &aux (nconcable nil))
(when (and (consp form) (eq (first form) 'BQ-NCONCABLE))
(setq form (second form) nconcable t))
(cond ((atom form)
(list (list 'VALUES-LIST form)))
((memq (first form) '(SPLICE NSPLICE))
; Test case: ``#(,.,.(f1) ,.,@(f2) ,@,.(f3) ,@,@(f4))
(list
(list 'VALUES-LIST
(list (if nconcable 'NCONC 'APPEND)
form))))
((eq (first form) 'LIST)
; Test case: `#(,(f1) ,@(f2))
(mapcar #'(lambda (f)
(if (bq-splicing-p f)
(list 'VALUES-LIST (list 'LIST f))
(list 'VALUES f)))
(rest form)))
((and (eq (first form) 'QUOTE)
(consp (cdr form)) (null (cddr form))
(not (bq-splicing-p (second form))))
; Test case: `#(c1 ,@(f2))
(mapcar #'(lambda (x) (list 'QUOTE x))
(second form)))
(t (list (list 'VALUES-LIST form)))))
unoptimized))))
(list 'APPLY '#'VECTOR optimized)))
;;; =========================== Other Entry-points ===========================
;;; Interfaces used by other modules within CLISP, and possibly
;;; by CLISP applications.
;;;
;;; Note: to dynamically add a variable number of unquotes to a nested
;;; backquote, consider using the ,,@ syntax:
;;;
;;; (let ((unquote-these-forms '((list 1 2) (list 3 4)))
;;; `(outer `(inner ,,@unquote-these-forms))
;;;
;;; rather than ADD-BACKQUOTE and ADD-UNQUOTE:
;;;
;;; (let ((unquote-these-forms '((list 1 2) (list 3 4))))
;;; `(outer ,(system::add-backquote
;;; `(inner ,@(mapcar #'system::add-unquote
;;; unquote-these-forms)))))
;;;
;;; The effect is like `(outer ,(inner ,(list 1 2) ,(list 3 4)))
;;;
;;; If you want the effect `(outer ,(inner ,@(list 1 2) ,@(list 3 4)))
;;; then substitute `(outer `(inner ,@,@unquote-these-forms))
;;;
;;; If you think you need ADD-BACKQUOTE and ADD-UNQUOTE, or even
;;; the nonexistent ADD-SPLICE, it's likely that your requirements
;;; may be satisfied by the ,,@ and ,@,@ syntax. The distributive
;;; rule is simple: the right ,@ splices the forms into the list, and the
;;; left , or ,@ distributes itself over those forms before the next
;;; expansion round.
;;;
;;; There are exceptions, like the more complicated situation in CLISP's
;;; giant defstruct macro, which prepares a list of nested lists each
;;; containing a buried unquote forms, and then later encloses it in a
;;; backquote.
(defun add-backquote (skel)
(list 'BACKQUOTE skel))
(defun add-unquote (skel)
(list 'UNQUOTE skel))
(defun backquote-cons (car cdr)
(bq-cons car cdr))
(defun backquote-append (left right)
(bq-append left right))
| 24,280 | Common Lisp | .lisp | 523 | 37.956023 | 92 | 0.563085 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 5b84792ae22c475cc5086a6c29b07fa2b8d0a271594175595b3e1f5ae1490803 | 11,346 | [
-1
] |
11,347 | clos-genfun3.lisp | ufasoft_lisp/clisp/clos-genfun3.lisp | ;;;; Common Lisp Object System for CLISP: Generic Functions
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004, 2007 - 2010
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
;; ============================= Runtime support =============================
;; Runtime support for CALL-NEXT-METHOD.
(defun %call-next-method (backpointer next-methods original-args new-args) ; ABI
(let* ((method (car backpointer))
(gf (method-generic-function method)))
(when (gf-never-called-p gf)
;; Oops, gf still contains a prototype dispatch which only calls
;; initial-funcall-gf. This can really happen, because make-instance
;; can call initial-make-instance, which calls initialize-instance's
;; effective method without going through initialize-instance itself.
;; Similarly for initial-initialize-instance and
;; initial-reinitialize-instance, which call shared-initialize's
;; effective method without going through shared-initialize's dispatch.
;; Similarly for slot-value, which call slot-value-using-class's
;; effective method without going through slot-value-using-class.
;; Remedy by calling the prototype dispatch once.
(apply (sys::generic-function-effective-method-function gf) original-args))
;; Now we can assume that the real dispatch is installed.
(let* ((emf (sys::generic-function-effective-method-function gf))
(original-em (apply emf original-args))
(new-em (apply emf new-args)))
;; Protect against the case that emf is a prototype dispatch which only
;; calls initial-funcall-gf.
(when (or (eq original-em gf) (eq new-em gf))
(error-of-type 'error
(TEXT "~S in ~S: bug in determination of effective methods")
'call-next-method gf))
(if (eq original-em new-em)
(if next-methods
(apply next-methods new-args)
(apply #'%no-next-method backpointer new-args))
(error-of-type 'error
(TEXT "~S in ~S: the new arguments ~S have a different effective method than the old arguments ~S")
'call-next-method gf new-args original-args)))))
;; =================== Initialization and Reinitialization ===================
(defun make-generic-function (generic-function-class caller whole-form funname lambda-list argument-precedence-order method-combination method-combination-p method-class method-class-p declspecs declspecs-p documentation documentation-p user-defined-args ; ABI
&rest methods)
(when user-defined-args
;; Provide good error messages. The error message from
;; MAKE-INSTANCE later is unintelligible.
(let ((valid-keywords (class-valid-initialization-keywords generic-function-class)))
(unless (eq valid-keywords 'T)
(dolist (option user-defined-args)
(unless (member (first option) valid-keywords)
(error-of-type 'ext:source-program-error
:form whole-form
:detail option
(TEXT "~S ~S: invalid ~S option ~S")
caller funname 'defgeneric option))))))
(let ((gf (apply #'make-generic-function-instance generic-function-class
:name funname
:lambda-list lambda-list
:argument-precedence-order argument-precedence-order
(append
(if method-class-p (list :method-class method-class))
(if method-combination-p (list :method-combination method-combination))
(if declspecs-p (list :declarations declspecs))
(if documentation-p (list :documentation documentation))
(mapcan #'(lambda (option) (list (first option) (rest option)))
user-defined-args)
(unless method-class-p (list :method-class method-class))
(unless method-combination-p (list :method-combination method-combination))
(unless declspecs-p (list :declarations declspecs))
(unless documentation-p (list :documentation documentation))))))
(dolist (method methods) (add-method gf method))
gf))
;; When this is true, it is possible to replace a non-generic function with
;; a generic function through DEFGENERIC or ENSURE-GENERIC-FUNCTION.
(defparameter *allow-making-generic* nil)
(defun ensure-generic-function-using-class-<t> (gf funname &rest all-keys
&key (generic-function-class <standard-generic-function>)
lambda-list
argument-precedence-order
(method-class nil method-class-p)
method-combination
documentation
declarations
declare
environment
((methods methods) nil) ; from DEFGENERIC
&allow-other-keys)
(declare (ignore lambda-list argument-precedence-order method-combination
documentation declarations declare environment methods))
;; Argument checks.
(unless (function-name-p funname)
(error-of-type 'program-error
(TEXT "~S: the name of a function must be a symbol, not ~S")
'ensure-generic-function-using-class funname))
(unless (defined-class-p generic-function-class)
(if (symbolp generic-function-class)
(setq generic-function-class (find-class generic-function-class))
(error (TEXT "~S for generic-function ~S: ~S ~S is neither a class or a symbol")
'ensure-generic-function-using-class funname
':generic-function-class generic-function-class)))
(unless (subclassp generic-function-class <generic-function>)
(error (TEXT "~S for generic-function ~S: ~S ~S is not a subclass of ~S")
'ensure-generic-function-using-class funname
':generic-function-class generic-function-class 'GENERIC-FUNCTION))
;; Preparation of initialization arguments.
(setq all-keys (copy-list all-keys))
(remf all-keys ':generic-function-class)
(when method-class-p
(unless (defined-class-p method-class)
(if (symbolp method-class)
(setq method-class (find-class method-class))
(error (TEXT "~S for generic-function ~S: ~S ~S is neither a class or a symbol")
'ensure-generic-function-using-class funname
':method-class method-class)))
(setf (getf all-keys ':method-class) method-class))
(if gf
;; Redefinition of a generic function.
(progn
;; Take into account the new generic-function-class.
(unless (eq (class-of gf) generic-function-class)
;; MOP p. 51 says that an error should be signalled in this case,
;; but ANSI CL says that CHANGE-CLASS is used to modify the GF.
(change-class gf generic-function-class))
(warn-if-gf-already-called gf)
(apply #'reinitialize-instance gf all-keys)
gf)
;; First definition of a generic function.
(setf (fdefinition funname)
(apply #'make-generic-function-instance
generic-function-class
:name funname
all-keys))))
;; Preliminary.
(predefun ensure-generic-function-using-class (gf funname &rest args
&key generic-function-class
lambda-list
argument-precedence-order
method-class
method-combination
documentation
declarations
declare
environment
&allow-other-keys)
(declare (ignore generic-function-class lambda-list argument-precedence-order
method-class method-combination documentation declarations
declare environment))
(apply #'ensure-generic-function-using-class-<t> gf funname args))
;; MOP p. 49
(defun ensure-generic-function (funname &rest args
&key generic-function-class
lambda-list
argument-precedence-order
method-class
method-combination
documentation
declarations
declare
environment
&allow-other-keys)
(declare (ignore generic-function-class lambda-list argument-precedence-order
method-class method-combination documentation declarations
declare environment))
(unless (function-name-p funname)
(error-of-type 'program-error
(TEXT "~S: the name of a function must be a symbol, not ~S")
'ensure-generic-function funname))
(let ((result
(apply #'ensure-generic-function-using-class
(if (fboundp funname)
(let ((gf (fdefinition funname)))
(if (typep-class gf <generic-function>)
gf
(if (not *allow-making-generic*)
(error-of-type 'program-error
(TEXT "~S: ~S does not name a generic function")
'ensure-generic-function funname)
nil)))
nil)
funname
args)))
; A check, to verify that user-defined methods on
; ensure-generic-function-using-class work as they should.
(unless (typep-class result <generic-function>)
(error (TEXT "Wrong ~S result for ~S: not a generic-function: ~S")
'ensure-generic-function-using-class funname result))
result))
#||
;; For GENERIC-FLET, GENERIC-LABELS
;; like make-generic-function, only that the dispatch-code is
;; installed immediately.
(defun make-generic-function-now (generic-function-class caller whole-form funname lambda-list argument-precedence-order method-combination method-class method-class-p declspecs declspecs-p documentation documentation-p user-defined-args
&rest methods)
(let ((gf (apply #'make-generic-function generic-function-class caller whole-form funname lambda-list argument-precedence-order method-combination method-class method-class-p declspecs declspecs-p documentation documentation-p user-defined-args methods)))
(install-dispatch gf)
gf))
||#
;; ================================ DEFMETHOD ================================
(defmacro defmethod (&whole whole-form
funname &rest method-description)
(setq funname (sys::check-function-name funname 'defmethod))
(multiple-value-bind (fast-function-factory-lambda method-initargs-forms signature)
(analyze-method-description 'defmethod whole-form funname method-description)
`(LET ()
(SYS::EVAL-WHEN-COMPILE
(SYS::C-DEFUN ',funname ,signature nil 'DEFMETHOD))
(WHEN (GET ',(SYS::GET-FUNNAME-SYMBOL funname) 'SYS::TRACED-DEFINITION)
(SYS::UNTRACE1 ',funname))
(DO-DEFMETHOD ',funname (FUNCTION ,fast-function-factory-lambda)
(LIST ,@method-initargs-forms)))))
;; Installs a method. Can be called in two ways:
;; (do-defmethod funname method)
;; (do-defmethod funname fast-function-factory method-initargs)
(defun do-defmethod (funname arg1 &optional (arg2 nil must-build-method)) ; ABI
(let* ((gf
(if (fboundp funname)
(let ((gf (fdefinition funname)))
(if (typep-class gf <generic-function>)
gf
(error-of-type 'error
(TEXT "~S: ~S does not name a generic function")
'defmethod funname)))
(setf (fdefinition funname)
;; Create a GF compatible with the given method signature.
(multiple-value-bind (m-lambdalist m-signature)
(if must-build-method
(values (getf arg2 ':lambda-list)
(getf arg2 'signature))
(values (method-lambda-list arg1)
(method-signature arg1)))
(let ((gf-lambdalist
(gf-lambdalist-from-first-method m-lambdalist m-signature)))
(make-generic-function-instance <standard-generic-function>
:name funname
:lambda-list gf-lambdalist
:method-class <standard-method>))))))
(method
(if must-build-method
(let ((method-class (safe-gf-default-method-class gf))
(backpointer (list nil)))
(apply #'make-method-instance method-class
'backpointer backpointer
(nconc (method-function-initargs method-class
(funcall arg1 backpointer))
arg2)))
arg1)))
(add-method gf method)
method))
;;; (DECLAIM-METHOD function-name qualifier* spec-lambda-list)
;; does the compile-time side effects of
;; (DEFMETHOD function-name qualifier* spec-lambda-list ...)
(defmacro declaim-method (&whole whole-form
funname &rest method-description)
(setq funname (sys::check-function-name funname 'declaim-method))
(multiple-value-bind (fast-function-factory-lambda method-initargs-forms signature)
(analyze-method-description 'defmethod whole-form funname method-description)
(declare (ignore fast-function-factory-lambda method-initargs-forms))
`(SYS::EVAL-WHEN-COMPILE
(SYS::C-DEFUN ',funname ,signature nil 'DEFMETHOD))))
;; ====================== DEFGENERIC and similar Macros ======================
;;; For DEFGENERIC, GENERIC-FUNCTION, GENERIC-FLET, GENERIC-LABELS,
;;; WITH-ADDED-METHODS
;; caller: symbol
;; whole-form: whole source form
;; funname: function name, symbol or (SETF symbol)
;; lambdalist: lambdalist of the generic function
;; options: (option*)
;; Returns 8 values:
;; 1. generic-function-class-form,
;; 2. signature,
;; 3. argument-precedence-order,
;; 4. method-combination-lambda, to be applied to the generic-function-class,
;; 5. method-combination-p,
;; 6. method-class-form,
;; 7. method-class-p,
;; 8. declspecs,
;; 9. declspecs-p,
;; 10. docstring,
;; 11. docstring-p,
;; 12. user-defined-args,
;; 13. method-forms.
(defun analyze-defgeneric (caller whole-form funname lambdalist options)
(setq funname (sys::check-function-name funname caller))
;; Parse the lambdalist:
(analyze-defgeneric-lambdalist caller whole-form funname lambdalist)
;; Process the options:
(let ((generic-function-classes nil)
(method-forms '())
(method-combinations nil)
(method-classes nil)
(argorders nil)
(declares nil)
(docstrings nil)
(user-defined-args))
(dolist (option options)
(unless (listp option)
(error-of-type 'ext:source-program-error
:form whole-form
:detail option
(TEXT "~S ~S: not a ~S option: ~S")
caller funname 'defgeneric option))
(case (first option)
(DECLARE
;; The DEFGENERIC description in ANSI CL is inconsistent. According to
;; the BNF syntax, multiple DECLARE options cannot be passed in a
;; single DEFGENERIC forms. However, it also says explicitly "The
;; declare option may be specified more than once..."
#|
(when declares
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: ~S may only be specified once.")
caller funname 'declare))
|#
(check-gf-declspecs (rest option) 'declare
#'(lambda (errorstring &rest arguments)
(error "~S ~S: ~A" caller funname
(apply #'format nil errorstring arguments))))
(setq declares
(if declares
`(DECLARE ,@(append (rest declares) (rest option)))
option)))
(:ARGUMENT-PRECEDENCE-ORDER
(when argorders
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: ~S may only be specified once.")
caller funname ':argument-precedence-order))
(setq argorders option))
(:DOCUMENTATION
(unless (and (eql (length option) 2) (stringp (second option)))
(error-of-type 'ext:source-program-error
:form whole-form
:detail option
(TEXT "~S ~S: A string must be specified after ~S : ~S")
caller funname ':documentation option))
(when docstrings
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: Only one ~S string is allowed.")
caller funname ':documentation))
(setq docstrings (rest option)))
(:METHOD-COMBINATION
(when method-combinations
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: ~S may only be specified once.")
caller funname ':method-combination))
;; The syntax for this option is
;; (method-combination-name method-combination-argument*)
;; CLHS writes "method-combination" here instead of
;; "method-combination-name" but this is most probably a typo.
;; To be liberal, we also allow a method-combination instead of a
;; method-combination-name.
(unless (>= (length option) 2)
(error-of-type 'ext:source-program-error
:form whole-form
:detail option
(TEXT "~S ~S: A method combination type name must be specified after ~S : ~S")
caller funname ':method-combination option))
(let ((method-combination-name (second option)))
(unless (or (symbolp method-combination-name)
(typep-class method-combination-name <method-combination>))
(error-of-type 'ext:source-program-error
:form whole-form
:detail method-combination-name
(TEXT "~S ~S: Invalid method combination specification: ~S")
caller funname option))
(setq method-combinations (rest option))))
(:GENERIC-FUNCTION-CLASS
(unless (and (eql (length option) 2) (symbolp (second option)))
(error-of-type 'ext:source-program-error
:form whole-form
:detail option
(TEXT "~S ~S: A class name must be specified after ~S : ~S")
caller funname ':generic-function-class option))
(when generic-function-classes
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: Only one ~S option is allowed.")
caller funname ':generic-function-class))
(setq generic-function-classes (rest option)))
(:METHOD-CLASS
(unless (and (eql (length option) 2) (symbolp (second option)))
(error-of-type 'ext:source-program-error
:form whole-form
:detail option
(TEXT "~S ~S: A class name must be specified after ~S : ~S")
caller funname ':method-class option))
(when method-classes
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: Only one ~S option is allowed.")
caller funname ':method-class))
(setq method-classes (rest option)))
(:METHOD
(multiple-value-bind (fast-function-factory-lambda method-initargs-forms)
(analyze-method-description caller whole-form funname (rest option))
(push (cons fast-function-factory-lambda method-initargs-forms)
method-forms)))
((:LAMBDA-LIST :DECLARATIONS)
(error-of-type 'ext:source-program-error
:form whole-form
:detail option
(TEXT "~S ~S: invalid ~S option ~S")
caller funname 'defgeneric option))
(t
(let ((optionkey (first option)))
(if (symbolp optionkey)
(if (assoc optionkey user-defined-args)
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: Only one ~S option is allowed.")
caller funname optionkey)
(push option user-defined-args))
(error-of-type 'ext:source-program-error
:form whole-form
:detail option
(TEXT "~S ~S: invalid syntax in ~S option: ~S")
caller funname 'defgeneric option))))))
;; Check :argument-precedence-order :
(multiple-value-bind (signature argument-precedence-order argorder)
(check-gf-lambdalist+argorder lambdalist (rest argorders) argorders
#'(lambda (detail errorstring &rest arguments)
(error-of-type 'ext:source-program-error
:form whole-form
:detail detail
"~S ~S: ~A" caller funname
(apply #'format nil errorstring arguments))))
(declare (ignore argorder))
(let ((method-combinations-defaulted
;; Default :method-combination is STANDARD:
(or method-combinations '(STANDARD)))
(generic-function-class-form
(if generic-function-classes
`(FIND-CLASS ',(first generic-function-classes))
'<STANDARD-GENERIC-FUNCTION>))
(method-class-form
(if method-classes
`(FIND-CLASS ',(first method-classes))
'<STANDARD-METHOD>)))
(values generic-function-class-form
signature
argument-precedence-order
(let ((method-combination-name (car method-combinations-defaulted))
(options (cdr method-combinations-defaulted)))
`(LAMBDA (GF-CLASS)
,(if (symbolp method-combination-name)
;; We need a preliminary generic function because the
;; method combination must be passed to
;; ensure-generic-function, and the GF has not yet been
;; created and initialized at this moment.
`(FIND-METHOD-COMBINATION
(MAKE-GENERIC-FUNCTION-PROTOTYPE GF-CLASS :NAME ',funname)
',method-combination-name ',options)
`(METHOD-COMBINATION-WITH-OPTIONS ',funname ',method-combination-name ',options))))
(not (null method-combinations))
method-class-form
(not (null method-classes))
;; list of declspecs
(cdr declares)
(not (null declares))
;; docstring or nil
(car docstrings)
(not (null docstrings))
(nreverse user-defined-args)
;; list of the method-forms
(mapcar #'(lambda (method-cons)
(let ((fast-function-factory-lambda (car method-cons))
(method-initargs-forms (cdr method-cons)))
`(LET ((METHOD-CLASS ,method-class-form)
(BACKPOINTER (LIST NIL)))
(APPLY #'MAKE-METHOD-INSTANCE METHOD-CLASS
,@method-initargs-forms
'BACKPOINTER BACKPOINTER
(METHOD-FUNCTION-INITARGS METHOD-CLASS
(,fast-function-factory-lambda BACKPOINTER))))))
(nreverse method-forms)))))))
;; Parse a DEFGENERIC lambdalist:
;; lambdalist --> reqnum, req-vars, optnum, restp, keyp, keywords, allowp
(defun analyze-defgeneric-lambdalist (caller whole-form funname lambdalist)
(multiple-value-bind (reqvars optvars rest keyp keywords keyvars allowp)
(sys::analyze-generic-function-lambdalist lambdalist
#'(lambda (lalist detail errorstring &rest arguments)
(declare (ignore lalist)) ; use WHOLE-FORM instead
(sys::lambda-list-error whole-form detail
(TEXT "~S ~S: invalid generic function lambda-list: ~A")
caller funname (apply #'format nil errorstring arguments))))
(declare (ignore keyvars))
(values (length reqvars) reqvars (length optvars)
(or (not (eql rest 0)) keyp) ; &key implies &rest
keyp keywords allowp)))
;;; DEFGENERIC
(defmacro defgeneric (&whole whole-form
funname lambda-list &rest options)
(multiple-value-bind (generic-function-class-form signature argument-precedence-order method-combination-lambda method-combination-p method-class-form method-class-p declspecs declspecs-p docstring docstring-p user-defined-args method-forms)
(analyze-defgeneric 'defgeneric whole-form funname lambda-list options)
(let* ((generic-function-class-var (gensym))
(generic-function-class-keywords-var (gensym))
(funname-symbol (sys::get-funname-symbol funname))
(method-combination-form `(,method-combination-lambda ,generic-function-class-var)))
`(LET ()
(DECLARE (SYS::IN-DEFUN ,funname))
(SYS::EVAL-WHEN-COMPILE
(SYS::C-DEFUN ',funname ',signature nil 'DEFGENERIC))
(WHEN (GET ',funname-symbol 'SYS::TRACED-DEFINITION)
(SYS::UNTRACE1 ',funname))
;; NB: no (SYSTEM::REMOVE-OLD-DEFINITIONS ',funname)
(sys::check-redefinition ',funname 'defgeneric
(sys::fbound-string ',funname-symbol))
(LET* ((,generic-function-class-var ,generic-function-class-form)
,@(if user-defined-args
`((,generic-function-class-keywords-var
(CLASS-VALID-INITIALIZATION-KEYWORDS ,generic-function-class-var)))))
;; Provide good error messages. The error message from
;; ENSURE-GENERIC-FUNCTION (actually MAKE-INSTANCE) later is unintelligible.
,@(if user-defined-args
`((UNLESS (EQ ,generic-function-class-keywords-var 'T)
,@(mapcar #'(lambda (option)
`(UNLESS (MEMBER ',(first option) ,generic-function-class-keywords-var)
(ERROR-OF-TYPE 'EXT:SOURCE-PROGRAM-ERROR
:FORM ',whole-form
:DETAIL ',option
(TEXT "~S ~S: invalid option ~S")
'DEFGENERIC ',funname ',option)))
user-defined-args))))
(APPLY #'ENSURE-GENERIC-FUNCTION ',funname
;; Here we pass a default for :GENERIC-FUNCTION-CLASS because
;; defaulting it in the context of ENSURE-GENERIC-FUNCTION is
;; less straightforward than defaulting it here.
:GENERIC-FUNCTION-CLASS ,generic-function-class-var
:LAMBDA-LIST ',lambda-list
;; Here we pass a default for :ARGUMENT-PRECEDENCE-ORDER because
;; it's error-prone to pass :LAMBDA-LIST without
;; :ARGUMENT-PRECEDENCE-ORDER.
:ARGUMENT-PRECEDENCE-ORDER ',argument-precedence-order
,@(if method-class-p `(:METHOD-CLASS ,method-class-form))
;; We have to pass a :METHOD-COMBINATION always. Here we pass it
;; only if explicitly specified; it will override user-defined
;; and default initargs. Otherwise we pass it further down the
;; argument list, where user-defined and default initargs can
;; override it. The MOP doesn't mandate this, but it allows users
;; to specify a default method-combination for a generic-function
;; class; see clisp tracker item #[ 1415783 ].
,@(if method-combination-p `(:METHOD-COMBINATION ,method-combination-form))
,@(if docstring-p `(:DOCUMENTATION ',docstring))
,@(if declspecs-p `(:DECLARATIONS ',declspecs))
'METHODS (LIST ,@method-forms)
;; Pass user-defined initargs of the generic-function-class.
,@(mapcan #'(lambda (option)
(list `',(first option) `',(rest option)))
user-defined-args)
(APPEND
;; Pass the default initargs of the generic-function class, in
;; order to erase leftovers from the previous definition.
(MAPCAN #'(LAMBDA (X) (LIST (FIRST X) (FUNCALL (THIRD X))))
(CLASS-DEFAULT-INITARGS ,generic-function-class-var))
(LIST
;; Here we pass defaults for :METHOD-CLASS, :DOCUMENTATION,
;; :DECLARATIONS if the corresponding option wasn't specified
;; in the DEFGENERIC form, because when a generic function is
;; being redefined, passing :DOCUMENTATION NIL to
;; ENSURE-GENERIC-FUNCTION means to erase the documentation
;; string, while nothing means to keep it! See MOP p. 61.
,@(unless method-class-p '(:METHOD-CLASS <STANDARD-METHOD>))
,@(unless method-combination-p `(:METHOD-COMBINATION ,method-combination-form))
,@(unless docstring-p '(:DOCUMENTATION NIL))
,@(unless declspecs-p '(:DECLARATIONS NIL))))))))))
;; ============================================================================
;; For GENERIC-FUNCTION, GENERIC-FLET, GENERIC-LABELS
;; Transform lambdalist into calling convention for the compiler:
(defun defgeneric-lambdalist-callinfo (caller whole-form funname lambdalist)
(multiple-value-bind (reqnum req-vars optnum restp keyp keywords allowp)
(analyze-defgeneric-lambdalist caller whole-form funname lambdalist)
(declare (ignore req-vars keyp))
(callinfo reqnum optnum restp keywords allowp)))
(defun make-generic-function-form (caller whole-form funname lambda-list options)
(multiple-value-bind (generic-function-class-form signature argument-precedence-order method-combination-lambda method-combination-p method-class-form method-class-p declspecs declspecs-p docstring docstring-p user-defined-args method-forms)
(analyze-defgeneric caller whole-form funname lambda-list options)
(declare (ignore signature))
(let ((generic-function-class-var (gensym)))
`(LET ((,generic-function-class-var ,generic-function-class-form))
(MAKE-GENERIC-FUNCTION ,generic-function-class-var ',caller ',whole-form ',funname ',lambda-list ',argument-precedence-order (,method-combination-lambda ,generic-function-class-var) ,method-combination-p ,method-class-form ,method-class-p ',declspecs ,declspecs-p ',docstring ,docstring-p ',user-defined-args
,@method-forms)))))
#| GENERIC-FUNCTION is a TYPE (and a COMMON-LISP symbol) in ANSI CL,
but not a macro, so this definition violates the standard
(defmacro generic-function (&whole whole-form
lambda-list &rest options)
(make-generic-function-form 'generic-function whole-form 'LAMBDA
lambda-list options))
|#
;; For GENERIC-FLET, GENERIC-LABELS
(defun analyze-generic-fundefs (caller whole-form fundefs)
(let ((names '())
(funforms '()))
(dolist (fundef fundefs)
(unless (and (consp fundef) (consp (cdr fundef)))
(error-of-type 'ext:source-program-error
:form whole-form
:detail fundef
(TEXT "~S: ~S is not a generic function specification")
caller fundef))
(push (first fundef) names)
(push (make-generic-function-form
caller whole-form (first fundef) (second fundef) (cddr fundef))
funforms))
(values (nreverse names) (nreverse funforms))))
;;; GENERIC-FLET
(defmacro generic-flet (&whole whole-form
fundefs &body body)
(multiple-value-bind (funnames funforms)
(analyze-generic-fundefs 'generic-flet whole-form fundefs)
(let ((varnames (gensym-list funnames)))
`(LET ,(mapcar #'list varnames funforms)
(FLET ,(mapcar #'(lambda (varname funname)
`(,funname (&rest args) (apply ,varname args)))
varnames funnames)
,@body)))))
;;; GENERIC-LABELS
(defmacro generic-labels (&whole whole-form
fundefs &body body)
(multiple-value-bind (funnames funforms)
(analyze-generic-fundefs 'generic-labels whole-form fundefs)
(let ((varnames (gensym-list funnames)))
`(LET ,varnames
(FLET ,(mapcar #'(lambda (varname funname)
`(,funname (&rest args) (apply ,varname args)))
varnames funnames)
,@(mapcar #'(lambda (varname funform) `(SETQ ,varname ,funform))
varnames funforms)
,@body)))))
;;; WITH-ADDED-METHODS
;; is screwed up and therefore will not be implemented.
;; ============================================================================
| 34,508 | Common Lisp | .lisp | 640 | 40.148438 | 317 | 0.583654 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | e369df0338b6d337cf7549aaff881fea23ea7cbf073b7d13f4e57501fe1db8cf | 11,347 | [
-1
] |
11,348 | clos-stablehash1.lisp | ufasoft_lisp/clisp/clos-stablehash1.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Objects with stable hash code
;;;; Part 1: Class definition.
;;;; Bruno Haible 2004-05-15
(in-package "CLOS")
;;; ===========================================================================
;;; The class <standard-stablehash> allows CLOS instances to have a
;;; GC-invariant EQ hash code.
;;; Used for (make-hash-table :test 'stablehash-eq).
(defvar *<standard-stablehash>-defclass*
'(defclass standard-stablehash ()
(($hashcode :initform (sys::random-posfixnum))) ; GC invariant hash code
(:fixed-slot-locations t)))
;; Fixed slot locations.
(defconstant *<standard-stablehash>-hashcode-location* 1)
;; No need for accessors. The hashcode is used by hashtabl.d.
;; Initialization of a <standard-stablehash> instance.
(defun shared-initialize-<standard-stablehash> (object situation &rest args
&key &allow-other-keys)
(if *classes-finished*
(apply #'%shared-initialize object situation args) ; == (call-next-method)
; Bootstrapping: Simulate the effect of #'%shared-initialize.
(when (eq situation 't) ; called from initialize-instance?
(setf (standard-instance-access object *<standard-stablehash>-hashcode-location*)
(sys::random-posfixnum))))
object)
;;; ===========================================================================
| 1,382 | Common Lisp | .lisp | 27 | 46.407407 | 87 | 0.616927 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | ceade2dba39ff5fee7132db38aff687c8b96d352104a88328176203fec7bdf4c | 11,348 | [
-1
] |
11,349 | trace.lisp | ufasoft_lisp/clisp/trace.lisp | ;; Tracer
;; Bruno Haible 13.2.1990, 15.3.1991, 4.4.1991
;; German comments translated into English: Stefan Kain 2001-12-26
;; Sam Steingold 2001-2009
(in-package "COMMON-LISP")
(export '(trace untrace))
(export '(custom::*trace-indent*) "CUSTOM")
(in-package "EXT")
(export '(*trace-function* *trace-args* *trace-form* *trace-values*
custom::*trace-indent*))
(in-package "SYSTEM")
(defvar *trace-indent* nil
"Use indentation in addition to numbering to indicate the trace level.")
(proclaim '(special *trace-function* *trace-args* *trace-form* *trace-values*))
(defvar *traced-functions* nil) ; list of currently traced function-names ; ABI
;; So long as a function-name funname [resp. more exactly: the Symbol
;; symbol = (get-funname-symbol funname)] are traced, the Property
;; sys::traced-definition contains the old content of the function-cell, the
;; Property sys::tracing-definition contains the new content of the
;; function-cell, and the function-name is element of the list
;; *traced-functions*.
;; Meanwhile the content of the function-cell can change, however!
;; At all events the following is true:
;; (and (fboundp symbol)
;; (eq (symbol-function symbol) (get symbol 'sys::tracing-definition)))
;; ===> (member funname *traced-functions* :test #'equal)
;; <==> (get symbol 'sys::traced-definition)
(defvar *trace-level* 0) ; nesting depth for Trace-Output
(labels ((subclosure-pos (closure name)
(do ((length (sys::%record-length closure))
;; sys::symbol-suffix is defined in compiler.lisp
(nm (sys::symbol-suffix (closure-name closure) name))
(pos 0 (1+ pos)) obj)
((= pos length)
(error (TEXT "~S: no local name ~S in ~S")
'local name closure))
(setq obj (sys::closure-const closure pos))
(when (and (closurep obj)
(or (eq (closure-name obj) nm)
(eq (closure-name obj)
(concat-pnames "TRACED-" nm))))
(return pos))))
(force-cclosure (name)
(let ((closure (fdefinition name)))
(unless (closurep closure)
(error-of-type 'type-error
:datum closure :expected-type 'closure
(TEXT "~S: ~S does not name a closure") 'local name))
(if (sys::%compiled-function-p closure)
closure
(fdefinition (compile name closure)))))
(local-helper (spec)
(do* ((spe (cdr spec) (cdr spe))
(clo (force-cclosure (car spec))
(sys::%record-ref clo pos))
(pos (subclosure-pos clo (car spe))
(subclosure-pos clo (car spe))))
((endp (cdr spe)) (values clo pos)))))
(defun %local-get (spec) ; ABI
(multiple-value-bind (clo pos) (local-helper spec)
(sys::closure-const clo pos)))
(defun %local-set (new-def spec) ; ABI
(unless (closurep new-def)
(error-of-type 'type-error
:datum new-def :expected-type 'closure
(TEXT "~S: ~S is not a closure") `(setf (local ,@spec)) new-def))
(multiple-value-bind (clo pos) (local-helper spec)
(setf (sys::closure-const clo pos)
(if (sys::%compiled-function-p new-def)
new-def
(fdefinition (compile (closure-name (sys::%record-ref clo pos))
new-def)))))))
(defmacro local (&rest spec)
"Return the closure defined locally with LABELS or FLET.
SPEC is a list of (CLOSURE SUB-CLOSURE SUB-SUB-CLOSURE ...)
CLOSURE must be compiled."
(%local-get spec))
(define-setf-expander local (&rest spec)
"Modify the local definition (LABELS or FLET).
This will not work with closures that use lexical variables!"
(let ((store (gensym "LOCAL-")))
(values nil nil `(,store) `(%LOCAL-SET ,store ',spec)
`(%LOCAL-GET ,spec))))
;; check whether the object might name a local (LABELS or FLET) function
(defun local-function-name-p (obj)
(and (consp obj) (eq 'local (car obj))))
;; Structure containing all trace options for a given function.
;; make-tracer is ABI
(defstruct (tracer (:type vector))
name symb cur-def local-p
suppress-if max-depth step-if pre post pre-break-if post-break-if
bindings
pre-print post-print print)
;; install the new function definition
(defun tracer-set-fdef (trr new-fdef)
(if (tracer-local-p trr)
(%local-set new-fdef (rest (tracer-name trr)))
(setf (symbol-function (tracer-symb trr)) new-fdef)))
(defmacro trace (&rest funs)
"Trace function execution.
\(TRACE) returns the list of all traced functions.
\(TRACE fun ...) additionally traces the functions fun, ... .
Format for fun:
Either a function name
or a list made of a function-cell and a few keyword arguments (pairwise!)
(function-name
[:suppress-if form] ; no Trace-Output, as long as form is true
[:max-depth form] ; no trace output, as long as (> *trace-level* form)
[:step-if form] ; Trace moves into the Stepper, if form is true
[:bindings ((variable form)...)] ; binds variables around the following forms
[:pre form] ; executes form before function call
[:post form] ; executes form after function call
[:pre-break-if form] ; Trace moves into break-loop before function call,
; if form is true
[:post-break-if form] ; Trace moves into break-loop after function call,
; if form is true
[:pre-print form] ; prints the values of form before function call
[:post-print form] ; prints the values of form after function call
[:print form] ; prints the values of form before
; and after the function call
)
In all these forms *TRACE-FUNCTION* (the function itself),
*TRACE-ARGS* (the function arguments),
*TRACE-FORM* (the function-/macro-call as form),
and after function call also *TRACE-VALUES* (the list of values
of the function call) can be accessed,
and the function can be left with RETURN with given values.
TRACE and UNTRACE are also applicable to functions (SETF symbol) and macros,
however not applicable to locally defined functions and macros."
(if (null funs)
'*TRACED-FUNCTIONS*
`(APPEND
,@(mapcar #'(lambda (fun)
`(TRACE1
,(if (or (function-name-p fun) (local-function-name-p fun))
`(MAKE-TRACER :NAME ',fun)
`(APPLY #'MAKE-TRACER :NAME ',fun))))
funs))))
;; check whether the FUNNAME can be traced,
;; fill SYMB, CUR-DEF and LOCAL-P slots of TRR and return TRR
(defun check-traceable (funname trr caller)
(tagbody restart
(cond ((function-name-p funname)
(let ((sym (get-funname-symbol funname)))
(unless (fboundp sym)
(error (TEXT "~S: undefined function ~S") caller funname))
(when (special-operator-p sym)
(error (TEXT "~S: cannot trace special operator ~S")
caller funname))
(setf (tracer-symb trr) sym
(tracer-cur-def trr) (symbol-function sym)
(tracer-local-p trr) nil)))
((local-function-name-p funname)
(setf (tracer-cur-def trr) (%local-get (rest funname))
(tracer-symb trr) (closure-name (tracer-cur-def trr))
(tracer-local-p trr) t)
(when (get (tracer-symb trr) 'sys::untraced-name)
(setf (tracer-symb trr)
(get (tracer-symb trr) 'sys::untraced-name))))
(t (setq funname (check-function-name funname caller))
(go restart))))
(check-redefinition funname caller (TEXT "function"))
trr)
(defun trace1 (trr) ; ABI
(check-traceable (tracer-name trr) trr 'trace)
(let ((macro-flag (macrop (tracer-cur-def trr)))
(sig (when (tracer-local-p trr)
(sig-to-list (get-signature (tracer-cur-def trr))))))
(unless (eq (tracer-cur-def trr) ; already traced?
(get (tracer-symb trr) 'sys::tracing-definition))
(setf (get (tracer-symb trr) 'sys::traced-definition)
(tracer-cur-def trr))
(pushnew (tracer-name trr) *traced-functions* :test #'equal))
(fresh-line)
(format t (TEXT ";; Tracing ~:[function~;macro~] ~S.")
macro-flag (tracer-name trr))
(setf (get (tracer-symb trr) 'sys::tracing-definition)
;; new function, that replaces the original one:
(let ((newname (concat-pnames "TRACED-" (tracer-symb trr)))
(body
`((declare (inline car cdr cons apply values-list))
(let ((*trace-level* (1+ *trace-level*))
,@(tracer-bindings trr))
(block nil
(unless (or ,(tracer-suppress-if trr)
,(if (tracer-max-depth trr) `(> *trace-level* ,(tracer-max-depth trr)) 'nil))
(trace-pre-output))
,@(when (tracer-pre-print trr)
`((trace-print (multiple-value-list
,(tracer-pre-print trr)))))
,@(when (tracer-print trr)
`((trace-print (multiple-value-list
,(tracer-print trr)))))
,(tracer-pre trr)
,@(when (tracer-pre-break-if trr)
`((when ,(tracer-pre-break-if trr)
(sys::break-loop t))))
(let ((*trace-values*
(multiple-value-list
,(if (tracer-local-p trr)
`(funcall ,(tracer-cur-def trr) ,@sig)
`(if ,(tracer-step-if trr)
(trace-step-apply)
(apply *trace-function* *trace-args*))))))
,@(when (tracer-post-break-if trr)
`((when ,(tracer-post-break-if trr)
(sys::break-loop t))))
,(tracer-post trr)
,@(when (tracer-print trr)
`((trace-print (multiple-value-list
,(tracer-print trr)))))
,@(when (tracer-post-print trr)
`((trace-print (multiple-value-list
,(tracer-post-print trr)))))
(unless (or ,(tracer-suppress-if trr)
,(if (tracer-max-depth trr) `(> *trace-level* ,(tracer-max-depth trr)) 'nil))
(trace-post-output))
(values-list *trace-values*)))))))
(setf (get newname 'sys::untraced-name) (tracer-symb trr))
(macrolet ((f (def) `(fdefinition (compile newname ,def))))
(cond (macro-flag
(make-macro
(f `(lambda (&rest *trace-args*
&aux (*trace-form* (car *trace-args*))
(*trace-function*
(macro-expander
(get-traced-definition
',(tracer-symb trr)))))
,@body))
(macro-lambda-list (tracer-cur-def trr))))
((tracer-local-p trr)
(f `(lambda ,sig
(let* ((*trace-args* (list ,@sig))
(*trace-form*
(make-apply-form ',(tracer-name trr)
*trace-args*))
(*trace-function*
(get-traced-definition
',(tracer-symb trr))))
,@body))))
(t (f `(lambda (&rest *trace-args*
&aux (*trace-form*
(make-apply-form ',(tracer-name trr)
*trace-args*))
(*trace-function*
(get-traced-definition
',(tracer-symb trr))))
,@body)))))))
;; install the new definition
(tracer-set-fdef trr (get (tracer-symb trr) 'sys::tracing-definition))
;; return the name
(list (tracer-name trr))))
;; auxiliary functions:
;; fetch original function definition:
(defun get-traced-definition (symbol) (get symbol 'sys::traced-definition))
;; apply, but step by step:
(defun trace-step-apply ()
(eval `(step (apply ',*trace-function* ',*trace-args*))))
;; build Eval-Form, that corresponds to an Apply (approximately) :
(defun make-apply-form (funname args)
(declare (inline cons mapcar))
(cons funname
(mapcar #'(lambda (arg)
;; (list 'quote arg)
(cons 'quote (cons arg nil)))
args)))
;; Output before call, uses *trace-level* and *trace-form*
(defun trace-output () ; common for pre & post
(fresh-line *trace-output*)
(when *trace-indent*
(write-spaces *trace-level* *trace-output*))
(write *trace-level* :stream *trace-output* :base 10 :radix t)
(write-string " Trace: " *trace-output*))
(defun trace-pre-output ()
(trace-output)
(prin1 *trace-form* *trace-output*)
(elastic-newline *trace-output*))
;; Output after call, uses *trace-level*, *trace-form* and *trace-values*
(defun trace-post-output ()
(declare (inline car cdr consp atom))
(trace-output)
(write (car *trace-form*) :stream *trace-output*)
(write-string " ==> " *trace-output*)
(trace-print *trace-values* nil))
;; Output of a list of values:
(defun trace-print (vals &optional (nl-flag t))
(when nl-flag (fresh-line *trace-output*))
(when (consp vals)
(loop
(prin1 (pop vals) *trace-output*)
(when (atom vals) (return))
(write-string ", " *trace-output*)))
(elastic-newline *trace-output*))
(defmacro untrace (&rest funs)
"(UNTRACE) returns the list of traced functions, stops tracing all of them.
\(UNTRACE symbol ...) removes symbol, ... from the list of traced functions."
`(MAPCAN #'UNTRACE1
,(if (null funs) `(COPY-LIST *TRACED-FUNCTIONS*) `',funs)))
(defun untrace1 (funname) ; ABI
(let* ((trr (check-traceable funname (make-tracer :name funname) 'untrace))
(symbol (tracer-symb trr))
(old-definition (get symbol 'sys::traced-definition)))
(prog1
(if old-definition
;; symbol was traced
(progn
(if (eq (tracer-cur-def trr)
(get symbol 'sys::tracing-definition))
(tracer-set-fdef trr old-definition)
(warn (TEXT "~S: ~S was traced and has been redefined!")
'untrace funname))
`(,funname))
;; funname was not traced
'())
(untrace2 trr))))
(defun untrace2 (funname)
;; funname can be either a tracer (from untrace1)
;; or a function name (from remove-old-definitions)
(let ((symbol (if (vectorp funname) (tracer-symb funname)
(get-funname-symbol funname))))
(remprop symbol 'sys::traced-definition)
(remprop symbol 'sys::tracing-definition))
(setq *traced-functions*
(delete (if (vectorp funname) (tracer-name funname) funname)
*traced-functions* :test #'equal)))
| 15,867 | Common Lisp | .lisp | 325 | 36.353846 | 114 | 0.549214 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 2ea37e0fdb55375c175c63f21f72ad6d03e8f9d7e4dae0b0890a05e01a62f511 | 11,349 | [
-1
] |
11,350 | subtypep.lisp | ufasoft_lisp/clisp/subtypep.lisp | ;;;; SUBTYPEP
;;;; Bruno Haible 2004-03-28, 2004-04-03
;;;; Sam Steingold 2004-2005
;; SUBTYPEP is very powerful. It can tell:
;; - whether a type is empty:
;; (subtypep a 'NIL)
;; - whether two types are disjoint:
;; (subtypep `(AND ,a ,b) 'NIL)
;; - whether two types are equal:
;; (and (subtypep a b) (subtypep b a))
;; - whether an object is an element of a given type:
;; (subtypep `(eql ,x) a)
;; - whether two objects are identical:
;; (subtypep `(eql ,x) `(eql ,y))
;; - whether a number is positive:
;; (subtypep `(eql ,x) '(real (0) *))
;; and much more.
(in-package "SYSTEM")
;;; SUBTYPEP
;;; After many hacked attempts that always failed to recognize complicated
;;; cases like the equivalence of
;;; (INTEGER 0 3) (MEMBER 0 3 1 2)
;;; (AND (INTEGER 0 4) (NOT (EQL 2))) (MEMBER 0 3 1 4)
;;; (AND (RATIONAL -1 1) (NOT INTEGER)) (AND (OR (RATIONAL -1 (0)) (RATIONAL (0) 1)) (NOT INTEGER))
;;; here finally comes an implementation of the approach presented in
;;; Henry G. Baker: A Decision Procedure for Common Lisp's SUBTYPEP Predicate
;;; Lisp and Symbolic Computation 5,3 (Sept. 1992), 157-190.
;;; The main idea is to use AND/OR logic to reduce the problem to 17 disjoint
;;; categories of types, and implement this logic correctly for each of the 17
;;; categories.
;;; The general outline of the decision procedure:
;;; 1. Do some superficial simplification and error checking:
;;; CANONICALIZE-TYPE.
;;; 2. Flatten the ANDs and ORs of the outermost level and reduce the
;;; problem to (SUBTYPEP `(AND ,a1 ... ,am) `(OR ,b1 ... ,bn)).
;;; 3. Remove MEMBER and EQL specifiers from a1, ..., am, b1, ..., bn.
;;; 4. Classify a1, ..., am, b1, ..., bn into one of the 17 categories.
;;; 5. In each of the 17 categories, simplify the AND part and the OR part
;;; to an appropriate canonical representation (for example, for REAL,
;;; an ordered list of intervals).
;;; 6. Decide the SUBTYPEP relationship in the particular category.
;;; SUBTYPEP and (function ...) types
;;;
;;; How is SUBTYPEP on specific function types meant to work?
;;;
;;; HyperSpec/Body/syscla_function.html says:
;;;
;;; "The list form of the function type-specifier can be used only for
;;; declaration and not for discrimination."
;;;
;;; So this means, the function call
;;;
;;; (typep #'cons '(function (t t) cons))
;;;
;;; is invalid. But HyperSpec/Body/fun_subtypep.html talks about what
;;; may happen when (function ...) is passed to SUBTYPEP. So the result of
;;;
;;; (subtypep '(eql #.#'cons) '(function (t t) cons))
;;;
;;; must be either nil;nil (means unknown) or t;t (means true).
;;;
;;; Now, what about
;;;
;;; (defun covariant ()
;;; (subtypep '(function (integer integer) cons)
;;; '(function (t t) cons)))
;;;
;;; (defun contravariant ()
;;; (subtypep '(function (t t) cons)
;;; '(function (integer integer) cons)))
;;;
;;; Can either of these functions ever return true? In other words, are the
;;; argument types in function types covariant or contravariant?
;;;
;;; Since a function that accepts any objects as arguments also accepts,
;;; integers but not versa, the interpretation of a type as a "set of objects"
;;; suggests that
;;; (covariant) => nil;t or nil;nil
;;; (contravariant) => t;t or nil;nil
;;;
;;; But type relationships can also be defined through declarations: According
;;; to HyperSpec/Body/dec_type.html, (subtypep A B) is true if and only if
;;;
;;; (locally (declare (type A x)) (declare (type B x))
;;; (form ...))
;;;
;;; is equivalent to
;;;
;;; (locally (declare (type A x))
;;; (form ...))
;;;
;;; When we transpose this to function types, (subtypep A B) should be true if
;;; and only if
;;;
;;; (locally (declare (ftype A x)) (declare (ftype B x))
;;; (form ...))
;;;
;;; is equivalent to
;;;
;;; (locally (declare (ftype A x))
;;; (form ...))
;;;
;;; Using the definition of the semantics of FTYPE declarations in
;;; HyperSpec/Body/syscla_function.html we arrive to the conclusion that
;;;
;;; (locally (declare (ftype (function (t t) cons) x))
;;; (declare (ftype (function (integer integer) cons)))
;;; (form ...))
;;;
;;; is equivalent to
;;;
;;; (locally (declare (ftype (function (integer integer) cons)))
;;; (form ...))
;;;
;;; hence
;;;
;;; (covariant) => t;t or nil;nil
;;; (contravariant) => nil;t or nil;nil
;;;
;;; In summary, the view of a type as a "set of objects" leads to a view of
;;; subtypes that is opposite to the view of a function type as describing
;;; function calls. Since "the function type-specifier can be used only for
;;; declaration and not for discrimination" the first view is not the correct
;;; one. Rather the second view should be used.
;;;
;;; However, I believe the contradiction persists because the view of a type
;;; as a "set of objects" is so fundamental.
;;;
;;; Implementations like SBCL, CMUCL use the second view:
;;;
;;; (covariant) => t;t
;;; (contravariant) => nil;t
;;;
;;; Implementations like ACL 6.2 and LispWorks 4.3 punt and return nil;nil.
;;; We do the same.
;;; Defines a type category.
;;; (DEF-TYPE-CATEGORY name atomic-type-specifiers list-type-specifiers
;;; and-simplifier or-simplifier subtype-decider)
;;; The name denotes the type category.
;;; The atomic-type-specifiers and list-type-specifiers are lists of symbols.
;;; The and-simplifier, or-simplifier, subtype-decider are lambda expressions.
;;; and-simplifier: Simplifies `(AND ,@parts). Takes a nonempty list of
;;; elementary type specifiers, returns a type specifier.
;;; Can, but does not need to, return NIL if `(AND ,@parts)
;;; is the empty type.
;;; or-simplifier: Simplifies `(OR ,@parts). Takes a list of elementary type
;;; specifiers, returns a list of elementary type specifiers.
;;; subtype-decider: Decides whether type1 is a subtype of `(OR ,@type2parts).
;;; Takes a result of and-simplifier (but not NIL), a result
;;; of or-simplifier, and a boolean telling whether an attempt
;;; should be made to prove (no) when a (yes) cannot be proven.
;;; Returns two values, with the same meaning as in SUBTYPEP.
;;; The macros (yes), (no), (unknown) can be used here. (no)
;;; may only be returned if the third argument try-prove-no is
;;; true.
(defmacro def-type-category (name atomic-type-specifiers list-type-specifiers
and-simplifier or-simplifier subtype-decider)
(let ((and-simplifier-name
(intern (string-concat "SIMPLIFY-AND-" (symbol-name name)) "SYSTEM"))
(or-simplifier-name
(intern (string-concat "SIMPLIFY-OR-" (symbol-name name)) "SYSTEM"))
(subtype-decider-name
(intern (string-concat "SUBTYPEP-" (symbol-name name)) "SYSTEM")))
`(PROGN
,@(if (symbol-package name)
`((EVAL-WHEN (COMPILE LOAD EVAL)
(SETF (GET ',name 'SUBTYPEP-ATOM) ',atomic-type-specifiers)
(SETF (GET ',name 'SUBTYPEP-LIST) ',list-type-specifiers)
(SETQ *type-categories* (UNION *type-categories* '(,name)))
) ))
(DEFUN ,and-simplifier-name ,(cadr and-simplifier)
,@(cddr and-simplifier))
(DEFUN ,or-simplifier-name ,(cadr or-simplifier)
,@(cddr or-simplifier))
,(multiple-value-bind (body-rest declarations)
(sys::parse-body (cddr subtype-decider))
`(DEFUN ,subtype-decider-name ,(cadr subtype-decider)
,@(if declarations `((DECLARE ,@declarations)))
(MACROLET ((YES () '(RETURN-FROM ,subtype-decider-name (VALUES T T)))
(NO () '(RETURN-FROM ,subtype-decider-name (VALUES NIL T)))
(UNKNOWN () '(RETURN-FROM ,subtype-decider-name (VALUES NIL NIL))))
,@body-rest)))
,@(if (symbol-package name)
`((SETF (GET ',name 'SUBTYPEP-SIMPLIFY-AND) ',and-simplifier-name)
(SETF (GET ',name 'SUBTYPEP-SIMPLIFY-OR) ',or-simplifier-name)
(SETF (GET ',name 'SUBTYPEP-DECIDE) ',subtype-decider-name)
) )
',name
)
) )
;; Defines a type category for a type which has no special subtypes except
;; NIL and itself (ignoring SATISFIES types).
(defmacro def-misc-type-category (name)
`(PROGN
(EVAL-WHEN (COMPILE LOAD EVAL)
(SETF (GET ',name 'SUBTYPEP-ATOM) '(,name))
(SETF (GET ',name 'SUBTYPEP-LIST) '())
(SETQ *type-categories* (UNION *type-categories* '(,name)))
)
(SETF (GET ',name 'SUBTYPEP-SIMPLIFY-AND) 'SIMPLIFY-AND-MISC)
(SETF (GET ',name 'SUBTYPEP-SIMPLIFY-OR) 'SIMPLIFY-OR-MISC)
(SETF (GET ',name 'SUBTYPEP-DECIDE) 'SUBTYPEP-MISC)
',name
)
)
(eval-when (compile load eval)
(defvar *type-categories* '())
)
(def-type-category ARRAY (ARRAY SIMPLE-ARRAY) (ARRAY SIMPLE-ARRAY)
;; Each part is of the form ([SIMPLE-]ARRAY &optional el-type dims).
(lambda (parts)
;; Simplify `(AND ,@parts):
(let ((final-kind 'ARRAY) (final-eltype '*) (final-dims '*))
(dolist (type parts `(,final-kind ,final-eltype ,final-dims))
(when (or (eq type 'SIMPLE-ARRAY)
(and (consp type) (eq (first type) 'SIMPLE-ARRAY)))
(setq final-kind 'SIMPLE-ARRAY))
(when (and (consp type) (rest type))
(let ((eltype (second type)))
(unless (eq eltype '*)
(setq eltype (upgraded-array-element-type eltype))
; Constraint: All upgraded-eltypes must be the same.
; Here we use the fact that the upgraded-array-element-type
; return values are so simple that they can be compared with
; EQUAL.
(if (eq final-eltype '*)
(setq final-eltype eltype)
(unless (equal eltype final-eltype)
; Contradictory element-types.
(return 'NIL))))))
(when (and (consp type) (cddr type))
(let ((dims (third type)))
(unless (eq dims '*)
(if (eq final-dims '*)
(setq final-dims dims)
(if (listp dims)
(if (listp final-dims)
(if (eql (length dims) (length final-dims))
(setq final-dims
(mapcar #'(lambda (d1 d2)
(if (integerp d2)
(if (integerp d1)
(if (eql d1 d2)
d1
; Contradictory dimension constraint.
(return 'NIL))
d2)
d1))
final-dims dims))
; Contradictory dimensions constraint.
(return 'NIL))
(if (eql (length dims) final-dims)
(setq final-dims dims)
; Contradictory dimensions constraint.
(return 'NIL)))
(unless (eql dims (if (listp final-dims) (length final-dims) final-dims))
; Contradictory dimensions constraint.
(return 'NIL))))))))))
(lambda (parts)
parts)
(lambda (type1 type2parts try-prove-no)
(let (kind1 eltype1 dims1)
(if (atom type1)
(setq kind1 type1
eltype1 '*
dims1 '*)
(setq kind1 (first type1)
eltype1 (if (rest type1) (second type1) '*)
dims1 (if (cddr type1) (third type1) '*)))
(assert (member kind1 '(ARRAY SIMPLE-ARRAY)))
(assert (or (eq eltype1 '*)
(equal eltype1 (upgraded-array-element-type eltype1))))
(let ((uncovered-eltypes
; The possible results of upgraded-array-element-type.
'(NIL CHARACTER BIT (UNSIGNED-BYTE 2) (UNSIGNED-BYTE 4)
(UNSIGNED-BYTE 8) (UNSIGNED-BYTE 16) (UNSIGNED-BYTE 32) T)))
(dolist (type2 type2parts)
(let (kind2 eltype2 dims2)
(if (atom type2)
(setq kind2 type2
eltype2 '*
dims2 '*)
(setq kind2 (first type2)
eltype2 (if (rest type2) (second type2) '*)
dims2 (if (cddr type2) (third type2) '*)))
(assert (member kind2 '(ARRAY SIMPLE-ARRAY)))
(when
(and (or (eq kind2 'ARRAY) (eq kind2 kind1))
(or (eq dims2 '*)
(if (listp dims1)
(if (listp dims2)
(and (eql (length dims1) (length dims2))
(every #'(lambda (a b) (or (eq b '*) (eql a b)))
dims1 dims2))
(eql (length dims1) dims2))
(if (listp dims2)
(and (eql dims1 (length dims2))
(every #'(lambda (b) (eq b '*)) dims2))
(eql dims1 dims2)))))
(if (eq eltype2 '*)
(yes)
(let ((eltype2 (upgraded-array-element-type eltype2)))
(if (eq eltype1 '*)
;; type2 does not cover all of type1 but only a significant
;; portion of it. Keep track which portions are covered.
(setq uncovered-eltypes
(remove eltype2 uncovered-eltypes :test #'equal))
(when (equal eltype1 eltype2)
(yes))))))))
(when (null uncovered-eltypes)
;; eltype1 was *, and the type2parts cover all possible array element
;; types.
(yes)))
(when try-prove-no
;; We could construct a testimony using MAKE-ARRAY.
;; Don't test eltype1 against NIL, since we have arrays with element
;; type NIL.
(when (or (eq dims1 '*)
(if (listp dims1)
(and (< (length dims1) #,array-rank-limit)
(every #'(lambda (a) (or (eq a '*) (< a #,array-dimension-limit)))
dims1)
(or (member '* dims1)
(< (reduce #'* dims1) #,array-total-size-limit)))
(< dims1 #,array-rank-limit)))
(no)))
(unknown)))
)
(def-type-category COMPLEX (COMPLEX) (COMPLEX)
;; Each part is of the form (COMPLEX &optional rtype itype).
(lambda (parts)
;; Simplify `(AND ,@parts):
(let ((final-rtype '*) (final-itype '*))
(dolist (type parts)
(when (and (consp type) (rest type))
(let* ((rtype (second type))
(itype (if (cddr type) (third type) rtype)))
(unless (eq rtype '*)
(setq rtype (upgraded-complex-part-type rtype))
(when (eq final-rtype '*) (setq final-rtype 'REAL))
(setq final-rtype `(AND ,final-rtype ,rtype)))
(unless (eq itype '*)
(setq itype (upgraded-complex-part-type itype))
(when (eq final-itype '*) (setq final-itype 'REAL))
(setq final-itype `(AND ,final-itype ,itype))))))
(if (or (and (not (eq final-rtype '*)) (subtypep final-rtype 'NIL))
(and (not (eq final-itype '*)) (subtypep final-itype 'NIL)))
; Contradictory type constraint.
'NIL
(if (and (eq final-rtype '*) (eq final-itype '*))
'COMPLEX
`(COMPLEX ,final-rtype ,final-itype)))))
(lambda (parts)
parts)
(lambda (type1 type2parts try-prove-no)
(let (rtype1 itype1)
(if (atom type1)
(setq rtype1 '*
itype1 '*)
(setq rtype1 (if (rest type1) (second type1) '*)
itype1 (if (cddr type1) (third type1) '*)))
(dolist (type2 type2parts)
(let (rtype2 itype2)
(if (atom type2)
(setq rtype2 '*
itype2 '*)
(setq rtype2 (if (rest type2) (second type2) '*)
itype2 (if (cddr type2) (third type2) '*)))
(when
(and (or (eq rtype2 '*)
(subtypep (if (eq rtype1 '*) 'REAL `(AND REAL ,rtype1))
(upgraded-complex-part-type `(AND REAL ,rtype2))))
(or ; shortcut to avoid calling subtypep a second time
(and (eq itype1 rtype1) (eq itype2 rtype2))
(eq itype2 '*)
(subtypep (if (eq itype1 '*) 'REAL `(AND REAL ,itype1))
(upgraded-complex-part-type `(AND REAL ,itype2)))))
(yes))))
(when try-prove-no
;; It's too hard to prove a (no) if there is more than one type2.
(when (<= (length type2parts) 1)
(multiple-value-bind (remptyis remptyknown)
(if (eq rtype1 '*)
(values nil t)
(subtypep `(AND REAL ,rtype1) 'NIL))
(multiple-value-bind (iemptyis iemptyknown)
(if (eq itype1 '*)
(values nil t)
(subtypep `(AND REAL ,itype1) 'NIL))
(case (length type2parts)
(0 (when (and remptyknown (not remptyis)
iemptyknown (not iemptyis))
(no)))
(1
(let ((type2 (first type2parts)) rtype2 itype2)
(if (atom type2)
(setq rtype2 '*
itype2 '*)
(setq rtype2 (if (rest type2) (second type2) '*)
itype2 (if (cddr type2) (third type2) '*)))
(multiple-value-bind (rsubis rsubknown)
(if (eq rtype2 '*)
(values t t)
(subtypep (if (eq rtype1 '*) 'REAL `(AND REAL ,rtype1))
(upgraded-complex-part-type `(AND REAL ,rtype2))))
(multiple-value-bind (isubis isubknown)
(if (eq itype2 '*)
(values t t)
(subtypep (if (eq itype1 '*) 'REAL `(AND REAL ,itype1))
(upgraded-complex-part-type `(AND REAL ,itype2))))
(when (or (and rsubknown (not rsubis)
iemptyknown (not iemptyis))
(and isubknown (not isubis)
remptyknown (not remptyis)))
(no)))))))))))
(unknown)))
)
(def-type-category CONS (CONS) (CONS)
;; Each part is of the form (CONS &optional cartype cdrtype).
(lambda (parts)
;; Simplify `(AND ,@parts):
(let ((final-cartype '*) (final-cdrtype '*))
(dolist (type parts)
(when (and (consp type) (rest type))
(let ((cartype (second type)))
(unless (eq cartype '*)
(setq final-cartype
(if (eq final-cartype '*)
cartype
`(AND ,final-cartype ,cartype)))))
(when (cddr type)
(let ((cdrtype (third type)))
(unless (eq cdrtype '*)
(setq final-cdrtype
(if (eq final-cdrtype '*)
cdrtype
`(AND ,final-cdrtype ,cdrtype))))))))
(if (or (and (not (eq final-cartype '*)) (subtypep final-cartype 'NIL))
(and (not (eq final-cdrtype '*)) (subtypep final-cdrtype 'NIL)))
; Contradictory type constraint.
'NIL
(if (and (eq final-cartype '*) (eq final-cdrtype '*))
'CONS
`(CONS ,final-cartype ,final-cdrtype)))))
(lambda (parts)
parts)
(lambda (type1 type2parts try-prove-no)
(let (cartype1 cdrtype1)
(if (atom type1)
(setq cartype1 '*
cdrtype1 '*)
(setq cartype1 (if (rest type1) (second type1) '*)
cdrtype1 (if (cddr type1) (third type1) '*)))
(dolist (type2 type2parts)
(let (cartype2 cdrtype2)
(if (atom type2)
(setq cartype2 '*
cdrtype2 '*)
(setq cartype2 (if (rest type2) (second type2) '*)
cdrtype2 (if (cddr type2) (third type2) '*)))
(when
(and (or (eq cartype2 '*)
(subtypep (if (eq cartype1 '*) 'T cartype1) cartype2))
(or (eq cdrtype2 '*)
(subtypep (if (eq cdrtype1 '*) 'T cdrtype1) cdrtype2)))
(yes))))
(when try-prove-no
;; It's too hard to prove a (no) if there is more than one type2.
(when (<= (length type2parts) 1)
(multiple-value-bind (caremptyis caremptyknown)
(if (eq cartype1 '*) (values nil t) (subtypep cartype1 'NIL))
(multiple-value-bind (cdremptyis cdremptyknown)
(if (eq cdrtype1 '*) (values nil t) (subtypep cdrtype1 'NIL))
(case (length type2parts)
(0 (when (and caremptyknown (not caremptyis)
cdremptyknown (not cdremptyis))
(no)))
(1
(let ((type2 (first type2parts)) cartype2 cdrtype2)
(if (atom type2)
(setq cartype2 '*
cdrtype2 '*)
(setq cartype2 (if (rest type2) (second type2) '*)
cdrtype2 (if (cddr type2) (third type2) '*)))
(multiple-value-bind (carsubis carsubknown)
(if (eq cartype2 '*)
(values t t)
(subtypep (if (eq cartype1 '*) 'T cartype1) cartype2))
(multiple-value-bind (cdrsubis cdrsubknown)
(if (eq cdrtype2 '*)
(values t t)
(subtypep (if (eq cdrtype1 '*) 'T cdrtype1) cdrtype2))
(when (or (and carsubknown (not carsubis)
cdremptyknown (not cdremptyis))
(and cdrsubknown (not cdrsubis)
caremptyknown (not caremptyis)))
(no)))))))))))
(unknown)))
)
(def-type-category REAL
(REAL RATIONAL INTEGER FLOAT SHORT-FLOAT SINGLE-FLOAT DOUBLE-FLOAT LONG-FLOAT)
(INTERVALS)
;; Each part is of the form (kind &optional lo-bound hi-bound).
;; The canonical representation is (INTERVALS kind [lo-bound hi-bound]+), a
;; non-empty list of disjoint intervals, in ascending order. This allows
;; grouping nonadjacent intervals of the same kind together, and also allows
;; removing single elements from an interval without too much list surgery.
;; If the kind is FLOAT or LONG-FLOAT, the bounds can be rational numbers
;; instead of floating-point numbers; this is needed because we don't have
;; a floating-point type of maximal precision.
(lambda (parts)
;; Simplify `(AND ,@parts):
(block simplify
(let ((final-kind 'REAL))
(dolist (type parts)
(let ((kind (if (atom type) type (second type))))
(if (or ; Exact and inexact types are disjoint.
(and (member final-kind '(RATIONAL INTEGER))
(member kind '(FLOAT SHORT-FLOAT SINGLE-FLOAT DOUBLE-FLOAT LONG-FLOAT)))
(and (member final-kind '(FLOAT SHORT-FLOAT SINGLE-FLOAT DOUBLE-FLOAT LONG-FLOAT))
(member kind '(RATIONAL INTEGER)))
; The four different floating-point types are disjoint.
(and (member final-kind '(SHORT-FLOAT SINGLE-FLOAT DOUBLE-FLOAT LONG-FLOAT))
(member kind '(SHORT-FLOAT SINGLE-FLOAT DOUBLE-FLOAT LONG-FLOAT))
(not (eq kind final-kind))))
(return-from simplify 'NIL)
(if (real-types-subtypep kind final-kind)
(setq final-kind kind)
(assert (real-types-subtypep final-kind kind))))))
;; Map the parts all to final-kind, make all INTEGER bounds inclusive,
;; and return NIL if any of the parts is empty.
(setq parts
(mapcar #'(lambda (type)
(let ((intervals (if (atom type) '(* *) (cddr type))))
(setq intervals (intervals-mapto intervals final-kind))
(when (null intervals)
(return-from simplify 'NIL))
`(INTERVALS ,final-kind ,@intervals)))
parts))
;; Intersect the interval ranges.
(let ((intervals (reduce #'intervals-intersection parts :key #'cddr)))
(if intervals
`(INTERVALS ,final-kind ,@intervals)
'NIL)))))
(lambda (parts)
;; Make all INTEGER bounds inclusive, and remove empty parts.
(setq parts
(mapcan #'(lambda (type)
(let ((kind (if (atom type) type (second type)))
(intervals (if (atom type) '(* *) (cddr type))))
(setq intervals (intervals-mapto intervals kind))
(if intervals
(list `(INTERVALS ,kind ,@intervals))
'())))
parts))
;; Merge those parts together that belong to the same kind. The parts
;; list thus becomes a kind of alist, indexed by the number kind.
(let ((new-parts '()))
(dolist (type parts)
(let* ((kind (second type))
(other (find kind new-parts :key #'second)))
(if other
(setf (cddr other) (intervals-union (cddr other) (cddr type) kind))
(push (list* 'INTERVALS kind (cddr type)) new-parts))))
(nreverse new-parts)))
(lambda (type1 type2parts try-prove-no)
(let ((kind1 (second type1))
(intervals1 (cddr type1)))
(dolist (type2 type2parts)
(let ((kind2 (second type2))
(intervals2 (cddr type2)))
(when (real-types-subtypep kind1 kind2)
(when (intervals-subtypep intervals1 (intervals-mapto intervals2 kind1))
(yes)))))
;; Handle disjoint unions: REAL == RATIONAL u FLOAT,
;; FLOAT == SHORT-FLOAT u SINGLE-FLOAT u DOUBLE-FLOAT u LONG-FLOAT,
;; through recursion.
;; (Think of (FLOAT 0.0 1.0) and
;; (OR (SHORT-FLOAT 0.0s0 1.0s0) (SINGLE-FLOAT 0.0f0 1.0f0)
;; (DOUBLE-FLOAT 0.0d0 1.0d0) (LONG-FLOAT 0.0L0 1.0L0)) ...)
(when (and (eq kind1 'REAL)
; No possible win if the type2parts are only REAL.
(intersection (mapcar #'second type2parts)
'(RATIONAL INTEGER FLOAT SHORT-FLOAT
SINGLE-FLOAT DOUBLE-FLOAT LONG-FLOAT)))
(when (and (let ((type1a (simplify-and-REAL (list type1 'RATIONAL))))
(or (eq type1a 'NIL)
(subtypep-REAL type1a type2parts nil)))
(let ((type1b (simplify-and-REAL (list type1 'FLOAT))))
(or (eq type1b 'NIL)
(subtypep-REAL type1b type2parts nil))))
(yes)))
(when (and (eq kind1 'FLOAT)
; No possible win if the type2parts are only FLOAT and REAL.
(intersection (mapcar #'second type2parts)
'(SHORT-FLOAT SINGLE-FLOAT DOUBLE-FLOAT
LONG-FLOAT)))
(when (and (let ((type1a (simplify-and-REAL (list type1 'SHORT-FLOAT))))
(or (eq type1a 'NIL)
(subtypep-REAL type1a type2parts nil)))
(let ((type1b (simplify-and-REAL (list type1 'SINGLE-FLOAT))))
(or (eq type1b 'NIL)
(subtypep-REAL type1b type2parts nil)))
(let ((type1c (simplify-and-REAL (list type1 'DOUBLE-FLOAT))))
(or (eq type1c 'NIL)
(subtypep-REAL type1c type2parts nil)))
(let ((type1d (simplify-and-REAL (list type1 'LONG-FLOAT))))
(or (eq type1d 'NIL)
(subtypep-REAL type1d type2parts nil))))
(yes)))
;; Similarly, RATIONAL == RATIO u INTEGER.
;; (Think of (RATIONAL -1 1) and
;; (OR (INTEGER * *) (RATIONAL -1 (0)) (RATIONAL (0) 1)) ...)
(when (and (eq kind1 'RATIONAL)
; No possible win if the type2parts are only RATIONAL and REAL.
(intersection (mapcar #'second type2parts) '(INTEGER)))
(when (and ; Look at the INTEGER part only:
(let ((type1a (simplify-and-REAL (list type1 'INTEGER))))
(or (eq type1a 'NIL)
(subtypep-REAL type1a type2parts nil)))
; Look at the RATIO part only:
(let ((type2b (find 'RATIONAL type2parts :key #'second)))
(and type2b
(subtypep-REAL type1
`((INTERVALS RATIONAL ,@(intervals-integer-closure (cddr type2b))))
nil))))
(yes)))
(when try-prove-no
;; All checks have already been done above.
(no))
(unknown)))
)
;; Subtypep for elements of the list
;; (REAL RATIONAL INTEGER FLOAT SHORT-FLOAT SINGLE-FLOAT DOUBLE-FLOAT LONG-FLOAT):
(defun real-types-subtypep (kind1 kind2)
(or (eq kind1 kind2)
(eq kind2 'REAL)
(and (eq kind2 'RATIONAL) (eq kind1 'INTEGER))
(and (eq kind2 'FLOAT)
(or (eq kind1 'SHORT-FLOAT) (eq kind1 'SINGLE-FLOAT)
(eq kind1 'DOUBLE-FLOAT) (eq kind1 'LONG-FLOAT)))))
;; Auxiliary functions working on interval lists: ([lo-bound hi-bound]*).
;; Each interval gives rise to 4 variables:
;; lo-incl lo-excl - inclusive and exclusive lower bound,
;; hi-incl hi-excl - inclusive and exclusive upper bound.
;; Missing bounds indicate -infty (for lo) or infty (for hi).
(defun interval-lolo-<= (lo1-incl lo1-excl lo2-incl lo2-excl)
(if lo1-incl
(if lo2-incl (<= lo1-incl lo2-incl) (if lo2-excl (<= lo1-incl lo2-excl) nil))
(if lo1-excl
(if lo2-incl (< lo1-excl lo2-incl) (if lo2-excl (<= lo1-excl lo2-excl) nil))
t)))
(defun interval-lolo-< (lo1-incl lo1-excl lo2-incl lo2-excl)
(if lo1-incl
(if lo2-incl (< lo1-incl lo2-incl) (if lo2-excl (< lo1-incl lo2-excl) nil))
(if lo1-excl
(if lo2-incl (< lo1-excl lo2-incl) (if lo2-excl (< lo1-excl lo2-excl) nil))
(if (or lo2-incl lo2-excl) t nil))))
(defun interval-hihi-<= (hi1-incl hi1-excl hi2-incl hi2-excl)
(if hi1-incl
(if hi2-incl (<= hi1-incl hi2-incl) (if hi2-excl (< hi1-incl hi2-excl) t))
(if hi1-excl
(if hi2-incl (<= hi1-excl hi2-incl) (if hi2-excl (<= hi1-excl hi2-excl) t))
(if (or hi2-incl hi2-excl) nil t))))
(defun interval-hihi-< (hi1-incl hi1-excl hi2-incl hi2-excl)
(if hi1-incl
(if hi2-incl (< hi1-incl hi2-incl) (if hi2-excl (< hi1-incl hi2-excl) t))
(if hi1-excl
(if hi2-incl (< hi1-excl hi2-incl) (if hi2-excl (< hi1-excl hi2-excl) t))
nil)))
; Tests whether the interval [lo,hi] is nonempty.
(defun interval-lohi-<= (lo-incl lo-excl hi-incl hi-excl)
(if lo-incl
(if hi-incl (<= lo-incl hi-incl) (if hi-excl (< lo-incl hi-excl) t))
(if lo-excl
(if hi-incl (< lo-excl hi-incl) (if hi-excl (< lo-excl hi-excl) t))
t)))
; Tests whether there are numbers not covered by (-infty,hi] u [lo,infty).
(defun interval-hilo-< (hi-incl hi-excl lo-incl lo-excl)
(if hi-incl
(if lo-incl (< hi-incl lo-incl) (if lo-excl (< hi-incl lo-excl) nil))
(if hi-excl
(if lo-incl (< hi-excl lo-incl) (if lo-excl (<= hi-excl lo-excl) nil))
nil)))
; Maps an interval list to a given number type.
(defun intervals-mapto (intervals kind)
(let ((new-intervals '()))
(do ((l intervals (cddr l)))
((endp l))
(let* ((lo (car l))
(lo-incl (and (realp lo) lo))
(lo-excl (and (consp lo) (car lo)))
(hi (cadr l))
(hi-incl (and (realp hi) hi))
(hi-excl (and (consp hi) (car hi))))
(flet ((mapto (value kind)
(case kind
(RATIONAL (values (rational value) nil))
(INTEGER (values (ceiling value) nil))
((FLOAT LONG-FLOAT)
(if (rationalp value)
(let ((x (coerce value kind)))
(if (= x value)
(values x nil)
;; Keep the rational number, because there is
;; no smallest FLOAT > value.
(values value t)))
(values value nil)))
(t (values (coerce value kind) nil)))))
(cond (lo-incl
(multiple-value-bind (x force-excl) (mapto lo-incl kind)
(if (or (< x lo-incl) force-excl)
(setq lo-excl x lo-incl nil)
(setq lo-incl x))))
(lo-excl
(let ((x (mapto lo-excl kind)))
(if (<= x lo-excl)
(setq lo-excl x)
(setq lo-incl x lo-excl nil))))))
(flet ((mapto (value kind)
(case kind
(RATIONAL (values (rational value) nil))
(INTEGER (values (floor value) nil))
((FLOAT LONG-FLOAT)
(if (rationalp value)
(let ((x (coerce value kind)))
(if (= x value)
(values x nil)
;; Keep the rational number, because there is
;; no smallest FLOAT < value.
(values value t)))
(values value nil)))
(t (values (coerce value kind) nil)))))
(cond (hi-incl
(multiple-value-bind (x force-excl) (mapto hi-incl kind)
(if (or (> x hi-incl) force-excl)
(setq hi-excl x hi-incl nil)
(setq hi-incl x))))
(hi-excl
(let ((x (mapto hi-excl kind)))
(if (>= x hi-excl)
(setq hi-excl x)
(setq hi-incl x hi-excl nil))))))
(when (eq kind 'INTEGER)
(when lo-excl (setq lo-incl (+ lo-excl 1) lo-excl nil))
(when hi-excl (setq hi-incl (- hi-excl 1) hi-excl nil)))
(when (interval-lohi-<= lo-incl lo-excl hi-incl hi-excl)
(push (if lo-incl lo-incl (if lo-excl `(,lo-excl) '*)) new-intervals)
(push (if hi-incl hi-incl (if hi-excl `(,hi-excl) '*)) new-intervals))))
(nreverse new-intervals)))
; Returns the intersection of two interval lists, assuming the same number type.
(defun intervals-intersection (intervals1 intervals2)
(if (and intervals1 intervals2)
(let ((new-intervals '())
lo1-incl lo1-excl hi1-incl hi1-excl
lo2-incl lo2-excl hi2-incl hi2-excl)
(macrolet ((advance1 ()
'(let ((lo (car intervals1)) (hi (cadr intervals1)))
(setq lo1-incl (and (realp lo) lo))
(setq lo1-excl (and (consp lo) (car lo)))
(setq hi1-incl (and (realp hi) hi))
(setq hi1-excl (and (consp hi) (car hi)))
(setq intervals1 (cddr intervals1))))
(advance2 ()
'(let ((lo (car intervals2)) (hi (cadr intervals2)))
(setq lo2-incl (and (realp lo) lo))
(setq lo2-excl (and (consp lo) (car lo)))
(setq hi2-incl (and (realp hi) hi))
(setq hi2-excl (and (consp hi) (car hi)))
(setq intervals2 (cddr intervals2)))))
(advance1)
(advance2)
(block outer-loop
(loop
;; Search the start of a common interval.
(loop
(cond ((not (interval-lohi-<= lo2-incl lo2-excl hi1-incl hi1-excl))
(when (null intervals1) (return-from outer-loop))
(advance1))
((not (interval-lohi-<= lo1-incl lo1-excl hi2-incl hi2-excl))
(when (null intervals2) (return-from outer-loop))
(advance2))
(t (return))))
(multiple-value-bind (lo-incl lo-excl)
(if (interval-lolo-<= lo1-incl lo1-excl lo2-incl lo2-excl)
(values lo2-incl lo2-excl)
(values lo1-incl lo1-excl))
(push (if lo-incl lo-incl (if lo-excl `(,lo-excl) '*))
new-intervals)
;; Seach the end of the common interval.
(if (interval-hihi-<= hi1-incl hi1-excl hi2-incl hi2-excl)
(progn
(push (if hi1-incl hi1-incl (if hi1-excl `(,hi1-excl) '*))
new-intervals)
(when (null intervals1) (return-from outer-loop))
(advance1))
(progn
(push (if hi2-incl hi2-incl (if hi2-excl `(,hi2-excl) '*))
new-intervals)
(when (null intervals2) (return-from outer-loop))
(advance2)))))))
(nreverse new-intervals))
'()))
; Returns the union of two interval lists, assuming the same number type.
(defun intervals-union (intervals1 intervals2 kind)
(if (and intervals1 intervals2)
(let ((new-intervals '())
lo1-incl lo1-excl (hi1-incl 'uninitialized) hi1-excl
lo2-incl lo2-excl (hi2-incl 'uninitialized) hi2-excl)
(macrolet ((halfadvance1 ()
'(let ((lo (car intervals1)))
(setq lo1-incl (and (realp lo) lo))
(setq lo1-excl (and (consp lo) (car lo)))))
(halfadvance2 ()
'(let ((lo (car intervals2)))
(setq lo2-incl (and (realp lo) lo))
(setq lo2-excl (and (consp lo) (car lo)))))
(advance1 ()
'(let ((hi (cadr intervals1)) (lo (caddr intervals1)))
(setq hi1-incl (and (realp hi) hi))
(setq hi1-excl (and (consp hi) (car hi)))
(setq lo1-incl (and (realp lo) lo))
(setq lo1-excl (and (consp lo) (car lo)))
(setq intervals1 (cddr intervals1))))
(advance2 ()
'(let ((hi (cadr intervals2)) (lo (caddr intervals2)))
(setq hi2-incl (and (realp hi) hi))
(setq hi2-excl (and (consp hi) (car hi)))
(setq lo2-incl (and (realp lo) lo))
(setq lo2-excl (and (consp lo) (car lo)))
(setq intervals2 (cddr intervals2)))))
(halfadvance1)
(halfadvance2)
(block outer-loop
(tagbody start
;; Search the start of a union interval.
(if (interval-lolo-<= lo1-incl lo1-excl lo2-incl lo2-excl)
(progn
(push (if lo1-incl lo1-incl (if lo1-excl `(,lo1-excl) '*))
new-intervals)
(go label1))
(progn
(push (if lo2-incl lo2-incl (if lo2-excl `(,lo2-excl) '*))
new-intervals)
(go label2)))
;; Seach the end of the union interval.
label1
(advance1)
(when (null intervals1)
(loop
(cond ((and intervals2
(not (interval-hilo-< hi1-incl hi1-excl
lo2-incl lo2-excl)))
(advance2))
(t (return))))
(return-from outer-loop))
(when (not (interval-hilo-< hi1-incl hi1-excl lo2-incl lo2-excl))
(go label2))
(push (if hi1-incl hi1-incl (if hi1-excl `(,hi1-excl) '*))
new-intervals)
(go start)
label2
(advance2)
(when (null intervals2)
(loop
(cond ((and intervals1
(not (interval-hilo-< hi2-incl hi2-excl
lo1-incl lo1-excl)))
(advance1))
(t (return))))
(return-from outer-loop))
(when (not (interval-hilo-< hi2-incl hi2-excl lo1-incl lo1-excl))
(go label1))
(push (if hi2-incl hi2-incl (if hi2-excl `(,hi2-excl) '*))
new-intervals)
(go start)))
(if (cond ((eq hi1-incl 'uninitialized) t)
((eq hi2-incl 'uninitialized) nil)
(t (interval-hihi-<= hi1-incl hi1-excl hi2-incl hi2-excl)))
(push (if hi2-incl hi2-incl (if hi2-excl `(,hi2-excl) '*))
new-intervals)
(push (if hi1-incl hi1-incl (if hi1-excl `(,hi1-excl) '*))
new-intervals)))
(setq new-intervals (nreconc new-intervals (or intervals1 intervals2)))
;; Simplify [x,y] u (y,z] and [x,y) u [y,z] to [x,z].
(do ((l new-intervals))
((null (cddr l)))
(let* ((hi (cadr l))
(hi-incl (and (realp hi) hi))
(hi-excl (and (consp hi) (car hi)))
(lo (caddr l))
(lo-incl (and (realp lo) lo))
(lo-excl (and (consp lo) (car lo))))
(if (or (and hi-incl lo-excl (= lo-excl hi-incl))
(and hi-excl lo-incl (= lo-incl hi-excl))
(and (eq kind 'INTEGER)
hi-incl lo-incl (eql lo-incl (1+ hi-incl))))
(setf (cdr l) (cdddr l))
(setq l (cddr l)))))
new-intervals)
(or intervals1 intervals2)))
; Tests whether intervals1 is contained in intervals2, assuming the same number
; type.
(defun intervals-subtypep (intervals1 intervals2)
(if intervals1
(if intervals2
(let (lo1-incl lo1-excl hi1-incl hi1-excl
lo2-incl lo2-excl hi2-incl hi2-excl)
(macrolet ((advance1 ()
'(let ((lo (car intervals1)) (hi (cadr intervals1)))
(setq lo1-incl (and (realp lo) lo))
(setq lo1-excl (and (consp lo) (car lo)))
(setq hi1-incl (and (realp hi) hi))
(setq hi1-excl (and (consp hi) (car hi)))
(setq intervals1 (cddr intervals1))))
(advance2 ()
'(let ((lo (car intervals2)) (hi (cadr intervals2)))
(setq lo2-incl (and (realp lo) lo))
(setq lo2-excl (and (consp lo) (car lo)))
(setq hi2-incl (and (realp hi) hi))
(setq hi2-excl (and (consp hi) (car hi)))
(setq intervals2 (cddr intervals2)))))
(advance1)
(advance2)
(loop
(when (not (interval-lolo-<= lo2-incl lo2-excl lo1-incl lo1-excl))
(return-from intervals-subtypep nil))
(if (interval-hilo-< hi2-incl hi2-excl lo1-incl lo1-excl)
(progn
(when (null intervals2)
(return-from intervals-subtypep nil))
(advance2))
(progn
(when (not (interval-hihi-<= hi1-incl hi1-excl hi2-incl hi2-excl))
(return-from intervals-subtypep nil))
(when (null intervals1)
(return-from intervals-subtypep t))
(advance1))))))
nil)
t))
; Tests whether a given object is covered by the interval.
(defun intervals-typep (intervals obj)
(do ((l intervals (cddr l)))
((endp l) nil)
(let* ((lo (car l))
(lo-incl (and (realp lo) lo))
(lo-excl (and (consp lo) (car lo)))
(hi (cadr l))
(hi-incl (and (realp hi) hi))
(hi-excl (and (consp hi) (car hi))))
(when (and (if lo-incl (<= lo-incl obj) (if lo-excl (< lo-excl obj) t))
(if hi-incl (<= obj hi-incl) (if hi-excl (< obj hi-excl) t)))
(return t)))))
; Returns the intervals, with exclusive integer bounds replaced with inclusive
; integer bounds. Implicitly, kind = RATIONAL.
(defun intervals-integer-closure (intervals)
(let ((new-intervals '()))
(do ((l intervals (cddr l)))
((endp l))
(let* ((lo (car l))
(lo-incl (and (realp lo) lo))
(lo-excl (and (consp lo) (car lo)))
(hi (cadr l))
(hi-incl (and (realp hi) hi))
(hi-excl (and (consp hi) (car hi))))
(when (integerp lo-excl) (setq lo-incl lo-excl lo-excl nil))
(when (integerp hi-excl) (setq hi-incl hi-excl hi-excl nil))
(setq new-intervals
(list* (if hi-incl hi-incl (if hi-excl `(,hi-excl) '*))
(if lo-incl lo-incl (if lo-excl `(,lo-excl) '*))
new-intervals))))
(setq new-intervals (nreverse new-intervals))
;; Simplify [x,y] u [y,z] and [x,y] u (y,z] and [x,y) u [y,z] to [x,z].
(do ((l new-intervals))
((null (cddr l)))
(let* ((hi (cadr l))
(hi-incl (and (realp hi) hi))
(hi-excl (and (consp hi) (car hi)))
(lo (caddr l))
(lo-incl (and (realp lo) lo))
(lo-excl (and (consp lo) (car lo))))
(if (or (and hi-incl lo-incl (= lo-incl hi-incl))
(and hi-incl lo-excl (= lo-excl hi-incl))
(and hi-excl lo-incl (= lo-incl hi-excl)))
(setf (cdr l) (cdddr l))
(setq l (cddr l)))))
new-intervals))
; Returns the intervals minus a given singleton, assuming it's of the right
; number type.
(defun intervals-remove-one (intervals kind obj)
(let ((new-intervals '()))
(flet ((cons-new-interval (lo-incl lo-excl hi-incl hi-excl kind new-intervals)
(when (eq kind 'INTEGER)
(when lo-excl (setq lo-incl (+ lo-excl 1) lo-excl nil))
(when hi-excl (setq hi-incl (- hi-excl 1) hi-excl nil)))
(if (interval-lohi-<= lo-incl lo-excl hi-incl hi-excl)
(list* (if hi-incl hi-incl (if hi-excl `(,hi-excl) '*))
(if lo-incl lo-incl (if lo-excl `(,lo-excl) '*))
new-intervals)
new-intervals)))
(macrolet ((add-new-interval (lo-incl lo-excl hi-incl hi-excl)
`(setq new-intervals
(cons-new-interval ,lo-incl ,lo-excl ,hi-incl ,hi-excl kind
new-intervals))))
(do ((l intervals (cddr l)))
((endp l))
(let* ((lo (car l))
(lo-incl (and (realp lo) lo))
(lo-excl (and (consp lo) (car lo)))
(hi (cadr l))
(hi-incl (and (realp hi) hi))
(hi-excl (and (consp hi) (car hi))))
(if (and (if lo-incl (<= lo-incl obj) (if lo-excl (< lo-excl obj) t))
(if hi-incl (<= obj hi-incl) (if hi-excl (< obj hi-excl) t)))
(progn
(add-new-interval lo-incl lo-excl nil obj)
(add-new-interval nil obj hi-incl hi-excl))
(add-new-interval lo-incl lo-excl hi-incl hi-excl))))))
(nreverse new-intervals)))
;; Remove a single object from the type. The type is of the form
;; (kind [lo-bound hi-bound]+). The result is a type in the same form, or
;; an `(OR ...) of types in the same form, or NIL.
(defun subtypep-REAL-remove-singleton (type obj)
(let* ((kind (if (atom type) type (second type)))
(intervals (if (atom type) '(* *) (cddr type)))
(test (get kind 'TYPE-SYMBOL)))
(if (and (funcall test obj) (intervals-typep intervals obj))
(let ((splittypes
(case kind
;; Have to split the type before removing obj. For example,
;; (AND REAL (NOT (EQL 0))) is equivalent to
;; (OR (RATIONAL * (0) (0) *) FLOAT), not (REAL * (0) (0) *).
(REAL
(remove 'NIL
(list (subtypep-REAL-remove-singleton
`(INTERVALS RATIONAL ,@(intervals-mapto intervals 'RATIONAL)) obj)
(subtypep-REAL-remove-singleton
`(INTERVALS FLOAT ,@(intervals-mapto intervals 'FLOAT)) obj))))
(FLOAT
(remove 'NIL
(list (subtypep-REAL-remove-singleton
`(INTERVALS SHORT-FLOAT ,@(intervals-mapto intervals 'SHORT-FLOAT)) obj)
(subtypep-REAL-remove-singleton
`(INTERVALS SINGLE-FLOAT ,@(intervals-mapto intervals 'SINGLE-FLOAT)) obj)
(subtypep-REAL-remove-singleton
`(INTERVALS DOUBLE-FLOAT ,@(intervals-mapto intervals 'DOUBLE-FLOAT)) obj)
(subtypep-REAL-remove-singleton
`(INTERVALS LONG-FLOAT ,@(intervals-mapto intervals 'LONG-FLOAT)) obj))))
(t
(setq intervals (intervals-remove-one intervals kind obj))
(if intervals (list `(INTERVALS ,kind ,@intervals)) '())))))
(case (length splittypes)
(0 'NIL)
(1 (first splittypes))
(t `(OR ,@splittypes))))
type)))
(def-type-category CHARACTER (CHARACTER) (CHARACTER-INTERVALS)
;; Each part is of the form (CHARACTER-INTERVALS [lo-bound hi-bound]+), a
;; non-empty list of disjoint intervals, in ascending order, or an encoding.
;; This allows manipulating encoding as true sets of characters.
;; TODO: This needs an update when we use upgraded-complex-element-type.
(lambda (parts)
;; Simplify `(AND ,@parts):
;; First, simplify encodings that cover the whole character range.
(setq parts (mapcar #'subtypep-CHARACTER-pre-simplify parts))
(setq parts (remove 'CHARACTER parts))
(case (length parts)
(0 'CHARACTER)
(1 (first parts))
(t
;; Intersect the interval ranges.
(let ((intervals
(reduce #'intervals-intersection parts
:key #'(lambda (type)
(if (encodingp type)
(map 'list #'char-code (get-charset-range (encoding-charset type)))
(rest type))))))
(if intervals
`(CHARACTER-INTERVALS ,@intervals)
'NIL)))))
(lambda (parts)
;; First, simplify encodings that cover the whole character range.
(setq parts (mapcar #'subtypep-CHARACTER-pre-simplify parts))
parts)
(lambda (type1 type2parts try-prove-no)
;; Try to work out things without expanding encodings to intervals unless
;; really needed.
(when (member 'CHARACTER type2parts)
(yes))
(cond ((encodingp type1)
(when (member type1 type2parts)
(yes))
#| ;; Shortcut that avoids consing but makes testing harder.
(when (and (eql (length type2parts) 1) (encodingp (first type2parts)))
(when (charset-subtypep type1 (first type2parts))
(yes))
(when try-prove-no (no))
(unknown))
|#
(let ((intervals
(map 'list #'char-code (get-charset-range (encoding-charset type1)))))
(setq type1 `(CHARACTER-INTERVALS ,@intervals))))
((eq type1 'CHARACTER)
(setq type1 '(CHARACTER-INTERVALS 0 #,char-code-limit))))
;; Now type1 is in `(CHARACTER-INTERVALS ,@intervals) form.
(assert (eq (first type1) 'CHARACTER-INTERVALS))
(let ((intervals1 (rest type1)))
;; First pass, ignoring encodings on the right-hand side.
(dolist (type2 type2parts)
(unless (encodingp type2)
(assert (eq (first type2) 'CHARACTER-INTERVALS))
(let ((intervals2 (rest type2)))
(when (intervals-subtypep intervals1 intervals2)
(yes)))))
;; Now we need to expand the encodings on the right-hand side.
(setq type2parts
(mapcar #'(lambda (type2)
(if (encodingp type2)
(let ((intervals
(map 'list #'char-code (get-charset-range (encoding-charset type2)))))
(when (intervals-subtypep intervals1 intervals)
(yes))
`(CHARACTER-INTERVALS ,@intervals))
type2))
type2parts))
;; Now all the type2parts are in `(CHARACTER-INTERVALS ,@intervals) form.
(when (> (length type2parts) 1)
(let ((intervals2 (reduce #'intervals-union type2parts :key #'rest)))
(when (intervals-subtypep intervals1 intervals2)
(yes))))
(when try-prove-no
;; All checks have already been done above.
(no))
(unknown)))
)
;; Simplify an encoding that covers the whole character range.
(defun subtypep-CHARACTER-pre-simplify (type)
(if (encodingp type)
(let ((charset (encoding-charset type)))
(case charset
#+UNICODE
((charset:unicode-16-big-endian charset:unicode-16-little-endian
charset:unicode-32-big-endian charset:unicode-32-little-endian
charset:utf-8 charset:java)
'CHARACTER)
(t
(if (and (stringp charset)
(or (string= charset "UTF-16") (string= charset "UTF-7")))
'CHARACTER
type))))
type))
;; Remove a single object from the type. The type is of the form
;; (CHARACTER [lo-bound hi-bound]+). The result is a type in the same form,
;; or NIL.
(defun subtypep-CHARACTER-remove-singleton (type obj)
(let ((intervals (if (atom type) '(* *) (rest type))))
(if (and (characterp obj) (intervals-typep intervals (char-code obj)))
(progn
(setq intervals (intervals-remove-one intervals 'INTEGER (char-code obj)))
(if intervals `(CHARACTER-INTERVALS ,@intervals) 'NIL))
type)))
;; Conversion of an encoding to a list of intervals.
#+UNICODE
(defun get-charset-range (charset &optional maxintervals)
(let ((table #,(make-hash-table :key-type '(or string symbol)
:value-type 'simple-string
:test 'stablehash-equal
:warn-if-needs-rehash-after-gc t)))
;; cache: charset name -> list of intervals #(start1 end1 ... startm endm)
#| ; Now in C and much more efficient.
(defun charset-range (encoding start end)
(setq start (char-code start))
(setq end (char-code end))
(let ((intervals '()) ; finished intervals
(i1 nil) (i2 nil) ; interval being built
(i start))
(loop
(if (charset-typep (code-char i) encoding)
(if i2 (setq i2 i) (setq i1 i i2 i))
(if i2 (setq intervals (list* i2 i1 intervals) i1 nil i2 nil)))
(when (eql i end) (return))
(incf i))
(when i2 (setq intervals (list* i2 i1 intervals)))
(map 'simple-string #'code-char (nreverse intervals))))
|#
;; Return the definition range of a character set. If necessary, compute it
;; and store it in the cache.
(or (gethash charset table)
(setf (gethash charset table)
(charset-range (make-encoding :charset charset)
(code-char 0) (code-char (1- char-code-limit))
maxintervals)))))
#| ;; Older code for a special case.
;; Test whether all characters encodable in encoding1 are also encodable in
;; encoding2.
(defun charset-subtypep (encoding1 encoding2)
#-UNICODE (declare (ignore encoding1 encoding2)) #-UNICODE t
#+UNICODE
(let* ((intervals1 (get-charset-range (encoding-charset encoding1)))
(intervals2 (get-charset-range (encoding-charset encoding2)))
(n1 (length intervals1))
(n2 (length intervals2))
(jj1 0) ; grows by 2 from 0 to n1
(jj2 0)) ; grows by 2 from 0 to n2
(loop
;; Get next interval from intervals1.
(when (eql jj1 n1) (return-from charset-subtypep t))
(let ((i1 (schar intervals1 jj1)) (i2 (schar intervals1 (+ jj1 1))))
;; Test whether [i1,i2] is contained in intervals2.
(let (i3 i4)
(loop
(when (eql jj2 n2) ; [i1,i2] not contained in intervals2.
(return-from charset-subtypep nil))
(setq i3 (schar intervals2 jj2))
(setq i4 (schar intervals2 (+ jj2 1)))
;; If i3 <= i4 < i1 <= i2, skip the interval [i3,i4].
(when (char>= i4 i1) (return))
(incf jj2 2))
(when (char< i1 i3) ; i1 not contained in intervals2.
(return-from charset-subtypep nil))
(when (char< i4 i2) ; i4+1 (in [i1,i2]) not contained in intervals2.
(return-from charset-subtypep nil))
;; Now (<= i3 i1) and (<= i2 i4),
;; hence [i1,i2] is contained in intervals2.
(incf jj1 2))))))
|#
(def-type-category PATHNAME (PATHNAME LOGICAL-PATHNAME) ()
;; Each part is PATHNAME or LOGICAL-PATHNAME.
(lambda (parts)
(cond #+LOGICAL-PATHNAMES ((member 'LOGICAL-PATHNAME parts) 'LOGICAL-PATHNAME)
(t 'PATHNAME)))
(lambda (parts)
(cond ((member 'PATHNAME parts) (list 'PATHNAME))
#+LOGICAL-PATHNAMES ((member 'LOGICAL-PATHNAME parts) (list 'LOGICAL-PATHNAME))
(t '())))
(lambda (type1 type2parts try-prove-no)
(when (and type2parts
#+LOGICAL-PATHNAMES (or (eq type1 'LOGICAL-PATHNAME)
(eq (first type2parts) 'PATHNAME)))
(yes))
(when try-prove-no
;; All checks have already been done above.
(no))
(unknown))
)
;; Miscellaneous types that each form their own category.
(def-type-category #:misc () ()
(lambda (parts)
; All parts are the same.
(first parts))
(lambda (parts)
parts)
(lambda (type1 type2parts try-prove-no)
(declare (ignore type1))
(when type2parts (yes))
(when try-prove-no (no))
(unknown))
)
(def-misc-type-category ENCODING)
(def-misc-type-category HASH-TABLE)
(def-misc-type-category PACKAGE)
(def-misc-type-category RANDOM-STATE)
(def-misc-type-category READTABLE)
(def-misc-type-category SYMBOL)
(def-misc-type-category BYTE)
(def-misc-type-category SPECIAL-OPERATOR)
(def-misc-type-category LOAD-TIME-EVAL)
(def-misc-type-category SYMBOL-MACRO)
#+(or UNIX FFI WIN32)
(def-misc-type-category FOREIGN-POINTER)
#+FFI
(def-misc-type-category FFI::FOREIGN-ADDRESS)
#+FFI
(def-misc-type-category FFI::FOREIGN-VARIABLE)
(def-misc-type-category WEAK-POINTER)
(def-misc-type-category READ-LABEL)
(def-misc-type-category FRAME-POINTER)
(def-misc-type-category SYSTEM-INTERNAL)
(def-type-category STRUCTURE-OBJECT () ()
;; Each part is a CLOS class of metaclass <structure-class>.
;; Exploit the fact that this metaclass supports no multiple inheritance.
(lambda (parts)
;; Simplify `(AND ,@parts):
(if (rest parts)
(let ((minimal-class (first parts)))
(dolist (other-class (rest parts) minimal-class)
(cond ((clos::subclassp minimal-class other-class))
((clos::subclassp other-class minimal-class)
(setq minimal-class other-class))
(t
;; No multiple inheritance -> minimal-class and other-class
;; can have no common subclass.
(return 'NIL)))))
(first parts)))
(lambda (parts)
;; It's not worth simplifying.
parts)
(lambda (type1 type2parts try-prove-no)
;; We actually need to test (clos::subclassp type1 class2) only for
;; those class2 that are maximal among type2parts. But it's not worth
;; determining the maximal classes. Just process them all.
(dolist (class2 type2parts)
(when (clos::subclassp type1 class2)
(yes)))
(when try-prove-no
;; All checks already done. Any instance of class1 would be a testimony.
(no))
(unknown))
)
(def-type-category STANDARD-OBJECT () (FUNCTION)
;; Each part is
;; a CLOS class of metaclass <standard-class> or <funcallable-standard-class>,
;; or <function>, of metaclass <built-in-class>,
;; or of the form (FUNCTION ...).
(lambda (parts)
;; Simplify `(AND ,@parts):
(cond #+FFI
((member 'FFI::FOREIGN-FUNCTION parts)
(let ((other-parts
(set-difference parts
(list (find-class 'FUNCTION) #+FFI 'FFI::FOREIGN-FUNCTION))))
(if (some #'atom other-parts)
'NIL
(if (null other-parts)
'FFI::FOREIGN-FUNCTION
`(AND ,@parts)))))
(t (when (some #'consp parts)
; If some part is (FUNCTION ...), #<class FUNCTION> is redundant.
(setq parts (remove (find-class 'FUNCTION) parts)))
(if (rest parts) `(AND ,@parts) (first parts)))))
(lambda (parts)
;; It's not worth simplifying the intersection of parts with
;; '(FUNCTION #+FFI FFI::FOREIGN-FUNCTION).
parts)
(lambda (type1 type2parts try-prove-no)
;; Under <standard-object>, any set of classes can have a common subclass
;; (you only need to be careful about the order of the superclasses when
;; you define the subclass, to avoid an error when computing the CPL)
;; and therefore also a common instance.
(cond #+FFI
((eq type1 'FFI::FOREIGN-FUNCTION)
(when (intersection type2parts
(list (find-class 'FUNCTION) #+FFI 'FFI::FOREIGN-FUNCTION))
(yes)))
((and (consp type1) (eq (car type1) 'FUNCTION)) ; (FUNCTION ...)
(when (member (find-class 'FUNCTION) type2parts)
(yes))
(when (member type1 type2parts :test #'canonicalized-types-equal-p)
(yes)))
(t (let ((type1parts
(if (consp type1)
(progn (assert (eq (first type1) 'AND)) (rest type1))
(list type1))))
(dolist (class1 type1parts)
(if (consp class1) ; (FUNCTION ...)
(when (member class1 type2parts :test #'canonicalized-types-equal-p)
(yes))
(dolist (class2 type2parts)
(multiple-value-bind (is known)
(indefinite-subclassp class1 class2)
(declare (ignore known))
(when is
(yes)))))))))
(when try-prove-no
;; For classes, all checks already done. Any common instance of type1
;; would be a testimony.
(unless (or (consp type1) (some #'consp type2parts))
(no)))
(unknown))
)
;; (indefinite-subclassp class1 class2) is like (clos::subclassp class1 class2),
;; except that it doesn't signal an error if class1 is not finalizable, and
;; it has the same return value convention as SUBTYPEP: NIL, NIL for
;; "unknown"; boolean, T for a definite result.
(defun indefinite-subclassp (class1 class2)
;; Can we guarantee that every class with metaclass <standard-class> will be
;; a subclass of <standard-object>? I don't think so, because the user can
;; play weird games by installing methods on VALIDATE-SUPERCLASSES.
#|
(when (and (eq (class-of class1) clos::<standard-class>)
(eq class2 clos::<standard-object>))
(return-from indefinite-subclassp (values t t)))
|#
;; Recurse through the known direct superclasses, starting from class1.
;; Use a hash table of the already visited classes, to avoid exponential
;; running time or running into cycles.
(let ((ht (make-hash-table :key-type 'class :value-type '(eql t)
:test 'ext:stablehash-eq :warn-if-needs-rehash-after-gc t))
(definite t))
(labels ((recurse (class)
(unless (gethash class ht) ; don't visit the same class twice
(if (eq class class2)
(return-from indefinite-subclassp (values t t))
(progn
(setf (gethash class ht) t)
(if (clos:class-finalized-p class)
(when (clos::subclassp class class2)
(return-from indefinite-subclassp (values t t)))
(dolist (sc (clos:class-direct-superclasses class))
(if (clos::forward-reference-to-class-p sc)
(setq definite nil)
(recurse sc)))))))))
(recurse class1)
(values nil definite))))
;; Determine the category of the given type.
;; Returns NIL for types about which nothing is known, such as SATISFIES types.
(defun type-category (type)
(macrolet ((case-atomic (expr &rest clauses)
`(CASE ,expr
,@(append (mapcan #'(lambda (category)
(let ((specifiers (get category 'SUBTYPEP-ATOM)))
(if specifiers
(list `(,specifiers ',category))
'())))
*type-categories*)
clauses)))
(case-list (expr &rest clauses)
`(CASE ,expr
,@(append (mapcan #'(lambda (category)
(let ((specifiers (get category 'SUBTYPEP-LIST)))
(if specifiers
(list `(,specifiers ',category))
'())))
*type-categories*)
clauses))))
(if (consp type)
(case-list (first type)
(t 'NIL)) ; SATISFIES and VALUES types cannot be classified.
(case-atomic type
((FUNCTION #+FFI FFI::FOREIGN-FUNCTION)
;; FUNCTION is not a category of its own, because of GENERIC-FUNCTION.
'STANDARD-OBJECT)
(t (cond ((clos::defined-class-p type)
(if (clos::structure-class-p type)
'STRUCTURE-OBJECT
'STANDARD-OBJECT))
((encodingp type) 'CHARACTER)
((symbolp type)
;; Symbols that name CLOS classes have already been mapped
;; the class object by canonicalize-type. No need to handle
;; them here.
'NIL)
(t 'NIL)))))))
;; To efficiently handle ranges of real numbers and characters, the REAL and
;; CHARACTER type categories use the type specifiers
;; (INTERVALS kind [lo-bound hi-bound]+)
;; (CHARACTER-INTERVALS [lo-bound hi-bound]+)
;; We use this type specifier, instead of just (kind [lo-bound hi-bound]+),
;; so that canonicalize-type can do proper error checking and reject malformed
;; type specifiers like (INTEGER 0 1 4 5) or (CHARACTER 0 255). The reason is
;; that canonicalized types can be fed to canonicalize-type again; indeed,
;; the handling of MEMBER types in subtypep-logic, through
;; subtypep-REAL-remove-singleton and subtypep-CHARACTER-remove-singleton,
;; passes a mix of INTERVALS types and canonicalized types to subtypep.
(setf (get 'INTERVALS 'TYPE-LIST)
(function type-list-intervals
(lambda (x kind &rest intervals)
(let ((test (get kind 'TYPE-SYMBOL)))
(and (funcall test x)
(intervals-typep intervals x))))))
(setf (get 'CHARACTER-INTERVALS 'TYPE-LIST)
(function type-list-character-intervals
(lambda (x &rest intervals)
(and (characterp x) (intervals-typep intervals (char-code x))))))
;; (CANONICALIZE-TYPE type) returns a superficially simplified type.
;; The purpose of this function is not to be a complicated simplifier,
;; but rather it only brings the type into a recognizable shape so that
;; SUBTYPEP can work in the right direction. SUBTYPEP is recursive,
;; therefore CANONICALIZE-TYPE does not need to be recursive. But
;; CANONICALIZE-TYPE must prepare for the classification; that's why
;; for example NUMBER becomes '(OR REAL COMPLEX).
;; CANONICALIZE-TYPE also does non-recursive error checking.
(defun canonicalize-type (type
&aux head)
;; Expand DEFTYPE types at the outermost level only.
(setq type (expand-deftype type))
(cond ((symbolp type)
(case type
(ATOM '(NOT CONS))
(BASE-CHAR #+BASE-CHAR=CHARACTER 'CHARACTER
#-BASE-CHAR=CHARACTER '(CHARACTER-INTERVALS 0 #,base-char-code-limit))
(BIGNUM '(AND INTEGER (NOT FIXNUM)))
(BIT '(INTERVALS INTEGER 0 1))
(BOOLEAN '(MEMBER NIL T))
(COMPILED-FUNCTION '(AND FUNCTION (SATISFIES COMPILED-FUNCTION-P)))
(EXTENDED-CHAR #+BASE-CHAR=CHARACTER '(OR) ; NIL
#-BASE-CHAR=CHARACTER '(CHARACTER-INTERVALS #,(1+ base-char-code-limit) #,char-code-limit))
(FIXNUM '(INTERVALS INTEGER #,most-negative-fixnum #,most-positive-fixnum))
(KEYWORD '(AND SYMBOL (SATISFIES KEYWORDP)))
(LIST '(OR CONS (MEMBER NIL)))
((NIL) '(OR))
(NULL '(MEMBER NIL))
(NUMBER '(OR REAL COMPLEX))
(RATIO '(AND RATIONAL (NOT INTEGER)))
(SEQUENCE '(OR LIST VECTOR)) ; user-defined sequences??
(SIGNED-BYTE '(INTERVALS INTEGER * *))
(STANDARD-CHAR '(CHARACTER-INTERVALS #,(char-code #\Newline) #,(char-code #\Newline) #,(char-code #\Space) #,(char-code #\~)))
(STRING-CHAR 'CHARACTER)
((T) '(AND))
(UNSIGNED-BYTE '(INTERVALS INTEGER 0 *))
(ARRAY
; (canonicalize-type (list type)) =>
'(ARRAY))
(SIMPLE-ARRAY
; (canonicalize-type (list type)) =>
'(SIMPLE-ARRAY))
(BIT-VECTOR
; (canonicalize-type (list type)) =>
'(ARRAY BIT (*)))
(SIMPLE-BIT-VECTOR
; (canonicalize-type (list type)) =>
'(SIMPLE-ARRAY BIT (*)))
((STRING cs-cl:string)
; (canonicalize-type (list type)) =>
'(OR (ARRAY CHARACTER (*))
#-BASE-CHAR=CHARACTER (ARRAY BASE-CHAR (*))
(ARRAY NIL (*))))
(SIMPLE-STRING
; (canonicalize-type (list type)) =>
'(OR (SIMPLE-ARRAY CHARACTER (*))
#-BASE-CHAR=CHARACTER (SIMPLE-ARRAY BASE-CHAR (*))
(SIMPLE-ARRAY NIL (*))))
(BASE-STRING
; (canonicalize-type (list type)) =>
'(ARRAY BASE-CHAR (*)))
(SIMPLE-BASE-STRING
; (canonicalize-type (list type)) =>
'(SIMPLE-ARRAY BASE-CHAR (*)))
(VECTOR
; (canonicalize-type (list type)) =>
'(ARRAY * (*)))
(SIMPLE-VECTOR
; (canonicalize-type (list type)) =>
'(SIMPLE-ARRAY T (*)))
(COMPLEX
; (canonicalize-type (list type)) =>
'(COMPLEX))
(REAL
; (canonicalize-type (list type)) =>
'(INTERVALS REAL * *))
(INTEGER
; (canonicalize-type (list type)) =>
'(INTERVALS INTEGER * *))
(RATIONAL
; (canonicalize-type (list type)) =>
'(INTERVALS RATIONAL * *))
(FLOAT
; (canonicalize-type (list type)) =>
'(INTERVALS FLOAT * *))
(SHORT-FLOAT
; (canonicalize-type (list type)) =>
'(INTERVALS SHORT-FLOAT * *))
(SINGLE-FLOAT
; (canonicalize-type (list type)) =>
'(INTERVALS SINGLE-FLOAT * *))
(DOUBLE-FLOAT
; (canonicalize-type (list type)) =>
'(INTERVALS DOUBLE-FLOAT * *))
(LONG-FLOAT
; (canonicalize-type (list type)) =>
'(INTERVALS LONG-FLOAT * *))
((FUNCTION STREAM FILE-STREAM SYNONYM-STREAM BROADCAST-STREAM
CONCATENATED-STREAM TWO-WAY-STREAM ECHO-STREAM STRING-STREAM)
;; We treat FUNCTION like a CLOS class, so that
;; (subtypep 'GENERIC-FUNCTION FUNCTION) can return T.
;; We treat STREAM and subclasses like CLOS classes, so that
;; (subtypep 'FUNDAMENTAL-STREAM 'STREAM) can return T.
(or (clos-class type) type))
;; Misc type categories, excluding those that are CLOS classes.
((ENCODING BYTE SPECIAL-OPERATOR LOAD-TIME-EVAL SYMBOL-MACRO
#+(or UNIX FFI WIN32) FOREIGN-POINTER
#+FFI FFI::FOREIGN-ADDRESS
#+FFI FFI::FOREIGN-VARIABLE
#+FFI FFI::FOREIGN-FUNCTION
WEAK-POINTER READ-LABEL FRAME-POINTER SYSTEM-INTERNAL)
type)
(t
(let ((f (clos-class type)))
(if f
(if (clos::built-in-class-p f) type f)
(or (ds-canonicalize-type type)
(typespec-error 'subtypep type)))))))
((and (consp type) (symbolp (setq head (first type))))
(unless (and (list-length type) (null (cdr (last type))))
(typespec-error 'subtypep type))
(case head
(MEMBER ; (MEMBER &rest objects)
(if (null (rest type))
'(OR)
type))
(EQL ; (EQL object)
(unless (eql (length type) 2)
(typespec-error 'subtypep type))
`(MEMBER ,(second type)))
((AND OR) ; (AND type*), (OR type*)
type)
(NOT ; (NOT type)
(unless (eql (length type) 2)
(typespec-error 'subtypep type))
type)
(MOD ; (MOD n)
(unless (eql (length type) 2)
(typespec-error 'subtypep type))
(let ((n (second type)))
(unless (and (integerp n) (>= n 0))
(typespec-error 'subtypep type))
(if (eql n 0) '(OR) `(INTERVALS INTEGER 0 ,(1- n)))))
(SIGNED-BYTE ; (SIGNED-BYTE &optional s)
(when (cddr type)
(typespec-error 'subtypep type))
(let ((s (if (cdr type) (second type) '*)))
(if (eq s '*)
'(INTERVALS INTEGER * *)
(progn
(unless (and (integerp s) (plusp s))
(typespec-error 'subtypep type))
(let ((n (ash 1 (1- s)))) ; (ash 1 n) == (expt 2 n)
`(INTERVALS INTEGER ,(- n) ,(1- n)))))))
(UNSIGNED-BYTE ; (UNSIGNED-BYTE &optional s)
(when (cddr type)
(typespec-error 'subtypep type))
(let ((s (if (cdr type) (second type) '*)))
(if (eq s '*)
'(INTERVALS INTEGER 0 *)
(progn
(unless (and (integerp s) (>= s 0))
(typespec-error 'subtypep type))
`(INTERVALS INTEGER 0 ,(1- (ash 1 s))))))) ; (ash 1 n) == (expt 2 n)
(SIMPLE-BIT-VECTOR ; (SIMPLE-BIT-VECTOR &optional size)
(when (cddr type)
(typespec-error 'subtypep type))
(let ((size (if (cdr type) (second type) '*)))
(unless (or (eq size '*) (and (integerp size) (>= size 0)))
(typespec-error 'subtypep type))
`(SIMPLE-ARRAY BIT (,size))))
(SIMPLE-STRING ; (SIMPLE-STRING &optional size)
(when (cddr type)
(typespec-error 'subtypep type))
(let ((size (if (cdr type) (second type) '*)))
(unless (or (eq size '*) (and (integerp size) (>= size 0)))
(typespec-error 'subtypep type))
`(OR (SIMPLE-ARRAY CHARACTER (,size))
#-BASE-CHAR=CHARACTER (SIMPLE-ARRAY BASE-CHAR (,size))
(SIMPLE-ARRAY NIL (,size)))))
(SIMPLE-BASE-STRING ; (SIMPLE-BASE-STRING &optional size)
(when (cddr type)
(typespec-error 'subtypep type))
(let ((size (if (cdr type) (second type) '*)))
(unless (or (eq size '*) (and (integerp size) (>= size 0)))
(typespec-error 'subtypep type))
`(SIMPLE-ARRAY BASE-CHAR (,size))))
(SIMPLE-VECTOR ; (SIMPLE-VECTOR &optional size)
(when (cddr type)
(typespec-error 'subtypep type))
(let ((size (if (cdr type) (second type) '*)))
(unless (or (eq size '*) (and (integerp size) (>= size 0)))
(typespec-error 'subtypep type))
`(SIMPLE-ARRAY T (,size))))
(BIT-VECTOR ; (BIT-VECTOR &optional size)
(when (cddr type)
(typespec-error 'subtypep type))
(let ((size (if (cdr type) (second type) '*)))
(unless (or (eq size '*) (and (integerp size) (>= size 0)))
(typespec-error 'subtypep type))
`(ARRAY BIT (,size))))
((STRING cs-cl:string) ; (STRING &optional size)
(when (cddr type)
(typespec-error 'subtypep type))
(let ((size (if (cdr type) (second type) '*)))
(unless (or (eq size '*) (and (integerp size) (>= size 0)))
(typespec-error 'subtypep type))
`(OR (ARRAY CHARACTER (,size))
#-BASE-CHAR=CHARACTER (ARRAY BASE-CHAR (,size))
(ARRAY NIL (,size)))))
(BASE-STRING ; (BASE-STRING &optional size)
(when (cddr type)
(typespec-error 'subtypep type))
(let ((size (if (cdr type) (second type) '*)))
(unless (or (eq size '*) (and (integerp size) (>= size 0)))
(typespec-error 'subtypep type))
`(ARRAY BASE-CHAR (,size))))
(VECTOR ; (VECTOR &optional el-type size)
(when (cdddr type)
(typespec-error 'subtypep type))
(let ((el-type (if (cdr type) (second type) '*))
(size (if (cddr type) (third type) '*)))
(unless (or (eq size '*) (and (integerp size) (>= size 0)))
(typespec-error 'subtypep type))
`(ARRAY ,el-type (,size))))
((ARRAY SIMPLE-ARRAY) ; ([SIMPLE-]ARRAY &optional el-type dims)
(when (cdddr type)
(typespec-error 'subtypep type))
(let ((dims (if (cddr type) (third type) '*)))
(unless (or (eq dims '*)
(and (integerp dims) (>= dims 0))
(and (listp dims)
(every #'(lambda (d)
(or (eq d '*)
(and (integerp d) (>= d 0))))
dims)))
(typespec-error 'subtypep type))
type))
((COMPLEX) ; (COMPLEX &optional rtype itype)
(when (cdddr type)
(typespec-error 'subtypep type))
type)
((REAL RATIONAL INTEGER FLOAT
SHORT-FLOAT SINGLE-FLOAT DOUBLE-FLOAT LONG-FLOAT)
(when (cdddr type)
(typespec-error 'subtypep type))
(let ((lo (if (cdr type) (second type) '*))
(hi (if (cddr type) (third type) '*))
(test (get head 'SYS::TYPE-SYMBOL)))
(flet ((valid-interval-designator-p (bound test)
;; Tests whether the bound is valid interval designator
;; for the given type.
(or (eq bound '*)
(funcall test bound)
(and (consp bound) (null (cdr bound))
(funcall test (first bound))))))
(unless (and (valid-interval-designator-p lo test)
(valid-interval-designator-p hi test))
(typespec-error 'subtypep type))
; Recons the type, to bring into the multiple-intervals
; representation that is used later.
`(INTERVALS ,head ,lo ,hi))))
(INTERVALS
(unless (and (member (second type)
'(REAL RATIONAL INTEGER FLOAT
SHORT-FLOAT SINGLE-FLOAT DOUBLE-FLOAT LONG-FLOAT))
(oddp (length (rest type))))
(typespec-error 'subtypep type))
;; We don't perform a full check of the intervals list here,
;; for speed.
type)
(CHARACTER-INTERVALS
(unless (oddp (length type))
(typespec-error 'subtypep type))
;; We don't perform a full check of the intervals list here,
;; for speed.
type)
((CONS) ; (CONS &optional cartype cdrtype)
(when (cdddr type)
(typespec-error 'subtypep type))
type)
(SATISFIES ; (SATISFIES predicate)
(unless (and (null (cddr type)) (symbolp (second type)))
(typespec-error 'subtypep type))
type)
(VALUES ; (VALUES &rest types)
type)
(FUNCTION ; (FUNCTION &optional argtypes valuetype)
(unless (and (listp (cdr type)) (listp (cadr type))
(listp (cddr type)) (null (cdddr type)))
(typespec-error 'subtypep type))
(if (null (cdr type))
;; (FUNCTION) = FUNCTION. Return the CLOS class, as above.
(clos-class 'FUNCTION)
type))
(t (typespec-error 'subtypep type))))
((clos::defined-class-p type)
(if (and (clos::built-in-class-p type)
(eq (get (clos:class-name type) 'CLOS::CLOSCLASS) type))
(canonicalize-type (clos:class-name type))
type))
((clos::eql-specializer-p type)
`(MEMBER ,(clos::eql-specializer-singleton type)))
((encodingp type)
#+UNICODE type
#-UNICODE 'CHARACTER)
(t (typespec-error 'subtypep type))))
;; Compares two canonicalized types for superficial equality.
;; Note that EQUAL is forbidden on types, because of (EQL #1=(x . #1#)).
(defun canonicalized-types-equal-p (type1 type2)
(or (eq type1 type2)
(and (consp type1) (consp type2)
(eq (first type1) (first type2))
(case (first type1)
(MEMBER ; (MEMBER &rest objects)
(let ((objects1 (remove-duplicates (rest type1) :test #'eql))
(objects2 (remove-duplicates (rest type2) :test #'eql)))
(and (eql (length objects1) (length objects2))
(or (every #'eql objects1 objects2)
(and (null (set-difference objects1 objects2 :test #'eql))
(null (set-difference objects2 objects1 :test #'eql)))))))
(EQL ; (EQL object)
(eql (second type1) (second type2)))
((AND OR COMPLEX CONS VALUES)
; (AND type*), (OR type*),
; (COMPLEX &optional rtype itype), (CONS &optional cartype cdrtype),
; (VALUES &rest types)
(let ((types1 (rest type1))
(types2 (rest type2)))
(and (eql (length types1) (length types2))
(every #'canonicalized-types-equal-p types1 types2))))
(NOT ; (NOT type)
(canonicalized-types-equal-p (second type1) (second type2)))
((ARRAY SIMPLE-ARRAY) ; ([SIMPLE-]ARRAY &optional el-type dims)
(and (canonicalized-types-equal-p (if (cdr type1) (second type1))
(if (cdr type2) (second type2)))
(equal (cddr type1) (cddr type2))))
(FUNCTION ; (FUNCTION &optional argtypes valuetype)
(and (= (length type1) (length type2))
(= (length (second type1)) (length (second type2)))
(every #'canonicalized-types-equal-p (second type1) (second type2))
(canonicalized-types-equal-p (third type1) (third type2))))
(t ; Other canonicalized types only contain numbers and symbols.
(equal (rest type1) (rest type2)))))))
(defun subtypep (type1 type2 &optional env
&aux head1)
(macrolet ((yes () '(return-from subtypep (values t t)))
(no () '(return-from subtypep (values nil t)))
(unknown () '(return-from subtypep (values nil nil))))
;; Rules:
;; - Say (yes) or (no) only when the result is mathematically provable.
;; - Don't say (unknown) too early, use (unknown) only as a last resort.
;; - Don't compare type specificier using EQUAL.
;;
;; Quick superficial simplification.
;; Note: it maps NIL to (OR), T to (AND).
(setq type1 (canonicalize-type type1))
(setq type2 (canonicalize-type type2))
;; Trivial cases.
(when (equal '(OR) type1) ; type1 the empty type?
(yes))
(when (equal '(AND) type2) ; type2 is T?
(yes))
(when (canonicalized-types-equal-p type1 type2)
; (subtypep type type) always true
(yes))
(when (consp type1)
(setq head1 (first type1))
(cond ;; Nothing is known about SATISFIES types.
;; But don't signal (unknown) too early.
;((and (eq head1 'SATISFIES) (eql (length type1) 2))
; (unknown)
;)
;; EQL: Element must belong to type2.
((eq head1 'EQL)
(return-from subtypep (safe-typep (second type1) type2 env)))
;; MEMBER: All elements must belong to type2.
((eq head1 'MEMBER)
(let ((all-yes t))
(dolist (x (rest type1))
(multiple-value-bind (is known) (safe-typep x type2 env)
(unless is
(if known (no) (setq all-yes nil)))))
(if all-yes (yes) (unknown))))
;; OR: Each type must be a subtype of type2.
((eq head1 'OR)
(let ((all-yes t))
(dolist (type (rest type1))
(multiple-value-bind (is known) (subtypep type type2)
(unless is
(if known (no) (setq all-yes nil)))))
(if all-yes (yes) (unknown))))))
(when (consp type2)
(cond ;; Nothing is known about SATISFIES types.
;; But don't signal (unknown) too early.
;((and (eq (first type2) 'SATISFIES) (eql (length type2) 2))
; (unknown)
;)
;; AND: type1 must be a subtype of each type.
((eq (first type2) 'AND)
(let ((all-yes t))
(dolist (type (rest type2))
(multiple-value-bind (is known) (subtypep type1 type)
(unless is
(if known (no) (setq all-yes nil)))))
(if all-yes (yes) (unknown))))))
(subtypep-logic (list type1) (list type2))))
;; Flattening the ANDs and ORs uses two mutually recursive functions.
;; Since our LABELS implementation allocates closures at runtime, use global
;; functions instead.
(defvar *subtypep-type1parts*)
(defvar *subtypep-type2parts*)
(defvar *subtypep-type2eqlparts*)
;; Add a canonicalized type to the left-hand side: type1parts.
(defun subtypep-flatten-AND (type)
(if (consp type)
(case (first type)
(AND
(mapc #'(lambda (x) (subtypep-flatten-AND (canonicalize-type x)))
(rest type)))
(NOT
(subtypep-flatten-OR (canonicalize-type (second type))))
(t
(push type *subtypep-type1parts*)))
(push type *subtypep-type1parts*)))
;; Add a canonicalized type to the right-hand side: type2parts, type2eqlparts.
(defun subtypep-flatten-OR (type)
(if (consp type)
(case (first type)
(OR
(mapc #'(lambda (x) (subtypep-flatten-OR (canonicalize-type x)))
(rest type)))
(NOT
(subtypep-flatten-AND (canonicalize-type (second type))))
(MEMBER
(setq *subtypep-type2eqlparts*
(revappend (rest type) *subtypep-type2eqlparts*)))
(EQL
(push (second type) *subtypep-type2eqlparts*))
(t
(push type *subtypep-type2parts*)))
(push type *subtypep-type2parts*)))
;; Entry point taking lists of canonicalized type specs.
(defun subtypep-logic (types1 types2)
(macrolet ((yes () '(return-from subtypep-logic (values t t)))
(no () '(return-from subtypep-logic (values nil t)))
(unknown () '(return-from subtypep-logic (values nil nil))))
;; Logic simplification: (subtypep type1 type2) is equivalent to
;; (subtypep (and type1 (not type2)) nil). Therefore the interesting
;; irreducible case is when type1 is an (AND ...) and type2 is an (OR ...).
;; Write type1 as `(AND ,@type1parts)
;; and type2 as `(OR ,@type2parts (MEMBER ,@type2eqlparts)),
;; shuffling around the NOTs according to the rules
;; (subtypep `(AND ,@a (NOT ,c)) `(OR ,@b)) <==> (subtypep `(AND ,@a) `(OR ,@b ,c))
;; (subtypep `(AND ,@a) `(OR ,@b (NOT ,c))) <==> (subtypep `(AND ,@a ,c) `(OR ,@b))
(let (type1parts type2parts type2eqlparts)
(let ((*subtypep-type1parts* '())
(*subtypep-type2parts* '())
(*subtypep-type2eqlparts* '()))
(mapc #'subtypep-flatten-AND types1)
(mapc #'subtypep-flatten-OR types2)
(setq type1parts (nreverse *subtypep-type1parts*))
(setq type2parts (nreverse *subtypep-type2parts*))
(setq type2eqlparts (nreverse *subtypep-type2eqlparts*)))
;; type1parts and type2parts are now lists of canonicalized types.
;; Now: None of the type1parts is an AND.
;; None of the type2parts is an OR or MEMBER/EQL.
;; Remove trivialities:
(when (member '(OR) type1parts :test #'equal)
; The left-hand side is equivalent to the type NIL.
(yes))
(when (member '(AND) type2parts :test #'equal)
; The right-hand side is equivalent to the type T.
(yes))
;; Remove duplicates:
(setq type1parts (remove-duplicates type1parts :test #'canonicalized-types-equal-p))
(setq type2parts (remove-duplicates type2parts :test #'canonicalized-types-equal-p))
(setq type2eqlparts (remove-duplicates type2eqlparts))
(setq type2eqlparts
(remove-if #'(lambda (x)
(dolist (tp type2parts nil)
(when (safe-typep x tp) (return t))))
(the list type2eqlparts)))
;; Enumeratable results:
;; Does type1parts contain only a finite set?
(let ((set 't))
(dolist (part1 type1parts)
(when (consp part1)
(cond ((eq (first part1) 'MEMBER)
(let ((l (rest part1)))
(setq set (if (eq set 't) l (intersection set l)))))
((eq (first part1) 'EQL)
(let ((l (list (second part1))))
(setq set (if (eq set 't) l (intersection set l))))))))
(unless (eq set 't) ; Is type1parts entirely enumerated?
; Yes, so we can decide the result by a finite number of TYPEP calls.
(let ((all-yes t))
(dolist (x set)
(multiple-value-bind (is1 known1)
; Is x eliminated by `(AND ,@type1parts) ?
(let ((all-yes t))
(dolist (tp type1parts (values nil all-yes))
(multiple-value-bind (is known) (safe-typep x tp)
(unless is
(if known (return (values t t)) (setq all-yes nil))))))
(multiple-value-bind (is2 known2)
; Is x contained in `(OR ,@type2parts (MEMBER ,@type2eqlparts)) ?
(let ((all-known t))
(dolist (tp type2parts
(if (member x type2eqlparts) (values t t) (values nil all-known)))
(multiple-value-bind (is known) (safe-typep x tp)
(when is (return (values t t)))
(unless known (setq all-known nil)))))
(cond ((and known1 known2)
(unless (or is1 is2) (no)))
(known1 (unless is1 (setq all-yes nil)))
(known2 (unless is2 (setq all-yes nil)))
(t (setq all-yes nil))))))
(if all-yes (yes) (unknown)))))
;; Now: None of the type1parts is an AND or MEMBER/EQL.
;; None of the type2parts is an OR or MEMBER/EQL.
;; Handle `(OR ...) in type1parts:
(let ((reducible-part1
(member-if #'(lambda (part1)
(and (consp part1) (eq (first part1) 'OR)))
type1parts)))
(when reducible-part1
(let ((type1parts-before (ldiff type1parts reducible-part1))
(type1parts-after (rest reducible-part1))
(all-yes t))
(dolist (sub (rest (first reducible-part1)))
(setq sub (canonicalize-type sub))
(multiple-value-bind (is known)
(subtypep-logic
(append type1parts-before (list sub) type1parts-after)
(append type2parts (if type2eqlparts `((MEMBER ,@type2eqlparts)) '())))
(unless is
(if known (no) (setq all-yes nil)))))
(if all-yes (yes) (unknown)))))
;; Handle `(AND ...) in type2parts:
(let ((reducible-part2
(member-if #'(lambda (part2)
(and (consp part2) (eq (first part2) 'AND)))
type2parts)))
(when reducible-part2
(let ((type2parts-before (ldiff type2parts reducible-part2))
(type2parts-after (rest reducible-part2))
(all-yes t))
(dolist (sub (rest (first reducible-part2)))
(setq sub (canonicalize-type sub))
(multiple-value-bind (is known)
(subtypep-logic
type1parts
(append type2parts-before (list sub) type2parts-after
(if type2eqlparts `((MEMBER ,@type2eqlparts)) '())))
(unless is
(if known (no) (setq all-yes nil)))))
(if all-yes (yes) (unknown)))))
;; Now: None of the type1parts is an AND, OR or MEMBER/EQL.
;; None of the type2parts is an AND, OR or MEMBER/EQL.
;; Simple results:
;; Is some part of type1parts the same as a part of type2parts?
(dolist (part1 type1parts)
(dolist (part2 type2parts)
(when (canonicalized-types-equal-p part1 part2)
(yes))))
#|
;; Is some part of type1parts a subtype of a part of type2parts?
;; FIXME: Is this test good or bad for performance?
(when (or (> (length type1parts) 1) ; avoid infinite recursion
(> (length type2parts) 1))
(dolist (part1 type1parts)
(dolist (part2 type2parts)
(when (subtypep-logic (list part1) (list part2))
(yes)))))
|#
(when type2eqlparts
;; Handle the type2eqlparts.
;; The type1parts are either
;; - built-in types that have an arbitrary number of instances, or
;; - numeric or character types, or
;; - SATISFIES types, which are undecidable anyway.
;; From each of them we remove each of the type2eqlparts. (It would
;; be necessary to remove each of the type2eqlparts only from _one_ of
;; the type1parts, but we don't know in advance which one is the best.)
(let ((modified nil))
(do ((type2eqlpartsr type2eqlparts))
((null type2eqlpartsr))
(let ((obj (pop type2eqlpartsr)))
(when (or (realp obj) (characterp obj))
(let ((got-OR nil))
(mapl #'(lambda (l)
(let ((type1part (car l)))
(cond ((and (realp obj)
(if (atom type1part)
(member type1part
'(REAL INTEGER RATIONAL FLOAT SHORT-FLOAT
SINGLE-FLOAT DOUBLE-FLOAT LONG-FLOAT))
(eq (first type1part) 'INTERVALS)))
(let ((type1part-without-obj
(subtypep-REAL-remove-singleton
type1part obj)))
(when (eq type1part-without-obj 'NIL)
(yes))
(unless (equal type1part-without-obj type1part)
(setq modified t)
(when (and (consp type1part-without-obj)
(eq (first type1part-without-obj) 'OR))
(setq got-OR t)))
(setf (car l) type1part-without-obj)))
((and (characterp obj)
(if (atom type1part)
(eq type1part 'CHARACTER)
(eq (first type1part) 'CHARACTER-INTERVALS)))
(let ((type1part-without-obj
(subtypep-CHARACTER-remove-singleton
type1part obj)))
(when (eq type1part-without-obj 'NIL)
(yes))
(unless (equal type1part-without-obj type1part)
(setq modified t)
; `(OR ...) types cannot occur here.
(when (consp type1part-without-obj)
(assert (eq (first type1part-without-obj) 'CHARACTER-INTERVALS))))
(setf (car l) type1part-without-obj))))))
type1parts)
(when got-OR
; Eliminate the OR, then continue processing.
(return-from subtypep-logic
(subtypep-logic
type1parts
(append type2parts
(if type2eqlpartsr `((MEMBER ,@type2eqlpartsr)) '())))))))))
(when modified
;; Do the simple tests once again.
;; Is some part of type1parts the same as a part of type2parts?
(dolist (part1 type1parts)
(dolist (part2 type2parts)
(when (canonicalized-types-equal-p part1 part2)
(yes)))))))
;; Now we can forget about type2eqlparts.
;; Now it's time to group the type1parts and type2parts into categories.
(let ((type1category nil))
(dolist (type1part type1parts)
(let ((category (type-category type1part)))
(if category
(cond ((null type1category)
(setq type1category category))
((eq type1category category))
(t ; Encountered two different categories.
; `(AND ,@type1parts) therefore is the empty type.
(yes))))))
(unless type1category
;; Could not categorize the type1parts.
(when (null type1parts)
;; No wonder: the left-hand side is equivalent to the type T.
(let ((try-prove-no t))
(dolist (type2part type2parts)
(unless (type-category type2part) (setq try-prove-no nil)))
(when try-prove-no
;; No right-hand side can possibly cover all possible objects
;; (think of implementation dependent extra misc type
;; categories), therefore we can say
(no))))
(unknown))
;; Keep only the parts belonging to the same category.
;; Set try-prove-no to nil if we remove some uncategorized parts
;; from type1parts.
(let ((try-prove-no t))
(setq type1parts
(remove-if-not #'(lambda (type1part)
(let ((category (type-category type1part)))
(if (eq category type1category)
t
(progn
(setq try-prove-no nil)
nil))))
(the list type1parts)))
(setq type2parts
(remove-if-not #'(lambda (type2part)
(let ((category (type-category type2part)))
(if (eq category type1category)
t
(progn
(unless category (setq try-prove-no nil))
nil))))
(the list type2parts)))
;; Operate using the functions specific to the category.
(let ((and-simplifier (get type1category 'SUBTYPEP-SIMPLIFY-AND))
(or-simplifier (get type1category 'SUBTYPEP-SIMPLIFY-OR))
(decider (get type1category 'SUBTYPEP-DECIDE)))
;; Simplify the type1parts. (It is still a non-empty list.)
;; Also see if it evidently represents the empty type.
(let ((type1 (funcall and-simplifier type1parts)))
(when (eq type1 'NIL)
;; The type1parts represent the empty type.
(yes))
;; Simplify the type2parts.
(setq type2parts (funcall or-simplifier type2parts))
;; Now perform the decision.
(funcall decider type1 type2parts try-prove-no))))))))
#|
;; Debugging hints:
(in-package "SYSTEM")
(setf (package-lock *system-package-list*) nil)
(trace sys::simplify-and-array sys::simplify-or-array sys::subtypep-array
sys::simplify-and-complex sys::simplify-or-complex sys::subtypep-complex
sys::simplify-and-cons sys::simplify-or-cons sys::subtypep-cons
sys::simplify-and-real sys::simplify-or-real sys::subtypep-real
sys::intervals-mapto sys::intervals-intersection sys::intervals-union sys::intervals-subtypep
sys::intervals-typep sys::intervals-integer-closure
sys::intervals-remove-one sys::subtypep-REAL-remove-singleton
sys::simplify-and-character sys::simplify-or-character sys::subtypep-character
sys::subtypep-CHARACTER-pre-simplify sys::subtypep-CHARACTER-remove-singleton
sys::subtypep-pathname
sys::subtypep-misc
sys::simplify-and-structure-object sys::subtypep-structure-object
sys::simplify-and-standard-object sys::subtypep-standard-object
sys::type-category
sys::canonicalize-type
subtypep sys::subtypep-logic)
|#
| 104,659 | Common Lisp | .lisp | 2,186 | 34.664227 | 137 | 0.526583 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 9f6fd1f65571bb06f3ec21ce020e2e15f636daf63ac283bb7edb88547910443c | 11,350 | [
-1
] |
11,351 | clos-package.lisp | ufasoft_lisp/clisp/clos-package.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2007, 2009
;; to use it: (USE-PACKAGE "CLOS").
(in-package "COMMON-LISP")
(pushnew ':mop *features*)
(pushnew ':clos *features*)
(in-package "SYSTEM") ; necessary despite DEFPACKAGE!
;; Defined later, in functions.lisp.
(import 'make-signature)
(import 'sig-req-num)
(import 'sig-opt-num)
(import 'sig-rest-p)
(import 'sig-keys-p)
(import 'sig-keywords)
(import 'sig-allow-p)
(import 'check-function-name)
;; Defined later, in compiler.lisp.
(import '%generic-function-lambda)
(import '%optimize-function-lambda)
(defpackage "CLOS"
(:nicknames "MOP")
(:documentation "http://www.lisp.org/HyperSpec/Body/chap-7.html")
(:import-from "EXT" ext:mapcap ext:proper-list-p)
(:import-from "SYSTEM"
;; Import:
sys::text ; for error messages (i18n.d)
sys::error-of-type ; defined in error.d
sys::check-function-name ; defined in control.d
sys::check-symbol ; defined in control.d
sys::function-name-p ; defined in control.d
sys::function-block-name ; defined in eval.d
sys::memq ; defined in list.d
sys::predefun ; defined in init.lisp
sys::gensym-list ; defined in macros2.lisp
sys::analyze-lambdalist ; defined in lambdalist.lisp
sys::make-signature ; defined in functions.lisp
sys::sig-req-num sys::sig-opt-num sys::sig-rest-p ; likewise
sys::sig-keys-p sys::sig-keywords sys::sig-allow-p ; likewise
;; clos::class-p clos::defined-class-p ; defined in predtype.d
;; clos:class-of clos:find-class ; defined in predtype.d
;; clos::typep-class ; defined in predtype.d
;; clos::structure-object-p ; defined in record.d
;; clos::std-instance-p clos::allocate-std-instance ; defined in record.d
;; clos::%allocate-instance ; defined in record.d
;; clos:slot-value clos::set-slot-value ; defined in record.d
;; clos:slot-boundp clos:slot-makunbound ; defined in record.d
;; clos:slot-exists-p ; defined in record.d
;; clos::class-gethash clos::class-tuple-gethash ; defined in hashtabl.d
sys::%generic-function-lambda ; defined in compiler.lisp
sys::%optimize-function-lambda ; defined in compiler.lisp
;; clos:generic-flet clos:generic-labels ; treated in compiler.lisp
;; Export:
;; clos::closclass ; property in predtype.d, type.lisp, compiler.lisp
;; clos:class ; used in record.d
;; clos:generic-function ; used in type.lisp, compiler.lisp
;; clos:standard-generic-function ; used in predtype.d, type.lisp, compiler.lisp
;; clos:slot-missing clos:slot-unbound ; called by record.d
;; clos::*make-instance-table* ; used in record.d
;; clos::*reinitialize-instance-table* ; used in record.d
;; clos::initial-reinitialize-instance ; called by record.d
;; clos::initial-initialize-instance ; called by record.d
;; clos::initial-make-instance ; called by record.d
;; clos:print-object ; called by io.d
;; clos:describe-object ; called by user2.lisp
;; clos::define-structure-class ; called by defstruct.lisp
;; clos::defstruct-remove-print-object-method ; called by defstruct.lisp
;; clos::built-in-class-p ; called by type.lisp
;; clos::subclassp ; called by type.lisp, used in compiler.lisp
;; clos:class-name ; used in type.lisp, compiler.lisp
;; clos:find-class ; used in compiler.lisp
;; clos::defgeneric-lambdalist-callinfo ; called by compiler.lisp
;; clos::make-generic-function-form ; called by compiler.lisp
)) ; defpackage
(in-package "CLOS")
;;; exports: ** also in init.lisp ** !
(export
'(;; names of functions and macros:
slot-value slot-boundp slot-makunbound slot-exists-p with-slots
with-accessors documentation
find-class class-of defclass defmethod call-next-method next-method-p
defgeneric generic-function generic-flet generic-labels
class-name no-applicable-method no-next-method no-primary-method
find-method add-method remove-method
compute-applicable-methods method-qualifiers function-keywords
slot-missing slot-unbound
print-object describe-object
make-instance allocate-instance initialize-instance reinitialize-instance
shared-initialize ensure-generic-function
make-load-form make-load-form-saving-slots
change-class update-instance-for-different-class
update-instance-for-redefined-class make-instances-obsolete
;; names of classes:
class standard-class structure-class built-in-class
standard-object structure-object
generic-function standard-generic-function method standard-method
;; method combinations
standard method-combination define-method-combination
method-combination-error invalid-method-error
call-method make-method))
;;; MOP exports: ** also in init.lisp ** !
(export '(metaobject
;; MOP for dependents
add-dependent remove-dependent map-dependents update-dependent
;; MOP for slot definitions
slot-definition standard-slot-definition
direct-slot-definition standard-direct-slot-definition
effective-slot-definition standard-effective-slot-definition
slot-definition-name
slot-definition-initform slot-definition-initfunction
slot-definition-type slot-definition-allocation
slot-definition-initargs
slot-definition-readers slot-definition-writers
slot-definition-location
;; MOP for slot access
slot-value-using-class slot-boundp-using-class
slot-makunbound-using-class
standard-instance-access funcallable-standard-instance-access
;; MOP for classes
class forward-referenced-class
built-in-class structure-class standard-class
class-name class-direct-superclasses class-precedence-list
class-direct-subclasses class-direct-slots class-slots
class-direct-default-initargs class-default-initargs class-prototype
class-finalized-p finalize-inheritance
compute-direct-slot-definition-initargs direct-slot-definition-class
compute-class-precedence-list
compute-slots compute-effective-slot-definition
compute-effective-slot-definition-initargs
effective-slot-definition-class
compute-default-initargs
validate-superclass add-direct-subclass remove-direct-subclass
standard-accessor-method
standard-reader-method standard-writer-method
reader-method-class writer-method-class
ensure-class ensure-class-using-class
;; MOP for specializers
specializer eql-specializer
specializer-direct-generic-functions specializer-direct-methods
add-direct-method remove-direct-method
eql-specializer-object intern-eql-specializer
;; MOP for methods
method standard-method
method-function method-generic-function method-lambda-list
method-specializers method-qualifiers accessor-method-slot-definition
extract-lambda-list extract-specializer-names
;; MOP for method combinations
find-method-combination compute-effective-method
;; MOP for generic functions
funcallable-standard-class funcallable-standard-object
set-funcallable-instance-function
generic-function-name generic-function-methods
generic-function-method-class generic-function-lambda-list
generic-function-method-combination
generic-function-argument-precedence-order
generic-function-declarations
compute-discriminating-function
compute-applicable-methods compute-applicable-methods-using-classes
compute-effective-method-as-function
ensure-generic-function ensure-generic-function-using-class
;; CLISP specific symbols
generic-flet generic-labels no-primary-method
method-call-error method-call-type-error
method-call-error-generic-function
method-call-error-method method-call-error-argument-list
standard-stablehash structure-stablehash
clos-warning gf-already-called-warning gf-replacing-method-warning
) )
| 8,472 | Common Lisp | .lisp | 168 | 43.892857 | 84 | 0.699337 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | d16cfad97fed5c515534fc19c619bbcefdeca89c11805fa7d3c18779f778b767 | 11,351 | [
-1
] |
11,352 | runprog.lisp | ufasoft_lisp/clisp/runprog.lisp | ;;;; Running external programs
(in-package "EXT")
#+WIN32 (export '(execute))
#+(or UNIX WIN32) (export '(run-shell-command run-program))
(in-package "SYSTEM")
;;-----------------------------------------------------------------------------
#+(or UNIX WIN32)
;; UNIX:
; Must quote the program name and arguments since Unix shells interpret
; characters like #\Space, #\', #\<, #\>, #\$ etc. in a special way. This
; kind of quoting should work unless the string contains #\Newline and we
; call csh. But we are lucky: only /bin/sh will be used.
;; WIN32:
; Must quote program name and arguments since Win32 interprets characters
; like #\Space, #\Tab, #\\, #\" (but not #\< and #\>) in a special way:
; - Space and Tab are interpreted as delimiters. They are not treated as
; delimiters if they are surrounded by double quotes: "...".
; - Unescaped double quotes are removed from the input. Their only effect is
; that within double quotes, space and tab are treated like normal characters.
; - Backslashes not followed by double quotes are not special.
; - But 2*n+1 backslashes followed by a double quote become
; n backslashes followed by a double quote (n >= 0):
; \" -> "
; \\\" -> \"
; \\\\\" -> \\"
; The high-level Win32 command interpreter cmd.exe (but not the low-level
; function CreateProcess()) also interprets #\&, #\<, #\>, #\| as special
; delimiters and makes #\^ disappear. To avoid this, quote them like spaces.
(labels (#+UNIX
(shell-simple-quote (string)
(shell-quote string)
)
#+UNIX
(shell-quote (string) ; surround a string by single quotes
(if (eql (length string) 0)
"''"
(let ((qchar nil) ; last quote character: nil or #\' or #\"
(qstring (make-array 10 :element-type 'character
:adjustable t :fill-pointer 0)))
(map nil #'(lambda (c)
(let ((q (if (eql c #\') #\" #\')))
(unless (eql qchar q)
(when qchar (vector-push-extend qchar qstring))
(vector-push-extend (setq qchar q) qstring)
)
(vector-push-extend c qstring)))
string
)
(when qchar (vector-push-extend qchar qstring))
qstring
) ) )
#+WIN32
(shell-simple-quote (string) ; protect against spaces only
; Also protect the characters which are special for the command
; interpreter. This is needed only if the command interpreter
; will be called, but doesn't hurt if CreateProcess() will be
; called directly.
(if (or (eql (length string) 0)
(some #'(lambda (c)
(or ; space?
(<= (char-code c) 32)
; special delimiter?
(eql c #\&)
(eql c #\<)
(eql c #\>)
(eql c #\|)
(eql c #\^)
) )
string
) )
(string-concat "\"" string "\"")
string
) )
#+WIN32
(shell-quote (string) ; full protection
(let ((quote-around
(or (eql (length string) 0)
(some #'(lambda (c)
(or ; space?
(<= (char-code c) 32)
; special delimiter?
(eql c #\&)
(eql c #\<)
(eql c #\>)
(eql c #\|)
(eql c #\^)
) )
string)))
(qstring (make-array 10 :element-type 'character
:adjustable t :fill-pointer 0))
(backslashes 0))
(when quote-around
(vector-push-extend #\" qstring)
)
(map nil #'(lambda (c)
(when (eql c #\")
(dotimes (i (+ backslashes 1))
(vector-push-extend #\\ qstring)
) )
(vector-push-extend c qstring)
(if (eql c #\\)
(incf backslashes)
(setq backslashes 0)
) )
string
)
(when quote-around
(dotimes (i backslashes)
(vector-push-extend #\\ qstring)
)
(vector-push-extend #\" qstring)
)
qstring
) )
; conversion to a string that works for a pathname as well
(xstring (object)
(if (pathnamep object)
(namestring (absolute-pathname object))
(if (symbolp object)
(princ-to-string object)
(string object)))))
#+WIN32
(defun execute (programfile &rest arguments)
(shell
(apply #'string-concat
(shell-simple-quote (xstring programfile))
(mapcan #'(lambda (argument)
(list " " (shell-quote (xstring argument)))
)
arguments
) ) ) )
(defun run-shell-command (command &key (input ':terminal) (output ':terminal)
(if-output-exists ':overwrite)
(wait t)
#+UNIX (may-exec nil)
#+WIN32 (indirectp t)
)
(case input
((:TERMINAL :STREAM) )
(t (if (eq input 'NIL)
(setq input #+UNIX "/dev/null" #+WIN32 "nul")
(setq input (xstring input))
)
(setq command (string-concat command " < " (shell-quote input)))
#+WIN32 (setq indirectp t)
) )
(case output
((:TERMINAL :STREAM) )
(t (if (eq output 'NIL)
(setq output #+UNIX "/dev/null" #+WIN32 "nul"
if-output-exists ':OVERWRITE
)
(progn
(setq output (xstring output))
(when (and (eq if-output-exists ':ERROR) (probe-file output))
(setq output (pathname output))
(error-of-type 'file-error
:pathname output
(TEXT "~S: File ~S already exists")
'run-shell-command output
) ) ) )
(setq command
(string-concat command
(ecase if-output-exists
((:OVERWRITE :ERROR) " > ")
(:APPEND " >> ")
)
(shell-quote output)
) )
#+WIN32 (setq indirectp t)
) )
#-WIN32
(unless wait
(setq command (string-concat command " &")))
#+WIN32
(unless wait
(setq indirectp t)
(setf command (string-concat "start " command)))
#+UNIX
(when may-exec
;; If the executing shell is "/bin/sh" and command is a
;; "simple command" in the sense of sh(1), we can optimize it a bit:
(setq command (string-concat "exec " command))
)
#+WIN32
(when indirectp
(setq command (string-concat (shell-name) " /c " command))
)
(if (eq input ':STREAM)
(if (eq output ':STREAM)
(make-pipe-io-stream command)
(make-pipe-output-stream command))
(if (eq output ':STREAM)
(make-pipe-input-stream command)
(shell command))))
(defun run-program (program &key (arguments '())
(input ':terminal) (output ':terminal)
(if-output-exists ':overwrite)
(wait t)
#+WIN32 (indirectp nil)
)
(run-shell-command
(apply #'string-concat
(shell-simple-quote (xstring program))
(mapcan #'(lambda (argument)
(list " " (shell-quote (xstring argument)))
)
arguments
) )
#+UNIX :may-exec #+UNIX t
#+WIN32 :indirectp #+WIN32 indirectp
:wait wait
:input input :output output :if-output-exists if-output-exists
) )
)
| 8,769 | Common Lisp | .lisp | 215 | 25.730233 | 80 | 0.447316 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 347974ebf9c4fcd70933a263c1e5b00b5e8a08273c3b33a39498240b845c5599 | 11,352 | [
-1
] |
11,353 | clos-class2.lisp | ufasoft_lisp/clisp/clos-class2.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Class metaobjects
;;;; Part 2: The class namespace.
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
;;; Predefined classes (see ANSI CL 4.3.7.):
;; Metaclasses:
(defvar <potential-class>) ; <standard-class>
(defvar <defined-class>) ; <standard-class>
(defvar <standard-class>) ; <standard-class>
(defvar <funcallable-standard-class>) ; <standard-class>
(defvar <structure-class>) ; <standard-class>
(defvar <built-in-class>) ; <standard-class>
;; Not really metaclasses:
(defvar <forward-reference-to-class>) ; <standard-class>
(defvar <misdesigned-forward-referenced-class>) ; <standard-class>
;; Classes:
(defvar <standard-object>) ; <standard-class>
(defvar <funcallable-standard-object>) ; <funcallable-standard-class>
(defvar <structure-object>) ; <structure-class>
(defvar <generic-function>) ; <funcallable-standard-class>
(defvar <standard-generic-function>) ; <funcallable-standard-class> ; ABI
;(defvar <method>) ; <standard-class>
;(defvar <standard-method>) ; <standard-class>
(defvar <standard-reader-method>) ; <standard-class>
(defvar <standard-writer-method>) ; <standard-class>
;(defvar <method-combination>) ; <standard-class>
(defvar <array>) ; <built-in-class>
(defvar <bit-vector>) ; <built-in-class>
(defvar <character>) ; <built-in-class>
(defvar <complex>) ; <built-in-class>
(defvar <cons>) ; <built-in-class>
(defvar <float>) ; <built-in-class>
(defvar <function>) ; <built-in-class>
(defvar <hash-table>) ; <built-in-class>
(defvar <integer>) ; <built-in-class>
(defvar <list>) ; <built-in-class>
(defvar <null>) ; <built-in-class>
(defvar <number>) ; <built-in-class>
(defvar <package>) ; <built-in-class>
(defvar <pathname>) ; <built-in-class>
#+LOGICAL-PATHNAMES
(defvar <logical-pathname>) ; <built-in-class>
(defvar <random-state>) ; <built-in-class>
(defvar <ratio>) ; <built-in-class>
(defvar <rational>) ; <built-in-class>
(defvar <readtable>) ; <built-in-class>
(defvar <real>) ; <built-in-class>
(defvar <sequence>) ; <built-in-class>
(defvar <stream>) ; <built-in-class>
(defvar <file-stream>) ; <built-in-class>
(defvar <synonym-stream>) ; <built-in-class>
(defvar <broadcast-stream>) ; <built-in-class>
(defvar <concatenated-stream>) ; <built-in-class>
(defvar <two-way-stream>) ; <built-in-class>
(defvar <echo-stream>) ; <built-in-class>
(defvar <string-stream>) ; <built-in-class>
(defvar <string>) ; <built-in-class>
(defvar <symbol>) ; <built-in-class>
(defvar <t>) ; <built-in-class>
(defvar <vector>) ; <built-in-class>
;; Condition classes and RESTART are defined later, in condition.lisp.
;;; Global management of classes and their names:
#|| ; see PREDTYPE.D
(defun find-class (symbol &optional (errorp t) environment)
(declare (ignore environment)) ; ignore distinction between
; compile-time and run-time environment
(unless (symbolp symbol)
(error-of-type 'type-error
:datum symbol :expected-type 'symbol
(TEXT "~S: argument ~S is not a symbol")
'find-class symbol))
(let ((class (get symbol 'CLOSCLASS)))
(if (not (defined-class-p class))
(if errorp
(error-of-type 'error
(TEXT "~S: ~S does not name a class")
'find-class symbol)
nil)
class)))
||#
(defun (setf find-class) (new-value symbol &optional errorp environment)
(declare (ignore errorp environment)) ; ignore distinction between
; compile-time and run-time environment
(unless (symbolp symbol)
(error-of-type 'type-error
:datum symbol :expected-type 'symbol
(TEXT "~S: argument ~S is not a symbol")
'(setf find-class) symbol))
(unless (or (null new-value) (defined-class-p new-value))
(error-of-type 'type-error
:datum new-value :expected-type 'class
(TEXT "~S: ~S is not a class")
'(setf find-class) new-value))
(let ((h (get symbol 'CLOSCLASS)))
(when (defined-class-p h)
(when (and (built-in-class-p h) (eq (class-name h) symbol)) ; protect structure classes, too??
(error-of-type 'error
(TEXT "~S: cannot redefine built-in class ~S")
'(setf find-class) h)))
;; Should we do (setf (class-name h) nil) ? No, because CLHS of FIND-CLASS
;; says that "the class object itself is not affected".
(sys::check-redefinition symbol '(setf find-class)
(and (defined-class-p h) (TEXT "class")))
(when (and h (forward-reference-to-class-p h) new-value)
;; Move the list of subclasses from the old class object to the new one.
(dolist (subclass (class-direct-subclasses h))
(add-direct-subclass new-value subclass))))
(if new-value
(setf (get symbol 'CLOSCLASS) new-value)
(progn (remprop symbol 'CLOSCLASS) nil)))
;; Converts a class to a pretty printing type.
(defun class-pretty (class)
(if (or (forward-reference-to-class-p class)
(eq (find-class (class-name class) nil) class))
(class-name class)
class))
| 5,891 | Common Lisp | .lisp | 119 | 45.453782 | 100 | 0.582683 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | b87cdcdae7750e480594b481da604a59f144d8e48c40d214f1de06b904c40c77 | 11,353 | [
-1
] |
11,354 | clos-custom.lisp | ufasoft_lisp/clisp/clos-custom.lisp | ;;;; Common Lisp Object System for CLISP: Customizable variables
;;;; Bruno Haible 2004
(in-package "EXT")
(progn
(export #1='(custom::*strict-mop*
custom::*forward-referenced-class-misdesign*)
"CUSTOM")
(export #1# "EXT"))
(in-package "CLOS")
;; ============================================================================
(define-symbol-macro custom:*forward-referenced-class-misdesign*
(<forward-referenced-class>-under-<class>))
(defvar *<forward-referenced-class>-under-<class>* nil)
(defun <forward-referenced-class>-under-<class> ()
*<forward-referenced-class>-under-<class>*)
(defun (setf <forward-referenced-class>-under-<class>) (val)
(when val (setq val 't))
(if val
(unless (eq (find-class 'class) <potential-class>)
(set-<class>-<potential-class>)
(set-<forward-referenced-class>-<misdesigned-forward-referenced-class>))
(unless (eq (find-class 'class) <defined-class>)
(set-<class>-<defined-class>)
(set-<forward-referenced-class>-<forward-reference-to-class>)))
(setq *<forward-referenced-class>-under-<class>* val)
val)
(defun set-<class>-<potential-class> ()
(ext:without-package-lock ("CLOS")
(setf (class-classname <defined-class>) 'defined-class)
(setf (class-classname <potential-class>) 'class)
(setf (find-class 'class) <potential-class>)
(setf (get 'class 'sys::type-symbol) (get 'potential-class 'sys::type-symbol))))
(defun set-<class>-<defined-class> ()
(ext:without-package-lock ("CLOS")
(setf (class-classname <potential-class>) 'potential-class)
(setf (class-classname <defined-class>) 'class)
(setf (find-class 'class) <defined-class>)
(setf (get 'class 'sys::type-symbol) (get 'defined-class 'sys::type-symbol))))
(defun set-<forward-referenced-class>-<misdesigned-forward-referenced-class> ()
(ext:without-package-lock ("CLOS")
(setf (class-classname <forward-reference-to-class>) 'forward-reference-to-class)
(setf (class-classname <misdesigned-forward-referenced-class>) 'forward-referenced-class)
(setf (find-class 'forward-referenced-class) <misdesigned-forward-referenced-class>)))
(defun set-<forward-referenced-class>-<forward-reference-to-class> ()
(ext:without-package-lock ("CLOS")
(setf (class-classname <misdesigned-forward-referenced-class>) 'misdesigned-forward-referenced-class)
(setf (class-classname <forward-reference-to-class>) 'forward-referenced-class)
(setf (find-class 'forward-referenced-class) <forward-reference-to-class>)))
; Initial setting:
(set-<class>-<defined-class>)
(set-<forward-referenced-class>-<forward-reference-to-class>)
;; ============================================================================
(define-symbol-macro custom:*strict-mop* (strict-mop))
(defvar *strict-mop* nil)
(defun strict-mop ()
*strict-mop*)
(defun (setf strict-mop) (val)
(when val (setq val 't))
(setf custom:*forward-referenced-class-misdesign* val)
(setq *strict-mop* val)
val)
| 3,019 | Common Lisp | .lisp | 61 | 45.409836 | 105 | 0.667347 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 4aa662b00aeb4b552d2bc35a8eb626747df66ce5ce095a6db11438246be53bfa | 11,354 | [
-1
] |
11,355 | clos-specializer3.lisp | ufasoft_lisp/clisp/clos-specializer3.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Specializers
;;;; Part n-1: Generic functions specified in the MOP.
;;;; Bruno Haible 2004-05-15
(in-package "CLOS")
;; Make creation of <specializer> instances customizable.
(setf (fdefinition 'initialize-instance-<eql-specializer>) #'initialize-instance)
(setf (fdefinition 'make-instance-<eql-specializer>) #'make-instance)
;; Optimized accessors, with type checking.
(defun specializer-direct-methods-table (specializer)
(accessor-typecheck specializer 'specializer 'specializer-direct-methods-table)
(sys::%record-ref specializer *<specializer>-direct-methods-location*))
(defun (setf specializer-direct-methods-table) (new-value specializer)
(accessor-typecheck specializer 'specializer '(setf specializer-direct-methods-table))
(setf (sys::%record-ref specializer *<specializer>-direct-methods-location*) new-value))
(defun eql-specializer-singleton (specializer)
(accessor-typecheck specializer 'eql-specializer 'eql-specializer-singleton)
(sys::%record-ref specializer *<eql-specializer>-singleton-location*))
(defun (setf eql-specializer-singleton) (new-value specializer)
(accessor-typecheck specializer 'eql-specializer '(setf eql-specializer-singleton))
(setf (sys::%record-ref specializer *<eql-specializer>-singleton-location*) new-value))
;; MOP p. 103
(defgeneric specializer-direct-generic-functions (specializer)
(:method ((specializer specializer))
(compute-direct-generic-functions specializer)))
;; MOP p. 31
(defgeneric add-direct-method (specializer method)
(:method ((specializer specializer) (method method))
(add-direct-method-<specializer>-<method> specializer method)))
;; MOP p. 89
(defgeneric remove-direct-method (specializer method)
(:method ((specializer specializer) (method method))
(remove-direct-method-internal specializer method)))
;; MOP p. 103
(defgeneric specializer-direct-methods (specializer)
(:method ((specializer specializer))
(list-direct-methods specializer)))
| 2,010 | Common Lisp | .lisp | 37 | 51.918919 | 90 | 0.778684 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | c6c4a1427d640d7aae0cac874855d57cc768a3fd117d0ade25bfb01791a40daa | 11,355 | [
-1
] |
11,356 | complete.lisp | ufasoft_lisp/clisp/complete.lisp | ;;;; Command-line completion hook
(in-package "SYSTEM")
;;-----------------------------------------------------------------------------
;; Completing routine for the GNU Readline library.
;; Input: string (the input line), and the boundaries of the text to be
;; completed: (subseq string start end)
;; Output: a list of simple-strings. empty, when no meaningful completions.
;; otherwise, CDR = list of all meaningful completions,
;; CAR = the immediate replacement
(let ((state nil))
(defun completion (string start end)
(let* ((quotedp (and (>= start 1) ; quoted completion?
(member (char string (- start 1)) '(#\" #\|))))
(start1 (if quotedp (1- start) start))
(functionalp1 (and (>= start1 1)
(equal (subseq string (- start1 1) start1) "(")))
(functionalp2 (and (>= start1 2)
(equal (subseq string (- start1 2) start1) "#'")))
;; completion of a function or of any symbol?
(functionalp (or (= start end) functionalp1 functionalp2))
(search-package-names nil) ; complete among package names
;; test for special case: nothing was entered to be completed,
;; so we try to DESCRIBE the last function symbol entered
(void-completion
(and (= start end)
(or (>= start (length string))
(whitespacep (schar string start))))))
;; If nothing useful was entered (just whitespace), print help.
(when void-completion
(do ((pos (min end (1- (length string))) (1- pos))
(depth 0)
(white end))
((or (minusp pos) (plusp depth))
(setq start (+ pos 2) end white))
(cond ((char= #\( (schar string pos)) (incf depth))
((char= #\) (schar string pos)) (decf depth))
((whitespacep (schar string pos)) (setq white pos))))
(when (< end start) ; nothing useful was entered - just whitespace
(sys::help) (terpri) ; print help
(return-from completion 0))) ; redraw the prompt
;; FIXME: If quotedp is true due to #\", we should better collect matching
;; filenames, not symbols, I think.
;; Collect matching symbols.
(let ((new-state (list* string start end))
(package *package*)
(mapfun #'sys::map-symbols)
(prefix nil))
;; Extract the package name:
(unless quotedp
(let ((colon (position #\: string :start start :end end)))
(if colon
(let ((packname (subseq string start colon))) ; fresh!
(case (readtable-case *readtable*)
(:upcase (nstring-upcase packname))
(:downcase (nstring-downcase packname))
(:invert (nstring-invertcase packname)))
(when (equal packname "") (setq packname "KEYWORD"))
(setq package (find-package packname))
(unless package
(return-from completion nil))
(incf colon)
(if (and (< colon end) (eql (char string colon) #\:))
(incf colon)
(setq mapfun #'sys::map-external-symbols))
(setq prefix (subseq string start colon))
(setq start colon))
(setq search-package-names t))))
(let* ((case-sensitive-p
(or quotedp
(package-case-sensitive-p package)
(case (readtable-case *readtable*)
((:UPCASE :DOWNCASE) nil)
((:PRESERVE :INVERT) t))))
;; FIXME: Handling of (readtable-case *readtable*) = :INVERT is
;; incomplete.
(case-inverted-p (package-case-inverted-p package))
(known-part (subseq string start end))
(known-len (length known-part))
(char-cmp (if case-sensitive-p #'char= #'char-equal))
(string-cmp (if case-sensitive-p #'string= #'string-equal))
(return-list '())
(match-and-collect
(lambda (name)
(when (>= (length name) known-len)
(when case-inverted-p
(setq name (string-invertcase name)))
(when (funcall string-cmp name known-part :end1 known-len)
(push name return-list)))))
(gatherer
(if functionalp
(lambda (sym)
(when (fboundp sym)
(funcall match-and-collect (symbol-name sym))))
(lambda (sym) (funcall match-and-collect (symbol-name sym))))))
(funcall mapfun gatherer package)
(when (and search-package-names (null return-list))
(dolist (pack (list-all-packages))
(funcall match-and-collect (package-name pack))
(dolist (nick (package-nicknames pack))
(funcall match-and-collect nick)))
(when return-list
(setq return-list
(mapcan (lambda (pack)
(ext:with-collect (c)
(do-external-symbols (s pack)
(let ((ret (ext:string-concat
(package-name pack) ":"
(symbol-name s))))
(when case-inverted-p
(setq ret (nstring-invertcase ret)))
(c ret)))))
(delete-duplicates
(map-into return-list #'find-package
return-list))))))
;; Now react depending on the list of matching symbols.
(when (null return-list)
(return-from completion nil))
(when (and void-completion
(< end (length string)) (whitespacep (schar string end)))
(let ((first-matching-name
(find known-part return-list :test string-cmp)))
(when case-inverted-p
(setq first-matching-name (string-invertcase first-matching-name)))
(let ((first-matching-sym (find-symbol first-matching-name package)))
(return-from completion
(when (and first-matching-sym (fboundp first-matching-sym))
;; FIXME: why not test (null (cdr return-list)) ?
(cond ((equalp state new-state)
(describe first-matching-sym) (terpri) (terpri))
(t (setq state new-state)))
0))))) ; redraw the prompt
;; For a function without arguments, append a closing paren.
(when (and functionalp1
(not quotedp) ; readline will close the quote after #\) !
(null (cdr return-list))
(let ((name (car return-list)))
(when case-inverted-p
(setq name (string-invertcase name)))
(let ((sym (find-symbol name package)))
(and sym (fboundp sym) (functionp (symbol-function sym))
(multiple-value-bind (name req-num opt-num rest-p key-p)
(function-signature (symbol-function sym))
(declare (ignore name))
(and (eql req-num 0) (eql opt-num 0)
(not rest-p) (not key-p)))))))
(setf (car return-list) (string-concat (car return-list) ")")))
;; Downcase a function name.
(when (and (not quotedp) (not case-sensitive-p))
(map-into return-list #'string-downcase return-list))
;; Sort the return-list.
(setq return-list (sort return-list #'string<))
;; Look for the largest common initial piece.
(let ((imax (reduce #'min return-list :key #'length)))
(do ((i 0 (1+ i)))
((or (= i imax)
(let ((c (char (first return-list) i)))
(dolist (s (rest return-list) nil)
(unless (funcall char-cmp (char s i) c) (return t)))))
(push (subseq (first return-list) 0 i) return-list))))
;; Reattach prefix consisting of package name and colons.
(when prefix
(mapl #'(lambda (l) (setf (car l) (string-concat prefix (car l))))
return-list))
return-list))))
)
| 8,509 | Common Lisp | .lisp | 165 | 36.454545 | 84 | 0.511029 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | a8325be22b4cd4168597a12f83033e1da883b88636c193ad7efb45bf9013a3f8 | 11,356 | [
-1
] |
11,357 | clos-metaobject1.lisp | ufasoft_lisp/clisp/clos-metaobject1.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Generic metaobjects
;;;; Bruno Haible 2004-05-29
(in-package "CLOS")
;;; The metaobject abstract class.
(defvar <metaobject> 'metaobject)
(defvar *<metaobject>-defclass*
'(defclass metaobject ()
()))
| 256 | Common Lisp | .lisp | 9 | 26.333333 | 40 | 0.713115 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 1ae5a76bd874a3e5565b6eeeb69fb370422cdb583cccf06888f4d0a0cf1e5f83 | 11,357 | [
-1
] |
11,358 | clos-methcomb2.lisp | ufasoft_lisp/clisp/clos-methcomb2.lisp | ;;;; Common Lisp Object System for CLISP: Method Combination
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2005, 2007, 2010
;;;; German comments translated into English: Stefan Kain 2002-04-08
;;;; James Anderson 2003
(in-package "CLOS")
;;; ---------------------------- Method Selection ----------------------------
;; CLtL2 28.1.6.3., ANSI CL 7.6.3.
;; Agreement on Parameter Specializers and Qualifiers
(defun specializers-agree-p (specializers1 specializers2)
(and (eql (length specializers1) (length specializers2))
(every #'same-specializers-p specializers1 specializers2)))
(defun same-specializers-p (specializer1 specializer2)
;; Since EQL-specializers can be assumed to be interned, just comparing
;; with EQ is sufficient.
(eq specializer1 specializer2))
;;; ----------------- Bridging different calling conventions -----------------
;; For most purposes, the fast-function is used. However, the MOP specifies
;; a slow calling convention for the method-function. There are two places
;; where this needs to be supported:
;; - The user can funcall the method-function of a method defined through
;; DEFMETHOD. For this case we need to convert the fast function into a
;; slow one. Done by std-method-function-or-substitute.
;; - The user can create methods through
;; (MAKE-INSTANCE <METHOD> :FUNCTION #'(lambda (args next-methods) ...))
;; and insert them in a generic-function. We have to call them with the
;; proper conventions. This is handled by the CALL-METHOD macro.
;; Note: We cannot provide the local macros/functions CALL-NEXT-METHOD and
;; NEXT-METHOD-P for this case. The user is responsible for peeking at the
;; next-methods list himself. Something like this:
;; (lambda (args next-methods)
;; (flet ((next-method-p () (not (null next-methods)))
;; (call-next-method (&rest new-args)
;; (unless new-args (setq new-args args))
;; (if (null next-methods)
;; (apply #'no-next-method ... ... new-args)
;; (funcall (method-function (first next-methods))
;; new-args (rest next-methods)))))
;; ...))
(defun method-list-to-continuation (methods-list)
(if methods-list
(let ((method (first methods-list))
(next-methods-list (rest methods-list)))
(if (and (typep-class method <standard-method>)
(std-method-fast-function method))
; Fast method function calling conventions.
(let ((fast-func (std-method-fast-function method)))
(if (std-method-wants-next-method-p method)
(let ((next-continuation (method-list-to-continuation next-methods-list)))
#'(lambda (&rest args)
(apply fast-func next-continuation args)))
; Some methods are known a-priori to not use the next-method list.
fast-func))
; Slow method function calling conventions.
(let ((slow-func (method-function method)))
#'(lambda (&rest args)
(funcall slow-func args next-methods-list)))))
nil))
(defun std-method-function-or-substitute (method)
(or (std-method-function method)
(setf (std-method-function method)
#'(lambda (arguments next-methods-list)
; Fast method function calling conventions.
(let ((fast-func (std-method-fast-function method)))
(if fast-func
(if (std-method-wants-next-method-p method)
(apply fast-func
(method-list-to-continuation next-methods-list)
arguments)
; Some methods are known a-priori to not use the next-method list.
(apply fast-func arguments))
(error (TEXT "The method function of ~S cannot be called before the method has been added to a generic function.")
method)))))))
(defun method-function-substitute (h)
(let ((fast-func (car h))
(wants-next-method-p (null (cadr h))))
(if wants-next-method-p
#'(lambda (arguments next-methods-list)
(apply fast-func
(method-list-to-continuation next-methods-list)
arguments))
; Some methods are known a-priori to not use the next-method list.
#'(lambda (arguments next-methods-list)
(declare (ignore next-methods-list))
(apply fast-func arguments)))))
;; Computes the :function / fast-function initargs list for a freshly allocated
;; (but yet uninitialized) method.
;; h = (funcall fast-function-factory method)
;; Returns a freshly allocated list.
(defun method-function-initargs (method-class h) ; ABI
(if (subclassp method-class <standard-method>)
(list 'fast-function (car h)
'wants-next-method-p (null (cadr h)))
(list ':function (method-function-substitute h))))
;;; ------------- Error Messages for Long Form Method Combination -------------
;; Context about the method combination call, set during the execution of a
;; long-expander.
; The actual generic function call arguments (in compute-effective-method).
(defvar *method-combination-arguments* nil) ; ABI
; The generic function applied (in compute-effective-method).
(defvar *method-combination-generic-function* nil) ; ABI
; The generic function's method combination (in compute-effective-method).
(defvar *method-combination* nil) ; ABI
;; Error about a method whose qualifiers don't fit with a method-combination.
;; This is specified to be a function, not a condition type, because it is
;; meant to be called from a DEFINE-METHOD-COMBINATION's body.
(defun invalid-method-error (method format-string &rest args)
(error
(TEXT "For function ~S applied to argument list ~S:~%While computing the effective method through ~S:~%Invalid method: ~S~%~?")
*method-combination-generic-function* *method-combination-arguments*
*method-combination*
method
format-string args))
;; Other error during method combination, not tied to a particular method.
;; This is specified to be a function, not a condition type, because it is
;; meant to be called from a DEFINE-METHOD-COMBINATION's body.
;; The fact that MISSING-REQUIRED-METHOD and NO-PRIMARY-METHOD don't call this
;; function is not a problem, because the user is not supposed to redefine or
;; customize this function.
(defun method-combination-error (format-string &rest args)
(error
(TEXT "For function ~S applied to argument list ~S:~%While computing the effective method through ~S:~%Impossible to combine the methods:~%~?")
*method-combination-generic-function* *method-combination-arguments*
*method-combination*
format-string args))
(defun invalid-method-sort-order-error (order-form order-value) ; ABI
(method-combination-error
(TEXT "The value of ~S is ~S, should be ~S or ~S.")
order-form order-value ':MOST-SPECIFIC-FIRST ':MOST-SPECIFIC-LAST))
(defun call-method-duplicates-error (gf method+groupname)
(let ((*method-combination-generic-function* gf)
(*method-combination* (safe-gf-method-combination gf)))
(method-combination-error
(TEXT "Method ~S has the same specializers and different qualifiers than other methods in method group ~S, and is actually used in the effective method.")
(car method+groupname) (cdr method+groupname))))
;;; ----------------------- General Method Combination -----------------------
(defun invalid-sort-order-error (order-form order-value) ; ABI
(error-of-type 'program-error
(TEXT "The value of ~S is ~S, should be ~S or ~S.")
order-form order-value ':MOST-SPECIFIC-FIRST ':MOST-SPECIFIC-LAST))
(defun any-method-combination-check-options (gf-name combination options checker) ; ABI
(locally (declare (compile))
(sys::%handler-bind
#'(lambda () (apply checker options))
'program-error
#'(lambda (err)
(error-of-type 'program-error
(TEXT "~S ~S: Invalid method-combination options ~S for ~S: ~A")
'defgeneric gf-name options combination err)))))
; Check the effective-method option (:ARGUMENTS ...).
; Returns two values:
; 1. the arguments-lambda-list,
; 2. the list of variables contained therein.
(defun check-em-arguments-option (option caller whole-form name)
(let ((arguments-lambda-list (cdr option)))
(multiple-value-bind (whole reqvars optvars optinits optsvars rest
keyp keywords keyvars keyinits keysvars allowp
auxvars auxinits)
(sys::analyze-method-combination-lambdalist arguments-lambda-list
#'(lambda (lalist detail errorstring &rest arguments)
(declare (ignore lalist)) ; use WHOLE-FORM instead
(if (eq caller 'define-method-combination)
(sys::lambda-list-error whole-form detail
#1=(TEXT "~S ~S: invalid ~S lambda-list: ~A")
caller name ':arguments
(apply #'format nil errorstring arguments))
(error-of-type 'program-error
#1# caller name ':arguments
(apply #'format nil errorstring arguments)))))
(declare (ignore optinits keyp keywords keyinits allowp auxinits))
(values
arguments-lambda-list
(remove 0 (append (list whole) reqvars optvars optsvars (list rest)
keyvars keysvars auxvars))))))
; Check the effective-method option (:GENERIC-FUNCTION ...).
; Returns the generic-function variable contained therein.
(defun check-em-generic-function-option (option caller whole-form name)
(unless (and (consp (cdr option)) (symbolp (cadr option)) (null (cddr option)))
(if (eq caller 'define-method-combination)
(error-of-type 'ext:source-program-error
:form whole-form
:detail option
#1=(TEXT "~S ~S: Invalid syntax for ~S option: ~S")
caller name ':generic-function option)
(error-of-type 'program-error
#1#
caller name ':generic-function option)))
(cadr option))
; Check the effective-method option (:DUPLICATES ...).
; Returns an alist of methods and its method group names.
(defun check-em-duplicates-option (option caller name)
(unless (and (proper-list-p (cdr option))
(every #'(lambda (x)
(and (consp x)
(typep-class (car x) <method>)
(symbolp (cdr x))))
(cdr option)))
(error-of-type 'program-error
(TEXT "~S ~S: Invalid syntax for ~S option: ~S")
caller name ':duplicates option))
(cdr option))
;; Adds the function-macro definitions of CALL-NEXT-METHOD and NEXT-METHOD-P.
(defun add-next-method-local-functions (backpointer cont req-dummies rest-dummy body)
`(SYSTEM::FUNCTION-MACRO-LET
((CALL-NEXT-METHOD
((&REST NEW-ARGS)
(IF NEW-ARGS
;; argument checking in the interpreter only
(IF (EVAL-WHEN (EVAL) T)
(%CALL-NEXT-METHOD
,backpointer
,cont
,(if rest-dummy
`(LIST* ,@req-dummies ,rest-dummy)
`(LIST ,@req-dummies))
NEW-ARGS)
(IF ,cont
(APPLY ,cont NEW-ARGS)
(APPLY (FUNCTION %NO-NEXT-METHOD) ,backpointer NEW-ARGS)))
,(if rest-dummy
`(IF ,cont
(APPLY ,cont ,@req-dummies ,rest-dummy)
(APPLY (FUNCTION %NO-NEXT-METHOD) ,backpointer
,@req-dummies ,rest-dummy))
`(IF ,cont
(FUNCALL ,cont ,@req-dummies)
(%NO-NEXT-METHOD ,backpointer ,@req-dummies)))))
,(system::make-funmacro-full-lambdabody
`(CALL-NEXT-METHOD (&REST NEW-ARG-EXPRS)
(IF NEW-ARG-EXPRS
;; argument checking in the interpreter only
(LIST 'IF '(EVAL-WHEN (EVAL) T)
(LIST '%CALL-NEXT-METHOD
',backpointer
',cont
(LIST ',(if rest-dummy 'LIST* 'LIST)
,@(mapcar #'(lambda (x) `',x) req-dummies)
,@(if rest-dummy `(',rest-dummy) '()))
(CONS 'LIST NEW-ARG-EXPRS))
(LIST 'IF ',cont
(LIST* 'FUNCALL ',cont NEW-ARG-EXPRS)
(LIST* '%NO-NEXT-METHOD ',backpointer NEW-ARG-EXPRS)))
,(if rest-dummy
`(LIST 'IF ',cont
(LIST 'APPLY ',cont
,@(mapcar #'(lambda (x) `',x) req-dummies)
',rest-dummy)
(LIST 'APPLY '(FUNCTION %NO-NEXT-METHOD)
',backpointer
,@(mapcar #'(lambda (x) `',x) req-dummies)
',rest-dummy))
`(LIST 'IF ',cont
(LIST 'FUNCALL ',cont
,@(mapcar #'(lambda (x) `',x) req-dummies))
(LIST '%NO-NEXT-METHOD
',backpointer
,@(mapcar #'(lambda (x) `',x) req-dummies))))))))
(NEXT-METHOD-P
(() ,cont)
,(system::make-funmacro-full-lambdabody
`(NEXT-METHOD-P () ',cont))))
,@body))
(defmacro call-method (&whole whole-form
method &optional next-methods-list)
(declare (ignore method next-methods-list))
(error-of-type 'ext:source-program-error
:form whole-form
:detail whole-form
(TEXT "~S is possible only from within the context of an effective method function. See ~S.")
'call-method 'define-method-combination))
(defmacro make-method (&whole whole-form
form)
(declare (ignore form))
(error-of-type 'ext:source-program-error
:form whole-form
:detail whole-form
(TEXT "~S is possible only at particular places from within the context of an effective method function. See ~S.")
'make-method 'define-method-combination))
(defun make-method-error (whole-form)
(error-of-type 'ext:source-program-error
:form whole-form
:detail whole-form
(TEXT "~S cannot be used here: ~S")
'make-method whole-form))
(defun callable-method-form-p (form)
(or (typep-class form <method>)
(and (consp form) (eq (car form) 'MAKE-METHOD)
(consp (cdr form)) (null (cddr form)))))
(defun call-method-arg1-error (whole-form)
(error-of-type 'ext:source-program-error
:form whole-form
:detail whole-form
(TEXT "~S: The first argument is neither a method nor a (MAKE-METHOD ...) form: ~S")
'call-method whole-form))
(defun call-method-arg2-error (whole-form)
(error-of-type 'ext:source-program-error
:form whole-form
:detail whole-form
(TEXT "~S: The second argument is not a list: ~S")
'call-method whole-form))
(defun call-method-arg2elements-error (whole-form)
(error-of-type 'ext:source-program-error
:form whole-form
:detail whole-form
(TEXT "~S: The second argument is not a list of methods or (MAKE-METHOD ...) forms: ~S")
'call-method whole-form))
;; Returns pieces of code to be used in the expansion of the effective-method.
;; 1. the lambda-list of the effective-method.
;; 2. the part of the lambda-list responsible for keyword checking.
;; 3. a declarations/forms list to use right after the lambda-list.
;; 4. an application primitive to use with argument lists for the methods.
;; 5. a list of forms representing the arguments to pass to methods.
;; 6. a set of macro definitions that defines local macros.
(defun effective-method-code-bricks (gf methods duplicates)
(let* ((signature (safe-gf-signature gf))
(req-num (sig-req-num signature))
(req-vars (gensym-list req-num))
(restp (gf-sig-restp signature))
(rest-var (if restp (gensym)))
(apply-fun (if restp 'APPLY 'FUNCALL))
(apply-args `(,@req-vars ,@(if restp `(,rest-var) '())))
(lambdalist `(,@req-vars ,@(if restp `(&REST ,rest-var) '()))))
(multiple-value-bind (opt-vars key-vars lambdalist-keypart)
(gf-keyword-arguments restp signature methods)
(values
;; 1. lambda-list
(if (null opt-vars)
(append lambdalist lambdalist-keypart)
lambdalist)
;; 2. lambda-list &key part
lambdalist-keypart
;; 3. declarations and first forms
(if (null opt-vars)
(if key-vars `((DECLARE (IGNORE ,@key-vars))) '())
`((APPLY #'(LAMBDA (&OPTIONAL ,@opt-vars ,@lambdalist-keypart)
(DECLARE (IGNORE ,@opt-vars ,@key-vars)))
,rest-var)))
;; 4. application primitive
apply-fun
;; 5. list of forms representing the argument
apply-args
;; 6. macro definitions
`((MAKE-METHOD (&WHOLE WHOLE FORM)
(DECLARE (IGNORE FORM))
(MAKE-METHOD-ERROR WHOLE))
(CALL-METHOD (&WHOLE WHOLE METHOD &OPTIONAL NEXT-METHODS-LIST)
(UNLESS (CALLABLE-METHOD-FORM-P METHOD)
(CALL-METHOD-ARG1-ERROR WHOLE))
(UNLESS (LISTP NEXT-METHODS-LIST)
(CALL-METHOD-ARG2-ERROR WHOLE))
,@(when duplicates
`((LET ((METHOD+GROUPNAME (ASSOC METHOD ',duplicates :TEST #'EQ)))
(WHEN METHOD+GROUPNAME
(CALL-METHOD-DUPLICATES-ERROR ',gf METHOD+GROUPNAME)))))
(LET ((NEXT-METHODS-EM-FORM
(IF NEXT-METHODS-LIST
(LIST 'FUNCTION
(LIST 'LAMBDA ',lambdalist
(LIST 'CALL-METHOD (CAR NEXT-METHODS-LIST)
(CDR NEXT-METHODS-LIST))))
'NIL)))
(IF (TYPEP-CLASS METHOD <METHOD>)
(IF (AND (TYPEP-CLASS METHOD <STANDARD-METHOD>)
(STD-METHOD-FAST-FUNCTION METHOD))
; Fast method function calling conventions.
(IF (STD-METHOD-WANTS-NEXT-METHOD-P METHOD)
(LIST* ',apply-fun (LIST 'QUOTE (STD-METHOD-FAST-FUNCTION METHOD))
NEXT-METHODS-EM-FORM ',apply-args)
; Some methods are known a-priori to not use the next-method list.
(LIST* ',apply-fun (LIST 'QUOTE (STD-METHOD-FAST-FUNCTION METHOD))
',apply-args))
; Slow method function calling conventions.
(PROGN
(UNLESS (EVERY #'CALLABLE-METHOD-FORM-P NEXT-METHODS-LIST)
(CALL-METHOD-ARG2ELEMENTS-ERROR WHOLE))
(LIST 'FUNCALL (LIST 'QUOTE (METHOD-FUNCTION METHOD))
',(cons (ecase apply-fun (APPLY 'LIST*) (FUNCALL 'LIST))
apply-args)
(LIST* 'LIST
(MAPCAR #'(LAMBDA (NEXT-METHOD)
(IF (TYPEP-CLASS NEXT-METHOD <METHOD>)
NEXT-METHOD ; no need to quote, since self-evaluating
(LIST 'LET
(LIST (LIST 'METHOD-CLASS
'',(safe-gf-default-method-class gf))
'(BACKPOINTER (LIST NIL)))
(LIST 'APPLY
'#'MAKE-METHOD-INSTANCE
'METHOD-CLASS
':LAMBDA-LIST '',lambdalist
''SIGNATURE ,signature
':SPECIALIZERS '',(make-list req-num :initial-element <t>)
''BACKPOINTER 'BACKPOINTER
(LIST 'METHOD-FUNCTION-INITARGS
'METHOD-CLASS
(LIST 'CONS
(LET ((CONT (GENSYM)))
(LIST 'FUNCTION
(LIST 'LAMBDA (CONS CONT ',lambdalist)
(LIST 'DECLARE (LIST 'IGNORABLE CONT))
(ADD-NEXT-METHOD-LOCAL-FUNCTIONS 'NIL CONT ',req-vars ',rest-var
(CDR NEXT-METHOD)))))
(LIST 'QUOTE '(NIL))))))))
NEXT-METHODS-LIST)))))
(LET ((CONT (GENSYM)))
(LIST 'LET (LIST (LIST CONT NEXT-METHODS-EM-FORM))
(LIST 'DECLARE (LIST 'IGNORABLE CONT))
(ADD-NEXT-METHOD-LOCAL-FUNCTIONS 'NIL CONT ',req-vars ',rest-var
(CDR METHOD))))))))))))
;; Given the generic function, its combination, and the effective method form
;; and the arguments-lambda-list specifying variables for it, constructs the
;; function form for the effective method, including correct arguments and with
;; the next-method support.
(defun build-effective-method-function-form (generic-function combination methods
effective-method-form
combination-arguments-lambda-list
generic-function-variable
duplicates)
(multiple-value-bind (lambdalist lambdalist-keypart firstforms apply-fun apply-args macrodefs)
(effective-method-code-bricks generic-function methods duplicates)
(let* ((declarations (method-combination-declarations combination))
(ef-fun
(if (and ;; Optimize the special but frequent case of
;; effective-method-form = `(CALL-METHOD ,method ...)
;; where CALL-METHOD would expand to a single call
;; without needing a next-methods argument and the outer
;; LAMBDA does not need to do keyword argument checking.
(consp effective-method-form)
(eq (first effective-method-form) 'CALL-METHOD)
(consp (cdr effective-method-form))
(typep-class (second effective-method-form) <standard-method>)
(let ((method (second effective-method-form)))
(and (std-method-fast-function method)
(not (std-method-wants-next-method-p method))
(null (assoc method duplicates :test #'eq))))
(null lambdalist-keypart))
(std-method-fast-function (second effective-method-form))
(let ((wrapped-ef-form
`(MACROLET ,macrodefs
,effective-method-form)))
(when combination-arguments-lambda-list
;; Use an inline lambda to assign values to the variables
;; of the combination-arguments-lambda-list.
(multiple-value-bind (whole reqvars optvars optinits optsvars rest
keyp keywords keyvars keyinits keysvars
allowp auxvars auxinits)
(sys::analyze-method-combination-lambdalist combination-arguments-lambda-list
#'(lambda (lalist detail errorstring &rest arguments)
(sys::lambda-list-error lalist detail
(TEXT "In ~S ~S lambda list: ~A")
combination ':arguments
(apply #'format nil errorstring arguments))))
(declare (ignore optinits optsvars
keywords keyvars keyinits keysvars
allowp auxvars auxinits))
(let ((whole-var nil)
(whole-form nil))
(unless (eql whole 0)
(setq whole-var whole)
(setq whole-form (list* (ecase apply-fun
(APPLY 'LIST*)
(FUNCALL 'LIST))
apply-args))
(setq combination-arguments-lambda-list
(cddr combination-arguments-lambda-list)))
;; The combination-arguments-lambda-list has an implicit
;; &ALLOW-OTHER-KEYS.
(when (and (memq '&KEY combination-arguments-lambda-list)
(not (memq '&ALLOW-OTHER-KEYS combination-arguments-lambda-list)))
(let ((i (or (position '&AUX combination-arguments-lambda-list)
(length combination-arguments-lambda-list))))
(setq combination-arguments-lambda-list
(append (subseq combination-arguments-lambda-list 0 i)
'(&ALLOW-OTHER-KEYS)
(subseq combination-arguments-lambda-list i)))))
(let* ((ll-req-num (length reqvars))
(ll-opt-num (length optvars))
(signature (safe-gf-signature generic-function))
(gf-req-num (sig-req-num signature))
(gf-opt-num (sig-opt-num signature)))
;; "If the section of the :arguments lambda-list is
;; shorter, extra arguments are ignored."
(when (< ll-req-num gf-req-num)
(setq apply-args (append (subseq apply-args 0 ll-req-num)
(subseq apply-args gf-req-num))))
;; "If the section of the :arguments lambda-list is
;; longer, excess required parameters are bound to
;; forms that evaluate to nil and excess optional
;; parameters are bound to their initforms."
(when (> ll-req-num gf-req-num)
(setq apply-args (append (subseq apply-args 0 gf-req-num)
(make-list (- ll-req-num gf-req-num)
:initial-element 'NIL)
(subseq apply-args gf-req-num))))
;; Now the required parameters section of apply-args
;; has length ll-req-num.
;; Likewise for the &optional section.
(when (< ll-opt-num gf-opt-num)
(let* ((has-&optional (eq (nth ll-req-num combination-arguments-lambda-list) '&OPTIONAL))
(i (+ ll-req-num (if has-&optional 1 0) ll-opt-num)))
(setq combination-arguments-lambda-list
(append (subseq combination-arguments-lambda-list 0 i)
(if has-&optional '() '(&OPTIONAL))
(gensym-list (- gf-opt-num ll-opt-num))
(subseq combination-arguments-lambda-list i)))))
(when (> ll-opt-num gf-opt-num)
;; In this case we have to split the one lambda into
;; two or three ones.
;; Outermost lambda: the required and present optional
;; variables.
;; Inner lambda: The missing optional variables.
;; Innermost lambda: The &rest/&key variables.
(let ((combination-arguments-rest
(subseq combination-arguments-lambda-list (+ ll-req-num 1 ll-opt-num)))
(apply-args-rest (subseq apply-args ll-req-num)))
(when (memq (first combination-arguments-rest) '(&REST &KEY))
(setq wrapped-ef-form
`(,apply-fun #'(LAMBDA ,(append (if (> gf-opt-num 0) '(&OPTIONAL) '())
(gensym-list gf-opt-num)
combination-arguments-rest)
,@declarations
,wrapped-ef-form)
,@apply-args-rest))
(setq combination-arguments-lambda-list
(subseq combination-arguments-lambda-list 0 (+ ll-req-num 1 ll-opt-num))))
(setq wrapped-ef-form
`(FUNCALL #'(LAMBDA (&OPTIONAL ,@(subseq combination-arguments-lambda-list (+ ll-req-num 1 gf-opt-num)))
,@declarations
,wrapped-ef-form)))
(setq combination-arguments-lambda-list
(subseq combination-arguments-lambda-list 0 (+ ll-req-num 1 gf-opt-num)))
(when (memq (first combination-arguments-rest) '(&REST &KEY))
(setq combination-arguments-lambda-list
(append combination-arguments-lambda-list `(&REST ,(gensym)))))))
;; When lambdalist has &rest or &key but combination-arguments-lambda-list
;; doesn't, add a dummy &rest variable to it.
(when (and (eq apply-fun 'APPLY)
(not (or (not (eql rest 0)) keyp)))
(let ((i (or (position '&AUX combination-arguments-lambda-list)
(length combination-arguments-lambda-list))))
(setq combination-arguments-lambda-list
(append (subseq combination-arguments-lambda-list 0 i)
`(&REST ,(gensym))
(subseq combination-arguments-lambda-list i)))))
;; "&whole var can be placed first in the :arguments lambda-list."
(when whole-form
(setq combination-arguments-lambda-list
(cons whole-var combination-arguments-lambda-list))
(setq apply-args (cons whole-form apply-args)))
(setq wrapped-ef-form
`(,apply-fun #'(LAMBDA ,combination-arguments-lambda-list
,@declarations
,wrapped-ef-form)
,@apply-args))))))
(when generic-function-variable
(setq wrapped-ef-form
`(LET ((,generic-function-variable ',generic-function))
,@declarations
,wrapped-ef-form)))
`#'(LAMBDA ,lambdalist
,@declarations
,@firstforms
,wrapped-ef-form)))))
ef-fun)))
(defun compute-effective-method-<generic-function> (gf combination methods)
;; Apply method combination:
(funcall (method-combination-expander combination)
gf combination (method-combination-options combination) methods))
;; Preliminary.
(predefun compute-effective-method (gf combination methods)
(compute-effective-method-<generic-function> gf combination methods))
(defun compute-effective-method-as-function-form (gf combination methods *method-combination-arguments*)
;; Call the customizable compute-effective-method from the MOP. (No need to
;; verify that it produces exactly two values: Many user-defined methods
;; probably return just the first value, letting the second value default
;; to empty.)
(multiple-value-bind (effective-method-form effective-method-options)
(funcall (cond ((or (eq gf |#'compute-discriminating-function|) ; for bootstrapping
(eq gf |#'compute-effective-method|)
(eq gf |#'compute-applicable-methods-using-classes|))
#'compute-effective-method-<generic-function>)
(t #'compute-effective-method))
gf combination methods)
;; Build a function form around the inner form:
(build-effective-method-function-form gf combination methods
effective-method-form
(let ((option (assoc ':ARGUMENTS effective-method-options)))
(if option
(check-em-arguments-option option 'compute-discriminating-function nil gf)
'()))
;; Supporting the :GENERIC-FUNCTION effective-method option here is
;; is useless, since COMPUTE-EFFECTIVE-METHOD has been passed the
;; generic function as argument, and COMPUTE-EFFECTIVE-METHOD could just
;; use this generic function object (quoted or not, doesn't matter, since
;; it's self-evaluating) instead of introducing a variable. But the MOP
;; p. 42 talks about it, and it increases consistency with the
;; DEFINE-METHOD-COMBINATION macro, so let's support it.
(let ((option (assoc ':GENERIC-FUNCTION effective-method-options)))
(if option
(check-em-generic-function-option option 'compute-discriminating-function nil gf)
nil))
(let ((option (assoc ':DUPLICATES effective-method-options)))
(if option
(check-em-duplicates-option option 'compute-discriminating-function gf)
'())))))
;;; ----------------------- Standard Method Combination -----------------------
(defun standard-method-combination-check-options (gf-name combination options)
(declare (ignore combination))
(unless (null options)
(error-of-type 'program-error
(TEXT "~S ~S: The ~S method combination permits no options: ~S")
'defgeneric gf-name 'standard options)))
;; partition the methods according to qualifiers
(defun partition-method-list (methods gf)
(let ((primary-methods '())
(before-methods '())
(after-methods '())
(around-methods '()))
(dolist (method methods)
(let ((quals (safe-method-qualifiers method gf)))
(cond ((equal quals '()) (push method primary-methods))
((equal quals '(:before)) (push method before-methods))
((equal quals '(:after)) (push method after-methods))
((equal quals '(:around)) (push method around-methods)))))
(values
(nreverse primary-methods)
(nreverse before-methods)
(nreverse after-methods)
(nreverse around-methods))))
(defun standard-method-combination-expander (gf combination options methods)
(declare (ignore combination))
(declare (ignore options)) ; already checked in check-options
;; Split up into individual method types.
(multiple-value-bind (primary-methods before-methods after-methods around-methods)
(partition-method-list methods gf)
(when (null primary-methods)
(return-from standard-method-combination-expander
(let ((rest-variable (gensym)))
(values `(APPLY #'NO-PRIMARY-METHOD ',gf ,rest-variable)
`((:ARGUMENTS &WHOLE ,rest-variable))))))
;; Combine methods into an "effective method":
(labels ((ef-1 (primary-methods before-methods after-methods
around-methods)
(if (null around-methods)
(ef-2 primary-methods before-methods after-methods)
(let ((next-ef
(ef-1 primary-methods before-methods
after-methods (rest around-methods))))
`(CALL-METHOD ,(first around-methods)
,(list `(MAKE-METHOD ,next-ef))))))
(forms-for-invoking-sequentially (methods)
(mapcar #'(lambda (method)
`(CALL-METHOD ,method))
methods))
(ef-2 (primary-methods before-methods after-methods)
(let ((next-ef (ef-3 primary-methods after-methods)))
(if (null before-methods)
next-ef
`(PROGN
; most-specific-first:
,@(forms-for-invoking-sequentially before-methods)
,next-ef))))
(ef-3 (primary-methods after-methods)
(let ((next-ef (ef-4 primary-methods)))
(if (null after-methods)
next-ef
`(MULTIPLE-VALUE-PROG1
,next-ef
; most-specific-last:
,@(forms-for-invoking-sequentially (reverse after-methods))))))
(ef-4 (primary-methods)
`(CALL-METHOD ,(first primary-methods) ,(rest primary-methods))))
(values
(ef-1 primary-methods before-methods after-methods around-methods)
'()))))
(defun standard-method-combination-check-method-qualifiers (gf method-combo method)
;; CLtL2 28.1.7.2., 28.1.7.4., ANSI CL 7.6.6.2., 7.6.6.4. Method qualifiers
(let ((qualifiers (method-qualifiers method)))
(when qualifiers
(let ((allowed-qualifiers (method-combination-qualifiers method-combo)))
(if allowed-qualifiers
(dolist (q qualifiers)
(unless (member q allowed-qualifiers)
(error-of-type 'program-error
(TEXT "~S method combination, used by ~S, allows no method qualifiers except ~S: ~S")
(method-combination-name method-combo) gf allowed-qualifiers method)))
(error-of-type 'program-error
(TEXT "~S method combination, used by ~S, does not allow method qualifiers: ~S")
(method-combination-name method-combo) gf method))
(when (> (length qualifiers) 1)
(error-of-type 'program-error
(TEXT "~S method combination, used by ~S, does not allow more than one method qualifier on a method: ~S")
(method-combination-name method-combo) gf method))))))
(defun standard-method-combination-call-next-method-allowed (gf method-combo method)
(declare (ignore gf method-combo))
(let ((qualifiers (method-qualifiers method)))
(or (equal qualifiers '()) (equal qualifiers '(:around)))))
(setf (get-method-combination 'standard)
(make-instance-<method-combination> <method-combination>
:name 'standard
:documentation "the STANDARD METHOD-COMBINATION object"
:qualifiers '(:before :after :around)
:check-options #'standard-method-combination-check-options
:expander #'standard-method-combination-expander
:check-method-qualifiers #'standard-method-combination-check-method-qualifiers
:call-next-method-allowed #'standard-method-combination-call-next-method-allowed))
;;; ---------------------- Short-Form Method Combination ----------------------
(defun short-form-method-combination-check-options (gf-name combination options) ; ABI
(any-method-combination-check-options gf-name combination options
(function method-combination-option-checker
(lambda (&optional (order ':most-specific-first))
(unless (memq order '(:most-specific-first :most-specific-last))
(invalid-sort-order-error 'order order))))))
(defun short-form-method-combination-expander (gf combination options methods) ; ABI
(sys::simple-destructuring-bind (&optional (order ':most-specific-first)) options
(let ((operator (method-combination-operator combination)))
(multiple-value-bind (primary around)
(let ((primary-methods '())
(around-methods '()))
(dolist (method methods)
(let ((quals (method-qualifiers method)))
(if (equal quals '(:around))
(push method around-methods)
(push method primary-methods))))
(when (null primary-methods)
(return-from short-form-method-combination-expander
(let ((rest-variable (gensym)))
(values `(APPLY #'NO-PRIMARY-METHOD ',gf ,rest-variable)
`((:ARGUMENTS &WHOLE ,rest-variable))))))
(values
(ecase order
(:most-specific-first (nreverse primary-methods))
(:most-specific-last primary-methods))
(nreverse around-methods)))
(let ((form
(if (and (null (rest primary))
(method-combination-identity-with-one-argument combination))
`(CALL-METHOD ,(first primary))
`(,operator ,@(mapcar #'(lambda (method) `(CALL-METHOD ,method)) primary)))))
(when around
(setq form `(CALL-METHOD ,(first around)
(,@(rest around) (make-method ,form)))))
(values form '()))))))
(defun short-form-method-combination-check-method-qualifiers
(gf method-combo method) ; ABI
(standard-method-combination-check-method-qualifiers gf method-combo method)
(let ((qualifiers (method-qualifiers method)))
(when (null qualifiers)
(error-of-type 'program-error
(TEXT "~S method combination, used by ~S, does not allow less than one method qualifier on a method: ~S")
(method-combination-name method-combo) gf method))))
(defun short-form-method-combination-call-next-method-allowed
(gf method-combo method) ; ABI
(declare (ignore gf method-combo))
(let ((qualifiers (method-qualifiers method)))
(equal qualifiers '(:around))))
;;; Predefined method combinations.
(dolist (name '(+ and append list max min nconc or progn))
(setf (get-method-combination name)
(make-instance-<method-combination> <method-combination>
:name name :operator name
:qualifiers (list name ':around)
:identity-with-one-argument (not (eq name 'list))
:documentation (format nil "the ~A ~A object"
name 'method-combination)
:check-options #'short-form-method-combination-check-options
:expander #'short-form-method-combination-expander
:check-method-qualifiers #'short-form-method-combination-check-method-qualifiers
:call-next-method-allowed #'short-form-method-combination-call-next-method-allowed)))
;;; ---------------------- Long-Form Method Combination ----------------------
(defun long-form-method-combination-expander
(*method-combination-generic-function* *method-combination* options methods) ; ABI
(multiple-value-bind (effective-method-form duplicates)
(apply (method-combination-long-expander *method-combination*)
*method-combination-generic-function* methods options)
(values
effective-method-form
`((:ARGUMENTS ,@(method-combination-arguments-lambda-list *method-combination*))
(:DUPLICATES ,@duplicates)))))
(defun long-form-method-combination-call-next-method-allowed (gf method-combo method) ; ABI
(declare (ignore gf method-combo method))
t)
;; ANSI CL says that when "two methods [with identical specializers, but with
;; different qualifiers,] play the same role and their order matters, an error
;; is signaled".
;; The way we implement this is that after partitioning the sorted list of
;; applicable methods into method groups, we scan the (still sorted!) lists
;; of each method group for duplicates. We don't signal an error on them
;; immediately, because they could be ignored, but instead let CALL-METHOD
;; signal an error on them.
(defun long-form-method-combination-collect-duplicates (methods groupname) ; ABI
(let ((duplicates '())
(last-was-duplicate nil))
(do ((l methods (cdr l)))
((endp (cdr l)))
(let ((method1 (first l))
(method2 (second l)))
(if (specializers-agree-p (method-specializers method1)
(method-specializers method2))
;; The specializers agree, so we know the qualifiers must differ.
(progn
(unless last-was-duplicate (push (cons method1 groupname) duplicates))
(push (cons method2 groupname) duplicates)
(setq last-was-duplicate t))
(setq last-was-duplicate nil))))
duplicates))
;;; ------------------------ DEFINE-METHOD-COMBINATION ------------------------
(defun parse-method-groups (whole-form name method-groups)
(labels ((group-error (group detail message &rest message-args)
(error-of-type 'ext:source-program-error
:form whole-form
:detail detail
(TEXT "~S ~S: invalid method group specifier ~S: ~A")
'define-method-combination name group
(apply #'format nil message message-args)))
;; Performs the syntax check of a method-group-specifier and
;; returns a simple-vector
;; #(name patterns/predicate orderform required-p description)
;; The second element can be a non-empty list of patterns, or a
;; non-null symbol naming a predicate.
(normalize-group (group)
(unless (and (consp group) (consp (cdr group)))
(group-error group group
(TEXT "Not a list of length at least 2")))
(let ((variable (car group))
(groupr (cdr group))
(patterns '())
(predicate nil)
(orderforms '())
(requireds '())
(description nil))
(unless (symbolp variable)
(group-error group variable (TEXT "Not a variable name: ~S")
variable))
; Parse the {qualifier-pattern+ | predicate} part:
(do ()
((atom groupr))
(let ((qp (car groupr)))
(cond ((or (eq qp '*)
(and (listp qp)
(memq (cdr (last qp)) '(nil *))))
; A qualifier pattern.
(when predicate
(group-error group predicate (TEXT "In method group ~S: Cannot specify both qualifier patterns and a predicate.") variable))
(push qp patterns))
((memq qp '(:DESCRIPTION :ORDER :REQUIRED))
; End of the {qualifier-pattern+ | predicate} part.
(return))
((symbolp qp)
; A predicate.
(when predicate
(group-error group predicate (TEXT "In method group ~S: Cannot specify more than one predicate.") variable))
(when patterns
(group-error group patterns (TEXT "In method group ~S: Cannot specify both qualifier patterns and a predicate.") variable))
(setq predicate qp))
(t
(group-error group qp (TEXT "In method group ~S: Neither a qualifier pattern nor a predicate: ~S") variable qp))))
(setq groupr (cdr groupr)))
(do ()
((atom groupr))
(when (atom (cdr groupr))
(group-error group groupr (TEXT "In method group ~S: options must come in pairs") variable))
(let ((optionkey (first groupr))
(argument (second groupr)))
(case optionkey
(:ORDER
(when orderforms
(group-error group orderforms (TEXT "In method group ~S: option ~S may only be given once") variable ':order))
(setq orderforms (list argument)))
(:REQUIRED
(when requireds
(group-error group requireds (TEXT "In method group ~S: option ~S may only be given once") variable ':required))
(setq requireds (list (not (null argument)))))
(:DESCRIPTION
(when description
(group-error group description (TEXT "In method group ~S: option ~S may only be given once") variable ':description))
(unless (stringp argument)
(group-error group argument (TEXT "In method group ~S: ~S is not a string") variable argument))
(setq description argument))
(t
(group-error group optionkey (TEXT "In method group ~S: Invalid option ~S") variable optionkey))))
(setq groupr (cddr groupr)))
(unless (or patterns predicate)
(group-error group group (TEXT "In method group ~S: Missing pattern or predicate.") variable))
(vector variable
(or predicate (nreverse patterns))
(if orderforms (first orderforms) '':MOST-SPECIFIC-FIRST)
(if requireds (first requireds) 'NIL)
(or description
(concatenate 'string
(sys::format-quote (format nil "~A" variable))
"~@{ ~S~}"))))))
(mapcar #'normalize-group method-groups)))
;; Given the normalized method group specifiers, computes
;; 1. a function without arguments, that checks the options,
;; 2. a function to be applied to a list of methods to produce the effective
;; method function's body and the list of duplicate methods. The group
;; variables are bound in the body.
;; 3. a function to be applied to a single method to produce a qualifiers check.
(defun compute-method-partition-lambdas (method-groups body)
(let ((order-bindings nil))
(labels (;; Returns a form that tests whether a list of qualifiers, assumed
;; to be present in the variable QUALIFIERS, matches the given pattern.
(compute-match-predicate-1 (pattern)
; Already checked above.
(assert (or (eq pattern '*)
(and (listp pattern)
(memq (cdr (last pattern)) '(nil *)))))
(cond ((null pattern) `(NULL QUALIFIERS))
((eq pattern '*) `T)
((null (cdr (last pattern))) `(EQUAL QUALIFIERS ',pattern))
(t (let* ((required-part (ldiff pattern '*))
(n (length required-part)))
`(AND (SYS::CONSES-P ,n QUALIFIERS)
(EQUAL (LDIFF QUALIFIERS (NTHCDR ,n QUALIFIERS))
',required-part))))))
;; Returns a form that tests whether a list of qualifiers, assumed
;; to be present in the variable QUALIFIERS, satisfies the test
;; for the given normalized method group description.
(compute-match-predicate (ngroup)
(let ((patterns (svref ngroup 1)))
; Already checked above.
(assert (and (or (listp patterns) (symbolp patterns))
(not (null patterns))))
(if (listp patterns)
`(OR ,@(mapcar #'compute-match-predicate-1 patterns))
`(,patterns QUALIFIERS))))
;; Tests whether there is only a single list of qualifiers that
;; matches the patterns.
(match-is-equality-p (ngroup)
(let ((patterns (svref ngroup 1)))
; Already checked above.
(assert (and (or (listp patterns) (symbolp patterns))
(not (null patterns))))
(if (listp patterns)
(and (= (length (remove-duplicates patterns :test #'equal)) 1)
(let ((pattern (first patterns)))
(and (listp pattern) (null (cdr (last pattern))))))
nil)))
;; Returns the variable binding for the given normalized method
;; group description.
(compute-variable-binding (ngroup)
(let ((variable (svref ngroup 0)))
`(,variable NIL)))
;; Returns a form that computes the duplicates among the contents
;; of the variable for the given normalized method group description.
(compute-duplicates-form (ngroup)
(unless (match-is-equality-p ngroup)
(let ((variable (svref ngroup 0)))
`(LONG-FORM-METHOD-COMBINATION-COLLECT-DUPLICATES ,variable ',variable))))
;; Returns a form that performs the :required check for the given
;; normalized method group description.
(compute-required-form (ngroup)
(let ((variable (svref ngroup 0))
(required-p (svref ngroup 3)))
(when required-p
`(UNLESS ,variable
(APPLY #'MISSING-REQUIRED-METHOD
*METHOD-COMBINATION-GENERIC-FUNCTION*
*METHOD-COMBINATION*
',variable
#'(LAMBDA (METH)
(LET ((QUALIFIERS (METHOD-QUALIFIERS METH)))
(DECLARE (IGNORABLE QUALIFIERS))
,(compute-match-predicate ngroup)))
*METHOD-COMBINATION-ARGUMENTS*)))))
;; Returns a form that reorders the list of methods in the method
;; group that originates from the given normalized method group
;; description.
(compute-reorder-form (ngroup)
;; If an order spec is present, make a binding for the
;; shared value and use that to decide whether to reverse.
;; If the order is :most-positive-first, we have to reverse,
;; to undo the reversal done by the previous PUSH operations.
(let ((variable (svref ngroup 0))
(order-form (svref ngroup 2)))
(if (or (equal order-form '':MOST-SPECIFIC-FIRST)
(equal order-form ':MOST-SPECIFIC-FIRST))
`(SETQ ,variable (NREVERSE ,variable))
(let ((order-variable
(first (find order-form order-bindings :key #'second))))
(unless order-variable
(setq order-variable (gensym "ORDER-"))
(push `(,order-variable ,order-form) order-bindings))
`(COND ((EQ ,order-variable ':MOST-SPECIFIC-FIRST)
(SETQ ,variable (NREVERSE ,variable)))
((EQ ,order-variable ':MOST-SPECIFIC-LAST))
(T (INVALID-METHOD-SORT-ORDER-ERROR ',order-form ,order-variable))))))))
(let ((match-clauses '())
(check-forms '()))
(dolist (ngroup method-groups)
(let ((variable (svref ngroup 0))
(qualifier-test-form (compute-match-predicate ngroup)))
(push `(,qualifier-test-form (PUSH METHD ,variable))
match-clauses)
(push qualifier-test-form check-forms)))
(setq match-clauses (nreverse match-clauses))
(setq check-forms (nreverse check-forms))
(let ((duplicates-forms
(delete nil (mapcar #'compute-duplicates-form method-groups)))
(order-forms
(delete nil (mapcar #'compute-reorder-form method-groups))))
(values
`(LAMBDA ()
(LET (,@order-bindings)
,@(mapcar #'(lambda (order-binding)
(let ((order-variable (first order-binding))
(order-form (second order-binding)))
`(UNLESS (MEMQ ,order-variable '(:MOST-SPECIFIC-FIRST :MOST-SPECIFIC-LAST))
(INVALID-SORT-ORDER-ERROR ',order-form ,order-variable))))
order-bindings)))
`(LAMBDA (METHODS)
(LET (,@(mapcar #'compute-variable-binding method-groups)
,@order-bindings)
(DOLIST (METHD METHODS)
(LET ((QUALIFIERS (METHOD-QUALIFIERS METHD)))
(DECLARE (IGNORABLE QUALIFIERS))
(COND ,@match-clauses
(T (INVALID-METHOD-QUALIFIERS-ERROR *METHOD-COMBINATION-GENERIC-FUNCTION* METHD)))))
(LET ,(if duplicates-forms `((DUPLICATES (NCONC ,@duplicates-forms))) '())
,@order-forms
,@(delete nil (mapcar #'compute-required-form method-groups))
(VALUES
(PROGN ,@body)
,(if duplicates-forms 'DUPLICATES 'NIL)))))
`(LAMBDA (GF METHD)
(LET ((QUALIFIERS (METHOD-QUALIFIERS METHD)))
(DECLARE (IGNORABLE QUALIFIERS))
(OR ,@check-forms
(INVALID-METHOD-QUALIFIERS-ERROR GF METHD))))))))))
(defmacro define-method-combination (&whole whole-form
name &rest options)
"The macro define-method-combination defines a new method combination.
Short-form options are :documentation, :identity-with-one-argument,
and :operator.
Long-form options are a list of method-group specifiers,
each of which comprises a sequence of qualifier patterns
followed by respective :description, :order, :required options,
and optional :generic-function, and :arguments options preceeding
the definition body."
(unless (symbolp name)
(error-of-type 'ext:source-program-error
:form whole-form
:detail name
(TEXT "~S: method combination name ~S should be a symbol")
'define-method-combination name))
(sys::check-redefinition
name 'define-method-combination
(and (get-method-combination name nil)
(TEXT "method combination")))
(cond ;; "The short form syntax ... is recognized when the second subform is
;; a non-nil symbol or is not present."
((or (null options)
(and (consp options)
(typep (first options) '(and symbol (not null)))))
;; Short form.
(when (oddp (length options))
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: options must come in pairs")
'define-method-combination name))
(let ((documentation nil)
(identities '())
(operators '()))
(do ((optionsr options (cddr optionsr)))
((atom optionsr))
(when (atom (cdr optionsr))
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: options must come in pairs")
'define-method-combination name))
(let ((optionkey (first optionsr))
(argument (second optionsr)))
(case optionkey
(:DOCUMENTATION
(when documentation
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: option ~S may only be given once")
'define-method-combination name ':documentation))
(unless (stringp argument)
(error-of-type 'ext:source-program-error
:form whole-form
:detail argument
(TEXT "~S ~S: ~S is not a string")
'define-method-combination name argument))
(setq documentation argument))
(:IDENTITY-WITH-ONE-ARGUMENT
(when identities
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: option ~S may only be given once")
'define-method-combination name ':identity-with-one-argument))
(setq identities (list (not (null argument)))))
(:OPERATOR
(when operators
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: option ~S may only be given once")
'define-method-combination name ':operator))
(unless (symbolp argument)
(error-of-type 'ext:source-program-error
:form whole-form
:detail argument
(TEXT "~S ~S, option ~S: ~S is not a symbol")
'define-method-combination name ':operator argument))
(setq operators (list argument)))
(t
(error-of-type 'ext:source-program-error
:form whole-form
:detail optionkey
(TEXT "~S ~S: ~S is not a valid short-form option")
'define-method-combination name optionkey)))))
`(DO-DEFINE-METHOD-COMBINATION
',name
,@(when documentation
`(:DOCUMENTATION ',documentation))
,@(when identities
`(:IDENTITY-WITH-ONE-ARGUMENT ',(first identities)))
:OPERATOR ',(if operators (first operators) name)
:QUALIFIERS ',(list name ':around)
:CHECK-OPTIONS #'SHORT-FORM-METHOD-COMBINATION-CHECK-OPTIONS
:EXPANDER #'SHORT-FORM-METHOD-COMBINATION-EXPANDER
:CHECK-METHOD-QUALIFIERS #'SHORT-FORM-METHOD-COMBINATION-CHECK-METHOD-QUALIFIERS
:CALL-NEXT-METHOD-ALLOWED #'SHORT-FORM-METHOD-COMBINATION-CALL-NEXT-METHOD-ALLOWED)))
;; "The long form syntax ... is recognized when the second subform is a
;; list."
((and (consp options) (listp (first options)))
;; Long form.
(unless (and (>= (length options) 2) (listp (second options)))
(error-of-type 'ext:source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: invalid syntax for long form: ~S")
'define-method-combination name whole-form))
(let ((lambda-list (first options))
(method-group-specifiers (second options))
(body (cddr options)))
; Check the lambda-list.
(analyze-lambdalist lambda-list
#'(lambda (lalist detail errorstring &rest arguments)
(declare (ignore lalist)) ; use WHOLE-FORM instead
(sys::lambda-list-error whole-form detail
(TEXT "~S ~S: invalid lambda-list: ~A")
'define-method-combination name
(apply #'format nil errorstring arguments))))
; Check the method-group-specifiers, then the rest.
(let ((method-groups
(parse-method-groups whole-form name method-group-specifiers))
(arguments-lambda-list nil)
(arguments-variables '())
(user-gf-variable nil)
(gf-name-variable (gensym "GF-NAME-"))
(gf-variable (gensym "GF-"))
(combination-variable (gensym "COMBINATION-"))
(options-variable (gensym "OPTIONS-"))
(methods-variable (gensym "METHODS-"))
(method-variable (gensym "METHOD-")))
(when (and (consp body) (consp (car body))
(eq (caar body) ':ARGUMENTS))
(multiple-value-setq (arguments-lambda-list arguments-variables)
(check-em-arguments-option (car body) 'define-method-combination whole-form name))
(setq body (cdr body)))
(when (and (consp body) (consp (car body))
(eq (caar body) ':GENERIC-FUNCTION))
(setq user-gf-variable
(check-em-generic-function-option (car body) 'define-method-combination whole-form name))
(setq body (cdr body)))
(multiple-value-bind (body-rest declarations documentation)
(sys::parse-body body t)
(when arguments-variables
;; Add bindings so that the effective method function can
;; access the arguments that were passed to generic function.
(setq body-rest
`((LET ,(mapcan
#'(lambda (variable)
(list `(,variable ',variable)))
arguments-variables)
,@body-rest))))
(multiple-value-bind (check-options-lambda partition-lambda check-lambda)
(compute-method-partition-lambdas method-groups body-rest)
`(DO-DEFINE-METHOD-COMBINATION
',name
,@(when documentation
`(:DOCUMENTATION ',documentation))
,@(when declarations
`(:DECLARATIONS '((DECLARE ,@declarations))))
,@(when arguments-lambda-list
`(:ARGUMENTS-LAMBDA-LIST ',arguments-lambda-list))
:CHECK-OPTIONS
#'(LAMBDA (,gf-name-variable ,combination-variable
,options-variable)
(ANY-METHOD-COMBINATION-CHECK-OPTIONS
,gf-name-variable ,combination-variable
,options-variable
(FUNCTION METHOD-COMBINATION-OPTION-CHECKER
(LAMBDA (,@lambda-list)
(,check-options-lambda)))))
:EXPANDER #'LONG-FORM-METHOD-COMBINATION-EXPANDER
:LONG-EXPANDER
#'(LAMBDA (,gf-variable ,methods-variable ,@lambda-list)
(LET (,@(when user-gf-variable `(,user-gf-variable ,gf-variable)))
(,partition-lambda ,methods-variable)))
:CHECK-METHOD-QUALIFIERS
#'(LAMBDA (,gf-variable ,combination-variable ,method-variable)
(DECLARE (IGNORE ,combination-variable))
(,check-lambda ,gf-variable ,method-variable))
:CALL-NEXT-METHOD-ALLOWED
#'LONG-FORM-METHOD-COMBINATION-CALL-NEXT-METHOD-ALLOWED))))))
(t (error-of-type 'ext:source-program-error
:form whole-form
:detail whole-form
(TEXT "~S ~S: invalid syntax, neither short form nor long form syntax: ~S")
'define-method-combination name whole-form))))
;; DEFINE-METHOD-COMBINATION execution.
;; Performs the instantiation and registration and returns the name.
(defun do-define-method-combination (name &rest initargs) ; ABI
(let ((method-combination
(apply #'make-instance-<method-combination> <method-combination>
:name name initargs)))
(setf (get-method-combination name) method-combination)
name))
;;; ---------------------------------- Misc ----------------------------------
(defun method-combination-with-options (gf-name combination options) ; ABI
(funcall (method-combination-check-options combination)
gf-name combination options)
(when options
(setq combination (copy-method-combination combination))
(setf (method-combination-options combination) (copy-list options)))
combination)
(defun find-method-combination-<generic-function>-<symbol> (gf name options)
(let ((combination (get-method-combination name 'defgeneric)))
(method-combination-with-options (sys::closure-name gf) combination options)))
;; Preliminary.
(predefun find-method-combination (gf name options)
(find-method-combination-<generic-function>-<symbol> gf name options))
| 69,633 | Common Lisp | .lisp | 1,241 | 40.074134 | 160 | 0.54771 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 31e23e2f6198fe0e27229eae48715d8b99dd4640b0fd00cc72a8f7d9813b30dd | 11,358 | [
-1
] |
11,359 | clos-specializer2.lisp | ufasoft_lisp/clisp/clos-specializer2.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Specializers
;;;; Part n-2: Final class definitions, make/initialize-instance methods.
;;;; Bruno Haible 2004-05-15
(in-package "CLOS")
;;; ===========================================================================
(defmethod shared-initialize ((specializer specializer) situation &rest args)
(apply #'shared-initialize-<specializer> specializer situation args))
(defmethod reinitialize-instance ((instance specializer) &rest initargs)
(declare (ignore initargs))
(error (TEXT "~S: It is not allowed to reinitialize ~S")
'reinitialize-instance instance))
;;; ===========================================================================
(defmethod shared-initialize ((specializer eql-specializer) situation &rest args
&key ((singleton singleton) nil))
(declare (ignore singleton))
(apply #'shared-initialize-<eql-specializer> specializer situation args))
;;; ===========================================================================
| 1,036 | Common Lisp | .lisp | 18 | 53.444444 | 80 | 0.563798 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | d5ce0394a4448ece2267af10ebba2c396552827ed2d9010bee8c861bd2b87476 | 11,359 | [
-1
] |
11,360 | defs1.lisp | ufasoft_lisp/clisp/defs1.lisp | ;;;; some definitions for standard functions in LISP
;;;; 1.8.1989, 2.9.1989, 8.10.1989
(in-package "EXT")
(export '(expand-form doseq dohash without-package-lock memoized))
(export '(#-(or UNIX WIN32) custom::*default-time-zone*
custom::*user-lib-directory*
custom::*system-package-list*)
"CUSTOM")
(ext:re-export "CUSTOM" "EXT")
(in-package "SYSTEM")
;;; code walker
(defun expand-form (form &aux *fenv* *venv*)
(%expand-form form))
;;; functions for symbols (Chapter 10)
(defun copy-symbol (symbol &optional flag) ;; Common LISP, p. 169
(let ((sym (make-symbol (symbol-name symbol))))
(when flag
(when (boundp symbol) (sys::set-symbol-value sym (symbol-value symbol)))
(when (fboundp symbol) (sys::%putd sym (symbol-function symbol)))
(sys::%putplist sym (copy-list (symbol-plist symbol)))
#| ;; No, ANSI CL does not say that the status of the symbol in the
;; global environment is copied as well.
(cond ((constantp symbol) (sys::%proclaim-constant sym (symbol-value symbol)))
((sys::special-variable-p symbol) (proclaim `(SPECIAL ,sym)))
((sys::global-symbol-macro-p symbol) (sys::%proclaim-symbol-macro sym)))
|#
)
sym))
(let ((gentemp-count 0)) ;; Common LISP, p. 170
(defun gentemp (&optional (prefix "T") (package *package*))
(loop
(setq gentemp-count (1+ gentemp-count))
(multiple-value-bind (sym flag)
(intern
(string-concat prefix
(write-to-string gentemp-count :base 10 :radix nil :readably nil))
package)
(unless flag (return sym))))))
;;; macros for packages (Chapter 11), p. 187-188
(defmacro do-symbols ((var &optional (packageform '*package*) (resultform nil))
&body body)
(multiple-value-bind (body-rest declarations) (system::parse-body body)
(let ((packvar (gensym "PACKAGE-")))
`(BLOCK NIL
(LET ((,packvar ,packageform))
(LET ((,var NIL))
(DECLARE (IGNORABLE ,var) ,@declarations)
(SYSTEM::MAP-SYMBOLS
#'(LAMBDA (,var)
,@(if declarations `((DECLARE ,@declarations)) '())
(TAGBODY ,@body-rest))
,packvar)
,resultform))))))
(defmacro do-external-symbols ((var &optional (packageform '*package*)
(resultform nil))
&body body)
(multiple-value-bind (body-rest declarations) (system::parse-body body)
(let ((packvar (gensym "PACKAGE-")))
`(BLOCK NIL
(LET ((,packvar ,packageform))
(LET ((,var NIL))
(DECLARE (IGNORABLE ,var) ,@declarations)
(SYSTEM::MAP-EXTERNAL-SYMBOLS
#'(LAMBDA (,var)
,@(if declarations `((DECLARE ,@declarations)) '())
(TAGBODY ,@body-rest))
,packvar)
,resultform))))))
(defmacro do-all-symbols ((var &optional (resultform nil)) &body body)
(multiple-value-bind (body-rest declarations) (system::parse-body body)
`(BLOCK NIL
(LET ((,var NIL))
(DECLARE (IGNORABLE ,var) ,@declarations)
(SYSTEM::MAP-ALL-SYMBOLS
#'(LAMBDA (,var)
,@(if declarations `((DECLARE ,@declarations)) '())
(TAGBODY ,@body-rest)))
,resultform))))
;;; <HS>/Body/mac_with-package-iterator.html
(defmacro with-package-iterator (&whole whole-form
(name pack-list &rest types) &body body)
(unless types
(error-of-type 'source-program-error
:form whole-form
:detail types ; == NIL
(TEXT "missing symbol types (~S/~S/~S) in ~S")
':internal ':external ':inherited 'with-package-iterator))
(dolist (symboltype types)
(case symboltype
((:INTERNAL :EXTERNAL :INHERITED))
(t (error-of-type 'source-program-error
:form whole-form
:detail symboltype
(TEXT "~S: flag must be one of the symbols ~S, ~S, ~S, not ~S")
'with-package-iterator ':internal ':external ':inherited
symboltype))))
(let ((iterfun (gensym "WPI-")))
`(LET ((,iterfun (SYS::PACKAGE-ITERATOR-FUNCTION
,pack-list ',(remove-duplicates types))))
(MACROLET ((,name () '(FUNCALL ,iterfun)))
,@body))))
(defun package-iterator-function (pack-list symbol-types) ; ABI
(let ((iterstates
(mapcar #'(lambda (pack) (sys::package-iterator pack symbol-types))
(if (listp pack-list) pack-list (list pack-list)))))
;; The iterstates list is cdr'ed down during the iteration.
#'(lambda ()
(loop
(if iterstates
(multiple-value-bind (more symb acc)
(sys::package-iterate (car iterstates))
(if more
(return (values more symb acc (svref (car iterstates) 4)))
(pop iterstates)))
(return nil))))))
(defvar *system-package-list*
'("SYSTEM" "COMMON-LISP" "EXT" "I18N" "GRAY" "CHARSET" "CLOS"
#+sockets "SOCKET" #+generic-streams "GSTREAM"
#+ffi "FFI" #+screen "SCREEN")
"The list of packages that will be locked by SAVEINITMEM.
Also the default packages to unlock by WITHOUT-PACKAGE-LOCK.")
;; Unlock the specified packages, execute the BODY, then lock them again.
(defmacro with-no-package-lock-internal (packages &body body)
(let ((locked-packages (gensym "WOPL-")))
`(LET ((,locked-packages (REMOVE-IF-NOT #'PACKAGE-LOCK ,packages)))
(UNWIND-PROTECT
(PROGN
(SETF (PACKAGE-LOCK ,locked-packages) NIL)
,@body)
(SETF (PACKAGE-LOCK ,locked-packages) T)))))
(defmacro without-package-lock (packages &body body)
;; NB: This is augmented by similar compiler processing,
;; see c-WITHOUT-PACKAGE-LOCK.
`(WITH-NO-PACKAGE-LOCK-INTERNAL
,(if packages `',packages '*SYSTEM-PACKAGE-LIST*)
,@body))
;;; module administration (Chapter 11.8), CLTL p. 188
(defvar *modules* nil)
; Conversion from module name to string.
; cl-user::abc -> "ABC", cs-cl-user::abc -> "abc".
(defun module-name (name)
(if (and (symbolp name)
(symbol-package name)
(package-case-inverted-p (symbol-package name)))
(cs-cl:string name)
(string name)))
(defun provide (name)
(setq *modules* (adjoin (module-name name) *modules* :test #'string=)))
(defvar *user-lib-directory* nil
"The location of user-installed modules.")
(defun augment-load-path (paths)
(dolist (path paths *load-paths*)
(when path (setq *load-paths* (adjoin path *load-paths* :test #'equal)))))
(defun load-path-augmentations (dynmod)
(list (merge-pathnames dynmod *lib-directory*)
(and *user-lib-directory*
(merge-pathnames dynmod *user-lib-directory*))
(and *load-pathname* ; not truename to respect symlinks
(make-pathname :name nil :type nil :defaults *load-pathname*))
(and *compile-file-pathname* ; could be called by eval-when-compile
(make-pathname :name nil :type nil
:defaults *compile-file-pathname*))))
(defmacro with-augmented-load-path (dirs &body body)
`(let ((*load-paths*
;; the name "dynmod/" used here should be in sync with clisp-link
(augment-load-path
,(if dirs `(list ,@dirs) '(load-path-augmentations "dynmod/")))))
,@body))
(defun require (module-name &optional (pathname nil p-given))
(setq module-name (module-name module-name))
(unless (member module-name *modules* :test #'string=)
(unless p-given (setq pathname (pathname module-name)))
(prog1
(with-augmented-load-path ()
(if (atom pathname) (load pathname) (mapcar #'load pathname)))
;; we might have loaded a `system' package: lock it,
;; unless CLISP was started with "-d" and thus locking is not desired
(when (package-lock "SYSTEM")
(|(SETF PACKAGE-LOCK)| t *system-package-list*)))))
;;; integer constants (Chapter 12)
;; see file INTLOG.D
(defconstant boole-clr 0)
(defconstant boole-set 15)
(defconstant boole-1 10)
(defconstant boole-2 12)
(defconstant boole-c1 5)
(defconstant boole-c2 3)
(defconstant boole-and 8)
(defconstant boole-ior 14)
(defconstant boole-xor 6)
(defconstant boole-eqv 9)
(defconstant boole-nand 7)
(defconstant boole-nor 1)
(defconstant boole-andc1 4)
(defconstant boole-andc2 2)
(defconstant boole-orc1 13)
(defconstant boole-orc2 11)
;; for input of BYTEs:
(defun make-byte (&key size position) (byte size position))
;; X3J13 vote <79>
(defconstant least-positive-normalized-short-float least-positive-short-float)
(defconstant least-negative-normalized-short-float least-negative-short-float)
(defconstant least-positive-normalized-single-float least-positive-single-float)
(defconstant least-negative-normalized-single-float least-negative-single-float)
(defconstant least-positive-normalized-double-float least-positive-double-float)
(defconstant least-negative-normalized-double-float least-negative-double-float)
(proclaim
'(constant-notinline
least-positive-normalized-short-float
least-negative-normalized-short-float
least-positive-normalized-single-float
least-negative-normalized-single-float
least-positive-normalized-double-float
least-negative-normalized-double-float))
;;; functions for sequences (Chapter 14)
(defmacro doseq ((var seqform &optional resultform) &body body)
(multiple-value-bind (body-rest declarations) (system::parse-body body)
(let ((seqvar (gensym "SEQ-")))
`(BLOCK NIL
(LET ((,seqvar ,seqform))
(LET ((,var NIL))
(DECLARE (IGNORABLE ,var) ,@declarations)
(MAP NIL
#'(LAMBDA (,var)
,@(if declarations `((DECLARE ,@declarations)) '())
(TAGBODY ,@body-rest))
,seqvar)
,resultform))))))
;;; functions for lists (Chapter 15)
;; convert the SET represented as a LIST to a SET represented as a HASH-TABLE
(defun list-to-ht (l0 list &key test test-not key)
(let ((n1 (list-length-proper l0))
(n2 (list-length-proper list)))
(unless test-not
(let ((ht-test (case test
(eq 'fasthash-eq)
((eql nil) 'fasthash-eql)
(equal 'fasthash-equal)
(equalp 'equalp)))) ; no separate fasthash & stablehash
(when ht-test
;; --- boxers or briefs? ---
;; when is it worthwhile to use HASH-TABLEs as opposed to LISTS?
;; in sequence.d:seq_duplicates() we use a HASH-TABLE
;; when the list is longer than 10
;; here we use the following heuristic,
;; supported by a numeric experiment on Linux
(unless (and (> n1 15) (> n2 5))
(return-from list-to-ht nil))
;; passed the test, generate the HASH-TABLE
(let ((ht (make-hash-table :test ht-test :size n2)))
(unless key (setq key #'identity))
(do ((tail list (cdr tail)))
((endp tail) ht)
(sys::puthash (funcall key (car tail)) ht tail))))))))
;; Auxiliary version of MEMBER, which applies the :KEY argument also to items
;; used only by the recursive version
;(defun sys::member1 (item list &rest rest &key test test-not key)
; (declare (ignore test test-not))
; (apply #'member (if key (funcall key item) item) list rest))
(macrolet ((member? (item)
(let ((i (gensym "ITEM-")) (k (gensym "KEY-")))
`(let* ((,i ,item) (,k (if key (funcall key ,i) ,i)))
(if ht2
;; values are non-NIL tails,
;; so the first GETHASH value is good enough
(gethash ,k ht2)
(apply #'member ,k list2 rest))))))
(defun union (list1 list2 &rest rest &key test test-not key)
(declare (ignore test test-not))
#| ; recursive (not suitable for long lists):
(cond ((endp list1) list2)
((apply #'sys::member1 (car list1) list2 rest)
(apply #'union (cdr list1) list2 rest))
(t (cons (car list1) (apply #'union (cdr list1) list2 rest))))
|# ; iterative
(let* ((list1-filtered '())
(ht2 #1=(apply #'list-to-ht list1 list2 rest)))
(dolist (item list1)
(unless (member? item)
(setq list1-filtered (cons item list1-filtered))))
(nreconc list1-filtered list2)))
(defun nunion (list1 list2 &rest rest &key test test-not key)
(declare (ignore test test-not))
#| ; recursive (not suitable for long lists):
(cond ((endp list1) list2)
((apply #'sys::member1 (car list1) list2 rest)
(apply #'nunion (cdr list1) list2 rest))
(t (rplacd list1 (apply #'nunion (cdr list1) list2 rest))))
|# ; iterative
(let* ((first nil) (last nil)
(ht2 #1#))
(do ((l list1 (cdr l)))
((endp l))
(unless (member? (car l))
(if last (rplacd last l) (setq first l))
(setq last l)))
(if last (progn (rplacd last list2) first) list2)))
(defun intersection (list1 list2 &rest rest &key test test-not key)
(declare (ignore test test-not))
#| ; recursive (not suitable for long lists):
(cond ((endp list1) nil)
((apply #'sys::member1 (car list1) list2 rest)
(cons (car list1)
(apply #'intersection (cdr list1) list2 rest)))
(t (apply #'intersection (cdr list1) list2 rest)))
|# ; iterative
(let* ((list1-filtered '())
(ht2 #1#))
(dolist (item list1)
(when (member? item)
(setq list1-filtered (cons item list1-filtered))))
(list-nreverse list1-filtered)))
(defun nintersection (list1 list2 &rest rest &key test test-not key)
(declare (ignore test test-not))
#| ; recursive (not suitable for long lists):
(cond ((endp list1) nil)
((apply #'sys::member1 (car list1) list2 rest)
(rplacd list1 (apply #'nintersection (cdr list1) list2 rest)))
(t (apply #'nintersection (cdr list1) list2 rest)))
|# ; iterative
(let* ((first nil) (last nil)
(ht2 #1#))
(do ((l list1 (cdr l)))
((endp l))
(when (member? (car l))
(if last (rplacd last l) (setq first l))
(setq last l)))
(if last (progn (rplacd last nil) first) nil)))
(defun set-difference (list1 list2 &rest rest &key test test-not key)
(declare (ignore test test-not))
#| ; recursive (not suitable for long lists):
(cond ((endp list1) nil)
((not (apply #'sys::member1 (car list1) list2 rest))
(cons (car list1)
(apply #'set-difference (cdr list1) list2 rest)))
(t (apply #'set-difference (cdr list1) list2 rest)))
|# ; iterative
(let* ((list1-filtered '())
(ht2 #1#))
(dolist (item list1)
(unless (member? item)
(setq list1-filtered (cons item list1-filtered))))
(list-nreverse list1-filtered)))
(defun nset-difference (list1 list2 &rest rest &key test test-not key)
(declare (ignore test test-not))
#| ; recursive (not suitable for long lists):
(cond ((endp list1) nil)
((not (apply #'sys::member1 (car list1) list2 rest))
(rplacd list1 (apply #'nset-difference (cdr list1) list2 rest)))
(t (apply #'nset-difference (cdr list1) list2 rest)))
|# ; iterative
(let* ((first nil) (last nil)
(ht2 #1#))
(do ((l list1 (cdr l)))
((endp l))
(unless (member? (car l))
(if last (rplacd last l) (setq first l))
(setq last l)))
(if last (progn (rplacd last nil) first) nil)))
(macrolet ((rev-arg (f) `(lambda (x y) (funcall ,f y x))))
;; this is done so that the elements of LIST1 and LIST2 are passed
;; to TEST and TEST-NOT always in the correct order
(defun set-exclusive-or (list1 list2 &rest rest &key test test-not key)
(declare (ignore key))
(append (apply #'set-difference list1 list2 rest)
(apply #'set-difference list2 list1
(cond (test (list* :test (rev-arg test) rest))
(test-not (list* :test-not (rev-arg test-not) rest))
(rest)))))
(defun nset-exclusive-or (list1 list2 &rest rest &key test test-not key)
(declare (ignore key))
(nconc (apply #'set-difference list1 list2 rest)
(apply #'nset-difference list2 list1
(cond (test (list* :test (rev-arg test) rest))
(test-not (list* :test-not (rev-arg test-not) rest))
(rest)))))
) ; macrolet rev-arg
(defun subsetp (list1 list2 &rest rest &key test test-not key)
(declare (ignore test test-not))
(do* ((l list1 (cdr l))
(ht2 #1#))
((endp l) t)
(if (not (member? (car l))) (return nil))))
) ; macrolet member?
;; Like SUBST-IF, only that the substitution element is
;; given by a function and must not be a constant
(defun subst-if-then (newfun testfun tree &key (key #'identity))
(labels ((subst (tree)
(if (funcall testfun (funcall key tree))
(funcall newfun tree)
(if (consp tree)
(let* ((car (car tree)) (cdr (cdr tree))
(newcar (subst car)) (newcdr (subst cdr)))
(if (and (eq car newcar) (eq cdr newcdr))
tree
(cons newcar newcdr)))
tree))))
(subst tree)))
;;; functions for hash tables (Chapter 16)
(defmacro dohash ((keyvar valuevar HTform &optional resultform) &body body)
(multiple-value-bind (body-rest declarations) (system::parse-body body)
(let ((HTvar (gensym "HASH-TABLE-")))
`(BLOCK NIL
(LET ((,HTvar ,HTform))
(LET ((,keyvar NIL) (,valuevar NIL))
(DECLARE (IGNORABLE ,keyvar ,valuevar) ,@declarations)
(MAPHASH
#'(LAMBDA (,keyvar ,valuevar)
,@(if declarations `((DECLARE ,@declarations)) '())
(TAGBODY ,@body-rest))
,HTvar)
,resultform))))))
;; Different hash code algorithms for the same test.
(sys::%putd 'ext:fasthash-eq #'eq)
(sys::%putd 'ext:stablehash-eq #'eq)
(sys::%putd 'ext:fasthash-eql #'eql)
(sys::%putd 'ext:stablehash-eql #'eql)
(sys::%putd 'ext:fasthash-equal #'equal)
(sys::%putd 'ext:stablehash-equal #'equal)
;;; functions for strings (Chapter 18)
(defun string-trim (character-bag string)
(sys::string-both-trim character-bag character-bag string nil))
(defun cs-cl::string-trim (character-bag string)
(sys::string-both-trim character-bag character-bag string t))
(defun string-left-trim (character-bag string)
(sys::string-both-trim character-bag nil string nil))
(defun cs-cl::string-left-trim (character-bag string)
(sys::string-both-trim character-bag nil string t))
(defun string-right-trim (character-bag string)
(sys::string-both-trim nil character-bag string nil))
(defun cs-cl::string-right-trim (character-bag string)
(sys::string-both-trim nil character-bag string t))
;;; functions for pathnames (Chapter 23.1.5)
#+LOGICAL-PATHNAMES
(export '(custom::*load-logical-pathname-translations-database*) "CUSTOM")
#+LOGICAL-PATHNAMES
(ext:re-export "CUSTOM" "EXT")
#+LOGICAL-PATHNAMES
(progn
(defvar *load-logical-pathname-translations-database* '(#p"loghosts"))
(defun logical-pathname-translations (host)
(setq host (string-upcase host))
(or (gethash host *logical-pathname-translations*) ; :test #'equal !
(error (TEXT "~S: ~S does not name a logical host")
'logical-pathname-translations host)))
(defun set-logical-pathname-translations (host translations)
(setq host (string-upcase host))
(puthash host *logical-pathname-translations* ; :test #'equal !
(mapcar #'(lambda (rule)
(cons (parse-namestring
(first rule) nil
(make-logical-pathname
:host host :name :wild :type :wild
:version :wild))
(rest rule)))
translations)))
;; load many hosts from a file, AllegroCL-style
(defun load-lpt-many (file host &aux (*load-level* (1+ *load-level*)))
(with-open-file (fi file :if-does-not-exist nil)
(unless fi (return-from load-lpt-many nil))
(loading-message (TEXT "Loading logical hosts from file ~A ...") file)
(do* ((eof fi) (host (read fi nil eof) (read fi nil eof)))
((eq host eof) (loading-message (TEXT "Loaded file ~A") file))
(setq host (string-upcase host))
(set-logical-pathname-translations host (eval (read fi)))
(loading-message (TEXT "Defined logical host ~A") host)))
(gethash host *logical-pathname-translations*))
;; load a single host from a file, CMUCL-style
(defun load-lpt-one (file host &aux (*load-level* (1+ *load-level*)))
(with-open-file (fi file :if-does-not-exist nil)
(unless fi (return-from load-lpt-one nil))
(loading-message (TEXT "Loading logical host from file ~A ...") file)
(set-logical-pathname-translations host (read fi))
(loading-message (TEXT "Defined logical host ~A") host))
(gethash host *logical-pathname-translations*))
(defun load-logical-pathname-translations (host)
(setq host (string-upcase host))
(unless (gethash host *logical-pathname-translations*) ; :test #'equal !
(let ((from (string-concat #2="LOGICAL_HOST_" host "_FROM"))
(to (string-concat #2# host "_TO"))
(ho (string-concat #2# host)))
(cond ((and (fboundp 'getenv) (getenv from) (getenv to))
(set-logical-pathname-translations
host (list (list (getenv from) (getenv to))))
(return-from load-logical-pathname-translations t))
((and (fboundp 'getenv) (getenv ho))
(set-logical-pathname-translations
host (read-from-string (getenv ho)))
(return-from load-logical-pathname-translations t))
((dolist (file *load-logical-pathname-translations-database*)
(dolist (f (search-file file '(nil "host")))
(if (pathname-name f)
(when (load-lpt-many f host) ; host defined?
(return-from load-logical-pathname-translations t))
(dolist (f1 (nconc (directory (make-pathname
:name host :defaults f))
(directory (make-pathname
:name host :type "host"
:defaults f))))
(when (load-lpt-one f1 host) ; host defined?
(return-from load-logical-pathname-translations
t)))))))))
(error (TEXT "No translations for logical host ~S found") host)))
(set-logical-pathname-translations "SYS"
'((";*.LISP" "*.lisp") (";*" "*") ("*" "/*"))))
;;; functions for time (Chapter 25.4.1)
;; help function for macro TIME ; ABI
(defun %time (new-real1 new-real2 new-run1 new-run2 new-gc1 new-gc2
new-space1 new-space2 new-gccount
old-real1 old-real2 old-run1 old-run2 old-gc1 old-gc2
old-space1 old-space2 old-gccount)
(macrolet ((diff4 (newval1 newval2 oldval1 oldval2)
(if (< internal-time-units-per-second 1000000)
;; TIME_1: UNIX_TIMES
`(delta4 ,newval1 ,newval2 ,oldval1 ,oldval2 16)
;; TIME_2: other UNIX, WIN32
`(+ (* (- ,newval1 ,oldval1) internal-time-units-per-second)
(- ,newval2 ,oldval2)))))
(let ((Real-Time (diff4 new-real1 new-real2 old-real1 old-real2))
(Run-Time (diff4 new-run1 new-run2 old-run1 old-run2))
(GC-Time (diff4 new-gc1 new-gc2 old-gc1 old-gc2))
(Space (delta4 new-space1 new-space2 old-space1 old-space2 24))
(GC-Count (- new-gccount old-gccount))
(stream *trace-output*))
(fresh-line stream)
(write-string "Real time: " stream)
(write (float (/ Real-Time internal-time-units-per-second)) :stream stream)
(write-string #1=" sec." stream)
(terpri stream)
(write-string "Run time: " stream)
(write (float (/ Run-Time internal-time-units-per-second)) :stream stream)
(write-string #1# stream)
(terpri stream)
(write-string "Space: " stream)
(write Space :stream stream)
(write-string " Bytes" stream)
(when (or (plusp GC-Count) (plusp GC-Time))
(terpri stream)
(write-string "GC: " stream) (write GC-Count :stream stream)
(write-string ", GC time: " stream)
(write (float (/ GC-Time internal-time-units-per-second)) :stream stream)
(write-string #1# stream))
(elastic-newline stream))))
;; (sleep N) pause for N seconds. CLTL p. 447
(defun sleep (time)
(if (and (realp time) (not (minusp time)))
(progn
; Diese Fallunterscheidung hängt von sys::%sleep in time.d ab.
#+UNIX
(if (> time 16700000) ; mehr als 193 Tage?
(loop (sys::%sleep 86400 0)) ; ja -> Endlosschleife
(multiple-value-bind (seconds rest) (floor time)
(sys::%sleep seconds (round (* rest 1000000)))))
#+WIN32
(if (> time 4250000) ; mehr als 49 Tage?
(loop (sys::%sleep 86400 0)) ; ja -> Endlosschleife
(multiple-value-bind (seconds rest) (floor time)
(sys::%sleep seconds (round (* rest 1000))))))
(error-of-type 'type-error
:datum time :expected-type '(REAL 0 *)
(TEXT "~S: argument ~S should be a nonnegative number")
'sleep time)))
;; functions for Zeit-Umrechnung und Zeitzonen (CLTL Chapter 25.4.1)
;; Version 2, beinhaltet mehr Mathematik und basiert auf März-Jahren
; Ein März-Jahr sei die Periode vom 1.3. bis 28/29.2.
; Vorteil: Umrechnung Monat/Tag <--> Jahrtag wird einfacher.
; Skizze:
; 1.1.1900 1.1.1901 1.1.1902
;
; |-------------------|-------------------|-------------------|
; | Jahr 1900 | Jahr 1901 | Jahr 1902 |
; |--|----------------|--|----------------|--|----------------|--|
; | März-Jahr 1900 | März-Jahr 1901 | März-Jahr 1902 |
; |-------------------|-------------------|-------------------|
;
; 1.3.1900 1.3.1901 1.3.1902
; (UTag Jahr) = Nummer des Tages 1.3.Jahr (gegenüber 1.1.1900)
; UTag(J) = 365*J + floor(J/4) - floor(J/100) + floor(J/400) - 693901
; damit UTag(J) - UTag(J-1) = 365 + [1 falls J Schaltjahr]
; und UTag(1899) = -306
; gelten.
(defun UTag (Jahr)
(+ (* 365 Jahr) (floor Jahr 4) (- (floor Jahr 100)) (floor Jahr 400) -693901))
; Näherungwert:
; 365+1/4-1/100+1/400 = 365.2425 = 146097/400 .
; Durch Betrachtung einer Wertetabelle der 400-periodischen Funktion
; (J -> UTag(J)-146097/400*J) sieht man:
; 146097/400*J - 693902.4775 <= UTag(J) <= 146097/400*J - 693900.28
; Bestimmt zu einem Tag (0 = 1.1.1900) das März-Jahr und den Tag im März-Jahr.
; (Jahr&Tag UTTag) ==> Jahr, Jahrtag
; mit (= UTTag (+ (UTag Jahr) Jahrtag))
(defun Jahr&Tag (UTTag)
; Gesucht ist das größte Jahr mit UTag(Jahr) <= UTTag.
; Für dieses Jahr J gilt
; 146097/400*J - 693902.4775 <= UTag(J) <= UTTag < UTag(J+1) <= 146097/400*J - 693535.0375,
; also 146097*J - 277560991 <= 400*UTTag < 146097*J - 277414015,
; also 146097*(J-1900) + 23309 <= 400*UTTag < 146097*(J-1900) + 170285,
; also J + 0.159544... <= 1900 + UTTag/(146097/400) < J + 1.165561... .
(let* ((Jahr (+ 1900 (floor (- UTTag 58) 146097/400)))
(Jahresanfang (UTag Jahr)))
; Wegen 146097*(J-1900) + 109 <= 400*(UTTag-58) < 146097*(J-1900) + 147084,
; also J <= 1900 + (UTTag-58)/(146097/400) < J+1.006755...,
; ist die Schätzung Jahr := floor(1900 + (UTTag-58)/(146097/400))
; meist richtig und jedenfalls nicht zu klein und um höchstens 1 zu groß.
(when (< UTTag Jahresanfang) ; zu groß?
(decf Jahr)
(setq Jahresanfang (UTag Jahr)))
(values Jahr (- UTTag Jahresanfang))))
; Bei vielen Betriebssystemen (nicht bei UNIX, WIN32) muss die Zeitzone beim
; Installieren in timezone.lisp eingetragen werden. Hier stehen nur
; Defaultwerte.
#-(or UNIX WIN32)
; lokale Zeitzone
(defvar *default-time-zone* -1) ; Default: 1 h östlich GMT = MEZ
; NB: Zeitzone muss nicht ganzzahlig sein, sollte aber Vielfaches
; einer Sekunde sein.
#-(or UNIX WIN32)
; Funktion, die feststellt, ob bei gegebenem März-Jahr und Tag und Stunde
; Sommerzeit gilt.
(defvar *default-dst-check* ; Default: Sommerzeit nicht explizit bekannt
#'(lambda (Jahr Jahrtag Stunde) (declare (ignore Jahr Jahrtag Stunde)) nil))
; andere Abbildung Jahrtag -> Monat für decode-universal-time:
; Seien Monat und Jahrtag auf den 1. März bezogen
; (d.h. Jahrtag = 0 am 1. März, = 364 am 28. Februar, usw.,
; und März=0,...,Dezember=9,Januar=10,Februar=11).
; Dann ist
; Monat = floor(a*Jahrtag+b)
; sofern a und b so gewählt sind, dass die Ungleichungen
; 122*a+b >= 4, 275*a+b >= 9, 30*a+b < 1, 336*a+b < 11
; gelten. Dies ist ein Viereck im Bereich
; 0.032653... = 8/245 <= a <= 7/214 = 0.032710...,
; 0.009345... = 1/107 <= b <= 1/49 = 0.020408...,
; in dem z.B. der Punkt (a=5/153,b=2/153) liegt:
; Monat = floor((5*Jahrtag+2)/153).
; andere Abbildung Monat -> Jahrtag
; für encode-universal-time und decode-universal-time:
; Seien Monat und Jahrtag auf den 1. März bezogen
; (d.h. Jahrtag = 0 am 1. März, = 364 am 28. Februar, usw.,
; und März=0,...,Dezember=9,Januar=10,Februar=11).
; Die Abbildung
; Monat 0 1 2 3 4 5 6 7 8 9 10 11
; Jahrtag 0 31 61 92 122 153 184 214 245 275 306 337
; kann man schreiben
; Jahrtag = floor(a*Monat+b)
; sofern a und b so gewählt sind, dass die Ungleichungen
; a+b >= 31, 11*a+b >= 337, 4*a+b < 123, 9*a+b < 276
; gelten. Dies ist ein Viereck im Bereich
; 30.5714... = 214/7 <= a <= 245/8 = 30.625,
; 0.375 = 3/8 <= b <= 5/7 = 0.7142...,
; in dem z.B. der Punkt (a=153/5,b=2/5) liegt:
; Jahrtag = floor((153*Monat+2)/5).
; Dies ist allerdings langsamer als ein Tabellenzugriff.
(macrolet ((Monat->Jahrtag (Monat) ; 0 <= Monat < 12, 0=März,...,11=Februar
`(svref '#(0 31 61 92 122 153 184 214 245 275 306 337) ,Monat)))
; (encode-universal-time second minute hour date month year [time-zone]),
; CLTL p. 446
(defun encode-universal-time
(Sekunde Minute Stunde Tag Monat Jahr &optional (Zeitzone nil)
&aux Monat3 Jahr3 Jahrtag UTTag UT)
(unless (and (and (integerp Jahr)
(progn
(when (<= 0 Jahr 99)
(multiple-value-bind (i1 i2 i3 i4 i5 Jahrjetzt)
(get-decoded-time)
(declare (ignore i1 i2 i3 i4 i5))
(setq Jahr
(+ Jahr (* 100 (ceiling (- Jahrjetzt Jahr 50)
100))))))
;; 1900-01-01 GMT == 1899-12-31 EST
(<= 1899 Jahr)))
(and (integerp Monat) (<= 1 Monat 12))
(progn
(if (< Monat 3)
(setq Jahr3 (1- Jahr) Monat3 (+ Monat 9)) ; Monat3 10..11
(setq Jahr3 Jahr Monat3 (- Monat 3))) ; Monat3 0..9
(and (and (integerp Tag) (<= 1 Tag))
(progn
(setq Jahrtag (+ (1- Tag) (Monat->Jahrtag Monat3)))
(setq UTTag (+ Jahrtag (UTag Jahr3)))
(and (if (not (eql Monat3 11))
(< Jahrtag (Monat->Jahrtag (1+ Monat3)))
(< UTTag (UTag (1+ Jahr3))))
(and (integerp Stunde) (<= 0 Stunde 23))
(and (integerp Minute) (<= 0 Minute 59))
(and (integerp Sekunde) (<= 0 Sekunde 59))
(and (progn
(unless Zeitzone
(setq Zeitzone
#-(or UNIX WIN32)
(- *default-time-zone*
(if (funcall *default-dst-check*
Jahr3 Jahrtag Stunde)
1 0))
#+(or UNIX WIN32)
(default-time-zone
(+ (* 24 UTTag) Stunde) nil)))
(when (floatp Zeitzone)
(setq Zeitzone (rational Zeitzone)))
(or (integerp Zeitzone)
(and (rationalp Zeitzone)
(integerp (* 3600 Zeitzone)))))
(<= -24 Zeitzone 24))
(<= 0 (setq UT (+ Sekunde
(* 60 (+ Minute
(* 60 (+ Stunde Zeitzone
(* 24 UTTag)))))))))))))
(error-of-type 'error
(TEXT "incorrect date: ~S-~S-~S ~S:~S:~S, time zone ~S")
Jahr Monat Tag Stunde Minute Sekunde Zeitzone))
UT)
; (decode-universal-time universal-time [time-zone]), CLTL p. 445
(defun decode-universal-time (UT &optional (time-zone nil)
&aux Sommerzeit Zeitzone)
(if time-zone
(setq Sommerzeit nil Zeitzone time-zone)
#-(or UNIX WIN32)
(setq time-zone *default-time-zone*
Sommerzeit (let ((UT (- UT (round (* 3600 time-zone)))))
(multiple-value-bind (UTTag Stunde) (floor UT (* 3600 24))
(multiple-value-bind (Jahr Jahrtag) (Jahr&Tag UTTag)
(funcall *default-dst-check* Jahr Jahrtag Stunde))))
Zeitzone (if Sommerzeit (1- time-zone) time-zone))
#+(or UNIX WIN32)
(progn
(multiple-value-setq (Zeitzone Sommerzeit)
(default-time-zone (floor UT 3600) t))
(setq time-zone (if Sommerzeit (1+ Zeitzone) Zeitzone))))
; time-zone = Zeitzone ohne Sommerzeitberücksichtigung,
; Zeitzone = Zeitzone mit Sommerzeitberücksichtigung.
(let ((UTSekunden (- UT (round (* 3600 Zeitzone)))))
(multiple-value-bind (UTMinuten Sekunde) (floor UTSekunden 60)
(multiple-value-bind (UTStunden Minute) (floor UTMinuten 60)
(multiple-value-bind (UTTage Stunde) (floor UTStunden 24)
(multiple-value-bind (Jahr Jahrtag) (Jahr&Tag UTTage)
(let* ((Monat (floor (+ (* 5 Jahrtag) 2) 153))
(Tag (1+ (- Jahrtag (Monat->Jahrtag Monat)))))
(if (< Monat 10) ; Monat März..Dezember?
(setq Monat (+ Monat 3)) ; Monat 3..12
(setq Monat (- Monat 9) Jahr (+ Jahr 1))) ; Monat 1..2
(values Sekunde Minute Stunde Tag Monat Jahr (mod UTTage 7)
Sommerzeit time-zone))))))))
) ; end of macrolet
; (get-decoded-time), CLTL p. 445
(defun get-decoded-time ()
(decode-universal-time (get-universal-time)))
;;; Verschiedenes
; (concat-pnames obj1 obj2) liefert zu zwei Objekten (Symbolen oder Strings)
; ein Symbol, dessen Printname sich aus den beiden Objekten zusammensetzt.
(defun concat-pnames (obj1 obj2)
(let ((str (string-concat (string obj1) (string obj2))))
(if (and (plusp (length str)) (eql (char str 0) #\:))
(intern (subseq str 1) *keyword-package*)
(intern str))))
; Gibt object in einen String aus, der nach Möglichkeit höchstens max Spalten
; lang sein soll.
(defun write-to-short-string (object max)
; Methode: probiere
; level = 0: length = 0,1,2
; level = 1: length = 1,2,3,4
; level = 2: length = 2,...,6
; usw. bis maximal level = 16.
; Dabei level möglichst groß, und bei festem level length möglichst groß.
(if (or (numberp object) (symbolp object)) ; von length und level unbeeinflusst?
(write-to-string object)
(macrolet ((minlength (level) `,level)
(maxlength (level) `(* 2 (+ ,level 1))))
; Um level möglist groß zu bekommen, dabei length = minlength wählen.
(let* ((level ; Binärsuche nach dem richtigen level
(let ((level1 0) (level2 16))
(loop
(when (= (- level2 level1) 1) (return))
(let ((levelm (floor (+ level1 level2) 2)))
(if (<= (string-width (write-to-string object :level levelm :length (minlength levelm))) max)
(setq level1 levelm) ; levelm passt, probiere größere
(setq level2 levelm) ; levelm passt nicht, probiere kleinere
) ) )
level1
) )
(length ; Binärsuche nach dem richtigen length
(let ((length1 (minlength level)) (length2 (maxlength level)))
(loop
(when (= (- length2 length1) 1) (return))
(let ((lengthm (floor (+ length1 length2) 2)))
(if (<= (string-width (write-to-string object :level level :length lengthm)) max)
(setq length1 lengthm) ; lengthm passt, probiere größere
(setq length2 lengthm) ; lengthm passt nicht, probiere kleinere
) ) )
length1
)) )
(write-to-string object :level level :length length)
) ) ) )
(defmacro memoized (form)
"(MEMOIZED form) memoizes the result of FORM from its first evaluation."
`(LET ((MEMORY
(IF (EVAL-WHEN (EVAL) T)
',(cons nil nil)
;; Careful: Different expansions of MEMOIZED forms must yield
;; LOAD-TIME-VALUE forms that are not EQ, otherwise compile-file
;; will coalesce these LOAD-TIME-VALUE forms. Therefore here we
;; explicitly cons up the list and don't use backquote.
,(list 'LOAD-TIME-VALUE '(CONS NIL NIL)))))
(UNLESS (CAR MEMORY)
(SETF (CDR MEMORY) ,form)
(SETF (CAR MEMORY) T))
(CDR MEMORY)))
;; *ERROR-HANDLER* should be NIL or a function which accepts the following
;; arguments:
;; - NIL (in case of ERROR) or a continue-format-string (in case of CERROR),
;; - error-format-string,
;; - more argument list for these two format strings,
;; and which may return only if the first argument is /= NIL.
(defvar *error-handler* nil)
| 39,017 | Common Lisp | .lisp | 812 | 38.657635 | 114 | 0.582009 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | c947235c4350e1ae5c02401b7a6858b87f30d24af64491d6bc152c09024efa01 | 11,360 | [
-1
] |
11,361 | clos-methcomb4.lisp | ufasoft_lisp/clisp/clos-methcomb4.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Method Combination
;;;; Part n-1: Generic functions specified in the MOP.
;;;; Bruno Haible 2004-06-10
(in-package "CLOS")
;; Make creation of <method-combination> instances customizable.
(setf (fdefinition 'make-instance-<method-combination>) #'make-instance)
;; MOP p. 54
(defgeneric find-method-combination (generic-function name options)
(:method ((gf generic-function) (name symbol) options)
(find-method-combination-<generic-function>-<symbol> gf name options)))
(initialize-extended-method-check #'find-method-combination)
| 586 | Common Lisp | .lisp | 12 | 47 | 75 | 0.761404 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | e813b653493fa0560191884c4983e7aa9340d2adc286267bb356003902e06662 | 11,361 | [
-1
] |
11,362 | clos-print.lisp | ufasoft_lisp/clisp/clos-print.lisp | ;;;; Common Lisp Object System for CLISP: Classes
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2007
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
(defgeneric print-object (object stream)
(:method ((object t) stream)
(unless (eq (class-of (class-of object)) <built-in-class>)
;; this method exists for things like (PRINT-OBJECT 2 *STANDARD-OUTPUT*)
;; and thus this error should never be reached
(error-of-type 'ext::source-program-error
:form (list 'print-object object stream) :detail object
(TEXT "No ~S method for ~S (~S (~S))")
'print-object object (class-of object) (class-of (class-of object))))
;; WRITE does not call PRINT-OBJECT for built-in objects
;; thus there will be no infinite recursion
(write object :stream stream))
(:method ((object standard-object) stream)
(if *print-readably*
(let ((form (make-init-form object)))
(if form
(write (sys::make-load-time-eval form) :stream stream)
(print-unreadable-object (object stream :type t :identity t))))
(print-unreadable-object (object stream :type t :identity t)))
object)
(:method ((object structure-object) stream)
(system::print-structure object stream)
object)
(:method ((object potential-class) stream)
(print-object-<potential-class> object stream)
object)
(:method ((object forward-reference-to-class) stream)
(print-object-<forward-reference-to-class> object stream)
object)
(:method ((object slot-definition) stream)
(print-object-<slot-definition> object stream)
object)
(:method ((object eql-specializer) stream)
(print-object-<eql-specializer> object stream)
object)
(:method ((object method-combination) stream)
(print-object-<method-combination> object stream)
object)
(:method ((object standard-method) stream)
(print-object-<standard-method> object stream)
object)
(:method ((object funcallable-standard-object) stream)
(print-object-<funcallable-standard-object> object stream)
object))
#| ;; Commented out because the example in the CLHS description of
;; PRINT-UNREADABLE-OBJECT leaves doubts about whether the
;; "print-object object stream => object"
;; specification was meant as it is.
;; CLISP's printer ignores the value of PRINT-OBJECT anyway.
;; Check that all user-defined print-object methods return the object.
(define-condition print-object-method-warning (warning) ())
(define-condition simple-print-object-method-warning (simple-condition print-object-method-warning) ())
(defun print-object-method-warning (method object result)
(clos-warn 'simple-print-object-method-warning
(TEXT "~S: invalid method ~S. ANSI CL requires that every ~S method returns the object as value. Expected ~S, but it returned ~S.")
'print-object method 'print-object object result))
(defmethod compute-effective-method ((gf (eql #'print-object))
method-combination methods)
(declare (ignore method-combination))
(multiple-value-bind (form options) (call-next-method)
(let ((object-var (gensym))
(result-var (gensym)))
(values `(LET ((,result-var ,form))
(UNLESS (EQL ,result-var ,object-var)
(PRINT-OBJECT-METHOD-WARNING ',(first methods) ,object-var ,result-var))
,object-var)
(cons `(:ARGUMENTS ,object-var) options)))))
|#
;; Another DEFSTRUCT hook.
(defun defstruct-remove-print-object-method (name) ; ABI
(let ((method (find-method #'print-object nil
(list (find-class name) <t>) nil)))
(when method (remove-method #'print-object method))))
| 3,760 | Common Lisp | .lisp | 78 | 42.320513 | 135 | 0.684168 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 39643e5479f228960c4adbee1abd2d05f0c4783efe900858c45d029f08e826b9 | 11,362 | [
-1
] |
11,363 | clos-class6.lisp | ufasoft_lisp/clisp/clos-class6.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Class metaobjects
;;;; Part n-1: Generic functions specified in the MOP.
;;;; Bruno Haible 2004-05-25
;;;; Sam Steingold 2005-2008
(in-package "CLOS")
;;; ===========================================================================
;; Make creation of <defined-class> instances customizable.
;; Installing the accessor methods can only be done after a class has been
;; initialized, but must be done in a _primary_ initialize-instance method,
;; so that it doesn't interfere with :after/:around methods that a user could
;; install. See MOP p. 60.
(defmethod initialize-instance ((class defined-class) &rest args)
(declare (ignore args))
(call-next-method) ; == (apply #'shared-initialize class 't args)
(install-class-direct-accessors class)
class)
(defmethod initialize-instance ((class structure-class) &rest args
&key ((defclass-form defclass-form))
&allow-other-keys)
(if (eq defclass-form 'defstruct) ; called from DEFINE-STRUCTURE-CLASS
;; we do not (CALL-NEXT-METHOD) because the
;; INITIALIZE-INSTANCE@DEFINED-CLASS method calls
;; INSTALL-CLASS-DIRECT-ACCESSORS which installs slot accessors
;; immediately overwritten by the accessors defined by DEFSTRUCT
(apply #'shared-initialize class 't args)
(call-next-method)) ; initialize-instance@defined-class
class)
(setf (fdefinition 'initialize-instance-<built-in-class>) #'initialize-instance)
(setf (fdefinition 'make-instance-<built-in-class>) #'make-instance)
(setf (fdefinition 'initialize-instance-<structure-class>) #'initialize-instance)
(setf (fdefinition 'make-instance-<structure-class>) #'make-instance)
(setf (fdefinition 'initialize-instance-<standard-class>) #'initialize-instance)
(setf (fdefinition 'make-instance-<standard-class>) #'make-instance)
(setf (fdefinition 'initialize-instance-<funcallable-standard-class>) #'initialize-instance)
(setf (fdefinition 'make-instance-<funcallable-standard-class>) #'make-instance)
;;; ===========================================================================
;;; Optimized class-xxx accessors.
;;; These are possible thanks to the :fixed-slot-locations class option.
(defun check-class-initialized (class level)
(unless (>= (class-initialized class) level)
(error (TEXT "The class ~S has not yet been initialized.")
class)))
(defun check-class-finalized (class level)
(check-class-initialized class 2)
(unless (>= (class-initialized class) level)
(error (TEXT "The class ~S has not yet been finalized.")
class)))
;; Not in MOP.
(defun class-classname (class)
(accessor-typecheck class 'potential-class 'class-classname)
(sys::%record-ref class *<potential-class>-classname-location*))
(defun (setf class-classname) (new-value class)
(accessor-typecheck class 'potential-class '(setf class-classname))
(setf (sys::%record-ref class *<potential-class>-classname-location*) new-value))
;; MOP p. 76
(defgeneric class-name (class)
(:method ((class defined-class))
(check-class-initialized class 1)
(class-classname class))
(:method ((class forward-reference-to-class))
(slot-value class '$classname)))
; No extended method check because this GF is specified in ANSI CL.
;(initialize-extended-method-check #'class-name)
;; MOP p. 92
(defgeneric (setf class-name) (new-value class)
(:method (new-value (class potential-class))
(unless (symbolp new-value)
(error-of-type 'type-error
:datum new-value :expected-type 'symbol
(TEXT "~S: The name of a class must be a symbol, not ~S")
'(setf class-name) new-value))
(when (built-in-class-p class)
(error-of-type 'error
(TEXT "~S: The name of the built-in class ~S cannot be modified")
'(setf class-name) class))
(reinitialize-instance class :name new-value)
new-value))
(initialize-extended-method-check #'(setf class-name))
;; Not in MOP.
(defun class-direct-subclasses-table (class)
(accessor-typecheck class 'super-class 'class-direct-subclasses-table)
(if (potential-class-p class)
(sys::%record-ref class *<potential-class>-direct-subclasses-location*)
(slot-value class '$direct-subclasses)))
(defun (setf class-direct-subclasses-table) (new-value class)
(accessor-typecheck class 'super-class '(setf class-direct-subclasses-table))
(if (potential-class-p class)
(setf (sys::%record-ref class *<potential-class>-direct-subclasses-location*) new-value)
(setf (slot-value class '$direct-subclasses) new-value)))
;; MOP p. 76
(defgeneric class-direct-subclasses (class)
(:method ((class defined-class))
(check-class-initialized class 2)
(list-direct-subclasses class))
(:method ((class forward-reference-to-class))
(list-direct-subclasses class)))
(defun class-not-yet-defined (method class)
(clos-warning (TEXT "~S being called on ~S, but class ~S is not yet defined.")
method class (class-name class)))
;; MOP p. 76
(defgeneric class-direct-superclasses (class)
(:method ((class defined-class))
(check-class-initialized class 2)
(sys::%record-ref class *<defined-class>-direct-superclasses-location*))
(:method ((class forward-reference-to-class))
;; Broken MOP. Any use of this method is a bug.
(class-not-yet-defined 'class-direct-superclasses class)
'()))
(initialize-extended-method-check #'class-direct-superclasses)
;; Not in MOP.
(defun (setf class-direct-superclasses) (new-value class)
(accessor-typecheck class 'defined-class '(setf class-direct-superclasses))
(setf (sys::%record-ref class *<defined-class>-direct-superclasses-location*) new-value))
;; Not in MOP.
(defun class-all-superclasses (class)
(accessor-typecheck class 'defined-class 'class-all-superclasses)
(sys::%record-ref class *<defined-class>-all-superclasses-location*))
(defun (setf class-all-superclasses) (new-value class)
(accessor-typecheck class 'defined-class '(setf class-all-superclasses))
(setf (sys::%record-ref class *<defined-class>-all-superclasses-location*) new-value))
;; MOP p. 76
(defgeneric class-precedence-list (class)
(:method ((class defined-class))
(check-class-finalized class 3)
(sys::%record-ref class *<defined-class>-precedence-list-location*)))
(initialize-extended-method-check #'class-precedence-list)
;; Not in MOP.
(defun (setf class-precedence-list) (new-value class)
(accessor-typecheck class 'defined-class '(setf class-precedence-list))
(setf (sys::%record-ref class *<defined-class>-precedence-list-location*) new-value))
;; MOP p. 75
(defgeneric class-direct-slots (class)
(:method ((class defined-class))
(check-class-initialized class 2)
(sys::%record-ref class *<defined-class>-direct-slots-location*))
(:method ((class forward-reference-to-class))
;; Broken MOP. Any use of this method is a bug.
(class-not-yet-defined 'class-direct-slots class)
'()))
(initialize-extended-method-check #'class-direct-slots)
;; Not in MOP.
(defun (setf class-direct-slots) (new-value class)
(accessor-typecheck class 'defined-class '(setf class-direct-slots))
(setf (sys::%record-ref class *<defined-class>-direct-slots-location*) new-value))
;; MOP p. 77
(defgeneric class-slots (class)
(:method ((class defined-class))
(check-class-finalized class 5)
(sys::%record-ref class *<defined-class>-slots-location*)))
(initialize-extended-method-check #'class-slots)
;; Not in MOP.
(defun (setf class-slots) (new-value class)
(accessor-typecheck class 'defined-class '(setf class-slots))
(setf (sys::%record-ref class *<defined-class>-slots-location*) new-value))
;; Not in MOP.
(defun class-slot-location-table (class)
(accessor-typecheck class 'defined-class 'class-slot-location-table)
(sys::%record-ref class *<defined-class>-slot-location-table-location*))
(defun (setf class-slot-location-table) (new-value class)
(accessor-typecheck class 'defined-class '(setf class-slot-location-table))
(setf (sys::%record-ref class *<defined-class>-slot-location-table-location*) new-value))
;; MOP p. 75
(defgeneric class-direct-default-initargs (class)
(:method ((class defined-class))
(check-class-initialized class 2)
(sys::%record-ref class *<defined-class>-direct-default-initargs-location*))
(:method ((class forward-reference-to-class))
;; Broken MOP. Any use of this method is a bug.
(class-not-yet-defined 'class-direct-default-initargs class)
'()))
(initialize-extended-method-check #'class-direct-default-initargs)
;; Not in MOP.
(defun (setf class-direct-default-initargs) (new-value class)
(accessor-typecheck class 'defined-class '(setf class-direct-default-initargs))
(setf (sys::%record-ref class *<defined-class>-direct-default-initargs-location*) new-value))
;; MOP p. 75
(defgeneric class-default-initargs (class)
(:method ((class defined-class))
(check-class-finalized class 6)
(sys::%record-ref class *<defined-class>-default-initargs-location*)))
(initialize-extended-method-check #'class-default-initargs)
;; Not in MOP.
(defun (setf class-default-initargs) (new-value class)
(accessor-typecheck class 'defined-class '(setf class-default-initargs))
(setf (sys::%record-ref class *<defined-class>-default-initargs-location*) new-value))
;; Not in MOP.
(defun class-documentation (class)
(accessor-typecheck class 'defined-class 'class-documentation)
(sys::%record-ref class *<defined-class>-documentation-location*))
(defun (setf class-documentation) (new-value class)
(accessor-typecheck class 'defined-class '(setf class-documentation))
(setf (sys::%record-ref class *<defined-class>-documentation-location*) new-value))
;; Not in MOP.
(defun class-listeners (class)
(accessor-typecheck class 'defined-class 'class-listeners)
(sys::%record-ref class *<defined-class>-listeners-location*))
(defun (setf class-listeners) (new-value class)
(accessor-typecheck class 'defined-class '(setf class-listeners))
(setf (sys::%record-ref class *<defined-class>-listeners-location*) new-value))
;; Not in MOP.
(defun class-initialized (class)
(accessor-typecheck class 'defined-class 'class-initialized)
(sys::%record-ref class *<defined-class>-initialized-location*))
(defun (setf class-initialized) (new-value class)
(accessor-typecheck class 'defined-class '(setf class-initialized))
(setf (sys::%record-ref class *<defined-class>-initialized-location*) new-value))
;; Not in MOP.
(defun class-subclass-of-stablehash-p (class)
(accessor-typecheck class 'slotted-class 'class-subclass-of-stablehash-p)
(sys::%record-ref class *<slotted-class>-subclass-of-stablehash-p-location*))
(defun (setf class-subclass-of-stablehash-p) (new-value class)
(accessor-typecheck class 'slotted-class '(setf class-subclass-of-stablehash-p))
(setf (sys::%record-ref class *<slotted-class>-subclass-of-stablehash-p-location*) new-value))
;; Not in MOP.
(defun class-generic-accessors (class)
(accessor-typecheck class 'slotted-class 'class-generic-accessors)
(sys::%record-ref class *<slotted-class>-generic-accessors-location*))
(defun (setf class-generic-accessors) (new-value class)
(accessor-typecheck class 'slotted-class '(setf class-generic-accessors))
(setf (sys::%record-ref class *<slotted-class>-generic-accessors-location*) new-value))
;; Not in MOP.
(defun class-direct-accessors (class)
(accessor-typecheck class 'slotted-class 'class-direct-accessors)
(sys::%record-ref class *<slotted-class>-direct-accessors-location*))
(defun (setf class-direct-accessors) (new-value class)
(accessor-typecheck class 'slotted-class '(setf class-direct-accessors))
(setf (sys::%record-ref class *<slotted-class>-direct-accessors-location*) new-value))
;; Not in MOP.
(defun class-valid-initargs-from-slots (class)
(accessor-typecheck class 'slotted-class 'class-valid-initargs-from-slots)
(sys::%record-ref class *<slotted-class>-valid-initargs-from-slots-location*))
(defun (setf class-valid-initargs-from-slots) (new-value class)
(accessor-typecheck class 'slotted-class '(setf class-valid-initargs-from-slots))
;; When the valid-initargs-from-slots change, the result of
;; (valid-initarg-keywords class ...) changes, therefore we need to invalidate
;; all the caches that use valid-initarg-keywords:
(when (or (eq (sys::%unbound) (sys::%record-ref class *<slotted-class>-valid-initargs-from-slots-location*))
(set-exclusive-or (sys::%record-ref class *<slotted-class>-valid-initargs-from-slots-location*) new-value))
(remhash class *make-instance-table*)
(remhash class *reinitialize-instance-table*)
(remhash class *update-instance-for-redefined-class-table*)
(remhash class *update-instance-for-different-class-table*))
(setf (sys::%record-ref class *<slotted-class>-valid-initargs-from-slots-location*) new-value))
;; Not in MOP.
(defun class-instance-size (class)
(accessor-typecheck class 'slotted-class 'class-instance-size)
(sys::%record-ref class *<slotted-class>-instance-size-location*))
(defun (setf class-instance-size) (new-value class)
(accessor-typecheck class 'slotted-class '(setf class-instance-size))
(setf (sys::%record-ref class *<slotted-class>-instance-size-location*) new-value))
;; Not in MOP.
(defun class-names (class)
(accessor-typecheck class 'structure-class 'class-names)
(sys::%record-ref class *<structure-class>-names-location*))
(defun (setf class-names) (new-value class)
(accessor-typecheck class 'structure-class '(setf class-names))
(setf (sys::%record-ref class *<structure-class>-names-location*) new-value))
;; Not in MOP.
(defun class-kconstructor (class)
(accessor-typecheck class 'structure-class 'class-kconstructor)
(sys::%record-ref class *<structure-class>-kconstructor-location*))
(defun (setf class-kconstructor) (new-value class)
(accessor-typecheck class 'structure-class '(setf class-kconstructor))
(setf (sys::%record-ref class *<structure-class>-kconstructor-location*) new-value))
;; Not in MOP.
(defun class-boa-constructors (class)
(accessor-typecheck class 'structure-class 'class-boa-constructors)
(sys::%record-ref class *<structure-class>-boa-constructors-location*))
(defun (setf class-boa-constructors) (new-value class)
(accessor-typecheck class 'structure-class '(setf class-boa-constructors))
(setf (sys::%record-ref class *<structure-class>-boa-constructors-location*) new-value))
;; Not in MOP.
(defun class-copier (class)
(accessor-typecheck class 'structure-class 'class-copier)
(sys::%record-ref class *<structure-class>-copier-location*))
(defun (setf class-copier) (new-value class)
(accessor-typecheck class 'structure-class '(setf class-copier))
(setf (sys::%record-ref class *<structure-class>-copier-location*) new-value))
;; Not in MOP.
(defun class-predicate (class)
(accessor-typecheck class 'structure-class 'class-predicate)
(sys::%record-ref class *<structure-class>-predicate-location*))
(defun (setf class-predicate) (new-value class)
(accessor-typecheck class 'structure-class '(setf class-predicate))
(setf (sys::%record-ref class *<structure-class>-predicate-location*) new-value))
;; Not in MOP.
(defun class-current-version (class)
(accessor-typecheck class 'semi-standard-class 'class-current-version)
(sys::%record-ref class *<semi-standard-class>-current-version-location*))
(defun (setf class-current-version) (new-value class)
(accessor-typecheck class 'semi-standard-class '(setf class-current-version))
(setf (sys::%record-ref class *<semi-standard-class>-current-version-location*) new-value))
;; Not in MOP.
(defun class-funcallablep (class)
(accessor-typecheck class 'semi-standard-class 'class-funcallablep)
(sys::%record-ref class *<semi-standard-class>-funcallablep-location*))
(defun (setf class-funcallablep) (new-value class)
(accessor-typecheck class 'semi-standard-class '(setf class-funcallablep))
(setf (sys::%record-ref class *<semi-standard-class>-funcallablep-location*) new-value))
;; Not in MOP.
(defun class-fixed-slot-locations (class)
(accessor-typecheck class 'semi-standard-class 'class-fixed-slot-locations)
(sys::%record-ref class *<semi-standard-class>-fixed-slot-locations-location*))
(defun (setf class-fixed-slot-locations) (new-value class)
(accessor-typecheck class 'semi-standard-class '(setf class-fixed-slot-locations))
(setf (sys::%record-ref class *<semi-standard-class>-fixed-slot-locations-location*) new-value))
;; Not in MOP.
(defun class-instantiated (class)
(accessor-typecheck class 'semi-standard-class 'class-instantiated)
(sys::%record-ref class *<semi-standard-class>-instantiated-location*))
(defun (setf class-instantiated) (new-value class)
(accessor-typecheck class 'semi-standard-class '(setf class-instantiated))
(setf (sys::%record-ref class *<semi-standard-class>-instantiated-location*) new-value))
;; Not in MOP.
(defun class-direct-instance-specializers-table (class)
(accessor-typecheck class 'semi-standard-class 'class-direct-instance-specializers-table)
(sys::%record-ref class *<semi-standard-class>-direct-instance-specializers-location*))
(defun (setf class-direct-instance-specializers-table) (new-value class)
(accessor-typecheck class 'semi-standard-class '(setf class-direct-instance-specializers-table))
(setf (sys::%record-ref class *<semi-standard-class>-direct-instance-specializers-location*) new-value))
;; Not in MOP.
(defun class-finalized-direct-subclasses-table (class)
(accessor-typecheck class 'semi-standard-class 'class-finalized-direct-subclasses-table)
(sys::%record-ref class *<semi-standard-class>-finalized-direct-subclasses-location*))
(defun (setf class-finalized-direct-subclasses-table) (new-value class)
(accessor-typecheck class 'semi-standard-class '(setf class-finalized-direct-subclasses-table))
(setf (sys::%record-ref class *<semi-standard-class>-finalized-direct-subclasses-location*) new-value))
;; MOP p. 77
(defgeneric class-prototype (class)
(:method ((class semi-standard-class))
(check-class-finalized class 6)
(or (sys::%record-ref class *<semi-standard-class>-prototype-location*)
(setf (sys::%record-ref class *<semi-standard-class>-prototype-location*)
(let ((old-instantiated (class-instantiated class)))
(prog1
(clos::%allocate-instance class)
;; The allocation of the prototype doesn't need to flag the
;; class as being instantiated, because 1. the prototype is
;; thrown away when the class is redefined, 2. we don't want
;; a redefinition with nonexistent or non-finalized
;; superclasses to succeed despite of the prototype.
(setf (class-instantiated class) old-instantiated))))))
(:method ((class built-in-class))
(let ((prototype (sys::%record-ref class *<built-in-class>-prototype-location*)))
(if (eq (sys::%unbound) prototype)
(error (TEXT "~S: ~S is an abstract class and therefore does not have a direct instance")
'class-prototype class)
prototype)))
;; CLISP extension:
(:method ((class structure-class))
(or (sys::%record-ref class *<structure-class>-prototype-location*)
(setf (sys::%record-ref class *<structure-class>-prototype-location*)
(clos::%allocate-instance class)))))
(initialize-extended-method-check #'class-prototype)
;; Not in MOP.
(defun (setf class-prototype) (new-value class)
(accessor-typecheck class 'semi-standard-class '(setf class-prototype))
(setf (sys::%record-ref class *<semi-standard-class>-prototype-location*) new-value))
;;; ===========================================================================
;;; Class Specification Protocol
;; Not in MOP.
(defgeneric compute-direct-slot-definition-initargs (class &rest slot-spec)
(:method ((class defined-class) &rest slot-spec)
slot-spec))
;;; ===========================================================================
;;; Class Finalization Protocol
;; MOP p. 76
(defgeneric class-finalized-p (class)
(:method ((class defined-class))
(= (class-initialized class) 6))
(:method ((class forward-reference-to-class))
nil)
;; CLISP extension: Convenience method on symbols.
(:method ((name symbol))
(class-finalized-p (find-class name))))
(initialize-extended-method-check #'class-finalized-p)
;; MOP p. 54
(defgeneric finalize-inheritance (class)
(:method ((class semi-standard-class))
(finalize-inheritance-<semi-standard-class> class))
;; CLISP extension: No-op method on other classes.
(:method ((class defined-class))
class)
;; CLISP extension: Convenience method on symbols.
(:method ((name symbol))
(finalize-inheritance (find-class name))))
(initialize-extended-method-check #'finalize-inheritance)
;; MOP p. 38
(defgeneric compute-class-precedence-list (class)
(:method ((class defined-class))
(compute-class-precedence-list-<defined-class> class)))
;; Not in MOP.
(defgeneric compute-effective-slot-definition-initargs (class direct-slot-definitions)
(:method ((class defined-class) direct-slot-definitions)
(compute-effective-slot-definition-initargs-<defined-class> class direct-slot-definitions)))
;; MOP p. 42
(defgeneric compute-effective-slot-definition (class slotname direct-slot-definitions)
(:method ((class defined-class) slotname direct-slot-definitions)
(compute-effective-slot-definition-<defined-class> class slotname direct-slot-definitions)))
;; MOP p. 43
(defgeneric compute-slots (class)
(:method ((class semi-standard-class))
(compute-slots-<defined-class>-primary class))
(:method :around ((class semi-standard-class))
(compute-slots-<slotted-class>-around class
#'(lambda (c) (call-next-method c)))))
;; MOP p. 39
(defgeneric compute-default-initargs (class)
(:method ((class defined-class))
(compute-default-initargs-<defined-class> class)))
;;; ===========================================================================
;;; Class definition customization
;; MOP p. 47
(defgeneric ensure-class-using-class (class name
&key metaclass
direct-superclasses
direct-slots
direct-default-initargs
documentation
; CLISP specific extension:
fixed-slot-locations
&allow-other-keys)
(:method ((class potential-class) name &rest args)
(apply #'ensure-class-using-class-<t> class name args))
(:method ((class null) name &rest args)
(apply #'ensure-class-using-class-<t> class name args)))
;; MOP p. 102
(defgeneric validate-superclass (class superclass)
(:method ((class potential-class) (superclass potential-class))
(or (eq superclass <t>)
(eq (class-of class) (class-of superclass))
(and (eq (class-of class) <funcallable-standard-class>)
(eq (class-of superclass) <standard-class>))
;; This makes no sense: If the superclass is a
;; funcallable-standard-class, it is a subclass of FUNCTION,
;; therefore class will become a subclass of FUNCTION too, but there
;; is no way to FUNCALL or APPLY it. Where did the MOP authors have
;; their brain here?
(and (eq (class-of class) <standard-class>)
(eq (class-of superclass) <funcallable-standard-class>))
;; Needed for clos-genfun1.lisp:
(and (eq superclass <function>)
(eq (class-classname class) 'funcallable-standard-object))
;; CLISP specific extension:
(subclassp (class-of class) (class-of superclass)))))
;;; ===========================================================================
;;; Subclass relationship change notification
;; MOP p. 32
(defgeneric add-direct-subclass (class subclass)
(:method ((class super-class) (subclass potential-class))
(add-direct-subclass-internal class subclass)))
;; MOP p. 90
(defgeneric remove-direct-subclass (class subclass)
(:method ((class super-class) (subclass potential-class))
(remove-direct-subclass-internal class subclass)))
;;; ===========================================================================
;;; Accessor definition customization
;; MOP p. 86
(defgeneric reader-method-class (class direct-slot &rest initargs)
(:method ((class defined-class) direct-slot &rest initargs)
(declare (ignore direct-slot initargs))
<standard-reader-method>))
;; MOP p. 103
(defgeneric writer-method-class (class direct-slot &rest initargs)
(:method ((class defined-class) direct-slot &rest initargs)
(declare (ignore direct-slot initargs))
<standard-writer-method>))
| 24,937 | Common Lisp | .lisp | 468 | 48.987179 | 119 | 0.706155 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 5ffc58697780067078f4a2ec87f9c8edad07c3f610589b560e842e2dbf5b2498 | 11,363 | [
-1
] |
11,364 | defmacro.lisp | ufasoft_lisp/clisp/defmacro.lisp | ;;; File DEFMACRO.LISP
;;; DEFMACRO macro and a few utility functions for complex macros.
;;; 1988-01-09
;;; Adapted from DEFTYPE on 1989-10-06
;;; German comments translated by Mirian Lennox <[email protected]> 2003-01-19
(in-package "SYSTEM")
;; Import from CONTROL.D:
#| (SYSTEM::PARSE-BODY body &optional docstring-allowed)
detects occurring declarations (and if docstring-allowed=T,
also a docstring) and returns three values:
1. body-rest, the remaining forms
2. declspec-list, a list of declspecs that appeared
3. docstring, a docstring that appeared, or NIL
|#
#| (SYSTEM::KEYWORD-TEST arglist kwlist)
tests if arglist (a pair of keyword/value lists) contains only
keywords which come from the list kwlist, or else contains a
keyword/value pair :ALLOW-OTHER-KEYS with value other than NIL.
If not, an error is raised.
(defun keyword-test (arglist kwlist)
(let ((unallowed-arglistr nil)
(allow-other-keys-flag nil))
(do ((arglistr arglist (cddr arglistr)))
((null arglistr))
(if (eq (first arglistr) ':ALLOW-OTHER-KEYS)
(if (second arglistr) (setq allow-other-keys-flag t))
(do ((kw (first arglistr))
(kwlistr kwlist (cdr kwlistr)))
((or (null kwlistr) (eq kw (first kwlistr)))
(if (and (null kwlistr) (null unallowed-arglistr))
(setq unallowed-arglistr arglistr))))))
(unless allow-other-keys-flag
(if unallowed-arglistr
(cerror (TEXT "Both will be ignored.")
(TEXT "Invalid keyword-value-pair: ~S ~S")
(first unallowed-arglistr) (second unallowed-arglistr))))))
;; Definition in assembler (see CONTROL.Q)
|#
(defun macro-call-error (macro-form) ; ABI
(multiple-value-bind (length tail) (sys::list-length-dotted macro-form)
(if (null length)
(let ((*print-circle* t))
(error-of-type 'source-program-error
:form macro-form
:detail macro-form
(TEXT "The macro ~S may not be called with a circular argument list: ~S")
(car macro-form) macro-form))
(if tail
(error-of-type 'source-program-error
:form macro-form
:detail macro-form
(TEXT "The macro ~S may not be called with a dotted argument list: ~S")
(car macro-form) macro-form)
(error-of-type 'source-program-error
:form macro-form
:detail macro-form
(TEXT "The macro ~S may not be called with ~S arguments: ~S")
(car macro-form) (1- (length macro-form)) macro-form)))))
(defun macro-nonnull-element-error (macro-form macro-name element) ; ABI
(error-of-type 'source-program-error
:form macro-form
:detail element
(TEXT "~S: ~S does not match lambda list element ~:S")
macro-name element '()))
(proclaim '(special
%whole-form ;; the whole source form being macroexpanded or compiled
%proper-list-p ;; check whether the whole list is proper,
;; even if %restp is true
%restp ;; indicates whether &REST/&BODY/&KEY was given,
;; and therefore the number of arguments is unlimited.
%min-args ;; indicates the mininum number of arguments
%arg-count ;; indicates the number of individual arguments
;; (required and optional arguments combined)
%let-list ;; reversed list of bindings that have to be done with LET*
%keyword-tests ;; list of KEYWORD-TEST calls that have to be included
%default-form ;; default form for optional and keyword arguments,
;; for which no default form is supplied
;; NIL normally, or (QUOTE *) for DEFTYPE.
%null-tests ;; tests for () matches
))
#|
(ANALYZE1 lambdalist accessexp name wholevar)
analyses a macro lambda list (without &ENVIRONMENT). accessexp is the
expression which supplies the arguments to be matched with this
lambda list.
(ANALYZE-REST lambdalistr restexp name)
analyses the part of a macro lambda list that appears after the &REST/&BODY
expression. restexp is the expression that returns the arguments to be matched with this rest of the list.
(ANALYZE-KEY lambdalistr restvar name)
analyses the part of a macro lambda list which comes after &KEY.
restvar is the symbol that will contain the remaining arguments.
(ANALYZE-AUX lambdalistr name)
analyses the part of a macro lambda list that comes after &AUX.
(REMOVE-ENV-ARG lambdalist name)
removes the pair &ENVIRONMENT/Symbol from a macro lambda list; returns
two values: the shortened lambda list and the symbol to be used
as environment (or the original lambda list and NIL, if &ENVIRONMENT
is not found).
(MAKE-LENGTH-TEST symbol)
creates a testform from %restp, %min-args, %arg-count, %proper-list-p,
which indicates during evaluation whether the variable value of the symbol
can be a function call for the macro.
(MAKE-MACRO-EXPANSION macrodef whole-form)
returns, for a macro definition macrodef = (name lambdalist . body),
1. the macro-expander as the program text (FUNCTION ... (LAMBDA ..)),
2. name, a symbol
3. lambda list
4. docstring (or NIL, if not there)
(MAKE-MACRO-EXPANDER macrodef whole-form &optional env)
returns, for a macro definition macrodef = (name lambdalist . body),
the actual object #<MACRO expander> for the FENV.
|#
(defun analyze-aux (lambdalistr name)
(do ((listr lambdalistr (cdr listr)))
((atom listr)
(if listr
(cerror (TEXT "The rest of the lambda list will be ignored.")
(TEXT "The lambda list of macro ~S contains a dot after ~S.")
name '&aux)))
(cond ((symbolp (car listr)) (setq %let-list (cons `(,(car listr) nil) %let-list)))
((atom (car listr))
(error-of-type 'source-program-error
:form %whole-form
:detail (car listr)
(TEXT "in macro ~S: ~S may not be used as &AUX variable.")
name (car listr)))
(t (setq %let-list
(cons `(,(caar listr) ,(cadar listr)) %let-list))))))
(defun get-supplied-p (name item)
(when (and (consp (cdr item)) (consp (cddr item)))
(unless (symbolp (caddr item))
(error-of-type 'source-program-error
:form %whole-form
:detail (caddr item)
(TEXT "~S: invalid supplied-p variable ~S")
name (caddr item)))
(third item)))
;; this should be a macro...
(defun kwd-arg-form (restvar kw svar default &aux (dummy '#.(cons nil nil)))
;; the default value should not be evaluated unless it is actually used
(let ((arg (gensym "KWD-ARG-")))
`(let ((,arg (GETF ,restvar ',kw ',dummy)))
(if (eq ,arg ',dummy)
(progn ,@(when svar `((setq ,svar nil))) ,default)
,arg))))
(defun analyze-key (lambdalistr restvar name
&aux (other-keys-forbidden t) (kwlist nil))
(do ((listr lambdalistr (cdr listr))
(next)
(kw)
(svar)
(g))
((atom listr)
(if listr
(cerror (TEXT "The rest of the lambda list will be ignored.")
(TEXT "The lambda list of macro ~S contains a dot after ~S.")
name '&key)))
(setq next (car listr))
(cond ((eq next '&ALLOW-OTHER-KEYS) (setq other-keys-forbidden nil))
((eq next '&AUX)
(return-from nil (analyze-aux (cdr listr) name)))
((or (eq next '&ENVIRONMENT) (eq next '&WHOLE) (eq next '&REST)
(eq next '&OPTIONAL) (eq next '&BODY) (eq next '&KEY))
(cerror #1=(TEXT "It will be ignored.")
(TEXT "The lambda list of macro ~S contains a badly placed ~S.")
name next))
(t
(when %default-form
(cond ((symbolp next) (setq next (list next %default-form)))
((and (consp next) (eql (length next) 1))
(setq next (list (car next) %default-form)))))
(cond ((symbolp next) ; foo
(setq kw (symbol-to-keyword next))
(setq %let-list
(cons `(,next (GETF ,restvar ',kw NIL)) %let-list))
(setq kwlist (cons kw kwlist)))
((atom next)
(cerror #1# (TEXT "The lambda list of macro ~S contains the invalid element ~S")
name next))
((symbolp (car next)) ; (foo ...)
(setq kw (symbol-to-keyword (car next)))
(when (setq svar (get-supplied-p name next))
(setq %let-list (cons `(,svar t) %let-list)))
(setq %let-list
(cons `(,(car next)
,(kwd-arg-form restvar kw svar (cadr next)))
%let-list))
(setq kwlist (cons kw kwlist)))
((not (and (consp (car next)) (symbolp (caar next)) (consp (cdar next))))
(cerror (TEXT "~0*It will be ignored.")
(TEXT "The lambda list of macro ~S contains an invalid keyword specification ~S")
name (car next)))
((symbolp (cadar next)) ; ((:foo *foo*) ...)
(setq kw (caar next))
(when (setq svar (get-supplied-p name next))
(setq %let-list (cons `(,svar t) %let-list)))
(setq %let-list
(cons `(,(cadar next)
,(kwd-arg-form restvar kw svar (cadr next)))
%let-list))
(setq kwlist (cons kw kwlist)))
(t ; subform
(setq kw (caar next))
(setq g (gensym))
(setq svar (and (cddr next) (symbolp (third next))
(third next)))
(when svar
(setq %let-list (cons `(,svar t) %let-list)))
(setq %let-list
(cons `(,g ,(kwd-arg-form restvar kw svar (cadr next)))
%let-list))
(setq kwlist (cons kw kwlist))
(let ((%min-args 0) (%arg-count 0) (%restp nil)
(%default-form nil))
(analyze1 (cadar next) g name g)))))))
(if other-keys-forbidden
(setq %keyword-tests
(cons `(KEYWORD-TEST ,restvar ',kwlist) %keyword-tests))))
(defun analyze-rest (lambdalistr restexp name)
(if (atom lambdalistr)
(error-of-type 'source-program-error
:form %whole-form
:detail lambdalistr
(TEXT "The lambda list of macro ~S is missing a variable after &REST/&BODY.")
name))
(let ((restvar (car lambdalistr))
(listr (cdr lambdalistr)))
(setq %restp t)
(cond ((symbolp restvar)
(setq %let-list (cons `(,restvar ,restexp) %let-list)))
((atom restvar)
(error-of-type 'source-program-error
:form %whole-form
:detail restvar
(TEXT "The lambda list of macro ~S contains an illegal variable after &REST/&BODY: ~S")
name restvar))
(t
(let ((%min-args 0) (%arg-count 0) (%restp nil))
(analyze1 restvar restexp name restexp))))
(cond ((null listr))
((atom listr)
(cerror (TEXT "The rest of the lambda list will be ignored.")
(TEXT "The lambda list of macro ~S contains a misplaced dot.")
name))
((eq (car listr) '&KEY) (analyze-key (cdr listr) restvar name))
((eq (car listr) '&AUX) (analyze-aux (cdr listr) name))
(t (cerror (TEXT "They will be ignored.")
(TEXT "The lambda list of macro ~S contains superfluous elements: ~S")
name listr)))))
(defun cons-car (exp &aux h)
(if
(and
(consp exp)
(setq h
(assoc (car exp)
'((car . caar) (cdr . cadr)
(caar . caaar) (cadr . caadr) (cdar . cadar) (cddr . caddr)
(caaar . caaaar) (caadr . caaadr) (cadar . caadar)
(caddr . caaddr) (cdaar . cadaar) (cdadr . cadadr)
(cddar . caddar) (cdddr . cadddr)
(cddddr . fifth)))))
(cons (cdr h) (cdr exp))
(list 'car exp)))
(defun cons-cdr (exp &aux h)
(if
(and
(consp exp)
(setq h
(assoc (car exp)
'((car . cdar) (cdr . cddr)
(caar . cdaar) (cadr . cdadr) (cdar . cddar) (cddr . cdddr)
(caaar . cdaaar) (caadr . cdaadr) (cadar . cdadar)
(caddr . cdaddr) (cdaar . cddaar) (cdadr . cddadr)
(cddar . cdddar) (cdddr . cddddr)))))
(cons (cdr h) (cdr exp))
(list 'cdr exp)))
(defun empty-pattern (name accessexp wholevar)
(let ((g (gensym)))
(setq %let-list (cons `(,g ,(cons-car accessexp)) %let-list))
(setq %null-tests
(cons `(WHEN ,g (MACRO-NONNULL-ELEMENT-ERROR ,wholevar ',name ,g))
%null-tests))))
(defun analyze1 (lambdalist accessexp name wholevar)
(do ((listr lambdalist (cdr listr))
(within-optional nil)
(item)
(g) (g1) (test))
((atom listr)
(when listr
(unless (symbolp listr)
(error-of-type 'source-program-error
:form %whole-form
:detail listr
(TEXT "The lambda list of macro ~S contains an illegal &REST variable: ~S")
name listr))
(setq %let-list (cons `(,listr ,accessexp) %let-list))
(setq %restp t)))
(setq item (car listr))
(cond ((eq item '&WHOLE)
(if (and wholevar (cdr listr))
(if (symbolp (cadr listr))
(setq %let-list (cons `(,(cadr listr) ,wholevar) %let-list)
listr (cdr listr))
(let ((%min-args 0) (%arg-count 0) (%restp nil))
(setq listr (cdr listr)) ; pop &WHOLE
(analyze1 (car listr) wholevar name wholevar)))
(error-of-type 'source-program-error
:form %whole-form
:detail listr
(TEXT "The lambda list of macro ~S contains an invalid &WHOLE: ~S")
name listr)))
((eq item '&OPTIONAL)
(if within-optional
(cerror #2=(TEXT "It will be ignored.")
(TEXT "The lambda list of macro ~S contains a superfluous ~S.")
name item))
(setq within-optional t))
((or (eq item '&REST) (eq item '&BODY))
(return-from nil (analyze-rest (cdr listr) accessexp name)))
((eq item '&KEY)
(setq g (gensym))
(setq %restp t)
(setq %let-list (cons `(,g ,accessexp) %let-list))
(return-from nil (analyze-key (cdr listr) g name)))
((eq item '&ALLOW-OTHER-KEYS)
(cerror #2# (TEXT "The lambda list of macro ~S contains ~S before &KEY.")
name item))
((eq item '&ENVIRONMENT)
(cerror #2# (TEXT "The lambda list of macro ~S contains ~S which is illegal here.")
name item))
((eq item '&AUX)
(return-from nil (analyze-aux (cdr listr) name)))
(within-optional
(setq %arg-count (1+ %arg-count))
(if %default-form
(cond ((symbolp item) (setq item (list item %default-form)))
((and (consp item) (eql (length item) 1))
(setq item (list (car item) %default-form)))))
(cond ((null item) (empty-pattern name accessexp wholevar))
((symbolp item)
(setq %let-list (cons `(,item ,(cons-car accessexp))
%let-list)))
((atom item)
#1=
(error-of-type 'source-program-error
:form %whole-form
:detail item
(TEXT "The lambda list of macro ~S contains an invalid element ~S")
name item))
((symbolp (car item))
(setq %let-list
(cons `(,(car item) (IF ,accessexp
,(cons-car accessexp)
,(if (consp (cdr item))
(cadr item) 'NIL)))
%let-list))
(when (setq g (get-supplied-p name item))
(setq %let-list
(cons `(,g (NOT (NULL ,accessexp)))
%let-list))))
(t
(setq g (gensym))
(setq %let-list
(cons `(,g ,(if (consp (cdr item))
`(IF ,accessexp
,(cons-car accessexp)
,(cadr item))
(cons-car accessexp)))
%let-list))
(let ((%min-args 0) (%arg-count 0) (%restp nil))
(analyze1 (car item) g name g))
(if (consp (cddr item))
(setq %let-list
(cons `(,(caddr item) (NOT (NULL ,accessexp))) %let-list)))))
(setq accessexp (cons-cdr accessexp)))
(t ; required arguments
(setq %min-args (1+ %min-args))
(setq %arg-count (1+ %arg-count))
(cond ((null item) (empty-pattern name accessexp wholevar))
((symbolp item)
(setq %let-list (cons `(,item ,(cons-car accessexp)) %let-list)))
((atom item)
#1#) ; (error-of-type ... name item), s.o.
(t
(setq g (gensym) g1 (gensym)
%let-list (list* `(,g1 ,g) `(,g ,(cons-car accessexp))
%let-list))
(let ((%min-args 0) (%arg-count 0) (%restp nil))
(analyze1 item g1 name g1)
(setq test (make-length-test g 0)))
(if test
(rplaca (cdr (assoc g1 %let-list))
`(if ,test
(error-of-type 'source-program-error
:form ,wholevar
:detail ,g
(TEXT "~S: ~S does not match lambda list element ~:S")
',name ,g ',item)
,g)))))
(setq accessexp (cons-cdr accessexp))))))
(defun remove-env-arg (lambdalist name)
(do ((listr lambdalist (cdr listr)))
((atom listr) (values lambdalist nil))
(if (eq (car listr) '&ENVIRONMENT)
(if (and (consp (cdr listr)) (symbolp (cadr listr)) (cadr listr))
;; found &ENVIRONMENT
(return
(values
(do ((l1 lambdalist (cdr l1)) ; lambda list without &ENVIRONMENT/symbol
(l2 nil (cons (car l1) l2)))
((eq (car l1) '&ENVIRONMENT)
(nreconc l2 (cddr l1))))
(cadr listr)))
(error-of-type 'source-program-error
:form %whole-form
:detail lambdalist
(TEXT "In the lambda list of macro ~S, &ENVIRONMENT must be followed by a non-NIL symbol: ~S")
name lambdalist)))))
(defun make-length-test (var &optional (header 1))
(if (and (zerop %min-args) %restp)
; No length constraint, test only whether the list is a proper list.
(if %proper-list-p
`(NOT (PROPER-LIST-P ,var))
NIL)
; Perform all tests in a single function call.
`(NOT
,(if %proper-list-p
`(SYS::PROPER-LIST-LENGTH-IN-BOUNDS-P ,var ,(+ header %min-args)
,@(if %restp '() (list (+ header %arg-count))))
`(SYS::LIST-LENGTH-IN-BOUNDS-P ,var ,(+ header %min-args)
,(+ header %arg-count) ,(not (not %restp)))))))
(defun make-macro-expansion (macrodef whole-form
;; Optional arguments, for define-compiler-macro:
&optional (valid-name-p #'symbolp)
pre-process)
(when (atom macrodef)
(error-of-type 'source-program-error
:form macrodef
:detail macrodef
(TEXT "Cannot define a macro from that: ~S")
macrodef))
(unless (funcall valid-name-p (car macrodef))
(error-of-type 'source-program-error
:form macrodef
:detail (car macrodef)
(TEXT "The name of a macro must be a symbol, not ~S")
(car macrodef)))
(when (atom (cdr macrodef))
(error-of-type 'source-program-error
:form macrodef
:detail (cdr macrodef)
(TEXT "Macro ~S is missing a lambda list.")
(car macrodef)))
(let ((name (car macrodef))
(lambdalist (cadr macrodef))
(body (cddr macrodef)))
(multiple-value-bind (body-rest declarations docstring) (parse-body body t)
(if declarations
(setq declarations (list (cons 'DECLARE declarations))))
(let ((%whole-form whole-form) (%proper-list-p nil))
(multiple-value-bind (newlambdalist envvar)
(remove-env-arg lambdalist name)
(let ((%arg-count 0) (%min-args 0) (%restp nil) (%null-tests nil)
(%let-list nil) (%keyword-tests nil) (%default-form nil))
(analyze1 newlambdalist '(CDR <MACRO-FORM>) name '<MACRO-FORM>)
(let ((lengthtest (make-length-test '<MACRO-FORM>))
(mainform `(LET* ,(nreverse %let-list)
,@declarations
,@(nreverse %null-tests)
,@(nreverse %keyword-tests)
(BLOCK ,(function-block-name name)
,@body-rest))))
(if lengthtest
(setq mainform
`(IF ,lengthtest
(MACRO-CALL-ERROR <MACRO-FORM>)
,mainform)))
(let ((lambdabody
`((<MACRO-FORM> ,(or envvar '<ENV-ARG>))
(DECLARE (CONS <MACRO-FORM>))
,@(if envvar
declarations ;; possibly contains a (declare (ignore envvar))
'((DECLARE (IGNORE <ENV-ARG>))))
,@(if docstring (list docstring))
,@(if pre-process
`((setq <MACRO-FORM> (,pre-process <MACRO-FORM>))))
,mainform)))
(values
`(FUNCTION ,name (LAMBDA ,@lambdabody))
lambdabody
name
lambdalist
docstring)))))))))
;; Creates a macro expander for MACROLET.
(defun make-macro-expander (macrodef whole-form
&optional
;; The environment is tricky: ANSI CL says that
;; 1. declarations, macros and symbol-macros from
;; outside can be used in the macro expander,
;; 2. other variable and function bindings cannot.
;; 3. It is unclear about BLOCK and TAGBODY tags.
(env (vector (and (boundp '*venv*)
(cons 'MACROLET *venv*))
(and (boundp '*fenv*)
(cons 'MACROLET *fenv*))
(and (boundp '*benv*)
*benv*)
(and (boundp '*genv*)
*genv*)
(if (boundp '*denv*)
*denv*
*toplevel-denv*))))
(make-macro
(evalhook (make-macro-expansion macrodef whole-form) nil nil env)
(second whole-form)))
;; Creates a macro expander for FUNCTION-MACRO-LET.
;; Unlike in MACROLET, the macro is defined in the null lexical environment.
(defun make-funmacro-full-lambdabody (macrodef)
(multiple-value-bind (expansion expansion-lambdabody)
(make-macro-expansion macrodef
`(#:FUNCTION-MACRO-LET ,macrodef)) ; a dummy
(declare (ignore expansion))
expansion-lambdabody))
(defun make-funmacro-expander (name full-lambdabody)
(make-macro
(evalhook `(FUNCTION ,name (LAMBDA ,@full-lambdabody)) nil nil
*toplevel-environment*)
(first full-lambdabody)))
| 24,890 | Common Lisp | .lisp | 528 | 33.49053 | 107 | 0.523164 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 2cf13e88d22a40968d016edfe26a2a9d26724a63fdf9509031b2397c21a54ec4 | 11,364 | [
-1
] |
11,365 | pprint.lisp | ufasoft_lisp/clisp/pprint.lisp | ;;; 22.2 The Lisp Pretty Printer
;;; Sam Steingold 2001-07-26 - 2007
(in-package "LISP")
(export
'(*print-pprint-dispatch* pprint-dispatch copy-pprint-dispatch
set-pprint-dispatch
pprint-logical-block pprint-pop pprint-exit-if-list-exhausted
pprint-fill pprint-linear pprint-tabular)
"LISP")
(in-package "EXT")
;; used here and in inspect.lisp
(defmacro with-gensyms ((title &rest names) &body body)
"Bind symbols in NAMES to gensyms. TITLE is a string - `gensym' prefix.
Inspired by Paul Graham, <On Lisp>, p. 145."
`(let (,@(mapcar (lambda (sy)
`(,sy (gensym ,(concatenate 'string title
(symbol-name sy) "-"))))
names))
,@body))
(export '(with-gensyms) "EXT")
(in-package "SYS")
;; ---------------------- Dispatch Tables ----------------------
;; a Dispatch Table is a cons of `*PRINT-PPRINT-DISPATCH*'
;; and an alist of (type priority function)
;; if you modify the structure of Dispatch Tables,
;; you have to change DISPATCH_TABLE_VALID_P in pretty_print_call() in io.d
;; since it checks whether the Dispatch Table contains any valid entries
(defun make-pprint-dispatch () (list '*print-pprint-dispatch*))
(defun pprint-dispatch-p (obj)
(and (consp obj) (eq (car obj) '*print-pprint-dispatch*)))
(defparameter *print-pprint-dispatch* (make-pprint-dispatch))
(defun default-print-dispatch-function (stream object)
(print-object object stream))
(defun pprint-dispatch (object &optional (table *print-pprint-dispatch*))
;; object ---an object.
;; table ---a pprint dispatch table, or nil.
;; The default is the value of *print-pprint-dispatch*.
;; values:
;; function---a function designator.
;; found-p ---a generalized boolean.
(let ((tail (cdr table)) top)
(loop (setq tail (member object tail :test #'typep :key #'car))
(when (endp tail)
(return (if top
(values (third top) t)
(values #'default-print-dispatch-function nil))))
(when (or (null top) (> (cadar tail) (second top)))
(setq top (car tail)))
(pop tail))))
(defun copy-pprint-dispatch (&optional (table *print-pprint-dispatch*)) ; ABI
;; table ---a pprint dispatch table, or nil.
;; value:
;; new-table---a fresh pprint dispatch table.
;; Creates and returns a copy of the specified table,
;; or of the value of *print-pprint-dispatch* if no table is specified,
;; or of the initial value of *print-pprint-dispatch* if nil is specified.
(if table
(if (pprint-dispatch-p table)
(copy-alist table)
(error-of-type 'type-error
:datum table :expected-type '(satisfies pprint-dispatch-p)
(TEXT "~S: ~S is not a valid print dispatch table")
'copy-pprint-dispatch table))
(make-pprint-dispatch)))
(defun set-pprint-dispatch (type-specifier function &optional (priority 0)
(table *print-pprint-dispatch*))
;; type-specifier---a type specifier.
;; function ---a function, a function name, or nil.
;; priority ---a real. The default is 0.
;; table ---a pprint dispatch table.
;; The default is the value of *print-pprint-dispatch*.
(unless (realp priority)
(error-of-type 'type-error
:datum priority :expected-type 'real
(TEXT "~S: priority must be a real number, not ~S")
'set-pprint-dispatch priority))
(let ((rec (member type-specifier (cdr table) :test #'equal :key #'car)))
(if rec
(if function
;; replace record
(setf (cdar rec) (list priority function))
;; remove record
(if (cdr rec)
(setf (car rec) (cadr rec)
(cdr rec) (cddr rec))
(setf (cdr table)
(delete type-specifier (cdr table) :test #'equal
:key #'car))))
(when function
(setf (cdr table)
(acons type-specifier (list priority function)
(cdr table)))))
(values nil)))
;; ---------------------- pprint-logical-block ----------------------
(defmacro pprint-logical-block ((stream-symbol object
&key prefix per-line-prefix suffix)
&body body)
(let ((out (case stream-symbol
((t) '*terminal-io*)
((nil) '*standard-output*)
(otherwise stream-symbol)))
(idx (gensym "PPLB-IDX-"))
(pre (gensym "PPLB-PREF-"))
(suf (gensym "PPLB-SUFF-")))
`(let ((,pre ,prefix)
(,suf ,suffix)
(*prin-line-prefix* ,per-line-prefix)
(*prin-miserp*
(and *print-miser-width*
(> (line-position ,out)
(- (or *print-right-margin* *prin-linelength*)
*print-miser-width*))))
(*prin-indentation*
(if (boundp '*prin-indentation*)
(+ *prin-indentation* *print-indent-lists*)
0)))
(when (and ,pre *prin-line-prefix*)
(pprint-logical-block-both-error ,pre))
(when (and ,pre (not (stringp ,pre)))
(pprint-logical-block-prefix-not-string-error ,pre))
(when (and ,suf (not (stringp ,suf)))
(pprint-logical-block-suffix-not-string-error ,suf))
(when (and *prin-line-prefix* (not (stringp *prin-line-prefix*)))
(pprint-logical-block-prefix-not-string-error *prin-line-prefix*))
(%pprint-logical-block
(lambda (,out obj)
(declare (ignorable obj))
(let ((,idx 0) (*prin-level* (1+ *prin-level*)))
(macrolet ((pprint-pop ()
'(cond
((and *print-length* (>= ,idx *print-length*))
(write-string "..." ,out)
(go pprint-logical-block-end))
((and (/= 0 ,idx) (%circlep obj ,out))
(go pprint-logical-block-end))
((listp obj) (incf ,idx) (pop obj))
(t (write-string ". " ,out)
(write obj :stream ,out)
(go pprint-logical-block-end))))
(pprint-exit-if-list-exhausted ()
'(unless obj (go pprint-logical-block-end))))
(when ,pre
(write-string ,pre ,out)
(pprint-indent :current 0 ,out))
(tagbody ,@body
pprint-logical-block-end
(when ,suf
;; to avoid suffix being attached to the last string
(pprint-newline :fill ,out)
(write-string ,suf ,out))))))
,object ,out))))
(defun pprint-logical-block-both-error (prefix) ; ABI
(error (TEXT "~S: cannot supply both ~S (~S) and ~S (~S)")
'pprint-logical-block ':prefix prefix
':per-line-prefix *prin-line-prefix*))
(defun pprint-logical-block-prefix-not-string-error (prefix) ; ABI
(error-of-type 'type-error
:datum prefix :expected-type 'string
(TEXT "~S: ~S must be a string, not ~S")
'pprint-logical-block ':prefix prefix))
(defun pprint-logical-block-suffix-not-string-error (suffix) ; ABI
(error-of-type 'type-error
:datum suffix :expected-type 'string
(TEXT "~S: ~S must be a string, not ~S")
'pprint-logical-block ':suffix suffix))
;; ---------------------- utilities ----------------------
(defun pprint-tab (kind colnum colinc &optional stream)
;; kind ---one of :line, :section, :line-relative, or :section-relative.
;; colnum---a non-negative integer.
;; colinc---a non-negative integer.
;; stream---an output stream designator.
(format-tabulate stream
(ecase kind
((:line :line-relative) nil)
((:section :section-relative) t))
(ecase kind
((:line :section) nil)
((:line-relative :section-relative) t))
colnum colinc))
;; ---------------------- list printing ----------------------
(defun pprint-fill (out list &optional (colon-p t) at-sign-p)
;; out ---an output stream designator.
;; list ---an object.
;; colon-p ---a generalized boolean. The default is true.
;; at-sign-p---a generalized boolean. ignored
(declare (ignore at-sign-p))
(pprint-logical-block (out list :prefix (if colon-p "(" "")
:suffix (if colon-p ")" ""))
(pprint-exit-if-list-exhausted)
(loop (write (pprint-pop) :stream out)
(pprint-exit-if-list-exhausted)
(write-char #\Space out)
(pprint-newline :fill out))))
(defun pprint-linear (out list &optional (colon-p t) at-sign-p)
;; out ---an output stream designator.
;; list ---an object.
;; colon-p ---a generalized boolean. The default is true.
;; at-sign-p---a generalized boolean. ignored
(declare (ignore at-sign-p))
(pprint-logical-block (out list :prefix (if colon-p "(" "")
:suffix (if colon-p ")" ""))
(pprint-exit-if-list-exhausted)
(loop (write (pprint-pop) :stream out)
(pprint-exit-if-list-exhausted)
(write-char #\Space out)
(pprint-newline :linear out))))
;; lifted verbatim from CLHS
(defun pprint-tabular (out list &optional (colon-p t) at-sign-p (tabsize nil))
;; out ---an output stream designator.
;; list ---an object.
;; colon-p ---a generalized boolean. The default is true.
;; at-sign-p---a generalized boolean. ignored
;; tabsize ---a non-negative integer. The default is 16.
(declare (ignore at-sign-p))
(when (null tabsize) (setq tabsize 16))
(pprint-logical-block (out list :prefix (if colon-p "(" "")
:suffix (if colon-p ")" ""))
(pprint-exit-if-list-exhausted)
(loop (write (pprint-pop) :stream out)
(pprint-exit-if-list-exhausted)
(write-char #\Space out)
(pprint-tab :section-relative 0 tabsize out)
(pprint-newline :fill out))))
| 10,223 | Common Lisp | .lisp | 223 | 36.183857 | 78 | 0.562381 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 0337f029633e9a39614f667bba9df4452ec45a2783b4986235b2b40b45b52015 | 11,365 | [
-1
] |
11,366 | clos.lisp | ufasoft_lisp/clisp/clos.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004, 2007
;;;; German comments translated into English: Stefan Kain 2002-04-08
;;;; method combinations: James Anderson 2003
(in-package "CLOS")
;;; preliminary remarks:
;; abbreviations:
;; std = standard
;; gf = generic function
;; <...> = (class ...), mostly = (find-class '...)
;; em = effective method
; Now DEFCLASS works (except for accessor methods).
(load "clos-slots1")
(load "clos-method1")
(load "clos-methcomb1")
(load "clos-genfun1")
(load "clos-genfun2a")
(load "clos-methcomb2")
(load "clos-genfun2b")
(load "clos-method2")
(load "clos-genfun3")
; Now DEFGENERIC, DEFMETHOD work. DEFCLASS works fully.
(load "clos-dependent")
(load "clos-genfun4")
(load "clos-method3")
(load "clos-methcomb3")
(load "clos-slots2")
(load "clos-slotdef2")
(load "clos-stablehash2")
(load "clos-specializer2")
(load "clos-class4")
(load "clos-class5")
; Now instance creation works. Instances can be passed to generic functions.
(setq *classes-finished* t)
(setq *allow-making-generic* t)
(load "clos-slotdef3")
(load "clos-specializer3")
(load "clos-class6")
(load "clos-method4")
(load "clos-methcomb4")
(load "clos-genfun5")
(load "clos-print")
(load "clos-custom")
(setq *allow-making-generic* nil)
(load "documentation")
(setq *enable-clos-warnings* t)
;; Bootstrapping techniques
; Due to the extreme self-circularity of CLOS - classes are CLOS instances
; and therefore described by CLOS classes, generic functions are customizable
; through generic functions, CLOS instances are constructed through
; make-instance which is a generic function, etc. - several techniques need
; to be used for bootstrapping.
; 1) class-version
; Since each CLOS instance points to its class, and CLOS classes are
; themselves CLOS instances - how can the first CLOS class be created?
; In particular, the class STANDARD-CLASS is a direct instance of itself.
; But it also inherits from the classes CLASS, STANDARD-OBJECT and T, which
; are themselves also instances of CLASS.
; The solution is to realize that each instance points to a CLASS-VERSION
; which itself points to the CLASS. These CLASS-VERSION objects are ideal
; points for breaking the circularity, because they are just plain
; simple-vectors and because they are small in number: just one per concrete
; class.
; So for a concrete class <foo> we pre-allocate a class-version:
;
; (defvar *<foo>-class-version* (make-class-version))
;
; and use it during bootstrapping:
;
; (defun make-instance-<foo> (class &rest args &key &allow-other-keys)
; (declare (ignore class))
; (let ((instance (allocate-metaobject-instance *<foo>-class-version* n)))
; (apply #'initialize-instance-<foo> instance args)))
;
; Later, immediately after the class is really defined (which creates a new
; class-version for this class) we only need to connect the old class-version
; with the new class:
;
; (defparameter <foo> (defclass foo ...))
; (replace-class-version <foo> *<foo>-class-version*)
;
; No need to update already created <foo> instances!
; 2) fixed-slot-locations
; Each local slot value of a standard-object instance is stored at an index
; called "slot location". Each slot value access has, to determine it, to
; look it up in the class' slot-location-table (or similar). But how can it
; know where to find the slot-location-table? In the presence of multiple
; inheritance - which is explicitly allowed for subclasses of CLASS - the
; slot-location-table's index could depend on the class, thus again requiring
; a slot-location-table access in the metaclass, etc. ad infinitum.
; There are two ways to resolve this:
; a) Note that every chain x -> (CLASS-OF x) -> (CLASS-OF (CLASS-OF x)) -> ...
; must eventually end at the STANDARD-CLASS class. This is because user
; defined classes must have a metaclass that was defined before them, and
; among the predefined classes, the STANDARD-CLASS class is the only object
; for which (EQ x (CLASS-OF x)).
; b) The MOP has a restriction that does not allow programs to create classes
; that inherit from two categories of metaobjects (classes, slot-definitions,
; generic functions, methods, method-combinations) simultaneously. See
; MOP p. 3: "A metaobject class is a subclass of exactly one of these
; classes. The results are undefined if an attempt is made to define a
; class that is a subclass of more than one basic metaobject class."
; This allows the Lisp implementation to fix the index of every slot of the
; built-in metaobject classes.
; We use approach b), since it obviously leads to more efficient operations.
; (In particular, it allows the operations in record.d to use fixed indices
; for the slot-location-table.)
; To this effect, DEFCLASS with metaclass STANDARD-CLASS supports an option
; (:FIXED-SLOT-LOCATIONS T) that specifies that all local slots listed in this
; class will be accessible under the same slot locations in _all_ subclasses.
; Effectively this disallows some kinds of multiple inheritance; an error
; is signalled during the computation of the slot locations of subclasses if
; the constraints cannot be fulfilled.
; If a class has (:FIXED-SLOT-LOCATIONS T), it makes sense to mark all its
; superclasses that have slots as (:FIXED-SLOT-LOCATIONS T) as well.
; So, after
;
; (defclass foo ()
; (slot1 slot2 ... slotN)
; (:fixed-slot-locations t))
;
; we know that slot1 will be at index 1, slot2 at index 2, etc. in all
; subclasses.
; 3) initialize-instance and make-instance methods
; make-instance and initialize-instance are generic functions used for the
; construction of instances. But they are themselves built from methods,
; which are CLOS instances, and whose specializers are CLOS classes, therefore
; also CLOS instances. How can the first CLOS instances be created then?
; The solution is to use plain non-generic functions for creating and
; initializing all CLOS instances, until the CLOS is sufficiently complete
; for executing generic functions like make-instance and initialize-instance.
; But we want 1. to avoid code duplication, 2. to avoid differences in
; behaviour between the incomplete CLOS and the complete CLOS.
; The way to achieve this is to define the bulk of the built-in methods of
; user-extensible generic functions in plain functions, which then get called
; or replaced by method definitions.
;
; Idiom 1, that can be used for any normal or user-extensible generic function:
; (defclass foo ...)
; (defun something-<foo> (a b c) ...)
; (defun something (a b c) (something-<foo> a b c))
; (defun other-code ... (something ...))
; ; and then after CLOS is complete:
; (fmakunbound 'something)
; (defgeneric something (a b c)
; (:method ((a foo) b c)
; (something-<foo> a b c)))
;
; Idiom 2, that can be used for methods with only the standard behaviour:
; (defclass foo ...)
;
; (defun initialize-instance-<foo> (instance &rest args &key &allow-other-keys)
; (apply #'shared-initialize instance 't args))
; (defun other-code ... (initialize-instance-<foo> ...))
; ; and then after CLOS is complete:
; (setf (fdefinition 'initialize-instance-<foo>) #'initialize-instance)
;
; (defun make-instance-<foo> (class &rest args &key &allow-other-keys)
; (declare (ignore class))
; (let ((instance (allocate-metaobject-instance *<foo>-class-version* n)))
; (apply #'initialize-instance-<foo> instance args)))
; (defun other-code ... (make-instance-<foo> ...))
; ; and then after CLOS is complete:
; (setf (fdefinition 'make-instance-<foo>) #'make-instance)
; 4) *classes-finished* and %initialize-instance
; When the user creates a subclass of a metaobject class, instances of his
; class should be initialized correctly:
; (defclass my-method (method)
; ((slot1 :initform (slot1-init) ...) ...))
; It is the last-priority applicable method of initialize-instance, called
; clos::%initialize-instance, that calls
; (setf (slot-value new-instance 'slot1) (slot1-init))
; So we have to call clos::%initialize-instance at the beginning of
; initialize-instance-<method>. But we cannot do this while the CLOS is not
; complete - because clos::%initialize-instance does a CLASS-OF of the instance
; and then traverses the slot-location-table of the class. Both of these (the
; pointer from the class-version to the class, and the slot-location-table
; in the class) don't exist at this moment. The fact that CLOS is complete or
; not is indicated by the variable *classes-finished*. So what we do is
;
; (defun initialize-instance-<method> (instance &rest args &key &allow-other-keys)
; (when *classes-finished*
; (apply #'%initialize-instance instance args)) ; == (call-next-method)
; ...)
;
; But to avoid behaviour differences between *classes-finished* = nil and = t,
; we have simulate the task of %initialize-instance during bootstrapping. In
; the initialize-instance-<xyz> function of each subclass we have to fill the
; slots with the initforms. Example:
;
; (defun initialize-instance-<foo-method> (instance &rest args &key &allow-other-keys)
; (apply #'initialize-instance-<method> instance args) ; == (call-next-method)
; (unless *classes-finished*
; ; Bootstrapping: Simulate the effect of #'%initialize-instance.
; (setf (foo-method-slot1) (foo-method-slot1-initform))
; ...)
; ...)
;
; For subclasses of <class>, the same holds for shared-initialize instead of
; initialize-instance.
; 5) generic-accessors
; Once CLASS and SLOT-DEFINITION and its subclasses are defined, we can already
; use DEFCLASS to define classes like METHOD or METHOD-COMBINATION. The use of
; (:FIXED-SLOT-LOCATIONS T) guarantees fast accessors if we write them by hand,
; one by one. As a shorthand, to automate the creation of accessors at a moment
; when generic functions don't yet work, the DEFCLASS option
; (:GENERIC-ACCESSORS NIL) allows to create the accessors as plain functions.
; This is like DEFSTRUCT does for STRUCTURE-CLASS/STRUCTURE-OBJECT instance
; accessors, except that it also works for STANDARD-CLASS/STANDARD-OBJECT
; accessors. Thus,
;
; (defclass foo ()
; ((slot1 :accessor foo-slot1) ...)
; (:generic-accessors nil))
;
; is equivalent to
;
; (defclass foo ()
; ((slot1) ...)
; (defun foo-slot1 (instance)
; (accessor-typecheck instance 'foo 'foo-slot1)
; (slot-value instance 'slot1))
; (defun (setf foo-slot1) (new-value instance)
; (accessor-typecheck instance 'foo '(setf foo-slot1))
; (setf (slot-value instance 'slot1) new-value))
;
; This can be combined with (:FIXED-SLOT-LOCATIONS T):
;
; (defclass foo ()
; ((slot1 :accessor foo-slot1) ...)
; (:fixed-slot-locations t)
; (:generic-accessors nil))
;
; is equivalent to
;
; (defclass foo ()
; ((slot1) ...)
; (defun foo-slot1 (instance)
; (accessor-typecheck instance 'foo 'foo-slot1)
; (sys::%record-ref instance 1))
; (defun (setf foo-slot1) (new-value instance)
; (accessor-typecheck instance 'foo '(setf foo-slot1))
; (setf (sys::%record-ref instance 1) new-value))
;; Debugging Techniques
; Some generic functions, like compute-effective-method or method-specializers,
; are used to implement the behaviour of generic functions. We have a boot-
; strapping problem here.
; Since we try to call the generic function whenever possible, and the non-
; generic particular method only if absolutely necessary, the technique is to
; write generic code and break the metacircularity at selected points.
; In practice this means you get a "*** - Lisp stack overflow. RESET" message
; and have to break the endless recursion. How to detect the metacircularity
; that causes the endless recursion?
; 1. Start "./lisp.run -i init.lisp | tee log". You get "Lisp stack overflow".
; 2. Find the source form which causes the endless recursion. If you are
; unsure, add a ":echo t" to the LOAD form loading the particular form in
; init.lisp or clos.lisp and go back to step 1.
; 3. At the prompt, type (in-package "CLOS") and the problematic source form.
; 4. While it is executing, eating more and more stack, interrupt it through a
; "kill -2 <pid>" from a nearby shell window, where <pid> is the lisp.run's
; process id. (Just pressing Ctrl-C would kill the lisp.run and tee
; processes.)
; 5. Type (ext:show-stack).
; 6. Analyze the resulting log file. To find the loop in the stack trace,
; concentrate on the middle. You have to skip the first 500 or 1000 lines
; of stack trace. To get a quick overview, look at only the lines
; starting with "APPLY frame".
; 7. Think about the ideal point for breaking the loop.
;; Extension Protocols
; The MOP specifies the following individual protocols.
; The "checks" column tells whether the CLISP code contains verifications
; that the user added code is fulfilling the required constraints.
; The "testsuite" column tells whether the mop.tst contains interesting
; testcases.
; checks testsuite
; add-dependent remove-dependent map-dependents -- OK
; add-direct-method remove-direct-method \
; specializer-direct-generic-functions \
; specializer-direct-methods -- OK
; add-direct-subclass remove-direct-subclass \
; class-direct-subclasses OK OK
; compute-applicable-methods \
; compute-applicable-methods-using-classes OK OK
; compute-class-precedence-list OK OK
; compute-default-initargs OK OK
; compute-direct-slot-definition-initargs OK OK
; compute-discriminating-function OK OK
; compute-effective-method -- OK
; compute-effective-slot-definition OK OK
; compute-effective-slot-definition-initargs OK OK
; compute-slots OK OK
; direct-slot-definition-class OK OK
; effective-slot-definition-class OK OK
; ensure-class-using-class OK OK
; ensure-generic-function-using-class OK OK
; make-method-lambda
; reader-method-class OK OK
; slot-value-using-class \
; (setf slot-value-using-class) \
; slot-boundp-using-class \
; slot-makunbound-using-class -- OK
; validate-superclass OK OK
; writer-method-class OK OK
| 14,745 | Common Lisp | .lisp | 304 | 47.444079 | 88 | 0.709214 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 044cb0b02da595bf2c4c3c618086e366fc34a1b7107e73786b074620bc0f653e | 11,366 | [
-1
] |
11,367 | clos-method1.lisp | ufasoft_lisp/clisp/clos-method1.lisp | ;;;; Common Lisp Object System for CLISP: Methods
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004, 2007, 2010
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
;;; ---------------------------------------------------------------------------
(defparameter <method>
(defclass method (standard-stablehash metaobject)
(($from-defgeneric ; flag, if this method comes from a DEFGENERIC
:type boolean
:accessor method-from-defgeneric))
(:fixed-slot-locations t)
(:generic-accessors nil)))
(defun initialize-instance-<method> (method &rest args
&key ((from-defgeneric from-defgeneric) nil)
((backpointer backpointer) nil backpointer-p)
&allow-other-keys)
(if *classes-finished*
(apply #'%initialize-instance method args) ; == (call-next-method)
; Bootstrapping: Simulate the effect of #'%initialize-instance.
(apply #'shared-initialize-<standard-stablehash> method 't args))
; Fill the slots.
(setf (method-from-defgeneric method) from-defgeneric)
; Fill the backpointer. This is needed for NO-NEXT-METHOD to work: When
; CALL-NEXT-METHOD is called from within the method function without a next
; method being available, the method function must call NO-NEXT-METHOD with
; the method object as argument. But since the method function is called
; with the argument list and the remaining methods list as arguments, it
; cannot know about the method object to which it belongs. We solve this
; paradox by constructing a backpointer cons that the method function
; has access to and that points back to the method object after it has been
; initialized.
(when backpointer-p
(setf (car backpointer) method))
method)
;;; ---------------------------------------------------------------------------
(defparameter <standard-method> ; ABI
(defclass standard-method (method)
(($fast-function ; the function with fast calling conventions, i.e.
; argument list (&rest arguments) or
; (next-methods-function &rest arguments), depending
; on wants-next-method-p
:type (or null function)
:accessor std-method-fast-function)
($wants-next-method-p ; flag, if the NEXT-METHOD (as function with all
; arguments) resp. NIL is to be passed as first
; argument (= NIL for :BEFORE- and :AFTER-methods)
:type boolean
:accessor std-method-wants-next-method-p)
($function ; the function with slow calling conventions, i.e.
; argument list (arguments next-methods-list)
:type (or null function)
:accessor std-method-function)
($specializers ; list of specializers, e.g. classes or
; eql-specializers
:type list
:accessor std-method-specializers)
($qualifiers ; list of non-NIL atoms, e.g. (:before)
:type list
:accessor std-method-qualifiers)
($lambda-list ; lambda list without specializers
:type list
:accessor std-method-lambda-list)
($signature ; signature struct (see functions.lisp)
:type (simple-vector 6)
:accessor std-method-signature)
($documentation ; string or NIL
:type (or string null)
:accessor std-method-documentation)
($gf ; the generic function, which this method belongs to
; (only for the purpose of CALL-NEXT-METHOD and
; NO-NEXT-METHOD)
:type (or null generic-function)
:accessor std-method-generic-function))
(:fixed-slot-locations t)
(:generic-accessors nil)))
;; Note about the argument passing convention for methods:
;; 1) The MOP description of COMPUTE-EFFECTIVE-METHOD and MAKE-METHOD-LAMBDA
;; says that a method function takes 2 arguments: the list of arguments (!)
;; and the list of next methods. This is awfully inefficient, and useless
;; (since MAKE-METHOD-LAMBDA is ill-designed anyway). Therefore here we
;; pass to the function the arguments as-is, and the next methods as
;; inserted first argument, if needed.
;; 2) Instead of the list of next methods, we pass an effective method that
;; consists of these next methods. This is more efficient (saves a FUNCALL)
;; for the simple case of a single applicable method, but is less
;; efficient (a FUNCALL instead of just a CAR) for longer lists of methods.
;; 3) We don't explicitly pass the generic function to the method during the
;; invocation. However, for CALL-NEXT-METHOD, NO-NEXT-METHOD and
;; METHOD-GENERIC-FUNCTION the generic function must be known. So we have
;; to store a generic function backpointer in the method.
(defun method-lambda-list-to-signature (lambda-list errfunc)
(multiple-value-bind (reqvars optvars optinits optsvars rest
keyp keywords keyvars keyinits keysvars
allowp auxvars auxinits)
(analyze-lambdalist lambda-list errfunc)
(declare (ignore optinits optsvars keyvars keyinits keysvars
auxvars auxinits))
(make-signature
:req-num (length reqvars) :opt-num (length optvars)
:rest-p (or keyp (not (eql rest 0))) :keys-p keyp
:keywords keywords :allow-p allowp)))
(defun initialize-instance-<standard-method> (method &rest args
&key (qualifiers '())
(lambda-list nil lambda-list-p)
(specializers nil specializers-p)
(function nil function-p)
(documentation nil)
((fast-function fast-function) nil fast-function-p)
((wants-next-method-p wants-next-method-p) nil)
((signature signature) nil signature-p)
((gf gf) nil)
((from-defgeneric from-defgeneric) nil)
((backpointer backpointer) nil)
&allow-other-keys)
(declare (ignore from-defgeneric backpointer))
(apply #'initialize-instance-<method> method args) ; == (call-next-method)
; Check the qualifiers.
(unless (proper-list-p qualifiers)
(error (TEXT "(~S ~S): The ~S argument should be a proper list, not ~S")
'initialize-instance 'standard-method ':qualifiers qualifiers))
(unless (notany #'listp qualifiers)
(error (TEXT "(~S ~S): The qualifiers list should consist of non-NIL atoms, not ~S")
'initialize-instance 'standard-method qualifiers))
; Check the lambda-list and compute the signature from it.
(unless lambda-list-p
(error (TEXT "(~S ~S): Missing ~S argument.")
'initialize-instance 'standard-method ':lambda-list))
(let ((sig (method-lambda-list-to-signature lambda-list
#'(lambda (form detail errorstring &rest arguments)
(sys::lambda-list-error form detail
(TEXT "(~S ~S): Invalid ~S argument: ~A")
'initialize-instance 'standard-method ':lambda-list
(apply #'format nil errorstring arguments))))))
; Check the signature argument. It is optional; specifying it only has
; the purpose of saving memory allocation (by sharing the same signature
; for all reader methods and the same signature for all writer methods).
(if signature-p
(unless (equalp sig signature)
(error (TEXT "(~S ~S): Lambda-list ~S and signature ~S are inconsistent.")
'initialize-instance 'standard-method lambda-list signature))
(setq signature sig)))
; Check the specializers.
(unless specializers-p
(error (TEXT "(~S ~S): Missing ~S argument.")
'initialize-instance 'standard-method ':specializers))
(unless (proper-list-p specializers)
(error (TEXT "(~S ~S): The ~S argument should be a proper list, not ~S")
'initialize-instance 'standard-method ':specializers specializers))
(dolist (x specializers)
(unless (or (defined-class-p x) (eql-specializer-p x))
(if (typep x 'specializer)
(error (TEXT "(~S ~S): The element ~S of the ~S argument is not yet defined.")
'initialize-instance 'standard-method x ':specializers)
(error (TEXT "(~S ~S): The element ~S of the ~S argument is not of type ~S.")
'initialize-instance 'standard-method x ':specializers 'specializer))))
(unless (= (length specializers) (sig-req-num signature))
(error (TEXT "(~S ~S): The lambda list ~S has ~S required arguments, but the specializers list ~S has length ~S.")
'initialize-instance 'standard-method lambda-list (sig-req-num signature)
specializers (length specializers)))
; Check the function, fast-function and wants-next-method-p.
(unless (or function-p fast-function-p)
(error (TEXT "(~S ~S): Missing ~S argument.")
'initialize-instance 'standard-method ':function))
(when function-p
(unless (functionp function)
(error (TEXT "(~S ~S): The ~S argument should be a function, not ~S")
'initialize-instance 'standard-method ':function function)))
(when fast-function-p
(unless (functionp fast-function)
(error (TEXT "(~S ~S): The ~S argument should be a function, not ~S")
'initialize-instance 'standard-method 'fast-function fast-function)))
(unless (typep wants-next-method-p 'boolean)
(error (TEXT "(~S ~S): The ~S argument should be a NIL or T, not ~S")
'initialize-instance 'standard-method 'wants-next-method-p wants-next-method-p))
(when function-p
;; :function overrides fast-function and wants-next-method-p, because it is
;; the standardized way (employed by user-defined method classes) to define
;; the behaviour of a method.
(setq fast-function nil
wants-next-method-p t))
; Check the documentation.
(unless (or (null documentation) (stringp documentation))
(error (TEXT "(~S ~S): The ~S argument should be a string or NIL, not ~S")
'initialize-instance 'standard-method ':documentation documentation))
; Fill the slots.
(setf (std-method-fast-function method) fast-function)
(setf (std-method-wants-next-method-p method) wants-next-method-p)
(setf (std-method-function method) function)
(setf (std-method-specializers method) specializers)
(setf (std-method-qualifiers method) qualifiers)
(setf (std-method-lambda-list method) lambda-list)
(setf (std-method-signature method) signature)
(setf (std-method-documentation method) documentation)
(setf (std-method-generic-function method) gf)
method)
(defun make-instance-<standard-method> (class &rest args
&key &allow-other-keys)
;; class = <standard-method>
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'make-instance later.
(declare (ignore class))
(let ((method (%allocate-instance <standard-method>)))
(apply #'initialize-instance-<standard-method> method args)))
(defun print-object-<standard-method> (method stream)
(print-unreadable-object (method stream :type t)
(if (and (not (eq (sys::%unbound) (std-method-qualifiers method)))
(not (eq (sys::%unbound) (std-method-specializers method))))
(progn
(dolist (q (std-method-qualifiers method))
(write q :stream stream)
(write-char #\Space stream))
(write (mapcar #'specializer-pretty (std-method-specializers method))
:stream stream))
(write :uninitialized :stream stream))))
;; Preliminary.
;; During bootstrapping, only <standard-method> instances are used.
(defun make-method-instance (class &rest args ; ABI
&key &allow-other-keys)
(apply #'make-instance-<standard-method> class args))
(predefun method-function (method)
(std-method-function-or-substitute method))
(predefun method-qualifiers (method)
(std-method-qualifiers method))
(predefun method-lambda-list (method)
(std-method-lambda-list method))
(predefun method-signature (method)
(std-method-signature method))
(predefun method-specializers (method)
(std-method-specializers method))
(predefun method-generic-function (method)
(std-method-generic-function method))
(predefun (setf method-generic-function) (new-gf method)
(setf (std-method-generic-function method) new-gf))
;;; ---------------------------------------------------------------------------
(defparameter <standard-accessor-method>
(defclass standard-accessor-method (standard-method)
(($slot-definition ; direct slot definition responsible for this method
:type direct-slot-definition
:accessor %accessor-method-slot-definition))
(:fixed-slot-locations t)
(:generic-accessors nil)))
(defun initialize-instance-<standard-accessor-method> (method &rest args
&key (slot-definition nil slot-definition-p)
&allow-other-keys)
(apply #'initialize-instance-<standard-method> method args) ; == (call-next-method)
; Check the slot-definition.
(unless slot-definition-p
(error (TEXT "(~S ~S): Missing ~S argument.")
'initialize-instance 'standard-accessor-method ':slot-definition))
(unless (typep slot-definition 'direct-slot-definition)
(error (TEXT "(~S ~S): Argument ~S is not of type ~S.")
'initialize-instance 'standard-accessor-method ':slot-definition
'direct-slot-definition))
; Fill the slots.
(setf (%accessor-method-slot-definition method) slot-definition)
method)
;;; ---------------------------------------------------------------------------
(defparameter <standard-reader-method>
(defclass standard-reader-method (standard-accessor-method)
()
(:fixed-slot-locations t)))
(defun make-instance-<standard-reader-method> (class &rest args
&key &allow-other-keys)
;; class = <standard-reader-method>
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'make-instance later.
(declare (ignore class))
(let ((method (%allocate-instance <standard-reader-method>)))
(apply #'initialize-instance-<standard-accessor-method> method args)))
;;; ---------------------------------------------------------------------------
(defparameter <standard-writer-method>
(defclass standard-writer-method (standard-accessor-method)
()
(:fixed-slot-locations t)))
(defun make-instance-<standard-writer-method> (class &rest args
&key &allow-other-keys)
;; class = <standard-writer-method>
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'make-instance later.
(declare (ignore class))
(let ((method (%allocate-instance <standard-writer-method>)))
(apply #'initialize-instance-<standard-accessor-method> method args)))
;;; ---------------------------------------------------------------------------
| 15,670 | Common Lisp | .lisp | 284 | 45.933099 | 118 | 0.626115 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 6e4be4b726c66d29eb9d5268616b585c8ca82e81563c39d463868becd4ed1505 | 11,367 | [
-1
] |
11,368 | clos-slots2.lisp | ufasoft_lisp/clisp/clos-slots2.lisp | ;;;; Common Lisp Object System for CLISP: Slots
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
;;; ===========================================================================
(defgeneric slot-missing (class instance slot-name operation
&optional new-value)
(:method ((class t) instance slot-name operation &optional new-value)
(declare (ignore instance new-value))
(error-of-type 'error
(TEXT "~S: The class ~S has no slot named ~S")
operation class slot-name)))
(defgeneric slot-unbound (class instance slot-name)
(:method ((class t) instance slot-name)
(declare (ignore class))
(multiple-value-bind (new-value store-p)
(sys::check-value `(slot-value ,instance ',slot-name)
(make-condition 'sys::simple-unbound-slot
:name slot-name
:instance instance
:format-control (TEXT "~S: The slot ~S of ~S has no value")
:format-arguments (list 'slot-value slot-name instance)))
(when store-p
(setf (slot-value instance slot-name) new-value))
new-value)))
;;; ===========================================================================
;; Optimization of SLOT-VALUE and its brothers.
;; They are optimized to work as follows:
;; Step 1: (class-of instance) -> a class object. Take its slot-location-table.
;; Step 2: Lookup the slot name in the table. The result is an object that
;; encodes the behaviour of
;; (slot-value-using-class this-class any-direct-instance slot)
;; ((setf slot-value-using-class) any-new-value this-class any-direct-instance slot)
;; (slot-boundp-using-class this-class any-direct-instance slot)
;; (slot-makunbound-using-class this-class any-direct-instance slot)
;; for the slot with the given name. In the particular case that these generic
;; functions' effective methods are the predefined ones, the object is just the
;; slot location (a cons or nonnegative fixnum).
(defun invalidate-slot-value-info (class-specializer instance-specializer slot-specializer)
;; Step 1: Determine all affected classes that satisfy the instance-specializer.
(let ((affected-classes
(if (defined-class-p instance-specializer)
(if (= (class-initialized instance-specializer) 6) ; finalized?
(list-all-finalized-subclasses instance-specializer)
'())
(list (class-of (eql-specializer-object instance-specializer))))))
;; Step 2: Filter out those that don't satisfy the class-specializer.
(setq affected-classes
(remove-if-not #'(lambda (c) (typep c class-specializer))
affected-classes))
;; Step 3: Iterate over the affected classes and recompute the relevant
;; entries in the slot-location-table.
(dolist (class affected-classes)
(let ((ht (class-slot-location-table class)))
(dolist (slot (class-slots class))
(when (typep slot slot-specializer)
(setf (gethash (slot-definition-name slot) ht)
(compute-slot-location-table-entry class slot))))))))
(defun note-svuc-change (method)
(apply #'invalidate-slot-value-info (method-specializers method)))
(defun note-ssvuc-change (method)
(apply #'invalidate-slot-value-info (cdr (method-specializers method))))
(defun note-sbuc-change (method)
(apply #'invalidate-slot-value-info (method-specializers method)))
(defun note-smuc-change (method)
(apply #'invalidate-slot-value-info (method-specializers method)))
;; MOP p. 97
(defgeneric slot-value-using-class (class object slot))
(setq |#'slot-value-using-class| #'slot-value-using-class)
#|
(defmethod slot-value-using-class ((class semi-standard-class) instance (slot standard-effective-slot-definition))
(let ((slot-name (slot-definition-name slot))
(slot-location (slot-definition-location slot)))
((lambda (value)
(if (eq value unbound)
(slot-unbound class instance slot-name)
value))
(cond ((null slot-location)
(slot-missing class instance slot-name 'slot-value))
((atom slot-location) ; access local slot
(sys::%record-ref instance slot-location))
(t ; access shared slot
(svref (cv-shared-slots (car slot-location))
(cdr slot-location)))))))
|#
;; The main work is done by a SUBR:
(do-defmethod 'slot-value-using-class
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'semi-standard-class)
(find-class 't)
(find-class 'standard-effective-slot-definition))
'fast-function #'clos::%slot-value-using-class
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(class instance slot)
'signature #s(system::signature :req-num 3)))
;; MOP p. 93
(defgeneric (setf slot-value-using-class) (new-value class object slot))
(setq |#'(setf slot-value-using-class)| #'(setf slot-value-using-class))
#|
(defmethod (setf slot-value-using-class) (new-value (class semi-standard-class) instance (slot standard-effective-slot-definition))
(let ((slot-name (slot-definition-name slot))
(slot-location (slot-definition-location slot)))
(cond ((null slot-location)
(slot-missing class instance slot-name 'setf new-value))
((atom slot-location) ; access local slot
(sys::%record-store instance slot-location new-value))
(t ; access shared slot
(setf (svref (cv-shared-slots (car slot-location))
(cdr slot-location))
new-value)))))
|#
;; The main work is done by a SUBR:
(do-defmethod '(setf slot-value-using-class)
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 't)
(find-class 'semi-standard-class)
(find-class 't)
(find-class 'standard-effective-slot-definition))
'fast-function #'clos::%set-slot-value-using-class
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(new-value class instance slot)
'signature #s(system::signature :req-num 4)))
;; MOP p. 94
(defgeneric slot-boundp-using-class (class object slot))
(setq |#'slot-boundp-using-class| #'slot-boundp-using-class)
#|
(defmethod slot-boundp-using-class ((class semi-standard-class) instance (slot standard-effective-slot-definition))
(let ((slot-name (slot-definition-name slot))
(slot-location (slot-definition-location slot)))
(cond ((null slot-location)
(slot-missing class instance slot-name 'slot-boundp))
((atom slot-location) ; access local slot
(not (eq (sys::%record-ref instance slot-location) unbound)))
(t ; access shared slot
(not (eq (svref (cv-shared-slots (car slot-location))
(cdr slot-location))
unbound))))))
|#
;; The main work is done by a SUBR:
(do-defmethod 'slot-boundp-using-class
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'semi-standard-class)
(find-class 't)
(find-class 'standard-effective-slot-definition))
'fast-function #'clos::%slot-boundp-using-class
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(class instance slot)
'signature #s(system::signature :req-num 3)))
;; MOP p. 96
(defgeneric slot-makunbound-using-class (class object slot))
(setq |#'slot-makunbound-using-class| #'slot-makunbound-using-class)
#|
(defmethod slot-makunbound-using-class ((class semi-standard-class) instance (slot standard-effective-slot-definition))
(let ((slot-name (slot-definition-name slot))
(slot-location (slot-definition-location slot)))
(cond ((null slot-location)
(slot-missing class instance slot-name 'slot-makunbound))
((atom slot-location) ; access local slot
(sys::%record-store instance slot-location unbound))
(t ; access shared slot
(setf (svref (cv-shared-slots (car slot-location))
(cdr slot-location))
unbound)))))
|#
;; The main work is done by a SUBR:
(do-defmethod 'slot-makunbound-using-class
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'semi-standard-class)
(find-class 't)
(find-class 'standard-effective-slot-definition))
'fast-function #'clos::%slot-makunbound-using-class
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(class instance slot)
'signature #s(system::signature :req-num 3)))
| 8,776 | Common Lisp | .lisp | 179 | 41.810056 | 131 | 0.650897 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | ada02bbd9c438be33903001fca3df10234c6a329b7e8288e4d49b238236d8b35 | 11,368 | [
-1
] |
11,369 | clos-method2.lisp | ufasoft_lisp/clisp/clos-method2.lisp | ;;;; Common Lisp Object System for CLISP: Methods
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004, 2008, 2010
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
;; ANSI CL 3.4.3. Specialized Lambda Lists
;; Decompose a specialized lambda list into
;; 1. an ordinary lambda list,
;; 2. a list of specializers for the required arguments,
;; 3. a list of ignorable required parameters.
(defun decompose-specialized-lambda-list (specialized-lambda-list errfunc)
(let ((remaining-lambda-list specialized-lambda-list)
(req-vars '())
(ignorable-req-vars '())
(spec-list '()))
(do ()
((or (atom remaining-lambda-list)
(memq (car remaining-lambda-list) lambda-list-keywords)))
(let ((item (pop remaining-lambda-list)))
;; item can be a variable or of the form (variable specializer-name).
;; ANSI CL 3.4.3. also allows the syntax (variable), but the DEFMETHOD
;; description forbids it, and the DEFGENERIC description refers to it.
(if (atom item)
(progn
(push item req-vars)
(push 't spec-list))
(if (and (consp (cdr item)) (null (cddr item)))
(progn
(push (first item) req-vars)
(push (first item) ignorable-req-vars) ; CLtL2 p. 840 top
(push (second item) spec-list))
(funcall errfunc specialized-lambda-list item
(TEXT "Invalid specialized parameter in method lambda list ~S: ~S")
specialized-lambda-list item)))))
(let ((lambda-list (nreconc req-vars remaining-lambda-list)))
(analyze-lambdalist lambda-list errfunc)
(values lambda-list (nreverse spec-list) (nreverse ignorable-req-vars)))))
;; helper
(defmacro program-error-reporter (caller)
`#'(lambda (form detail errorstring &rest arguments)
(apply #'sys::lambda-list-error form detail
"~S: ~A" ,caller (apply #'format nil errorstring arguments))))
;; MOP p. 52
(defun extract-lambda-list (specialized-lambda-list)
(nth-value 0
(decompose-specialized-lambda-list
specialized-lambda-list
(program-error-reporter 'extract-lambda-list))))
;; MOP p. 53
(defun extract-specializer-names (specialized-lambda-list)
(nth-value 1
(decompose-specialized-lambda-list
specialized-lambda-list
(program-error-reporter 'extract-specializer-names))))
;;; For DEFMETHOD, DEFGENERIC, GENERIC-FUNCTION, GENERIC-FLET,
;;; GENERIC-LABELS, WITH-ADDED-METHODS
;; caller: symbol
;; whole-form: whole source form
;; funname: function name, symbol or (SETF symbol)
;; description: (qualifier* spec-lambda-list {declaration|docstring}* form*)
;; ==>
;; 1. a function lambda, to be applied to a backpointer cons (that will later
;; point back to the method object), that returns a cons h with
;; (car h) = fast-function,
;; (cadr h) = true if the compiler could optimize away the ",cont" variable.
;; 2. method-initargs-forms,
;; 3. signature
(defun analyze-method-description (caller whole-form funname description)
;; Collect the qualifiers:
(let ((qualifiers nil))
(loop
(when (atom description)
(error-of-type 'ext:source-program-error
:form whole-form
:detail description
(TEXT "~S ~S: missing lambda list")
caller funname))
(when (listp (car description)) (return))
(push (pop description) qualifiers))
(setq qualifiers (nreverse qualifiers))
;; Build lambdalist, extract parameter-specializers and signature:
(let ((specialized-lambda-list (car description))
(body (cdr description)))
(multiple-value-bind (lambda-list spec-list ignorable-req-vars)
(decompose-specialized-lambda-list specialized-lambda-list
#'(lambda (form detail errorstring &rest arguments)
(declare (ignore form)) ; FORM is lambda-list, use WHOLE-FORM
(sys::lambda-list-error whole-form detail
"~S ~S: ~A" caller funname
(apply #'format nil errorstring arguments))))
(let ((req-specializer-forms
(mapcar #'(lambda (specializer-name)
(cond ((defined-class-p specializer-name)
`',specializer-name)
((symbolp specializer-name)
`(FIND-CLASS ',specializer-name))
((and (consp specializer-name)
(eq (car specializer-name) 'EQL)
(consp (cdr specializer-name))
(null (cddr specializer-name)))
`(INTERN-EQL-SPECIALIZER ,(second specializer-name)))
(t (error-of-type 'ext:source-program-error
:form whole-form
:detail specializer-name
(TEXT "~S ~S: Invalid specializer ~S in lambda list ~S")
caller funname specializer-name specialized-lambda-list))))
spec-list)))
(check-method-redefinition funname qualifiers spec-list caller)
(multiple-value-bind (reqvars optvars optinits optsvars rest
keyp keywords keyvars keyinits keysvars
allowp auxvars auxinits)
(analyze-lambdalist lambda-list
#'(lambda (lalist detail errorstring &rest arguments)
(declare (ignore lalist)) ; use WHOLE-FORM instead
(sys::lambda-list-error whole-form detail
"~S ~S: ~A" caller funname
(apply #'format nil errorstring arguments))))
(declare (ignore optinits optsvars keyvars keyinits keysvars
auxvars auxinits))
(let ((reqnum (length reqvars))
(optnum (length optvars))
(restp (or keyp (not (eql rest 0))))
(weakened-lambda-list lambda-list))
;; Methods have an implicit &allow-other-keys (CLtL2 28.1.6.4., ANSI CL 7.6.4.):
(when (and keyp (not allowp))
(let ((index (+ (position '&KEY lambda-list :test #'eq) 1 (length keywords))))
(setq weakened-lambda-list
`(,@(subseq lambda-list 0 index) &ALLOW-OTHER-KEYS
,@(subseq lambda-list index)))))
(let* ((backpointer (gensym))
(compile-decl nil)
(documentation nil)
(lambdabody
(multiple-value-bind (body-rest declarations docstring compile-name)
(sys::parse-body body t)
(setq compile-decl
(case compile-name
(0 '()) (1 '((DECLARE (COMPILE))))
(t `((DECLARE (COMPILE ,compile-name))))))
(setq documentation docstring)
(when ignorable-req-vars
(push `(IGNORABLE ,@ignorable-req-vars) declarations))
(let ((lambdabody-part1
`(,weakened-lambda-list
,@(if declarations `((DECLARE ,@declarations)))))
(lambdabody-part2
(if (eq caller 'generic-function)
body-rest
;; implicit block
`((BLOCK ,(function-block-name funname)
,@body-rest)))))
(let ((cont (gensym)) ; variable for the continuation
(req-dummies (gensym-list reqnum))
(rest-dummy (if (or restp (> optnum 0)) (gensym)))
(lambda-expr `(LAMBDA ,@lambdabody-part1 ,@lambdabody-part2)))
`(; new lambda-list:
(,cont
,@req-dummies
,@(if rest-dummy `(&REST ,rest-dummy) '()))
,(add-next-method-local-functions
backpointer cont req-dummies rest-dummy
;; new body:
(list
(if rest-dummy
`(APPLY (FUNCTION ,lambda-expr)
,@req-dummies ,rest-dummy)
`(,lambda-expr ,@req-dummies)))))))))
(sig (make-signature :req-num reqnum :opt-num optnum
:rest-p restp :keys-p keyp
:keywords keywords :allow-p allowp)))
(values
`(LAMBDA (,backpointer)
,@compile-decl
(%OPTIMIZE-FUNCTION-LAMBDA (T) ,@lambdabody))
`(:QUALIFIERS ',qualifiers
:LAMBDA-LIST ',lambda-list
'SIGNATURE ,sig
:SPECIALIZERS (LIST ,@req-specializer-forms)
,@(if documentation `(:DOCUMENTATION ',documentation))
,@(if (eq caller 'DEFGENERIC) `('FROM-DEFGENERIC T)))
sig)))))))))
| 9,708 | Common Lisp | .lisp | 181 | 36.331492 | 98 | 0.520323 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | ee6ca5b24746b3d5258a52c3660a0ac8528ab4c1c5986e39e9f7661942a15d29 | 11,369 | [
-1
] |
11,370 | lambdalist.lisp | ufasoft_lisp/clisp/lambdalist.lisp | ;;; Parsing ordinary lambda lists
;;; Bruno Haible 1988-2004
;;; Sam Steingold 1999-2005, 2010
(in-package "SYSTEM")
;; this is the standard errfunc argument for analyze-lambdalist et al.
(defun lambda-list-error (form detail &rest args)
(apply #'error-of-type 'ext:source-program-error
:form form :detail detail args))
(macrolet ((push (element-form list-var)
`(setq ,list-var (cons ,element-form ,list-var)))
(err-misplaced (item)
`(funcall errfunc lambdalist ,item
(TEXT "Lambda list marker ~S not allowed here.")
,item))
(err-invalid (item)
`(funcall errfunc lambdalist ,item
(if (or (symbolp ,item) (listp ,item))
(TEXT "Invalid lambda list element ~S")
(TEXT "Invalid lambda list element ~S. A lambda list may only contain symbols and lists."))
,item))
(err-no-default (marker item)
`(funcall errfunc lambdalist ,item
(TEXT "Invalid lambda list element ~S. ~S parameters cannot have default value forms in generic function lambda lists.")
',marker ,item))
(check-item (item permissible)
`(if (memq ,item ',permissible)
(return)
(err-misplaced ,item)))
(dolist ((item L) &body body)
;; this is different from CL:DOLIST which uses ENDP instead of ATOM
`(loop (if (atom ,L) (return))
(let ((,item (car ,L))) ,@body)
(setq ,L (cdr ,L))))
(check-exhausted (L)
`(when ,L
(funcall errfunc lambdalist ,L
(TEXT "Lambda lists with dots are only allowed in macros, not here: ~S")
lambdalist)))
(symbol-or-pair-p (x) ; FOO or (FOO BAR)
`(or (symbolp ,x)
(and (consp ,x)
(symbolp (car ,x))
(consp (cdr ,x))
(symbolp (cadr ,x))
(null (cddr ,x)))))
(singleton-symbol-p (x) ; (FOO)
`(and (consp ,x) (symbolp (car ,x)) (null (cdr ,x))))
(err-missing (marker)
`(funcall errfunc lambdalist lambdalist
(TEXT "Missing ~S parameter in lambda list ~S")
',marker lambdalist))
(last-parameter (L var marker &body body)
`(when (and (consp ,L) (eq (car ,L) ',marker))
(setq ,L (cdr ,L))
(if (atom L)
(err-missing ,marker)
(prog ((item (car ,L)))
(if (symbolp item)
(if (memq item lambda-list-keywords)
(progn (err-missing ,marker) (return))
(setq ,var item))
(err-invalid item))
(setq ,L (cdr ,L))))
,@body))
(process-required (L reqvar permissible &optional no-duplicates)
`(dolist (item ,L)
(if (symbolp item)
(if (memq item lambda-list-keywords)
(check-item item ,permissible)
,(if no-duplicates
`(if (memq item ,reqvar)
(funcall errfunc lambdalist item
(TEXT "Duplicate variable name ~S") item)
(push item ,reqvar))
`(push item ,reqvar)))
(err-invalid item))))
(push3 (s1 s2 s3 d1 d2 d3)
`(progn (push ,s1 ,d1) (push ,s2 ,d2) (push ,s3 ,d3)))
(process-optional (L optvar optinit optsvar permissible)
`(when (and (consp ,L) (eq (car ,L) '&optional))
(setq ,L (cdr ,L))
(dolist (item ,L)
(if (symbolp item)
(if (memq item lambda-list-keywords)
(check-item item ,permissible)
(push3 item nil 0 optvar optinit optsvar))
(if (and (consp item) (symbolp (car item)))
(if (null (cdr item))
(push3 (car item) nil 0 optvar optinit optsvar)
(if (consp (cdr item))
(if (null (cddr item))
(push3 (car item) (cadr item) 0
optvar optinit optsvar)
(if (singleton-symbol-p (cddr item))
(push3 (car item) (cadr item) (caddr item)
optvar optinit optsvar)
(err-invalid item)))
(err-invalid item)))
(err-invalid item))))))
(process-allow-other-keys (L allow-other-keys permissible)
`(when (and (consp ,L) (eq (car ,L) '&allow-other-keys))
(setq ,allow-other-keys t)
(setq ,L (cdr ,L))
(skip-L &allow-other-keys ,permissible)))
(process-keywords (L keyflag keyword keyvar keyinit keysvar
allow-other-keys permissible)
`(when (and (consp ,L) (eq (car ,L) '&key))
(setq ,L (cdr ,L))
(setq ,keyflag t)
(dolist (item ,L)
(if (symbolp item)
(if (memq item lambda-list-keywords)
(check-item item ,permissible)
(progn
(push (symbol-to-keyword item) ,keyword)
(push3 item nil 0 ,keyvar ,keyinit ,keysvar)))
(if (and (consp item)
(symbol-or-pair-p (car item))
(or (null (cdr item))
(and (consp (cdr item))
(or (null (cddr item))
(singleton-symbol-p (cddr item))))))
(progn
(if (consp (car item))
(progn
(push (caar item) ,keyword)
(push (cadar item) ,keyvar))
(progn
(push (symbol-to-keyword (car item)) ,keyword)
(push (car item) ,keyvar)))
(if (consp (cdr item))
(progn
(push (cadr item) ,keyinit)
(if (consp (cddr item))
(push (caddr item) ,keysvar)
(push 0 ,keysvar)))
(progn (push nil ,keyinit) (push 0 ,keysvar))))
(err-invalid item))))
;; Now (or (atom L) (member (car L) permissible)).
(process-allow-other-keys ,L ,allow-other-keys
,(cdr permissible))))
(skip-L (lastseen items)
`(dolist (item L)
(if (memq item lambda-list-keywords)
(check-item item ,items)
(funcall errfunc lambdalist item
,(case lastseen
((&REST &ENVIRONMENT) '(TEXT "Lambda list element ~S is superfluous. Only one variable is allowed after ~S."))
(&ALLOW-OTHER-KEYS '(TEXT "Lambda list element ~S is superfluous. No variable is allowed right after ~S."))
(t '(TEXT "Lambda list element ~S (after ~S) is superfluous.")))
item ',lastseen)))))
;;; Analyzes a lambda-list of a function (CLtL2 p. 76, ANSI CL 3.4.1.).
;;; Reports errors through errfunc (a function taking form & detail objects,
;;; an error format string and format string arguments).
;; Returns 13 values:
;; 1. list of required parameters
;; 2. list of optional parameters
;; 3. list of init-forms of the optional parameters
;; 4. list of supplied-vars for the optional parameters (0 for the missing)
;; 5. &rest parameter or 0
;; 6. flag, if keywords are allowed
;; 7. list of keywords
;; 8. list of keyword parameters
;; 9. list of init-forms of the keyword parameters
;; 10. list of supplied-vars for the keyword parameters (0 for the missing)
;; 11. flag, if other keywords are allowed
;; 12. list of &aux variables
;; 13. list of init-forms of the &aux variables
(defun analyze-lambdalist (lambdalist errfunc)
(let ((L lambdalist) ; rest of the lambda-list
(reqvar nil)
(optvar nil)
(optinit nil)
(optsvar nil)
(rest 0)
(keyflag nil)
(keyword nil)
(keyvar nil)
(keyinit nil)
(keysvar nil)
(allow-other-keys nil)
(auxvar nil)
(auxinit nil))
;; The lists are all accumulated in reversed order.
;; Required parameters:
(process-required L reqvar (&optional &rest &key &aux))
;; Now (or (atom L) (member (car L) '(&optional &rest &key &aux))).
;; Optional parameters:
(process-optional L optvar optinit optsvar (&rest &key &aux))
;; Now (or (atom L) (member (car L) '(&rest &key &aux))).
;; &rest parameters:
(last-parameter L rest &rest (skip-L &rest (&key &aux)))
;; Now (or (atom L) (member (car L) '(&key &aux))).
;; Keyword & Allow-other-keys parameters:
(process-keywords L keyflag keyword keyvar keyinit keysvar
allow-other-keys (&allow-other-keys &aux))
;; Now (or (atom L) (member (car L) '(&aux))).
;; &aux variables:
(when (and (consp L) (eq (car L) '&aux))
(setq L (cdr L))
(dolist (item L)
(if (symbolp item)
(if (memq item lambda-list-keywords)
(err-misplaced item)
(progn (push item auxvar) (push nil auxinit)))
(if (and (consp item) (symbolp (car item)))
(if (null (cdr item))
(progn (push (car item) auxvar) (push nil auxinit))
(if (and (consp (cdr item)) (null (cddr item)))
(progn (push (car item) auxvar) (push (cadr item) auxinit))
(err-invalid item)))
(err-invalid item)))))
;; Now (atom L).
(check-exhausted L)
(values
(nreverse reqvar)
(nreverse optvar) (nreverse optinit) (nreverse optsvar)
rest
keyflag
(nreverse keyword) (nreverse keyvar) (nreverse keyinit) (nreverse keysvar)
allow-other-keys
(nreverse auxvar) (nreverse auxinit))))
;;; Analyzes a lambda-list of a generic function (ANSI CL 3.4.2.).
;;; Reports errors through errfunc (a function taking form & detail objects,
;;; an error format string and format string arguments).
;; Returns 7 values:
;; 1. list of required parameters
;; 2. list of optional parameters
;; 3. &rest parameter or 0
;; 4. flag, if keywords are allowed
;; 5. list of keywords
;; 6. list of keyword parameters
;; 7. flag, if other keywords are allowed
(defun analyze-generic-function-lambdalist (lambdalist errfunc)
(let ((L lambdalist) ; rest of the lambda-list
(reqvar nil)
(optvar nil)
(rest 0)
(keyflag nil)
(keyword nil)
(keyvar nil)
(allow-other-keys nil))
;; The lists are all accumulated in reversed order.
;; Required parameters:
;; Need to check for duplicates here because otherwise the
;; :arguments-precedence-order makes no sense.
(process-required L reqvar (&optional &rest &key) t)
;; Now (or (atom L) (member (car L) '(&optional &rest &key))).
;; Optional parameters:
(when (and (consp L) (eq (car L) '&optional))
(setq L (cdr L))
(dolist (item L)
(if (symbolp item)
(if (memq item lambda-list-keywords)
(check-item item (&rest &key))
(push item optvar))
(if (and (consp item) (symbolp (car item)))
(if (null (cdr item))
(push (car item) optvar)
(err-no-default &optional item))
(err-invalid item)))))
;; Now (or (atom L) (member (car L) '(&rest &key))).
;; &rest parameters:
(last-parameter L rest &rest (skip-L &rest (&key)))
;; Now (or (atom L) (member (car L) '(&key))).
;; Keyword parameters:
(when (and (consp L) (eq (car L) '&key))
(setq L (cdr L))
(setq keyflag t)
(dolist (item L)
(if (symbolp item)
(if (memq item lambda-list-keywords)
(check-item item (&allow-other-keys))
(progn
(push (symbol-to-keyword item) keyword)
(push item keyvar)))
(if (and (consp item)
(symbol-or-pair-p (car item)))
(if (null (cdr item))
(if (consp (car item))
(progn
(push (caar item) keyword)
(push (cadar item) keyvar))
(progn
(push (symbol-to-keyword (car item)) keyword)
(push (car item) keyvar)))
(err-no-default &key item))
(err-invalid item))))
;; Now (or (atom L) (member (car L) '(&allow-other-keys))).
(process-allow-other-keys L allow-other-keys ()))
;; Now (atom L).
(check-exhausted L)
(values
(nreverse reqvar)
(nreverse optvar)
rest
keyflag
(nreverse keyword) (nreverse keyvar)
allow-other-keys)))
;;; Analyzes a defsetf lambda-list (ANSI CL 3.4.7.).
;;; Reports errors through errfunc (a function taking form & detail objects,
;;; an error format string and format string arguments).
;; Returns 12 values:
;; 1. list of required parameters
;; 2. list of optional parameters
;; 3. list of init-forms of the optional parameters
;; 4. list of supplied-vars for the optional parameters (0 for the missing)
;; 5. &rest parameter or 0
;; 6. flag, if keywords are allowed
;; 7. list of keywords
;; 8. list of keyword parameters
;; 9. list of init-forms of the keyword parameters
;; 10. list of supplied-vars for the keyword parameters (0 for the missing)
;; 11. flag, if other keywords are allowed
;; 12. &environment parameter or 0
(defun analyze-defsetf-lambdalist (lambdalist errfunc)
(let ((L lambdalist) ; rest of the lambda-list
(reqvar nil)
(optvar nil)
(optinit nil)
(optsvar nil)
(rest 0)
(keyflag nil)
(keyword nil)
(keyvar nil)
(keyinit nil)
(keysvar nil)
(allow-other-keys nil)
(env 0))
;; The lists are all accumulated in reversed order.
;; Required parameters:
(process-required L reqvar (&optional &rest &key &environment))
;; Now (or (atom L) (member (car L) '(&optional &rest &key &environment))).
;; Optional parameters:
(process-optional L optvar optinit optsvar (&rest &key &environment))
;; Now (or (atom L) (member (car L) '(&rest &key &environment))).
;; &rest parameters:
(last-parameter L rest &rest (skip-L &rest (&key &environment)))
;; Now (or (atom L) (member (car L) '(&key &environment))).
;; Keyword & Allow-other-keys parameters:
(process-keywords L keyflag keyword keyvar keyinit keysvar
allow-other-keys (&allow-other-keys &environment))
;; Now (or (atom L) (member (car L) '(&environment))).
;; &environment parameter:
(last-parameter L env &environment (skip-L &environment ()))
;; Now (atom L).
(check-exhausted L)
(values
(nreverse reqvar)
(nreverse optvar) (nreverse optinit) (nreverse optsvar)
rest
keyflag
(nreverse keyword) (nreverse keyvar) (nreverse keyinit) (nreverse keysvar)
allow-other-keys
env)))
;;; Analyzes a define-modify-macro lambda-list (ANSI CL 3.4.9.).
;;; Reports errors through errfunc (a function taking form & detail objects,
;;; an error format string and format string arguments).
;; Returns 5 values:
;; 1. list of required parameters
;; 2. list of optional parameters
;; 3. list of init-forms of the optional parameters
;; 4. list of supplied-vars for the optional parameters (0 for the missing)
;; 5. &rest parameter or 0
(defun analyze-modify-macro-lambdalist (lambdalist errfunc)
(let ((L lambdalist) ; rest of the lambda-list
(reqvar nil)
(optvar nil)
(optinit nil)
(optsvar nil)
(rest 0))
;; The lists are all accumulated in reversed order.
;; Required parameters:
(process-required L reqvar (&optional &rest))
;; Now (or (atom L) (member (car L) '(&optional &rest))).
;; Optional parameters:
(process-optional L optvar optinit optsvar (&rest))
;; Now (or (atom L) (member (car L) '(&rest))).
;; &rest parameters:
(last-parameter L rest &rest (skip-L &rest ()))
;; Now (atom L).
(check-exhausted L)
(values
(nreverse reqvar)
(nreverse optvar) (nreverse optinit) (nreverse optsvar)
rest)))
;;; Analyzes a define-method-combination lambda-list (ANSI CL 3.4.10.).
;;; Reports errors through errfunc (a function taking form & detail objects,
;;; an error format string and format string arguments).
;; Returns 14 values:
;; 1. &whole parameter or 0
;; 2. list of required parameters
;; 3. list of optional parameters
;; 4. list of init-forms of the optional parameters
;; 5. list of supplied-vars for the optional parameters (0 for the missing)
;; 6. &rest parameter or 0
;; 7. flag, if keywords are allowed
;; 8. list of keywords
;; 9. list of keyword parameters
;; 10. list of init-forms of the keyword parameters
;; 11. list of supplied-vars for the keyword parameters (0 for the missing)
;; 12. flag, if other keywords are allowed
;; 13. list of &aux variables
;; 14. list of init-forms of the &aux variables
(defun analyze-method-combination-lambdalist (lambdalist errfunc)
(let ((L lambdalist) ; rest of the lambda-list
(whole 0))
;; The lists are all accumulated in reversed order.
;; &whole parameter:
(last-parameter L whole &whole)
;; The rest should be an ordinary lambda-list.
(multiple-value-bind (reqvar optvar optinit optsvar rest
keyflag keyword keyvar keyinit keysvar allow-other-keys
auxvar auxinit)
(analyze-lambdalist L errfunc)
(values
whole
reqvar
optvar optinit optsvar
rest
keyflag
keyword keyvar keyinit keysvar
allow-other-keys
auxvar auxinit))))
) ; macrolet
| 18,640 | Common Lisp | .lisp | 425 | 32.489412 | 143 | 0.547896 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | af529ea7b9fb7bd0bf92f0bf41b6fd277175ee4ab7341edb59b0fed29f9231fe | 11,370 | [
-1
] |
11,371 | reploop.lisp | ufasoft_lisp/clisp/reploop.lisp | ;;;; Debugger, Stepper, Errors
(in-package "EXT")
(export
'(custom::*prompt-start* custom::*prompt-step* custom::*prompt-break*
custom::*prompt-body* custom::*prompt-finish* custom::*user-commands*)
"CUSTOM")
(ext:re-export "CUSTOM" "EXT")
(export
'(*command-index* prompt-new-package
break-level step-level)
"EXT")
(in-package "SYSTEM")
;;;--------------------------------------------------------------------------
;;; Debugger
;; Number of active break-loops (Fixnum >=0)
(defvar *break-count* 0)
;; Defines how many frames will be displayed.
;; Initially nil, this means all frames will be printed.
(defvar *debug-print-frame-limit* nil)
;; Counter to avoid infinite recursion due to *error-output*
(defvar *recurse-count-error-output* 0)
;; Counter to avoid infinite recursion due to *debug-io*
(defvar *recurse-count-debug-io* 0)
; The number of commands received so far.
(defvar *command-index* 0)
;; The starting package of this session (used here and in SAVEINITMEM)
(defvar *home-package* nil)
;; Returns the current package or NIL if it never changed.
(defun prompt-new-package ()
(unless *home-package* (setq *home-package* *package*))
(unless (eq *home-package* *package*) *package*))
(defmacro prompt-to-string (variable)
`(typecase ,variable
(string ,variable)
(function
(multiple-value-bind (value error) (ignore-errors (funcall ,variable))
(if error
(string-concat ,(symbol-name variable) "->"
(symbol-name (type-of error)))
(if (stringp value) value
(princ-to-string value)))))
(t (princ-to-string ,variable))))
;; Prompt - first part:
(defvar *prompt-start* ""
"The initial part of the prompt, defaults to an empty string.")
(defun prompt-start () (prompt-to-string *prompt-start*))
(defun break-level () *break-count*)
(defvar *prompt-break*
(lambda () (string-concat "Break " (princ-to-string (break-level)) " "))
"The break level part of the prompt, may use `EXT:BREAK-LEVEL'.")
(defun prompt-break () (prompt-to-string *prompt-break*))
(defvar *prompt-body*
(lambda ()
;; prompt with *package* when it is different from the initial one
;; or when it doesn't contain standard LISP symbols, like T.
(if (and (packagep *package*) (package-name *package*))
(format nil "~@[~a~][~:d]"
(if (or (not (find-symbol "T" *package*))
(prompt-new-package))
;; use symbol so that ~A will respect *PRINT-CASE*
(make-symbol (package-shortest-name *package*)))
(incf *command-index*))
(TEXT "[*package* invalid]")))
"The main top level prompt.")
(defun prompt-body () (prompt-to-string *prompt-body*))
;; Prompt: last part
(defvar *prompt-finish* "> "
"The final part of the prompt")
(defun prompt-finish () (prompt-to-string *prompt-finish*))
;; http://sourceforge.net/tracker/index.php?func=detail&aid=1865636&group_id=1355&atid=101355
;; [ 1865636 ] infinite recursive error reporting
(defun safe-wr-st (string &optional (stream *standard-output*))
(handler-case (write-string string stream)
(system::charset-type-error ()
(format stream "Unprintable message: change ~S or ~S" '*current-language*
'*terminal-encoding*))))
;; Help-function:
(defvar *key-bindings* nil) ; list of key-bindings and help strings
(defun help ()
(dolist (s *key-bindings*)
(when (stringp s)
(safe-wr-st s #|*debug-io*|#))))
(defun show-local-symbols (argline)
(setq argline (trim-if #'whitespacep argline))
(let ((l '())
(package (if (equal argline "") *package*
(or (find-package argline)
argline)))) ; for error reporting
(do-symbols (s package)
(when (eq package (symbol-package s))
(push s l)))
(princ l)
(throw 'debug 'continue)))
(defvar *saved-debug-package* *common-lisp-user-package*)
(defvar *saved-debug-readtable* (copy-readtable nil))
(defun debug-reset-io (a)
(declare (ignore a))
(rotatef *package* *saved-debug-package*)
(rotatef *readtable* *saved-debug-readtable*)
(fresh-line *debug-io*)
(format *debug-io* (TEXT "Reset *PACKAGE* to ~s") *package*)
(throw 'debug 'continue))
;; Components of the Break-Loop:
(defvar *debug-frame*)
(defvar *stack-mode* 4)
; lower bound for frame-down
(defvar *frame-limit-down* nil)
; upper bound for frame-up
(defvar *frame-limit-up* nil)
(defun frame-limit-down (frames-to-skip)
(let ((frame (the-frame)))
(let ((*frame-limit-down* nil)
(*frame-limit-up* nil))
(dotimes (i frames-to-skip) (setq frame (frame-up 1 frame 1))))
frame))
(defun frame-limit-up ()
(let ((frame (the-frame)))
(let ((*frame-limit-down* nil)
(*frame-limit-up* nil))
(loop
(let ((nextframe (frame-up 1 frame 1)))
(when (or (eq nextframe frame) (driver-frame-p nextframe)) (return))
(setq frame nextframe)))
(dotimes (i 2) (setq frame (frame-down 1 frame 1))))
frame))
(defun debug-help (a) (declare (ignore a)) (help) (throw 'debug 'continue))
(defun debug-unwind (a) (declare (ignore a)) (throw 'debug 'unwind))
(defun debug-quit (a) (declare (ignore a)) (throw 'debug 'abort-to-top))
(defun stack-mode (argline &key (start 0) (end (length argline)))
(multiple-value-bind (mode pos)
(read-from-string argline nil *stack-mode* :start start :end end)
(check-type mode (integer 1 5))
(values mode pos)))
(defun debug-mode (argline)
(setq *stack-mode* (stack-mode argline)) (throw 'debug 'continue))
(defun debug-where (a)
(declare (ignore a))
(describe-frame *standard-output* *debug-frame*)
(throw 'debug 'continue))
(defun debug-up (a)
(declare (ignore a))
(describe-frame *standard-output*
(setq *debug-frame* (frame-up 1 *debug-frame* *stack-mode*)))
(throw 'debug 'continue))
(defun debug-top (a)
(declare (ignore a))
(describe-frame *standard-output*
(setq *debug-frame* (frame-up t *debug-frame* *stack-mode*)))
(throw 'debug 'continue))
(defun debug-down (a)
(declare (ignore a))
(describe-frame *standard-output*
(setq *debug-frame* (frame-down 1 *debug-frame*
*stack-mode*)))
(throw 'debug 'continue))
(defun debug-bottom (a)
(declare (ignore a))
(describe-frame *standard-output*
(setq *debug-frame* (frame-down t *debug-frame*
*stack-mode*)))
(throw 'debug 'continue))
(defun frame-limit (argline &key (start 0) (end (length argline)))
(multiple-value-bind (limit pos)
(read-from-string argline nil *debug-print-frame-limit*
:start start :end end)
(check-type limit (or null (eql :all) integer))
(values (if (eq limit :all) nil limit)
pos)))
;;; sets the limit for frames to print in a backtrace
(defun debug-frame-limit (argline)
(setq *debug-print-frame-limit* (frame-limit argline))
(throw 'debug 'continue))
(defun frame-up-down (limit mode) (frame-down 1 (frame-up 1 limit mode) mode))
(defun print-backtrace (&key ((:out *standard-output*) *standard-output*)
(mode *stack-mode*) (limit *debug-print-frame-limit*))
;; SHOW-STACK prints its output to *STANDARD-OUTPUT*, so we bind that
(let ((frame-count
(show-stack
mode limit
(frame-up-down (or *frame-limit-down* (frame-limit-down 13)) mode))))
(fresh-line *standard-output*)
(format *standard-output* (TEXT "Printed ~D frame~:P") frame-count)
(elastic-newline *standard-output*)))
;;; debug-backtrace with-optional 'print-limit'
(defun debug-backtrace (argline)
(multiple-value-bind (mode pos) (stack-mode argline)
(print-backtrace :out *debug-io* :mode mode
:limit (frame-limit argline :start pos)))
(throw 'debug 'continue))
(defun debug-trap-on (a)
(declare (ignore a))
(trap-eval-frame *debug-frame* t)
(throw 'debug 'continue))
(defun debug-trap-off (a)
(declare (ignore a))
(trap-eval-frame *debug-frame* nil)
(throw 'debug 'continue))
(defun debug-redo (a)
(declare (ignore a))
(redo-eval-frame *debug-frame*)
(throw 'debug 'continue))
(defun debug-return (argline)
(return-from-eval-frame *debug-frame* (read-from-string argline))
(throw 'debug 'continue))
(defun debug-continue (a) (declare (ignore a)) (throw 'debug 'quit))
;;; New command to print the error message again
(defun debug-print-error (a)
(declare (ignore a))
;; condition is local to break-loop so have to go back there
(throw 'debug 'print-error))
(defun debug-inspect-error (a)
(declare (ignore a))
(throw 'debug 'inspect-error))
;;; print it
(defun print-error (condition)
(fresh-line *debug-io*)
(safe-wr-st (TEXT "The last error:") *debug-io*)
(pretty-print-condition condition *debug-io* :text-indent 3)
(elastic-newline *debug-io*))
(defvar *user-commands* nil
"The list of functions, each of which should return a list of bindings.
A `binding' is either a doc string (printed by `Help' or `:h')
or a pair (STRING . FUNCTION) so that typing STRING will call FUNCTION.")
(defun wrap-user-commands (functions)
"wrap user commands in THROWs"
(mapcar (lambda (binding)
(etypecase binding
(string binding)
(cons (cons (car binding)
(lambda (argline)
(funcall (cdr binding) argline)
(throw 'debug 'continue))))))
(mapcap #'funcall functions)))
;; extended commands
(defun commands0 ()
(list*
(TEXT "You are in the top-level Read-Eval-Print loop.
Help (abbreviated :h) = this list
Use the usual editing capabilities.
\(quit) or (exit) leaves CLISP.")
(cons "Help" #'debug-help)
(cons ":h" #'debug-help)
(cons "?" #'debug-help)
(cons "LocalSymbols" #'show-local-symbols)
(cons ":ls" #'show-local-symbols)
(wrap-user-commands *user-commands*)))
(defun commands1 ()
(list
(TEXT "
Commands may be abbreviated as shown in the second column.
COMMAND ABBR DESCRIPTION
Help :h, ? print this command list
Error :e print the last error message
Inspect :i inspect the last error
Abort :a abort to the next recent input loop
Unwind :uw abort to the next recent input loop
Reset :re toggle *PACKAGE* and *READTABLE* between the
local bindings and the sane values
Quit :q quit to the top-level input loop
Where :w inspect this frame
Up :u go up one frame, inspect it
Top :t go to top frame, inspect it
Down :d go down one frame, inspect it
Bottom :b go to bottom (most recent) frame, inspect it
Mode mode :m set stack mode for Backtrace: 1=all the stack elements
2=all the frames 3=only lexical frames
4=only EVAL and APPLY frames (default) 5=only APPLY frames
Frame-limit n :fl set the frame-limit for Backtrace. This many frames
will be printed in a backtrace at most.
Backtrace [mode [limit]] :bt inspect the stack
Break+ :br+ set breakpoint in EVAL frame
Break- :br- disable breakpoint in EVAL frame
Redo :rd re-evaluate form in EVAL frame
Return value :rt leave EVAL frame, prescribing the return values")
(cons "Help" #'debug-help )
(cons ":h" #'debug-help )
(cons "?" #'debug-help )
(cons "LocalSymbols" #'show-local-symbols)
(cons ":ls" #'show-local-symbols)
(cons "Error" #'debug-print-error)
(cons ":e" #'debug-print-error)
(cons "Inspect" #'debug-inspect-error)
(cons ":i" #'debug-inspect-error)
(cons "Abort" #'debug-unwind)
(cons ":a" #'debug-unwind)
(cons "Unwind" #'debug-unwind)
(cons ":uw" #'debug-unwind)
(cons "Reset" #'debug-reset-io)
(cons ":re" #'debug-reset-io)
(cons "Quit" #'debug-quit)
(cons ":q" #'debug-quit)
(cons "Where" #'debug-where )
(cons ":w" #'debug-where )
(cons "Up" #'debug-up )
(cons ":u" #'debug-up )
(cons "Top" #'debug-top )
(cons ":t" #'debug-top )
(cons "Down" #'debug-down )
(cons ":d" #'debug-down )
(cons "Bottom" #'debug-bottom)
(cons ":b" #'debug-bottom)
(cons "Mode" #'debug-mode)
(cons ":m" #'debug-mode)
(cons "Frame-limit" #'debug-frame-limit)
(cons ":fl" #'debug-frame-limit)
(cons "Backtrace" #'debug-backtrace)
(cons ":bt" #'debug-backtrace)))
(defun commands2 ()
(list
(cons "Break+" #'debug-trap-on )
(cons ":br+" #'debug-trap-on )
(cons "Break-" #'debug-trap-off)
(cons ":br-" #'debug-trap-off)
(cons "Redo" #'debug-redo )
(cons ":rd" #'debug-redo )
(cons "Return" #'debug-return)
(cons ":rt" #'debug-return)))
(defun commands3 ()
(list
(TEXT "
Continue :c continue evaluation")
(cons "Continue" #'debug-continue)
(cons ":c" #'debug-continue)))
(defun commands4 ()
(list
(TEXT "
Step :s step into form: evaluate this form in single step mode
Next :n step over form: evaluate this form at once
Over :o step over this level: evaluate at once up to the next return
Continue :c switch off single step mode, continue evaluation
-- Step-until :su, Next-until :nu, Over-until :ou, Continue-until :cu --
same as above, specify a condition when to stop")
(cons "Step" #'(lambda (a) (declare (ignore a))
(throw 'stepper 'into)))
(cons ":s" #'(lambda (a) (declare (ignore a))
(throw 'stepper 'into)))
(cons "Next" #'(lambda (a) (declare (ignore a))
(throw 'stepper 'over)))
(cons ":n" #'(lambda (a) (declare (ignore a))
(throw 'stepper 'over)))
(cons "Over" #'(lambda (a) (declare (ignore a))
(throw 'stepper 'over-this-level)))
(cons ":o" #'(lambda (a) (declare (ignore a))
(throw 'stepper 'over-this-level)))
(cons "Continue" #'(lambda (a) (declare (ignore a))
(throw 'stepper 'continue)))
(cons ":c" #'(lambda (a) (declare (ignore a))
(throw 'stepper 'continue)))
(cons "Step-until" #'(lambda (a) (declare (ignore a))
(throw 'stepper (values 'into t))))
(cons ":su" #'(lambda (a) (declare (ignore a))
(throw 'stepper (values 'into t))))
(cons "Next-until" #'(lambda (a) (declare (ignore a))
(throw 'stepper (values 'over t))))
(cons ":nu" #'(lambda (a) (declare (ignore a))
(throw 'stepper (values 'over t))))
(cons "Over-until" #'(lambda (a) (declare (ignore a))
(throw 'stepper (values 'over-this-level t))))
(cons ":ou" #'(lambda (a) (declare (ignore a))
(throw 'stepper (values 'over-this-level t))))
(cons "Continue-until" #'(lambda (a) (declare (ignore a))
(throw 'stepper (values 'continue t))))
(cons ":cu" #'(lambda (a) (declare (ignore a))
(throw 'stepper (values 'continue t))))))
(defun commands (may-continue commandsr)
(nconc (commands1)
(when (eval-frame-p *debug-frame*)
(commands2))
(when may-continue
(commands3))
commandsr
(wrap-user-commands *user-commands*)))
;; establish the DEBUG catcher and the ABORT restart
(defmacro with-abort-restart ((&key report) &body body)
`(catch 'debug
(with-restarts ((ABORT () :report (lambda (s) (write-string ,report s))
(throw 'debug 'continue)))
,@body)))
;; Main-Loop with additional help-command
(defun main-loop (&optional (exit t))
(setq *break-count* 0)
(driver ; build driver-frame; do #'lambda "infinitely"
#'(lambda ()
(with-abort-restart (:report (TEXT "Abort main loop"))
;; ANSI CL wants an ABORT restart to be available.
(when (read-eval-print ; read-eval-print INPUT-line
(string-concat (prompt-start) (prompt-body) (prompt-finish))
(commands0))
;; T -> #<EOF>
;; NIL -> form is already evaluated
;; result has been printed
(if exit
;; if you want to change this logic, you need to make sure that
;; 1. "clisp -x (1+ 2) -repl" prints "3" and then the prompt
;; 2. "cat script | clisp" and "clisp < script" do not hang
(exit)
(progn (setq *command-index* 0) ; reset *command-index*
(handler-case (return-from main-loop)
(error () (exit 1))))))))))
(setq *driver* #'main-loop)
(defun break-loop (continuable &optional (condition nil) (print-it nil)
&aux
(may-continue
(or continuable
(and condition
(let ((restart
(find-restart 'CONTINUE condition)))
(and restart
;; Ignore the CONTINUE restart if it is not
;; useful without prior corrective action,
;; otherwise it leads to user frustration.
(restart-meaningfulp restart)
restart)))))
(interactive-p (interactive-stream-p *debug-io*))
(commandsr '()))
(when (and print-it (typep condition (clos:find-class 'condition)))
(symbol-stream '*error-output* :output)
;; print something on *error-output* but catch infinite recursion.
(let ((*recurse-count-error-output* (1+ *recurse-count-error-output*)))
(when (> *recurse-count-error-output* 3)
(setq *recurse-count-error-output* 0)
(makunbound '*error-output*)
(let ((*recurse-count-debug-io* (1+ *recurse-count-debug-io*)))
(when (> *recurse-count-debug-io* 3)
(setq *recurse-count-debug-io* 0)
(makunbound '*debug-io*)
(symbol-stream '*debug-io* :io))
(symbol-stream '*error-output* :output)))
(terpri *error-output*))
(if may-continue
(progn
(write-string "** - " *error-output*)
(safe-wr-st (TEXT "Continuable Error") *error-output*)
(terpri *error-output*))
(write-string "*** - " *error-output*))
;; Output the error message, but don't trap into recursive errors.
(let ((*recursive-error-count* (1+ *recursive-error-count*)))
(if (> *recursive-error-count* 3)
(progn
(setq *recursive-error-count* 0)
(write-string (TEXT "Unprintable error message")
*error-output*))
(pretty-print-condition condition *error-output*
:text-indent (if may-continue 5 6))))
;; Now the error message is on the screen; give the user some information
;; how to continue from continuable errors.
(symbol-stream '*debug-io* :io)
(when may-continue
(if continuable
(when interactive-p
(fresh-line *debug-io*)
(safe-wr-st (TEXT "You can continue (by typing 'continue').")
*debug-io*)
(elastic-newline *debug-io*))
(progn
(fresh-line *debug-io*)
(when interactive-p
(safe-wr-st (TEXT "If you continue (by typing 'continue'): ")
*debug-io*))
(princ may-continue *debug-io*)
(elastic-newline *debug-io*)))))
(when condition
(let ((restarts (remove may-continue (compute-restarts condition)))
(restarts-help (if may-continue
(TEXT "The following restarts are also available:")
(TEXT "The following restarts are available:"))))
(when restarts
(when interactive-p
(fresh-line *debug-io*)
(safe-wr-st restarts-help *debug-io*)
(elastic-newline *debug-io*))
(let ((counter 0))
(dolist (restart restarts)
(let* ((command
(string-concat ":R" (sys::decimal-string (incf counter))))
(name (string (restart-name restart)))
(helpstring (format nil "~A~15T~A~24T~A" name command
(princ-to-string restart)))
(restart restart) ; for FUNC
(func #'(lambda (a) (declare (ignore a))
(invoke-restart-interactively restart))))
;; display the restarts:
(when interactive-p
(fresh-line *debug-io*)
(safe-wr-st helpstring *debug-io*)
(elastic-newline *debug-io*))
(push (string-concat (string #\Newline) helpstring) commandsr)
;; put it into the commandsr list.
(push (cons command func) commandsr)
(push (cons name func) commandsr)))
(setq commandsr (cons (string-concat (string #\Newline) restarts-help)
(nreverse commandsr)))))))
(force-output *debug-io*)
(tagbody
(makunbound '*terminal-read-stream*)
(makunbound '*terminal-read-open-object*)
(clear-input *debug-io*) ; because the user did not expect a break loop
(let* ((*break-count* (1+ *break-count*))
(stream (make-synonym-stream '*debug-io*))
(*standard-input* stream)
(*standard-output* stream)
(prompt (string-concat (prompt-start) (prompt-break)
(prompt-body) (prompt-finish)))
(*frame-limit-down* (frame-limit-down 13))
(*frame-limit-up* (frame-limit-up))
(*stack-mode* *stack-mode*)
(*debug-frame* (frame-up-down *frame-limit-down* *stack-mode*))
(*saved-debug-package* *saved-debug-package*)
(*saved-debug-readtable* *saved-debug-readtable*)
(commands-list (commands may-continue commandsr)))
(driver
;; build driver frame and repeat #'lambda (infinitely; ...)
#'(lambda ()
(case (with-abort-restart (:report (TEXT "Abort debug loop"))
;; ANSI CL wants an ABORT restart to be available.
;; build environment *debug-frame*
;; which is valid/equal for/to *debug-frame*
(same-env-as *debug-frame*
#'(lambda ()
(if (read-eval-print prompt commands-list)
;; T -> #<EOF>
;; NIL -> form is already evaluated;
;; result has been printed
(throw 'debug (if may-continue 'quit 'unwind))))))
((print-error) (print-error condition))
((inspect-error) (inspect condition))
((unwind) (go unwind))
((abort-to-top) (go abort-to-top))
((quit) ; reached only if may-continue is T
(if continuable
(go quit)
(invoke-restart-interactively may-continue)))
(t ))))) ; other cases, especially continue
unwind (unwind-to-driver nil)
abort-to-top (unwind-to-driver t)
quit))
(setq *break-driver* #'break-loop)
;;;--------------------------------------------------------------------------
;;; convenient Stepper. (runs only if compiled!)
(defvar *step-level* 0 "current Step-depth") ; ABI
(defvar *step-quit* most-positive-fixnum "critical Step-depth") ; ABI
;; the stepper wakes up, as soon as *step-level* <= *step-quit*
(defvar *step-watch* nil) ; terminating condition ; ABI
(defmacro step (form)
"(STEP form), CLTL p. 441"
`(let* ((*step-level* 0)
(*step-quit* most-positive-fixnum)
(*step-watch* nil)
(*evalhook* #'step-hook-fn))
,form))
(defun step-values (values)
(let ((*standard-output* *debug-io*))
(fresh-line #|*debug-io*|#)
(safe-wr-st (TEXT "step ") #|*debug-io*|#)
(write *step-level* #|:stream *debug-io*|#)
(write-string " ==> " #|*debug-io*|#)
(case (length values)
(0 (safe-wr-st (TEXT "no values") #|*debug-io*|#))
(1 (safe-wr-st (TEXT "value: ") #|*debug-io*|#)
(write (car values) #|:stream *debug-io*|#))
(t (write (length values) #|:stream *debug-io*|#)
(safe-wr-st (TEXT " values: ") #|*debug-io*|#)
(do ((L values))
((endp L))
(write (pop L) #|:stream *debug-io*|#)
(unless (endp L) (write-string ", " #|*debug-io*|#)))))
(elastic-newline #|*debug-io*|#))
(values-list values))
(defun step-level () *step-level*)
(defvar *prompt-step*
(lambda () (string-concat "Step " (princ-to-string (step-level)) " "))
"The stepper part of the prompt, may use `EXT:STEP-LEVEL'." )
(defun prompt-step () (prompt-to-string *prompt-step*))
(defun step-hook-fn (form &optional (env *toplevel-environment*))
(let ((*step-level* (1+ *step-level*)))
(when (>= *step-level* *step-quit*) ; while *step-level* >= *step-quit*
(if (and *step-watch* (funcall *step-watch*)) ; and no Breakpoint,
(setq *step-quit* most-positive-fixnum)
(return-from step-hook-fn ; the Stepper remains passive
(evalhook form nil nil env)))) ; (e.g. it simply evaluates the Form)
(tagbody
(let* ((stream (make-synonym-stream '*debug-io*))
(*standard-input* stream)
(*standard-output* stream)
(prompt (string-concat (prompt-start) (prompt-step)
(prompt-body) (prompt-finish)))
(*frame-limit-down* (frame-limit-down 11))
(*frame-limit-up* (frame-limit-up))
(*stack-mode* *stack-mode*)
(*debug-frame* (frame-up-down *frame-limit-down* *stack-mode*))
(commands-list (commands nil (commands4))))
(fresh-line #|*debug-io*|#)
(safe-wr-st (TEXT "step ") #|*debug-io*|#)
(write *step-level* #|:stream *debug-io*|#)
(write-string " --> " #|*debug-io*|#)
(write form #|:stream *debug-io*|# :length 4 :level 3)
(loop
(multiple-value-bind (what watchp)
(catch 'stepper
;; catch the (throw 'stepper ...) and analyse ...
(driver
;; build driver frame and repeat #'lambda (infinitely ...)
#'(lambda ()
;; catch the (throw 'debug ...) and analyse
(case (with-abort-restart (:report (TEXT "Abort stepper"))
;; ANSI CL wants an ABORT restart to be available.
(same-env-as *debug-frame*
;; build environment *debug-frame* that
;; is valid/equal for/to *debug-frame*
#'(lambda ()
(if (read-eval-print prompt commands-list)
;; T -> #<EOF>
(go continue)
;; NIL -> form is already evaluated;
;; result has been printed
#|(throw 'debug 'continue)|#
))))
((unwind) (go unwind))
((abort-to-top) (go abort-to-top))
(t ))))) ; other cases, especially continue
(when watchp
(let ((form (read-form (TEXT "condition when to stop: "))))
(setq *step-watch*
;; function which evaluates 'form' in/with *debug-frame*
(eval-at *debug-frame* `(function (lambda () ,form))))))
(case what
(into (go into))
(over (go over))
(over-this-level (go over-this-level))
(continue (go continue))))))
unwind (unwind-to-driver nil)
abort-to-top (unwind-to-driver t)
into
(return-from step-hook-fn
(step-values
(multiple-value-list (evalhook form #'step-hook-fn nil env))))
over-this-level
(setq *step-quit* *step-level*) ; keep the Stepper sleeping
over
(return-from step-hook-fn
(step-values
(multiple-value-list (evalhook form nil nil env))))
continue
(setq *step-quit* 0)
(go over))))
;;;--------------------------------------------------------------------------
;; Now that condition.lisp is loaded and *break-driver* has a value:
;; Activate the Condition System.
(setq *use-clcs* t)
| 29,854 | Common Lisp | .lisp | 649 | 36.676425 | 93 | 0.553733 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 61e28a068c8281bae382342fb2ded667468f8a13a2aabd7a197430a6e30d2a2c | 11,371 | [
-1
] |
11,372 | clos-slotdef1.lisp | ufasoft_lisp/clisp/clos-slotdef1.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Slot Definition metaobjects
;;;; Part 1: Class definitions, preliminary accessors, utility functions.
;;;; Bruno Haible 2004-04-18
(in-package "CLOS")
;;; ===========================================================================
;;; The parts of a slot-definition that can be inherited to subclasses, in
;;; such a way that a modification of these values in a superclass can be
;;; adopted by the subclasses without any notification.
;;; We are allowed to do this trick because the functions
;;; (setf slot-definition-initform)
;;; (setf slot-definition-initfunction)
;;; (setf slot-definition-documentation)
;;; are not part of the MOP, i.e. the user is not allowed to modify a
;;; slot-definition after it has been created and initialized.
(defvar *<inheritable-slot-definition-initer>-defclass*
'(defclass inheritable-slot-definition-initer ()
((initform :type t :initarg :initform)
(initfunction :type (or null function) :initarg :initfunction))
(:metaclass structure-class)
; (:type cons)
)
)
(defvar *<inheritable-slot-definition-doc>-defclass*
'(defclass inheritable-slot-definition-doc ()
((documentation :type (or null string) :initarg :documentation))
(:metaclass structure-class)
; (:type cons)
)
)
(defmacro inheritable-slot-definition-initform (inheritable)
`(car ,inheritable))
(defmacro inheritable-slot-definition-initfunction (inheritable)
`(cdr ,inheritable))
(defun make-inheritable-slot-definition-initer (initform initfunction)
(cons initform initfunction))
(defmacro inheritable-slot-definition-documentation (inheritable)
`(car ,inheritable))
(defun make-inheritable-slot-definition-doc (documentation)
(list documentation))
;;; ===========================================================================
;;; The slot-definition abstract class.
;; Note that the C code can use constant offsets to access the components
;; of <slot-definition> and its subclasses, because
;; 1) The user is not allowed to override methods of the slot-definition-xxx
;; accessors. (MOP p. 10, 85-86)
;; 2) The user is not allowed to use multiple inheritance between different
;; categories of metaobjects (MOP p. 3) This allows us to use the
;; :fixed-slot-locations class option.
;; If this were not possible, we would have to wrap every
;; effective-slot-definition instance in a simple-vector that caches its
;; components. (This is possible because the (setf slot-definition-xxx)
;; functions are not part of the MOP.)
;; Information about a slot, as specified in a DEFCLASS form and kept
;; at runtime.
(defvar *<slot-definition>-defclass*
'(defclass slot-definition (metaobject)
(($name :type symbol :initarg :name)
($initargs :type list :initarg :initargs)
($type :type t :initarg :type)
($allocation :type symbol :initarg :allocation)
($inheritable-initer :type #| inheritable-slot-definition-initer |# cons
:initarg inheritable-initer)
($inheritable-doc :type #| inheritable-slot-definition-doc |# cons
:initarg inheritable-doc))
(:fixed-slot-locations t)))
;; Information about a slot, as specified in a DEFCLASS form.
(defvar <direct-slot-definition> 'direct-slot-definition)
(defvar *<direct-slot-definition>-defclass*
'(defclass direct-slot-definition (slot-definition)
(($readers :type list :initarg :readers)
($writers :type list :initarg :writers))
(:fixed-slot-locations t)))
;; Information about a slot that is still significant at runtime.
(defvar <effective-slot-definition> 'effective-slot-definition)
(defvar *<effective-slot-definition>-defclass*
'(defclass effective-slot-definition (slot-definition)
(($location :type (or null integer cons)
:initarg location)
; effective method for slot-value-using-class
($efm-svuc :type function)
; effective method for (setf slot-value-using-class)
($efm-ssvuc :type function)
; effective method for slot-boundp-using-class
($efm-sbuc :type function)
; effective method for slot-makunbound-using-class
($efm-smuc :type function))
(:fixed-slot-locations t)))
;; Fixed slot locations.
(defconstant *<slot-definition>-name-location* 1)
(defconstant *<slot-definition>-initargs-location* 2)
(defconstant *<slot-definition>-type-location* 3)
(defconstant *<slot-definition>-allocation-location* 4)
(defconstant *<slot-definition>-inheritable-initer-location* 5)
(defconstant *<slot-definition>-inheritable-doc-location* 6)
(defconstant *<direct-slot-definition>-readers-location* 7)
(defconstant *<direct-slot-definition>-writers-location* 8)
(defconstant *<effective-slot-definition>-location-location* 7)
(defconstant *<effective-slot-definition>-efm-svuc-location* 8)
(defconstant *<effective-slot-definition>-efm-ssvuc-location* 9)
(defconstant *<effective-slot-definition>-efm-sbuc-location* 10)
(defconstant *<effective-slot-definition>-efm-smuc-location* 11)
;; Preliminary accessors.
(predefun slot-definition-name (object)
(sys::%record-ref object *<slot-definition>-name-location*))
(predefun (setf slot-definition-name) (new-value object)
(setf (sys::%record-ref object *<slot-definition>-name-location*) new-value))
(predefun slot-definition-inheritable-initer (object)
(sys::%record-ref object *<slot-definition>-inheritable-initer-location*))
(predefun (setf slot-definition-inheritable-initer) (new-value object)
(setf (sys::%record-ref object *<slot-definition>-inheritable-initer-location*) new-value))
(predefun slot-definition-initform (object)
(inheritable-slot-definition-initform (sys::%record-ref object *<slot-definition>-inheritable-initer-location*)))
(predefun (setf slot-definition-initform) (new-value object)
(setf (inheritable-slot-definition-initform (sys::%record-ref object *<slot-definition>-inheritable-initer-location*)) new-value))
(predefun slot-definition-initfunction (object)
(inheritable-slot-definition-initfunction (sys::%record-ref object *<slot-definition>-inheritable-initer-location*)))
(predefun (setf slot-definition-initfunction) (new-value object)
(setf (inheritable-slot-definition-initfunction (sys::%record-ref object *<slot-definition>-inheritable-initer-location*)) new-value))
(predefun slot-definition-initargs (object)
(sys::%record-ref object *<slot-definition>-initargs-location*))
(predefun (setf slot-definition-initargs) (new-value object)
(setf (sys::%record-ref object *<slot-definition>-initargs-location*) new-value))
(predefun slot-definition-type (object)
(sys::%record-ref object *<slot-definition>-type-location*))
(predefun (setf slot-definition-type) (new-value object)
(setf (sys::%record-ref object *<slot-definition>-type-location*) new-value))
(predefun slot-definition-allocation (object)
(sys::%record-ref object *<slot-definition>-allocation-location*))
(predefun (setf slot-definition-allocation) (new-value object)
(setf (sys::%record-ref object *<slot-definition>-allocation-location*) new-value))
(predefun slot-definition-inheritable-doc (object)
(sys::%record-ref object *<slot-definition>-inheritable-doc-location*))
(predefun (setf slot-definition-inheritable-doc) (new-value object)
(setf (sys::%record-ref object *<slot-definition>-inheritable-doc-location*) new-value))
(predefun slot-definition-documentation (object)
(inheritable-slot-definition-documentation (sys::%record-ref object *<slot-definition>-inheritable-doc-location*)))
(predefun (setf slot-definition-documentation) (new-value object)
(setf (inheritable-slot-definition-documentation (sys::%record-ref object *<slot-definition>-inheritable-doc-location*)) new-value))
(predefun slot-definition-readers (object)
(sys::%record-ref object *<direct-slot-definition>-readers-location*))
(predefun (setf slot-definition-readers) (new-value object)
(setf (sys::%record-ref object *<direct-slot-definition>-readers-location*) new-value))
(predefun slot-definition-writers (object)
(sys::%record-ref object *<direct-slot-definition>-writers-location*))
(predefun (setf slot-definition-writers) (new-value object)
(setf (sys::%record-ref object *<direct-slot-definition>-writers-location*) new-value))
(predefun slot-definition-location (object)
(sys::%record-ref object *<effective-slot-definition>-location-location*))
(predefun (setf slot-definition-location) (new-value object)
(setf (sys::%record-ref object *<effective-slot-definition>-location-location*) new-value))
(predefun slot-definition-efm-svuc (object)
(sys::%record-ref object *<effective-slot-definition>-efm-svuc-location*))
(predefun (setf slot-definition-efm-svuc) (new-value object)
(setf (sys::%record-ref object *<effective-slot-definition>-efm-svuc-location*) new-value))
(predefun slot-definition-efm-ssvuc (object)
(sys::%record-ref object *<effective-slot-definition>-efm-ssvuc-location*))
(predefun (setf slot-definition-efm-ssvuc) (new-value object)
(setf (sys::%record-ref object *<effective-slot-definition>-efm-ssvuc-location*) new-value))
(predefun slot-definition-efm-sbuc (object)
(sys::%record-ref object *<effective-slot-definition>-efm-sbuc-location*))
(predefun (setf slot-definition-efm-sbuc) (new-value object)
(setf (sys::%record-ref object *<effective-slot-definition>-efm-sbuc-location*) new-value))
(predefun slot-definition-efm-smuc (object)
(sys::%record-ref object *<effective-slot-definition>-efm-smuc-location*))
(predefun (setf slot-definition-efm-smuc) (new-value object)
(setf (sys::%record-ref object *<effective-slot-definition>-efm-smuc-location*) new-value))
;; Initialization of a <slot-definition> instance.
(defun initialize-instance-<slot-definition> (slotdef &rest args
&key (name nil name-p)
(initform nil initform-p)
(initfunction nil initfunction-p)
(initargs '())
(type 'T)
(allocation ':instance)
(documentation nil)
((inheritable-initer inheritable-initer) nil)
((inheritable-doc inheritable-doc) nil)
&allow-other-keys)
(when *classes-finished*
(apply #'%initialize-instance slotdef args)) ; == (call-next-method)
(unless name-p
(error (TEXT "(~S ~S): The slot name is not specified.")
'initialize-instance 'slot-definition))
(unless (symbolp name)
(error (TEXT "(~S ~S): The slot name should be a symbol, not ~S")
'initialize-instance 'slot-definition name))
(unless (eq initform-p initfunction-p)
(error (TEXT "(~S ~S) for slot ~S: The ~S and ~S arguments can only be specified together.")
'initialize-instance 'slot-definition name ':initform ':initfunction))
(when initfunction-p
(when initfunction ; FIXME: defstruct.lisp passes :initfunction nil
(unless (functionp initfunction)
(error (TEXT "(~S ~S) for slot ~S: The ~S argument should be a function, not ~S")
'initialize-instance 'slot-definition name ':initfunction initfunction))))
(unless (symbolp allocation)
(error (TEXT "(~S ~S) for slot ~S: The ~S argument should be a symbol, not ~S")
'initialize-instance 'slot-definition name ':allocation allocation))
(unless (and (proper-list-p initargs) (every #'symbolp initargs))
(error (TEXT "(~S ~S) for slot ~S: The ~S argument should be a proper list of symbols, not ~S")
'initialize-instance 'slot-definition name ':initargs initargs))
(unless (or (null documentation) (stringp documentation))
(error (TEXT "(~S ~S) for slot ~S: The ~S argument should be a string or NIL, not ~S")
'initialize-instance 'slot-definition name :documentation documentation))
(unless inheritable-initer
(setq inheritable-initer
(make-inheritable-slot-definition-initer initform initfunction)))
(unless inheritable-doc
(setq inheritable-doc
(make-inheritable-slot-definition-doc documentation)))
(setf (slot-definition-name slotdef) name)
(setf (slot-definition-initargs slotdef) initargs)
(setf (slot-definition-type slotdef) type)
(setf (slot-definition-allocation slotdef) allocation)
(setf (slot-definition-inheritable-initer slotdef) inheritable-initer)
(setf (slot-definition-inheritable-doc slotdef) inheritable-doc)
slotdef)
;; Initialization of a <direct-slot-definition> instance.
(defun initialize-instance-<direct-slot-definition> (slotdef &rest args
&key (readers '())
(writers '())
((defclass-form defclass-form))
&allow-other-keys)
(declare (ignore defclass-form))
(apply #'initialize-instance-<slot-definition> slotdef args)
(unless (and (proper-list-p readers) (every #'sys::function-name-p readers))
(error (TEXT "(~S ~S) for slot ~S: The ~S argument should be a proper list of function names, not ~S")
'initialize-instance 'slot-definition (slot-definition-name slotdef) ':readers readers))
(unless (and (proper-list-p writers) (every #'sys::function-name-p writers))
(error (TEXT "(~S ~S) for slot ~S: The ~S argument should be a proper list of function names, not ~S")
'initialize-instance 'slot-definition (slot-definition-name slotdef) ':writers writers))
(setf (slot-definition-readers slotdef) readers)
(setf (slot-definition-writers slotdef) writers)
slotdef)
;; Initialization of a <effective-slot-definition> instance.
(defun initialize-instance-<effective-slot-definition> (slotdef &rest args
&key ((location location) nil)
&allow-other-keys)
(apply #'initialize-instance-<slot-definition> slotdef args)
(setf (slot-definition-location slotdef) location)
slotdef)
;;; ===========================================================================
;;; Now the concrete classes for <standard-class> and <structure-class> slots.
;;; ---------------------------------------------------------------------------
;; Common superclass of <standard-direct-slot-definition> and
;; <standard-effective-slot-definition>. Not used otherwise.
(defvar *<standard-slot-definition>-defclass*
'(defclass standard-slot-definition (slot-definition)
()
(:fixed-slot-locations t)))
;;; ---------------------------------------------------------------------------
;; Information about a slot of <standard-class> in DEFCLASS.
(defvar <standard-direct-slot-definition> 'standard-direct-slot-definition)
(defvar *<standard-direct-slot-definition>-defclass*
'(defclass standard-direct-slot-definition (direct-slot-definition standard-slot-definition)
()
(:fixed-slot-locations t)))
(defvar *<standard-direct-slot-definition>-class-version* (make-class-version))
;; Initialization of a <standard-direct-slot-definition> instance.
(defun initialize-instance-<standard-direct-slot-definition> (slotdef &rest args
&key
&allow-other-keys)
(apply #'initialize-instance-<direct-slot-definition> slotdef args)
slotdef)
(defun make-instance-<standard-direct-slot-definition> (class &rest args
&key &allow-other-keys)
;; class = <standard-direct-slot-definition>
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'make-instance later.
(declare (ignore class))
(let ((slotdef (allocate-metaobject-instance *<standard-direct-slot-definition>-class-version* 9)))
(apply #'initialize-instance-<standard-direct-slot-definition> slotdef args)))
;;; ---------------------------------------------------------------------------
;; Information about a slot of <standard-class> at runtime.
(defvar <standard-effective-slot-definition> 'standard-effective-slot-definition)
(defvar *<standard-effective-slot-definition>-defclass*
'(defclass standard-effective-slot-definition (effective-slot-definition standard-slot-definition)
()
(:fixed-slot-locations t)))
(defvar *<standard-effective-slot-definition>-class-version* (make-class-version))
;; Initialization of a <standard-effective-slot-definition> instance.
(defun initialize-instance-<standard-effective-slot-definition> (slotdef &rest args
&key
&allow-other-keys)
(apply #'initialize-instance-<effective-slot-definition> slotdef args)
slotdef)
(defun make-instance-<standard-effective-slot-definition> (class &rest args
&key &allow-other-keys)
;; class = <standard-effective-slot-definition>
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'make-instance later.
(declare (ignore class))
(let ((slotdef (allocate-metaobject-instance *<standard-effective-slot-definition>-class-version* 12)))
(apply #'initialize-instance-<standard-effective-slot-definition> slotdef args)))
;;; ---------------------------------------------------------------------------
;; Information about a slot of <structure-class> in DEFCLASS.
(defvar <structure-direct-slot-definition> 'structure-direct-slot-definition)
(defvar *<structure-direct-slot-definition>-defclass*
'(defclass structure-direct-slot-definition (direct-slot-definition)
()
(:fixed-slot-locations t)))
(defvar *<structure-direct-slot-definition>-class-version* (make-class-version))
;; Initialization of a <structure-direct-slot-definition> instance.
(defun initialize-instance-<structure-direct-slot-definition> (slotdef &rest args
&key &allow-other-keys)
(apply #'initialize-instance-<direct-slot-definition> slotdef args)
slotdef)
; ABI
(defun make-instance-<structure-direct-slot-definition> (class &rest args
&key &allow-other-keys)
;; class = <structure-direct-slot-definition>
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'make-instance later.
(declare (ignore class))
(let ((slotdef (allocate-metaobject-instance *<structure-direct-slot-definition>-class-version* 9)))
(apply #'initialize-instance-<structure-direct-slot-definition> slotdef args)))
;;; ---------------------------------------------------------------------------
;; Information about a slot of <structure-class> at runtime.
(defvar <structure-effective-slot-definition> 'structure-effective-slot-definition)
(defvar *<structure-effective-slot-definition>-defclass*
'(defclass structure-effective-slot-definition (effective-slot-definition)
(; Inherited slots with different initform.
($efm-svuc :type function :initform #'%slot-value-using-class)
($efm-ssvuc :type function :initform #'%set-slot-value-using-class)
($efm-sbuc :type function :initform #'%slot-boundp-using-class)
($efm-smuc :type function :initform #'%slot-makunbound-using-class)
; New slots:
($readonly :type boolean :initarg readonly))
(:fixed-slot-locations t)))
(defvar *<structure-effective-slot-definition>-class-version* (make-class-version))
(predefun structure-effective-slot-definition-readonly (object)
(sys::%record-ref object 12))
(predefun (setf structure-effective-slot-definition-readonly) (new-value object)
(setf (sys::%record-ref object 12) new-value))
;; Initialization of a <structure-effective-slot-definition> instance.
(defun initialize-instance-<structure-effective-slot-definition> (slotdef &rest args
&key ((readonly readonly) nil)
&allow-other-keys)
(apply #'initialize-instance-<effective-slot-definition> slotdef args)
(setf (slot-definition-efm-svuc slotdef) #'%slot-value-using-class)
(setf (slot-definition-efm-ssvuc slotdef) #'%set-slot-value-using-class)
(setf (slot-definition-efm-sbuc slotdef) #'%slot-boundp-using-class)
(setf (slot-definition-efm-smuc slotdef) #'%slot-makunbound-using-class)
(setf (structure-effective-slot-definition-readonly slotdef) readonly)
slotdef)
; ABI
(defun make-instance-<structure-effective-slot-definition> (class &rest args
&key &allow-other-keys)
;; class = <structure-effective-slot-definition>
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'make-instance later.
(declare (ignore class))
(let ((slotdef (allocate-metaobject-instance *<structure-effective-slot-definition>-class-version* 13)))
(apply #'initialize-instance-<structure-effective-slot-definition> slotdef args)))
;;; ===========================================================================
(defun print-object-<slot-definition> (slotdef stream)
(print-unreadable-object (slotdef stream :type t :identity t)
(write (slot-definition-name slotdef) :stream stream)))
;; Preliminary.
(predefun compute-direct-slot-definition-initargs (class &rest slot-spec)
(declare (ignore class))
slot-spec)
;; Preliminary.
(predefun direct-slot-definition-class (class &rest initargs)
(declare (ignore class initargs))
'standard-direct-slot-definition)
;; Converts a list of direct slot specifications (plists) to a list of
;; direct-slot-definition instances.
(defun convert-direct-slots (class direct-slots)
(mapcar #'(lambda (slot-spec)
(let ((slot-initargs
(apply #'compute-direct-slot-definition-initargs class slot-spec)))
(unless (and (listp slot-initargs) (evenp (length slot-initargs)))
(error (TEXT "Wrong ~S result for class ~S: not a property list: ~S")
'compute-direct-slot-definition-initargs (class-name class) slot-initargs))
(unless (eq (getf slot-initargs ':NAME) (getf slot-spec ':NAME))
(error (TEXT "Wrong ~S result for class ~S, slot ~S: value of ~S is wrong: ~S")
'compute-direct-slot-definition-initargs (class-name class)
(getf slot-spec ':NAME) ':NAME slot-initargs))
(let ((slot-definition-class
(apply #'direct-slot-definition-class class slot-initargs)))
(cond ((semi-standard-class-p class)
(unless (or ; for bootstrapping
(eq slot-definition-class 'standard-direct-slot-definition)
(and (defined-class-p slot-definition-class)
(subclassp slot-definition-class <standard-direct-slot-definition>)))
(error (TEXT "Wrong ~S result for class ~S: not a subclass of ~S: ~S")
'direct-slot-definition-class (class-name class)
'standard-direct-slot-definition slot-definition-class)))
((structure-class-p class)
(unless (and (defined-class-p slot-definition-class)
(subclassp slot-definition-class <structure-direct-slot-definition>))
(error (TEXT "Wrong ~S result for class ~S: not a subclass of ~S: ~S")
'direct-slot-definition-class (class-name class)
'structure-direct-slot-definition slot-definition-class))))
(let ((defclass-form (getf slot-spec 'DEFCLASS-FORM)))
(when defclass-form
;; Provide good error messages. The error message from
;; MAKE-INSTANCE later is unintelligible.
(let ((valid-keywords
(class-valid-initialization-keywords slot-definition-class)))
(unless (eq valid-keywords 'T)
;; The valid-keywords contain at least
;; :NAME :READERS :WRITERS :ALLOCATION :INITARGS
;; :INITFORM :INITFUNCTION :TYPE :DOCUMENTATION DEFCLASS-FORM.
(do ((specr slot-spec (cddr specr)))
((endp specr))
(let ((optionkey (car specr)))
(unless (member optionkey valid-keywords)
(error-of-type 'ext:source-program-error
:form defclass-form
:detail optionkey
(TEXT "~S ~S, slot option for slot ~S: ~S is not a valid slot option")
'defclass (second defclass-form) (getf slot-spec ':NAME) optionkey))))))))
(apply (cond ((eq slot-definition-class 'standard-direct-slot-definition)
#'make-instance-<standard-direct-slot-definition>)
(t #'make-instance))
slot-definition-class slot-initargs))))
direct-slots))
;; Test two direct slots for equality, except for the inheritable slots,
;; where only the presence is compared.
;; Preliminary.
(predefun equal-direct-slot (slot1 slot2)
(and (eq (class-of slot1) (class-of slot2))
(eq (slot-definition-name slot1) (slot-definition-name slot2))
(equal (slot-definition-initargs slot1) (slot-definition-initargs slot2))
(equal (slot-definition-type slot1) (slot-definition-type slot2))
(equal (slot-definition-allocation slot1) (slot-definition-allocation slot2))
(eq (null (slot-definition-initfunction slot1)) (null (slot-definition-initfunction slot2)))
(eq (null (slot-definition-documentation slot1)) (null (slot-definition-documentation slot2)))
(equal (slot-definition-readers slot1) (slot-definition-readers slot2))
(equal (slot-definition-writers slot1) (slot-definition-writers slot2))))
;; Type test.
(defun direct-slot-definition-p (object)
(and (std-instance-p object)
(let ((cv (sys::%record-ref object 0)))
; Treat the most frequent case first, for speed and bootstrapping.
(cond ((eq cv *<standard-direct-slot-definition>-class-version*) t)
(t ; Now a slow, but general instanceof test.
(gethash <direct-slot-definition>
(class-all-superclasses (class-of object))))))))
;; Preliminary.
(predefun effective-slot-definition-class (class &rest initargs)
(declare (ignore class initargs))
'standard-effective-slot-definition)
;; Type test.
(defun effective-slot-definition-p (object)
(and (std-instance-p object)
(let ((cv (sys::%record-ref object 0)))
; Treat the most frequent case first, for speed and bootstrapping.
(cond ((eq cv *<standard-effective-slot-definition>-class-version*) t)
(t ; Now a slow, but general instanceof test.
(gethash <effective-slot-definition>
(class-all-superclasses (class-of object))))))))
;; Type test.
(defun standard-effective-slot-definition-p (object)
(and (std-instance-p object)
(let ((cv (sys::%record-ref object 0)))
; Treat the most frequent case first, for speed and bootstrapping.
(cond ((eq cv *<standard-effective-slot-definition>-class-version*) t)
(t ; Now a slow, but general instanceof test.
(gethash <standard-effective-slot-definition>
(class-all-superclasses (class-of object))))))))
;; To avoid function calls when calling the initfunction of constants, we use
;; a specially tagged function.
(defun make-initfunction-form (form slotname)
(if (constantp form)
`(SYS::MAKE-CONSTANT-INITFUNCTION ,form)
`(FUNCTION ,(sys::concat-pnames "DEFAULT-" slotname)
(LAMBDA () ,form))))
;; Needed by DEFSTRUCT.
(defun make-load-form-<structure-direct-slot-definition> (object &optional initff)
`(make-instance-<structure-direct-slot-definition>
<structure-direct-slot-definition>
:name ',(slot-definition-name object)
:initargs ',(slot-definition-initargs object)
:type ',(slot-definition-type object)
:allocation ',(slot-definition-allocation object)
'inheritable-initer ;; The initfunction is serializable only by virtue
;; of the initfunctionform.
;; It's not necessary to preserve the EQ-ness of
;; the initer between the slot in the class and
;; the slot in its subclasses, because structure
;; classes don't support class redefinition.
(make-inheritable-slot-definition-initer
',(slot-definition-initform object)
,initff)
'inheritable-doc ',(slot-definition-inheritable-doc object)
:readers ',(slot-definition-readers object)
:writers ',(slot-definition-writers object)))
;; Needed by DEFSTRUCT.
(defun make-load-form-<structure-effective-slot-definition> (object &optional initff)
`(make-instance-<structure-effective-slot-definition>
<structure-effective-slot-definition>
:name ',(slot-definition-name object)
:initargs ',(slot-definition-initargs object)
:type ',(slot-definition-type object)
:allocation ',(slot-definition-allocation object)
'inheritable-initer ;; The initfunction is serializable only by virtue
;; of the initfunctionform.
;; It's not necessary to preserve the EQ-ness of
;; the initer between the slot in the class and
;; the slot in its subclasses, because structure
;; classes don't support class redefinition.
(make-inheritable-slot-definition-initer
',(slot-definition-initform object)
,initff)
'inheritable-doc ',(slot-definition-inheritable-doc object)
'location ',(slot-definition-location object)
'readonly ',(structure-effective-slot-definition-readonly object)))
| 31,453 | Common Lisp | .lisp | 510 | 51.892157 | 136 | 0.640711 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 35964e9a7b976394e4288924bf2732888a03ea6b48b4a713e6aa923154d06c5f | 11,372 | [
-1
] |
11,373 | loadform.lisp | ufasoft_lisp/clisp/loadform.lisp | ;;; MAKE-LOAD-FORM for CLISP
;;; Sam Steingold 2001-2004, 2009
;;; Bruno Haible 2004
;; this could have been placed in in clos.lisp,
;; but `make-init-form' uses conditions
(in-package "CLOS")
(defun make-load-form-saving-slots
(object &key environment
(slot-names
(let ((slots (class-slots (class-of object))))
(etypecase object
(standard-object
(mapcan (lambda (slot)
(when (eq (slot-definition-allocation slot) ':instance)
(list (slot-definition-name slot))))
slots))
(structure-object (mapcar #'slot-definition-name slots))))))
(declare (ignore environment))
(values `(allocate-instance (find-class ',(class-name (class-of object))))
`(progn
(setf ,@(mapcan (lambda (slot)
(when (slot-boundp object slot)
`((slot-value ,object ',slot)
',(slot-value object slot))))
slot-names))
(initialize-instance ,object))))
;; Condition type thrown by make-load-form.
;; It's not sufficient to rely on method-call-error because a test like
;; (eq (method-call-error-generic-function err) #'make-load-form)
;; doesn't work when make-load-form is traced.
(define-condition missing-load-form (error)
(($object :initarg :object :reader missing-load-form-object)))
(define-condition simple-missing-load-form (simple-error missing-load-form) ())
(defun signal-missing-load-form (object)
(let ((class (class-name (class-of object))))
(error-of-type 'simple-missing-load-form :object object
(TEXT "A method on ~S for class ~S is necessary for externalizing the object ~S, according to ANSI CL 3.2.4.4, but no such method is defined.")
'make-load-form class object)))
(defgeneric make-load-form (object &optional environment)
;; <http://www.lisp.org/HyperSpec/Body/stagenfun_make-load-form.html>
;; "The methods specialized on standard-object, structure-object, and
;; condition all signal an error of type error."
(:method ((object standard-object) &optional environment)
(declare (ignore environment))
(signal-missing-load-form object))
(:method ((object structure-object) &optional environment)
(declare (ignore environment))
(signal-missing-load-form object))
(:method ((object condition) &optional environment)
(declare (ignore environment))
(signal-missing-load-form object))
(:method ((object defined-class) &optional environment)
(declare (ignore environment))
;; TODO: Implement as described in CLHS
`(find-class ',(class-name object))))
(defun mlf-init-function (object)
(multiple-value-bind (creation-form initialization-form)
(make-load-form object)
(let ((funname
(gensym
(sys::string-concat
"CREATE-INSTANCE-OF-<"
(write-to-string (class-name (class-of object)) :readably nil)
">-"))))
`(FUNCTION ,funname
(LAMBDA ()
,@(if (and sys::*compiling* sys::*compiling-from-file*)
'((DECLARE (COMPILE)))
'())
,(if initialization-form
(let ((var (gensym "MAKE-LOAD-FORM-")))
`(LET ((,var ,creation-form))
,(sublis `((',object . ,var) (,object . ,var))
initialization-form
:test #'equal)
,var))
creation-form))))))
(defun make-init-form (object)
(when sys::*load-forms*
(multiple-value-bind (form found-p)
(gethash object sys::*load-forms*)
(if found-p
form
(setf (gethash object sys::*load-forms*)
(block compute-init-form
(handler-bind
((missing-load-form
#'(lambda (err)
(when (eql (missing-load-form-object err) object)
(return-from compute-init-form nil)))))
`(funcall ,(eval (mlf-init-function object))))))))))
| 4,130 | Common Lisp | .lisp | 91 | 35.340659 | 149 | 0.593401 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | fdea2ce8da26004d6e7cae0b3a8ab3b2305866e2c815183d46869b58453290f7 | 11,373 | [
-1
] |
11,374 | functions.lisp | ufasoft_lisp/clisp/functions.lisp | ;;; Utilities for function objects
;;; Sam Steingold 2001-2005, 2008
;;; Bruno Haible 2004
(in-package "COMMON-LISP")
(export '(function-lambda-expression))
(in-package "SYSTEM")
;; The signature of a function object.
(defstruct (signature (:type vector) (:conc-name sig-))
;; (name nil :type (or symbol cons))
(req-num 0 :type fixnum)
(opt-num 0 :type fixnum)
(rest-p nil :type boolean)
(keys-p nil :type boolean)
(keywords nil :type list)
(allow-p nil :type boolean))
;; X3J13 vote <88>
;; function --> lambda expression, CLtL2 p. 682
(defun function-lambda-expression (obj)
(setq obj (coerce obj 'function))
(cond #+FFI
((eq (type-of obj) 'FFI::FOREIGN-FUNCTION)
(values nil nil (sys::%record-ref obj 0))) ; ff_name
((sys::subr-info obj)
(values nil nil (sys::subr-info obj)))
((sys::%compiled-function-p obj) ; compiled closure?
(let* ((name (sys::closure-name obj))
(def (get (if (symbolp name)
name (get (second name) 'sys::setf-function))
'sys::definition)))
(values (when def (cons 'LAMBDA (cddar def))) t name)))
((sys::closurep obj) ; interpreted closure?
(values (cons 'LAMBDA (sys::%record-ref obj 1)) ; lambda-expression without docstring (from clos_form)
(vector ; environment
(sys::%record-ref obj 4) ; venv
(sys::%record-ref obj 5) ; fenv
(sys::%record-ref obj 6) ; benv
(sys::%record-ref obj 7) ; genv
(sys::%record-ref obj 8)); denv
(sys::closure-name obj))))) ; name
(defun function-name (obj)
;; Equivalent to (nth-value 2 (function-lambda-expression obj))
(setq obj (coerce obj 'function))
(cond #+FFI
((eq (type-of obj) 'FFI::FOREIGN-FUNCTION)
(sys::%record-ref obj 0)) ; ff_name
((sys::subr-info obj))
((sys::%compiled-function-p obj) ; compiled closure?
(sys::closure-name obj))
((sys::closurep obj) ; interpreted closure?
(sys::closure-name obj))))
;; Returns the function definition of a function name, ignoring wrappers
;; installed by TRACE, profilers etc.
(defun unwrapped-fdefinition (funname)
(let* ((sym (get-funname-symbol funname))
(def (or (get sym 'sys::traced-definition)
(symbol-function sym))))
(if (macrop def)
(macro-expander def)
def)))
| 2,537 | Common Lisp | .lisp | 59 | 34.491525 | 111 | 0.583502 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 1e9b36ea9c289f8e1d52e4a96f20f1026e31394ab4896e97f4e44e8216d71008 | 11,374 | [
-1
] |
11,375 | macros1.lisp | ufasoft_lisp/clisp/macros1.lisp | ;;;; Definitions for control structures etc.
;;;; 29.4.1988, 3.9.1988
(in-package "SYSTEM")
(export '(ext::fcase) "EXT")
(export '(custom::*suppress-similar-constant-redefinition-warning*) "CUSTOM")
;; (DEFMACRO-SPECIAL . macrodef) is like (DEFMACRO . macrodef) except
;; that it works on a special form without replacing the special form
;; handler. ANSI CL requires that all standard macros, even when implemented
;; as special forms, have a macro expander available.
(defmacro defmacro-special (&whole whole-form
&body macrodef)
(multiple-value-bind (expansion expansion-lambdabody name lambdalist docstring)
(make-macro-expansion macrodef whole-form)
(declare (ignore expansion-lambdabody lambdalist docstring))
`(SYSTEM::%PUT ',name 'SYSTEM::MACRO ,expansion)))
(defmacro defvar (&whole whole-form
symbol &optional (initial-value nil svar) docstring)
(unless (symbolp symbol)
(error-of-type 'source-program-error
:form whole-form
:detail symbol
(TEXT "~S: non-symbol ~S cannot be a variable")
'defvar symbol))
(if (constantp symbol)
(error-of-type 'source-program-error
:form whole-form
:detail symbol
(TEXT "~S: the constant ~S must not be redefined to be a variable")
'defvar symbol))
`(LET ()
(PROCLAIM '(SPECIAL ,symbol))
,@(if svar
`((UNLESS (BOUNDP ',symbol)
(SYS::SET-SYMBOL-VALUE ',symbol ,initial-value))))
,@(if docstring
`((SYS::%SET-DOCUMENTATION ',symbol 'VARIABLE ',docstring)))
',symbol))
(defmacro defparameter (&whole whole-form
symbol initial-value &optional docstring)
(unless (symbolp symbol)
(error-of-type 'source-program-error
:form whole-form
:detail symbol
(TEXT "~S: non-symbol ~S cannot be a variable")
'defparameter symbol))
(if (constantp symbol)
(error-of-type 'source-program-error
:form whole-form
:detail symbol
(TEXT "~S: the constant ~S must not be redefined to be a variable")
'defparameter symbol))
`(LET ()
(PROCLAIM '(SPECIAL ,symbol))
(SYS::SET-SYMBOL-VALUE ',symbol ,initial-value)
,@(if docstring `((SYS::%SET-DOCUMENTATION ',symbol 'VARIABLE ',docstring)))
',symbol))
(defmacro defconstant (&whole whole-form
symbol initial-value &optional docstring)
(unless (symbolp symbol)
(error-of-type 'source-program-error
:form whole-form
:detail symbol
(TEXT "~S: non-symbol ~S cannot be defined constant")
'defconstant symbol))
(let ((initial-var (gensym)))
`(LET ()
(SYS::EVAL-WHEN-COMPILE
(SYS::C-PROCLAIM-CONSTANT ',symbol ',initial-value))
(LET ((,initial-var ,initial-value))
(IF (CONSTANTP ',symbol)
(UNLESS (CONSTANT-EQL ,initial-value ,initial-var
(SYMBOL-VALUE ',symbol))
(CONSTANT-WARNING ',symbol ',whole-form ,initial-var)))
(SYS::%PROCLAIM-CONSTANT ',symbol ,initial-var)
,@(if docstring
`((SYS::%SET-DOCUMENTATION ',symbol 'VARIABLE ',docstring)))
',symbol))))
; For inhibiting warnings about redefining constants when the old and the new
; value are the same string / bit vector:
(defmacro constant-eql (new-form new-value old-value) ; ABI
(declare (ignore new-form))
`(EQL ,new-value ,old-value))
; If new-value is known to be an immutable string / bit vector and old-value
; is the same string / bit vector, this can return T by using EQUAL instead of
; EQL.
(defun loose-constant-eql (new-value old-value) ; ABI
(and (equal (type-of new-value) (type-of old-value))
(equal new-value old-value)))
; The redefinition warning.
(defvar custom:*suppress-similar-constant-redefinition-warning* nil
"When non-NIL, no warning is issued when a constant is redefined
to a new value which is visually similar (prints identically) to the old one.")
(defun constant-warning (symbol form new-value) ; ABI
(let ((old-value (symbol-value symbol)))
;; use write-to-string instead of equal to handle circularity
(if (string= (write-to-string new-value :pretty nil :circle t)
(write-to-string old-value :pretty nil :circle t))
(unless custom:*suppress-similar-constant-redefinition-warning*
(warn (TEXT "~S redefines the constant ~S. Its old value was visually similar though. Set ~S to avoid this warning.")
form symbol
'custom:*suppress-similar-constant-redefinition-warning*))
(warn (TEXT "~S redefines the constant ~S. Its old value was ~S.")
form symbol old-value))))
(defmacro-special and (&body args)
(cond ((null args) T)
((null (cdr args)) (car args))
(t (let ((L (mapcar #'(lambda (x) `((NOT ,x) NIL) ) args)))
(rplaca (last L) `(T ,(car (last args))))
(cons 'COND L)))))
(defmacro-special or (&body args)
(cond ((null args) NIL)
((null (cdr args)) (car args))
(t (let ((L (mapcar #'list args)))
(rplaca (last L) `(T ,(car (last args))))
(cons 'COND L)))))
(defmacro-special prog1 (form1 &rest moreforms)
(let ((g (gensym "PROG1-")))
`(LET ((,g ,form1)) ,@moreforms ,g)))
(defmacro-special prog2 (form1 form2 &rest moreforms)
(let ((g (gensym "PROG2-")))
`(LET () (PROGN ,form1 (LET ((,g ,form2)) ,@moreforms ,g)))))
(defmacro-special when (test &body forms)
`(IF ,test (PROGN ,@forms)))
(defmacro-special unless (test &body forms)
`(IF (NOT ,test) (PROGN ,@forms)))
;; DECLARE is a special form in CLISP, so it should provide a macroexpansion
(defmacro-special declare (&body ignore)
(declare (ignore ignore))
nil)
(defmacro return (&optional return-value)
`(RETURN-FROM NIL ,return-value))
(predefmacro loop (&body body)
(let ((tag (gensym)))
`(BLOCK NIL (TAGBODY ,tag ,@body (GO ,tag)))))
(defun do/do*-expand (whole-form varclauselist exitclause body do let psetq)
(when (atom exitclause)
(error-of-type 'source-program-error
:form whole-form
:detail exitclause
(TEXT "exit clause in ~S must be a list")
do))
(flet ((bad-syntax (formpiece)
(error-of-type 'source-program-error
:form whole-form
:detail formpiece
(TEXT "Invalid syntax in ~S form: ~S.") do formpiece)))
(let ((bindlist nil)
(reinitlist nil)
(testtag (gensym "LOOP-"))
(exittag (gensym "END-")))
(multiple-value-bind (body-rest declarations) (sys::parse-body body)
(when declarations
(setq declarations (list (cons 'DECLARE declarations))))
(loop
(when (atom varclauselist)
(if (null varclauselist)
(return)
(bad-syntax varclauselist)))
(let ((varclause (first varclauselist)))
(setq varclauselist (rest varclauselist))
(cond ((atom varclause)
(setq bindlist (cons varclause bindlist)))
((null (cdr varclause))
(setq bindlist (cons (first varclause) bindlist)))
((atom (cdr varclause))
(bad-syntax varclause))
((null (cddr varclause))
(setq bindlist (cons varclause bindlist)))
((atom (cddr varclause))
(bad-syntax varclause))
((null (cdddr varclause))
(setq bindlist
(cons (list (first varclause) (second varclause))
bindlist))
(setq reinitlist
(list* (third varclause) (first varclause) reinitlist)))
(t ;;(not (null (cdddr varclause)))
(bad-syntax varclause)))))
`(BLOCK NIL
(,let ,(nreverse bindlist)
,@declarations
(TAGBODY
,testtag
(IF ,(first exitclause) (GO ,exittag))
,@body-rest
(,psetq ,@(nreverse reinitlist))
(GO ,testtag)
,exittag
(RETURN-FROM NIL (PROGN ,@(rest exitclause))))))))))
(fmakunbound 'do)
(defmacro do (&whole whole-form
varclauselist exitclause &body body)
(do/do*-expand whole-form varclauselist exitclause body 'DO 'LET 'PSETQ))
(defmacro do* (&whole whole-form
varclauselist exitclause &body body)
(do/do*-expand whole-form varclauselist exitclause body 'DO* 'LET* 'SETQ))
(defmacro dolist ((var listform &optional resultform) &body body)
(multiple-value-bind (body-rest declarations) (sys::parse-body body)
(let ((g (gensym "LIST-")))
`(DO* ((,g ,listform (CDR ,g))
(,var NIL))
((ENDP ,g)
,(if (constantp resultform)
; Ist resultform konstant, so ist es /= var. Daher braucht var
; wahrend Auswertung von resultform nicht an NIL gebunden zu sein: ;!!!P non UTF8 char
`,resultform
`(LET ((,var NIL))
(DECLARE (IGNORABLE ,var) ,@declarations)
,resultform)))
(DECLARE (LIST ,g) ,@declarations)
(SETQ ,var (CAR ,g))
,@body-rest))))
(fmakunbound 'dotimes)
(defmacro dotimes ((var countform &optional resultform) &body body)
(multiple-value-bind (body-rest declarations) (sys::parse-body body)
(if declarations
(setq declarations (list (cons 'DECLARE declarations))))
(if (constantp countform)
`(DO ((,var 0 (1+ ,var)))
((>= ,var ,countform) ,resultform)
,@declarations
,@body-rest)
(let ((g (gensym "COUNT-")))
`(DO ((,var 0 (1+ ,var))
(,g ,countform))
((>= ,var ,g) ,resultform)
,@declarations
,@body-rest)))))
(defmacro-special psetq (&whole whole-form
&rest args)
(do* ((setlist nil)
(bindlist nil)
(arglist args (cddr arglist)))
((null arglist)
(setq setlist (cons 'NIL setlist))
(cons 'LET (cons (nreverse bindlist) (nreverse setlist))))
(if (null (cdr arglist))
(error-of-type 'source-program-error
:form whole-form
:detail whole-form
(TEXT "~S called with an odd number of arguments: ~S")
'psetq whole-form))
(let ((g (gensym "PSETQ-")))
(setq setlist (cons `(SETQ ,(first arglist) ,g) setlist))
(setq bindlist (cons `(,g ,(second arglist)) bindlist)))))
(defmacro-special multiple-value-list (form)
`(MULTIPLE-VALUE-CALL #'LIST ,form))
(defmacro-special multiple-value-bind (varlist form &body body)
(let ((g (gensym "VALUES-"))
(poplist nil))
(dolist (var varlist) (setq poplist (cons `(,var (POP ,g)) poplist)))
`(LET* ((,g (MULTIPLE-VALUE-LIST ,form)) ,@(nreverse poplist))
,@body)))
(defmacro-special multiple-value-setq (varlist form)
(let ((g (gensym "VALUES-"))
(poplist nil))
(dolist (var varlist) (setq poplist (cons `(SETQ ,var (POP ,g)) poplist)))
`(LET* ((,g (MULTIPLE-VALUE-LIST ,form)))
,(if poplist `(PROG1 ,@(nreverse poplist)) NIL))))
(defmacro-special locally (&body body)
`(LET () ,@body))
(defun case-expand (whole-form form-name test keyform clauses)
(let ((var (gensym (string-concat (symbol-name form-name) "-KEY-"))))
`(let ((,var ,keyform))
(cond
,@(maplist
#'(lambda (remaining-clauses)
(let ((clause (first remaining-clauses))
(remaining-clauses (rest remaining-clauses)))
(unless (consp clause)
(error-of-type 'source-program-error
:form whole-form
:detail clause
(TEXT "~S: missing key list")
form-name))
(let ((keys (first clause)))
`(,(cond ((or (eq keys 'T) (eq keys 'OTHERWISE))
(if remaining-clauses
(error-of-type 'source-program-error
:form whole-form
:detail clause
(TEXT "~S: the ~S clause must be the last one")
form-name keys)
't))
((listp keys)
`(or ,@(mapcar #'(lambda (key)
`(,test ,var ',key))
keys)))
(t `(,test ,var ',keys)))
,@(rest clause)))))
clauses)))))
(defmacro fcase (&whole whole-form
test keyform &body clauses)
(case-expand whole-form 'fcase test keyform clauses))
(defmacro-special case (&whole whole-form
keyform &body clauses)
(case-expand whole-form 'case 'eql keyform clauses))
(defmacro prog (varlist &body body)
(multiple-value-bind (body-rest declarations) (sys::parse-body body)
(if declarations
(setq declarations (list (cons 'DECLARE declarations))))
`(BLOCK NIL
(LET ,varlist
,@declarations
(TAGBODY ,@body-rest)))))
(defmacro prog* (varlist &body body)
(multiple-value-bind (body-rest declarations) (sys::parse-body body)
(if declarations
(setq declarations (list (cons 'DECLARE declarations))))
`(BLOCK NIL
(LET* ,varlist
,@declarations
(TAGBODY ,@body-rest)))))
;!!!P
;; Dieser hier reduziert COND etwas umstandlicher auf IF-Folgen:
(defmacro-special cond (&whole whole-form
&body clauses)
(let ((g (gensym "RESULT-")))
(multiple-value-bind (ifif needed-g) (ifify whole-form clauses g)
(if needed-g
`(LET (,g) ,ifif)
ifif))))
; macht eine clauselist von COND zu verschachtelten IFs.
; Zwei Werte: die neue Form, und ob die Dummyvariable g benutzt wurde.
(defun ifify (whole-form clauselist g)
(cond ((null clauselist) (values NIL nil))
((atom clauselist)
(error-of-type 'source-program-error
:form whole-form
:detail clauselist
(TEXT "Not a list of COND clauses: ~S")
clauselist))
((atom (car clauselist))
(error-of-type 'source-program-error
:form whole-form
:detail (car clauselist)
(TEXT "The atom ~S must not be used as a COND clause.")
(car clauselist)))
(t (multiple-value-bind (ifif needed-g) (ifify whole-form (cdr clauselist) g)
(if (cdar clauselist)
; mindestens zweielementige Klausel
(if (constantp (caar clauselist))
(if (eval (caar clauselist)) ; Test zur Expansionszeit auswerten
(if (cddar clauselist)
(values `(PROGN ,@(cdar clauselist)) nil)
(values (cadar clauselist) nil))
(values ifif needed-g))
(values
`(IF ,(caar clauselist)
,(if (cddar clauselist)
`(PROGN ,@(cdar clauselist)) (cadar clauselist))
,ifif)
needed-g))
; einelementige Klausel
(if (constantp (caar clauselist))
(if (eval (caar clauselist)) ; Test zur Expansionszeit auswerten
(values (caar clauselist) nil)
(values ifif needed-g))
(if (atom (caar clauselist))
(values ; ein Atom produziert nur einen Wert und darf
`(IF ,(caar clauselist) ; mehrfach hintereinander
,(caar clauselist) ; ausgewertet werden!
,ifif)
needed-g)
(values
`(IF (SETQ ,g ,(caar clauselist)) ,g ,ifif)
t))))))))
| 16,044 | Common Lisp | .lisp | 367 | 33.318801 | 127 | 0.57446 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | d55befc16b347492c2aded2cb674d2aa3020dfadd2e83935c5b56046aac7878d | 11,375 | [
-1
] |
11,376 | clos-dependent.lisp | ufasoft_lisp/clisp/clos-dependent.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Dependent Protocol
;;;; Bruno Haible 2004-07-29
(in-package "CLOS")
;; ----------------------------------------------------------------------------
;; MOP p. 30
(defgeneric add-dependent (metaobject dependent)
(:method ((metaobject defined-class) dependent)
(pushnew dependent (class-listeners metaobject) :test #'eq))
(:method ((metaobject generic-function) dependent)
(pushnew dependent (gf-listeners metaobject) :test #'eq)))
;; MOP p. 87
(defgeneric remove-dependent (metaobject dependent)
(:method ((metaobject defined-class) dependent)
(setf (class-listeners metaobject)
(delete dependent (the list (class-listeners metaobject)) :test #'eq)))
(:method ((metaobject generic-function) dependent)
(setf (gf-listeners metaobject)
(delete dependent (the list (gf-listeners metaobject)) :test #'eq))))
;; MOP p. 73
(defgeneric map-dependents (metaobject function)
(:method ((metaobject defined-class) function)
(map-dependents-<defined-class> metaobject function))
(:method ((metaobject generic-function) function)
(map-dependents-<generic-function> metaobject function)))
;; MOP p. 101
(defgeneric update-dependent (metaobject dependent &rest initargs))
| 1,263 | Common Lisp | .lisp | 27 | 43.481481 | 81 | 0.688618 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | f48dc4beaa194ab7cd1051b5774398bc7fd1ce9823362d29492603909f40c342 | 11,376 | [
-1
] |
11,377 | gray.lisp | ufasoft_lisp/clisp/gray.lisp | ;;; Gray streams, following David N. Gray's STREAM-DEFINITION-BY-USER proposal
;;; ftp://parcftp.xerox.com/pub/cl/cleanup/mail/stream-definition-by-user.mail
(in-package "GRAY")
(common-lisp:export
'(;; Classes:
fundamental-stream
fundamental-input-stream
fundamental-output-stream
fundamental-character-stream
fundamental-binary-stream
fundamental-character-input-stream
fundamental-character-output-stream
fundamental-binary-input-stream
fundamental-binary-output-stream
;; general generic functions:
stream-position
stream-read-sequence
stream-write-sequence
;; Generic functions for character input:
stream-read-char
stream-unread-char
stream-read-char-no-hang
stream-peek-char
stream-listen
stream-read-char-will-hang-p
stream-read-char-sequence
stream-read-line
stream-clear-input
;; Generic functions for character output:
stream-write-char
stream-line-column
stream-start-line-p
stream-write-char-sequence
stream-write-string
stream-terpri
stream-fresh-line
stream-finish-output
stream-force-output
stream-clear-output
stream-advance-to-column
;; Generic functions for binary input:
stream-read-byte
stream-read-byte-lookahead
stream-read-byte-will-hang-p
stream-read-byte-no-hang
stream-read-byte-sequence
;; Generic functions for binary output:
stream-write-byte
stream-write-byte-sequence))
(common-lisp:in-package "SYSTEM")
(import '(close open-stream-p stream-element-type) "GRAY")
(use-package '("GRAY") "EXT")
(ext:re-export "GRAY" "EXT")
;; Classes
(defmethod clos:validate-superclass ((class class)
(superclass (eql clos::<stream>)))
(or (call-next-method)
(eq (clos:class-name class) 'fundamental-stream)))
(ext:compiler-let ((clos::*allow-mixing-metaclasses* t))
(let ((clos::*allow-mixing-metaclasses* t))
(clos:defclass fundamental-stream (stream clos:standard-object)
(($open :type boolean :initform t) ; whether the stream is open
($fasl :type boolean :initform nil) ; read-eval is allowed; \r=#\Return
($penl :type boolean :initform nil) ; whether an elastic newline is pending
) ) ) )
(clos:defclass fundamental-input-stream (fundamental-stream)
()
)
(clos:defclass fundamental-output-stream (fundamental-stream)
()
)
; Stuff these classes into the runtime system.
(%defgray
(vector
(clos:find-class 'fundamental-stream) ; for STREAMP to work
(clos:find-class 'fundamental-input-stream) ; for INPUT-STREAM-P to work
(clos:find-class 'fundamental-output-stream) ; for OUTPUT-STREAM-P to work
) )
(clos:defclass fundamental-character-stream (fundamental-stream)
()
)
(clos:defclass fundamental-binary-stream (fundamental-stream)
()
)
(clos:defclass fundamental-character-input-stream (fundamental-input-stream fundamental-character-stream)
(($lastchar :initform nil) ; last character read (and not yet unread)
) )
(clos:defclass fundamental-character-output-stream (fundamental-output-stream fundamental-character-stream)
()
)
(clos:defclass fundamental-binary-input-stream (fundamental-input-stream fundamental-binary-stream)
()
)
(clos:defclass fundamental-binary-output-stream (fundamental-output-stream fundamental-binary-stream)
()
)
;; General generic functions
(clos:defgeneric close (stream &key abort)
(:method ((stream stream) &rest args)
(apply #'sys::built-in-stream-close stream args))
(:method ((stream fundamental-stream) &rest more-args)
(declare (ignore more-args))
(clos:with-slots ($open $penl) stream
(when $penl (setq $penl nil) (write-char #\Newline stream))
(prog1 $open (setq $open nil))
) )
)
(clos:defgeneric open-stream-p (stream)
(:method ((stream stream))
(sys::built-in-stream-open-p stream)
)
(:method ((stream fundamental-stream))
(clos:with-slots ($open) stream
$open
) )
)
(clos:defgeneric stream-element-type (stream)
(:method ((stream stream))
(sys::built-in-stream-element-type stream)
)
(:method ((stream fundamental-stream))
(clos:no-applicable-method #'stream-element-type stream)
)
(:method ((stream fundamental-character-stream))
'CHARACTER
)
)
(clos:defgeneric (setf stream-element-type) (new-element-type stream)
(:method (new-element-type (stream stream))
(sys::built-in-stream-set-element-type stream new-element-type)
)
(:method (new-element-type (stream fundamental-stream))
(clos:no-applicable-method #'(setf stream-element-type) new-element-type stream)
)
)
(clos:defgeneric stream-position (stream position)
(:method ((stream stream) position)
(if position
(cl:file-position stream position)
(cl:file-position stream)))
(:method ((stream fundamental-stream) position)
(clos:no-applicable-method #'stream-position stream position)))
(clos:defgeneric stream-read-sequence (sequence stream &key start end)
(:method (sequence (stream fundamental-binary-input-stream)
&key (start 0) (end nil))
(stream-read-byte-sequence stream sequence start end))
(:method (sequence (stream fundamental-character-input-stream)
&key (start 0) (end nil))
(stream-read-char-sequence stream sequence start end))
(:method (sequence (stream fundamental-input-stream) &rest rest)
(apply #'sys::%read-sequence sequence stream rest)))
(clos:defgeneric stream-write-sequence (sequence stream &key start end)
(:method (sequence (stream fundamental-binary-output-stream)
&key (start 0) (end nil))
(stream-write-byte-sequence stream sequence start end))
(:method (sequence (stream fundamental-character-output-stream)
&key (start 0) (end nil))
(stream-write-char-sequence stream sequence start end))
(:method (sequence (stream fundamental-output-stream) &rest rest)
(apply #'sys::%write-sequence sequence stream rest)))
;; Generic functions for character input
; We define the methods on fundamental-input-stream, not
; fundamental-character-input-stream, so that people can use
; (setf stream-element-type).
(clos:defgeneric stream-read-char (stream))
(clos:defgeneric stream-unread-char (stream char))
(clos:defgeneric stream-read-char-no-hang (stream)
(:method ((stream fundamental-input-stream))
(stream-read-char stream)
)
)
(clos:defgeneric stream-peek-char (stream)
(:method ((stream fundamental-input-stream))
(let ((c (stream-read-char stream)))
(unless (eq c ':EOF) (stream-unread-char stream c))
c
) )
)
(clos:defgeneric stream-listen (stream)
(:method ((stream fundamental-input-stream))
(let ((c (stream-read-char-no-hang stream)))
(if (or (eq c 'NIL) (eq c ':EOF))
nil
(progn (stream-unread-char stream c) t)
) ) )
)
(clos:defgeneric stream-read-char-will-hang-p (stream)
(:method ((stream fundamental-input-stream))
(let ((c (stream-read-char-no-hang stream)))
(cond ((eq c 'NIL) t)
((eq c ':EOF) nil)
(t (stream-unread-char stream c) nil)
) ) )
)
(clos:defgeneric stream-read-char-sequence (stream sequence &optional start end)
(:method ((stream fundamental-input-stream) (sequence string) &optional (start 0) (end nil))
; sequence is a simple-string, and start and end are suitable integers.
(unless end (setq end (length sequence)))
(do ((index start (1+ index)))
((eql index end) index)
(let ((c (stream-read-char stream)))
(when (eq c ':EOF) (return index))
(setf (char sequence index) c)
) ) )
)
(clos:defgeneric stream-read-line (stream)
(:method ((stream fundamental-input-stream))
(let ((buffer (make-array 10 :element-type 'character :adjustable t :fill-pointer 0)))
(loop
(let ((c (stream-read-char stream)))
(cond ((eq c ':EOF) (return (values (coerce buffer 'simple-string) t)))
((eql c #\Newline) (return (values (coerce buffer 'simple-string) nil)))
(t (vector-push-extend c buffer))
) ) ) ) )
)
(clos:defgeneric stream-clear-input (stream)
(:method ((stream fundamental-input-stream))
nil
)
)
;; Generic functions for character output
; We define the methods on fundamental-output-stream, not
; fundamental-character-output-stream, so that people can use
; (setf stream-element-type).
(clos:defgeneric stream-write-char (stream character))
(clos:defgeneric stream-line-column (stream))
(clos:defgeneric stream-start-line-p (stream)
(:method ((stream fundamental-output-stream))
(eql (stream-line-column stream) 0)
)
)
(clos:defgeneric stream-write-char-sequence (stream sequence &optional start end)
(:method ((stream fundamental-output-stream) (sequence string) &optional (start 0) (end nil))
; sequence is a simple-string, and start and end are suitable integers.
(unless end (setq end (length sequence)))
(do ((index start (1+ index)))
((eql index end) nil)
(stream-write-char stream (char sequence index))
) )
)
(clos:defgeneric stream-write-string (stream string &optional start end)
(:method ((stream fundamental-output-stream) string &optional (start 0) (end nil))
(stream-write-char-sequence stream string start end)
string
)
)
(clos:defgeneric stream-terpri (stream)
(:method ((stream fundamental-output-stream))
(stream-write-char stream #\Newline)
nil
)
)
(clos:defgeneric stream-fresh-line (stream)
(:method ((stream fundamental-output-stream))
(if (stream-start-line-p stream)
nil
(progn (stream-terpri stream) t)
) )
)
(clos:defgeneric stream-finish-output (stream)
(:method ((stream fundamental-output-stream))
nil
)
)
(clos:defgeneric stream-force-output (stream)
(:method ((stream fundamental-output-stream))
nil
)
)
(clos:defgeneric stream-clear-output (stream)
(:method ((stream fundamental-output-stream))
nil
)
)
(clos:defgeneric stream-advance-to-column (stream column)
(:method ((stream fundamental-output-stream) (column real))
(let ((currcol (stream-line-column stream)))
(if currcol
(dotimes (i (- column currcol) t) (stream-write-char stream #\Space))
nil
) ) )
)
;; Generic functions for binary input
(clos:defgeneric stream-read-byte (stream))
(clos:defgeneric stream-read-byte-lookahead (stream))
(clos:defgeneric stream-read-byte-will-hang-p (stream)
(:method ((stream fundamental-input-stream))
(eq (stream-read-byte-lookahead stream) 'NIL)
)
)
(clos:defgeneric stream-read-byte-no-hang (stream)
(:method ((stream fundamental-input-stream))
(if (stream-read-byte-lookahead stream)
(stream-read-byte stream)
nil
) )
)
(clos:defgeneric stream-read-byte-sequence (stream sequence
&optional start end no-hang interactive)
(:method ((stream fundamental-input-stream) (sequence vector)
&optional (start 0) (end nil) (no-hang nil) (interactive nil))
;; sequence is a (simple-array (unsigned-byte 8) (*)),
;; and start and end are suitable integers.
(unless end (setq end (length sequence)))
(do ((index start (1+ index)))
((eql index end) index)
(let ((x (if (or no-hang (and interactive (> index start)))
(stream-read-byte-no-hang stream)
(stream-read-byte stream))))
(when (or (null x) (eq x ':EOF)) (return index))
(setf (aref sequence index) x)))))
;; Generic functions for binary output
(clos:defgeneric stream-write-byte (stream integer))
(clos:defgeneric stream-write-byte-sequence (stream sequence
&optional start end no-hang interactive)
(:method ((stream fundamental-output-stream) (sequence vector)
&optional (start 0) (end nil) (no-hang nil) (interactive nil))
;; sequence is a (simple-array (unsigned-byte 8) (*)),
;; and start and end are suitable integers.
;; if no-hang and you write less than end-start bytes then you should
;; return the first unwritten index as the second value
;; first value should then be sequence argument
(when no-hang
(error "~S: ~S is not supported by the default method"
'stream-write-byte-sequence :NO-HANG))
(when interactive
(error "~S: ~S is not supported by the default method"
'stream-write-byte-sequence :INTERACTIVE))
(unless end (setq end (length sequence)))
(do ((index start (1+ index)))
((eql index end) nil)
(stream-write-byte stream (aref sequence index)))))
| 12,577 | Common Lisp | .lisp | 332 | 33.403614 | 107 | 0.700025 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 6e6d981c47869585b4e93715f81b49f16ee5f1f55faea3298289e2afbf5c2d07 | 11,377 | [
-1
] |
11,378 | loop.lisp | ufasoft_lisp/clisp/loop.lisp | ;; ANSI CL Loop
;; (LOOP {loop-clause}*), CLtL2 p. 163,709-747
;; <http://www.lisp.org/HyperSpec/Body/sec_6-1.html>
;; <http://www.lisp.org/HyperSpec/Body/mac_loop.html>
;; Bruno Haible 1991-2004
;; Sam Steingold 1999-2005
(in-package "COMMON-LISP")
(export '(loop loop-finish))
(pushnew ':loop *features*)
(in-package "SYSTEM")
;; Parser auxiliary functions
;; (loop-keywordp obj) determines whether OBJ is a loop keyword,
;; and then returns the appropriate unique symbol, otherwise NIL.
(defun loop-keywordp (obj)
(and (symbolp obj)
(gethash (symbol-name obj)
(load-time-value
(make-hash-table
:key-type 'string :value-type 'symbol
:test 'fasthash-equal :warn-if-needs-rehash-after-gc t
:initial-contents
(mapcar #'(lambda (s) (cons (symbol-name s) s))
'(named
for as and from downfrom upfrom to downto upto below
above by in on = then across being each the hash-key
hash-keys hash-value hash-values of using symbol
present-symbol internal-symbol external-symbol symbols
present-symbols internal-symbols external-symbols
repeat
while until always never thereis
collect collecting append appending nconc nconcing
count counting sum summing maximize maximizing
minimize minimizing into
with
if when unless else end it
do doing return
of-type
initially finally)))))))
(defvar *whole*) ; the entire form (LOOP ...)
;; (loop-syntax-error loop-keyword) reports a syntax error.
(defun loop-syntax-error (loop-keyword)
(error-of-type 'source-program-error
:form *whole*
:detail loop-keyword ; FIXME: should be something more useful
(TEXT "~S: syntax error after ~A in ~S")
'loop (symbol-name loop-keyword) *whole*))
;; destructuring:
;; (destructure-vars pattern) returns the list of variables occuring
;; in the pattern.
(defun destructure-vars (pattern)
(let ((vars '()))
(labels ((accumulate (pattern)
(cond ((null pattern))
((atom pattern) (push pattern vars))
(t
(accumulate (car pattern))
(accumulate (cdr pattern))))))
(accumulate pattern))
(nreverse vars)))
;; (empty-tree-p pattern) determine whether the pattern has no variables
;; at all.
(defun empty-tree-p (pattern)
(cond ((null pattern) t)
((atom pattern) nil)
(t (and (empty-tree-p (car pattern))
(empty-tree-p (cdr pattern))))))
;; (destructure-type pattern type) returns the list of declaration
;; specifiers, that declare that each variable in 'pattern' is of the
;; corresponding type in 'type'.
(defun destructure-type (pattern type)
(let ((declspecs '()))
(labels ((accumulate (pattern type)
(cond ((null pattern))
((atom pattern)
(push `(TYPE ,type ,pattern) declspecs))
((consp type)
(accumulate (car pattern) (car type))
(accumulate (cdr pattern) (cdr type)))
(t
(let ((vars (destructure-vars pattern)))
(when vars
(push `(TYPE ,type ,@vars) declspecs)))))))
(accumulate pattern type))
(nreverse declspecs)))
;; (simple-type-p type) determines whether 'type' contains, after
;; destructuring, only NIL, T, FIXNUM, FLOAT, and therefore can be
;; used without OF-TYPE.
(defun simple-type-p (type)
(if (atom type)
(case type
((NIL T FIXNUM FLOAT) t)
(t nil))
(and (simple-type-p (car type))
(simple-type-p (cdr type)))))
(defvar *helpvars*) ;; vector of auxiliary variables for destructuring
;; (helpvar n) returns the (n+1)-st auxiliary variable (n>=0).
;; At least n auxiliary variable must already have been used.
(defun helpvar (n)
;; '*helpvars*' is extended if necessary.
(when (= n (fill-pointer *helpvars*))
(vector-push-extend (gensym "PATTERN-") *helpvars*))
(aref *helpvars* n))
;; (destructure pattern form) returns a list of lists (variable_i form_i).
;; variable_i is a variable from 'pattern', form_i is a form, whose
;; result must be bound or assigned to variable_i. The order of the
;; bindings/assignments doesn't matter, i.e. both LET and LET*, or
;; both PSETQ and SETQ are possible.
(defun destructure (pattern form)
(labels ((destructure-tree (pattern form helpvar-count)
; helpvar-count = Anzahl der belegten Hilfsvariablen
(cond ((empty-tree-p pattern) nil)
((atom pattern) (list (list pattern form)))
((empty-tree-p (car pattern))
(destructure-tree (cdr pattern) `(CDR ,form) helpvar-count))
((empty-tree-p (cdr pattern))
(destructure-tree (car pattern) `(CAR ,form) helpvar-count))
(t ; muss form zwischendurch einer Hilfsvariablen zuweisen
(let ((helpvar (helpvar helpvar-count)))
(nconc (destructure-tree (car pattern) `(CAR (SETQ ,helpvar ,form)) (1+ helpvar-count))
(destructure-tree (cdr pattern) `(CDR ,helpvar) helpvar-count)))))))
(or (destructure-tree pattern form 0)
; no variables -> must nevertheless evaluate form!
(list (list (helpvar 0) form)))))
;; (default-bindings vars declspecs).
;; vars = (var ...) is a list of variables without init forms.
;; Returns the binding list ((var var-init) ...), where var-init is
;; compatible with the declspecs.
(defun default-bindings (vars declspecs)
; Use NIL or 0 or 0.0 if it fits the declarations.
; Otherwise use NIL and extend the type declarations.
(let ((bindings (mapcar #'(lambda (var) (list var 'NIL)) vars)))
(dolist (declspec declspecs)
(when (eq (first declspec) 'TYPE)
; declspec is of form (TYPE type . vars)
(let* ((type (second declspec))
(dtype (type-for-discrimination type))
h)
(cond ((typep 'NIL dtype)) ; OK
((or (typep (setq h '0) dtype) (typep (setq h '0.0) dtype))
(dolist (var (cddr declspec))
(setf (second (find var bindings :key #'first)) h)))
(t (setf (second declspec) `(OR NULL ,type)))))))
bindings))
;; A loop-initialization describes at macro expansion time the task
;; to initialise one or more variables. The initialization may end up
;; generating code in the prologue or in the inner loop.
(defstruct (loop-initialization
(:copier nil)
(:conc-name "LI-")
(:predicate nil)
(:constructor make-loop-init))
;; How to generate the Lisp code.
specform ; special form: LET or MULTIPLE-VALUE-BIND or PROGN
bindings ; for LET: list of bindings,
; for MULTIPLE-VALUE-BIND: varlist and form
declspecs ; list of declspecs
(endtest-forms nil) ; more forms to be inserted after the declarations,
; within the tagbody.
;; Properties of this initialization.
everytime ; If the assignment has to be evaluated in the prologue only: NIL.
; If the assignment has to be evaluated once for each iteration:
; a cons, pointing at the right place in the stepafter-code.
(requires-stepbefore nil) ; True if the variables can get their values only
; in the stepbefore-code or preamble,
; false if the first assignment can be merged
; with the initial binding.
(depends-preceding nil) ; True if everytime=NIL and the values may depend
; on preceding variables, so that these preceding
; variables must get their values no later than in
; the preamble (= prologue + startup)
preamble ; cons = location in preamble
(later-depend nil)) ; True if some later variables depend on these values,
; so that these values
; must be computed no later than in the preamble.
(proclaim '(inline li-vars))
(defun li-vars (li)
(case (li-specform li)
((MULTIPLE-VALUE-BIND) (first (li-bindings li)))
((LET) (mapcar #'first (li-bindings li)))))
; (wrap-initializations initializations form) wickelt eine (umgedrehte!)
; Liste von Initialisierungen um form herum und liefert die neue Form.
(defun wrap-initializations (initializations form)
(dolist (initialization initializations)
(let ((name (li-specform initialization))
(bindings (li-bindings initialization))
(declarations (li-declspecs initialization)))
(setq form
`(,name
,@(case name (MULTIPLE-VALUE-BIND bindings) (LET `(,bindings)))
,@(if declarations `((DECLARE ,@declarations)))
,@(li-endtest-forms initialization)
,form))))
form)
;; Variable containing the last test result, called "it".
(defvar *last-it*)
;; Flag whether this variable is used.
(defvar *used-it*)
;;; (revadd a b c d)) ==
;;; (SETF A (REVAPPEND B (REVAPPEND C (REVAPPEND D A))))
(defmacro revadd (place &rest forms)
(labels ((expand (rest)
(if rest `(revappend ,(car rest) ,(expand (cdr rest))) place)))
`(setf ,place ,(expand forms))))
;; The bulk of the expander.
(defun expand-loop (*whole* body)
(let ((body-rest body) ; alle Parse-Funktionen verkürzen body-rest
(block-name 'NIL) ; Name des umgebenden BLOCKs
(already-within-main nil) ; im zweiten Teil von {variables}* {main}* ?
(*helpvars* (make-array 1 :fill-pointer 0 :adjustable t))
(*last-it* nil)
(var-list nil) ; all variables seen so far
(acculist-var nil) ; Akkumulationsvariable für collect, append etc.
(accuvar-tailvar-alist nil) ; alist of (accu-var . tail-var)
(accunum-var nil) ; Akkumulationsvariable für count, sum etc.
(accu-vars-nil nil) ; Akkumulationsvariablen mit Initialwert NIL
(accu-vars-0 nil) ; Akkumulationsvariablen mit Initialwert 0
(accu-table (make-hash-table :warn-if-needs-rehash-after-gc t
:test 'stablehash-eq)) ; var --> clauses
(accu-declarations nil) ; Typdeklarationen (umgedrehte Liste von declspecs)
(initializations nil) ; Bindungen: (init ...) (umgedrehte Liste)
(seen-for-as-= nil) ; schon eine FOR-AS-= Klausel gesehen?
(seen-endtest nil) ; schon eine FOR-AS Klausel mit Abbruchbedingung gesehen?
(preamble nil) ; annotated: ([:INITIALLY|:START] . code) (reversed)
(stepbefore-code nil) ; Code zum Abbruch vor dem Schleifendurchlauf (umgedrehte Liste)
(main-code nil) ; Code im Hauptteil der Schleife (umgedrehte Liste)
(stepafter-code nil) ; Code zur Vorbereitung des nächsten Schleifendurchlaufs (umgedrehte Liste)
(accu-vars-nreverse nil) ; Akkumulationsvariablen, die am Schluss umzudrehen sind
(finally-code nil) ; finally-Code (umgedrehte Liste)
(backward-consing-p ; is backward-consing possible?
(do ((rest *whole* (cdr rest)))
((endp rest) t)
(case (loop-keywordp (car rest))
((NCONC NCONCING APPEND APPENDING)
(unless (eq (loop-keywordp (caddr rest)) 'INTO)
(return nil))))))
(results nil)) ; alist (value-form . (clause list))
(labels
((next-kw () ; Schaut, ob als nächstes ein Keyword kommt.
; Wenn ja, wird es geliefert. Wenn nein, Ergebnis NIL.
(and (consp body-rest) (loop-keywordp (first body-rest))))
(preamble (kind &optional form) (car (push (cons kind form) preamble)))
(cons-forward (form accuvar accufuncsym)
(let ((tailvar
(cdr (or (assoc accuvar accuvar-tailvar-alist)
(car (setq accuvar-tailvar-alist
(acons accuvar
(gensym (symbol-name accuvar))
accuvar-tailvar-alist))))))
(incrementvar (gensym "ADDLIST-")))
(push accuvar accu-vars-nil)
(push tailvar accu-vars-nil)
`(LET ((,incrementvar
,(ecase accufuncsym
(CONS `(LIST ,form))
(REVAPPEND `(COPY-LIST ,form))
(NRECONC `,form))))
(IF ,accuvar
,(case accufuncsym
(CONS `(SETF ,tailvar (SETF (CDR ,tailvar) ,incrementvar)))
(t `(SETF ,tailvar (LAST (RPLACD ,tailvar ,incrementvar)))))
,(case accufuncsym
(CONS `(SETF ,tailvar (SETF ,accuvar ,incrementvar)))
(t `(SETF ,tailvar (LAST (SETF ,accuvar
,incrementvar)))))))))
(compatible-p (kw1 kw2)
;; <http://www.lisp.org/HyperSpec/Body/sec_6-1-3.html>
(let ((ht #,(make-hash-table
:warn-if-needs-rehash-after-gc t
:test 'stablehash-eq
:initial-contents
'((collect . list) (collecting . list)
(append . list) (appending . list)
(nconc . list) (nconcing . list)
(sum . sum-count) (summing . sum-count)
(count . sum-count) (counting . sum-count)
(maximize . max-min) (maximizing . max-min)
(minimize . max-min) (minimizing . max-min)))))
(eq (gethash kw1 ht) (gethash kw2 ht))))
(new-accu-var (var clause)
(let ((others (gethash var accu-table)) bad)
(when (setq bad (find (first clause) others
:key #'first :test-not #'compatible-p))
(error-of-type 'source-program-error
:form *whole* :detail clause
(TEXT "~S: variable ~S is used in incompatible clauses~{ ~A ~S~} and~{ ~A ~S~}")
*whole* var clause bad))
(setf (gethash var accu-table) (cons clause others))))
(new-result (form clause)
(let ((pair (assoc form results :test #'equal)))
(if pair
(push clause (cdr pair))
(push (list form clause) results))
results))
(acculist-var (keyword form)
(or acculist-var
(progn (setq acculist-var (gensym "ACCULIST-VAR-"))
(push acculist-var accu-vars-nil)
(let ((clause (list keyword form)))
(new-accu-var acculist-var clause)
(unless backward-consing-p
(new-result acculist-var clause)))
acculist-var)))
(cons-backward (keyword form) ; accuvar is NIL, accufuncsym is CONS
(let ((accuvar (acculist-var keyword form)))
(new-result `(SYS::LIST-NREVERSE ,accuvar) `(,keyword ,form))
`(SETQ ,accuvar (CONS ,form ,accuvar))))
(parse-kw-p (kw) ; Schaut, ob als nächstes das Keyword kw kommt.
; Wenn ja, wird es übergangen. Wenn nein, Ergebnis NIL.
(and (consp body-rest) (eq (loop-keywordp (first body-rest)) kw)
(progn (pop body-rest) t)))
(parse-form (kw) ; Nach kw: parst expr
(unless (consp body-rest) (loop-syntax-error kw))
(pop body-rest))
(parse-form-or-it (kw) ; Nach kw: parst expr, das auch 'it' sein kann
(unless (consp body-rest) (loop-syntax-error kw))
(let ((form (pop body-rest)))
(if (eq (loop-keywordp form) 'it)
(if *last-it*
(progn (setq *used-it* t) *last-it*)
form)
form)))
(parse-var-typespec () ;; parse var [typespec]
;; return the variable pattern and the list of declspecs
(unless (consp body-rest)
(error-of-type 'source-program-error
:form *whole* :detail body-rest
(TEXT "~S: missing variable.") 'loop))
(let ((pattern (pop body-rest))
(typedecl nil))
(block nil
(unless (consp body-rest) (return))
(case (loop-keywordp (first body-rest))
((NIL) ; no loop keyword ->interpret as typespec
(setq typedecl (pop body-rest))
(unless (simple-type-p typedecl)
(warn (TEXT "~S: After ~S, ~S is interpreted as a type specification")
'loop pattern typedecl)))
((OF-TYPE) ; OF-TYPE -> expect a typespec
(pop body-rest)
(setq typedecl (parse-form 'of-type)))
(T (return))) ; other
(setq typedecl (destructure-type pattern typedecl)))
(values pattern typedecl)))
(parse-progn () ;; parses {expr}* and return the list of forms
(let ((list nil))
(loop
(unless (and (consp body-rest)
(not (loop-keywordp (first body-rest))))
(return))
(push (pop body-rest) list))
(nreverse list)))
(parse-nonempty-progn (kw) ;; after kw: [CLTS] {expr}+ or [CLTL2] {expr}*
(let ((exprs (parse-progn)))
(unless exprs
(if *loop-ansi*
(loop-syntax-error kw)
(warn (TEXT "~S: missing forms after ~A: permitted by CLtL2, forbidden by ANSI CL.") 'loop (symbol-name kw))))
exprs))
(parse-unconditional () ;; parse an unconditional
;; unconditional ::= {do | doing} {expr}*
;; unconditional ::= return expr
;; Returns a lisp form or NIL when no unconditional was parsed.
(let ((kw (next-kw)))
(case kw
((DO DOING)
(pop body-rest)
`(PROGN ,@(parse-nonempty-progn kw)))
((RETURN)
(pop body-rest)
`(RETURN-FROM ,block-name ,(parse-form-or-it kw)))
(t 'NIL))))
(parse-clause () ;; parses a clause
;; clause ::= accumulation | conditional | unconditional
;; accumulation ::= {collect | collecting | append | appending |
;; nconc | nconcing} expr [into var]
;; accumulation ::= {count | counting | sum | summing |
;; maximize | maximizing | minimize |
;; minimizing} expr [into var] [typespec]
;; conditional ::= {if | when | unless} expr clause {and clause}*
;; [else clause {and clause}*] [end]
;; Returns a lisp form or NIL when no clause was parsed.
(or (parse-unconditional)
(let ((kw (next-kw)))
(case kw
((COLLECT COLLECTING APPEND APPENDING NCONC NCONCING)
(pop body-rest)
;; It seems permitted to write
;; (loop ... collect i into c collect (copy-list c))
;; Therefore we must use forward-consing collection
;; (keeping the tail in a separate variable) if the
;; accumulation variable is named, and can use the more
;; efficient backward-consing (with nreverse at the end)
;; only for unnamed accumulation.
;; Also, APPEND/NCONC require forward-consing because
;; REVAPPEND/NRECONC drop the last atom in dotted lists
(let ((form (parse-form-or-it kw))
(accuvar nil)
(accufuncsym
(case kw
((COLLECT COLLECTING) 'CONS)
((APPEND APPENDING) 'REVAPPEND)
((NCONC NCONCING) 'NRECONC))))
(when (parse-kw-p 'into)
(unless (and (consp body-rest)
(symbolp (setq accuvar (pop body-rest))))
(loop-syntax-error 'into)))
(cond (accuvar ; named acc var -> forward-consing.
(cons-forward form accuvar accufuncsym))
((or (eq accufuncsym 'REVAPPEND)
(eq accufuncsym 'NRECONC)
(null backward-consing-p))
;; REVAPPEND/NRECONC now or before
(when backward-consing-p
(error "~s: internal error: backward consing should be illegal!" *whole*))
(cons-forward form (acculist-var kw form)
accufuncsym))
(t ; Unnamed acc var & CONS -> cons-backward
(cons-backward kw form)))))
((COUNT COUNTING SUM SUMMING MAXIMIZE MAXIMIZING
MINIMIZE MINIMIZING)
(pop body-rest)
(let* ((form (parse-form-or-it kw)) (type 'fixnum)
(accuvar nil) (clause (list kw form)))
(when (parse-kw-p 'into)
(unless (and (consp body-rest)
(symbolp (setq accuvar (pop body-rest))))
(loop-syntax-error 'into)))
(unless accuvar
(setq accuvar
(or accunum-var
(setq accunum-var (gensym "ACCUNUM-VAR-"))))
(new-result accuvar clause))
(new-accu-var accuvar clause)
(when (consp body-rest)
(let ((kw2 (loop-keywordp (first body-rest))))
(when (or (not kw2) (eq kw2 'of-type))
(setq type
(if (not kw2) (pop body-rest)
(progn (pop body-rest)
(parse-form 'of-type))))
(case kw
((MAXIMIZE MAXIMIZING MINIMIZE MINIMIZING)
(setq type `(OR NULL ,type)))) ; wegen Startwert NIL
(push `(TYPE ,type ,accuvar) accu-declarations))))
(case kw
((MAXIMIZE MAXIMIZING MINIMIZE MINIMIZING)
(push accuvar accu-vars-nil))
((COUNT COUNTING SUM SUMMING)
(push (list accuvar (coerce 0 type)) accu-vars-0)))
(case kw
((COUNT COUNTING) `(WHEN ,form (INCF ,accuvar)))
((SUM SUMMING) `(SETQ ,accuvar (+ ,accuvar ,form)))
((MAXIMIZE MAXIMIZING) `(SETQ ,accuvar (MAX-IF ,form ,accuvar)))
((MINIMIZE MINIMIZING) `(SETQ ,accuvar (MIN-IF ,form ,accuvar))))))
((IF WHEN UNLESS)
(pop body-rest)
(let* ((condition (parse-form kw))
(it-var (gensym "IT-"))
used-it
(true-form
(let ((*last-it* it-var) (*used-it* nil))
(prog1
(parse-clauses kw)
(setq used-it *used-it*))))
(false-form 'NIL))
(when (parse-kw-p 'else)
(setq false-form
(let ((*last-it* it-var) (*used-it* nil))
(prog1
(parse-clauses 'else)
(setq used-it (or used-it *used-it*))))))
(parse-kw-p 'end)
(when used-it
(psetq it-var `((,it-var ,condition))
condition it-var))
(let ((form
`(IF ,(if (eq kw 'UNLESS)
`(NOT ,condition) ; UNLESS
`,condition) ; IF, WHEN
,true-form
,false-form)))
(if used-it `(LET ,it-var ,form) `,form))))
(t 'NIL)))))
(parse-clauses (kw) ; Nach kw: parst clause {and clause}*
; oder kurz {clause}+{and}
; Liefert eine Lisp-Form.
(let ((clauses nil))
(loop
(let ((clause (parse-clause)))
(unless clause (loop-syntax-error kw))
(push clause clauses))
(unless (parse-kw-p 'and) (return))
(setq kw 'and)
(setq *last-it* nil)) ; 'it' ist nur in der ersten Klausel gültig
`(PROGN ,@(nreverse clauses))))
; Binden und Initialisieren von Variablen:
; Nach ANSI-CL 6.1.1.4 gelten zwei Grundregeln:
; - Beim Initialisieren von FOR-AS Variablen (außer FOR-AS-=) sind
; mindestens alle vorherigen FOR-AS Variablen sichtbar.
; - Beim Initialisieren von FOR-AS-= Variablen sind alle FOR-AS Variablen
; sichtbar.
; Zusätzlich ist die folgende Grundregel wünschenswert:
; - Beim Initialisieren von FOR-AS-= Variablen sind mindestens alle
; vorherigen FOR-AS Variablen initialisiert und deren Abbruch-
; bedingungen abgeprüft.
; Man könnte erst alle Variablen binden und dann im preamble
; die Initialisierungen durchführen. Wir führen demgegenüber zwei
; Optimierungen durch:
; - Falls vor der FOR-AS Variablen keine FOR-AS-= Klausel kommt,
; braucht die Variable zum Zeitpunkt ihrer Initialisierung nicht
; sichtbar zu sein, und wir verlagern ihre Initialisierung nach
; vorne, zur Bindung. Das geht aber nur, wenn vor der FOR-AS Variablen
; keine FOR-AS Klausel mit Abbruchbedingung kommt.
; - Falls eine Variable gar nicht sichtbar zu sein braucht, weil keine
; FOR-AS-= Klausel vorkommt und hinter ihr auch keine andere FOR-AS
; Klausel stört, können die Bindung und die Initialiserung der
; Variablen ins Schleifeninnere verschoben werden.
(note-initialization (initialization)
(when (or (li-bindings initialization)
(li-declspecs initialization)
(li-endtest-forms initialization))
(when seen-for-as-=
(setf (li-requires-stepbefore initialization) t))
(when (li-endtest-forms initialization)
(setq seen-endtest t))
(dolist (var (li-vars initialization))
(when (memq var var-list)
(error-of-type 'source-program-error
:form *whole* :detail var
(TEXT "~S: duplicate iteration variable ~S") *whole* var))
(push var var-list))
(push initialization initializations)))
(make-endtest (endtest-form)
(make-loop-init
:specform 'PROGN
:bindings nil
:declspecs nil
:endtest-forms (list endtest-form)
:everytime (setq stepafter-code (cons 'NIL stepafter-code))
:preamble (preamble :start)
:requires-stepbefore seen-endtest)))
;; Los geht's!
; parst: [named name]
(when (parse-kw-p 'named)
(unless (and (consp body-rest) (symbolp (first body-rest)))
(loop-syntax-error 'named))
(setq block-name (pop body-rest)))
(loop
; main ::= clause | termination | initially | finally |
; with | for-as | repeat
; termination ::= {while | until | always | never | thereis} expr
; initially ::= initially {expr}*
; finally ::= finally { unconditional | {expr}* }
; with ::= with {var-typespec [= expr]}+{and}
; for-as ::= {for | as} {var-typespec ...}+{and}
; repeat ::= repeat expr
(unless (consp body-rest) (return))
(let ((clause (parse-clause)))
(if clause
(progn (setq already-within-main t) (push clause main-code))
(let ((kw (loop-keywordp (first body-rest))))
(case kw
((WHILE UNTIL ALWAYS NEVER THEREIS)
(pop body-rest)
(setq already-within-main t)
(let ((form (parse-form kw)))
(push (case kw
(WHILE `(UNLESS ,form (LOOP-FINISH)))
(UNTIL `(WHEN ,form (LOOP-FINISH)))
(ALWAYS
(new-result 'T (list kw form))
`(UNLESS ,form (RETURN-FROM ,block-name 'NIL)))
(NEVER
(new-result 'T (list kw form))
`(WHEN ,form (RETURN-FROM ,block-name 'NIL)))
(THEREIS
(let ((dummy (gensym "THEREIS-")))
(new-result 'NIL (list kw form))
`(BLOCK ,dummy
(RETURN-FROM ,block-name
(OR ,form (RETURN-FROM ,dummy NIL)))))))
main-code)))
((INITIALLY)
(pop body-rest)
(preamble :INITIALLY `(PROGN ,@(parse-nonempty-progn kw))))
((FINALLY)
(pop body-rest)
(push (let ((form (parse-unconditional)))
(if form
(if *loop-ansi*
(loop-syntax-error 'FINALLY)
(warn (TEXT "~S: loop keyword immediately after ~A: permitted by CLtL2, forbidden by ANSI CL.") 'loop (symbol-name kw)))
(setq form `(PROGN ,@(parse-nonempty-progn kw))))
form)
finally-code))
((WITH FOR AS REPEAT)
(pop body-rest)
(when already-within-main
(warn (TEXT "~S: ~A clauses should occur before the loop's main body")
'loop (symbol-name kw)))
(case kw
((WITH)
(let ((bindings nil)
(declspecs nil))
(loop
(let (new-bindings)
(multiple-value-bind (pattern new-declspecs) (parse-var-typespec)
(if (parse-kw-p '=)
; Initialisierungsform angegeben.
(let ((form (parse-form '=)))
(setq new-bindings (destructure pattern form)))
; keine Initialisierungsform angegeben.
(setq new-bindings (default-bindings (destructure-vars pattern) new-declspecs)))
(setq bindings (revappend new-bindings bindings))
(setq declspecs (revappend new-declspecs declspecs))))
(unless (parse-kw-p 'and) (return))
(setq kw 'and))
(note-initialization
(make-loop-init
:specform 'LET
:bindings (nreverse bindings)
:declspecs (nreverse declspecs)
:everytime nil
;; WITH vars should always be bound on top
:requires-stepbefore nil ; seen-endtest
:preamble (preamble :start)
:depends-preceding t))))
((FOR AS)
; for-as ::= {for | as} for-as-clause {and [{for | as}] for-as-clause}*
; for-as-clause ::= var-typespec
; [{from | downfrom | upfrom} expr]
; [{to | downto | upto | below | above} expr]
; [by expr]
; for-as-clause ::= var-typespec {in | on} expr [by expr]
; for-as-clause ::= var-typespec = expr [then expr]
; for-as-clause ::= var-typespec across expr
; for-as-clause ::= var-typespec being {each | the}
; {hash-key[s] | hash-value[s]}
; {in | of} expr
; [using ( {hash-value | hash-key} var ) ]
; for-as-clause ::= var-typespec being {each | the}
; {symbol[s] | present-symbol[s] | internal-symbol[s] | external-symbol[s]}
; {in | of} expr
(let ((bindings nil)
(declspecs nil)
(initializations nil)
(stepafter nil)
(old-seen-endtest seen-endtest)
;; remember the _CURRENT_ location in preamble
(preamble-entry (preamble :start))
(depends-preceding nil))
(flet ((note-initialization (initialization)
;; supersedes the outer definition!
;; Calls to note-initialization must temporarily be suspended.
(when (li-endtest-forms initialization)
(setq seen-endtest t))
(push initialization initializations)))
(loop
(multiple-value-bind (pattern new-declspecs) (parse-var-typespec)
(let ((preposition (next-kw)))
(case preposition
((IN ON)
(pop body-rest)
(let ((start-form (parse-form preposition))
(step-function-form '(FUNCTION CDR))
(step-function-var nil))
(when (parse-kw-p 'by)
(setq step-function-form (parse-form 'by))
(unless (and (function-form-p step-function-form)
(function-name-p (second step-function-form)))
(setq step-function-var (gensym "BY-"))))
(let ((var (if (and pattern (symbolp pattern)
(eq preposition 'ON))
pattern (gensym "LIST-"))))
(push `(,var ,start-form) bindings)
(when step-function-var
(push `(,step-function-var ,step-function-form)
bindings))
(note-initialization
(make-endtest
`(WHEN (,(if (eq preposition 'IN)
'ENDP 'ATOM)
,var)
(LOOP-FINISH))))
(unless (eq var pattern)
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure pattern (if (eq preposition 'IN) `(CAR ,var) var))
:declspecs new-declspecs
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest)))
(push
(list var
(if step-function-var
`(FUNCALL ,step-function-var ,var)
`(,(second step-function-form) ,var)))
stepafter))))
(=
(pop body-rest)
(let* ((first-form (parse-form 'preposition))
(then-form first-form))
(when (parse-kw-p 'then)
(setq then-form (parse-form 'then)))
(setq bindings
(revappend (destructure pattern first-form)
bindings))
(setq declspecs (revappend new-declspecs declspecs))
(unless (and (constantp first-form)
(constantp then-form))
(setq seen-for-as-= t)
;; Even when `first-form' is constant but
;; `then-form' is not, we must set
;; `depends-preceding', because the
;; `stepafter-code' depends on the order of
;; the steppings, which forbids moving
;; some code from `preamble' +
;; `stepafter-code' to `stepbefore-code.'
(setq depends-preceding t))
(setq stepafter (revappend (destructure pattern then-form) stepafter))))
(ACROSS
(pop body-rest)
(let ((vector-form (parse-form preposition))
(vector-var (gensym "VECTOR-"))
(index-var (gensym "INDEX-")))
(push `(,vector-var ,vector-form) bindings)
(push `(,index-var 0) bindings)
(note-initialization
(make-endtest `(WHEN (>= ,index-var (LENGTH ,vector-var)) (LOOP-FINISH))))
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure pattern `(AREF ,vector-var ,index-var))
:declspecs new-declspecs
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))
(push (list index-var `(1+ ,index-var)) stepafter)))
(BEING
(pop body-rest)
(let ((plural (next-kw)))
(case plural
((EACH THE))
(t (loop-syntax-error 'being)))
(pop body-rest)
(let ((preposition (next-kw)))
(case preposition
((HASH-KEY HASH-VALUE
SYMBOL PRESENT-SYMBOL INTERNAL-SYMBOL EXTERNAL-SYMBOL)
(when (eq plural 'THE)
(warn (TEXT "~S: After ~S a plural loop keyword is required, not ~A")
'loop plural (symbol-name preposition))))
((HASH-KEYS HASH-VALUES
SYMBOLS PRESENT-SYMBOLS INTERNAL-SYMBOLS EXTERNAL-SYMBOLS)
(when (eq plural 'EACH)
(warn (TEXT "~S: After ~S a singular loop keyword is required, not ~A")
'loop plural (symbol-name preposition))))
(t (loop-syntax-error plural)))
(pop body-rest)
(case preposition
((HASH-KEY HASH-KEYS HASH-VALUE HASH-VALUES)
(let ((other-pattern nil)
(form
(case (next-kw)
((IN OF) (pop body-rest)
(parse-form preposition))
(t (loop-syntax-error
preposition)))))
(when (parse-kw-p 'using)
(unless (and (consp body-rest)
(consp (car body-rest))
(consp (cdar body-rest))
(null (cddar body-rest))
(case (loop-keywordp (caar body-rest))
((HASH-KEY HASH-KEYS)
(case preposition
((HASH-VALUE HASH-VALUES) t) (t nil)))
((HASH-VALUE HASH-VALUES)
(case preposition
((HASH-KEY HASH-KEYS) t) (t nil)))))
(loop-syntax-error 'using))
(setq other-pattern (second (pop body-rest))))
(let ((state-var (gensym "WHTI-"))
(nextp-var (gensym "MORE?"))
(nextkey-var (gensym "HASH-KEY-"))
(nextvalue-var (gensym "HASH-VALUE-")))
(multiple-value-bind (nextmain-var nextother-var)
(case preposition
((HASH-KEY HASH-KEYS) (values nextkey-var nextvalue-var))
((HASH-VALUE HASH-VALUES) (values nextvalue-var nextkey-var)))
(push `(,state-var (SYS::HASH-TABLE-ITERATOR ,form)) bindings)
(note-initialization
(make-loop-init
:specform 'MULTIPLE-VALUE-BIND
:bindings `((,nextp-var ,nextkey-var ,nextvalue-var)
(SYS::HASH-TABLE-ITERATE ,state-var))
:declspecs (unless other-pattern `((IGNORE ,nextother-var)))
:endtest-forms `((UNLESS ,nextp-var (LOOP-FINISH)))
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure pattern nextmain-var)
:declspecs new-declspecs
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))
(when other-pattern
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure other-pattern nextother-var)
:declspecs nil
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest)))))))
((SYMBOL SYMBOLS PRESENT-SYMBOL PRESENT-SYMBOLS
INTERNAL-SYMBOL INTERNAL-SYMBOLS EXTERNAL-SYMBOL EXTERNAL-SYMBOLS)
(let ((flags (case preposition
((SYMBOL SYMBOLS) '(:internal :external :inherited))
((PRESENT-SYMBOL PRESENT-SYMBOLS) '(:internal :external))
((INTERNAL-SYMBOL INTERNAL-SYMBOLS) '(:internal))
((EXTERNAL-SYMBOL EXTERNAL-SYMBOLS) '(:external))))
(state-var (gensym "WPI-"))
(nextp-var (gensym "MORE?"))
(nextsym-var (gensym "SYMBOL-"))
(form
(case (next-kw)
((IN OF) (pop body-rest)
(parse-form preposition))
(t '*package*))))
(push `(,state-var (SYS::PACKAGE-ITERATOR ,form ',flags))
bindings)
(note-initialization
(make-loop-init
:specform 'MULTIPLE-VALUE-BIND
:bindings `((,nextp-var ,nextsym-var)
(SYS::PACKAGE-ITERATE ,state-var))
:declspecs nil
:endtest-forms `((UNLESS ,nextp-var (LOOP-FINISH)))
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))
(note-initialization
(make-loop-init
:specform 'LET
:bindings (destructure pattern nextsym-var)
:declspecs new-declspecs
:everytime t
:preamble (preamble :start)
:requires-stepbefore seen-endtest))))))))
(t
(unless (symbolp pattern) (loop-syntax-error kw))
(unless pattern (setq pattern (gensym "FOR-NUM-")))
;; ANSI CL 6.1.2.1.1 implies that the
;; start/end/by clauses can come in any
;; order, but only one of each kind.
(let ((step-start-p nil)
(step-end-p nil)
(step-by-p nil)
step-start-form
step-end-form
step-by-form
step-end-preposition
dir)
(loop
(cond ((and (not step-start-p)
(setq dir (case preposition
(FROM 't)
(UPFROM 'up)
(DOWNFROM 'down)
(t nil))))
(setq step-start-p dir)
(pop body-rest)
(setq step-start-form (parse-form preposition))
(push `(,pattern ,step-start-form) bindings))
((and (not step-end-p)
(setq dir (case preposition
(TO 't)
((UPTO BELOW) 'up)
((DOWNTO ABOVE) 'down)
(t nil))))
(setq step-end-p dir)
(setq step-end-preposition preposition)
(pop body-rest)
(setq step-end-form (parse-form preposition))
(unless (constantp step-end-form)
(let ((step-end-var (gensym "LIMIT-")))
(push `(,step-end-var ,step-end-form) bindings)
(setq step-end-form step-end-var))))
((and (not step-by-p)
(eq preposition 'BY))
(setq step-by-p t)
(pop body-rest)
(setq step-by-form (parse-form 'by))
(unless (constantp step-by-form)
(let ((step-by-var (gensym "BY-")))
(push `(,step-by-var ,step-by-form) bindings)
(setq step-by-form step-by-var))))
(t (return)))
(setq preposition (next-kw)))
;; All parsing done, gather the declarations:
(setq declspecs (revappend new-declspecs declspecs))
;; Determine the direction of iteration:
(let ((step-direction
(if (or (eq step-start-p 'down) (eq step-end-p 'down))
(if (or (eq step-start-p 'up) (eq step-end-p 'up))
(error-of-type 'source-program-error
:form *whole* :detail kw
(TEXT "~S: questionable iteration direction after ~A")
'loop (symbol-name kw))
'down)
'up)))
;; Determine start, unless given:
(unless step-start-p
(when (eq step-direction 'down)
; Abwärtsiteration ohne Startwert ist nicht erlaubt.
; Die zweite optionale Klausel (d.h. preposition) muss abwärts zeigen.
(error-of-type 'source-program-error
:form *whole* :detail preposition
(TEXT "~S: specifying ~A requires FROM or DOWNFROM")
'loop (symbol-name preposition)))
; Aufwärtsiteration -> Startwert 0
(setq step-start-form '0)
(push `(,pattern ,step-start-form) bindings))
; Determine step, unless given:
(unless step-by-p (setq step-by-form '1))
; Determine end test:
(when step-end-p
(let* ((compfun
(if (eq step-direction 'up)
(if (eq step-end-preposition 'below) '>= '>) ; up
(if (eq step-end-preposition 'above) '<= '<))) ; down
(endtest
(if (and (constantp step-end-form) (zerop (eval step-end-form)))
(case compfun
(>= `(NOT (MINUSP ,pattern)))
(> `(PLUSP ,pattern))
(<= `(NOT (PLUSP ,pattern)))
(< `(MINUSP ,pattern)))
`(,compfun ,pattern ,step-end-form))))
(note-initialization
(make-endtest `(WHEN ,endtest (LOOP-FINISH))))))
(push
(list pattern `(,(if (eq step-direction 'up) '+ '-) ,pattern ,step-by-form))
stepafter)))))))
(unless (parse-kw-p 'and) (return))
(setq kw 'and)
(case (next-kw) ((FOR AS) (pop body-rest)))))
(when (setq stepafter (apply #'append (nreverse stepafter)))
(push `(PSETQ ,@stepafter) stepafter-code))
(push 'NIL stepafter-code) ; Markierung für spätere Initialisierungen
(note-initialization ; outer `note-initialization'!
(make-loop-init
:specform 'LET
:bindings (nreverse bindings)
:declspecs (nreverse declspecs)
:everytime nil
:requires-stepbefore old-seen-endtest
:preamble preamble-entry
:depends-preceding depends-preceding))
(dolist (initialization (nreverse initializations))
(when (li-everytime initialization)
(setf (li-everytime initialization) stepafter-code))
(note-initialization initialization))))
((REPEAT)
(let ((form (parse-form kw))
(var (gensym "COUNT-")))
(note-initialization
(make-loop-init
:specform 'LET
:bindings `((,var ,form))
:declspecs nil
:everytime nil
:requires-stepbefore seen-endtest
:preamble (preamble :start)
:depends-preceding t))
(push `(SETQ ,var (1- ,var)) stepafter-code)
(note-initialization
(make-endtest `(UNLESS (PLUSP ,var) (LOOP-FINISH))))))))
(t (error-of-type 'source-program-error
:form *whole* :detail *whole*
(TEXT "~S: illegal syntax near ~S in ~S")
'loop (first body-rest) *whole*)))))))
; Noch einige semantische Tests:
(when (> (length results) 1)
(error-of-type 'source-program-error
:form *whole* :detail *whole*
(TEXT "~S: ambiguous result:~:{~%~S from ~@{~{~A ~S~}~^, ~}~}")
*whole* results))
(unless (null results)
(push `(RETURN-FROM ,block-name ,(caar results)) finally-code))
; Initialisierungen abarbeiten und optimieren:
(let ((initializations1
(unless (zerop (length *helpvars*))
;; `*helpvars*' must be bound first thing
(list (make-loop-init
:specform 'LET
:preamble (preamble :start)
:bindings
(map 'list #'(lambda (var) `(,var NIL)) *helpvars*))))))
; `depends-preceding' backpropagation:
(let ((later-depend nil))
(dolist (initialization initializations)
(when later-depend (setf (li-later-depend initialization) t))
(when (li-depends-preceding initialization)
(setq later-depend t))))
(dolist (initialization (nreverse initializations))
(let* ((everytime (li-everytime initialization))
(requires-stepbefore (li-requires-stepbefore initialization))
(name (li-specform initialization))
(bindings (li-bindings initialization))
(declarations (li-declspecs initialization))
(vars (case name
(MULTIPLE-VALUE-BIND (first bindings))
(LET (mapcar #'first bindings))))
(initforms
(case name
(MULTIPLE-VALUE-BIND `((MULTIPLE-VALUE-SETQ ,@bindings)))
(LET `((SETQ ,@(apply #'append bindings))))
(t '())))
(endtest-forms (li-endtest-forms initialization)))
(if requires-stepbefore
; wegen seen-for-as-= oder AREF nicht optimierbar
(progn
(push
(make-loop-init
:specform 'LET
:bindings (default-bindings vars declarations)
:preamble (preamble :start)
:declspecs declarations)
initializations1)
(if everytime
(if (li-later-depend initialization)
(progn ; double code: preamble and stepafter-code
(revadd (cdr (li-preamble initialization))
endtest-forms initforms)
(revadd (cdr everytime) endtest-forms initforms))
(revadd stepbefore-code endtest-forms initforms))
(revadd (cdr (li-preamble initialization))
endtest-forms initforms)))
; Initialisierungsklausel nach initializations1 schaffen:
(progn
(push
(make-loop-init
:specform name
:bindings bindings
:preamble (preamble :start)
:declspecs declarations)
initializations1)
(if everytime
(progn
; put the initforms into the stepafter-code only.
(revadd (cdr everytime) initforms)
; handle the endtest-forms.
(if (li-later-depend initialization)
(progn ; double endtest: preamble and stepafter-code
(revadd (cdr (li-preamble initialization))
endtest-forms)
(revadd (cdr everytime) endtest-forms))
(revadd stepbefore-code endtest-forms)))
(revadd (cdr (li-preamble initialization)) endtest-forms))))))
(flet ((check-accu-var (var)
(when (memq var var-list)
(error-of-type 'source-program-error
:form *whole* :detail var
(TEXT "~S: accumulation variable ~S is already bound")
*whole* var))))
(push
(make-loop-init
:specform 'LET
:bindings
`(,@(mapcar #'(lambda (var) (check-accu-var var) `(,var NIL))
(delete-duplicates accu-vars-nil))
,@(mapcar #'(lambda (var) (check-accu-var (car var)) var)
(delete-duplicates accu-vars-0 :key #'car)))
:preamble (preamble :start)
:declspecs (nreverse accu-declarations))
initializations1))
(setq preamble
(mapcan (lambda (rec)
(case (car rec)
(:start (nreverse
(mapcar (lambda (f) (cons :start f))
(cdr rec))))
(:initially (list rec))))
preamble))
;; Remove the NIL placeholders in stepafter-code.
(setq stepafter-code (delete 'NIL stepafter-code))
;; If preamble and stepafter-code both end in the same
;; forms, drag these forms across the label to stepbefore-code.
(flet ((form-eq (form1 form2) ; Calling EQUAL on user-given forms would be wrong
(or (eql form1 form2)
(and (consp form1) (consp form2)
(eql (length form1) (length form2))
(or (eq (car form1) (car form2))
(and (case (length form1) ((1 3) t))
(case (car form1) ((SETQ PSETQ) t))
(case (car form2) ((SETQ PSETQ) t))))
(every #'eq (cdr form1) (cdr form2))))))
(loop
(unless (and (consp preamble) (consp stepafter-code)
(eq :start (caar preamble))
(form-eq (cdar preamble) (car stepafter-code)))
(return))
(setq stepbefore-code
(nconc stepbefore-code (list (pop stepafter-code))))
(pop preamble)))
;; Final macroexpansion.
`(MACROLET ((LOOP-FINISH () (LOOP-FINISH-ERROR)))
(BLOCK ,block-name
,(wrap-initializations initializations1
`(MACROLET ((LOOP-FINISH () '(GO END-LOOP)))
(TAGBODY
,@(if preamble (nreverse (mapcar #'cdr preamble)))
BEGIN-LOOP
,@(if stepbefore-code (nreverse stepbefore-code))
,(cons 'PROGN (nreverse main-code))
,@(if stepafter-code (nreverse stepafter-code))
(GO BEGIN-LOOP)
END-LOOP
,@(mapcar #'(lambda (var)
`(SETQ ,var (SYS::LIST-NREVERSE ,var)))
accu-vars-nreverse)
(MACROLET ((LOOP-FINISH () (LOOP-FINISH-WARN)
'(GO END-LOOP)))
,@(nreverse finally-code)))))))))))
;; Der eigentliche Macro:
(defmacro loop (&whole whole &body body)
(if (some #'atom body)
;; "extended" loop form
(expand-loop whole body)
;; "simple" loop form
(let ((tag (gensym "LOOP-")))
`(BLOCK NIL (TAGBODY ,tag ,@body (GO ,tag))))))
(defmacro loop-finish (&whole whole)
(error (TEXT "~S is possible only from within ~S")
whole 'loop))
(defun loop-finish-warn ()
(warn (TEXT "Use of ~S in FINALLY clauses is deprecated because it can lead to infinite loops.")
'(loop-finish)))
(defun loop-finish-error ()
(error (TEXT "~S is not possible here")
'(loop-finish)))
;; Run-Time-Support:
(defun max-if (x y) ; ABI
(if y (max x y) x))
(defun min-if (x y) ; ABI
(if y (min x y) x))
| 65,803 | Common Lisp | .lisp | 1,152 | 33.741319 | 149 | 0.438843 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | e155f5f0ec851cf22bd6e55c7d8b427cdc35266e939540bb075809f603eec51d | 11,378 | [
-1
] |
11,379 | clos-methcomb3.lisp | ufasoft_lisp/clisp/clos-methcomb3.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Method Combination
;;;; Part n-2: make/initialize-instance methods.
;;;; Bruno Haible 2004-06-10
(in-package "CLOS")
;;; Lift the initialization protocol.
(defmethod initialize-instance ((combination method-combination) &rest args
&key name
documentation
check-options
expander
check-method-qualifiers
call-next-method-allowed
declarations
qualifiers
operator
identity-with-one-argument
long-expander
arguments-lambda-list
options)
(declare (ignore name documentation check-options expander
check-method-qualifiers call-next-method-allowed
declarations qualifiers operator identity-with-one-argument
long-expander arguments-lambda-list options))
(apply #'initialize-instance-<method-combination> combination args))
(defmethod reinitialize-instance ((instance method-combination) &rest initargs)
(declare (ignore initargs))
(error (TEXT "~S: It is not allowed to reinitialize ~S")
'reinitialize-instance instance))
| 1,528 | Common Lisp | .lisp | 29 | 32.103448 | 79 | 0.516064 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | a1412de84d32f877f0fe15a4a243dc4390f7a83298f8fd099dda6addbf5be5c4 | 11,379 | [
-1
] |
11,380 | clos-slots1.lisp | ufasoft_lisp/clisp/clos-slots1.lisp | ;;;; Common Lisp Object System for CLISP: Slots
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
#||
;; The access functions could look like this, if we use
;; SLOT-VALUE-USING-CLASS.
;; Access to the slots of objects of the metaclass <standard-class>.
;; Note that all functions that refer to #<UNBOUND> must be compiled.
(defun std-slot-value (instance slot-name)
(declare (compile))
(let* ((class (class-of instance))
(slot-location (gethash slot-name (class-slot-location-table class))))
((lambda (value)
(if (eq value unbound)
(slot-unbound class instance slot-name)
value))
(cond ((null slot-location)
(slot-missing class instance slot-name 'slot-value))
((atom slot-location) ; access local slot
(sys::%record-ref instance slot-location))
(t ; access shared slot
(svref (cv-shared-slots (car slot-location))
(cdr slot-location)))))))
(defun std-setf-slot-value (instance slot-name new-value)
(let* ((class (class-of instance))
(slot-location (gethash slot-name (class-slot-location-table class))))
(cond ((null slot-location)
(slot-missing class instance slot-name 'setf new-value))
((atom slot-location) ; access local slot
(sys::%record-store instance slot-location new-value))
(t ; access shared slot
(setf (svref (cv-shared-slots (car slot-location))
(cdr slot-location))
new-value)))))
(defun std-slot-boundp (instance slot-name)
(declare (compile))
(let* ((class (class-of instance))
(slot-location (gethash slot-name (class-slot-location-table class))))
(cond ((null slot-location)
(slot-missing class instance slot-name 'slot-boundp))
((atom slot-location) ; access local slot
(not (eq (sys::%record-ref instance slot-location) unbound)))
(t ; access shared slot
(not (eq (svref (cv-shared-slots (car slot-location))
(cdr slot-location))
unbound))))))
(defun std-slot-makunbound (instance slot-name)
(declare (compile))
(let* ((class (class-of instance))
(slot-location (gethash slot-name (class-slot-location-table class))))
(cond ((null slot-location)
(slot-missing class instance slot-name 'slot-makunbound))
((atom slot-location) ; access local slot
(sys::%record-store instance slot-location unbound))
(t ; access shared slot
(setf (svref (cv-shared-slots (car slot-location))
(cdr slot-location))
unbound)))))
(defun std-slot-exists-p (instance slot-name)
(and (gethash slot-name (class-slot-location-table (class-of instance))) t))
;; General access to slots:
(defun slot-value (object slot-name)
(let ((class (class-of object)))
;; Treat metaclass <standard-class> separately for efficiency reasons
;; and because of bootstrapping.
(if (eq (class-of class) <standard-class>)
(std-slot-value object slot-name)
(slot-value-using-class class object slot-name))))
(defun (setf slot-value) (new-value object slot-name)
(let ((class (class-of object)))
;; Treat metaclass <standard-class> separately for efficiency reasons
;; and because of bootstrapping.
(if (eq (class-of class) <standard-class>)
(std-setf-slot-value object slot-name new-value)
(setf-slot-value-using-class new-value class object slot-name))))
(defun slot-boundp (object slot-name)
(let ((class (class-of object)))
;; Treat metaclass <standard-class> separately for efficiency reasons
;; and because of bootstrapping.
(if (eq (class-of class) <standard-class>)
(std-slot-boundp object slot-name)
(slot-boundp-using-class class object slot-name))))
(defun slot-makunbound (object slot-name)
(let ((class (class-of object)))
;; Treat metaclass <standard-class> separately for efficiency reasons
;; and because of bootstrapping.
(if (eq (class-of class) <standard-class>)
(std-slot-makunbound object slot-name)
(slot-makunbound-using-class class object slot-name))))
(defun slot-exists-p (object slot-name)
(let ((class (class-of object)))
;; Treat metaclass <standard-class> separately for efficiency reasons
;; and because of bootstrapping.
(if (eq (class-of class) <standard-class>)
(std-slot-exists-p object slot-name)
(slot-exists-p-using-class class object slot-name))))
(defun slot-value-using-class (class object slot-name)
(no-slot-error class object slot-name))
(defun setf-slot-value-using-class (new-value class object slot-name)
(declare (ignore new-value))
(no-slot-error class object slot-name))
(defun slot-boundp-using-class (class object slot-name)
(no-slot-error class object slot-name))
(defun slot-makunbound-using-class (class object slot-name)
(no-slot-error class object slot-name))
(defun slot-exists-p-using-class (class object slot-name)
(no-slot-error class object slot-name))
(defun no-slot-error (class object slot-name)
(declare (ignore slot-name))
(error-of-type 'error
(TEXT "instance ~S of class ~S has no slots (wrong metaclass)")
object class))
||#
;; For efficiency - we want to circumvent the test for <standard-class> -,
;; all classes (no matter if standard- or built-in-) get a
;; slot-location-table.
;; Furthermore, we can deal here with unbound only very badly.
;; Hence,
;; slot-value, set-slot-value, slot-boundp, slot-makunbound, slot-exists-p
;; are now contained already in RECORD.D.
(defsetf slot-value set-slot-value)
;; WITH-SLOTS
(defmacro with-slots (&whole whole-form
slot-entries instance-form &body body)
(let ((vars '())
(slots '()))
(unless (listp slot-entries)
(error-of-type 'ext:source-program-error
:form whole-form
:detail slot-entries
(TEXT "~S: not a list of slots: ~S")
'with-slots slot-entries))
(dolist (slot slot-entries)
(let ((var slot))
(when (consp slot)
(unless (eql (length slot) 2)
(error-of-type 'ext:source-program-error
:form whole-form
:detail slot
(TEXT "~S: invalid slot and variable specification ~S")
'with-slots slot))
(setq var (first slot) slot (second slot))
(unless (symbolp var)
(error-of-type 'ext:source-program-error
:form whole-form
:detail var
(TEXT "~S: variable ~S should be a symbol")
'with-slots var)))
(unless (symbolp slot)
(error-of-type 'ext:source-program-error
:form whole-form
:detail slot
(TEXT "~S: slot name ~S should be a symbol")
'with-slots slot))
(push var vars)
(push slot slots)))
(multiple-value-bind (body-rest declarations) (sys::parse-body body)
(let ((instance-var (gensym)))
`(LET ((,instance-var ,instance-form))
(SYMBOL-MACROLET
,(mapcar #'(lambda (var slot)
`(,var (SLOT-VALUE ,instance-var ',slot)))
(nreverse vars) (nreverse slots))
,@(if declarations `((DECLARE ,@declarations)))
,@body-rest))))))
;; WITH-ACCESSORS
(defmacro with-accessors (&whole whole-form
slot-entries instance-form &body body)
(unless (listp slot-entries)
(error-of-type 'ext:source-program-error
:form whole-form
:detail slot-entries
(TEXT "~S: not a list of slots: ~S")
'with-accessors slot-entries))
(dolist (slot-entry slot-entries)
(unless (and (consp slot-entry) (eql (length slot-entry) 2))
(error-of-type 'ext:source-program-error
:form whole-form
:detail slot-entry
(TEXT "~S: invalid slot and accessor specification ~S")
'with-accessors slot-entry))
(unless (symbolp (first slot-entry))
(error-of-type 'ext:source-program-error
:form whole-form
:detail (first slot-entry)
(TEXT "~S: variable ~S should be a symbol")
'with-accessors (first slot-entry)))
(unless (symbolp (second slot-entry))
(error-of-type 'ext:source-program-error
:form whole-form
:detail (second slot-entry)
(TEXT "~S: accessor name ~S should be a symbol")
'with-accessors (second slot-entry))))
(multiple-value-bind (body-rest declarations) (sys::parse-body body)
(let ((instance-var (gensym)))
`(LET ((,instance-var ,instance-form))
(SYMBOL-MACROLET
,(mapcar #'(lambda (slot-entry)
`(,(first slot-entry)
(,(second slot-entry) ,instance-var)))
slot-entries)
,@(if declarations `((DECLARE ,@declarations)))
,@body-rest)))))
;; Low-level instance access. MOP p. 100, p. 55.
;; In standard-instance-access and funcallable-standard-instance-access,
;; - the instance can be any standard-object instance (funcallable or not),
;; - the instance can be a non-updated obsolete instance,
;; - the location can refer to a local slot or to a shared slot,
;; - when the slot is not bound, #<UNBOUND> is returned.
;; A setter function is also provided.
(setf (fdefinition 'funcallable-standard-instance-access)
#'standard-instance-access)
(system::%put 'funcallable-standard-instance-access 'SYSTEM::SETF-FUNCTION
'|(SETF STANDARD-INSTANCE-ACCESS)|)
| 9,829 | Common Lisp | .lisp | 216 | 37.467593 | 80 | 0.633476 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 2cedcbf09fec545645c69d33f428257c80b10cd4043568057251d77ab2a02460 | 11,380 | [
-1
] |
11,381 | clos-class4.lisp | ufasoft_lisp/clisp/clos-class4.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Class metaobjects
;;;; Part n-2: Final class definitions, make/initialize-instance methods.
;;;; Bruno Haible 2004-05-25
;;;; Sam Steingold 2005
(in-package "CLOS")
;;; ===========================================================================
;;; Lift the initialization protocol.
(defmethod shared-initialize ((class potential-class) situation &rest args
&key name)
(declare (ignore name))
(apply #'shared-initialize-<potential-class> class situation args))
;;; ===========================================================================
(defmethod shared-initialize ((class defined-class) situation &rest args
&key name direct-superclasses direct-slots
direct-default-initargs documentation)
(declare (ignore name direct-superclasses direct-slots
direct-default-initargs documentation))
(apply #'shared-initialize-<defined-class> class situation args))
(defmethod reinitialize-instance ((class defined-class) &rest args
&key &allow-other-keys)
(apply #'reinitialize-instance-<defined-class> class args))
;;; ===========================================================================
(defmethod shared-initialize ((class built-in-class) situation &rest args
&key name direct-superclasses
((prototype prototype) nil))
(declare (ignore name direct-superclasses prototype))
(apply #'shared-initialize-<built-in-class> class situation args))
;;; ===========================================================================
(defmethod shared-initialize ((class structure-class) situation &rest args
&key name direct-superclasses direct-slots
direct-default-initargs documentation
(generic-accessors t)
((direct-slots direct-slots-as-metaobjects) '())
((names names) nil)
((kconstructor kconstructor) nil)
((boa-constructors boa-constructors) '())
((copier copier) nil)
((predicate predicate) nil)
((slots slots) '()) ((size size) 1))
(declare (ignore name direct-superclasses direct-slots
direct-default-initargs documentation generic-accessors
direct-slots-as-metaobjects names kconstructor
boa-constructors copier predicate slots size))
(apply #'shared-initialize-<structure-class> class situation args))
;;; ===========================================================================
(defmethod shared-initialize ((class standard-class) situation &rest args
&key name direct-superclasses direct-slots
direct-default-initargs documentation
(generic-accessors t)
(fixed-slot-locations nil))
(declare (ignore name direct-superclasses direct-slots
direct-default-initargs documentation generic-accessors
fixed-slot-locations))
(apply #'shared-initialize-<standard-class> class situation args))
;;; ===========================================================================
(defmethod shared-initialize ((class funcallable-standard-class) situation &rest args
&key name direct-superclasses direct-slots
direct-default-initargs documentation
(generic-accessors t)
(fixed-slot-locations nil))
(declare (ignore name direct-superclasses direct-slots
direct-default-initargs documentation generic-accessors
fixed-slot-locations))
(apply #'shared-initialize-<funcallable-standard-class> class situation args))
;;; ===========================================================================
;; Now that all the predefined subclasses of <defined-class> have been defined,
;; CLASS-OF can work on all existing <defined-class> instances. Therefore now,
;; not earlier, it's possible to pass these <defined-class> instances to
;; generic functions.
| 4,485 | Common Lisp | .lisp | 70 | 48.728571 | 85 | 0.526148 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 623d718d717224a888a9245dd65eb5b244e6522d89cdc4577ee1d9fd520c6fe4 | 11,381 | [
-1
] |
11,382 | clos-method3.lisp | ufasoft_lisp/clisp/clos-method3.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Methods
;;;; Part n-2: make/initialize-instance methods, generic functions.
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004, 2010
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
;;; Lift the initialization protocol.
(defmethod initialize-instance ((method method) &rest args
&key ((from-defgeneric from-defgeneric) nil)
((backpointer backpointer) nil)
&allow-other-keys)
(declare (ignore from-defgeneric backpointer))
(apply #'initialize-instance-<method> method args))
(defmethod initialize-instance ((method standard-method) &rest args
&key qualifiers
lambda-list
specializers
function
documentation
((fast-function fast-function) nil)
((wants-next-method-p wants-next-method-p) nil)
((signature signature) nil)
((gf gf) nil)
((from-defgeneric from-defgeneric) nil)
((backpointer backpointer) nil)
&allow-other-keys)
(declare (ignore qualifiers lambda-list specializers function documentation
fast-function wants-next-method-p signature gf
from-defgeneric backpointer))
(apply #'initialize-instance-<standard-method> method args))
(defmethod initialize-instance ((method standard-accessor-method) &rest args
&key slot-definition
&allow-other-keys)
(declare (ignore slot-definition))
(apply #'initialize-instance-<standard-accessor-method> method args))
(defmethod reinitialize-instance ((instance method) &rest initargs)
(declare (ignore initargs))
(error (TEXT "~S: The MOP does not allow reinitializing ~S")
'reinitialize-instance instance))
;; MOP p. 82
(fmakunbound 'method-function)
(defgeneric method-function (method)
(:method ((method standard-method))
(std-method-function-or-substitute method)))
(initialize-extended-method-check #'method-function)
;; MOP p. 82
(let ((*allow-making-generic* t))
(defgeneric method-qualifiers (method)
(:method ((method standard-method))
(std-method-qualifiers method))))
(setq |#'method-qualifiers| #'method-qualifiers)
; No extended method check because this GF is specified in ANSI CL.
;(initialize-extended-method-check #'method-qualifiers)
;; MOP p. 82
(fmakunbound 'method-lambda-list)
(defgeneric method-lambda-list (method)
(:method ((method standard-method))
(std-method-lambda-list method)))
(initialize-extended-method-check #'method-lambda-list)
;; Not in MOP.
(let ((*allow-making-generic* t))
(defgeneric method-signature (method)
(:method ((method method))
(let ((lambda-list (method-lambda-list method)))
(method-lambda-list-to-signature lambda-list
#'(lambda (form detail errorstring &rest arguments)
(sys::lambda-list-error form detail
(TEXT "Invalid ~S result for ~S: ~:S: ~A")
'method-lambda-list method lambda-list
(apply #'format nil errorstring arguments))))))
(:method ((method standard-method))
(std-method-signature method))))
;; MOP p. 82
(let ((*allow-making-generic* t))
(defgeneric method-specializers (method)
(:method ((method standard-method))
(std-method-specializers method))))
(setq |#'method-specializers| #'method-specializers)
(initialize-extended-method-check #'method-specializers)
;; MOP p. 82
(let ((*allow-making-generic* t))
(defgeneric method-generic-function (method)
(:method ((method standard-method))
(std-method-generic-function method))))
(initialize-extended-method-check #'method-generic-function)
;; Not in MOP.
(let ((*allow-making-generic* t))
(defgeneric (setf method-generic-function) (new-gf method)
(:method (new-gf (method standard-method))
(setf (std-method-generic-function method) new-gf))))
(defgeneric function-keywords (method)
(:method ((method standard-method))
(let ((sig (method-signature method)))
(values (sig-keywords sig) (sig-allow-p sig)))))
;; MOP p. 82-83
(defgeneric accessor-method-slot-definition (method)
(:method ((method standard-accessor-method))
(%accessor-method-slot-definition method)))
(initialize-extended-method-check #'accessor-method-slot-definition)
| 4,755 | Common Lisp | .lisp | 100 | 37.97 | 84 | 0.633757 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 1436b2607896dd929c3918cdb07a74486df81d35c68a2ce3afa2f369b2b900c2 | 11,382 | [
-1
] |
11,383 | clos-slotdef3.lisp | ufasoft_lisp/clisp/clos-slotdef3.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Slot Definition metaobjects
;;;; Part n-1: Generic functions specified in the MOP.
;;;; Bruno Haible 2004-04-18
(in-package "CLOS")
;; Make creation of <slot-definition> instances customizable.
(setf (fdefinition 'make-instance-<standard-direct-slot-definition>) #'make-instance)
(setf (fdefinition 'make-instance-<standard-effective-slot-definition>) #'make-instance)
(setf (fdefinition 'make-instance-<structure-direct-slot-definition>) #'make-instance)
(setf (fdefinition 'make-instance-<structure-effective-slot-definition>) #'make-instance)
#| ;;; Unoptimized slot-definition-xxx accessors.
;; MOP p. 84
(defgeneric slot-definition-name (slotdef)
(:method ((slotdef slot-definition))
(slot-value slotdef '$name)))
(initialize-extended-method-check #'slot-definition-name)
(defun (setf slot-definition-name) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-name))
(setf (slot-value slotdef '$name) new-value))
(defun slot-definition-inheritable-initer (slotdef)
(accessor-typecheck slotdef 'slot-definition 'slot-definition-inheritable-initer)
(slot-value slotdef '$inheritable-initer))
;; MOP p. 84
(defgeneric slot-definition-initform (slotdef)
(:method ((slotdef slot-definition))
(inheritable-slot-definition-initform (slot-value slotdef '$inheritable-initer))))
(initialize-extended-method-check #'slot-definition-initform)
(defun (setf slot-definition-initform) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-initform))
(setf (inheritable-slot-definition-initform (slot-value slotdef '$inheritable-initer)) new-value))
;; MOP p. 84
(defgeneric slot-definition-initfunction (slotdef)
(:method ((slotdef slot-definition))
(inheritable-slot-definition-initfunction (slot-value slotdef '$inheritable-initer))))
(initialize-extended-method-check #'slot-definition-initfunction)
(defun (setf slot-definition-initfunction) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-initfunction))
(setf (inheritable-slot-definition-initfunction (slot-value slotdef '$inheritable-initer)) new-value))
;; MOP p. 84
(defgeneric slot-definition-initargs (slotdef)
(:method ((slotdef slot-definition))
(slot-value slotdef '$initargs)))
(initialize-extended-method-check #'slot-definition-initargs)
(defun (setf slot-definition-initargs) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-initargs))
(setf (slot-value slotdef '$initargs) new-value))
;; MOP p. 85
(defgeneric slot-definition-type (slotdef)
(:method ((slotdef slot-definition))
(slot-value slotdef '$type)))
(initialize-extended-method-check #'slot-definition-type)
(defun (setf slot-definition-type) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-type))
(setf (slot-value slotdef '$type) new-value))
;; MOP p. 84
(defgeneric slot-definition-allocation (slotdef)
(:method ((slotdef slot-definition))
(slot-value slotdef '$allocation)))
(initialize-extended-method-check #'slot-definition-allocation)
(defun (setf slot-definition-allocation) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-allocation))
(setf (slot-value slotdef '$allocation) new-value))
(defun slot-definition-inheritable-doc (slotdef)
(accessor-typecheck slotdef 'slot-definition 'slot-definition-inheritable-doc)
(slot-value slotdef '$inheritable-doc))
(defun slot-definition-documentation (slotdef)
(accessor-typecheck slotdef 'slot-definition 'slot-definition-documentation)
(inheritable-slot-definition-documentation (slot-value slotdef '$inheritable-doc)))
(defun (setf slot-definition-documentation) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-documentation))
(setf (inheritable-slot-definition-documentation (slot-value slotdef '$inheritable-doc)) new-value))
;; MOP p. 85
(defgeneric slot-definition-readers (slotdef)
(:method ((slotdef direct-slot-definition))
(slot-value slotdef '$readers)))
(initialize-extended-method-check #'slot-definition-readers)
(defun (setf slot-definition-readers) (new-value slotdef)
(accessor-typecheck slotdef 'direct-slot-definition '(setf slot-definition-readers))
(setf (slot-value slotdef '$readers) new-value))
;; MOP p. 85
(defgeneric slot-definition-writers (slotdef)
(:method ((slotdef direct-slot-definition))
(slot-value slotdef '$writers)))
(initialize-extended-method-check #'slot-definition-writers)
(defun (setf slot-definition-writers) (new-value slotdef)
(accessor-typecheck slotdef 'direct-slot-definition '(setf slot-definition-writers))
(setf (slot-value slotdef '$writers) new-value))
;; MOP p. 86
(defgeneric slot-definition-location (slotdef)
(:method ((slotdef effective-slot-definition))
(slot-value slotdef '$location)))
(initialize-extended-method-check #'slot-definition-location)
(defun (setf slot-definition-location) (new-value slotdef)
(accessor-typecheck slotdef 'effective-slot-definition '(setf slot-definition-location))
(setf (slot-value slotdef '$location) new-value))
(defun slot-definition-efm-svuc (slotdef)
(accessor-typecheck slotdef 'effective-slot-definition 'slot-definition-efm-svuc)
(slot-value slotdef '$efm-svuc))
(defun (setf slot-definition-efm-svuc) (new-value slotdef)
(accessor-typecheck slotdef 'effective-slot-definition '(setf slot-definition-efm-svuc))
(setf (slot-value slotdef '$efm-svuc) new-value))
(defun slot-definition-efm-ssvuc (slotdef)
(accessor-typecheck slotdef 'effective-slot-definition 'slot-definition-efm-ssvuc)
(slot-value slotdef '$efm-ssvuc))
(defun (setf slot-definition-efm-ssvuc) (new-value slotdef)
(accessor-typecheck slotdef 'effective-slot-definition '(setf slot-definition-efm-ssvuc))
(setf (slot-value slotdef '$efm-ssvuc) new-value))
(defun slot-definition-efm-sbuc (slotdef)
(accessor-typecheck slotdef 'effective-slot-definition 'slot-definition-efm-sbuc)
(slot-value slotdef '$efm-sbuc))
(defun (setf slot-definition-efm-sbuc) (new-value slotdef)
(accessor-typecheck slotdef 'effective-slot-definition '(setf slot-definition-efm-sbuc))
(setf (slot-value slotdef '$efm-sbuc) new-value))
(defun slot-definition-efm-smuc (slotdef)
(accessor-typecheck slotdef 'effective-slot-definition 'slot-definition-efm-smuc)
(slot-value slotdef '$efm-smuc))
(defun (setf slot-definition-efm-smuc) (new-value slotdef)
(accessor-typecheck slotdef 'effective-slot-definition '(setf slot-definition-efm-smuc))
(setf (slot-value slotdef '$efm-smuc) new-value))
|#
;;; Optimized slot-definition-xxx accessors.
;;; These are possible thanks to the :fixed-slot-locations class option.
;; MOP p. 84
(defgeneric slot-definition-name (slotdef)
(:method ((slotdef slot-definition))
(sys::%record-ref slotdef *<slot-definition>-name-location*)))
(initialize-extended-method-check #'slot-definition-name)
;; Not in MOP.
(defun (setf slot-definition-name) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-name))
(setf (sys::%record-ref slotdef *<slot-definition>-name-location*) new-value))
;; Not in MOP.
(defun slot-definition-inheritable-initer (slotdef)
(accessor-typecheck slotdef 'slot-definition 'slot-definition-inheritable-initer)
(sys::%record-ref slotdef *<slot-definition>-inheritable-initer-location*))
(defun (setf slot-definition-inheritable-initer) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-inheritable-initer))
(setf (sys::%record-ref slotdef *<slot-definition>-inheritable-initer-location*) new-value))
;; MOP p. 84
(defgeneric slot-definition-initform (slotdef)
(:method ((slotdef slot-definition))
(inheritable-slot-definition-initform (sys::%record-ref slotdef *<slot-definition>-inheritable-initer-location*))))
(initialize-extended-method-check #'slot-definition-initform)
;; Not in MOP.
(defun (setf slot-definition-initform) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-initform))
(setf (inheritable-slot-definition-initform (sys::%record-ref slotdef *<slot-definition>-inheritable-initer-location*)) new-value))
;; MOP p. 84
(defgeneric slot-definition-initfunction (slotdef)
(:method ((slotdef slot-definition))
(inheritable-slot-definition-initfunction (sys::%record-ref slotdef *<slot-definition>-inheritable-initer-location*))))
(initialize-extended-method-check #'slot-definition-initfunction)
;; Not in MOP.
(defun (setf slot-definition-initfunction) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-initfunction))
(setf (inheritable-slot-definition-initfunction (sys::%record-ref slotdef *<slot-definition>-inheritable-initer-location*)) new-value))
;; MOP p. 84
(defgeneric slot-definition-initargs (slotdef)
(:method ((slotdef slot-definition))
(sys::%record-ref slotdef *<slot-definition>-initargs-location*)))
(initialize-extended-method-check #'slot-definition-initargs)
;; Not in MOP.
(defun (setf slot-definition-initargs) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-initargs))
(setf (sys::%record-ref slotdef *<slot-definition>-initargs-location*) new-value))
;; MOP p. 85
(defgeneric slot-definition-type (slotdef)
(:method ((slotdef slot-definition))
(sys::%record-ref slotdef *<slot-definition>-type-location*)))
(initialize-extended-method-check #'slot-definition-type)
;; Not in MOP.
(defun (setf slot-definition-type) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-type))
(setf (sys::%record-ref slotdef *<slot-definition>-type-location*) new-value))
;; MOP p. 84
(defgeneric slot-definition-allocation (slotdef)
(:method ((slotdef slot-definition))
(sys::%record-ref slotdef *<slot-definition>-allocation-location*)))
(initialize-extended-method-check #'slot-definition-allocation)
;; Not in MOP.
(defun (setf slot-definition-allocation) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-allocation))
(setf (sys::%record-ref slotdef *<slot-definition>-allocation-location*) new-value))
;; Not in MOP.
(defun slot-definition-inheritable-doc (slotdef)
(accessor-typecheck slotdef 'slot-definition 'slot-definition-inheritable-doc)
(sys::%record-ref slotdef *<slot-definition>-inheritable-doc-location*))
(defun (setf slot-definition-inheritable-doc) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-inheritable-doc))
(setf (sys::%record-ref slotdef *<slot-definition>-inheritable-doc-location*) new-value))
;; Not in MOP.
(defun slot-definition-documentation (slotdef)
(accessor-typecheck slotdef 'slot-definition 'slot-definition-documentation)
(inheritable-slot-definition-documentation (sys::%record-ref slotdef *<slot-definition>-inheritable-doc-location*)))
(defun (setf slot-definition-documentation) (new-value slotdef)
(accessor-typecheck slotdef 'slot-definition '(setf slot-definition-documentation))
(setf (inheritable-slot-definition-documentation (sys::%record-ref slotdef *<slot-definition>-inheritable-doc-location*)) new-value))
;; MOP p. 85
(defgeneric slot-definition-readers (slotdef)
(:method ((slotdef direct-slot-definition))
(sys::%record-ref slotdef *<direct-slot-definition>-readers-location*)))
(initialize-extended-method-check #'slot-definition-readers)
;; Not in MOP.
(defun (setf slot-definition-readers) (new-value slotdef)
(accessor-typecheck slotdef 'direct-slot-definition '(setf slot-definition-readers))
(setf (sys::%record-ref slotdef *<direct-slot-definition>-readers-location*) new-value))
;; MOP p. 85
(defgeneric slot-definition-writers (slotdef)
(:method ((slotdef direct-slot-definition))
(sys::%record-ref slotdef *<direct-slot-definition>-writers-location*)))
(initialize-extended-method-check #'slot-definition-writers)
;; Not in MOP.
(defun (setf slot-definition-writers) (new-value slotdef)
(accessor-typecheck slotdef 'direct-slot-definition '(setf slot-definition-writers))
(setf (sys::%record-ref slotdef *<direct-slot-definition>-writers-location*) new-value))
;; MOP p. 86
(defgeneric slot-definition-location (slotdef)
(:method ((slotdef effective-slot-definition))
(sys::%record-ref slotdef *<effective-slot-definition>-location-location*)))
(initialize-extended-method-check #'slot-definition-location)
;; Not in MOP.
(defun (setf slot-definition-location) (new-value slotdef)
(accessor-typecheck slotdef 'effective-slot-definition '(setf slot-definition-location))
(setf (sys::%record-ref slotdef *<effective-slot-definition>-location-location*) new-value))
;; Not in MOP.
(defun slot-definition-efm-svuc (slotdef)
(accessor-typecheck slotdef 'effective-slot-definition 'slot-definition-efm-svuc)
(sys::%record-ref slotdef *<effective-slot-definition>-efm-svuc-location*))
(defun (setf slot-definition-efm-svuc) (new-value slotdef)
(accessor-typecheck slotdef 'effective-slot-definition '(setf slot-definition-efm-svuc))
(setf (sys::%record-ref slotdef *<effective-slot-definition>-efm-svuc-location*) new-value))
;; Not in MOP.
(defun slot-definition-efm-ssvuc (slotdef)
(accessor-typecheck slotdef 'effective-slot-definition 'slot-definition-efm-ssvuc)
(sys::%record-ref slotdef *<effective-slot-definition>-efm-ssvuc-location*))
(defun (setf slot-definition-efm-ssvuc) (new-value slotdef)
(accessor-typecheck slotdef 'effective-slot-definition '(setf slot-definition-efm-ssvuc))
(setf (sys::%record-ref slotdef *<effective-slot-definition>-efm-ssvuc-location*) new-value))
;; Not in MOP.
(defun slot-definition-efm-sbuc (slotdef)
(accessor-typecheck slotdef 'effective-slot-definition 'slot-definition-efm-sbuc)
(sys::%record-ref slotdef *<effective-slot-definition>-efm-sbuc-location*))
(defun (setf slot-definition-efm-sbuc) (new-value slotdef)
(accessor-typecheck slotdef 'effective-slot-definition '(setf slot-definition-efm-sbuc))
(setf (sys::%record-ref slotdef *<effective-slot-definition>-efm-sbuc-location*) new-value))
;; Not in MOP.
(defun slot-definition-efm-smuc (slotdef)
(accessor-typecheck slotdef 'effective-slot-definition 'slot-definition-efm-smuc)
(sys::%record-ref slotdef *<effective-slot-definition>-efm-smuc-location*))
(defun (setf slot-definition-efm-smuc) (new-value slotdef)
(accessor-typecheck slotdef 'effective-slot-definition '(setf slot-definition-efm-smuc))
(setf (sys::%record-ref slotdef *<effective-slot-definition>-efm-smuc-location*) new-value))
;; MOP p. 45
(defgeneric direct-slot-definition-class (class &rest initargs)
(:method ((class semi-standard-class) &rest initargs)
(declare (ignore initargs))
<standard-direct-slot-definition>)
(:method ((class structure-class) &rest initargs)
(declare (ignore initargs))
<structure-direct-slot-definition>))
;; MOP p. 45
(defgeneric effective-slot-definition-class (class &rest initargs)
(:method ((class semi-standard-class) &rest initargs)
(declare (ignore initargs))
<standard-effective-slot-definition>)
(:method ((class structure-class) &rest initargs)
(declare (ignore initargs))
<structure-effective-slot-definition>))
;; Customizable function used to compare two slots of given objects belonging
;; to the same class.
;; Arguments: class is a subclass of <direct-slot-definition>,
;; (class-of object1) = class,
;; (class-of object2) = class,
;; slot is a slot of class,
;; value1 = (slot-value object1 (slot-definition-name slot)),
;; value2 = (slot-value object2 (slot-definition-name slot)).
(defgeneric slot-equal-using-class (class object1 object2 slot value1 value2)
(:method (class (object1 standard-direct-slot-definition) (object2 standard-direct-slot-definition) slot value1 value2)
(declare (ignore class object1 object2 slot))
(equal value1 value2)))
;; Test two direct slots for equality, except for the inheritable slots,
;; where only the presence is compared.
(defun equal-direct-slot (slot1 slot2 &aux slot-class)
(and (eq (setq slot-class (class-of slot1)) (class-of slot2))
(eq (slot-definition-name slot1) (slot-definition-name slot2))
(eq (null (slot-definition-initfunction slot1)) (null (slot-definition-initfunction slot2)))
(eq (null (slot-definition-documentation slot1)) (null (slot-definition-documentation slot2)))
;; The MOP doesn't specify an equality method that the user could define,
;; therefore we use the generic "compare all slots" approach.
(dolist (s (class-slots slot-class) t)
(let ((n (slot-definition-name s)))
;; $inheritable-initer covers the :initform :initfunction slot options.
;; $inheritable-doc covers the :documentation slot option.
(unless (memq n '($inheritable-initer $inheritable-doc))
(let ((unboundp1 (not (slot-boundp slot1 n)))
(unboundp2 (not (slot-boundp slot2 n))))
(unless (and (eq unboundp1 unboundp2)
(or unboundp1
(slot-equal-using-class slot-class slot1 slot2 s
(slot-value slot1 n)
(slot-value slot2 n))))
(return nil))))))))
#|
;; Tell the compiler how to serialize <structure-effective-slot-definition>
;; instances. This is needed for DEFSTRUCT.
(defmethod make-load-form ((object structure-effective-slot-definition) &optional environment)
(declare (ignore environment))
(make-load-form-<structure-effective-slot-definition> object))
|#
| 17,848 | Common Lisp | .lisp | 309 | 54.478964 | 137 | 0.75323 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 8963df048dc29c0167a8cc4f27a4d569a70ace107357dcd34f9d68841d4ae339 | 11,383 | [
-1
] |
11,384 | macros3.lisp | ufasoft_lisp/clisp/macros3.lisp | (in-package "EXT")
(export '(ethe letf letf* with-collect compiled-file-p compile-time-value
canonicalize))
(in-package "SYSTEM")
;;; ---------------------------------------------------------------------------
;;; Wie THE, nur dass auch im compilierten Code der Typtest durchgeführt wird.
(defmacro ethe (typespec form)
(let ((g (gensym "VALUES-")))
`(THE ,typespec
(LET ((,g (MULTIPLE-VALUE-LIST ,form)))
(IF (SYS::%THE ,g ',(type-for-discrimination typespec))
(VALUES-LIST ,g)
(ERROR-OF-TYPE 'ERROR ; 'TYPE-ERROR ??
(TEXT "The form ~S yielded ~:[no values~;~:*~{~S~^ ; ~}~] ,~@
that's not of type ~S.")
',form ,g ',typespec
) ) ) ) ) )
;;; ---------------------------------------------------------------------------
; Macro LETF / LETF* wie LET, LET*, nur dass als "Variable" beliebige Places
; (wie bei SETF) zugelassen sind, inklusive VALUES, VALUES-LIST.
; (LETF ((A form)) ...) --> (LET ((A form)) ...)
; (LETF (((CAR A) form)) ...)
; --> (LET* ((#:G1 A)
; (#:G2 (CAR #:G1))
; (#:G3 form))
; (UNWIND-PROTECT
; (PROGN (SYSTEM::%RPLACA #:G1 #:G3) ...)
; (SYSTEM::%RPLACA #:G1 #:G2)
; ) )
; (LETF (((VALUES A B) form)) ...) --> (MULTIPLE-VALUE-BIND (A B) form ...)
; (LETF (((VALUES (CAR A) (CDR B)) form)) ...)
; --> (LET* ((#:G1 A)
; (#:G2 (CAR #:G1))
; (#:G3 B)
; (#:G4 (CDR #:G3)))
; (MULTIPLE-VALUE-BIND (#:G5 #:G6) form
; (UNWIND-PROTECT
; (PROGN (SYSTEM::%RPLACA #:G1 #:G5) (SYSTEM::%RPLACD #:G3 #:G6)
; ...
; )
; (SYSTEM::%RPLACA #:G1 #:G2) (SYSTEM::%RPLACA #:G3 #:G4)
; ) ) )
; (LETF (((VALUES-LIST A) form)) ...)
; --> (LET ((A (MULTIPLE-VALUE-LIST form))) ...)
(defmacro LETF* (&whole whole-form
bindlist &body body &environment env)
(multiple-value-bind (body-rest declarations) (SYSTEM::PARSE-BODY body)
(let ((declare (if declarations `((DECLARE ,@declarations)) '())))
(values (expand-LETF* bindlist declare body-rest whole-form env)))))
; expandiert ein LETF*, liefert die Expansion und
; T, falls diese Expansion mit einem LET* anfängt, dessen Bindungsliste
; erweitert werden darf.
(defun expand-LETF* (bindlist declare body whole-form env)
(if (atom bindlist)
(if bindlist
(error-of-type 'source-program-error
:form whole-form
:detail bindlist
(TEXT "LETF* code contains a dotted list, ending with ~S")
bindlist
)
(values `(LET* () ,@declare ,@body) t)
)
(let ((bind (car bindlist)) place form)
(if (atom bind)
(setq place bind form nil)
(if (and (consp (cdr bind)) (null (cddr bind)))
(progn
(setq place (car bind) form (cadr bind))
(when (and (consp place) (eq (car place) 'VALUES-LIST) (eql (length place) 2))
(setq place (second place) form `(MULTIPLE-VALUE-LIST ,form))
)
(loop
(if (and (consp place) (eq (car place) 'THE) (eql (length place) 3))
(setq place (third place) form `(THE ,(second place) ,form))
(return)
) ) )
(illegal-syntax bind 'LETF* whole-form)))
(multiple-value-bind (rest-expanded flag)
(expand-LETF* (cdr bindlist) declare body whole-form env)
(if (and (atom place)
(not (and (symbolp place) (nth-value 1 (macroexpand-1 place env))))
)
(values
(if flag
`(LET* ,(cons (list place form) (cadr rest-expanded))
,@(cddr rest-expanded)
)
`(LET* ((,place ,form)) ,@declare ,rest-expanded)
)
t
)
(if (and (consp place) (eq (car place) 'VALUES))
(if (every #'(lambda (subplace)
(and (symbolp subplace)
(not (nth-value 1 (macroexpand-1 subplace env)))
) )
place)
(values
`(MULTIPLE-VALUE-BIND ,(cdr place) ,form ,@declare ,rest-expanded)
nil
)
(values
(do ((bindlist nil)
(storetemps nil)
(stores1 nil)
(stores2 nil)
(subplacesr (cdr place)))
((atom subplacesr)
`(LET* ,(nreverse bindlist)
,@declare
(MULTIPLE-VALUE-BIND ,(nreverse storetemps) ,form
,@declare
(UNWIND-PROTECT
(PROGN ,@(nreverse stores1) ,rest-expanded)
,@(nreverse stores2)
) ) ) )
(multiple-value-bind (SM-temps SM-subforms SM-stores SM-setterform SM-getterform)
(get-setf-method (pop subplacesr) env)
(setq bindlist
(cons (list (first SM-stores) SM-getterform)
(nreconc (mapcar #'list SM-temps SM-subforms) bindlist)
) )
(let ((storetemp (gensym "LETF*-")))
(setq storetemps (cons storetemp storetemps))
; We can use subst-in-form here, because storetemp is just a variable reference.
(setq stores1 (cons (subst-in-form storetemp (first SM-stores) SM-setterform) stores1))
)
(setq stores2 (cons SM-setterform stores2))
) )
t
) )
(multiple-value-bind (SM-temps SM-subforms SM-stores SM-setterform SM-getterform)
(get-setf-method place env)
(let ((formvar (gensym "LETF*-VALUE-")))
(values
`(LET* (,.(mapcar #'list SM-temps SM-subforms)
(,(first SM-stores) ,SM-getterform)
(,formvar ,form))
,@declare
(UNWIND-PROTECT
; We can use subst-in-form here, because formvar is just a variable reference.
(PROGN ,(subst-in-form formvar (first SM-stores) SM-setterform) ,rest-expanded)
,SM-setterform
) )
t
) ) )
) ) ) ) ) )
(defmacro LETF (&whole whole-form
bindlist &body body &environment env)
(multiple-value-bind (body-rest declarations) (SYSTEM::PARSE-BODY body)
(let ((declare (if declarations `((DECLARE ,@declarations)) '()))
(let-list nil))
(multiple-value-bind (let*-list let/let*-list uwp-store1 uwp-store2)
(expand-LETF bindlist whole-form env)
; mehrfach folgendes anwenden:
; endet let*-list mit (#:G form) und kommt in let/let*-list (var #:G)
; vor, so dürfen beide gestrichen werden, und dafür kommt (var form)
; an den Anfang von let-list.
(setq let*-list (nreverse let*-list))
(loop
(unless (and (consp let*-list)
(let ((last (caar let*-list)))
(and (symbolp last) (null (symbol-package last))
(dolist (bind let/let*-list nil)
(when (eq (second bind) last)
(push (list (first bind) (second (car let*-list)))
let-list
)
(setq let/let*-list
(delete last let/let*-list :key #'second
:test #'eq :count 1
) )
(setq let*-list (cdr let*-list))
(return t)
) ) ) ) )
(return)
) )
(setq let*-list (nreverse let*-list))
; Nun muss folgendes gemacht werden:
; 1. Die Bindungen von let*-list mit LETF* aktivieren,
; 2. die Bindungen von let-list mit LET aktivieren,
; 3. in beliebiger Reihenfolge:
; a. die Bindungen von let/let*-list mit LET oder LET* aktivieren,
; b. die Bindungen von uwp-store1 mit UNWIND-PROTECT aktivieren
; und danach mit uwp-store2 deaktivieren.
; Beispielsweise:
#| `(LETF* ,let*-list
,@declare
(LET ,let-list
,@declare
(LET* ,let/let*-list
,@declare
`(UNWIND-PROTECT (PROGN ,@uwp-store1 ,@body-rest) ,@uwp-store2)
) ) )
|#
(let ((body body-rest) ; eine Formenliste ohne Deklarationen
(1form nil)) ; zeigt an, ob body aus einer einzigen Form besteht
(when uwp-store1
(unless body (setq body '(nil)))
(setq body `((UNWIND-PROTECT (PROGN ,@uwp-store1 ,@body) ,@uwp-store2))
1form t
) )
(when let/let*-list
(setq body `((LET* ,let/let*-list ,@declare ,@body)) 1form t)
)
(when let-list
(setq body `((LET ,let-list ,@declare ,@body)) 1form t)
)
(when let*-list
(setq body `((LETF* ,let*-list ,@declare ,@body)) 1form t)
)
(if (and 1form (or (null declare) (not (eq (caar body) 'unwind-protect))))
; eine Form, keine Deklarationen oder fängt mit letf*/let/let* an
(car body)
; allgemein
`(LET () ,@declare (PROGN ,@body))
) ) ) ) ) )
; expandiert ein LETF, liefert:
; 1. eine Bindungsliste für LETF*,
; 2. eine Bindungsliste für LET/LET* (Reihenfolge der Bindung darin beliebig),
; 3. eine Liste von Bindungsanweisungen,
; 4. eine Liste von Entbindungsanweisungen
; (beide gleich lang).
(defun expand-LETF (bindlist whole-form env)
(if (atom bindlist)
(if bindlist
(error-of-type 'source-program-error
:form whole-form
:detail bindlist
(TEXT "LETF code contains a dotted list, ending with ~S")
bindlist
)
(values '() '() '() '())
)
(let ((bind (car bindlist)) place form)
(if (atom bind)
(setq place bind form nil)
(if (and (consp (cdr bind)) (null (cddr bind)))
(progn
(setq place (car bind) form (cadr bind))
(when (and (consp place) (eq (car place) 'VALUES-LIST) (eql (length place) 2))
(setq place (second place) form `(MULTIPLE-VALUE-LIST ,form))
)
(loop
(if (and (consp place) (eq (car place) 'THE) (eql (length place) 3))
(setq place (third place) form `(THE ,(second place) ,form))
(return)
) ) )
(illegal-syntax bind 'LETF whole-form)))
(multiple-value-bind (L1 L2 L3 L4) (expand-LETF (cdr bindlist) whole-form env)
(if (and (atom place)
(not (and (symbolp place) (nth-value 1 (macroexpand-1 place env))))
)
(let ((g (gensym)))
(values (cons (list g form) L1) (cons (list place g) L2) L3 L4)
)
(if (and (consp place) (eq (car place) 'VALUES))
(if (every #'(lambda (subplace)
(and (symbolp subplace)
(not (nth-value 1 (macroexpand-1 subplace env)))
) )
place)
(let ((gs (mapcar #'(lambda (subplace)
(gensym (symbol-name subplace))
)
(cdr place)
)) )
(values
(cons (list (cons 'VALUES gs) form) L1)
(nconc (mapcar #'list (cdr place) gs) L2)
L3
L4
) )
(do ((bindlist nil)
(storetemps nil)
(stores1 nil)
(stores2 nil)
(subplacesr (cdr place)))
((atom subplacesr)
(values
(nreconc bindlist
(cons (list (cons 'VALUES (nreverse storetemps)) form) L1)
)
L2
(nreconc stores1 L3)
(nreconc stores2 L4)
))
(multiple-value-bind (SM-temps SM-subforms SM-stores SM-setterform SM-getterform)
(get-setf-method (pop subplacesr) env)
(setq bindlist
(cons (list (first SM-stores) SM-getterform)
(nreconc (mapcar #'list SM-temps SM-subforms) bindlist)
) )
(let ((storetemp (gensym "LETF-")))
(setq storetemps (cons storetemp storetemps))
; We can use subst-in-form here, because storetemp is just a variable reference.
(setq stores1 (cons (subst-in-form storetemp (first SM-stores) SM-setterform) stores1))
)
(setq stores2 (cons SM-setterform stores2))
) ) )
(multiple-value-bind (SM-temps SM-subforms SM-stores SM-setterform SM-getterform)
(get-setf-method place env)
(let ((g (gensym "LETF-VALUE-")))
(values
`(,.(mapcar #'list SM-temps SM-subforms)
(,(first SM-stores) ,SM-getterform)
(,g ,form)
. ,L1)
L2
; We can use subst-in-form here, because g is just a variable reference.
(cons (subst-in-form g (first SM-stores) SM-setterform) L3)
(cons SM-setterform L4)
) ) )
) ) ) ) ) )
;;; ---------------------------------------------------------------------------
(defmacro with-collect ((&rest collectors) &body forms)
"Evaluate forms, collecting objects into lists.
Within the FORMS, you can use local macros listed among collectors,
they are returned as multiple values.
E.g., (with-collect (c1 c2) (dotimes (i 10) (if (oddp i) (c1 i) (c2 i))))
==> (1 3 5 7 9); (0 2 4 6 8) [2 values]
In CLISP, push/nreverse is about 1.25 times as fast as pushing into the
tail, so this macro uses push/nreverse on CLISP and push into the tail
on other lisps (which is 1.5-2 times as fast as push/nreverse there)."
#+clisp
(let ((ret (mapcar (lambda (cc) (gensym (format nil "~:@(~s~)-RET-" cc)))
collectors)))
`(let (,@ret)
(declare (list ,@ret))
(macrolet ,(mapcar (lambda (co re) `(,co (form) `(push ,form ,',re)))
collectors ret)
,@forms
(values ,@(mapcar (lambda (re) `(sys::list-nreverse ,re)) ret)))))
#-clisp
(let ((ret (mapcar (lambda (cc) (gensym (format nil "~:@(~s~)-RET-" cc)))
collectors))
(tail (mapcar (lambda (cc) (gensym (format nil "~:@(~s~)-TAIL-" cc)))
collectors))
(tmp (mapcar (lambda (cc) (gensym (format nil "~:@(~s~)-TMP-" cc)))
collectors)))
`(let (,@ret ,@tail)
(declare (list ,@ret ,@tail))
(macrolet ,(mapcar (lambda (co re ta tm)
`(,co (form)
`(let ((,',tm (list ,form)))
(if ,',re (setf (cdr ,',ta) (setf ,',ta ,',tm))
(setf ,',re (setf ,',ta ,',tm))))))
collectors ret tail tmp)
,@forms
(values ,@ret)))))
;;; ---------------------------------------------------------------------------
(defun compiled-file-p (file-name)
"Return non-NIL if FILE-NAME names a CLISP-compiled file
with compatible bytecodes."
(with-open-file (in file-name :direction :input :if-does-not-exist nil)
(handler-bind ((error (lambda (c) (declare (ignore c))
(return-from compiled-file-p nil))))
(and in (char= #\( (peek-char nil in nil #\a))
(let ((form (read in nil nil)))
(and (consp form)
(eq (car form) 'SYSTEM::VERSION)
(null (eval form))))))))
;;; ---------------------------------------------------------------------------
;;; http://groups.google.com/group/comp.lang.lisp/browse_thread/thread/7fda163e5e8194f2/65564bd5e2810f01
(defmacro compile-time-value (expression)
"Evaluate the EXPRESSION at compile time, writing the value into the FAS file."
(declare (ignore expression))
() ; see compiler.lisp:c-COMPILE-TIME-VALUE
#+(or) ;; the gensym result leaks into the *.lib and *.fas files
(let ((result (gensym "COMPILE-TIME-VALUE-")))
`(let ((,result nil))
(declare (special ,result))
(eval-when (compile)
(setq ,result `',(eval ',expression)))
(eval-when (compile load eval)
(macrolet ((ctv () ,result))
(eval-when (load eval) (ctv)))))))
;;; ---------------------------------------------------------------------------
(defun canonicalize (value functions &key (test 'eql) (max-iter 1024))
"Call FUNCTIONS on VALUE until it stabilizes according to TEST.
TEST should be a avalid HASH-TABLE-TEST.
MAX-ITER limits the number of iteration over the FUNCTIONS (defaults to 1024).
Returns the canonicalized value and the number of iterations it required."
(if functions
(let ((ht (make-hash-table :test test)) (prev value) next (count 0))
(setf (gethash value ht) 0)
(loop (setq next (reduce (lambda (v f) (funcall f v)) functions
:initial-value prev))
(when (funcall test next prev) (return (values next count)))
(let ((old (gethash next ht)))
(when old
(error "~S(~S ~S): circular computation: value ~S appears at steps ~:D and ~:D" 'canonicalize value functions next old (1+ count))))
(when (and max-iter (= count max-iter))
(error "~S(~S ~S): maximum number of iterations exceeded ~:D, last two values were ~S and ~S" 'canonicalize value functions max-iter prev next))
(setq prev next)
(setf (gethash next ht) (incf count))))
value))
| 18,465 | Common Lisp | .lisp | 398 | 33.560302 | 156 | 0.490774 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | c804f2ce93b6d3d64c40715e554909ec7a429d74bc504d0c1ad0609cee4eeb0c | 11,384 | [
-1
] |
11,385 | international.lisp | ufasoft_lisp/clisp/international.lisp | ;;; INTERNATIONALIZATION
(in-package "I18N")
(cl:export '(deflanguage definternational deflocalized localized english))
(common-lisp:in-package "SYSTEM")
(use-package '("I18N") "EXT")
(ext:re-export "I18N" "EXT")
;; ----------------------------------------------------------------------------
;; Languages and Internationalization:
;; (sys::current-language)
;; returns the current language, a symbol.
;; (deflanguage lang [parent-lang])
;; defines a language, being a descendant of parent-lang.
;; (sys::assert-language lang)
;; asserts that lang is a valid language.
;; (definternational symbol
;; { (lang value-form) }*
;; [ (t lang) | (t (var) value-form*) ]
;; )
;; defines an internationalized object, with some predefined values in
;; the specified languages, and a default language or default function for
;; unspecified languages.
;; (deflocalized symbol lang value-form)
;; enhances an internationalized object.
;; (localized symbol [lang])
;; looks up the value of an internationalized object in lang, which defaults
;; to the current language.
;;
;; There is an analogy between
;; deflanguage -- defclass
;; definternational -- defgeneric
;; deflocalized -- defmethod
;; localized -- funcall
;; If you need something like "definternational with arguments", then use
;; defgeneric with EQL methods for the language argument. (Well, language
;; inheritance doesn't work with EQL methods.)
;;
(defvar *all-languages* nil)
(defun assert-language (lang) ; ABI
(let ((h (assoc lang *all-languages*)))
(unless h
(error-of-type 'error
(TEXT "Language ~S is not defined")
lang
) )
(cdr h)
) )
(defun ensure-language (lang parent-lang) ; ABI
(let ((h (assoc lang *all-languages*)))
(if h
(unless (eq (cdr h) parent-lang)
(error-of-type 'error
(TEXT "Language ~S inherits from ~S")
lang (cdr h)
) )
(progn
(or (null parent-lang) (assert-language parent-lang))
(setq *all-languages*
(nconc *all-languages* (list (cons lang parent-lang)))
) ) ) )
lang
)
(defmacro deflanguage (lang &optional parent-lang)
`(SYSTEM::ENSURE-LANGUAGE ',lang ',parent-lang)
)
(deflanguage ENGLISH)
(defmacro definternational (symbol &rest options)
`(PROGN
,@(mapcap #'(lambda (option)
(let ((lang (first option)))
(if (eq lang 'T)
`((SYS::%PUT ',symbol 'SYS::OTHER-LANGUAGE
,(if (listp (second option))
`(FUNCTION (LAMBDA ,@(cdr option)))
`(SYSTEM::DEFINTERNATIONAL-DEFAULT
',symbol ',(second option)
)
)
))
`((ASSERT-LANGUAGE ',lang)
(SYS::%PUT ',symbol ',lang ,(second option))
)
) ) )
options
)
',symbol
)
)
(defmacro deflocalized (symbol lang form)
`(PROGN
(ASSERT-LANGUAGE ',lang)
(SYS::%PUT ',symbol ',lang ,form)
',symbol
)
)
(defun localized (symbol &optional (language (sys::current-language)))
(let ((notfound '#:notfound)
(lang language))
(loop
(let ((h (assoc lang *all-languages*)))
(unless h
(error-of-type 'error
(TEXT "~S: Language ~S is not defined")
'localized lang
) )
(let ((value (get symbol lang notfound)))
(unless (eq value notfound) (return-from localized value))
)
; not found -> search parent language
(setq lang (cdr h))
; no parent language -> lookup default function
(unless lang (return))
) ) )
(let ((h (get symbol 'SYS::OTHER-LANGUAGE)))
(if h
(funcall h language)
; no more parent language and no lookup default -> return nil
nil
) ) )
;; Default defaulter: Look up for another language.
(defvar *localized-recursion* nil)
(defun definternational-default (symbol default-language) ; ABI
#'(lambda (language)
(if (eq *localized-recursion* symbol) ; catch endless recursion
(error-of-type 'error
(TEXT "~S ~S: no value for default language ~S")
'localized symbol language
)
(let ((*localized-recursion* symbol))
(localized symbol default-language)
) ) )
)
| 4,538 | Common Lisp | .lisp | 131 | 27.839695 | 79 | 0.575062 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | bdc0c673f3dc106d770c4bf25de502af924f1723c0d4dff459ef15bc35443fa9 | 11,385 | [
-1
] |
11,386 | clos-slotdef2.lisp | ufasoft_lisp/clisp/clos-slotdef2.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Slot Definition metaobjects
;;;; Part n-2: Final class definitions, make/initialize-instance methods.
;;;; Bruno Haible 2004-04-18
(in-package "CLOS")
;;; ===========================================================================
;;; Lift the initialization protocol.
(defmethod initialize-instance ((slotdef slot-definition) &rest args
&key name initform initfunction initargs
type allocation documentation
((inheritable-initer inheritable-initer))
((inheritable-doc inheritable-doc)))
(declare (ignore name initform initfunction initargs type allocation
documentation inheritable-initer inheritable-doc))
(apply #'initialize-instance-<slot-definition> slotdef args))
(defmethod initialize-instance ((slotdef direct-slot-definition) &rest args
&key name initform initfunction initargs
type allocation documentation
((inheritable-initer inheritable-initer))
((inheritable-doc inheritable-doc))
readers writers
((defclass-form defclass-form)))
(declare (ignore name initform initfunction initargs type allocation
documentation inheritable-initer inheritable-doc readers
writers defclass-form))
(apply #'initialize-instance-<direct-slot-definition> slotdef args))
(defmethod initialize-instance ((slotdef effective-slot-definition) &rest args
&key name initform initfunction initargs
type allocation documentation
((inheritable-initer inheritable-initer))
((inheritable-doc inheritable-doc)))
(declare (ignore name initform initfunction initargs type allocation
documentation inheritable-initer inheritable-doc))
(apply #'initialize-instance-<effective-slot-definition> slotdef args))
(defmethod reinitialize-instance ((instance slot-definition) &rest initargs)
(declare (ignore initargs))
(error (TEXT "~S: The MOP does not allow reinitializing ~S")
'reinitialize-instance instance))
;;; ===========================================================================
;;; Now the concrete classes for <standard-class> and <structure-class> slots.
;;; ---------------------------------------------------------------------------
(defmethod initialize-instance ((slotdef standard-direct-slot-definition) &rest args)
(apply #'initialize-instance-<standard-direct-slot-definition> slotdef args))
;;; ---------------------------------------------------------------------------
(defmethod initialize-instance ((slotdef standard-effective-slot-definition) &rest args)
(apply #'initialize-instance-<standard-effective-slot-definition> slotdef args))
;;; ---------------------------------------------------------------------------
(defmethod initialize-instance ((slotdef structure-direct-slot-definition) &rest args)
(apply #'initialize-instance-<structure-direct-slot-definition> slotdef args))
;;; ---------------------------------------------------------------------------
(defun structure-effective-slot-definition-readonly (slotdef)
(slot-value slotdef '$readonly))
(defun (setf structure-effective-slot-definition-readonly) (new-value slotdef)
(setf (slot-value slotdef '$readonly) new-value))
(defmethod initialize-instance ((slotdef structure-effective-slot-definition) &rest args)
(apply #'initialize-instance-<structure-effective-slot-definition> slotdef args))
;;; ===========================================================================
;; Now that all the predefined subclasses of <slot-definition> have been
;; defined, CLASS-OF can work on all existing <slot-definition> instances.
;; Therefore now, not earlier, it's possible to pass these <slot-definition>
;; instances to generic functions.
| 4,181 | Common Lisp | .lisp | 61 | 57.114754 | 89 | 0.583415 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | b848147ef209c6626d0f708ebc59747982a5405cdaeceb46ceac6de5195f2777 | 11,386 | [
-1
] |
11,387 | clos-method4.lisp | ufasoft_lisp/clisp/clos-method4.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Methods
;;;; Part n-1: Generic functions specified in the MOP.
;;;; Bruno Haible 2004-06-01
(in-package "CLOS")
;; Make creation of <standard-method> instances customizable.
(setf (fdefinition 'make-instance-<standard-method>) #'make-instance)
;; Make creation of <standard-reader-method>, <standard-writer-method>
;; instances customizable.
(setf (fdefinition 'make-instance-<standard-reader-method>) #'make-instance)
(setf (fdefinition 'make-instance-<standard-writer-method>) #'make-instance)
;; Make creation of method instances customizable.
(setf (fdefinition 'make-method-instance) #'make-instance) ; ABI
| 663 | Common Lisp | .lisp | 13 | 49.615385 | 76 | 0.762791 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 5252ccc3864ff980be7f3584d63e32ab84811c9eda122a0a2a4f38251b2924c8 | 11,387 | [
-1
] |
11,388 | clos-specializer1.lisp | ufasoft_lisp/clisp/clos-specializer1.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Specializers
;;;; Part 1: Class definitions, preliminary accessors, utility functions.
;;;; Bruno Haible 2004-05-15
(in-package "CLOS")
;;; ===========================================================================
;;; The abstract class <specializer> allows specializers for methods in
;;; generic functions (i.e. classes and EQL-specializers) to be treated in a
;;; homogenous way.
(defvar *<specializer>-defclass*
'(defclass specializer (standard-stablehash metaobject)
(($direct-methods ; weak-list or weak-hash-table of methods that
; use this specializer
:initform nil))
(:fixed-slot-locations t)))
;; Fixed slot locations.
(defconstant *<specializer>-direct-methods-location* 2)
;; Preliminary accessors.
(predefun specializer-direct-methods-table (object)
(sys::%record-ref object *<specializer>-direct-methods-location*))
(predefun (setf specializer-direct-methods-table) (new-value object)
(setf (sys::%record-ref object *<specializer>-direct-methods-location*) new-value))
;; Initialization of a <specializer> instance.
(defun shared-initialize-<specializer> (specializer situation &rest args
&key &allow-other-keys)
(apply #'shared-initialize-<standard-stablehash> specializer situation args)
(unless *classes-finished*
; Bootstrapping: Simulate the effect of #'%shared-initialize.
(when (eq situation 't) ; called from initialize-instance?
(setf (specializer-direct-methods-table specializer) nil)))
specializer)
;;; ===========================================================================
;;; The class <eql-specializer> represents an EQL-specializer.
(defvar <eql-specializer> 'eql-specializer)
(defvar *<eql-specializer>-defclass*
'(defclass eql-specializer (specializer)
(($singleton :initarg singleton))
(:fixed-slot-locations t)))
(defvar *<eql-specializer>-class-version* (make-class-version))
;; Fixed slot locations.
(defconstant *<eql-specializer>-singleton-location* 3)
;; Preliminary accessors.
(predefun eql-specializer-singleton (object)
(sys::%record-ref object *<eql-specializer>-singleton-location*))
(predefun (setf eql-specializer-singleton) (new-value object)
(setf (sys::%record-ref object *<eql-specializer>-singleton-location*) new-value))
(defconstant *<eql-specializer>-instance-size* 4)
;; Initialization of an <eql-specializer> instance.
(defun shared-initialize-<eql-specializer> (specializer situation &rest args
&key ((singleton singleton) nil singleton-p)
&allow-other-keys)
(apply #'shared-initialize-<specializer> specializer situation args)
(unless *classes-finished*
; Bootstrapping: Simulate the effect of #'%shared-initialize.
(when singleton-p
(setf (eql-specializer-singleton specializer) singleton)))
specializer)
(defun initialize-instance-<eql-specializer> (specializer &rest args
&key &allow-other-keys)
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'initialize-instance later.
(apply #'shared-initialize-<eql-specializer> specializer 't args))
(defun make-instance-<eql-specializer> (class &rest args
&key &allow-other-keys)
;; class = <eql-specializer>
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'make-instance later.
(declare (ignore class))
(let ((specializer (allocate-metaobject-instance *<eql-specializer>-class-version* *<eql-specializer>-instance-size*)))
(apply #'initialize-instance-<eql-specializer> specializer args)))
;; Type test.
(defun eql-specializer-p (object)
(and (std-instance-p object)
(let ((cv (sys::%record-ref object 0)))
; Treat the most frequent case first, for bootstrapping.
(or (eq cv *<eql-specializer>-class-version*)
(gethash <eql-specializer>
(class-all-superclasses (class-of object)))))))
;;; ===========================================================================
;; We don't store the list of generic functions that use a given specializer
;; in the specializer, but instead compute it on the fly, because
;; 1. For good asymptotic performance the generic-functions list would have to
;; be stored as a weak set or a weak multiset, thus requiring that
;; <generic-function> inherits from <standard-stable-hash> - but this gives
;; a collision with <funcallable-instance>.
;; 2. The generic-functions list of a specializer is generally not much
;; shorter than the methods list of the specializer, and is redundant.
(defun compute-direct-generic-functions (specializer)
(let* ((methods (specializer-direct-methods specializer))
(gfs (delete-duplicates (mapcar #'method-generic-function methods) :test #'eq)))
(when (memq nil gfs)
(error (TEXT "~S: Some methods have been removed from their generic function, but the list in the ~S specializer was not updated.")
'specializer-direct-generic-functions specializer))
gfs))
;; MOP p. 103
(predefun specializer-direct-generic-functions (specializer)
(compute-direct-generic-functions specializer))
#|
;; Adds a method to the list of direct methods.
(defun add-direct-method (specializer method) ...)
;; Removes a method from the list of direct methods.
(defun remove-direct-method (specializer method) ...)
;; Returns the currently existing direct methods, as a freshly consed list.
(defun list-direct-methods (specializer) ...)
|#
(def-weak-set-accessors specializer-direct-methods-table method
add-direct-method-internal
remove-direct-method-internal
list-direct-methods)
(defun add-direct-method-<specializer>-<method> (specializer method)
(add-direct-method-internal specializer method)
(when (eql-specializer-p specializer)
(let ((its-class (class-of (eql-specializer-singleton specializer))))
(when (semi-standard-class-p its-class)
(add-direct-instance-specializer its-class specializer)))))
;; Preliminary.
(predefun add-direct-method (specializer method)
(add-direct-method-<specializer>-<method> specializer method))
(predefun remove-direct-method (specializer method)
(remove-direct-method-internal specializer method))
;; MOP p. 103
(predefun specializer-direct-methods (specializer)
(list-direct-methods specializer))
;;; ===========================================================================
;; EQL-specializers for numbers.
(defvar *eql-specializer-table*
(make-hash-table :key-type 'number :value-type 'eql-specializer
:test 'ext:fasthash-eql :warn-if-needs-rehash-after-gc t))
;; EQL-specializers for other kinds of objects.
(defvar *eq-specializer-table*
(make-hash-table :key-type '(not number) :value-type 'eql-specializer
:test 'ext:stablehash-eq
:weak :key))
;; MOP p. 70
(defun intern-eql-specializer (object)
(let ((table (if (numberp object) *eql-specializer-table* *eq-specializer-table*)))
(or (gethash object table)
(setf (gethash object table)
(make-instance-<eql-specializer> <eql-specializer>
'singleton object)))))
;; Returns the eql-specializer for the given object only if it already exists,
;; otherwise nil.
(defun existing-eql-specializer (object)
(let ((table (if (numberp object) *eql-specializer-table* *eq-specializer-table*)))
(gethash object table)))
;; MOP p. 52
(defun eql-specializer-object (specializer)
(eql-specializer-singleton specializer))
(defun print-object-<eql-specializer> (specializer stream)
(print-unreadable-object (specializer stream :type t)
(write (eql-specializer-object specializer) :stream stream)))
;;; ===========================================================================
;; Converts a specializer to a pretty printing type.
(defun specializer-pretty (specializer)
(if (eql-specializer-p specializer)
`(EQL ,(eql-specializer-object specializer))
specializer))
| 8,225 | Common Lisp | .lisp | 157 | 47.089172 | 137 | 0.679198 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 5dd1a4b8e875f6e94cbb9299e7aae7bffa718e93b37de15ee6fa32a50df4dcb5 | 11,388 | [
-1
] |
11,389 | defpackage.lisp | ufasoft_lisp/clisp/defpackage.lisp | ;;; ANSI-compatible definitions
;;; Bruno Haible 21.7.1994
;;; Sam Steingold 1999-2005
;; ============================================================================
(in-package "COMMON-LISP")
(export '(defpackage))
(in-package "SYSTEM")
;; ----------------------------------------------------------------------------
;; X3J13 vote <52>
;; Package-Definition und -Installation, CLtL2 S. 270
(defmacro defpackage (&whole whole-form
packname &rest options)
(setq packname (string packname))
;; Process important options:
(let ((case-sensitive nil) ; flag for :CASE-SENSITIVE
(case-inverted nil) ; flag for :CASE-INVERTED
(modern :DEFAULT)) ; flag for :MODERN
;; Process :MODERN first, because it specifies some defaults.
(dolist (option options)
(when (listp option)
(case (first option)
(:MODERN ; CLISP extension
(setq modern (second option))
(setq case-inverted (setq case-sensitive (not (null modern))))))))
(dolist (option options)
(when (listp option)
(case (first option)
(:CASE-SENSITIVE ; CLISP extension
(setq case-sensitive (not (null (second option)))))
(:CASE-INVERTED ; CLISP extension
(setq case-inverted (not (null (second option))))))))
(let ((to-string (if case-inverted #'cs-cl:string #'cl:string)))
;; Process options:
(let ((size nil) ; :SIZE has been supplied
(documentation nil) ; :DOCUMENTATION string
(nickname-list '()) ; list of nicknames
(shadow-list '()) ; list of symbol names to shadow
(shadowing-list '()) ; list of pairs (symbol-name . package-name) for shadowing-import
(use-list '()) ; list of package-names for use-package
(use-default "COMMON-LISP") ; default use-list
(import-list '()) ; list of (symbol-name . package-name) for import
(intern-list '()) ; list of symbol-names for intern
(symname-list '()) ; list of all symbol names specified so far
(export-list '())) ; liste of symbol-names for export
(flet ((record-symname (name)
(if (member name symname-list :test #'string=)
(error-of-type 'source-program-error
:form whole-form
:detail name
(TEXT "~S ~A: the symbol ~A must not be specified more than once")
'defpackage packname name)
(push name symname-list)))
(modernize (name)
;; MODERN: CL ==> CS-CL
(let ((pack (if (packagep name) name
(sys::%find-package (string name)))))
(ecase modern
((t) (if (eq pack #.(find-package "COMMON-LISP"))
"CS-COMMON-LISP" (package-name pack)))
((nil) (if (eq pack #.(find-package "CS-COMMON-LISP"))
"COMMON-LISP" (package-name pack)))
((:DEFAULT) (package-name pack))))))
(setq use-default (modernize use-default))
(dolist (option options)
(if (listp option)
(if (keywordp (car option))
(case (first option)
(:SIZE
(if size
(error-of-type 'source-program-error
:form whole-form
:detail options
(TEXT "~S ~A: the ~S option must not be given more than once")
'defpackage packname ':SIZE)
(setq size t))) ; ignored
(:DOCUMENTATION ; ANSI-CL
(if documentation
(error-of-type 'source-program-error
:form whole-form
:detail options
(TEXT "~S ~A: the ~S option must not be given more than once")
'defpackage packname ':DOCUMENTATION)
(setq documentation (second option))))
(:NICKNAMES
(dolist (name (rest option))
(push (string name) nickname-list)))
(:SHADOW
(dolist (name (rest option))
(setq name (funcall to-string name))
(unless (member name shadow-list :test #'string=)
(push name shadow-list)
(record-symname name))))
(:SHADOWING-IMPORT-FROM
(let ((pack (modernize (second option))))
(dolist (name (cddr option))
(setq name (funcall to-string name))
(let ((name+pack (cons name pack)))
(unless (member name+pack shadowing-list :test #'equal) ; #'string= on car and cdr
(push name+pack shadowing-list)
(record-symname name))))))
(:USE
(dolist (name (rest option))
(push (modernize name) use-list))
(setq use-default nil))
(:IMPORT-FROM
(let ((pack (modernize (second option))))
(dolist (name (cddr option))
(setq name (funcall to-string name))
(let ((name+pack (cons name pack)))
(unless (member name+pack import-list :test #'equal) ; #'string= on car and cdr
(push name+pack import-list)
(record-symname name))))))
(:INTERN
(dolist (name (rest option))
(setq name (funcall to-string name))
(unless (member name intern-list :test #'string=)
(push name intern-list)
(record-symname name))))
(:EXPORT
(dolist (name (rest option))
(setq name (funcall to-string name))
(unless (member name export-list :test #'string=)
(push name export-list))))
(:CASE-SENSITIVE) ; CLISP extension, already handled above
(:CASE-INVERTED) ; CLISP extension, already handled above
(:MODERN) ; CLISP extension, already handled above
(T (error-of-type 'source-program-error
:form whole-form
:detail (first option)
(TEXT "~S ~A: unknown option ~S")
'defpackage packname (first option))))
(error-of-type 'source-program-error
:form whole-form
:detail option
(TEXT "~S ~A: invalid syntax in ~S option: ~S")
'defpackage packname 'defpackage option))
(error-of-type 'source-program-error
:form whole-form
:detail option
(TEXT "~S ~A: not a ~S option: ~S")
'defpackage packname 'defpackage option)))
;; Check for overlaps between intern-list and export-list:
(setq symname-list intern-list)
(mapc #'record-symname export-list))
;; Reverse lists and apply default values:
(setq nickname-list (nreverse nickname-list))
(setq shadow-list (nreverse shadow-list))
(setq shadowing-list (nreverse shadowing-list))
(setq use-list (if use-default (list use-default) (nreverse use-list)))
(setq import-list (nreverse import-list))
(setq intern-list (nreverse intern-list))
(setq export-list (nreverse export-list))
;; Produce the expansion:
`(EVAL-WHEN (:COMPILE-TOPLEVEL :LOAD-TOPLEVEL :EXECUTE)
(SYSTEM::%IN-PACKAGE ,packname :NICKNAMES ',nickname-list :USE '()
:CASE-SENSITIVE ,case-sensitive
:CASE-INVERTED ,case-inverted)
;; Step 0
,@(ecase modern
((t)
`((when (find "COMMON-LISP" (package-use-list ,packname)
:test #'string= :key #'package-name)
(unuse-package "COMMON-LISP" ,packname)
(use-package "CS-COMMON-LISP" ,packname))))
((nil)
`((when (find "CS-COMMON-LISP" (package-use-list ,packname)
:test #'string= :key #'package-name)
(unuse-package "CS-COMMON-LISP" ,packname)
(use-package "COMMON-LISP" ,packname))))
((:DEFAULT) '()))
;; Step 1
,@(if shadow-list
`((,(if case-inverted 'CS-CL:shadow 'CL:SHADOW)
',shadow-list ,packname)))
,@(mapcar #'(lambda (pair)
`(SHADOWING-IMPORT-CERROR ,(car pair) ,(cdr pair)
,case-inverted ,packname))
shadowing-list)
;; Step 2
,@(if use-list `((USE-PACKAGE ',use-list ,packname)))
;; Step 3
,@(mapcar #'(lambda (pair)
`(IMPORT-CERROR ,(car pair) ,(cdr pair)
,case-inverted ,packname))
import-list)
,@(mapcar #'(lambda (symname)
`(,(if case-inverted 'CS-CL:intern 'CL:INTERN)
,symname ,packname))
intern-list)
;; Step 4
,@(if export-list
`((INTERN-EXPORT ',export-list ,packname ,case-inverted)))
;; Step 5
,@(if documentation
`((SETF (SYS::PACKAGE-DOCUMENTATION (FIND-PACKAGE ,packname))
,documentation)))
(FIND-PACKAGE ,packname))))))
; Hilfsfunktionen:
(defun find-symbol-cerror (string packname invert calling-packname)
(multiple-value-bind (sym found)
(if invert
(cs-cl:find-symbol string packname)
(cl:find-symbol string packname))
(unless found
(cerror ; 'package-error ??
(TEXT "This symbol will be created.")
(TEXT "~S ~A: There is no symbol ~A::~A .")
'defpackage calling-packname packname string)
(setq sym (if invert
(cs-cl:intern string packname)
(cl:intern string packname))))
sym))
(defun shadowing-import-cerror (string packname invert calling-packname) ; ABI
(let ((sym (find-symbol-cerror string packname invert calling-packname)))
(shadowing-import (or sym '(NIL)) calling-packname)))
(defun import-cerror (string packname invert calling-packname) ; ABI
(let ((sym (find-symbol-cerror string packname invert calling-packname)))
(import (or sym '(NIL)) calling-packname)))
(defun intern-export (string-list packname invert) ; ABI
(export (mapcar #'(lambda (string)
(if invert
(cs-cl:intern string packname)
(cl:intern string packname)))
string-list)
packname))
| 11,277 | Common Lisp | .lisp | 225 | 33.982222 | 107 | 0.499004 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 667eb776be73513209f226635560af1fb24c908dab562ebc7411725e0e2e4f9d | 11,389 | [
-1
] |
11,390 | case-sensitive.lisp | ufasoft_lisp/clisp/case-sensitive.lisp | ;;; Case-Sensitive Packages for CLISP
;;; Bruno Haible 2004-07-14
;;; Sam Steingold 2005
(in-package "SYSTEM")
;; From CS-COMMON-LISP export all standard symbols which don't have a
;; case-sensitive variant (like SYMBOL-NAME etc).
(let ((cs-cl-package (find-package "CS-COMMON-LISP")))
(do-external-symbols (standard-sym "COMMON-LISP")
(let ((cs-sym (find-symbol (symbol-name standard-sym) cs-cl-package)))
(if cs-sym
;; Copy the property list (important for STRING et al.).
(setf (symbol-plist cs-sym) (copy-list (symbol-plist standard-sym)))
;; Use the standard-sym unmodified.
(progn
(import (list standard-sym) cs-cl-package)
(setq cs-sym standard-sym)))
(export (list cs-sym) cs-cl-package))))
;; #<PACKAGE CS-COMMON-LISP-USER> is the default case-sensitive user package.
(use-package '("CS-COMMON-LISP" "EXT") "CS-COMMON-LISP-USER")
(pushnew "CS-COMMON-LISP" custom:*system-package-list* :test #'string=)
| 984 | Common Lisp | .lisp | 20 | 44.55 | 77 | 0.681582 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 478720faf87eabaca8da027b085b71ce5c6c8ef280efe88e6190d0e309a36e55 | 11,390 | [
-1
] |
11,391 | clos-class1.lisp | ufasoft_lisp/clisp/clos-class1.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Class metaobjects
;;;; Part 1: Class definitions, preliminary accessors.
;;;; Bruno Haible 2004-05-25
;;;; Sam Steingold 2005-2006
(in-package "CLOS")
;;; Low-level representation:
;; In the runtime-system, the type "CLOS instance" exists.
;; The first component is the class-version, the rest are the local slot
;; values.
;; Classes are instances of type CLASS,
;; The "value" of a slot that is unbound, is #<UNBOUND> - what else?
;;; see RECORD.D :
;; (STD-INSTANCE-P obj) tests, if an object is a CLOS-instance.
;; (ALLOCATE-STD-INSTANCE class n) returns a non-funcallable CLOS-instance
;; with Class class and n-1 additional slots.
;; (ALLOCATE-FUNCALLABLE-INSTANCE class n) returns a funcallable CLOS-instance
;; with Class class and n-3 additional slots.
;;; see IO.D :
;; CLOS-instances are printed via (PRINT-OBJECT object stream).
;; (CLASS-OF object) see PREDTYPE.D, uses property CLOSCLASS.
;;; ===========================================================================
;;; Auxiliary stuff.
;; An empty hash table.
(defconstant empty-ht
(make-hash-table :key-type 'symbol :value-type 't
:test 'eq :warn-if-needs-rehash-after-gc t
:size 0))
;;; ===========================================================================
;;; The abstract class <super-class> allows defined classes and
;;; forward-references to classes to be treated in a homogenous way.
(defvar *<super-class>-defclass*
'(defclass super-class (standard-stablehash metaobject)
(($classname ; (class-name class) = (class-classname class),
; a symbol
:type symbol
:initarg :name)
($direct-subclasses ; set of all direct subclasses, as a weak-list or
; weak-hash-table or NIL
:type (or hash-table weak-list null)
:initform nil))
(:fixed-slot-locations nil)))
;;; ===========================================================================
;;; The abstract class <potential-class> is the abstract base class of all
;;; classes.
(defvar *<potential-class>-defclass*
'(defclass potential-class (specializer super-class)
()
(:fixed-slot-locations t)))
;; Fixed slot locations.
(defconstant *<potential-class>-classname-location* 3)
(defconstant *<potential-class>-direct-subclasses-location* 4)
;; Preliminary accessors.
(predefun class-classname (object)
(sys::%record-ref object *<potential-class>-classname-location*))
(predefun (setf class-classname) (new-value object)
(setf (sys::%record-ref object *<potential-class>-classname-location*) new-value))
(predefun class-direct-subclasses-table (object)
(if (potential-class-p object)
(sys::%record-ref object *<potential-class>-direct-subclasses-location*)
(slot-value object '$direct-subclasses)))
(predefun (setf class-direct-subclasses-table) (new-value object)
(if (potential-class-p object)
(setf (sys::%record-ref object *<potential-class>-direct-subclasses-location*) new-value)
(setf (slot-value object '$direct-subclasses) new-value)))
;; Initialization of a <potential-class> instance.
(defun shared-initialize-<potential-class> (class situation &rest args
&key (name nil name-p)
&allow-other-keys)
(apply #'shared-initialize-<specializer> class situation args)
(unless *classes-finished*
; Bootstrapping: Simulate the effect of #'%shared-initialize.
(when (eq situation 't) ; called from initialize-instance?
(setf (class-direct-subclasses-table class) nil)))
(when (or (eq situation 't) name-p)
(setf (class-classname class) (check-symbol name '(setf class-name))))
class)
;;; ===========================================================================
;;; The class <forward-referenced-class> allows forward-references to classes
;;; to collect their direct subclasses already before they are defined:
;;; (defclass b (a) ())
;;; (defclass a () ())
;;; (class-direct-subclasses (find-class 'a)) => (#<STANDARD-CLASS B>)
;;; A forward-referenced-class's name is always a symbol that cannot be
;;; changed, and the forward-referenced-class is available as
;;; (get name 'CLOSCLASS), until it is replaced with the defined class.
;;; The MOP specification regarding <forward-referenced-class> is severely
;;; misdesigned. The actual meaning of a <forward-referenced-class> is a
;;; forward-reference to (= placeholder for) a not yet defined class. The only
;;; place where it is used is in the direct-superclasses list of some classes
;;; that are not yet finalized.
;;;
;;; Putting it under <class> is a mistake because:
;;; 1. Classes fundamentally describe the slots and operations available
;;; on its (direct and indirect) instances. But a forward-referenced
;;; class can never have (direct and indirect) instances, since the
;;; slots and operations are not yet known.
;;; 2. All the generic functions on <class>, such as class-precedence-list
;;; or class-direct-default-initargs, make no sense on a
;;; <forward-referenced-class> - since the real information is not yet
;;; available.
;;; 3. <class> inherits from <specializer>, but it makes no sense to use
;;; a <forward-referenced-class> as a specializer in a method or as a
;;; type in TYPEP or SUBTYPEP.
;;;
;;; This is also backed by the fact that this MOP implementation has three
;;; times more tests for <defined-class> (i.e. for <class> without
;;; <forward-referenced-class>) than for <potential-class>.
;;;
;;; A better design would be to define an abstract class <superclass> and
;;; let <forward-referenced-class> inherit from it:
;;; (defclass super-class () ...)
;;; (defclass class (super-class specializer) ...)
;;; (defclass forward-referenced-class (super-class) ...)
;;; and (class-direct-superclasses class) would simply be a list of
;;; <super-class> instances.
;; The proper <forward-referenced-class> inherits from <super-class> but
;; not from <specializer>.
(defvar *<forward-reference-to-class>-defclass*
'(defclass forward-reference-to-class (super-class)
()
(:fixed-slot-locations nil)))
;; The crappy <forward-referenced-class> from the MOP is subclass of
;; <potential-class> and thus also of <specializer>.
(defvar *<misdesigned-forward-referenced-class>-defclass*
'(defclass misdesigned-forward-referenced-class (forward-reference-to-class potential-class)
()
(:fixed-slot-locations nil)))
;;; ===========================================================================
;;; The abstract class <defined-class> allows built-in objects, user-defined
;;; objects and proxies to external worlds to be treated in a homogenous way.
(defvar *<defined-class>-defclass*
'(defclass defined-class (potential-class)
(($direct-superclasses ; list of all direct superclasses (or their names,
; while the class is waiting to be finalized)
:type list
:initarg :direct-superclasses)
($all-superclasses ; hash table of all superclasses (including
; the class itself)
:type hash-table)
($precedence-list ; ordered list of all superclasses (with the class
; itself first), or NIL while the class is waiting
; to be finalized
:type list)
($direct-slots ; list of all freshly added slots (as
; direct-slot-definition instances)
:type list
:initarg :direct-slots)
($slots ; list of all slots (as effective-slot-definition
; instances)
:type list)
($slot-location-table ; hash table slotname -> descriptor
; where the descriptor is either
; - the location of the slot (a fixnum or cons), or
; - its effective slot definition
:type hash-table
:initform empty-ht)
($direct-default-initargs ; freshly added default-initargs
; (as alist initarg -> (form function))
:type list
:initarg :direct-default-initargs)
($default-initargs ; default-initargs
; (as alist initarg -> (form function))
)
($documentation ; string or NIL
:type (or string null)
:initarg :documentation)
($listeners ; list of objects to be notified upon a change
:type list
:initform nil)
($initialized ; describes which parts of the class are initialized
:type (integer 0 6) ; 0 = nothing
; 1 = name
; 2 = likewise, plus direct-... info
; 3 = likewise, plus class-precedence-list
; 4 = likewise, plus class-all-superclasses
; 5 = likewise, plus class-slots
; 6 = likewise, plus slot-location-table, default-initargs
:initform 0))
(:fixed-slot-locations t)))
;; Fixed slot locations.
(defconstant *<defined-class>-direct-superclasses-location* 5)
(defconstant *<defined-class>-all-superclasses-location* 6)
(defconstant *<defined-class>-precedence-list-location* 7)
(defconstant *<defined-class>-direct-slots-location* 8)
(defconstant *<defined-class>-slots-location* 9)
(defconstant *<defined-class>-slot-location-table-location* 10)
(defconstant *<defined-class>-direct-default-initargs-location* 11)
(defconstant *<defined-class>-default-initargs-location* 12)
(defconstant *<defined-class>-documentation-location* 13)
(defconstant *<defined-class>-listeners-location* 14)
(defconstant *<defined-class>-initialized-location* 15)
;; Preliminary accessors.
(predefun class-direct-superclasses (object)
(sys::%record-ref object *<defined-class>-direct-superclasses-location*))
(predefun (setf class-direct-superclasses) (new-value object)
(setf (sys::%record-ref object *<defined-class>-direct-superclasses-location*) new-value))
(predefun class-all-superclasses (object)
(sys::%record-ref object *<defined-class>-all-superclasses-location*))
(predefun (setf class-all-superclasses) (new-value object)
(setf (sys::%record-ref object *<defined-class>-all-superclasses-location*) new-value))
(predefun class-precedence-list (object)
(sys::%record-ref object *<defined-class>-precedence-list-location*))
(predefun (setf class-precedence-list) (new-value object)
(setf (sys::%record-ref object *<defined-class>-precedence-list-location*) new-value))
(predefun class-direct-slots (object)
(sys::%record-ref object *<defined-class>-direct-slots-location*))
(predefun (setf class-direct-slots) (new-value object)
(setf (sys::%record-ref object *<defined-class>-direct-slots-location*) new-value))
(predefun class-slots (object)
(sys::%record-ref object *<defined-class>-slots-location*))
(predefun (setf class-slots) (new-value object)
(setf (sys::%record-ref object *<defined-class>-slots-location*) new-value))
(predefun class-slot-location-table (object)
(sys::%record-ref object *<defined-class>-slot-location-table-location*))
(predefun (setf class-slot-location-table) (new-value object)
(setf (sys::%record-ref object *<defined-class>-slot-location-table-location*) new-value))
(predefun class-direct-default-initargs (object)
(sys::%record-ref object *<defined-class>-direct-default-initargs-location*))
(predefun (setf class-direct-default-initargs) (new-value object)
(setf (sys::%record-ref object *<defined-class>-direct-default-initargs-location*) new-value))
(predefun class-default-initargs (object)
(sys::%record-ref object *<defined-class>-default-initargs-location*))
(predefun (setf class-default-initargs) (new-value object)
(setf (sys::%record-ref object *<defined-class>-default-initargs-location*) new-value))
(predefun class-documentation (object)
(sys::%record-ref object *<defined-class>-documentation-location*))
(predefun (setf class-documentation) (new-value object)
(setf (sys::%record-ref object *<defined-class>-documentation-location*) new-value))
(predefun class-listeners (object)
(sys::%record-ref object *<defined-class>-listeners-location*))
(predefun (setf class-listeners) (new-value object)
(setf (sys::%record-ref object *<defined-class>-listeners-location*) new-value))
(predefun class-initialized (object)
(sys::%record-ref object *<defined-class>-initialized-location*))
(predefun (setf class-initialized) (new-value object)
(setf (sys::%record-ref object *<defined-class>-initialized-location*) new-value))
(defun canonicalized-slot-p (x)
; A "canonicalized slot specification" is a special kind of property list.
; See MOP p. 13-15.
(and (proper-list-p x)
(evenp (length x))
(let ((default '#:default))
(not (eq (getf x ':name default) default)))))
(defun canonicalized-default-initarg-p (x)
; A "canonicalized default initarg" is an element of an alist mapping
; a slot name (a symbol) to a list of the form (form function).
; See MOP p. 16.
(and (consp x) (symbolp (first x))
(consp (cdr x)) (consp (cddr x)) (functionp (third x))
(null (cdddr x))))
;; Initialization of a <defined-class> instance.
(defun shared-initialize-<defined-class> (class situation &rest args
&key (name nil)
(direct-superclasses nil direct-superclasses-p)
((:direct-slots direct-slots-as-lists) '() direct-slots-as-lists-p)
((direct-slots direct-slots-as-metaobjects) '() direct-slots-as-metaobjects-p)
(direct-default-initargs nil direct-default-initargs-p)
(documentation nil documentation-p)
&allow-other-keys
&aux old-direct-superclasses)
(setq old-direct-superclasses
(if (eq situation 't) ; called from initialize-instance?
'()
(sys::%record-ref class *<defined-class>-direct-superclasses-location*)))
(apply #'shared-initialize-<potential-class> class situation args)
(unless *classes-finished*
; Bootstrapping: Simulate the effect of #'%shared-initialize.
(when (eq situation 't) ; called from initialize-instance?
(setf (class-slot-location-table class) empty-ht)
(setf (class-listeners class) nil)
(setf (class-initialized class) 0)))
(when (eq situation 't)
; shared-initialize-<potential-class> has initialized the name.
(setf (class-initialized class) 1))
; Get the name, for error message purposes.
(setq name (class-classname class))
(when (or (eq situation 't) direct-superclasses-p)
; Check the direct-superclasses.
(unless (proper-list-p direct-superclasses)
(error (TEXT "(~S ~S) for class ~S: The ~S argument should be a proper list, not ~S")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'class name ':direct-superclasses direct-superclasses))
(unless (every #'(lambda (x)
(or (defined-class-p x)
(forward-reference-to-class-p x)))
direct-superclasses)
(error (TEXT "(~S ~S) for class ~S: The direct-superclasses list should consist of classes, not ~S")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'class name direct-superclasses))
(when (and (> (length direct-superclasses) 1)
(typep class <structure-class>))
(error (TEXT "(~S ~S) for class ~S: The metaclass ~S forbids more than one direct superclass: It does not support multiple inheritance.")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'class name (class-of class)))
(dolist (sc direct-superclasses)
(when (defined-class-p sc)
(check-allowed-superclass class sc)))
(when (null direct-superclasses)
(setq direct-superclasses (default-direct-superclasses class))))
(when (or (eq situation 't) direct-slots-as-lists-p)
; Check the direct-slots.
(unless (proper-list-p direct-slots-as-lists)
(error (TEXT "(~S ~S) for class ~S: The ~S argument should be a proper list, not ~S")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'class name ':direct-slots direct-slots-as-lists))
(dolist (sl direct-slots-as-lists)
(unless (canonicalized-slot-p sl)
(error (TEXT "(~S ~S) for class ~S: The direct slot specification ~S is not in the canonicalized form (slot-name initform initfunction).")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'class name sl))))
(when (or (eq situation 't) direct-default-initargs-p)
; Check the direct-default-initargs.
(unless (proper-list-p direct-default-initargs)
(error (TEXT "(~S ~S) for class ~S: The ~S argument should be a proper list, not ~S")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'class name ':direct-default-initargs direct-default-initargs))
(dolist (definitarg direct-default-initargs)
(unless (canonicalized-default-initarg-p definitarg)
(error (TEXT "(~S ~S) for class ~S: The direct default initarg ~S is not in canonicalized form (a property list).")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'class name definitarg))))
(when (or (eq situation 't) documentation-p)
; Check the documentation.
(unless (or (null documentation) (stringp documentation))
(error (TEXT "(~S ~S) for class ~S: The ~S argument should be a string or NIL, not ~S")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'class name :documentation documentation)))
; Fill the slots.
(when (or (eq situation 't) direct-superclasses-p)
(setf (class-direct-superclasses class) (copy-list direct-superclasses))
(update-subclasses-sets class old-direct-superclasses direct-superclasses))
(when (or (eq situation 't) direct-slots-as-lists-p direct-slots-as-metaobjects-p)
(setf (class-direct-slots class)
(if direct-slots-as-metaobjects-p
direct-slots-as-metaobjects
(convert-direct-slots class direct-slots-as-lists))))
(when (or (eq situation 't) direct-default-initargs-p)
(setf (class-direct-default-initargs class) direct-default-initargs))
(when (or (eq situation 't) documentation-p)
(setf (class-documentation class) documentation))
; The following slots are initialized by the subclass' shared-initialize:
; all-superclasses
; precedence-list
; slots
; slot-location-table
; default-initargs
; Now allow the user to call some class-xxx accessor functions.
(when (eq situation 't)
(setf (class-initialized class) 2))
class)
;;; ===========================================================================
;;; The class <built-in-class> represents those classes for which the user
;;; cannot create subclasses.
(defvar <built-in-class> 'built-in-class)
(defvar *<built-in-class>-defclass*
'(defclass built-in-class (defined-class)
(($prototype ; class prototype - an instance
:type t))
(:fixed-slot-locations t)))
(defvar *<built-in-class>-class-version* (make-class-version))
;; Fixed slot locations.
(defconstant *<built-in-class>-prototype-location* 16)
(defconstant *<built-in-class>-instance-size* 17)
;;; ===========================================================================
;;; The class <slotted-class> represents those classes for which the local
;;; slot values are stored in the instance. It also represents common
;;; behaviour of <standard-class> and <structure-class>.
(defvar *<slotted-class>-defclass*
'(defclass slotted-class (defined-class)
(($subclass-of-stablehash-p ; true if <standard-stablehash> or
; <structure-stablehash> is among the superclasses
:type boolean)
($generic-accessors ; flag whether to create the accessors as methods;
; if false, regular functions are used
:initform t)
($direct-accessors ; automatically generated accessor methods
; (as plist)
:type list
:initform '())
($valid-initargs-from-slots ; list of valid initargs, computed from slots
:type list) ; (not including those declared valid by methods!)
($instance-size ; number of local slots of the direct instances + 1
:type (integer 1 *)))
(:fixed-slot-locations t)))
;; Fixed slot locations.
(defconstant *<slotted-class>-subclass-of-stablehash-p-location* 16)
(defconstant *<slotted-class>-generic-accessors-location* 17)
(defconstant *<slotted-class>-direct-accessors-location* 18)
(defconstant *<slotted-class>-valid-initargs-from-slots-location* 19)
(defconstant *<slotted-class>-instance-size-location* 20)
;; Preliminary accessors.
(predefun class-subclass-of-stablehash-p (object)
(sys::%record-ref object *<slotted-class>-subclass-of-stablehash-p-location*))
(predefun (setf class-subclass-of-stablehash-p) (new-value object)
(setf (sys::%record-ref object *<slotted-class>-subclass-of-stablehash-p-location*) new-value))
(predefun class-generic-accessors (object)
(sys::%record-ref object *<slotted-class>-generic-accessors-location*))
(predefun (setf class-generic-accessors) (new-value object)
(setf (sys::%record-ref object *<slotted-class>-generic-accessors-location*) new-value))
(predefun class-direct-accessors (object)
(sys::%record-ref object *<slotted-class>-direct-accessors-location*))
(predefun (setf class-direct-accessors) (new-value object)
(setf (sys::%record-ref object *<slotted-class>-direct-accessors-location*) new-value))
(predefun class-valid-initargs-from-slots (object)
(sys::%record-ref object *<slotted-class>-valid-initargs-from-slots-location*))
(predefun (setf class-valid-initargs-from-slots) (new-value object)
(setf (sys::%record-ref object *<slotted-class>-valid-initargs-from-slots-location*) new-value))
(predefun class-instance-size (object)
(sys::%record-ref object *<slotted-class>-instance-size-location*))
(predefun (setf class-instance-size) (new-value object)
(setf (sys::%record-ref object *<slotted-class>-instance-size-location*) new-value))
;; Initialization of a <slotted-class> instance.
(defun shared-initialize-<slotted-class> (class situation &rest args
&key (generic-accessors t generic-accessors-p)
&allow-other-keys)
(apply #'shared-initialize-<defined-class> class situation args)
(unless *classes-finished*
; Bootstrapping: Simulate the effect of #'%shared-initialize.
(when (eq situation 't) ; called from initialize-instance?
(setf (class-direct-accessors class) '())))
(when (or (eq situation 't) generic-accessors-p)
(setf (class-generic-accessors class) generic-accessors))
; The following slots are initialized by the subclass' shared-initialize:
; subclass-of-stablehash-p
; valid-initargs-from-slots
; instance-size
class)
;;; ===========================================================================
;;; The class <structure-class> represents classes like those defined through
;;; DEFSTRUCT.
(defvar <structure-class> 'structure-class)
(defvar *<structure-class>-defclass*
'(defclass structure-class (slotted-class)
(($names ; encoding of the include-nesting, a list
; (name_1 ... name_i-1 name_i) with name=name_1,
:type cons) ; name_1 contains name_2, ..., name_i-1 contains name_i.
($kconstructor ; name of keyword constructor function
:type symbol)
($boa-constructors ; list of all BOA constructor function names
:type list)
($copier ; name of the copier function
:type symbol)
($predicate ; name of the predicate function
:type symbol)
($prototype ; class prototype - an instance or NIL
:type (or structure-object null)))
(:fixed-slot-locations t)))
(defvar *<structure-class>-class-version* (make-class-version))
;; Fixed slot locations.
(defconstant *<structure-class>-names-location* 21)
(defconstant *<structure-class>-kconstructor-location* 22)
(defconstant *<structure-class>-boa-constructors-location* 23)
(defconstant *<structure-class>-copier-location* 24)
(defconstant *<structure-class>-predicate-location* 25)
(defconstant *<structure-class>-prototype-location* 26)
;; Preliminary accessors.
(predefun class-names (object)
(sys::%record-ref object *<structure-class>-names-location*))
(predefun (setf class-names) (new-value object)
(setf (sys::%record-ref object *<structure-class>-names-location*) new-value))
(predefun class-kconstructor (object)
(sys::%record-ref object *<structure-class>-kconstructor-location*))
(predefun (setf class-kconstructor) (new-value object)
(setf (sys::%record-ref object *<structure-class>-kconstructor-location*) new-value))
(predefun class-boa-constructors (object)
(sys::%record-ref object *<structure-class>-boa-constructors-location*))
(predefun (setf class-boa-constructors) (new-value object)
(setf (sys::%record-ref object *<structure-class>-boa-constructors-location*) new-value))
(predefun class-copier (object)
(sys::%record-ref object *<structure-class>-copier-location*))
(predefun (setf class-copier) (new-value object)
(setf (sys::%record-ref object *<structure-class>-copier-location*) new-value))
(predefun class-predicate (object)
(sys::%record-ref object *<structure-class>-predicate-location*))
(predefun (setf class-predicate) (new-value object)
(setf (sys::%record-ref object *<structure-class>-predicate-location*) new-value))
(defconstant *<structure-class>-instance-size* 27)
;;; ===========================================================================
;;; The class <semi-standard-class> is a common superclass of <standard-class>
;;; and <funcallable-standard-class>. Both implement the "default" CLOS
;;; behaviour.
(defvar <semi-standard-class> 'semi-standard-class)
(defvar *<semi-standard-class>-defclass*
'(defclass semi-standard-class (slotted-class)
(($current-version ; most recent class-version, points back to this
; class
:type simple-vector)
($funcallablep ; flag whether direct instances are funcallable
:type boolean)
($fixed-slot-locations ; flag whether to guarantee same slot locations
; in all subclasses
:initarg :fixed-slot-locations
)
($instantiated ; true if an instance has already been created
:type boolean
:initform nil)
($direct-instance-specializers ; set of all eql-specializers of direct
; instances that may be used in methods, as a
; weak-list or weak-hash-table or NIL
:type (or hash-table weak-list null)
:initform nil)
($finalized-direct-subclasses ; set of all finalized direct subclasses,
; as a weak-list or weak-hash-table or NIL
:type (or hash-table weak-list null)
:initform '())
($prototype ; class prototype - an instance or NIL
:type (or standard-object null)))
(:default-initargs :fixed-slot-locations nil)
(:fixed-slot-locations t)))
;; Fixed slot locations.
(defconstant *<semi-standard-class>-current-version-location* 21)
(defconstant *<semi-standard-class>-funcallablep-location* 22)
(defconstant *<semi-standard-class>-fixed-slot-locations-location* 23)
(defconstant *<semi-standard-class>-instantiated-location* 24)
(defconstant *<semi-standard-class>-direct-instance-specializers-location* 25)
(defconstant *<semi-standard-class>-finalized-direct-subclasses-location* 26)
(defconstant *<semi-standard-class>-prototype-location* 27)
;; Preliminary accessors.
(predefun class-current-version (object)
(sys::%record-ref object *<semi-standard-class>-current-version-location*))
(predefun (setf class-current-version) (new-value object)
(setf (sys::%record-ref object *<semi-standard-class>-current-version-location*) new-value))
(predefun class-funcallablep (object)
(sys::%record-ref object *<semi-standard-class>-funcallablep-location*))
(predefun (setf class-funcallablep) (new-value object)
(setf (sys::%record-ref object *<semi-standard-class>-funcallablep-location*) new-value))
(predefun class-fixed-slot-locations (object)
(sys::%record-ref object *<semi-standard-class>-fixed-slot-locations-location*))
(predefun (setf class-fixed-slot-locations) (new-value object)
(setf (sys::%record-ref object *<semi-standard-class>-fixed-slot-locations-location*) new-value))
(predefun class-instantiated (object)
(sys::%record-ref object *<semi-standard-class>-instantiated-location*))
(predefun (setf class-instantiated) (new-value object)
(setf (sys::%record-ref object *<semi-standard-class>-instantiated-location*) new-value))
(predefun class-direct-instance-specializers-table (object)
(sys::%record-ref object *<semi-standard-class>-direct-instance-specializers-location*))
(predefun (setf class-direct-instance-specializers-table) (new-value object)
(setf (sys::%record-ref object *<semi-standard-class>-direct-instance-specializers-location*) new-value))
(predefun class-finalized-direct-subclasses-table (object)
(sys::%record-ref object *<semi-standard-class>-finalized-direct-subclasses-location*))
(predefun (setf class-finalized-direct-subclasses-table) (new-value object)
(setf (sys::%record-ref object *<semi-standard-class>-finalized-direct-subclasses-location*) new-value))
(predefun class-prototype (object)
(sys::%record-ref object *<semi-standard-class>-prototype-location*))
(predefun (setf class-prototype) (new-value object)
(setf (sys::%record-ref object *<semi-standard-class>-prototype-location*) new-value))
;;; ===========================================================================
;;; The class <standard-class> represents classes with the "default" CLOS
;;; behaviour.
(defvar <standard-class> 'standard-class) ; ABI
(defvar *<standard-class>-defclass*
'(defclass standard-class (semi-standard-class)
()
(:fixed-slot-locations t)))
(defvar *<standard-class>-class-version* (make-class-version))
(defconstant *<standard-class>-instance-size* 28)
;; For DEFCLASS macro expansions.
(defconstant *<standard-class>-valid-initialization-keywords* ; ABI
'(:name :direct-superclasses :direct-slots :direct-default-initargs
:documentation :generic-accessors :fixed-slot-locations))
(defconstant *<standard-class>-default-initargs* '(:fixed-slot-locations nil))
;;; ===========================================================================
;;; The classes <funcallable-standard-class> and <funcallable-standard-object>
;;; can be defined later.
(defvar <funcallable-standard-class> nil)
(defvar *<funcallable-standard-class>-class-version* nil)
(defvar <funcallable-standard-object> nil)
;;; ===========================================================================
;;; Type tests.
(defun built-in-class-p (object) ; ABI
(and (std-instance-p object)
(let ((cv (sys::%record-ref object 0)))
; Treat the most frequent cases first, for speed and bootstrapping.
(cond ((eq cv *<standard-class>-class-version*) nil)
((eq cv *<structure-class>-class-version*) nil)
((eq cv *<built-in-class>-class-version*) t)
(t ; Now a slow, but general instanceof test.
(gethash <built-in-class>
(class-all-superclasses (class-of object))))))))
(defun structure-class-p (object) ; ABI
(and (std-instance-p object)
(let ((cv (sys::%record-ref object 0)))
; Treat the most frequent cases first, for speed and bootstrapping.
(cond ((eq cv *<standard-class>-class-version*) nil)
((eq cv *<structure-class>-class-version*) t)
((eq cv *<built-in-class>-class-version*) nil)
(t ; Now a slow, but general instanceof test.
(gethash <structure-class>
(class-all-superclasses (class-of object))))))))
(defun semi-standard-class-p (object)
(and (std-instance-p object)
(let ((cv (sys::%record-ref object 0)))
; Treat the most frequent cases first, for speed and bootstrapping.
(cond ((eq cv *<standard-class>-class-version*) t)
((eq cv *<structure-class>-class-version*) nil)
((eq cv *<built-in-class>-class-version*) nil)
(t ; Now a slow, but general instanceof test.
(gethash <semi-standard-class>
(class-all-superclasses (class-of object))))))))
(defun standard-class-p (object) ; ABI
(and (std-instance-p object)
(let ((cv (sys::%record-ref object 0)))
; Treat the most frequent cases first, for speed and bootstrapping.
(cond ((eq cv *<standard-class>-class-version*) t)
((eq cv *<structure-class>-class-version*) nil)
((eq cv *<built-in-class>-class-version*) nil)
(t ; Now a slow, but general instanceof test.
(gethash <standard-class>
(class-all-superclasses (class-of object))))))))
(sys::def-atomic-type potential-class potential-class-p)
(sys::def-atomic-type defined-class defined-class-p)
(sys::def-atomic-type built-in-class built-in-class-p)
(sys::def-atomic-type structure-class structure-class-p)
(sys::def-atomic-type standard-class standard-class-p)
(defun forward-reference-to-class-p (object)
(and (std-instance-p object)
(gethash <forward-reference-to-class>
(class-all-superclasses (class-of object)))))
;;; ===========================================================================
;;; Copying.
(defun copy-standard-class (class)
(let* ((n (sys::%record-length class))
(copy (allocate-metaobject-instance (sys::%record-ref class 0) n)))
(dotimes (i n) (setf (sys::%record-ref copy i) (sys::%record-ref class i)))
copy))
(defun print-object-<potential-class> (object stream)
(if (and *print-readably* (defined-class-p object))
; Only defined-class instances can be restored through FIND-CLASS.
(write (sys::make-load-time-eval `(FIND-CLASS ',(class-classname object)))
:stream stream)
(print-unreadable-object (object stream :type t)
(let ((name (class-classname object)))
;; The class <string> has two names: cl:string and cs-cl:string.
;; Which one we show, depends on *package*.
(when (and (eq name 'string)
(eq (find-symbol "STRING" *package*) 'cs-cl:string))
(setq name 'cs-cl:string))
(write name :stream stream))
(when (semi-standard-class-p object)
(if (and (slot-boundp object '$current-version)
(class-version-p (class-current-version object))
(slot-boundp object '$precedence-list))
(progn
(when (< (class-initialized object) 3) ; not yet finalized?
(write-string " " stream)
(write :incomplete :stream stream))
;; FIXME: Overhaul this questionable and confusing feature.
(let ((serial (cv-serial (class-current-version object))))
(unless (eql serial 0)
(write-string " " stream)
(write :version :stream stream)
(write-string " " stream)
(write serial :stream stream))))
(progn
(write-string " " stream)
(write :uninitialized :stream stream)))))))
(defun print-object-<forward-reference-to-class> (object stream)
(print-unreadable-object (object stream :type t)
(write (slot-value object '$classname) :stream stream)))
;; Preliminary.
;; Now we can at least print classes.
(predefun print-object (object stream)
(cond ((potential-class-p object) (format stream "#<CLASS ~S>" (class-classname object)))
(t (write-string "#<UNKNOWN>" stream))))
| 36,709 | Common Lisp | .lisp | 665 | 48.455639 | 146 | 0.656092 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 6c8ac729468436b8b18b4d6b93885fffb920ce6fc26385faf4a72d3792030004 | 11,391 | [
-1
] |
11,392 | condition.lisp | ufasoft_lisp/clisp/condition.lisp | ;;; Condition System for CLISP
;;; David Gadbois <[email protected]> 30.11.1993
;;; Bruno Haible 24.11.1993, 2.12.1993 -- 2005
;;; Sam Steingold 1998-2005, 2007-2010
(in-package "COMMON-LISP")
;;; exports:
(export
'(;; types:
restart condition serious-condition error program-error control-error
arithmetic-error division-by-zero floating-point-overflow
floating-point-underflow floating-point-inexact
floating-point-invalid-operation
cell-error unbound-variable undefined-function unbound-slot
type-error package-error print-not-readable parse-error stream-error
end-of-file reader-error file-error storage-condition warning
style-warning simple-condition simple-error simple-type-error simple-warning
;; macros:
define-condition handler-bind ignore-errors handler-case
with-condition-restarts restart-bind restart-case
with-simple-restart check-type assert etypecase ctypecase ecase ccase
;; functions:
make-condition arithmetic-error-operation arithmetic-error-operands
cell-error-name unbound-slot-instance type-error-datum
type-error-expected-type package-error-package print-not-readable-object
stream-error-stream file-error-pathname
simple-condition-format-control simple-condition-format-arguments
signal restart-name compute-restarts find-restart invoke-restart
invoke-restart-interactively invoke-debugger break error cerror warn
;; functions and restart names:
abort continue muffle-warning store-value use-value
;; variables:
*break-on-signals* *debugger-hook*))
;; extensions:
(in-package "EXT")
(export
'(muffle-cerrors appease-cerrors exit-on-error with-restarts os-error
abort-on-error set-global-handler without-global-handlers
source-program-error source-program-error-form source-program-error-detail
simple-condition-format-string simple-charset-type-error retry)
"EXT")
(in-package "CUSTOM")
(common-lisp:export
'(*break-on-warnings* *report-error-print-backtrace*)
"CUSTOM")
(ext:re-export "CUSTOM" "EXT")
(common-lisp:in-package "SYSTEM")
;;; Overview of Concepts
;; A condition is some information about an exceptional situation the program
;; cannot or does not want handle locally.
;; A handler is some code that tries to do recovery from exceptional situations
;; that happen elsewhere, or that decides to transfer control.
;; A restart is a point where control may be transferred to, together with a
;; description what is about to happen in this case.
;;; The CONDITION type
; The condition type system is integrated with CLOS.
(clos:defclass condition () ())
;; 29.3.18. Printing Conditions when *print-escape*
;; and *print-readably* are NIL.
;; <http://www.lisp.org/HyperSpec/Body/sec_9-1-3.html>
(definternational print-condition-format
(t ENGLISH))
(deflocalized print-condition-format ENGLISH
(formatter "Condition of type ~S."))
(clos:defmethod clos:print-object ((condition condition) stream)
(if (or *print-escape* *print-readably*)
(clos:call-next-method)
(progn
(format stream (localized 'print-condition-format) (type-of condition))
condition)))
; Entry-points used by other parts of CLISP.
(defun print-condition (condition stream)
(let ((*print-escape* nil)
(*print-readably* nil))
(print-object condition stream)))
(defun pretty-print-condition (condition stream &key (text-indent 6))
(with-fill-stream (out stream :text-indent text-indent)
(print-condition condition out)))
;;; 29.4.5. Defining Conditions
;;; <http://www.lisp.org/HyperSpec/Body/sec_9-1-2.html>
;; DEFINE-CONDITION, CLtL2 p. 898
(defmacro define-condition (&whole whole-form
name parent-types slot-specs &rest options)
(setq name (check-not-declaration name 'define-condition))
(unless (and (listp parent-types) (every #'symbolp parent-types))
(error-of-type 'source-program-error
:form whole-form
:detail parent-types
(TEXT "~S: the parent-type list must be a list of symbols, not ~S")
'define-condition parent-types))
(unless (listp slot-specs)
(error-of-type 'source-program-error
:form whole-form
:detail slot-specs
(TEXT "~S: the slot description list must be a list, not ~S")
'define-condition slot-specs))
(let ((default-initargs-option nil)
(docstring-option nil)
(report-function nil))
(dolist (option options)
(if (listp option)
(cond ((and (eq (car option) ':DEFAULT-INITARGS) (oddp (length option)))
(setq default-initargs-option option))
((and (keywordp (car option)) (eql (length option) 2))
(case (first option)
(:DOCUMENTATION (setq docstring-option option))
(:REPORT (setq report-function (rest option)))
(T (error-of-type 'source-program-error
:form whole-form
:detail (first option)
(TEXT "~S ~S: unknown option ~S")
'define-condition name (first option)))))
(t
(error-of-type 'source-program-error
:form whole-form
:detail option
(TEXT "~S ~S: invalid syntax in ~S option: ~S")
'define-condition name 'define-condition option)))
(error-of-type 'source-program-error
:form whole-form
:detail option
(TEXT "~S ~S: not a ~S option: ~S")
'define-condition name 'define-condition option)))
(let ((defclass-form
`(CLOS:DEFCLASS ,name
,(or parent-types '(CONDITION))
,slot-specs
,@(if docstring-option `(,docstring-option))
,@(if default-initargs-option `(,default-initargs-option)))))
`(PROGN
,defclass-form
,@(when report-function
`((CLOS:DEFMETHOD PRINT-OBJECT ((CONDITION ,name) STREAM)
(IF (OR *PRINT-ESCAPE* *PRINT-READABLY*)
(CLOS:CALL-NEXT-METHOD)
(PROGN
,(if (stringp (first report-function))
`(WRITE-STRING ,(first report-function) STREAM)
`(FUNCALL (FUNCTION ,@report-function) CONDITION STREAM))
CONDITION)))))
',name))))
;;; 29.4.6. Creating Conditions
(defun find-subclasses-of-type (type class)
"Find all subclasses of CLASS that are subtypes of the given TYPE."
(if (subtypep class type)
(list class)
(delete-duplicates
(loop :for c :in (clos:class-direct-subclasses class)
:nconc (find-subclasses-of-type type c)))))
#+(or) ; not used
(defun prune-subclasses (classes)
"Delete classes that are subclasses of other classes."
(do ((tail classes (cdr tail)) this)
((endp tail) (delete nil classes))
(setq this (car tail))
(when (loop :for c :in classes
;; when THIS is a subclass of C, remove THIS
:thereis (and c (not (eq this c)) (clos::subclassp this c)))
(setf (car tail) nil))))
;; MAKE-CONDITION, CLtL2 p. 901
(defun make-condition (type &rest slot-initializations)
(unless (subtypep type 'condition)
(error-of-type 'error
(TEXT "~S: type ~S is not a subtype of ~S")
'make-condition type 'condition))
(let ((class (or (and (symbolp type) (find-class type nil))
;; not a specific class - find a maximal subclass of
;; CONDITION that has the given TYPE
(car (last (sort (find-subclasses-of-type
type (find-class 'condition))
#'clos::subclassp))))))
(if class
(apply #'clos:make-instance class slot-initializations)
(error-of-type 'error
(TEXT "~S: cannot find a ~S class that is a subtype of ~S")
'make-condition 'condition type))))
;; canonicalize a condition argument, CLtL2 p. 888
(defun try-coerce-to-condition (datum arguments
caller-name
default-type &rest more-initargs)
(typecase datum
(condition
(when arguments
(unless (eq caller-name 'cerror)
(error-of-type 'type-error
:datum arguments :expected-type 'null
(TEXT "~S ~S: superfluous arguments ~S")
caller-name datum arguments)))
datum)
(symbol
(apply #'make-condition datum arguments))
((or string function) ; only this case uses default-type and more-initargs
(apply #'make-condition default-type
:format-control datum
:format-arguments arguments
more-initargs))
(t
(error-of-type 'type-error
:datum datum :expected-type '(or condition symbol string function)
(TEXT "~S: the condition argument must be a string, a symbol or a condition, not ~S")
caller-name datum))))
(defun valid-condition-designator-p (datum+arguments)
(handler-case
(try-coerce-to-condition (car datum+arguments) (cdr datum+arguments)
'coerce-to-condition 'simple-error) ; hmmpf
(ERROR () nil)
(:NO-ERROR (&rest values) (declare (ignore values)) t)))
(defun coerce-to-condition (datum arguments
caller-name
default-type &rest more-initargs)
(handler-case
(apply #'try-coerce-to-condition datum arguments
caller-name default-type more-initargs)
(TYPE-ERROR (error) (error error))
(ERROR (error)
;; ANSI CL wants a type error here.
(error-of-type 'type-error
:datum (cons datum arguments)
:expected-type '(satisfies valid-condition-designator-p)
"~A" error))))
;;; 29.5. Predefined Condition Types
; Hierarchy:
;
; condition
; |
; |-- simple-condition
; |
; |-- serious-condition
; | |
; | |-- error
; | | |
; | | |-- simple-error
; | | |
; | | |-- arithmetic-error
; | | | |
; | | | |-- division-by-zero
; | | | |
; | | | |-- floating-point-overflow
; | | | |
; | | | |-- floating-point-underflow
; | | | |
; | | | |-- floating-point-inexact
; | | | |
; | | | |-- floating-point-invalid-operation
; | | |
; | | |-- cell-error
; | | | |
; | | | |-- unbound-variable
; | | | |
; | | | |-- undefined-function
; | | | |
; | | | |-- unbound-slot
; | | |
; | | |-- control-error
; | | |
; | | |-- file-error
; | | |
; | | |-- os-error
; | | |
; | | |-- package-error
; | | |
; | | |-- print-not-readable
; | | |
; | | |-- program-error
; | | | |
; | | | +---------------------------------------+
; | | | |
; | | |-- parse-error |
; | | | | |
; | | | +-------------------+ |
; | | | | |
; | | |-- stream-error | |
; | | | | | |
; | | | |-- end-of-file | |
; | | | | | |
; | | | +-------------------+-- reader-error |
; | | | |
; | | |-- type-error |
; | | | |
; | | |-- simple-type-error |
; | | | |
; | | +---------------------------------------+-- argument-list-dotted
; | |
; | |-- storage-condition
; | |
; | |-- interrupt-condition
; |
; |-- warning
; |
; |-- simple-warning
; |
; |-- style-warning
; | |
; | |-- simple-style-warning
; |
; |-- clos-warning
; |
; |-- gf-already-called-warning
; |
; |-- gf-replacing-method-warning
;
;; X3J13 writeup <CONDITION-SLOTS:HIDDEN> wants the slot names to be hidden,
;; (e.g. no slot named `package', `stream', `pathname'), hence we prepend $.
; conditions that require interactive intervention
(define-condition serious-condition () ())
; serious conditions that occur deterministically
(define-condition error (serious-condition) ())
; mostly statically detectable errors of a program
(define-condition program-error (error) ())
; all the other errors must be detected by the runtime system
; statically detectable errors of a program, source available
(define-condition source-program-error (program-error)
(;; The "outer-most" bad form, i.e. the list whose first element is the
;; macro or special-operator name.
($form :initarg :form :reader source-program-error-form)
;; The "inner-most" detail of the bad form, e.g., when a string is
;; given as a variable name, this is the string, not the whole form.
($detail :initarg :detail :reader source-program-error-detail)))
; CLISP specific
; not statically detectable errors in program control
(define-condition control-error (error) ())
; errors that occur while doing arithmetic operations
(define-condition arithmetic-error (error)
(($operation :initarg :operation :reader arithmetic-error-operation)
($operands :initarg :operands :reader arithmetic-error-operands)))
; trying to evaluate a mathematical function at a singularity
(define-condition division-by-zero (arithmetic-error) ())
; trying to get too close to infinity in the floating point domain
(define-condition floating-point-overflow (arithmetic-error) ())
; trying to get too close to zero in the floating point domain
(define-condition floating-point-underflow (arithmetic-error) ())
(define-condition floating-point-inexact (arithmetic-error) ())
(define-condition floating-point-invalid-operation (arithmetic-error) ())
; trying to access a location which contains #<UNBOUND>
(define-condition cell-error (error)
(($name :initarg :name :reader cell-error-name)))
; trying to get the value of an unbound variable
(define-condition unbound-variable (cell-error) ())
; trying to get the global function definition of an undefined function
(define-condition undefined-function (cell-error) ())
; trying to get the value of an unbound slot
(define-condition unbound-slot (cell-error)
(($instance :initarg :instance :reader unbound-slot-instance)))
; when some datum does not belong to the expected type
(define-condition type-error (error)
(($datum :initarg :datum :reader type-error-datum)
($expected-type :initarg :expected-type :reader type-error-expected-type)))
; when some keyword does not belong to one of the allowed keywords
; ANSI CL 3.5.1.4., 3.5.1.5. want this to be a subclass of PROGRAM-ERROR.
(define-condition keyword-error (program-error type-error) ())
; CLISP specific
; when some character does not belong to a given character set
(define-condition charset-type-error (type-error) ())
; CLISP specific
; when an argument list in APPLY is dotted
; ANSI CL 3.5.1.2. want this to be a subclass of PROGRAM-ERROR.
; For the use of APPLY in the expansion of the FORMATTER macro, this
; must also be a subclass of TYPE-ERROR.
(define-condition argument-list-dotted (program-error type-error) ())
; CLISP specific
; errors during operation on packages
(define-condition package-error (error)
(($package :initarg :package :reader package-error-package)))
; attempted violation of *PRINT-READABLY*
(define-condition print-not-readable (error)
(($object :initarg :object :reader print-not-readable-object)))
; errors related to parsing
(define-condition parse-error (error) ())
; errors while doing stream I/O
(define-condition stream-error (error)
(($stream :initarg :stream :reader stream-error-stream)))
; unexpected end of stream
(define-condition end-of-file (stream-error) ())
; parsing/tokenization error during READ
(define-condition reader-error (parse-error stream-error) ())
; errors with pathnames, OS level errors with streams
(define-condition file-error (error)
(($pathname :initarg :pathname :reader file-error-pathname)))
; general OS errors
(define-condition os-error (error) ())
; CLISP specific
; "Virtual memory exhausted"
(define-condition storage-condition (serious-condition) ())
; "User break"
(define-condition interrupt-condition (serious-condition) ())
; CLISP specific
; conditions for which user notification is appropriate
(define-condition warning () ())
; conditions which are a matter of programming style (not serious)
(define-condition style-warning (warning) ())
; CLOS user notifications [CLISP specific]
(define-condition clos:clos-warning (warning) ())
; CLOS: generic function is being modified, but has already been called
(define-condition clos:gf-already-called-warning (clos:clos-warning) ())
; CLISP specific
; CLOS: replacing method in a GF
(define-condition clos:gf-replacing-method-warning (clos:clos-warning) ())
; CLISP specific
;; These shouldn't be separate types but we cannot adjoin slots without
;; defining subtypes.
; conditions usually created by SIGNAL
(define-condition simple-condition ()
(($format-control :initarg :format-control :initform nil
:reader simple-condition-format-string ; for CLtL2 backward compatibility
:reader simple-condition-format-control)
($format-arguments :initarg :format-arguments :initform nil
:reader simple-condition-format-arguments))
#|
(:report
(lambda (condition stream)
(let ((fstring (simple-condition-format-control condition)))
(when fstring
(apply #'format stream fstring
(simple-condition-format-arguments condition))))))
|#
)
;; We don't use the :report option here. Instead we define a print-object
;; method which will be executed regardless of the condition type's CPL.
(clos:defmethod print-object :around ((condition simple-condition) stream)
(if (or *print-escape* *print-readably*)
(clos:call-next-method)
(let ((fstring (simple-condition-format-control condition)))
(if fstring
(apply #'format stream fstring (simple-condition-format-arguments condition))
(clos:call-next-method))))
condition)
;; conditions usually created by ERROR or CERROR
(define-condition simple-error (simple-condition error) ())
;; conditions usually created by CHECK-TYPE
(define-condition simple-type-error (simple-condition type-error) ())
;; conditions usually created by WARN
(define-condition simple-warning (simple-condition warning) ())
(define-condition simple-style-warning (simple-condition style-warning) ())
;; CLOS warnings
(define-condition clos::simple-clos-warning (simple-condition clos:clos-warning) ())
(define-condition clos::simple-gf-already-called-warning (simple-condition clos:gf-already-called-warning) ())
(define-condition clos::simple-gf-replacing-method-warning (simple-condition clos:gf-replacing-method-warning) ())
;; All conditions created by the C runtime code are of type simple-condition.
;; Need the following types. Don't use them for discrimination.
(define-condition simple-serious-condition (simple-condition serious-condition) ())
(define-condition simple-program-error (simple-error program-error) ())
(define-condition simple-source-program-error (simple-error source-program-error) ())
(define-condition simple-control-error (simple-error control-error) ())
(define-condition simple-arithmetic-error (simple-error arithmetic-error) ())
(define-condition simple-division-by-zero (simple-error division-by-zero) ())
(define-condition simple-floating-point-overflow (simple-error floating-point-overflow) ())
(define-condition simple-floating-point-underflow (simple-error floating-point-underflow) ())
(define-condition simple-cell-error (simple-error cell-error) ())
(define-condition simple-unbound-variable (simple-error unbound-variable) ())
(define-condition simple-undefined-function (simple-error undefined-function) ())
(define-condition simple-unbound-slot (simple-error unbound-slot) ())
(define-condition simple-keyword-error (simple-error keyword-error) ())
(define-condition simple-charset-type-error (simple-error charset-type-error) ())
(define-condition simple-argument-list-dotted (simple-error argument-list-dotted) ())
(define-condition simple-package-error (simple-error package-error) ())
(define-condition simple-print-not-readable (simple-error print-not-readable) ())
(define-condition simple-parse-error (simple-error parse-error) ())
(define-condition simple-stream-error (simple-error stream-error) ())
(define-condition simple-end-of-file (simple-error end-of-file) ())
(define-condition simple-reader-error (simple-error reader-error) ())
(define-condition simple-file-error (simple-error file-error) ())
(define-condition simple-os-error (simple-error os-error) ())
(define-condition simple-storage-condition (simple-condition storage-condition) ())
(define-condition simple-interrupt-condition (simple-condition interrupt-condition) ())
;; for NO-APPLICABLE-METHOD, NO-PRIMARY-METHOD, NO-NEXT-METHOD
(define-condition method-call-error (simple-error)
(($gf :initarg :generic-function :reader method-call-error-generic-function)
($method :initarg :method :reader method-call-error-method)
($args :initarg :argument-list :reader method-call-error-argument-list)))
(define-condition method-call-type-error
(simple-type-error method-call-error) ())
;; Bootstrapping
(%defclcs
;; The order of the types in this vector must be the same as in lispbibl.d.
'#((condition . simple-condition)
(serious-condition . simple-serious-condition)
(error . simple-error)
(program-error . simple-program-error)
(source-program-error . simple-source-program-error)
(control-error . simple-control-error)
(arithmetic-error . simple-arithmetic-error)
(division-by-zero . simple-division-by-zero)
(floating-point-overflow . simple-floating-point-overflow)
(floating-point-underflow . simple-floating-point-underflow)
(cell-error . simple-cell-error)
(unbound-variable . simple-unbound-variable)
(undefined-function . simple-undefined-function)
(unbound-slot . simple-unbound-slot)
(type-error . simple-type-error)
(keyword-error . simple-keyword-error)
(charset-type-error . simple-charset-type-error)
(argument-list-dotted . simple-argument-list-dotted)
(package-error . simple-package-error)
(print-not-readable . simple-print-not-readable)
(parse-error . simple-parse-error)
(stream-error . simple-stream-error)
(end-of-file . simple-end-of-file)
(reader-error . simple-reader-error)
(file-error . simple-file-error)
(os-error . simple-os-error)
(storage-condition . simple-storage-condition)
(interrupt-condition . simple-interrupt-condition)
(warning . simple-warning)))
;;; Handling and Signalling - Primitives
(defvar *break-on-signals* nil)
#|
;; This would be a possible implementation. However, it forces too many
;; variables into closures although in the most frequent case - no condition
;; at all - they won't be needed. Furthermore, it conses too much.
;; List of active invocations of HANDLER-BIND.
(defvar *handler-clusters* '())
;; HANDLER-BIND, CLtL2 p. 898
(defmacro handler-bind (clauses &body body)
`(LET ((*HANDLER-CLUSTERS*
(CONS
(LIST ,@(mapcar #'(lambda (clause)
(let ((type (first clause))
(function-form (second clause)))
`(CONS ',type ,function-form)))
clauses))
*HANDLER-CLUSTERS*)))
(PROGN ,@body)))
;; SIGNAL, CLtL2 p. 888
(defun signal (datum &rest arguments)
(let ((condition
;; CLtL2 p. 918 specifies this
(coerce-to-condition datum arguments 'signal 'simple-condition)))
(when (typep condition *break-on-signals*)
; Enter the debugger prior to signalling the condition
(restart-case (invoke-debugger condition)
(CONTINUE ())))
; CLtL2 p. 884: "A handler is executed in the dynamic context of the
; signaler, except that the set of available condition handlers will
; have been rebound to the value that was active at the time the condition
; handler was made active."
(let ((*handler-clusters* *handler-clusters*))
(loop
(when (null *handler-clusters*) (return))
(dolist (handler (pop *handler-clusters*))
(when (typep condition (car handler))
(funcall (cdr handler) condition)
(return)))))
nil))
|#
;; HANDLER-BIND, CLtL2 p. 898
;; Since we can build handler frames only in compiled code
;; there is SYS::%HANDLER-BIND which is synonymous to HANDLER-BIND except
;; that SYS::%HANDLER-BIND only occurs in compiled code.
(defmacro handler-bind (clauses &body body)
(let* ((typespecs (mapcar #'first clauses))
(handlers (nconc (mapcar #'rest clauses) (list body)))
(handler-vars (gensym-list (length handlers))))
`(LET ,(mapcar #'list
handler-vars
(mapcar #'(lambda (handler)
`(FUNCTION (LAMBDA () (PROGN ,@handler))))
handlers))
(LOCALLY (DECLARE (COMPILE))
(SYS::%HANDLER-BIND
,(car (last handler-vars))
,@(mapcan #'(lambda (typespec handler-var)
`(',typespec #'(LAMBDA (CONDITION)
(FUNCALL (FUNCALL ,handler-var)
CONDITION))))
typespecs handler-vars))))))
;; SIGNAL, CLtL2 p. 888
;; is in error.d
;;; Handling and Signalling - Part 2
;; IGNORE-ERRORS, CLtL2 p. 897
(defmacro ignore-errors (&body body)
(let ((blockname (gensym "IGNORE-ERRORS-")))
`(BLOCK ,blockname
(HANDLER-BIND
((ERROR #'(LAMBDA (CONDITION)
(RETURN-FROM ,blockname (VALUES NIL CONDITION)))))
,@body))))
;; HANDLER-CASE, CLtL2 p. 895
(defmacro handler-case (&whole whole-form
form &rest clauses)
;; split off the :NO-ERROR clause and
;; add a GO tag to the other clauses (type varlist . body)
(let ((no-error-clause nil) ; the :no-error clause, if found
(extended-clauses '())) ; ((tag type varlist . body) ...)
(do ()
((endp clauses))
(let ((clause (pop clauses)))
(block check-clause
(unless (and (consp clause) (consp (cdr clause))
(listp (second clause)))
(error-of-type 'source-program-error
:form whole-form
:detail clause
(TEXT "~S: illegal syntax of clause ~S")
'handler-case clause))
(when (eq (first clause) ':no-error)
(if (null no-error-clause)
(setq no-error-clause clause)
(warn (TEXT "~S: multiple ~S clauses: ~S and ~S")
'handler-case ':no-error clause no-error-clause))
(return-from check-clause))
(let ((varlist (second clause))) ; known to be a list
(unless (null (cdr varlist))
(error-of-type 'source-program-error
:form whole-form
:detail varlist
(TEXT "~S: too many variables ~S in clause ~S")
'handler-case varlist clause)))
(push (cons (gensym "HANDLER-") clause) extended-clauses))))
(setq extended-clauses (nreverse extended-clauses))
(let ((blockname (gensym "HANDLER-CASE-"))
(tempvar (gensym "CONDITION-")))
`(BLOCK ,blockname
(LET (,tempvar) ; tempvar is IGNORABLE since it is a gensym
(TAGBODY
(RETURN-FROM ,blockname
,(let ((main-form
`(HANDLER-BIND
,(mapcar #'(lambda (xclause)
(let ((tag (first xclause))
(type (first (rest xclause)))
(varlist (second (rest xclause))))
`(,type
#'(LAMBDA (CONDITION)
,(if (null varlist)
`(DECLARE (IGNORE CONDITION))
`(SETQ ,tempvar CONDITION))
(GO ,tag)))))
extended-clauses)
,form)))
(if no-error-clause
`(MULTIPLE-VALUE-CALL #'(LAMBDA ,@(rest no-error-clause))
,main-form)
main-form)))
,@(mapcap #'(lambda (xclause)
(let ((tag (first xclause))
(varlist (second (rest xclause)))
(body (cddr (rest xclause)))) ; may contain declarations
`(,tag
(RETURN-FROM ,blockname
(LET ,(if (null varlist)
'() `((,@varlist ,tempvar)))
,@body)))))
extended-clauses)))))))
;;; Restarts
;; This stuff is needed only once an exception has already occurred. No need
;; to optimize the hell out of it.
; The default test function for restarts always returns T. See CLtL2 p. 905,909.
(defun default-restart-test (condition)
(declare (ignore condition))
t)
; The default interactive function for restarts returns the empty argument list.
(defun default-restart-interactive ()
'())
;; The RESTART type, CLtL2 p. 916
;; Also defines RESTART-NAME, CLtL2 p. 911
;; Also defines MAKE-RESTART, ABI
(defstruct restart
name ; its name, or NIL if it is not named
(test #'default-restart-test) ; function that tests whether this restart
; applies to a given condition
(invoke-tag nil) ; tag used to invoke the restart, or nil
invoke-function ; function used to invoke the restart, if invoke-tag is nil
(report nil) ; function used to print a description of the restart
(interactive #'default-restart-interactive)
; function used to gather additional data from the user
; before invoking the restart
(meaningfulp t) ; whether it makes sense to invoke this restart without
; prior corrective action
)
#| ; We could also define it as a CLOS class:
(clos:defclass restart ()
(name :initarg :name :reader restart-name)
(test :initarg :test :reader restart-test
:initform #'default-restart-test)
(invoke-tag :initarg :invoke-tag :reader restart-invoke-tag
:initform nil)
(invoke-function :initarg :invoke-function :reader restart-invoke-function)
(report :initarg :report :reader restart-report
:initform nil)
(interactive :initarg :interactive :reader restart-interactive
:initform #'default-restart-interactive)
(meaningfulp :initarg :meaningfulp :reader restart-meaningfulp
:initform t))
|#
;; Printing restarts
(clos:defmethod clos:print-object ((restart restart) stream)
(if (or *print-escape* *print-readably*)
(clos:call-next-method)
(let ((report-function (restart-report restart)))
(if report-function
(funcall report-function stream)
(prin1 (restart-name restart) stream))))
restart)
;; Expands to the equivalent of `(MAKE-RESTART :NAME name ...)
;; but makes intelligent use of the defaults to reduce code size.
(defun make-restart-form (name test invoke-tag invoke-function report interactive meaningfulp)
`(MAKE-RESTART
:NAME ,name
,@(if (not (equal test '(FUNCTION DEFAULT-RESTART-TEST)))
`(:TEST ,test))
,@(if (not (equal invoke-tag 'NIL))
`(:INVOKE-TAG ,invoke-tag))
:INVOKE-FUNCTION ,invoke-function
,@(if (not (equal report 'NIL))
`(:REPORT ,report))
,@(if (not (equal interactive '(FUNCTION DEFAULT-RESTART-INTERACTIVE)))
`(:INTERACTIVE ,interactive))
,@(if (not (equal meaningfulp 'T))
`(:MEANINGFULP ,meaningfulp))))
;; The list of active restarts.
(defvar *active-restarts* nil) ; ABI
;; A list of pairs of conditions and restarts associated with them. We have to
;; keep the associations separate because there can be a many-to-many mapping
;; between restarts and conditions, and this mapping has dynamic extent.
(defvar *condition-restarts* nil) ; ABI
; Add an association between a condition and a couple of restarts.
(defun add-condition-restarts (condition restarts) ; ABI
(dolist (restart restarts)
(push (cons condition restart) *condition-restarts*)))
;; WITH-CONDITION-RESTARTS, CLtL2 p. 910
(defmacro with-condition-restarts (condition-form restarts-form &body body)
`(LET ((*CONDITION-RESTARTS* *CONDITION-RESTARTS*))
(ADD-CONDITION-RESTARTS ,condition-form ,restarts-form)
;; ANSI CL does not allow declarations at the beginning of the body, but
;; we do, as an extension.
(LET () ,@body)))
;;; 29.4.8. Finding and Manipulating Restarts
; Tests whether a given restart is applicable to a given condition
(defun applicable-restart-p (restart condition)
(and
(or (null condition)
;; A restart is applicable if it is associated to that condition
;; or if it is not associated to any condition.
(let ((not-at-all t))
(dolist (asso *condition-restarts* not-at-all)
(when (eq (cdr asso) restart)
(if (eq (car asso) condition)
(return t)
(setq not-at-all nil))))))
;; Call the restart's test function:
(funcall (restart-test restart) condition)))
;; COMPUTE-RESTARTS, CLtL2 p. 910
(defun compute-restarts (&optional condition)
(remove-if-not #'(lambda (restart) (applicable-restart-p restart condition))
*active-restarts*))
;; FIND-RESTART, CLtL2 p. 911
; returns a restart or nil
(defun find-restart (restart-identifier &optional condition)
;; cannot use (E)TYPECASE for bootstrapping reasons
(cond ((null restart-identifier)
(error-of-type 'error
(TEXT "~S: ~S is not a valid restart name here. Use ~S instead.")
'find-restart restart-identifier 'compute-restarts))
((symbolp restart-identifier)
;;(find restart-identifier *active-restarts*
;; :test (lambda (ri restart)
;; (and (eq (restart-name restart) ri)
;; (applicable-restart-p restart condition))))
(dolist (restart *active-restarts*)
(when (and (eq (restart-name restart) restart-identifier)
(applicable-restart-p restart condition))
(return restart))))
((typep restart-identifier 'restart)
;;(find restart-identifier *active-restarts*
;; :test (lambda (ri restart)
;; (and (eq restart ri)
;; (applicable-restart-p restart condition))))
(dolist (restart *active-restarts*)
(when (and (eq restart restart-identifier)
(applicable-restart-p restart condition))
(return restart))))
(t (error-of-type 'type-error
:datum restart-identifier :expected-type '(or symbol restart)
(TEXT "~S: invalid restart name ~S")
'find-restart restart-identifier))))
(defun restart-not-found (restart-identifier)
(error-of-type 'control-error
(TEXT "~S: No restart named ~S is visible.")
'invoke-restart restart-identifier))
(defun %invoke-restart (restart arguments)
(if (restart-invoke-tag restart)
(throw (restart-invoke-tag restart) arguments)
(apply (restart-invoke-function restart) arguments)
;; This may return normally, the restart need not transfer control.
;; (See CLtL2 p. 880.)
))
;; INVOKE-RESTART, CLtL2 p. 911
(defun invoke-restart (restart-identifier &rest arguments)
(let ((restart (find-restart restart-identifier)))
(unless restart (restart-not-found restart-identifier))
(%invoke-restart restart arguments)))
(defun invoke-restart-condition (restart-identifier condition &rest arguments)
(let ((restart (find-restart restart-identifier condition)))
(unless restart (restart-not-found restart-identifier))
(%invoke-restart restart arguments)))
(defun invoke-restart-condition-if-exists (restart-identifier condition &rest arguments)
(let ((restart (find-restart restart-identifier condition)))
(when restart
(%invoke-restart restart arguments))))
;; INVOKE-RESTART-INTERACTIVELY, CLtL2 p. 911
(defun invoke-restart-interactively (restart-identifier)
(let ((restart (find-restart restart-identifier)))
(unless restart (restart-not-found restart-identifier))
(let ((arguments (funcall (restart-interactive restart))))
(%invoke-restart restart arguments))))
;;; 29.4.7. Establishing Restarts
;; This conses out the wazoo, but there seems to be no good way around it short
;; of special casing things a zillion ways. The main problem is that someone
;; could write:
;;
;; (restart-bind ((nil *fun-1*
;; :interactive-function *fun-2*
;; :report-function *fun-3*
;; :test-function *fun-4*
;; )) ...)
;;
;; and it is supposed to work.
;; RESTART-BIND, CLtL2 p. 909
(defmacro restart-bind (&whole whole-form
restart-specs &body body)
(setq body `(PROGN ,@body))
(unless (listp restart-specs)
(error-of-type 'source-program-error
:form whole-form
:detail restart-specs
(TEXT "~S: not a list: ~S")
'restart-bind restart-specs))
(if restart-specs
`(LET ((*ACTIVE-RESTARTS*
(LIST*
,@(mapcar #'(lambda (spec)
(unless (and (listp spec) (consp (cdr spec))
(symbolp (first spec)))
(error-of-type 'source-program-error
:form whole-form
:detail spec
(TEXT "~S: invalid restart specification ~S")
'restart-bind spec))
(apply #'(lambda (name function
&key (test-function '(FUNCTION DEFAULT-RESTART-TEST))
(interactive-function '(FUNCTION DEFAULT-RESTART-INTERACTIVE))
(report-function 'NIL)
((meaningfulp meaningfulp) 'T))
(when (and (null name) (eq report-function 'NIL))
;; CLtL2 p. 906: "It is an error if an unnamed restart is used
;; and no report information is provided."
(error-of-type 'source-program-error
:form whole-form
:detail spec
(TEXT "~S: unnamed restarts require ~S to be specified: ~S")
'restart-bind ':REPORT-FUNCTION spec))
(make-restart-form
`',name
test-function
'NIL
function
report-function
interactive-function
meaningfulp))
spec))
restart-specs)
*ACTIVE-RESTARTS*)))
,body)
body))
;; RESTART-CASE, CLtL2 p. 903
;; WITH-RESTARTS
;; Syntax: (RESTART-CASE form {restart-clause}*)
;; (WITH-RESTARTS ({restart-clause}*) {form}*)
;; restart-clause ::= (restart-name arglist {keyword value}* {form}*)
;; | (restart-name {keyword value}* arglist {form}*)
;; There are a number of special cases we could optimize for. If we
;; can determine that we will not have to cons any closures at
;; runtime, then we could statically allocate the list of restarts.
;;
;; Since we have to deal with the wacky way RESTART-CASE interacts with
;; WITH-CONDITION-RESTARTS, we do not go through RESTART-BIND.
(eval-when (compile load eval)
(defun expand-restart-case (caller whole-form restart-clauses form)
(unless (listp restart-clauses)
(error-of-type 'source-program-error
:form whole-form
:detail restart-clauses
(TEXT "~S: not a list: ~S")
caller restart-clauses))
(let ((xclauses ;; list of expanded clauses
;; ((tag name test interactive report lambdalist . body) ...)
(mapcar
#'(lambda (restart-clause &aux (clause restart-clause))
(unless (and (consp clause) (consp (cdr clause))
(symbolp (first clause)))
(error-of-type 'source-program-error
:form whole-form
:detail clause
(TEXT "~S: invalid restart specification ~S")
caller clause))
(let ((name (pop clause))
(passed-arglist nil)
(passed-keywords nil)
arglist
(keywords '()))
(loop
(when (endp clause) (return))
(cond ((and (not passed-arglist) (listp (first clause)))
(setq arglist (pop clause))
(setq passed-arglist t)
(when keywords (setq passed-keywords t)))
((and (not passed-keywords) (consp (cdr clause))
(symbolp (first clause)))
(push (pop clause) keywords)
(push (pop clause) keywords))
(t (return))))
(unless passed-arglist
(error-of-type 'source-program-error
:form whole-form
:detail clause
(TEXT "~S: missing lambda list in restart specification ~S")
caller clause))
(multiple-value-bind (test interactive report meaningfulp)
(apply #'(lambda (&key (test 'DEFAULT-RESTART-TEST)
(interactive 'DEFAULT-RESTART-INTERACTIVE)
(report 'DEFAULT-RESTART-REPORT)
((meaningfulp meaningfulp) 'T))
(values test interactive report meaningfulp))
(nreverse keywords))
(when (and (null name) (eq report 'DEFAULT-RESTART-REPORT))
;; CLtL2 p. 906: "It is an error if an unnamed restart
;; is used and no report information is provided."
(error-of-type 'source-program-error
:form whole-form
:detail restart-clause
(TEXT "~S: unnamed restarts require ~S to be specified: ~S")
caller ':REPORT restart-clause))
(when (and (consp arglist) (not (member (first arglist) lambda-list-keywords))
(eq interactive 'DEFAULT-RESTART-INTERACTIVE))
;; restart takes required arguments but does not have an
;; interactive function that will prompt for them.
(warn (TEXT "~S: restart cannot be invoked interactively because it is missing a ~S option: ~S")
caller ':INTERACTIVE restart-clause))
`(,(gensym) ,name ,test ,interactive ,report ,meaningfulp
,arglist ,@clause))))
restart-clauses))
(blockname (gensym "RESTART-"))
(arglistvar (gensym "ARGS-"))
(associate
;; Yick. As a pretty lame way of allowing for an association
;; between conditions and restarts, RESTART-CASE has to
;; notice if its body is signalling a condition, and, if so,
;; associate the restarts with the condition.
(and (consp form)
(case (first form)
((SIGNAL ERROR CERROR WARN ERROR-OF-TYPE) t)
(t nil))
(gensym "RESTARTS-"))))
`(BLOCK ,blockname
(LET (,arglistvar) ; arglistvar is IGNORABLE since it is a gensym
(TAGBODY
,(let ((restart-forms
(mapcar #'(lambda (xclause)
(let ((tag (first xclause))
(name (second xclause))
(test (third xclause))
(interactive (fourth xclause))
(report (fifth xclause))
(meaningfulp (sixth xclause)))
(make-restart-form
`',name
`(FUNCTION ,test)
'NIL
`(FUNCTION (LAMBDA (&REST ARGUMENTS)
(SETQ ,arglistvar ARGUMENTS)
(GO ,tag)))
(if (eq report 'DEFAULT-RESTART-REPORT)
`NIL
`(FUNCTION
,(if (stringp report)
`(LAMBDA (STREAM)
(WRITE-STRING ,report STREAM))
report)))
`(FUNCTION ,interactive)
meaningfulp)))
xclauses))
(form `(RETURN-FROM ,blockname ,form)))
`(LET* ,(if associate
`((,associate (LIST ,@restart-forms))
(*ACTIVE-RESTARTS*
(APPEND ,associate *ACTIVE-RESTARTS*))
(*CONDITION-RESTARTS* *CONDITION-RESTARTS*))
`((*ACTIVE-RESTARTS*
(LIST* ,@restart-forms *ACTIVE-RESTARTS*))))
,(if associate
#| ; This code resignals the condition in a different dynamic context!
`(LET ((CONDITION
(HANDLER-CASE ,form ; evaluate the form
(CONDITION (C) C)))) ; catch the condition
(WITH-CONDITION-RESTARTS CONDITION ,associate ; associate the condition with the restarts
(SIGNAL CONDITION))) ; resignal the condition
|#
#| ; This code invokes the debugger even if it shouldn't!
`(HANDLER-BIND
((CONDITION ; catch the condition
#'(LAMBDA (CONDITION)
(WITH-CONDITION-RESTARTS CONDITION ,associate ; associate the condition with the restarts
(SIGNAL CONDITION) ; resignal the condition
(INVOKE-DEBUGGER CONDITION))))) ; this is weird!
,form)
|#
`(HANDLER-BIND
((CONDITION ; catch the condition
#'(LAMBDA (CONDITION)
(ADD-CONDITION-RESTARTS CONDITION ,associate) ; associate the condition with the restarts
(SIGNAL CONDITION)))) ; resignal the condition
,form)
form)))
,@(mapcap #'(lambda (xclause)
(let ((tag (first xclause))
(lambdabody (cddddr (cddr xclause))))
`(,tag
(RETURN-FROM ,blockname
(APPLY (FUNCTION (LAMBDA ,@lambdabody))
,arglistvar)))))
xclauses))))))
)
(defmacro restart-case (&whole whole-form
form &rest restart-clauses &environment env)
(expand-restart-case 'restart-case whole-form restart-clauses
(macroexpand form env)))
(defmacro with-restarts (&whole whole-form
restart-clauses &body body &environment env)
(expand-restart-case 'with-restarts whole-form restart-clauses
(if (cdr body)
(cons 'PROGN body)
(macroexpand (car body) env))))
;; WITH-SIMPLE-RESTART, CLtL2 p. 902
(defmacro with-simple-restart ((name format-string &rest format-arguments) &body body)
(if (or format-arguments (not (constantp format-string)))
`(WITH-RESTARTS
((,name
:REPORT (LAMBDA (STREAM) (FORMAT STREAM ,format-string ,@format-arguments))
() (VALUES NIL T)))
,@body)
;; Here's an example of how we can easily optimize things. There is no
;; need to refer to anything in the lexical environment, so we can avoid
;; consing a restart at run time.
(let ((blockname (gensym "RESTART-"))
(tag (gensym "SIMPLE-RESTART-")))
`(BLOCK ,blockname
(CATCH ',tag
(LET ((*ACTIVE-RESTARTS*
(CONS
(LOAD-TIME-VALUE
(MAKE-RESTART :NAME ',name
:INVOKE-TAG ',tag
:REPORT #'(LAMBDA (STREAM)
(FORMAT STREAM ,format-string))))
*ACTIVE-RESTARTS*)))
(RETURN-FROM ,blockname (PROGN ,@body))))
(VALUES NIL T)))))
;;; 29.4.10. Restart Functions
;; These functions are customary way to pass control from a handler to a
;; restart. They just invoke the restart of the same name.
;; ABORT, CLtL2 p. 913
(defun abort (&optional condition)
(invoke-restart-condition 'ABORT condition))
;; CONTINUE, CLtL2 p. 913
(defun continue (&optional condition)
(invoke-restart-condition-if-exists 'CONTINUE condition))
;; MUFFLE-WARNING, CLtL2 p. 913
(defun muffle-warning (&optional condition)
(invoke-restart-condition 'MUFFLE-WARNING condition))
;; STORE-VALUE, CLtL2 p. 913
(defun store-value (value &optional condition)
(invoke-restart-condition-if-exists 'STORE-VALUE condition value))
;; USE-VALUE, CLtL2 p. 914
(defun use-value (value &optional condition)
(invoke-restart-condition-if-exists 'USE-VALUE condition value))
;; like CONTINUE but is not triggered by ^D
(defun retry (&optional condition)
(invoke-restart-condition-if-exists 'RETRY condition))
;;; 29.4.2. Assertions
;; These macros supersede the corresponding ones from macros2.lisp.
;; Queries the user for the values to put into the given place.
;; Returns a fresh list of length place-numvalues.
(defun prompt-for-new-value (place place-numvalues &optional instead-p) ; ABI
(cond ((= place-numvalues 1)
(format *debug-io*
(if instead-p
(concatenate 'string "~&" (TEXT "Use instead~@[ of ~S~]")
(prompt-finish))
(prompt-for-new-value-string))
place)
(list (eval (read *debug-io*))))
(t (do ((ii 1 (1+ ii)) res)
((> ii place-numvalues) (nreverse res))
(fresh-line *debug-io*)
(format *debug-io*
(if instead-p
(TEXT "Use instead of ~S [value ~D of ~D]~A")
(TEXT "New ~S [value ~D of ~D]~A"))
place ii place-numvalues (prompt-finish))
(push (eval (read *debug-io*)) res)))))
;; CHECK-TYPE, CLtL2 p. 889
(defmacro check-type (place typespec &optional (string nil) &environment env)
(let ((tag1 (gensym "CHECK-TYPE-"))
(tag2 (gensym "OK-"))
(var (gensym)))
`(TAGBODY
,tag1
(LET ((,var ,place))
(WHEN (TYPEP ,var ',typespec) (GO ,tag2))
(CHECK-TYPE-FAILED ',place ,var
#'(LAMBDA (NEW-VALUE) (SETF ,place NEW-VALUE))
,(length (nth-value 2 (get-setf-expansion place env)))
,string ',typespec))
(GO ,tag1)
,tag2)))
(defun check-type-failed (place place-oldvalue place-setter place-numvalues string typespec) ; ABI
(restart-case
(error-of-type 'type-error
:datum place-oldvalue :expected-type typespec
(type-error-string)
(check-type-error-string place string typespec)
place-oldvalue)
;; Only one restart. Call it STORE-VALUE, not CONTINUE, so that it's not
;; chosen by "continue".
(STORE-VALUE (new-value)
:report (lambda (stream)
(format stream (report-one-new-value-string) place))
:interactive (lambda () (prompt-for-new-value place place-numvalues))
(funcall place-setter new-value))))
;; ASSERT, CLtL2 p. 891
(defmacro assert (test-form &optional (place-list nil) (datum nil) &rest args
&environment env)
(let ((tag1 (gensym "ASSERT-"))
(tag2 (gensym "OK-")))
`(TAGBODY
,tag1
(WHEN ,test-form (GO ,tag2))
(,@(if place-list
(let ((all-numvalues '())
(all-setter-vars '())
(all-setter-forms '()))
(do ((pl place-list (cdr pl)))
((endp pl))
(multiple-value-bind (temps subforms stores setterform getterform)
(get-setf-expansion (car pl) env)
(declare (ignore getterform))
(push (length stores) all-numvalues)
(setq all-setter-vars
(revappend stores all-setter-vars))
(push (wrap-let* (mapcar #'list temps subforms) setterform)
all-setter-forms)))
(setq all-numvalues (nreverse all-numvalues))
(setq all-setter-vars (nreverse all-setter-vars))
(setq all-setter-forms (nreverse all-setter-forms))
`(ASSERT-FAILED ',place-list ',all-numvalues
#'(LAMBDA ,all-setter-vars ,@all-setter-forms)))
`(SIMPLE-ASSERT-FAILED))
,@(if datum
`(NIL ,datum ,@args) ; use coerce-to-condition??
`((ASSERT-ERROR-STRING ',test-form))))
(GO ,tag1)
,tag2)))
(defun assert-failed (place-list place-numvalues-list places-setter error-string &rest condition-datum+args) ; ABI
(restart-case
;; No need for explicit association, see APPLICABLE-RESTART-P.
(if error-string
(error ; of-type ??
"~A" error-string)
(apply #'error condition-datum+args)) ; use coerce-to-condition??
;; Only one restart: CONTINUE.
(CONTINUE (&rest new-values)
:REPORT (lambda (stream)
(apply #'format stream
(if (= (length place-list) 1)
(report-one-new-value-string)
(report-new-values-string))
place-list))
:INTERACTIVE (lambda ()
(mapcan #'(lambda (place place-numvalues)
(prompt-for-new-value place place-numvalues))
place-list place-numvalues-list))
(apply places-setter new-values))))
(defun simple-assert-failed (error-string &rest condition-datum+args) ; ABI
(restart-case
;; No need for explicit association, see APPLICABLE-RESTART-P.
(if error-string
(error ; of-type ??
"~A" error-string)
(apply #'error condition-datum+args)) ; use coerce-to-condition??
;; Only one restart: CONTINUE.
;; But mark it as not meaningful, because it leads to user frustration.
(CONTINUE ()
:REPORT (lambda (stream) (format stream (report-no-new-value-string)))
MEANINGFULP nil)))
(defun correctable-error (options condition)
(let ((restarts
(mapcar (lambda (option)
(destructuring-bind (name report . return) option
(make-restart
:name (etypecase name
(string (intern name *keyword-package*))
(symbol name))
:report (lambda (s) (princ report s))
:interactive (if (consp return)
(lambda ()
(apply (car return) (cdr return)))
#'default-restart-interactive)
:invoke-function
(if (consp return)
(lambda (value) ; get `value' from :INTERACTIVE
(return-from correctable-error value))
(lambda ()
(return-from correctable-error return))))))
options)))
(with-condition-restarts condition restarts
(let ((*active-restarts* (nconc restarts *active-restarts*)))
(error condition)))))
;; Report an error and try to recover by asking the user to supply a value.
;; Returns
;; 1. value supplied by the user,
;; 2. a boolean indicating whether PLACE should be filled, or 0 for FDEFINITION
(defun check-value (place condition)
(let ((restarts
(nconc
(when (eq place 'SYSTEM::PATHNAME-ENCODING)
(setq place '*pathname-encoding*) ; make it look nicer
(list (make-restart ; for direntry_to_string
:name 'CONTINUE
:report (lambda (stream)
(format stream
(TEXT "Discard this directory entry")))
:invoke-function
(lambda () (return-from check-value (values nil 0))))))
(unless (eq place '*pathname-encoding*)
(list (make-restart
:name 'USE-VALUE
:report
(lambda (stream)
(format stream (report-one-new-value-string-instead)
place))
:interactive (lambda () (prompt-for-new-value place 1 t))
:invoke-function
(lambda (val)
(return-from check-value (values val nil))))))
(when (and (consp place) (eq 'fdefinition (car place)))
(list (make-restart ; for check_fdefinition() only!
:name 'RETRY
:report (lambda (stream)
(format stream (report-no-new-value-string)))
:invoke-function
(lambda ()
(return-from check-value (values nil 0))))))
(when place
(list (make-restart
:name 'STORE-VALUE
:report
(lambda (stream)
(format stream (report-one-new-value-string) place))
:interactive (lambda () (prompt-for-new-value place 1))
:invoke-function
(lambda (val)
(return-from check-value (values val t)))))))))
(with-condition-restarts condition restarts
(let ((*active-restarts* (nconc restarts *active-restarts*)))
(error condition)))))
(defun retry-function-call (condition function arguments)
(with-restarts ((retry
:report (lambda (out)
(format out (TEXT "try calling ~S again")
(function-name function)))
() (return-from retry-function-call
(apply function arguments)))
(return
:report (lambda (out)
(format out (TEXT "specify return values")))
:interactive (lambda () (prompt-for-new-value 'VALUES 1))
(l) (return-from retry-function-call (values-list l))))
(with-condition-restarts condition
(list (find-restart 'RETRY) (find-restart 'RETURN))
(error condition))))
;; redefine the function in init.lisp, used by LOAD
(eval-when (compile) (fmakunbound 'eval-loaded-form)) ; avoid a warning
;; FILE is the *LOAD-TRUENAME* of the file being loaded
;; we cannot use *LOAD-TRUENAME* because when the error is in a nested LOAD,
;; we will get the truename of the inner-most file instead of the current one
(defun eval-loaded-form (obj file)
(flet ((report (word obj out)
(write-string word out)
(if (compiled-function-p obj)
(write (closure-name obj) :stream out
:pretty nil :escape nil)
(write obj :stream out :pretty nil :escape nil
:level 2 :length 3))))
(restart-case (eval-loaded-form-low obj)
(skip ()
:report (lambda (out) (report (TEXT "skip ") obj out))
:interactive default-restart-interactive
(return-from eval-loaded-form 'skip))
(retry ()
:report (lambda (out) (report (TEXT "retry ") obj out))
:interactive default-restart-interactive
(return-from eval-loaded-form 'retry))
(stop ()
:report (lambda (out) (format out (TEXT "stop loading file ~A") file))
:interactive default-restart-interactive
(return-from eval-loaded-form 'stop)))))
;;; 29.4.3. Exhaustive Case Analysis
;; These macros supersede the corresponding ones from macros2.lisp.
(flet ((parenthesize-keys (clauses)
;; PARENTHESIZE-KEYS is necessary to avoid confusing
;; the symbols OTHERWISE and T used as keys, with the same
;; symbols used in the syntax of the non exhaustive CASE.
(mapcar #'(lambda (c)
(cond ((or (eq (car c) 't)
(eq (car c) 'otherwise))
(warn (TEXT "~S used as a key in ~S, it would be better to use parentheses.")
(car c) c)
(cons (list (car c)) (cdr c)))
(t c)))
clauses)))
(flet ((typecase-errorstring (keyform keyclauselist)
(let ((typelist (mapcar #'first keyclauselist)))
`(TYPECASE-ERROR-STRING ',keyform ',typelist)))
(typecase-expected-type (keyclauselist)
`(OR ,@(mapcar #'first keyclauselist)))
(case-errorstring (keyform keyclauselist)
(let ((caselist
(mapcap #'(lambda (keyclause)
(setq keyclause (car keyclause))
(if (listp keyclause) keyclause (list keyclause)))
keyclauselist)))
`(CASE-ERROR-STRING ',keyform ',caselist)))
(case-expected-type (keyclauselist)
`(MEMBER ,@(mapcap #'(lambda (keyclause)
(setq keyclause (car keyclause))
(if (listp keyclause)
keyclause (list keyclause)))
keyclauselist)))
(simply-error (casename form clauselist errorstring expected-type)
(let ((var (gensym (string-concat (symbol-name casename) "-KEY-"))))
`(LET ((,var ,form))
(,casename ,var ,@(parenthesize-keys clauselist)
;; if a clause contains an OTHERWISE or T key,
;; it is treated as a normal key, as per CLHS.
(OTHERWISE
(ETYPECASE-FAILED ,var ,errorstring ',expected-type))))))
(retry-loop (casename place clauselist errorstring expected-type env)
(let ((g (gensym (symbol-name casename)))
(h (gensym "RETRY-")))
`(BLOCK ,g
(TAGBODY
,h
(RETURN-FROM ,g
(,casename ,place ,@(parenthesize-keys clauselist)
;; if a clause contains an OTHERWISE or T key,
;; it is treated as a normal key, as per CLHS.
(OTHERWISE
(CTYPECASE-FAILED ',place ,place
#'(LAMBDA (NEW-VALUE) (SETF ,place NEW-VALUE))
,(length (nth-value 2 (get-setf-expansion place env)))
,errorstring ',expected-type)
(GO ,h)))))))))
(defmacro etypecase (keyform &rest keyclauselist)
(if (assoc t keyclauselist)
`(TYPECASE ,keyform ,@keyclauselist)
(simply-error 'TYPECASE keyform keyclauselist
(typecase-errorstring keyform keyclauselist)
(typecase-expected-type keyclauselist))))
(defmacro ctypecase (keyplace &rest keyclauselist &environment env)
(if (assoc t keyclauselist)
`(TYPECASE ,keyplace ,@keyclauselist)
(retry-loop 'TYPECASE keyplace keyclauselist
(typecase-errorstring keyplace keyclauselist)
(typecase-expected-type keyclauselist)
env)))
(defmacro ecase (keyform &rest keyclauselist)
(simply-error 'CASE keyform keyclauselist
(case-errorstring keyform keyclauselist)
(case-expected-type keyclauselist)))
(defmacro ccase (keyform &rest keyclauselist &environment env)
(retry-loop 'CASE keyform keyclauselist
(case-errorstring keyform keyclauselist)
(case-expected-type keyclauselist)
env))
;; for use in macros: when a file with generated ffi forms is compiled
;; (prime example: gtk.lisp), any error message can become cryptic because
;; the sources are efemeral - unless the whole form is printed in the error
(defmacro mecase (whole-form keyform &rest keyclauselist)
(simply-error 'CASE keyform keyclauselist
`(format nil (TEXT "In form ~S~%~A") ,whole-form
,(case-errorstring keyform keyclauselist))
(case-expected-type keyclauselist)))
) )
(defun etypecase-failed (value errorstring expected-type) ; ABI
(error-of-type 'type-error
:datum value :expected-type expected-type
(type-error-string)
errorstring value))
(defun ctypecase-failed (place place-oldvalue place-setter place-numvalues errorstring expected-type) ; ABI
(restart-case
(progn ; no need for explicit association, see applicable-restart-p
(error-of-type 'type-error
:datum place-oldvalue :expected-type expected-type
(type-error-string)
errorstring
place-oldvalue))
;; Only one restart. Call it STORE-VALUE, not CONTINUE, so that it's not
;; chosen by "continue".
(STORE-VALUE (new-value)
:report (lambda (stream)
(format stream (report-one-new-value-string) place))
:interactive (lambda () (prompt-for-new-value place place-numvalues))
(funcall place-setter new-value))))
;;; 29.4.11. Debugging Utilities
(defvar *debugger-hook* nil)
;; INVOKE-DEBUGGER, CLtL2 p. 915
; is in error.d
;; BREAK, CLtL2 p. 914
; (BREAK [format-string {arg}*])
; we call INVOKE-DEBUGGER and therefore need a condition.
(defun break (&optional (format-string "Break") &rest args)
(if (not *use-clcs*)
(progn
(fresh-line *error-output*)
(apply #'format *error-output*
(concatenate 'string "*** - " format-string)
args)
(elastic-newline *error-output*)
(funcall *break-driver* t))
(let ((condition
(make-condition 'simple-condition
:format-control format-string
:format-arguments args))
(*debugger-hook* nil)) ; Issue 91
(with-restarts
((CONTINUE
:report (lambda (stream)
(format stream (TEXT "Return from ~S loop")
'break))
()))
(with-condition-restarts condition (list (find-restart 'CONTINUE))
(invoke-debugger condition)))))
nil)
;;; 29.4.1. Signaling Conditions
;; ERROR, CLtL2 p. 886
#| ; is in error.d
(defun error (errorstring &rest args)
(if (or *error-handler* (not *use-clcs*))
(progn
(if *error-handler*
(apply *error-handler* nil errorstring args)
(progn
(fresh-line *error-output*)
(write-string "*** - " *error-output*)
(apply #'format *error-output* errorstring args)
(elastic-newline *error-output*)))
(funcall *break-driver* nil))
(let ((condition (coerce-to-condition errorstring args 'error 'simple-error)))
(signal condition)
(invoke-debugger condition))))
|#
;; CERROR, CLtL2 p. 887
(defun cerror (continue-format-string error-format-string &rest args)
(if *error-handler*
(apply *error-handler*
(or continue-format-string t) error-format-string args)
(if (not *use-clcs*)
(progn
(fresh-line *error-output*)
(write-string "** - " *error-output*)
(write-string (TEXT "Continuable Error") *error-output*)
(terpri *error-output*)
(apply #'format *error-output* error-format-string args)
(elastic-newline *error-output*)
(fresh-line *debug-io*)
(if (interactive-stream-p *debug-io*)
(progn
(write-string (TEXT "If you continue (by typing 'continue'): ")
*debug-io*)
(apply #'format *debug-io* continue-format-string args)
(elastic-newline *debug-io*)
(funcall *break-driver* t))
(progn
(apply #'format *debug-io* continue-format-string args)
(elastic-newline *debug-io*))))
(let ((condition (coerce-to-condition error-format-string args
'cerror 'simple-error)))
(with-restarts
((CONTINUE
:report (lambda (stream)
(apply #'format stream continue-format-string args))
()))
(with-condition-restarts condition (list (find-restart 'CONTINUE))
(signal condition)
(invoke-debugger condition))))))
nil)
;;; 29.4.9. Warnings
(defvar *break-on-warnings* nil)
(defun warn-of-type (type format-string &rest args)
(if (not *use-clcs*)
(progn
(fresh-line *error-output*)
(write-string (TEXT "WARNING:") *error-output*)
(terpri *error-output*)
(apply #'format *error-output* format-string args)
(elastic-newline *error-output*)
(when *break-on-warnings* (funcall *break-driver* t)))
(block warn
(let ((condition (coerce-to-condition format-string args 'warn type)))
(unless (typep condition 'warning)
(error-of-type 'type-error
:datum condition :expected-type 'warning
(TEXT "~S: This is more serious than a warning: ~A")
'warn condition))
(when (boundp '*warning-count*) (incf *warning-count*))
(when (and (boundp '*style-warning-count*)
(typep condition 'style-warning))
(incf *style-warning-count*))
(with-restarts ((MUFFLE-WARNING () (return-from warn)))
(with-condition-restarts condition (list (find-restart 'MUFFLE-WARNING))
(signal condition)))
(fresh-line *error-output*)
(let ((first-line-prefix (TEXT "WARNING: ")))
(write-string first-line-prefix *error-output*)
(pretty-print-condition
condition *error-output*
:text-indent (string-width first-line-prefix)))
(elastic-newline *error-output*)
(when *break-on-warnings*
(with-restarts
((CONTINUE :report
(lambda (stream)
(format stream (TEXT "Return from ~S loop") 'break))
() (return-from warn)))
(with-condition-restarts condition (list (find-restart 'CONTINUE))
;; We don't call (invoke-debugger condition) because that
;; would tell the user about a "Continuable error".
;; Actually, it is only a warning!
(funcall *break-driver* nil condition nil)))))))
nil)
;; for X3J13 Issue COMPILER-DIAGNOSTICS:USE-HANDLER
(defun c-warning (type format-string &rest args)
(let ((*error-output* *c-error-output*))
(apply #'warn-of-type type (string-concat "~A" format-string)
(c-current-location) args)))
(defun c-cerror (location detail format-string &rest args)
(let ((*error-output* *c-error-output*))
(apply #'cerror-of-type (TEXT "Ignore the error and proceed")
'simple-source-program-error
:form *form* :detail detail
(string-concat location format-string)
args)))
;; WARN, CLtL2 p. 912
;; (WARN format-string {arg}*)
(defun warn (format-string &rest args)
(apply #'warn-of-type 'simple-warning format-string args))
#|
Todo:
29.3.6 29.3.7 29.3.8 29.3.9 29.3.10
29.3.11 29.3.12 29.3.13 29.3.14 29.3.15 29.3.16 29.3.17 29.3.18
29.4. 29.4.9 29.4.11
29.5.
|#
;; Miscellaneous functions that use condition macros.
#+LOGICAL-PATHNAMES
(defun valid-logical-pathname-string-p (string)
(handler-case (logical-pathname string)
(TYPE-ERROR () nil)
(:NO-ERROR (&rest values) (declare (ignore values)) t)))
;; Extensions. They assume *USE-CLCS* is T.
; Which restarts are suitable for automatic invocation?
; - Only CONTINUE restarts.
; E.g. (check-type x float) has no CONTINUE restart.
; - Only meaningful CONTINUE restarts.
; E.g. (assert (= 3 4)) has a CONTINUE restart, but it is not meaningful.
; - Only non-interactive CONTINUE restarts.
; E.g. (assert (>= i 0) (i)) has a CONTINUE restart, but it prompts the user
; for a new value of i.
(defun find-noninteractively-invokable-continue-restart (condition)
(let ((restart (find-restart 'CONTINUE condition)))
(and restart
(restart-meaningfulp restart)
(eq (restart-interactive restart) #'default-restart-interactive)
restart)))
(defun muffle-cerror (condition) ; ABI
(let ((restart (find-noninteractively-invokable-continue-restart condition)))
(when restart
(invoke-restart restart))))
(defmacro muffle-cerrors (&body body)
"(MUFFLE-CERRORS {form}*) executes the forms, but when a continuable
error occurs, the CONTINUE restart is silently invoked."
`(HANDLER-BIND ((ERROR #'MUFFLE-CERROR))
,@body))
#|| ; This works as well, but looks more like a hack.
(defmacro muffle-cerrors (&body body)
(let ((old-debugger-hook (gensym)))
`(LET* ((,old-debugger-hook *DEBUGGER-HOOK*)
(*DEBUGGER-HOOK*
(LAMBDA (CONDITION DEBUGGER-HOOK)
(CONTINUE CONDITION)
(WHEN ,old-debugger-hook
(FUNCALL ,old-debugger-hook CONDITION ,old-debugger-hook)))))
(PROGN ,@body))))
||#
(defun appease-cerror (condition) ; ABI
(let ((restart (find-noninteractively-invokable-continue-restart condition)))
(when restart
(warn #'(lambda (stream &rest arguments)
(print-condition condition stream)
(let ((report-function (restart-report restart)))
(when report-function
(terpri stream)
(funcall report-function stream)))
arguments))
(invoke-restart restart))))
(defmacro appease-cerrors (&body body)
"(APPEASE-CERRORS {form}*) executes the forms, but turns continuable errors
into warnings. A continuable error is signalled again as a warning, then
its CONTINUE restart is invoked."
`(HANDLER-BIND ((ERROR #'APPEASE-CERROR))
,@body))
(defvar *report-error-print-backtrace* nil)
(defun report-error (condition)
(when *report-error-print-backtrace*
(print-backtrace :out *error-output*))
(fresh-line *error-output*)
(write-string "*** - " *error-output*)
(pretty-print-condition condition *error-output*)
(elastic-newline *error-output*))
(defun exitunconditionally (condition) ; ABI
(report-error condition)
(exit t)) ; exit Lisp with error
(defun exitonerror (condition) ; ABI
(unless (find-noninteractively-invokable-continue-restart condition)
(exitunconditionally condition)))
(defmacro exit-on-error (&body body)
"(EXIT-ON-ERROR {form}*) executes the forms, but exits Lisp if a
non-continuable error or a Ctrl-C interrupt occurs."
`(HANDLER-BIND ((INTERRUPT-CONDITION #'EXITUNCONDITIONALLY)
(SERIOUS-CONDITION #'EXITONERROR))
,@body))
(defun abortonerror (condition) ; ABI
(report-error condition)
(invoke-restart (find-restart 'abort condition)))
(defmacro abort-on-error (&body body)
"(ABORT-ON-ERROR {form}*) executes the forms and aborts all errors."
`(HANDLER-BIND ((SERIOUS-CONDITION #'ABORTONERROR))
,@body))
(defgeneric global-handler (condition)
(:method-combination progn)
(:documentation "the global error handler, methods should not return")
(:method progn ((condition t)) nil))
(defun set-global-handler (condition-name handler)
"Make HANDLER handle CONDITION globally.
HANDLER should be funcallable (symbol or function).
If it returns, the next applicable error handler is invoked.
When HANDLER is nil, remove the global handler for CONDITION.
Returns the added or removed method(s)."
(let ((clos::*enable-clos-warnings* nil))
(cond (handler ; install handler
(clos::do-defmethod 'global-handler
(lambda (backpointer)
(declare (ignore backpointer)) ; we do not need CALL-NEXT-METHOD
(list
(lambda (condition)
;; avoid infinite recursion by disabling the handler
(let ((clos::*enable-clos-warnings* nil)
(old-handler (set-global-handler condition-name nil)))
(unwind-protect (funcall handler condition)
(when old-handler
(clos:add-method #'global-handler old-handler)))))
t)) ; wants-next-method-p == NIL
(list :qualifiers #1='(progn) :lambda-list '(condition)
'clos::signature #(1 0 NIL NIL NIL NIL)
:specializers (list (find-class condition-name)))))
((consp condition-name) ; install all these handlers
(dolist (handler condition-name)
(clos:add-method #'global-handler handler)))
((null condition-name) ; remove all global handlers
(let ((handlers '()))
(dolist (method (clos::generic-function-methods #'global-handler))
(unless (equal '#,(list (find-class 't))
(clos::method-specializers method))
(push method handlers)
(clos:remove-method #'global-handler method)))
handlers))
((symbolp condition-name) ; remove handler for this condition
(let ((method (find-method #'global-handler #1#
(list (find-class condition-name)) nil)))
(when method
(clos:remove-method #'global-handler method)
method)))
(t (error "~S(~S ~S): invalid arguments"
'set-global-handler condition-name handler)))))
(defmacro without-global-handlers (&body body)
"Remove all global handlers, execute BODY, restore the handlers."
(let ((handlers (gensym "HANDLERS-")))
`(let ((,handlers (set-global-handler nil nil)))
(unwind-protect (progn ,@body)
(set-global-handler ,handlers nil)))))
;;; <http://www.lisp.org/HyperSpec/Body/dec_type.html>:
;;; A symbol cannot be both the name of a type and the name of a
;;; declaration. Defining a symbol as the name of a class, structure,
;;; condition, or type, when the symbol has been declared as a
;;; declaration name, or vice versa, signals an error.
(defun check-not-type (symbol caller)
(loop
(setq symbol (check-symbol symbol caller))
(when (handler-bind ((error #'(lambda (c)
(declare (ignore c))
(return-from check-not-type symbol))))
(type-expand symbol))
(with-restarts ((use-value (new-value)
:report
(lambda (stream)
(format stream (report-one-new-value-string-instead)
symbol))
:interactive
(lambda () (prompt-for-new-value symbol 1 t))
(setq symbol new-value)))
(error (TEXT "~S: ~S defines a type, cannot be declared a ~S")
caller symbol 'declaration)))))
(defun check-not-declaration (symbol caller)
(loop
(setq symbol (check-symbol symbol caller))
(unless (memq symbol (cdar *toplevel-denv*))
(return-from check-not-declaration symbol))
(with-restarts ((use-value (new-value)
:report
(lambda (stream)
(format stream (report-one-new-value-string-instead)
symbol))
:interactive
(lambda () (prompt-for-new-value symbol 1 t))
(setq symbol new-value)))
(error (TEXT "~S: ~S names a ~S, cannot name a type")
caller symbol 'declaration))))
| 83,773 | Common Lisp | .lisp | 1,736 | 37.109447 | 123 | 0.577669 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 2094333c9a068acff9a0b2c08982e26c4dafea4c654c05d6f877c03c0b0c2fc6 | 11,392 | [
-1
] |
11,393 | cmacros.lisp | ufasoft_lisp/clisp/cmacros.lisp | ;;; CLISP Compiler Macros
;;; Sam Steingold 2001-05-09
;;; Bruno Haible 2005
;;; CLHS 3.2.2.1 http://www.lisp.org/HyperSpec/Body/sec_3-2-2-1.html
(in-package "SYSTEM")
;; a legitimate option is to keep the `compiler-macro' definition of the
;; symbol in a global hash-table instead of the `symbol-plist'.
;; the reason we use plists is that
;; * this performance issue is related only to the compilation speed,
;; not the execution speed
;; * the plists are actually quite short:
;; [non-standard functions & macros used in this snippet are in CLOCC:
;; compose: <http://clocc.sf.net/clocc/src/port/ext.lisp>
;; standard-deviation: <http://clocc.sf.net/clocc/src/cllib/math.lisp>
;; top-bottom-ui: <http://clocc.sf.net/clocc/src/cllib/sorted.lisp>
;; CLOCC is available at <http://clocc.sf.net>]
;; (let ((al nil)
;; (acc (compose length symbol-plist)))
;; (do-all-symbols (sy) (push sy al))
;; (delete-duplicates al :test #'eq)
;; (format t "~&none:~10t ~5:d~%" (count-if #'zerop al :key acc))
;; (multiple-value-bind (de me le) (standard-deviation al :key acc)
;; (format t "std dev:~10t ~5f~%mean:~10t ~5f~%length:~10t ~5:d~%"
;; de me le))
;; (top-bottom-ui al 5 nil nil :key acc))
;; none: 4,206
;; std dev: 1.874
;; mean: .6492
;; length: 5,089
;; Top/Bottom: list: 5,089 records.
;; Top (5):
;; 1: hostent-addrtype ==> 10
;; 2: hostent-aliases ==> 10
;; 3: hostent-addr-list ==> 10
;; 4: hostent-name ==> 10
;; 5: dir-key-info-type ==> 10
;; also, compiler macros are probably not used often anyway.
;; At any rate, if someone will want to switch to a global hash-table,
;; one needs to change only the following two functions:
;; compiler-macro-function and
;; (setf compiler-macro-function)
(defun compiler-macro-function (name &optional environment)
(declare (ignore environment))
(setq name (check-function-name name 'compiler-macro-function))
(get (get-funname-symbol name) 'compiler-macro))
(defun (setf compiler-macro-function) (newf name &optional environment) ; ABI
(declare (ignore environment))
(setq name (check-function-name name '(setf compiler-macro-function)))
(setf (get (get-funname-symbol name) 'compiler-macro) newf))
;; (proclaim '(inline function-form-p simple-function-form-p))
;; Test whether the form is (FUNCTION ...).
(defun function-form-p (form)
(and (consp form) (eq (car form) 'FUNCTION)
(consp (cdr form)) (null (cddr form))))
;; Test whether the form is #'symbol or #'(SETF symbol).
(defun simple-function-form-p (form)
(and (function-form-p form) (function-name-p (second form))))
;; (funcall (function foo) ...) ==> (foo ...)
(defun strip-funcall-form (form) ; ABI
(if (and (eq (car form) 'funcall) (simple-function-form-p (second form)))
(cons (second (second form)) (cddr form))
form))
(defmacro define-compiler-macro (&whole whole-form
name args &body body)
(declare (ignore name args body))
(multiple-value-bind (expansion expansion-lambdabody name lambdalist docstring)
(sys::make-macro-expansion (cdr whole-form) whole-form
#'function-name-p 'strip-funcall-form)
(declare (ignore expansion-lambdabody lambdalist))
(sys::check-redefinition name 'define-compiler-macro
(and (compiler-macro-function name)
(TEXT "compiler macro")))
`(EVAL-WHEN (COMPILE LOAD EVAL)
,@(when docstring
`((SYSTEM::%SET-DOCUMENTATION ',name 'COMPILER-MACRO ,docstring)))
(SETF (COMPILER-MACRO-FUNCTION ',name) ,expansion)
',name)))
| 3,693 | Common Lisp | .lisp | 77 | 44.038961 | 81 | 0.652897 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | a2d2809c12b62b7f798c971a5e2cb3d0a8b17136420a1e71048805020d9f60fc | 11,393 | [
-1
] |
11,394 | type.lisp | ufasoft_lisp/clisp/type.lisp | ;;;; TYPEP und Verwandtes
;;;; Michael Stoll, 21. 10. 1988
;;;; Bruno Haible, 10.6.1989
;;;; Sam Steingold 2000-2005, 2007
;;; Datenstrukturen für TYPEP:
;;; - Ein Type-Specifier-Symbol hat auf seiner Propertyliste unter dem
;;; Indikator SYS::TYPE-SYMBOL eine Funktion von einem Argument, die
;;; testet, ob ein Objekt vom richtigen Typ ist.
;;; - Ein Symbol, das eine Type-Specifier-Liste beginnen kann, hat auf seiner
;;; Propertyliste unter dem Indikator SYS::TYPE-LIST eine Funktion von
;;; einem Argument für das zu testende Objekt und zusätzlichen Argumenten
;;; für die Listenelemente.
;;; - Ein Symbol, das als Typmacro definiert wurde, hat auf seiner Property-
;;; liste unter dem Indikator SYSTEM::DEFTYPE-EXPANDER den zugehörigen
;;; Expander: eine Funktion, die den zu expandierenden Type-Specifier (eine
;;; mindestens einelementige Liste) als Argument bekommt.
(in-package "EXT")
(export '(type-expand))
(in-package "SYSTEM")
; vorläufig, solange bis clos.lisp geladen wird:
(eval-when (eval)
(predefun clos::built-in-class-p (object) (declare (ignore object)) nil))
(unless (fboundp 'clos::class-name)
(defun clos::class-name (c) (declare (ignore c)) nil)
)
(defun typespec-error (fun type)
(error-of-type 'error
(TEXT "~S: invalid type specification ~S")
fun type
) )
;; ============================================================================
;; return the CLOS class named by TYPESPEC or NIL
(defun clos-class (typespec)
(let ((cc (get typespec 'CLOS::CLOSCLASS)))
(when (and cc (clos::defined-class-p cc) (eq (clos:class-name cc) typespec))
cc)))
;;; TYPEP, CLTL S. 72, S. 42-51
(defun typep (x y &optional env &aux f) ; x = Objekt, y = Typ
(declare (ignore env))
(setq y (expand-deftype y))
(cond
((symbolp y)
(cond ((setq f (get y 'TYPE-SYMBOL)) (funcall f x))
((setq f (get y 'TYPE-LIST)) (funcall f x))
((setq f (get y 'DEFSTRUCT-DESCRIPTION)) (ds-typep x y f))
((setq f (clos-class y))
; It's not worth handling structure classes specially here.
(clos::typep-class x f))
(t (typespec-error 'typep y))
) )
((and (consp y) (symbolp (first y)))
(cond
((and (eq (first y) 'SATISFIES) (eql (length y) 2))
(unless (symbolp (second y))
(error-of-type 'error
(TEXT "~S: argument to SATISFIES must be a symbol: ~S")
'typep (second y)
) )
(if (funcall (symbol-function (second y)) x) t nil)
)
((eq (first y) 'MEMBER)
(if (member x (rest y)) t nil)
)
((and (eq (first y) 'EQL) (eql (length y) 2))
(eql x (second y))
)
((and (eq (first y) 'NOT) (eql (length y) 2))
(not (typep x (second y)))
)
((eq (first y) 'AND)
(dolist (type (rest y) t)
(unless (typep x type) (return nil))
) )
((eq (first y) 'OR)
(dolist (type (rest y) nil)
(when (typep x type) (return t))
) )
((setq f (get (first y) 'TYPE-LIST)) (apply f x (rest y)))
(t (typespec-error 'typep y))
) )
((clos::defined-class-p y) (clos::typep-class x y))
((clos::eql-specializer-p y) (eql x (clos::eql-specializer-singleton y)))
((encodingp y) (charset-typep x y))
(t (typespec-error 'typep y))
) )
;; ----------------------------------------------------------------------------
;; UPGRADED-ARRAY-ELEMENT-TYPE is a lattice homomorphism, see
;; ANSI CL 15.1.2.1.
(defun upgraded-array-element-type (type &optional environment)
(declare (ignore environment))
;; see array.d
(case type
((BIT) 'BIT)
((CHARACTER) 'CHARACTER)
((T) 'T)
((NIL) 'NIL)
(t (if (subtypep type 'NIL)
'NIL
(multiple-value-bind (low high) (sys::subtype-integer type)
; Es gilt (or (null low) (subtypep type `(INTEGER ,low ,high)))
(if (and (integerp low) (not (minusp low)) (integerp high))
(let ((l (integer-length high)))
; Es gilt (subtypep type `(UNSIGNED-BYTE ,l))
(cond ((<= l 1) 'BIT)
((<= l 2) '(UNSIGNED-BYTE 2))
((<= l 4) '(UNSIGNED-BYTE 4))
((<= l 8) '(UNSIGNED-BYTE 8))
((<= l 16) '(UNSIGNED-BYTE 16))
((<= l 32) '(UNSIGNED-BYTE 32))
(t 'T)))
(if (subtypep type 'CHARACTER)
'CHARACTER
'T)))))))
;; ----------------------------------------------------------------------------
;; UPGRADED-COMPLEX-PART-TYPE is a lattice homomorphism, see
;; HyperSpec/Body/fun_complex.html and HyperSpec/Body/syscla_complex.html,
;; and an idempotent. Therefore
;; (subtypep (upgraded-complex-part-type T1) (upgraded-complex-part-type T2))
;; is equivalent to
;; (subtypep T1 (upgraded-complex-part-type T2))
;; (Proof: Let U T be an abbreviation for (upgraded-complex-part-type T).
;; If U T1 <= U T2, then T1 <= U T1 <= U T2.
;; If T1 <= U T2, then by homomorphism U T1 <= U U T2 = U T2.)
;;
;; For _any_ CL implementation, you could define
;; (defun upgraded-complex-part-type (type) 'REAL)
;; Likewise for _any_ CL implementation, you could define
;; (defun upgraded-complex-part-type (type) type)
;; or - again for _any_ CL implementation:
;; (defun upgraded-complex-part-type (type)
;; (cond ((subtypep type 'NIL) 'NIL)
;; ((subtypep type 'SHORT-FLOAT) 'SHORT-FLOAT)
;; ((subtypep type 'SINGLE-FLOAT) 'SINGLE-FLOAT)
;; ((subtypep type 'DOUBLE-FLOAT) 'DOUBLE-FLOAT)
;; ((subtypep type 'LONG-FLOAT) 'LONG-FLOAT)
;; ((subtypep type 'RATIONAL) 'RATIONAL)
;; ((subtypep type 'REAL) 'REAL)
;; (t (error ...))))
;; The reason is that a complex number is immutable: no setters for the
;; realpart and imagpart exist.
;;
;; We choose the second implementation because it allows the most precise
;; type inference.
(defun upgraded-complex-part-type (type &optional environment)
(declare (ignore environment))
(if (subtypep type 'REAL)
type
(error-of-type 'error
(TEXT "~S: type ~S is not a subtype of ~S")
'upgraded-complex-part-type type 'real)))
;; ----------------------------------------------------------------------------
;; Macros for defining the various built-in "atomic type specifier"s and
;; "compound type specifier"s. The following macros add information for both
;; the TYPEP function above and the c-TYPEP in the compiler.
; Alist symbol -> funname, used by the compiler.
(defparameter c-typep-alist1 '())
; Alist symbol -> lambdabody, used by the compiler.
(defparameter c-typep-alist2 '())
; Alist symbol -> expander function, used by the compiler.
(defparameter c-typep-alist3 '())
; (def-atomic-type symbol function-name)
; defines an atomic type. The function-name designates a function taking one
; argument and returning a generalized boolean value. It can be either a
; symbol or a lambda expression.
(defmacro def-atomic-type (symbol funname)
(let ((lambdap (and (consp funname) (eq (car funname) 'LAMBDA))))
`(PROGN
(SETF (GET ',symbol 'TYPE-SYMBOL)
,(if lambdap
`(FUNCTION ,(concat-pnames "TYPE-SYMBOL-" symbol) ,funname)
`(FUNCTION ,funname)
)
)
,(if lambdap
`(SETQ C-TYPEP-ALIST2
(NCONC C-TYPEP-ALIST2 (LIST (CONS ',symbol ',(cdr funname))))
)
`(SETQ C-TYPEP-ALIST1
(NCONC C-TYPEP-ALIST1 (LIST (CONS ',symbol ',funname)))
)
)
',symbol
)
) )
; (def-compound-type symbol lambda-list (x) check-form typep-form c-typep-form)
; defines a compound type. The lambda-list is of the form (&optional ...)
; where the arguments come from the CDR of the type specifier.
; For typep-form, x is an object.
; For c-typep-form, x is a multiply evaluatable form (actually a gensym).
; check-form is a form performing error checking, may call `error'.
; typep-form should return a generalized boolean value.
; c-typep-form should produce a form returning a generalized boolean value.
(defmacro def-compound-type (symbol lambdalist (var) check-form typep-form c-typep-form)
`(PROGN
(SETF (GET ',symbol 'TYPE-LIST)
(FUNCTION ,(concat-pnames "TYPE-LIST-" symbol)
(LAMBDA (,var ,@lambdalist)
,@(if check-form
`((MACROLET ((ERROR (&REST ERROR-ARGS)
(LIST* 'ERROR-OF-TYPE ''ERROR ERROR-ARGS)
))
,check-form
))
)
,typep-form
) ) )
(SETQ C-TYPEP-ALIST3
(NCONC C-TYPEP-ALIST3
(LIST (CONS ',symbol
#'(LAMBDA (,var ,@lambdalist &REST ILLEGAL-ARGS)
(DECLARE (IGNORE ILLEGAL-ARGS))
,@(if check-form
`((MACROLET ((ERROR (&REST ERROR-ARGS)
(LIST 'PROGN
(LIST* 'C-WARN ERROR-ARGS)
'(THROW 'C-TYPEP NIL)
)) )
,check-form
))
)
,c-typep-form
)
) ) ) )
',symbol
)
)
; CLtL1 p. 43
(def-atomic-type ARRAY arrayp)
(def-atomic-type ATOM atom)
(def-atomic-type BASE-CHAR
#+BASE-CHAR=CHARACTER
characterp
#-BASE-CHAR=CHARACTER
(lambda (x) (and (characterp x) (base-char-p x)))
)
(def-atomic-type BASE-STRING
(lambda (x)
(and (stringp x)
(eq (array-element-type x)
#+BASE-CHAR=CHARACTER 'CHARACTER #-BASE-CHAR=CHARACTER 'BASE-CHAR
) ) ) )
(def-atomic-type BIGNUM (lambda (x) (and (integerp x) (not (fixnump x)))))
(def-atomic-type BIT (lambda (x) (or (eql x 0) (eql x 1))))
(def-atomic-type BIT-VECTOR bit-vector-p)
(def-atomic-type BOOLEAN (lambda (x) (or (eq x 'nil) (eq x 't))))
(def-atomic-type BYTE bytep)
(def-atomic-type CHARACTER characterp)
(def-atomic-type COMPILED-FUNCTION compiled-function-p)
(def-atomic-type COMPLEX complexp)
(def-atomic-type CONS consp)
(def-atomic-type DOUBLE-FLOAT double-float-p)
(def-atomic-type ENCODING encodingp)
(def-atomic-type EXTENDED-CHAR
#+BASE-CHAR=CHARACTER
(lambda (x) (declare (ignore x)) nil)
#-BASE-CHAR=CHARACTER
(lambda (x) (and (characterp x) (not (base-char-p x))))
)
(def-atomic-type FIXNUM fixnump)
(def-atomic-type FLOAT floatp)
(def-atomic-type FUNCTION functionp)
(def-atomic-type HASH-TABLE hash-table-p)
(def-atomic-type INTEGER integerp)
(def-atomic-type KEYWORD keywordp)
(def-atomic-type LIST listp)
#+LOGICAL-PATHNAMES
(def-atomic-type LOGICAL-PATHNAME logical-pathname-p)
(def-atomic-type LONG-FLOAT long-float-p)
(def-atomic-type NIL
(lambda (x) (declare (ignore x)) nil)
)
(def-atomic-type NULL null)
(def-atomic-type NUMBER numberp)
(def-atomic-type PACKAGE packagep)
(def-atomic-type PATHNAME pathnamep)
(def-atomic-type RANDOM-STATE random-state-p)
(def-atomic-type RATIO
(lambda (x) (and (rationalp x) (not (integerp x))))
)
(def-atomic-type RATIONAL rationalp)
(def-atomic-type READTABLE readtablep)
(def-atomic-type REAL realp)
(def-atomic-type SEQUENCE sequencep)
(def-atomic-type SHORT-FLOAT short-float-p)
(def-atomic-type SIMPLE-ARRAY simple-array-p)
(def-atomic-type SIMPLE-BASE-STRING
(lambda (x)
(and (simple-string-p x)
(eq (array-element-type x)
#+BASE-CHAR=CHARACTER 'CHARACTER #-BASE-CHAR=CHARACTER 'BASE-CHAR
) ) ) )
(def-atomic-type SIMPLE-BIT-VECTOR simple-bit-vector-p)
(def-atomic-type SIMPLE-STRING simple-string-p)
(def-atomic-type SIMPLE-VECTOR simple-vector-p)
(def-atomic-type SINGLE-FLOAT single-float-p)
(defun %standard-char-p (x) (and (characterp x) (standard-char-p x))) ; ABI
(def-atomic-type STANDARD-CHAR %standard-char-p)
(def-atomic-type CLOS:STANDARD-OBJECT clos::std-instance-p)
(def-atomic-type STREAM streamp)
(def-atomic-type FILE-STREAM file-stream-p)
(def-atomic-type SYNONYM-STREAM synonym-stream-p)
(def-atomic-type BROADCAST-STREAM broadcast-stream-p)
(def-atomic-type CONCATENATED-STREAM concatenated-stream-p)
(def-atomic-type TWO-WAY-STREAM two-way-stream-p)
(def-atomic-type ECHO-STREAM echo-stream-p)
(def-atomic-type STRING-STREAM string-stream-p)
(def-atomic-type STRING stringp)
(def-atomic-type STRING-CHAR characterp)
(def-atomic-type CLOS:STRUCTURE-OBJECT clos::structure-object-p)
(def-atomic-type SYMBOL symbolp)
(def-atomic-type T (lambda (x) (declare (ignore x)) t))
;; foreign1.lisp is loaded after this file,
;; so these symbols are not external yet
#+ffi
(def-atomic-type ffi::foreign-function
(lambda (x) (eq 'ffi::foreign-function (type-of x))))
#+ffi
(def-atomic-type ffi::foreign-variable
(lambda (x) (eq 'ffi::foreign-variable (type-of x))))
#+ffi
(def-atomic-type ffi::foreign-address
(lambda (x) (eq 'ffi::foreign-address (type-of x))))
;; see lispbibl.d (#define FOREIGN) and predtype.d (TYPE-OF):
#+(or unix ffi win32)
(def-atomic-type foreign-pointer
(lambda (x) (eq 'foreign-pointer (type-of x))))
;; threads.lisp is loaded after this file,
;; so these symbols are not external yet
#+mt (def-atomic-type threads::thread threads::threadp)
#+mt (def-atomic-type threads::mutex threads::mutexp)
#+mt (def-atomic-type threads::exemption threads::exemptionp)
(def-atomic-type VECTOR vectorp)
(def-atomic-type PLIST
(lambda (x) (multiple-value-bind (length tail) (list-length-dotted x)
(and (null tail) (evenp length)))))
(defmacro ensure-dim (type dim)
;; make sure DIM is a valid dimension
`(unless (or (eq ,dim '*) (typep ,dim `(INTEGER 0 (,ARRAY-DIMENSION-LIMIT))))
(error (TEXT "~S: dimension ~S is invalid") ',type ,dim)))
(defmacro ensure-rank (type rank)
;; make sure RANK is a valid rank
`(unless (typep ,rank `(INTEGER 0 (,ARRAY-RANK-LIMIT)))
(error (TEXT "~S: rank ~S is invalid") ',type ,rank)))
; CLtL1 p. 46-50
(defun c-typep-array (tester el-type dims x)
`(AND (,tester ,x)
,@(if (eq el-type '*)
'()
`((EQUAL (ARRAY-ELEMENT-TYPE ,x) ',(upgraded-array-element-type el-type)))
)
,@(if (eq dims '*)
'()
(if (numberp dims)
`((EQL ,dims (ARRAY-RANK ,x)))
`((EQL ,(length dims) (ARRAY-RANK ,x))
,@(let ((i 0))
(mapcap #'(lambda (dim)
(prog1
(if (eq dim '*)
'()
`((EQL ',dim (ARRAY-DIMENSION ,x ,i)))
)
(incf i)
) )
dims
) )
)
) )
)
)
(defun c-typep-vector (tester size x)
`(AND (,tester ,x)
,@(if (eq size '*)
'()
`((EQL ',size (ARRAY-DIMENSION ,x 0)))
)
)
)
(defun typep-number-test (x low high test type)
(and (funcall test x)
(cond ((eq low '*))
((funcall test low) (<= low x))
((and (consp low) (null (rest low)) (funcall test (first low)))
(< (first low) x)
)
(t (error-of-type 'error
#1=(TEXT "~S: argument to ~S must be *, ~S or a list of ~S: ~S")
'typep type type type low
) ) )
(cond ((eq high '*))
((funcall test high) (>= high x))
((and (consp high) (null (rest high)) (funcall test (first high)))
(> (first high) x)
)
(t (error-of-type 'error
#1# 'typep type type type high
) ) ) ) )
(defun c-typep-number (caller tester low high x)
`(AND (,tester ,x)
,@(cond ((eq low '*) '())
((funcall tester low) `((<= ,low ,x)))
((and (consp low) (null (rest low)) (funcall tester (first low)))
`((< ,(first low) ,x))
)
(t (c-warn #1=(TEXT "~S: argument to ~S must be *, ~S or a list of ~S: ~S")
'typep caller caller caller low
)
(throw 'c-TYPEP nil)
) )
,@(cond ((eq high '*) '())
((funcall tester high) `((>= ,high ,x)))
((and (consp high) (null (rest high)) (funcall tester (first high)))
`((> ,(first high) ,x))
)
(t (c-warn #1# 'typep caller caller caller high)
(throw 'c-TYPEP nil)
) )
)
)
(def-compound-type ARRAY (&optional (el-type '*) (dims '*)) (x)
(unless (eq dims '*)
(if (numberp dims)
(ensure-rank ARRAY dims)
(dolist (dim dims) (ensure-dim ARRAY dim))))
(and (arrayp x)
(or (eq el-type '*)
(equal (array-element-type x) (upgraded-array-element-type el-type))
)
(or (eq dims '*)
(if (numberp dims)
(eql dims (array-rank x))
(and (eql (length dims) (array-rank x))
(every #'(lambda (a b) (or (eq a '*) (eql a b)))
dims (array-dimensions x)
) ) ) ) )
(c-typep-array 'ARRAYP el-type dims x)
)
(def-compound-type SIMPLE-ARRAY (&optional (el-type '*) (dims '*)) (x)
(unless (eq dims '*)
(if (numberp dims)
(ensure-rank SIMPLE-ARRAY dims)
(dolist (dim dims) (ensure-dim SIMPLE-ARRAY dim))))
(and (simple-array-p x)
(or (eq el-type '*)
(equal (array-element-type x) (upgraded-array-element-type el-type))
)
(or (eq dims '*)
(if (numberp dims)
(eql dims (array-rank x))
(and (eql (length dims) (array-rank x))
(every #'(lambda (a b) (or (eq a '*) (eql a b)))
dims (array-dimensions x)
) ) ) ) )
(c-typep-array 'SIMPLE-ARRAY-P el-type dims x)
)
(def-compound-type VECTOR (&optional (el-type '*) (size '*)) (x)
(ensure-dim VECTOR size)
(and (vectorp x)
(or (eq el-type '*)
(equal (array-element-type x) (upgraded-array-element-type el-type))
)
(or (eq size '*) (eql (array-dimension x 0) size))
)
`(AND (VECTORP ,x)
,@(if (eq el-type '*)
'()
`((EQUAL (ARRAY-ELEMENT-TYPE ,x) ',(upgraded-array-element-type el-type)))
)
,@(if (eq size '*)
'()
`((EQL (ARRAY-DIMENSION ,x 0) ',size))
)
)
)
(def-compound-type SIMPLE-VECTOR (&optional (size '*)) (x)
(ensure-dim SIMPLE-VECTOR size)
(and (simple-vector-p x)
(or (eq size '*) (eql size (array-dimension x 0)))
)
(c-typep-vector 'SIMPLE-VECTOR-P size x)
)
(def-compound-type COMPLEX (&optional (rtype '*) (itype rtype)) (x)
nil
(and (complexp x)
(or (eq rtype '*)
(typep (realpart x) (upgraded-complex-part-type rtype)))
(or (eq itype '*)
(typep (imagpart x) (upgraded-complex-part-type itype))))
`(AND (COMPLEXP ,x)
,@(if (eq rtype '*)
'()
`((TYPEP (REALPART ,x) ',(upgraded-complex-part-type rtype))))
,@(if (eq itype '*)
'()
`((TYPEP (IMAGPART ,x) ',(upgraded-complex-part-type itype))))))
(def-compound-type INTEGER (&optional (low '*) (high '*)) (x)
nil
(typep-number-test x low high #'integerp 'INTEGER)
(c-typep-number 'INTEGER 'INTEGERP low high x)
)
(def-compound-type MOD (n) (x)
(unless (integerp n)
(error (TEXT "~S: argument to MOD must be an integer: ~S")
'typep n
) )
(and (integerp x) (<= 0 x) (< x n))
`(AND (INTEGERP ,x) (NOT (MINUSP ,x)) (< ,x ,n))
)
(def-compound-type SIGNED-BYTE (&optional (n '*)) (x)
(unless (or (eq n '*) (integerp n))
(error (TEXT "~S: argument to ~S must be an integer or * : ~S")
'typep 'signed-byte n))
(and (integerp x) (or (eq n '*) (< (integer-length x) n)))
`(AND (INTEGERP ,x)
,@(if (eq n '*) '() `((< (INTEGER-LENGTH ,x) ,n)))
)
)
(def-compound-type UNSIGNED-BYTE (&optional (n '*)) (x)
(unless (or (eq n '*) (integerp n))
(error (TEXT "~S: argument to ~S must be an integer or * : ~S")
'typep 'unsigned-byte n))
(and (integerp x)
(not (minusp x))
(or (eq n '*) (<= (integer-length x) n))
)
`(AND (INTEGERP ,x) (NOT (MINUSP ,x))
,@(if (eq n '*) '() `((<= (INTEGER-LENGTH ,x) ,n)))
)
)
(def-compound-type REAL (&optional (low '*) (high '*)) (x)
nil
(typep-number-test x low high #'realp 'REAL)
(c-typep-number 'REAL 'REALP low high x)
)
(def-compound-type RATIONAL (&optional (low '*) (high '*)) (x)
nil
(typep-number-test x low high #'rationalp 'RATIONAL)
(c-typep-number 'RATIONAL 'RATIONALP low high x)
)
(def-compound-type FLOAT (&optional (low '*) (high '*)) (x)
nil
(typep-number-test x low high #'floatp 'FLOAT)
(c-typep-number 'FLOAT 'FLOATP low high x)
)
(def-compound-type SHORT-FLOAT (&optional (low '*) (high '*)) (x)
nil
(typep-number-test x low high #'short-float-p 'SHORT-FLOAT)
(c-typep-number 'SHORT-FLOAT 'SHORT-FLOAT-P low high x)
)
(def-compound-type SINGLE-FLOAT (&optional (low '*) (high '*)) (x)
nil
(typep-number-test x low high #'single-float-p 'SINGLE-FLOAT)
(c-typep-number 'SINGLE-FLOAT 'SINGLE-FLOAT-P low high x)
)
(def-compound-type DOUBLE-FLOAT (&optional (low '*) (high '*)) (x)
nil
(typep-number-test x low high #'double-float-p 'DOUBLE-FLOAT)
(c-typep-number 'DOUBLE-FLOAT 'DOUBLE-FLOAT-P low high x)
)
(def-compound-type LONG-FLOAT (&optional (low '*) (high '*)) (x)
nil
(typep-number-test x low high #'long-float-p 'LONG-FLOAT)
(c-typep-number 'LONG-FLOAT 'LONG-FLOAT-P low high x)
)
(def-compound-type STRING (&optional (size '*)) (x)
(ensure-dim STRING size)
(and (stringp x)
(or (eq size '*) (eql size (array-dimension x 0)))
)
(c-typep-vector 'STRINGP size x)
)
(def-compound-type SIMPLE-STRING (&optional (size '*)) (x)
(ensure-dim SIMPLE-STRING size)
(and (simple-string-p x)
(or (eq size '*) (eql size (array-dimension x 0)))
)
(c-typep-vector 'SIMPLE-STRING-P size x)
)
(def-compound-type BASE-STRING (&optional (size '*)) (x)
(ensure-dim BASE-STRING size)
(and (stringp x)
(or (eq size '*) (eql size (array-dimension x 0)))
)
(c-typep-vector 'STRINGP size x)
)
(def-compound-type SIMPLE-BASE-STRING (&optional (size '*)) (x)
(ensure-dim SIMPLE-BASE-STRING size)
(and (simple-string-p x)
(or (eq size '*) (eql size (array-dimension x 0)))
)
(c-typep-vector 'SIMPLE-STRING-P size x)
)
(def-compound-type BIT-VECTOR (&optional (size '*)) (x)
(ensure-dim BIT-VECTOR size)
(and (bit-vector-p x)
(or (eq size '*) (eql size (array-dimension x 0)))
)
(c-typep-vector 'BIT-VECTOR-P size x)
)
(def-compound-type SIMPLE-BIT-VECTOR (&optional (size '*)) (x)
(ensure-dim SIMPLE-BIT-VECTOR size)
(and (simple-bit-vector-p x)
(or (eq size '*) (eql size (array-dimension x 0)))
)
(c-typep-vector 'SIMPLE-BIT-VECTOR-P size x)
)
(def-compound-type CONS (&optional (car-type '*) (cdr-type '*)) (x)
nil
(and (consp x)
(or (eq car-type '*) (typep (car x) car-type))
(or (eq cdr-type '*) (typep (cdr x) cdr-type))
)
`(AND (CONSP ,x)
,@(if (eq car-type '*) '() `((TYPEP (CAR ,x) ',car-type)))
,@(if (eq cdr-type '*) '() `((TYPEP (CDR ,x) ',cdr-type)))
)
)
(fmakunbound 'def-compound-type)
;; ----------------------------------------------------------------------------
; Typtest ohne Gefahr einer Fehlermeldung. Für SIGNAL und HANDLER-BIND.
(defun safe-typep (x y &optional env)
(let ((*error-handler*
#'(lambda (&rest error-args)
(declare (ignore error-args))
(return-from safe-typep (values nil nil))
)) )
(values (typep x y env) t)
) )
; Umwandlung eines "type for declaration" in einen "type for discrimination".
(defun type-for-discrimination (y &optional (notp nil) &aux f)
(cond ((symbolp y)
(cond ((get y 'TYPE-SYMBOL) y)
((get y 'TYPE-LIST) y)
((setq f (get y 'DEFTYPE-EXPANDER))
(let* ((z (funcall f (list y)))
(zx (type-for-discrimination z notp)))
(if (eql zx z) y zx)
))
(t y)
) )
((and (consp y) (symbolp (first y)))
(case (first y)
((SATISFIES MEMBER EQL) y)
(NOT
(let* ((z (second y))
(zx (type-for-discrimination z (not notp))))
(if (eql zx z) y `(NOT ,zx))
))
((AND OR COMPLEX VALUES)
(let* ((z (rest y))
(zx (mapcar #'(lambda (x) (type-for-discrimination x notp)) z)))
(if (every #'eql z zx) y (cons (first y) zx))
))
(FUNCTION
;; (FUNCTION arg-types res-type) is somewhere between
;; NIL and FUNCTION, but undecidable.
(if notp 'NIL 'FUNCTION)
)
(t (cond ((get (first y) 'TYPE-LIST) y)
((setq f (get (first y) 'DEFTYPE-EXPANDER))
(let* ((z (funcall f y))
(zx (type-for-discrimination z notp)))
(if (eql zx z) y zx)
))
(t y)
) ) ) )
(t y)
) )
; Testet eine Liste von Werten auf Erfüllen eines Type-Specifiers. Für THE.
(defun %the (values type) ; ABI
(macrolet ((near-typep (objform typform)
;; near-typep ist wie typep, nur dass das Objekt auch ein
;; Read-Label sein darf. Das tritt z.B. auf bei
;; (read-from-string "#1=#S(FOO :X #1#)")
;; im Konstruktor MAKE-FOO. Die Implementation ist aber
;; nicht gezwungen, bei fehlerhaftem THE zwingend einen
;; Fehler zu melden, darum ist ein lascherer Typcheck hier
;; erlaubt.
(let ((g (gensym)))
`(let ((,g ,objform))
(or (typep ,g ,typform) (eq (type-of ,g) 'READ-LABEL))))))
(if (and (consp type) (eq (car type) 'VALUES))
;; The VALUES type specifier is ill-defined in ANSI CL.
;;
;; There are two possibilities to define a VALUES type specifier in a
;; sane way:
;; - (EXACT-VALUES type1 ... [&optional ...]) describes the exact shape
;; of the values list, as received by MULTIPLE-VALUE-LIST.
;; For example, (EXACT-VALUES SYMBOL) is matched by (values 'a) but not
;; by (values 'a 'b) or (values).
;; - (ASSIGNABLE-VALUES type1 ... [&optional ...]) describes the values
;; as received by a set of variables through MULTIPLE-VALUE-BIND or
;; MULTIPLE-VALUE-SETQ. For example, (ASSIGNABLE-VALUES SYMBOL) is
;; defined by whether
;; (MULTIPLE-VALUE-BIND (var1) values (DECLARE (TYPE SYMBOL var1)) ...)
;; is valid or not; therefore (ASSIGNABLE-VALUES SYMBOL) is matched by
;; (values 'a) and (values 'a 'b) and (values).
;; Note that &OPTIONAL is actually redundant here:
;; (ASSIGNABLE-VALUES type1 ... &optional otype1 ...)
;; is equivalent to
;; (ASSIGNABLE-VALUES type1 ... (OR NULL otype1) ...)
;; HyperSpec/Body/typspe_values.html indicates that VALUES means
;; EXACT-VALUES; however, HyperSpec/Body/speope_the.html indicates that
;; VALUES means ASSIGNABLE-VALUES.
;;
;; SBCL interprets the VALUES type specifier to mean EXACT-VALUES when
;; it contains &OPTIONAL or &REST, but ASSIGNABLE-VALUES when it has
;; only a tuple of type specifiers. This is utter nonsense, in particular
;; because it makes (VALUES type1 ... typek &OPTIONAL)
;; different from (VALUES type1 ... typek).
;;
;; Here we use the ASSIGNABLE-VALUES interpretation.
;; In SUBTYPEP we just punt and don't assume any interpretation.
(let ((vals values) (types (cdr type)))
;; required:
(loop
(when (or (atom types) (atom vals)) (return-from %the t))
(when (memq (car types) lambda-list-keywords) (return))
(unless (near-typep (pop vals) (pop types))
(return-from %the nil)))
;; &optional:
(when (and (consp types) (eq (car types) '&optional))
(setq types (cdr types))
(loop
(when (or (atom types) (atom vals)) (return-from %the t))
(when (memq (car types) lambda-list-keywords) (return))
(unless (near-typep (pop vals) (pop types))
(return-from %the nil))))
;; &rest &key:
(case (car types)
(&rest
(setq types (cdr types))
(when (atom types) (typespec-error 'the type))
(unless (near-typep (pop vals) (pop types))
(return-from %the nil)))
(&key)
(t (typespec-error 'the type)))
(if (eq (car types) '&key)
(progn
(setq types (cdr types))
(when (oddp (length vals)) (return-from %the nil))
(let ((keywords nil))
(loop
(when (or (atom types) (atom vals)) (return-from %the t))
(when (memq (car types) lambda-list-keywords) (return))
(let ((item (pop types)))
(unless (and (listp item) (eql (length item) 2)
(symbolp (first item)))
(typespec-error 'the type))
(let ((kw (symbol-to-keyword (first item))))
(unless (near-typep (getf vals kw) (second item))
(return-from %the nil))
(push kw keywords))))
(if (and (consp types) (eq (car types) '&allow-other-keys))
(setq types (cdr types))
(unless (getf vals ':allow-other-keys)
(do ((L vals (cddr L)))
((atom L))
(unless (memq (car L) keywords)
(return-from %the nil)))))))
(when (consp types) (typespec-error 'the type)))
t)
(near-typep (if (consp values) (car values) nil) type))))
;;; ===========================================================================
;; SUBTYPEP
(load "subtypep")
;; Returns the number of bytes that are needed to represent #\Null in a
;; given encoding.
(defun encoding-zeroes (encoding)
#+UNICODE
;; this should use min_bytes_per_char for cache, not the hash table
(let ((name (ext:encoding-charset encoding))
(table #.(make-hash-table :key-type '(or string symbol) :value-type 'fixnum
:test 'stablehash-equal :warn-if-needs-rehash-after-gc t
:initial-contents '(("UTF-7" . 1))))
(tester #.(make-string 2 :initial-element (code-char 0))))
(or (gethash name table)
(setf (gethash name table)
(- (length (ext:convert-string-to-bytes tester encoding))
(length (ext:convert-string-to-bytes tester encoding
:end 1))))))
#-UNICODE 1)
;; Determines two values low,high such that
;; (subtypep type `(INTEGER ,low ,high))
;; holds and low is as large as possible and high is as small as possible.
;; low = * means -infinity, high = * means infinity.
;; When (subtypep type 'INTEGER) is false, the values NIL,NIL are returned.
;; We need this function only for MAKE-ARRAY, UPGRADED-ARRAY-ELEMENT-TYPE and
;; OPEN and can therefore w.l.o.g. replace
;; type with `(OR ,type (MEMBER 0))
#| ;; The original implementation calls canonicalize-type and then applies
;; a particular SUBTYPE variant:
(defun subtype-integer (type)
(macrolet ((yes () '(return-from subtype-integer (values low high)))
(no () '(return-from subtype-integer nil))
(unknown () '(return-from subtype-integer nil)))
(setq type (canonicalize-type type))
(if (consp type)
(case (first type)
(MEMBER ; (MEMBER &rest objects)
;; All elements must be of type INTEGER.
(let ((low 0) (high 0)) ; wlog!
(dolist (x (rest type) (yes))
(unless (typep x 'INTEGER) (return (no)))
(setq low (min low x) high (max high x)))))
(OR ; (OR type*)
;; Every type must be subtype of INTEGER.
(let ((low 0) (high 0)) ; wlog!
(dolist (type1 (rest type) (yes))
(multiple-value-bind (low1 high1) (subtype-integer type1)
(unless low1 (return (no)))
(setq low (if (or (eq low '*) (eq low1 '*)) '* (min low low1))
high (if (or (eq high '*) (eq high1 '*))
'* (max high high1)))))))
(AND ; (AND type*)
;; If one of the types is subtype of INTEGER, then yes,
;; otherwise unknown.
(let ((low nil) (high nil))
(dolist (type1 (rest type))
(multiple-value-bind (low1 high1) (subtype-integer type1)
(when low1
(if low
(setq low (if (eq low '*) low1 (if (eq low1 '*) low (max low low1)))
high (if (eq high '*) high1 (if (eq high1 '*) high (min high high1))))
(setq low low1 high high1)))))
(if low
(progn
(when (and (numberp low) (numberp high) (not (<= low high)))
(setq low 0 high 0) ; type equivalent to NIL)
(yes))
(unknown)))))
(setq type (list type)))
(if (eq (first type) 'INTEGER)
(let ((low (if (rest type) (second type) '*))
(high (if (cddr type) (third type) '*)))
(when (consp low)
(setq low (first low))
(when (numberp low) (incf low)))
(when (consp high)
(setq high (first high))
(when (numberp high) (decf high)))
(when (and (numberp low) (numberp high) (not (<= low high))) ; type leer?
(setq low 0 high 0))
(yes))
(if (and (eq (first type) 'INTERVALS) (eq (second type) 'INTEGER))
(let ((low (third type))
(high (car (last type))))
(when (consp low)
(setq low (first low))
(when (numberp low) (incf low)))
(when (consp high)
(setq high (first high))
(when (numberp high) (decf high)))
(yes))
(unknown)))))
|# ;; This implementation inlines the (tail-recursive) canonicalize-type
;; function. Its advantage is that it doesn't cons as much.
;; (For example, (subtype-integer '(UNSIGNED-BYTE 8)) doesn't cons.)
(defun subtype-integer (type)
(macrolet ((yes () '(return-from subtype-integer (values low high)))
(no () '(return-from subtype-integer nil))
(unknown () '(return-from subtype-integer nil)))
(setq type (expand-deftype type))
(cond ((symbolp type)
(case type
(BIT (let ((low 0) (high 1)) (yes)))
(FIXNUM
(let ((low '#,most-negative-fixnum)
(high '#,most-positive-fixnum))
(yes)))
((INTEGER BIGNUM SIGNED-BYTE)
(let ((low '*) (high '*)) (yes)))
(UNSIGNED-BYTE
(let ((low 0) (high '*)) (yes)))
((NIL)
(let ((low 0) (high 0)) (yes))) ; wlog!
(t (no))))
((and (consp type) (symbolp (first type)))
(unless (and (list-length type) (null (cdr (last type))))
(typespec-error 'subtypep type))
(case (first type)
(MEMBER ; (MEMBER &rest objects)
;; All elements must be of type INTEGER.
(let ((low 0) (high 0)) ; wlog!
(dolist (x (rest type) (yes))
(unless (typep x 'INTEGER) (return (no)))
(setq low (min low x) high (max high x)))))
(EQL ; (EQL object)
(let ((x (second type)))
(if (typep x 'INTEGER)
(let ((low (min 0 x)) (high (max 0 x))) (yes))
(no))))
(OR ; (OR type*)
;; Every type must be subtype of INTEGER.
(let ((low 0) (high 0)) ; wlog!
(dolist (type1 (rest type) (yes))
(multiple-value-bind (low1 high1) (subtype-integer type1)
(unless low1 (return (no)))
(setq low (if (or (eq low '*) (eq low1 '*))
'* (min low low1))
high (if (or (eq high '*) (eq high1 '*))
'* (max high high1)))))))
(AND ; (AND type*)
;; If one of the types is subtype of INTEGER, then yes,
;; otherwise unknown.
(let ((low nil) (high nil))
(dolist (type1 (rest type))
(multiple-value-bind (low1 high1) (subtype-integer type1)
(when low1
(if low
(setq low (if (eq low '*) low1
(if (eq low1 '*) low
(max low low1)))
high (if (eq high '*) high1
(if (eq high1 '*) high
(min high high1))))
(setq low low1
high high1)))))
(if low
(progn
(when (and (numberp low) (numberp high)
(not (<= low high)))
(setq low 0 high 0)) ; type equivalent to NIL
(yes))
(unknown))))
(INTEGER
(let ((low (if (rest type) (second type) '*))
(high (if (cddr type) (third type) '*)))
(when (consp low)
(setq low (first low))
(when (numberp low) (incf low)))
(when (consp high)
(setq high (first high))
(when (numberp high) (decf high)))
(when (and (numberp low) (numberp high) (not (<= low high)))
(setq low 0 high 0)) ; type equivalent to NIL
(yes)))
(INTERVALS
(if (eq (second type) 'INTEGER)
(let ((low (third type))
(high (car (last type))))
(when (consp low)
(setq low (first low))
(when (numberp low) (incf low)))
(when (consp high)
(setq high (first high))
(when (numberp high) (decf high)))
(yes))
(unknown)))
(MOD ; (MOD n)
(let ((n (second type)))
(unless (and (integerp n) (>= n 0))
(typespec-error 'subtypep type))
(if (eql n 0)
(no)
(let ((low 0) (high (1- n)))
(yes)))))
(SIGNED-BYTE ; (SIGNED-BYTE &optional s)
(let ((s (if (cdr type) (second type) '*)))
(if (eq s '*)
(let ((low '*) (high '*)) (yes))
(progn
(unless (and (integerp s) (plusp s))
(typespec-error 'subtypep type))
(let ((n (ash 1 (1- s)))) ; (ash 1 *) == (expt 2 *)
(let ((low (- n)) (high (1- n)))
(yes)))))))
(UNSIGNED-BYTE ; (UNSIGNED-BYTE &optional s)
(let ((s (if (cdr type) (second type) '*)))
(if (eq s '*)
(let ((low 0) (high '*)) (yes))
(progn
(unless (and (integerp s) (>= s 0))
(typespec-error 'subtypep type))
(let ((n (ash 1 s))) ; (ash 1 *) == (expt 2 *)
(let ((low 0) (high (1- n)))
(yes)))))))
(t (no))))
((clos::defined-class-p type)
(if (and (clos::built-in-class-p type)
(eq (get (clos:class-name type) 'CLOS::CLOSCLASS) type))
(return-from subtype-integer
(subtype-integer (clos:class-name type)))
(no)))
((clos::eql-specializer-p type)
(let ((x (clos::eql-specializer-singleton type)))
(if (typep x 'INTEGER)
(let ((low (min 0 x)) (high (max 0 x))) (yes))
(no))))
((encodingp type) (no))
(t (typespec-error 'subtypep type)))))
#| TODO: Fix subtype-integer such that this works.
Henry Baker:
(defun type-null (x)
(values (and (eq 'bit (upgraded-array-element-type `(or bit ,x)))
(not (typep 0 x))
(not (typep 1 x)))
t))
(type-null '(and symbol number))
(type-null '(and integer symbol))
(type-null '(and integer character))
|#
;; Determines a sequence kind (an atom, as defined in defseq.lisp: one of
;; LIST - stands for LIST
;; VECTOR - stands for (VECTOR T)
;; STRING - stands for (VECTOR CHARACTER)
;; 1, 2, 4, 8, 16, 32 - stands for (VECTOR (UNSIGNED-BYTE n))
;; 0 - stands for (VECTOR NIL))
;; that indicates the sequence type meant by the given type. Other possible
;; return values are
;; SEQUENCE - denoting a type whose intersection with (OR LIST VECTOR) is not
;; subtype of LIST or VECTOR, or
;; NIL - indicating a type whose intersection with (OR LIST VECTOR) is empty.
;; When the type is (OR (VECTOR eltype1) ... (VECTOR eltypeN)), the chosen
;; element type is the smallest element type that contains all of eltype1 ...
;; eltypeN.
;;
;; User-defined sequence types are not supported here.
;;
;; This implementation inlines the (tail-recursive) canonicalize-type
;; function. Its advantage is that it doesn't cons as much. Also it employs
;; some heuristics and does not have the full power of SUBTYPEP.
(defun subtype-sequence (type)
(setq type (expand-deftype type))
(cond ((symbolp type)
(case type
((LIST CONS NULL) 'LIST)
((NIL) 'NIL)
((BIT-VECTOR SIMPLE-BIT-VECTOR) '1)
((STRING SIMPLE-STRING BASE-STRING SIMPLE-BASE-STRING) 'STRING)
((VECTOR SIMPLE-VECTOR ARRAY SIMPLE-ARRAY) 'VECTOR)
((SEQUENCE) 'SEQUENCE)
(t 'NIL)))
((and (consp type) (symbolp (first type)))
(unless (and (list-length type) (null (cdr (last type))))
(typespec-error 'subtypep type))
(case (first type)
(MEMBER ; (MEMBER &rest objects)
(let ((kind 'NIL))
(dolist (x (rest type))
(setq kind (sequence-type-union kind (type-of-sequence x))))
kind))
(EQL ; (EQL object)
(unless (eql (length type) 2)
(typespec-error 'subtypep type))
(type-of-sequence (second type)))
(OR ; (OR type*)
(let ((kind 'NIL))
(dolist (x (rest type))
(setq kind (sequence-type-union kind (subtype-sequence x))))
kind))
(AND ; (AND type*)
(let ((kind 'SEQUENCE))
(dolist (x (rest type))
(setq kind (sequence-type-intersection kind (subtype-sequence x))))
kind))
((SIMPLE-BIT-VECTOR BIT-VECTOR) ; (SIMPLE-BIT-VECTOR &optional size)
(when (cddr type)
(typespec-error 'subtypep type))
'1)
((SIMPLE-STRING STRING SIMPLE-BASE-STRING BASE-STRING) ; (SIMPLE-STRING &optional size)
(when (cddr type)
(typespec-error 'subtypep type))
'STRING)
(SIMPLE-VECTOR ; (SIMPLE-VECTOR &optional size)
(when (cddr type)
(typespec-error 'subtypep type))
'VECTOR)
((VECTOR ARRAY SIMPLE-ARRAY) ; (VECTOR &optional el-type size), (ARRAY &optional el-type dimensions)
(when (cdddr type)
(typespec-error 'subtypep type))
(let ((el-type (if (cdr type) (second type) '*)))
(if (eq el-type '*)
'VECTOR
(let ((eltype (upgraded-array-element-type el-type)))
(cond ((eq eltype 'T) 'VECTOR)
((eq eltype 'CHARACTER) 'STRING)
((eq eltype 'BIT) '1)
((and (consp eltype) (eq (first eltype) 'UNSIGNED-BYTE)) (second eltype))
((eq eltype 'NIL) '0)
(t (error (TEXT "~S is not up-to-date with ~S for element type ~S")
'subtypep-sequence 'upgraded-array-element-type eltype)))))))
((CONS) ; (CONS &optional cartype cdrtype)
(when (cdddr type)
(typespec-error 'subtypep type))
'LIST)
(t 'NIL)))
((clos::defined-class-p type)
(if (and (clos::built-in-class-p type)
(eq (get (clos:class-name type) 'CLOS::CLOSCLASS) type))
(subtype-sequence (clos:class-name type))
'NIL))
((clos::eql-specializer-p type)
(type-of-sequence (clos::eql-specializer-singleton type)))
(t 'NIL)))
(defun type-of-sequence (x)
(cond ((listp x) 'LIST)
((vectorp x)
(let ((eltype (array-element-type x)))
(cond ((eq eltype 'T) 'VECTOR)
((eq eltype 'CHARACTER) 'STRING)
((eq eltype 'BIT) '1)
((and (consp eltype) (eq (first eltype) 'UNSIGNED-BYTE)) (second eltype))
((eq eltype 'NIL) '0)
(t (error (TEXT "~S is not up-to-date with ~S for element type ~S")
'type-of-sequence 'array-element-type eltype)))))
(t 'NIL)))
(defun sequence-type-union (t1 t2)
(cond ; Simple general rules.
((eql t1 t2) t1)
((eq t1 'NIL) t2)
((eq t2 'NIL) t1)
; Now the union of two different types.
((or (eq t1 'SEQUENCE) (eq t2 'SEQUENCE)) 'SEQUENCE)
((or (eq t1 'LIST) (eq t2 'LIST))
; union of LIST and a vector type
'SEQUENCE)
((or (eq t1 'VECTOR) (eq t2 'VECTOR)) 'VECTOR)
((eql t1 0) t2)
((eql t2 0) t1)
((or (eq t1 'STRING) (eq t2 'STRING))
; union of STRING and an integer-vector type
'VECTOR)
(t (max t1 t2))))
(defun sequence-type-intersection (t1 t2)
(cond ; Simple general rules.
((eql t1 t2) t1)
((or (eq t1 'NIL) (eq t2 'NIL)) 'NIL)
; Now the intersection of two different types.
((eq t1 'SEQUENCE) t2)
((eq t2 'SEQUENCE) t1)
((or (eq t1 'LIST) (eq t2 'LIST))
; intersection of LIST and a vector type
'NIL)
((eq t1 'VECTOR) t2)
((eq t2 'VECTOR) t1)
((or (eql t1 0) (eql t2 0)) '0)
((or (eq t1 'STRING) (eq t2 'STRING))
; intersection of STRING and an integer-vector type
'0)
(t (min t1 t2))))
;; ============================================================================
(defun type-expand (typespec &optional once-p)
(multiple-value-bind (expanded user-defined-p)
(expand-deftype typespec once-p)
(if user-defined-p (values expanded user-defined-p)
(cond ((symbolp typespec)
(cond ((or (get typespec 'TYPE-SYMBOL) (get typespec 'TYPE-LIST))
(values typespec nil))
((or (get typespec 'DEFSTRUCT-DESCRIPTION)
(clos-class typespec))
(values typespec nil))
(t (typespec-error 'type-expand typespec))))
((and (consp typespec) (symbolp (first typespec)))
(case (first typespec)
((SATISFIES MEMBER EQL NOT AND OR) (values typespec nil))
(t (cond ((get (first typespec) 'TYPE-LIST)
(values typespec nil))
(t (typespec-error 'type-expand typespec))))))
((clos::defined-class-p typespec) (values typespec nil))
(t (typespec-error 'type-expand typespec))))))
;; ============================================================================
(unless (clos::funcallable-instance-p #'clos::class-name)
(fmakunbound 'clos::class-name))
| 49,151 | Common Lisp | .lisp | 1,164 | 32.448454 | 111 | 0.531851 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 518d86359db0ce1b129acbdabcdb3cef26e36a834582dc26a600a5bb538a25f4 | 11,394 | [
-1
] |
11,395 | clos-genfun2a.lisp | ufasoft_lisp/clisp/clos-genfun2a.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Generic Functions
;;;; Part 2: Generic function dispatch and execution
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004, 2007
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
;; ======================== Avoiding endless recursion ========================
;; Generic functions which are used in implementing the generic function
;; dispatch and execution.
(defvar |#'compute-discriminating-function| nil)
(defvar |#'compute-applicable-methods| nil)
(defvar |#'compute-applicable-methods-using-classes| nil)
(defvar |#'compute-effective-method| nil)
(defvar |#'generic-function-methods| nil)
(defvar |#'generic-function-method-class| nil)
(defvar |#'generic-function-signature| nil)
(defvar |#'generic-function-undeterminedp| nil)
(defvar |#'generic-function-method-combination| nil)
(defvar |#'generic-function-argorder| nil)
(defvar |#'generic-function-declarations| nil)
(defvar |#'method-qualifiers| nil)
(defvar |#'method-specializers| nil)
(defun safe-gf-methods (gf)
(if (or (eq gf #'generic-function-methods) ; for bootstrapping
(eq gf |#'generic-function-methods|)
(eq gf |#'compute-effective-method|)
(eq gf |#'compute-discriminating-function|)
(eq gf |#'compute-applicable-methods-using-classes|))
(std-gf-methods gf)
(generic-function-methods gf)))
(defun safe-gf-default-method-class (gf)
(if (or (eq gf |#'generic-function-method-class|)
(eq gf |#'compute-effective-method|))
(std-gf-default-method-class gf)
(generic-function-method-class gf)))
(defun safe-gf-signature (gf)
(if (or (eq gf #'generic-function-signature) ; for bootstrapping
(eq gf |#'generic-function-signature|)
(eq gf |#'generic-function-method-class|)
(eq gf |#'compute-effective-method|))
(std-gf-signature gf)
(generic-function-signature gf)))
(defun safe-gf-undeterminedp (gf)
(if (or (eq gf #'generic-function-undeterminedp) ; for bootstrapping
(eq gf |#'generic-function-undeterminedp|))
(std-gf-undeterminedp gf)
(generic-function-undeterminedp gf)))
(defun safe-gf-method-combination (gf)
(if (or (eq gf #'generic-function-method-combination) ; for bootstrapping
(eq gf |#'generic-function-method-combination|)
(eq gf |#'compute-effective-method|))
(std-gf-method-combination gf)
(generic-function-method-combination gf)))
(defun safe-gf-argorder (gf)
(if (or (eq gf |#'generic-function-argorder|)
(eq gf |#'method-qualifiers|)
(eq gf |#'compute-effective-method|))
(std-gf-argorder gf)
(generic-function-argorder gf)))
(defun safe-gf-declspecs (gf)
(if (or (eq gf |#'generic-function-declarations|)
(eq gf |#'generic-function-argorder|)
(eq gf |#'method-qualifiers|)
(eq gf |#'compute-effective-method|))
(std-gf-declspecs gf)
(generic-function-declarations gf)))
(defun safe-method-qualifiers (method gf)
(if (or (eq gf #'method-qualifiers) ; for bootstrapping
(eq gf |#'method-qualifiers|)
(eq gf |#'compute-effective-method|))
(std-method-qualifiers method)
(method-qualifiers method)))
(defun safe-method-specializers (method gf)
(if (or (eq gf #'method-specializers) ; for bootstrapping
(eq gf |#'method-specializers|)
(eq gf |#'compute-effective-method|))
(std-method-specializers method)
(method-specializers method)))
;; ============================= Method Selection =============================
;; CLtL2 28.1.6.2., ANSI CL 7.6.2. Applicable methods
(defun method-applicable-p (method required-arguments gf)
(every #'typep required-arguments (safe-method-specializers method gf)))
;; CLtL2 28.1.7.1., ANSI CL 7.6.6.1.2.
;; Sorting the applicable methods by precedence order
;; > methods: A list of methods from the same generic function that are
;; already known to be applicable for the given required-arguments.
;; > required-argument-classes: the list of classes the required arguments are
;; direct instances of.
;; > argument-order: A list of indices in the range 0..req-num-1 that
;; determines the argument order.
(defun sort-applicable-methods (methods required-argument-classes argument-order gf)
(sort (copy-list methods)
#'(lambda (method1 method2) ; method1 < method2 ?
(let ((specializers1 (safe-method-specializers method1 gf))
(specializers2 (safe-method-specializers method2 gf)))
(dolist (arg-index argument-order nil)
(let ((arg-class (nth arg-index required-argument-classes))
(psp1 (nth arg-index specializers1))
(psp2 (nth arg-index specializers2)))
(if (eql-specializer-p psp1)
(if (eql-specializer-p psp2)
nil ; (EQL x) = (EQL x)
(return t)) ; (EQL x) < <class> ==> method1 < method2
(if (eql-specializer-p psp2)
(return nil) ; <class> > (EQL x) ==> method1 > method2
;; two classes: compare the position in the CPL of arg-class:
(let* ((cpl (class-precedence-list arg-class))
(pos1 (position psp1 cpl))
(pos2 (position psp2 cpl)))
(cond ((< pos1 pos2) (return t)) ; method1 < method2
((> pos1 pos2) (return nil)) ; method1 > method2
))))))))))
;; Preliminary.
(predefun compute-applicable-methods (gf args)
(compute-applicable-methods-<generic-function> gf args))
(defun compute-applicable-methods-<generic-function> (gf args)
(if (safe-gf-undeterminedp gf)
;; gf has uninitialized lambda-list, hence no methods.
'()
(let ((req-num (sig-req-num (safe-gf-signature gf))))
(if (>= (length args) req-num)
;; 0. Check the method specializers:
(let ((methods (safe-gf-methods gf)))
(dolist (method methods)
(check-method-only-standard-specializers gf method
'compute-applicable-methods))
;; 1. Select the applicable methods:
(let ((req-args (subseq args 0 req-num)))
(setq methods
(remove-if-not #'(lambda (method)
(method-applicable-p method req-args gf))
(the list methods)))
;; 2. Sort the applicable methods by precedence order:
(sort-applicable-methods methods (mapcar #'class-of req-args) (safe-gf-argorder gf) gf)))
(error (TEXT "~S: ~S has ~S required argument~:P, but only ~S arguments were passed to ~S: ~S")
'compute-applicable-methods gf req-num (length args)
'compute-applicable-methods args)))))
;; ----------------------------------------------------------------------------
;; compute-applicable-methods-using-classes is just plain redundant, and must
;; be a historical relic of the time before CLOS had EQL specializers (or a
;; brain fart of the PCL authors). But the MOP wants it, so we implement it.
;; Preliminary.
(predefun compute-applicable-methods-using-classes (gf req-arg-classes)
(compute-applicable-methods-using-classes-<generic-function> gf req-arg-classes))
(defun compute-applicable-methods-using-classes-<generic-function> (gf req-arg-classes)
(unless (and (proper-list-p req-arg-classes) (every #'defined-class-p req-arg-classes))
(error (TEXT "~S: argument should be a proper list of classes, not ~S")
'compute-applicable-methods-using-classes req-arg-classes))
(if (safe-gf-undeterminedp gf)
;; gf has uninitialized lambda-list, hence no methods.
'()
(let ((req-num (sig-req-num (safe-gf-signature gf))))
(if (= (length req-arg-classes) req-num)
;; 0. Check the method specializers:
(let ((methods (safe-gf-methods gf)))
(dolist (method methods)
(check-method-only-standard-specializers gf method
'compute-applicable-methods-using-classes))
;; 1. Select the applicable methods. Note that the arguments are
;; assumed to be _direct_ instances of the given classes, i.e.
;; classes = (mapcar #'class-of required-arguments).
(setq methods
(remove-if-not #'(lambda (method)
(let ((specializers (safe-method-specializers method gf))
(applicable t) (unknown nil))
(mapc #'(lambda (arg-class specializer)
(if (defined-class-p specializer)
;; For class specializers,
;; (typep arg specializer) is equivalent to
;; (subtypep (class-of arg) specializer).
(unless (subclassp arg-class specializer)
(setq applicable nil))
;; For EQL specializers,
;; (typep arg specializer) is certainly false
;; if (class-of arg) and (class-of (eql-specializer-object specializer))
;; differ. Otherwise unknown.
(if (eq arg-class (class-of (eql-specializer-object specializer)))
(setq unknown t)
(setq applicable nil))))
req-arg-classes specializers)
(when (and applicable unknown)
(return-from compute-applicable-methods-using-classes-<generic-function>
(values nil nil)))
applicable))
(the list methods)))
;; 2. Sort the applicable methods by precedence order:
(values (sort-applicable-methods methods req-arg-classes (safe-gf-argorder gf) gf) t))
(error (TEXT "~S: ~S has ~S required argument~:P, but ~S classes were passed to ~S: ~S")
'compute-applicable-methods-using-classes gf req-num (length req-arg-classes)
'compute-applicable-methods-using-classes req-arg-classes)))))
;; ----------------------------------------------------------------------------
;; compute-applicable-methods-for-set
;; is a generalization of compute-applicable-methods[-using-classes].
;; For each argument position you can specify a set of possible required
;; arguments through one of:
;; (TYPEP class) [covers direct and indirect instances of class],
;; (INSTANCE-OF-P class) [covers only direct instances of class],
;; (EQL object) [covers the given object only].
;; Returns 1. the list of applicable methods and 2. a certainty value.
(defun compute-applicable-methods-for-set (gf req-arg-specs)
(unless (and (proper-list-p req-arg-specs)
(every #'(lambda (x) (and (consp x) (memq (car x) '(TYPEP INSTANCE-OF-P EQL))))
req-arg-specs))
(error (TEXT "~S: argument should be a proper list of specifiers, not ~S")
'compute-applicable-methods-for-set req-arg-specs))
(if (safe-gf-undeterminedp gf)
;; gf has uninitialized lambda-list, hence no methods.
'()
(let ((req-num (sig-req-num (safe-gf-signature gf))))
(if (= (length req-arg-specs) req-num)
;; 0. Check the method specializers:
(let ((methods (safe-gf-methods gf)))
(dolist (method methods)
(check-method-only-standard-specializers gf method
'compute-applicable-methods-for-set))
;; 1. Select the applicable methods:
(setq methods
(remove-if-not #'(lambda (method)
(let ((specializers (safe-method-specializers method gf))
(applicable t) (unknown nil))
(mapc #'(lambda (arg-spec specializer)
(ecase (first arg-spec)
(TYPEP
(if (defined-class-p specializer)
;; For class specializers,
;; (typep arg specializer) is certainly true
;; if the known class of arg is a subclass of
;; the specializer. Otherwise unknown.
(unless (subclassp (second arg-spec) specializer)
(setq unknown t))
;; For EQL specializers,
;; (typep arg specializer) is certainly false
;; if (eql-specializer-object specializer)
;; doesn't belong to the known class of arg.
;; Otherwise unknown.
(if (typep (eql-specializer-object specializer) (second arg-spec))
(setq unknown t)
(setq applicable nil))))
(INSTANCE-OF-P ; see ...-using-classes
(if (defined-class-p specializer)
;; For class specializers,
;; (typep arg specializer) is equivalent to
;; (subtypep (class-of arg) specializer).
(unless (subclassp (second arg-spec) specializer)
(setq applicable nil))
;; For EQL specializers,
;; (typep arg specializer) is certainly false
;; if (class-of arg) and (class-of (eql-specializer-object specializer))
;; differ. Otherwise unknown.
(if (eq (second arg-spec) (class-of (eql-specializer-object specializer)))
(setq unknown t)
(setq applicable nil))))
(EQL ; see method-applicable-p
(unless (typep (second arg-spec) specializer)
(setq applicable nil)))))
req-arg-specs specializers)
(when (and applicable unknown)
(return-from compute-applicable-methods-for-set
(values nil nil)))
applicable))
(the list methods)))
;; 2. Sort the applicable methods by precedence order:
(let ((argument-order (safe-gf-argorder gf)))
(values
(sort (copy-list methods)
#'(lambda (method1 method2) ; method1 < method2 ?
(let ((specializers1 (safe-method-specializers method1 gf))
(specializers2 (safe-method-specializers method2 gf)))
(dolist (arg-index argument-order nil)
(let ((arg-spec (nth arg-index req-arg-specs))
(psp1 (nth arg-index specializers1))
(psp2 (nth arg-index specializers2)))
(if (eql-specializer-p psp1)
(if (eql-specializer-p psp2)
nil ; (EQL x) = (EQL x)
(return t)) ; (EQL x) < <class> ==> method1 < method2
(if (eql-specializer-p psp2)
(return nil) ; <class> > (EQL x) ==> method1 > method2
;; two classes: compare the position in the CPL of
;; the arg's class, if known:
(unless (eq psp1 psp2)
(cond ((eq psp2 <t>) (return t)) ; method1 < method2
((eq psp1 <t>) (return nil)) ; method1 > method2
(t (let* ((arg-class
(ecase (first arg-spec)
(TYPEP
; The precise arg-class is unknown.
(return-from compute-applicable-methods-for-set
(values nil nil)))
(INSTANCE-OF-P (second arg-spec))
(EQL (class-of (second arg-spec)))))
(cpl (class-precedence-list arg-class))
(pos1 (position psp1 cpl))
(pos2 (position psp2 cpl)))
(cond ((< pos1 pos2) (return t)) ; method1 < method2
((> pos1 pos2) (return nil)) ; method1 > method2
))))))))))))
t)))
(error (TEXT "~S: ~S has ~S required argument~:P")
'compute-applicable-methods-for-set gf req-num)))))
;; ----------------------------------------------------------------------------
;; There's no real reason for checking the method specializers in
;; compute-applicable-methods, rather than in
;; compute-effective-method-as-function, but that's how the MOP specifies it.
(defun check-method-only-standard-specializers (gf method caller)
(dolist (spec (safe-method-specializers method gf))
(unless (or (defined-class-p spec) (typep-class spec <eql-specializer>))
(error (TEXT "~S: Invalid method specializer ~S on ~S in ~S")
caller spec method gf))))
;; ================ Combination of Applicable Methods, Part 1 ================
(defun gf-keyword-arguments (restp signature methods)
;; CLtL2 28.1.6.4., 28.1.6.5., ANSI CL 7.6.4., 7.6.5.
;; Keyword Arguments in Generic Functions
(when restp
;; The generic function has &REST or &KEY, thus try all methods.
;; "If the lambda-list of ... the generic function definition
;; contains &allow-other-keys, all keyword arguments are accepted."
(unless (sig-allow-p signature)
;; "The specific set of keyword arguments accepted ...
;; varies according to the applicable methods."
(let ((signatures (mapcar #'method-signature methods)))
;; "A method that has &rest but not &key does not affect the
;; set of acceptable keyword arguments."
(setq signatures (delete-if-not #'sig-keys-p signatures))
;; No &key in the generic function, and no method with &key ==>
;; no restriction on the arguments.
(when (or (sig-keys-p signature) signatures)
;; "If the lambda-list of any applicable method ... contains
;; &allow-other-keys, all keyword arguments are accepted."
(unless (some #'sig-allow-p signatures)
;; "The set of keyword arguments accepted for a
;; particular call is the union of the keyword
;; arguments accepted by all applicable methods and
;; the keyword arguments mentioned after &key in the
;; generic function definition."
(let* ((keywords
(remove-duplicates
(append (sig-keywords signature)
(mapcap #'sig-keywords signatures))
:from-end t))
(opt-vars (gensym-list (sig-opt-num signature)))
(key-vars (gensym-list keywords))
(lambdalist-keypart
`(&KEY ; lambdalist-keypart
,@(mapcar #'(lambda (kw var) `((,kw ,var)))
keywords key-vars))))
(values opt-vars key-vars lambdalist-keypart))))))))
;; ================ Combination of Applicable Methods, Part 2 ================
;; is in the file clos-methcomb2.lisp
| 21,605 | Common Lisp | .lisp | 350 | 42.628571 | 127 | 0.507232 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 0515b06c30cbda1cadc12cbf7bf1774cf19fb6add39d5b9258cdbbd2406c8628 | 11,395 | [
-1
] |
11,396 | clos-macros.lisp | ufasoft_lisp/clisp/clos-macros.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Internal Macros
;;;; Bruno Haible 2004
(in-package "CLOS")
;;; ===========================================================================
;;; Support for weak sets that are stored as either
;;; - NIL or a weak-list (for saving memory when there are few subclasses), or
;;; - a weak-hash-table (for speed when there are many subclasses).
;;; (def-weak-set-accessors ACCESSOR ELEMENT-TYPE
;;; ADDER REMOVER LISTER)
;;; defines three functions
;;; (defun ADDER (holder element) ...) ; adds element to the set
;;; (defun REMOVER (holder element) ...) ; removes element from the set
;;; (defun LISTER (holder) ...) ; returns the set as a freshly consed list
(defmacro def-weak-set-accessors (accessor element-type adder remover lister)
`(PROGN
(DEFUN ,adder (HOLDER ELEMENT)
(ADD-TO-WEAK-SET HOLDER (,accessor HOLDER) ELEMENT
#'(SETF ,accessor) ',element-type))
(DEFUN ,remover (HOLDER ELEMENT)
(REMOVE-FROM-WEAK-SET HOLDER (,accessor HOLDER) ELEMENT))
(DEFUN ,lister (HOLDER)
(LIST-WEAK-SET (,accessor HOLDER)))))
;; Auxiliary functions for def-weak-set-accessors.
(defun add-to-weak-set (holder set element setter element-type)
(cond ((null set)
(let ((new-set (ext:make-weak-list (list element))))
(funcall setter new-set holder)))
((ext:weak-list-p set)
(let ((list (ext:weak-list-list set)))
(unless (member element list :test #'eq)
(push element list)
(if (<= (length list) 10)
(setf (ext:weak-list-list set) list)
(let ((new-set
(let ((ht (make-hash-table :key-type element-type :value-type '(eql t)
:test 'ext:stablehash-eq :warn-if-needs-rehash-after-gc t
:weak :key)))
(dolist (x list) (setf (gethash x ht) t))
ht)))
(funcall setter new-set holder))))))
(t (setf (gethash element set) t))))
(defun remove-from-weak-set (holder set element)
(declare (ignore holder))
(cond ((null set))
((ext:weak-list-p set)
(let ((list (ext:weak-list-list set)))
(when (member element list :test #'eq)
(setf (ext:weak-list-list set) (remove element list :test #'eq)))))
(t (remhash element set))))
(defun list-weak-set (set)
(cond ((null set) '())
((ext:weak-list-p set)
(ext:weak-list-list set))
(t (let ((l '()))
(maphash #'(lambda (x y) (declare (ignore y)) (push x l)) set)
l))))
;;; ===========================================================================
;; Typecheck in accessor functions that are not generic functions.
;; (accessor-typecheck object class caller)
;; > object: a form producing any object.
;; > class: a form producing a class or a class name.
;; > caller: a form producing the accessor's name, usually a quoted symbol.
(defmacro accessor-typecheck (object class caller)
`(UNLESS (TYPEP ,object ,class)
(ERROR-ACCESSOR-TYPECHECK ,caller ,object ,class)))
;; Auxiliary function for non-generic accessors.
(defun error-accessor-typecheck (caller object class) ; ABI
(error-of-type 'type-error
:datum object :expected-type class
"~S: The argument is not of type ~S: ~S"
caller
(if (and (defined-class-p class) (eq (find-class (class-name class) nil) class))
(class-name class)
class)
object))
| 3,586 | Common Lisp | .lisp | 76 | 39.276316 | 107 | 0.580903 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | cf5abbe07a2bcd8f6ec0c0792d9153198f0fb6a56f03350dbba2faf8b6e337e1 | 11,396 | [
-1
] |
11,397 | clos-class5.lisp | ufasoft_lisp/clisp/clos-class5.lisp | ;;;; Common Lisp Object System for CLISP: Classes
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004, 2009
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
;;; CLtL2 28.1.9., ANSI CL 7.1. Object Creation and Initialization
;; Cruel hack (CLtL2 28.1.9.2., ANSI CL 7.1.2.):
;; - MAKE-INSTANCE must be informed about the methods of ALLOCATE-INSTANCE,
;; INITIALIZE-INSTANCE and SHARED-INITIALIZE.
;; - INITIALIZE-INSTANCE must be informed about the methods of
;; INITIALIZE-INSTANCE and SHARED-INITIALIZE.
;; - REINITIALIZE-INSTANCE must be informed about the methods of
;; REINITIALIZE-INSTANCE and SHARED-INITIALIZE.
;; - UPDATE-INSTANCE-FOR-REDEFINED-CLASS must be informed about the methods of
;; UPDATE-INSTANCE-FOR-REDEFINED-CLASS and SHARED-INITIALIZE.
;; - UPDATE-INSTANCE-FOR-DIFFERENT-CLASS must be informed about the methods of
;; UPDATE-INSTANCE-FOR-DIFFERENT-CLASS and SHARED-INITIALIZE.
(defparameter *make-instance-table*
(make-hash-table :key-type 'defined-class :value-type '(simple-vector 4)
:test 'ext:stablehash-eq :warn-if-needs-rehash-after-gc t))
;; Hash table, mapping a class to a simple-vector containing
;; - a list of valid keyword arguments,
;; - the effective method of allocate-instance,
;; - the effective method of initialize-instance,
;; - the effective method of shared-initialize.
(defparameter *reinitialize-instance-table*
(make-hash-table :key-type 'defined-class :value-type 'cons
:test 'ext:stablehash-eq :warn-if-needs-rehash-after-gc t))
;; Hash table, mapping a class to a cons containing
;; - a list of valid keyword arguments,
;; - the effective method of shared-initialize.
(defparameter *update-instance-for-redefined-class-table*
(make-hash-table :key-type 'defined-class :value-type 'list
:test 'ext:stablehash-eq :warn-if-needs-rehash-after-gc t))
;; Hash table, mapping a class to
;; - a list of valid keyword arguments.
(defparameter *update-instance-for-different-class-table*
(make-hash-table :key-type '(cons class class) :value-type 'list
:test 'ext:stablehash-equal :warn-if-needs-rehash-after-gc t))
;; Hash table, mapping a cons (old-class . new-class) to
;; - a list of valid keyword arguments.
;; FIXME: These tables must also be cleaned when a class is redefined
;; (because subclassp changes, and for *update-instance-for-redefined-class-table*
;; also because the class-slots change).
(defun note-i-change (specializer table)
(maphash #'(lambda (class value) (declare (ignore value))
(when (subclassp class specializer)
(remhash class table)))
table))
(defun note-i-meta-change (meta-specializer table)
(maphash #'(lambda (class value) (declare (ignore value))
(when (typep-class class meta-specializer) ; <==> (typep class meta-specializer)
(remhash class table)))
table))
(defun note-ai-change (method)
(let ((specializer (first (method-specializers method))))
(if (eql-specializer-p specializer)
;; EQL-method for ALLOCATE-INSTANCE:
;; object must be a class, else worthless.
(let ((specialized-object (eql-specializer-object specializer)))
(when (defined-class-p specialized-object)
;; Remove the entries from *make-instance-table* for which the
;; implied method might be applicable:
(note-i-change specialized-object *make-instance-table*)))
;; remove the entries from *make-instance-table* for which the
;; implied method might be applicable:
(note-i-meta-change specializer *make-instance-table*))))
(defun note-ii-change (method)
(let ((specializer (first (method-specializers method))))
;; EQL-methods for INITIALIZE-INSTANCE are worthless in any case.
(unless (eql-specializer-p specializer)
;; Remove the entries from *make-instance-table* for which the
;; implied method might be applicable:
(note-i-change specializer *make-instance-table*))))
(defun note-ri-change (method)
(let ((specializer (first (method-specializers method))))
;; EQL-methods for REINITIALIZE-INSTANCE are essentially worthless.
(unless (eql-specializer-p specializer)
;; Remove the entries from *reinitialize-instance-table* for which the
;; implied method might be applicable:
(note-i-change specializer *reinitialize-instance-table*))))
(defun note-uirc-change (method)
(let ((specializer (first (method-specializers method))))
;; EQL-methods for UPDATE-INSTANCE-FOR-REDEFINED-CLASS are essentially
;; worthless.
(unless (eql-specializer-p specializer)
;; Remove the entries from *update-instance-for-redefined-class-table*
;; for which the implied method might be applicable:
(note-i-change specializer *update-instance-for-redefined-class-table*))))
(defun note-uidc-change (method)
(let ((specializer1 (first (method-specializers method)))
(specializer2 (second (method-specializers method))))
;; Methods for UPDATE-INSTANCE-FOR-DIFFERENT-CLASS with EQL specializer
;; in the first argument are essentially worthless.
(unless (eql-specializer-p specializer1)
;; Methods for UPDATE-INSTANCE-FOR-DIFFERENT-CLASS with EQL specializer
;; in the second argument are worthless in any case.
(unless (eql-specializer-p specializer2)
;; Remove the entries from *update-instance-for-different-class-table*
;; for which the implied method might be applicable:
(let ((table *update-instance-for-different-class-table*))
(maphash #'(lambda (classes value) (declare (ignore value))
(let ((class1 (car classes))
(class2 (cdr classes)))
(when (and (subclassp class1 specializer1)
(subclassp class2 specializer2))
(remhash classes table))))
table))))))
(defun note-si-change (method)
(let* ((specializers (method-specializers method))
(specializer1 (first specializers))
(specializer2 (second specializers)))
;; EQL-methods for SHARED-INITIALIZE are essentially worthless.
(unless (eql-specializer-p specializer1)
;; As second argument, INITIALIZE-INSTANCE passes always T .
(when (typep 'T specializer2)
;; Remove the entries from *make-instance-table* for which the
;; implied method might be applicable:
(note-i-change specializer1 *make-instance-table*))
;; As second argument, REINITIALIZE-INSTANCE passes always NIL .
(when (typep 'NIL specializer2)
;; Remove the entries from *reinitialize-instance-table* for which the
;; implied method might be applicable:
(note-i-change specializer1 *reinitialize-instance-table*))
;; Remove the entries from *update-instance-for-redefined-class-table*
;; for which the implied method might be applicable:
(note-i-change specializer1 *reinitialize-instance-table*)
;; Remove the entries from *update-instance-for-different-class-table*
;; for which the implied method might be applicable:
(let ((table *update-instance-for-different-class-table*))
(maphash #'(lambda (classes value) (declare (ignore value))
(let ((class2 (cdr classes)))
(when (subclassp class2 specializer1)
(remhash classes table))))
table)))))
;;; collect all keywords from a list of applicable methods
(defun valid-initarg-keywords (class methods)
(let ((signatures (mapcar #'method-signature methods)))
;; "A method that has &rest but not &key does not affect the set of
;; acceptable keyword srguments."
(setq signatures (delete-if-not #'sig-keys-p signatures))
;; "The presence of &allow-other-keys in the lambda list of an applicable
;; method disables validity checking of initialization arguments."
;; (ANSI CL section 7.1.2)
(if (some #'sig-allow-p signatures)
't
;; "The keyword name of each keyword parameter specified in the method's
;; lambda-list becomes an initialization argument for all classes for
;; which the method is applicable."
(remove-duplicates
(append (class-valid-initargs-from-slots class)
(mapcap #'sig-keywords signatures))
:from-end t))))
;; NB: On calculation of an effective method, the residual
;; arguments do not count.
;; At the first call of INITIALIZE-INSTANCE or MAKE-INSTANCE of each class
;; we memorize the needed information in *make-instance-table*.
;; For MAKE-INSTANCE the following is necessary as keys:
;; - the initargs that are used for the initialization of slots,
;; - the keywords of methods from SHARED-INITIALIZE,
;; - the keywords of methods from INITIALIZE-INSTANCE,
;; - the keywords of methods from ALLOCATE-INSTANCE.
(defun valid-make-instance-keywords (class)
(valid-initarg-keywords
class
(append
;; list of all applicable methods from SHARED-INITIALIZE
(remove-if-not
#'(lambda (method)
(let* ((specializers (method-specializers method))
(specializer1 (first specializers))
(specializer2 (second specializers)))
(and (not (eql-specializer-p specializer1))
(subclassp class specializer1)
(typep 'T specializer2))))
(the list (generic-function-methods |#'shared-initialize|)))
;; list of all applicable methods from INITIALIZE-INSTANCE
(remove-if-not
#'(lambda (method)
(let ((specializer (first (method-specializers method))))
(and (not (eql-specializer-p specializer))
(subclassp class specializer))))
(the list (generic-function-methods |#'initialize-instance|)))
;; list of all applicable methods from ALLOCATE-INSTANCE
(remove-if-not
#'(lambda (method)
(let ((specializer (first (method-specializers method))))
(if (eql-specializer-p specializer)
(eql class (eql-specializer-object specializer))
(typep-class class specializer)))) ; <==> (typep class specializer)
(the list (generic-function-methods |#'allocate-instance|))))))
(defun make-instance-table-entry1 (class)
(values (valid-make-instance-keywords class)
(compute-applicable-methods-effective-method |#'allocate-instance| class)))
(defun make-instance-table-entry2 (instance)
(values (compute-applicable-methods-effective-method |#'initialize-instance| instance)
(compute-applicable-methods-effective-method |#'shared-initialize| instance 'T)))
;; For REINITIALIZE-INSTANCE the following is necessary as keys:
;; - the initargs that are used for the initialization of slots,
;; - the keywords of methods from SHARED-INITIALIZE,
;; - the keywords of methods from REINITIALIZE-INSTANCE.
(defun valid-reinitialize-instance-keywords (class)
(valid-initarg-keywords
class
(append
;; list of all applicable methods from SHARED-INITIALIZE
(remove-if-not
#'(lambda (method)
(let* ((specializers (method-specializers method))
(specializer1 (first specializers))
(specializer2 (second specializers)))
(and (not (eql-specializer-p specializer1))
(subclassp class specializer1)
(typep 'NIL specializer2))))
(the list (generic-function-methods |#'shared-initialize|)))
;; list of all applicable methods from REINITIALIZE-INSTANCE
(remove-if-not
#'(lambda (method)
(let ((specializer (first (method-specializers method))))
(and (not (eql-specializer-p specializer))
(subclassp class specializer))))
(the list (generic-function-methods |#'reinitialize-instance|))))))
;; For UPDATE-INSTANCE-FOR-REDEFINED-CLASS the following is necessary as keys:
;; - the initargs that are used for the initialization of slots,
;; - the keywords of methods from SHARED-INITIALIZE,
;; - the keywords of methods from UPDATE-INSTANCE-FOR-REDEFINED-CLASS.
;; Return a 2nd value that indicates whether the result is independent of
;; added-slots, discarded-slots, property-list.
(defun valid-update-instance-for-redefined-class-keywords (class added-slots discarded-slots property-list)
(let ((independent t))
(values
(valid-initarg-keywords
class
(append
;; list of all applicable methods from SHARED-INITIALIZE
(remove-if-not
#'(lambda (method)
(let* ((specializers (method-specializers method))
(specializer1 (first specializers))
(specializer2 (second specializers)))
(and (not (eql-specializer-p specializer1))
(subclassp class specializer1)
(progn
(when (or (eql-specializer-p specializer2)
(eq specializer2 <null>))
(setq independent nil))
(typep added-slots specializer2)))))
(the list (generic-function-methods |#'shared-initialize|)))
;; list of all applicable methods from UPDATE-INSTANCE-FOR-REDEFINED-CLASS
(remove-if-not
#'(lambda (method)
(let* ((specializers (method-specializers method))
(specializer1 (first specializers))
(specializer2 (second specializers))
(specializer3 (third specializers))
(specializer4 (fourth specializers)))
(and (not (eql-specializer-p specializer1))
(subclassp class specializer1)
(progn
(when (or (eql-specializer-p specializer2)
(eq specializer2 <null>))
(setq independent nil))
(when (or (eql-specializer-p specializer3)
(eq specializer3 <null>))
(setq independent nil))
(when (or (eql-specializer-p specializer4)
(eq specializer4 <null>))
(setq independent nil))
(and (typep added-slots specializer2)
(typep discarded-slots specializer3)
(typep property-list specializer4))))))
(the list (generic-function-methods |#'update-instance-for-redefined-class|)))))
independent)))
;; For UPDATE-INSTANCE-FOR-DIFFERENT-CLASS the following is necessary as keys:
;; - the initargs that are used for the initialization of slots,
;; - the keywords of methods from SHARED-INITIALIZE,
;; - the keywords of methods from UPDATE-INSTANCE-FOR-DIFFERENT-CLASS.
(defun valid-update-instance-for-different-class-keywords (old-class new-class added-slots)
(valid-initarg-keywords
new-class
(append
;; list of all applicable methods from SHARED-INITIALIZE
(remove-if-not
#'(lambda (method)
(let* ((specializers (method-specializers method))
(specializer1 (first specializers))
(specializer2 (second specializers)))
(and (not (eql-specializer-p specializer1))
(subclassp new-class specializer1)
(typep added-slots specializer2))))
(the list (generic-function-methods |#'shared-initialize|)))
;; list of all applicable methods from UPDATE-INSTANCE-FOR-DIFFERENT-CLASS
(remove-if-not
#'(lambda (method)
(let* ((specializers (method-specializers method))
(specializer1 (first specializers))
(specializer2 (second specializers)))
(and (not (eql-specializer-p specializer1))
(subclassp old-class specializer1)
(not (eql-specializer-p specializer2))
(subclassp new-class specializer2))))
(the list (generic-function-methods |#'update-instance-for-different-class|))))))
;; Also in record.d.
(defun check-initialization-argument-list (initargs caller)
(do ((l initargs (cddr l)))
((endp l))
(unless (symbolp (car l))
(error-of-type 'program-error ; ANSI CL 3.5.1.5. wants a PROGRAM-ERROR here.
"~S: invalid initialization argument ~S"
caller (car l)))
(when (endp (cdr l))
(error-of-type 'program-error ; ANSI CL 3.5.1.6. wants a PROGRAM-ERROR here.
"~S: keyword arguments in ~S should occur pairwise"
caller initargs))))
;; CLtL2 28.1.9.5., 28.1.9.4., ANSI CL 7.1.5., 7.1.4.
(defgeneric shared-initialize
(instance slot-names &rest initargs &key &allow-other-keys))
(setq |#'shared-initialize| #'shared-initialize)
#||
(defmethod shared-initialize ((instance standard-object) slot-names
&rest initargs)
(check-initialization-argument-list initargs 'shared-initialize)
(dolist (slot (class-slots (class-of instance)))
(let ((slotname (slot-definition-name slot)))
(multiple-value-bind (init-key init-value foundp)
(get-properties initargs (slot-definition-initargs slot))
(declare (ignore init-key))
(if foundp
(setf (slot-value instance slotname) init-value)
(unless (slot-boundp instance slotname)
(let ((initfunction (slot-definition-initfunction slot)))
(when init
(when (or (eq slot-names 'T) (memq slotname slot-names))
(setf (slot-value instance slotname)
(funcall initfunction))))))))))
instance)
||#
;; the main work is done by a SUBR:
(do-defmethod 'shared-initialize
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'standard-object) (find-class 't))
'fast-function #'clos::%shared-initialize
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(instance slot-names &rest initargs)
'signature #s(system::signature :req-num 2 :rest-p t)))
(do-defmethod 'shared-initialize
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'structure-object) (find-class 't))
'fast-function #'clos::%shared-initialize
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(instance slot-names &rest initargs)
'signature #s(system::signature :req-num 2 :rest-p t)))
;; CLtL2 28.1.12., ANSI CL 7.3.
(defgeneric reinitialize-instance
(instance &rest initargs &key &allow-other-keys))
(setq |#'reinitialize-instance| #'reinitialize-instance)
#||
(defmethod reinitialize-instance ((instance standard-object) &rest initargs)
(check-initialization-argument-list initargs 'reinitialize-instance)
(apply #'shared-initialize instance 'NIL initargs))
||#
#|| ; optimized:
(defmethod reinitialize-instance ((instance standard-object) &rest initargs)
(check-initialization-argument-list initargs 'reinitialize-instance)
(let ((h (gethash (class-of instance) *reinitialize-instance-table*)))
(if h
(progn
;; CLtL2 28.1.9.2., ANSI CL 7.1.2. Validity of initialization arguments
(let ((valid-keywords (car h)))
(unless (eq valid-keywords 't)
(sys::keyword-test initargs valid-keywords)))
(if (not (eq (cdr h) #'clos::%shared-initialize))
;; apply effective method from shared-initialize:
(apply (cdr h) instance 'NIL initargs)
;; clos::%shared-initialize with slot-names=NIL can be simplified:
(progn
(dolist (slot (class-slots (class-of instance)))
(let ((slotname (slot-definition-name slot)))
(multiple-value-bind (init-key init-value foundp)
(get-properties initargs (slot-definition-initargs slot))
(declare (ignore init-key))
(if foundp
(setf (slot-value instance slotname) init-value)))))
instance)))
(apply #'initial-reinitialize-instance instance initargs))))
||#
;; the main work is done by a SUBR:
(do-defmethod 'reinitialize-instance
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'standard-object))
'fast-function #'clos::%reinitialize-instance
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(instance &rest initargs)
'signature #s(system::signature :req-num 1 :rest-p t)))
(do-defmethod 'reinitialize-instance
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'structure-object))
'fast-function #'clos::%reinitialize-instance
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(instance &rest initargs)
'signature #s(system::signature :req-num 1 :rest-p t)))
;; At the first call of REINITIALIZE-INSTANCE of each class
;; we memorize the needed information in *reinitialize-instance-table*.
(defun initial-reinitialize-instance (instance &rest initargs)
(let* ((class (class-of instance))
(valid-keywords (valid-reinitialize-instance-keywords class)))
;; CLtL2 28.1.9.2., ANSI CL 7.1.2. Validity of initialization arguments
(unless (eq valid-keywords 't)
(sys::keyword-test initargs valid-keywords))
(let ((si-ef (compute-applicable-methods-effective-method |#'shared-initialize| instance 'NIL)))
(setf (gethash class *reinitialize-instance-table*)
(cons valid-keywords si-ef))
(apply si-ef instance 'NIL initargs))))
;; CLtL2 28.1.9.6., ANSI CL 7.1.6.
(defgeneric initialize-instance (instance &rest initargs
&key &allow-other-keys))
(setq |#'initialize-instance| #'initialize-instance)
#||
(defmethod initialize-instance ((instance standard-object) &rest initargs)
(check-initialization-argument-list initargs 'initialize-instance)
(apply #'shared-initialize instance 'T initargs))
||#
#|| ; optimized:
(defmethod initialize-instance ((instance standard-object) &rest initargs)
(check-initialization-argument-list initargs 'initialize-instance)
(let ((h (gethash class *make-instance-table*)))
(if h
(if (not (eq (svref h 3) #'clos::%shared-initialize))
;; apply effective method from shared-initialize:
(apply (svref h 3) instance 'T initargs)
;; clos::%shared-initialize with slot-names=T can be simplified:
(progn
(dolist (slot (class-slots (class-of instance)))
(let ((slotname (slot-definition-name slot)))
(multiple-value-bind (init-key init-value foundp)
(get-properties initargs (slot-definition-initargs slot))
(declare (ignore init-key))
(if foundp
(setf (slot-value instance slotname) init-value)
(unless (slot-boundp instance slotname)
(let ((initfunction (slot-definition-initfunction slot)))
(when initfunction
(setf (slot-value instance slotname)
(funcall initfunction)))))))))
instance))
(apply #'initial-initialize-instance instance initargs))))
||#
;; the main work is done by a SUBR:
(do-defmethod 'initialize-instance
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'standard-object))
'fast-function #'clos::%initialize-instance
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(instance &rest initargs)
'signature #s(system::signature :req-num 1 :rest-p t)))
(do-defmethod 'initialize-instance
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'structure-object))
'fast-function #'clos::%initialize-instance
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(instance &rest initargs)
'signature #s(system::signature :req-num 1 :rest-p t)))
;; At the first call of MAKE-INSTANCE or INITIALIZE-INSTANCE of each class
;; we memorize the needed information in *make-instance-table*.
(defun initial-initialize-instance (instance &rest initargs)
(let ((class (class-of instance)))
(multiple-value-bind (valid-keywords ai-ef)
(make-instance-table-entry1 class)
(multiple-value-bind (ii-ef si-ef) (make-instance-table-entry2 instance)
(setf (gethash class *make-instance-table*)
(vector valid-keywords ai-ef ii-ef si-ef))
;; apply effective method from SHARED-INITIALIZE:
(apply si-ef instance 'T initargs)))))
;; User-defined methods on allocate-instance are now supported.
(defgeneric allocate-instance (instance &rest initargs &key &allow-other-keys))
(setq |#'allocate-instance| #'allocate-instance)
#||
(defgeneric allocate-instance (class)
(:method ((class semi-standard-class))
(unless (= (class-initialized class) 6) (finalize-inheritance class))
(allocate-std-instance class (class-instance-size class)))
(:method ((class structure-class))
(sys::%make-structure (class-names class) (class-instance-size class)
:initial-element unbound)))
||#
#||
(defun %allocate-instance (class &rest initargs)
(check-initialization-argument-list initargs 'allocate-instance)
;; No need to check the validity of the initargs, because ANSI CL says
;; "The caller of allocate-instance is expected to have already checked
;; the initialization arguments."
;; Quick and dirty dispatch among <semi-standard-class> and <structure-class>.
;; (class-current-version class) is an atom, (class-names class) a cons.
(if (atom (class-current-version class))
(progn
(unless (= (class-initialized class) 6) (finalize-inheritance class))
;; Dispatch among <standard-class> and <funcallable-standard-class>.
(if (not (class-funcallablep class))
(allocate-std-instance class (class-instance-size class))
(allocate-funcallable-instance class (class-instance-size class))))
(sys::%make-structure (class-names class) (class-instance-size class)
:initial-element unbound)))
||#
; the main work is done by a SUBR:
(do-defmethod 'allocate-instance
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'semi-standard-class))
'fast-function #'clos::%allocate-instance
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(class &rest initargs)
'signature #s(system::signature :req-num 1 :rest-p t)))
(do-defmethod 'allocate-instance
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'structure-class))
'fast-function #'clos::%allocate-instance
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(class &rest initargs)
'signature #s(system::signature :req-num 1 :rest-p t)))
; No extended method check because this GF is specified in ANSI CL.
;(initialize-extended-method-check #'allocate-instance)
;; CLtL2 28.1.9.7., ANSI CL 7.1.7.
(defgeneric make-instance (class &rest initargs &key &allow-other-keys)
(:method ((class symbol) &rest initargs)
(apply #'make-instance (find-class class) initargs)))
#||
(defmethod make-instance ((class semi-standard-class) &rest initargs)
(check-initialization-argument-list initargs 'make-instance)
;; CLtL2 28.1.9.3., 28.1.9.4., ANSI CL 7.1.3., 7.1.4.: Take note of
;; default-initargs:
(dolist (default-initarg (class-default-initargs class))
(let ((nothing default-initarg))
(when (eq (getf initargs (car default-initarg) nothing) nothing)
(setq initargs
(append initargs
(list (car default-initarg)
(funcall (caddr default-initarg))))))))
#||
;; CLtL2 28.1.9.2., ANSI CL 7.1.2. Validity of initialization arguments
(sys::keyword-test initargs
(union (class-valid-initargs-from-slots class)
(applicable-keywords #'initialize-instance class))) ; ??
(let ((instance (apply #'allocate-instance class initargs)))
(apply #'initialize-instance instance initargs))
||#
(let ((h (gethash class *make-instance-table*)))
(if h
(progn
;; CLtL2 28.1.9.2., ANSI CL 7.1.2. Validity of initialization arguments
(let ((valid-keywords (svref h 0)))
(unless (eq valid-keywords 't)
(sys::keyword-test initargs valid-keywords)))
(let ((instance (apply #'allocate-instance class initargs)))
(if (not (eq (svref h 2) #'clos::%initialize-instance))
;; apply effective method from initialize-instance:
(apply (svref h 2) instance initargs)
;; clos::%initialize-instance can be simplified (one does not need
;; to look into *make-instance-table* once again):
(if (not (eq (svref h 3) #'clos::%shared-initialize))
;; apply effective method from shared-initialize:
(apply (svref h 3) instance 'T initargs)
...
))))
(apply #'initial-make-instance class initargs))))
||#
;; the main work is done by a SUBR:
(do-defmethod 'make-instance
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'semi-standard-class))
'fast-function #'clos::%make-instance
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(class &rest initargs)
'signature #s(system::signature :req-num 1 :rest-p t)))
(do-defmethod 'make-instance
(make-instance-<standard-method> <standard-method>
:specializers (list (find-class 'structure-class))
'fast-function #'clos::%make-instance
'wants-next-method-p nil
:qualifiers '()
:lambda-list '(class &rest initargs)
'signature #s(system::signature :req-num 1 :rest-p t)))
; No extended method check because this GF is specified in ANSI CL.
;(initialize-extended-method-check #'make-instance)
;; At the first call of MAKE-INSTANCE or INITIALIZE-INSTANCE of each class
;; we memorize the needed information in *make-instance-table*.
(defun initial-make-instance (class &rest initargs)
(multiple-value-bind (valid-keywords ai-ef)
(make-instance-table-entry1 class)
;; http://www.lisp.org/HyperSpec/Body/sec_7-1-2.html
;; 7.1.2 Declaring the Validity of Initialization Arguments
(unless (eq valid-keywords 't)
(sys::keyword-test initargs valid-keywords))
;; call the effective method of ALLOCATE-INSTANCE:
(let ((instance (apply ai-ef class initargs)))
(unless (eq (class-of instance) class)
(error-of-type 'error
(TEXT "~S method for ~S returned ~S")
'allocate-instance class instance))
(multiple-value-bind (ii-ef si-ef) (make-instance-table-entry2 instance)
(setf (gethash class *make-instance-table*)
(vector valid-keywords ai-ef ii-ef si-ef))
;; call the effective method of INITIALIZE-INSTANCE:
(apply ii-ef instance initargs))
;; return the instance
instance)))
;; Returns the valid initialization arguments of a class, or T if any symbol
;; is allowed.
(defun class-valid-initialization-keywords (class) ; ABI
(let ((entry (gethash class *make-instance-table*)))
(if entry
;; Get it from the cache.
(svref entry 0)
;; Compute it. Don't need to cache it, since this function does not need
;; to be fast.
(valid-make-instance-keywords class))))
;;; change-class
(defgeneric change-class (instance new-class &key &allow-other-keys)
(:method ((instance standard-object) (new-class standard-class)
&rest initargs)
(apply #'do-change-class instance new-class initargs))
(:method ((instance funcallable-standard-object) (new-class standard-class)
&rest initargs)
(declare (ignore initargs))
(error (TEXT "~S cannot change a funcallable object to a non-funcallable object: ~S")
'change-class instance))
(:method ((instance funcallable-standard-object) (new-class funcallable-standard-class)
&rest initargs)
(apply #'do-change-class instance new-class initargs))
(:method ((instance standard-object) (new-class funcallable-standard-class)
&rest initargs)
(declare (ignore initargs))
(error (TEXT "~S cannot change a non-funcallable object to a funcallable object: ~S")
'change-class instance))
(:method ((instance t) (new-class symbol) &rest initargs)
(apply #'change-class instance (find-class new-class) initargs)))
(defun do-change-class (instance new-class &rest initargs)
;; ANSI CL 7.2.1. Modifying the Structure of the Instance.
(let ((previous (%change-class instance new-class)))
;; previous = a copy of instance
;; instance = mutated instance, with new class, slots unbound
;; When the instance was used in an EQL specializer, the instance
;; could be used as index in a generic function's dispatch table. Need
;; to invalidate all the affected generic functions' dispatch tables.
(let ((specializer (existing-eql-specializer instance)))
(when specializer
(dolist (gf (specializer-direct-generic-functions specializer))
(when (typep-class gf <standard-generic-function>)
;; Clear the discriminating function.
;; The effective method cache does not need to be invalidated.
#|(setf (std-gf-effective-method-cache gf) '())|#
(finalize-fast-gf gf)))
;; Also, the EQL specializer is recorded in its class. But now its
;; class has changed; we have to record it in the new class.
(let ((old-class (class-of previous))
(new-class (class-of instance)))
(when (semi-standard-class-p old-class)
(remove-direct-instance-specializer old-class specializer))
(when (and (semi-standard-class-p new-class)
(specializer-direct-methods specializer))
(add-direct-instance-specializer new-class specializer)))))
;; Copy identically named slots:
(let ((old-slots (class-slots (class-of previous)))
(new-slots (class-slots new-class)))
(dolist (slot old-slots)
(let ((name (slot-definition-name slot)))
(when (slot-boundp previous name)
;; Retain the slot's value if it is a local slot in new-class.
(let ((new-slot (find name new-slots :test #'eq
:key #'slot-definition-name)))
(when (and new-slot (atom (slot-definition-location new-slot)))
(setf (slot-value instance name)
(slot-value previous name))))))))
;; ANSI CL 7.2.2. Initializing Newly Added Local Slots.
(apply #'update-instance-for-different-class
previous instance initargs)))
(defgeneric update-instance-for-different-class (previous current
&key &allow-other-keys)
(:method ((previous standard-object) (current standard-object)
&rest initargs)
;; ANSI CL 7.2.2. Initializing Newly Added Local Slots.
(check-initialization-argument-list initargs 'update-instance-for-different-class)
(let* ((old-class (class-of previous))
(old-slots-table (class-slot-location-table old-class))
(new-class (class-of current))
(added-slots
(mapcan #'(lambda (slot)
; Only local slots.
(when (atom (slot-definition-location slot))
(let ((name (slot-definition-name slot)))
; Only slots for which no slot of the same name
; exists in the previous class.
(when (null (gethash name old-slots-table))
(list name)))))
(class-slots new-class))))
;; CLtL2 28.1.9.2., ANSI CL 7.1.2. Validity of initialization arguments
(multiple-value-bind (valid-keywords found)
(gethash (cons old-class new-class) *update-instance-for-different-class-table*)
(unless found
(setq valid-keywords
(valid-update-instance-for-different-class-keywords
old-class new-class added-slots))
(setf (gethash (cons old-class new-class) *update-instance-for-different-class-table*)
valid-keywords))
(unless (eq valid-keywords 't)
(sys::keyword-test initargs valid-keywords)))
(apply #'shared-initialize current added-slots initargs)))
;; MOP p. 57.
(:method ((previous potential-class) (current standard-object) &rest initargs)
(declare (ignore initargs))
(update-metaobject-instance-for-different-class previous))
;; MOP p. 61.
(:method ((previous generic-function) (current standard-object) &rest initargs)
(declare (ignore initargs))
#| ;; MOP p. 61.
(update-metaobject-instance-for-different-class previous)
|# ;; We support this anyway, as an extension.
(let ((gf current))
(when (typep-class gf <standard-generic-function>)
;; Clear the effective method cache and the discriminating function.
(setf (std-gf-effective-method-cache gf) '())
(finalize-fast-gf gf)))
(call-next-method))
;; MOP p. 64.
(:method ((previous method) (current standard-object) &rest initargs)
(declare (ignore initargs))
#| ;; MOP p. 64.
(update-metaobject-instance-for-different-class previous)
|# ;; We support this anyway, as an extension.
(let ((gf (method-generic-function previous)))
(when (and gf (typep-class gf <standard-generic-function>))
;; Clear the effective method cache and the discriminating function.
(setf (std-gf-effective-method-cache gf) '())
(finalize-fast-gf gf))
(prog1
(call-next-method)
(setf (method-generic-function current) gf))))
;; MOP p. 67.
(:method ((previous slot-definition) (current standard-object) &rest initargs)
(declare (ignore initargs))
(update-metaobject-instance-for-different-class previous)))
(setq |#'update-instance-for-different-class| #'update-instance-for-different-class)
(defun update-metaobject-instance-for-different-class (previous)
(error (TEXT "~S: The MOP does not allow changing the class of metaobject ~S")
'update-instance-for-different-class previous))
;; Users want to be able to create subclasses of <standard-class> and write
;; methods on MAKE-INSTANCES-OBSOLETE on them. So, we now go redefine
;; MAKE-INSTANCES-OBSOLETE as a generic function.
(fmakunbound 'make-instances-obsolete)
(defgeneric make-instances-obsolete (class)
(:method ((class semi-standard-class))
(make-instances-obsolete-<semi-standard-class> class)
class)
(:method ((class symbol))
(make-instances-obsolete (find-class class))
class))
(defgeneric update-instance-for-redefined-class
(instance added-slots discarded-slots property-list &rest initargs
&key &allow-other-keys)
(:method ((instance standard-object) added-slots discarded-slots
property-list &rest initargs)
;; Check initargs.
(check-initialization-argument-list initargs 'update-instance-for-redefined-class)
;; CLtL2 28.1.9.2., ANSI CL 7.1.2. Validity of initialization arguments
(let ((class (class-of instance)))
(multiple-value-bind (valid-keywords found)
(gethash class *update-instance-for-redefined-class-table*)
(unless found
(let (independent)
(multiple-value-setq (valid-keywords independent)
(valid-update-instance-for-redefined-class-keywords
class added-slots discarded-slots property-list))
(when independent
(setf (gethash class *update-instance-for-redefined-class-table*)
valid-keywords))))
(unless (eq valid-keywords 't)
(sys::keyword-test initargs valid-keywords))))
(apply #'shared-initialize instance added-slots initargs))
#| ;; MOP p. 57, 61, 64, 67.
;; This is not needed, because the tests for <metaobject> in
;; reinitialize-instance-<defined-class> and
;; make-instances-obsolete-<semi-standard-class>-nonrecursive
;; prevent metaobject instances from being updated.
(:method ((instance metaobject) added-slots discarded-slots
property-list &rest initargs)
(declare (ignore added-slots discarded-slots property-list initargs))
(error (TEXT "~S: The MOP does not allow changing the metaobject class ~S")
'update-instance-for-redefined-class (class-of instance)))
|#
)
(setq |#'update-instance-for-redefined-class| #'update-instance-for-redefined-class)
;;; Utility functions
;; Returns the slot names of an instance of a slotted-class
;; (i.e. of a structure-object or standard-object).
(defun slot-names (object)
(mapcar #'slot-definition-name (class-slots (class-of object))))
| 41,206 | Common Lisp | .lisp | 803 | 43.135741 | 107 | 0.662083 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | c767957e80298e56b04f34beb87c1e9d39bbc84cbedf0139027b47fc5ed2b341 | 11,397 | [
-1
] |
11,398 | defstruct.lisp | ufasoft_lisp/clisp/defstruct.lisp | ;;; Sources for CLISP DEFSTRUCT macro
;;; Bruno Haible 1988-2005
;;; Sam Steingold 1998-2006, 2010
;;; German comments translated into English: Stefan Kain 2003-01-14
(in-package "SYSTEM")
#| Explanation of the appearing data types:
For structure types (but not for structure classes!):
(get name 'DEFSTRUCT-DESCRIPTION) =
#(type size keyword-constructor effective-slotlist direct-slotlist
boa-constructors copier predicate defaultfun0 defaultfun1 ...)
type (if the type of the whole structure is meant):
= LIST storage as list
= VECTOR storage as (simple-)vector
= (VECTOR element-type) storage as vector with element-type
size is the list length / vector length.
keyword-constructor = NIL or the name of the keyword-constructor
boa-constructors = list of names of BOA constructors
copier = NIL or the name of the copier function
predicate = NIL or the name of the predicate function
effective-slotlist is a packed description of the slots of a structure:
effective-slotlist = ({slot}*)
slot = an instance of structure-effective-slot-definition, containing:
name - the slotname,
initargs - a list containing the initialization argument,
or NIL for the pseudo-slot containing the structure name in
named structures,
offset - the location of the slot in any instance,
initer = (initform . initfunction) - as usual,
init-function-form -
a form (a symbol or a list (SVREF ...)), that yields
upon evaluation in an arbitrary environment a function,
that returns the default value, when called.
type - the declared type for this slot,
readonly = NIL or = T specifying, if this slot is readonly, i.e.
after the construction of the Structure the slot cannot be
changed with (setf ...) anymore.
(See also pr_structure_default() in io.d.)
direct-slotlist is the list of slots defined together with the structure:
direct-slotlist = ({slot*})
slot = an instance of structure-direct-slot-definition, containing:
name, initform, initfunction, initargs, type, initer - see above
writers - list of setters: ((setf struct-slot-name))
readers - list of getters: (struct-slot-name)
The initializations are specified as follows:
- not real slot (i.e. initargs = ()):
initform = `(QUOTE ,name)
initfunction = a constant-initfunction for name
init-function-form = `(MAKE-CONSTANT-INITFUNCTION ',name)
- real slot with constant initform:
initform = as specified by the user
initfunction = a constant-initfunction for the initform's value
init-function-form = `(MAKE-CONSTANT-INITFUNCTION ,initform)
- real slot with non-constant initform:
initform = as specified by the user
initfunction = a closure taking 0 arguments, or nil
init-function-form = for inherited slots: `(SVREF ...)
for direct slots: `(FUNCTION (LAMBDA () ,initform))
In both cases, after some processing: a gensym
referring to a binding.
For structure classes, i.e. if type = T, all this information is contained
in the CLOS class (get name 'CLOS::CLOSCLASS). In this case, all slots are
real slots: the names list is stored in the first memory word already by
ALLOCATE-INSTANCE, without need for corresponding effective-slot-definition.
|#
;; Indices of the fixed elements of a defstruct-description:
;; if you add a slot, you need to modify io.d:SYS::STRUCTURE-READER
(defconstant *defstruct-description-type-location* 0)
(defconstant *defstruct-description-size-location* 1)
(defconstant *defstruct-description-kconstructor-location* 2)
(defconstant *defstruct-description-slots-location* 3)
(defconstant *defstruct-description-direct-slots-location* 4)
(defconstant *defstruct-description-boa-constructors-location* 5)
(defconstant *defstruct-description-copier-location* 6)
(defconstant *defstruct-description-predicate-location* 7)
(proclaim '(constant-inline *defstruct-description-type-location*
*defstruct-description-size-location*
*defstruct-description-kconstructor-location*
*defstruct-description-slots-location*
*defstruct-description-direct-slots-location*
*defstruct-description-boa-constructors-location*
*defstruct-description-copier-location*
*defstruct-description-predicate-location*))
(defun make-ds-slot (name initargs offset initer type readonly)
(clos::make-instance-<structure-effective-slot-definition>
clos::<structure-effective-slot-definition>
:name name
:initargs initargs
:initform (car initer) :initfunction (cdr initer) 'clos::inheritable-initer initer
:type type
'clos::readonly readonly
'clos::location offset))
(defun copy-<structure-effective-slot-definition> (slot)
(make-ds-slot
(clos:slot-definition-name slot)
(clos:slot-definition-initargs slot)
(clos:slot-definition-location slot)
(clos::slot-definition-inheritable-initer slot)
(clos:slot-definition-type slot)
(clos::structure-effective-slot-definition-readonly slot)))
(defmacro ds-real-slot-p (slot)
`(not (null (clos:slot-definition-initargs ,slot))))
(defmacro ds-pseudo-slot-default (slot)
;; The pseudo-slots have an initform = (QUOTE name) and an initfunction which
;; returns the name.
`(funcall (clos:slot-definition-initfunction ,slot)))
#| The type test comes in 4 variants. Keep them in sync! |#
#| Type test, for TYPEP.
Must be equivalent to (typep object (ds-canonicalize-type symbol)).
|#
(defun ds-typep (object symbol desc)
(declare (ignore symbol))
(let ((type (svref desc *defstruct-description-type-location*))
(size (svref desc *defstruct-description-size-location*)))
(if (eq type 'LIST)
(and (conses-p size object)
(dolist (slot (svref desc *defstruct-description-slots-location*) t)
(unless (ds-real-slot-p slot)
(unless (eq (nth (clos:slot-definition-location slot) object)
(ds-pseudo-slot-default slot))
(return nil)))))
(and (vectorp object) (simple-array-p object)
(>= (length object) size)
(equal (array-element-type object)
(if (consp type)
(upgraded-array-element-type (second type))
'T))
(dolist (slot (svref desc *defstruct-description-slots-location*) t)
(unless (ds-real-slot-p slot)
(unless (and (simple-vector-p object)
(eq (svref object (clos:slot-definition-location slot))
(ds-pseudo-slot-default slot)))
(return nil))))))))
#| Type test expansion, for TYPEP compiler macro. |#
(defun ds-typep-expansion (objform symbol desc)
(declare (ignore symbol))
(let ((type (svref desc *defstruct-description-type-location*))
(size (svref desc *defstruct-description-size-location*))
(tmp (gensym)))
`(LET ((,tmp ,objform))
,(if (eq type 'LIST)
`(AND ,@(case size
(0 '())
(1 `((CONSP ,tmp)))
(t `((CONSES-P ,size ,tmp))))
,@(mapcan #'(lambda (slot)
(unless (ds-real-slot-p slot)
`((EQ (NTH ,(clos:slot-definition-location slot) ,tmp)
',(ds-pseudo-slot-default slot)))))
(svref desc *defstruct-description-slots-location*)))
(let ((eltype (if (consp type)
(upgraded-array-element-type (second type))
'T)))
`(AND ,@(if (eq eltype 'T)
`((SIMPLE-VECTOR-P ,tmp))
`((VECTORP ,tmp)
(SIMPLE-ARRAY-P ,tmp)
(EQUAL (ARRAY-ELEMENT-TYPE ,tmp) ',eltype)))
,(case size
(0 'T)
(t `(>= (LENGTH ,tmp) ,size)))
,@(mapcan #'(lambda (slot)
(unless (ds-real-slot-p slot)
`((EQ (SVREF ,tmp ,(clos:slot-definition-location slot))
',(ds-pseudo-slot-default slot)))))
(svref desc *defstruct-description-slots-location*))))))))
#| Type canonicalization, for SUBTYPEP. |#
(defun ds-canonicalize-type (symbol)
(let ((desc (get symbol 'DEFSTRUCT-DESCRIPTION)))
(if desc
(let ((type (svref desc *defstruct-description-type-location*))
(size (svref desc *defstruct-description-size-location*))
(slotlist (svref desc *defstruct-description-slots-location*)))
(if (eq type 'LIST)
(let ((resulttype 'T))
;; Start with T, not (MEMBER NIL), because of the possibility
;; of subclasses.
(dotimes (i size) (setq resulttype (list 'CONS 'T resulttype)))
(dolist (slot slotlist)
(unless (ds-real-slot-p slot)
(let ((resttype resulttype))
(dotimes (j (clos:slot-definition-location slot))
(setq resttype (third resttype)))
(setf (second resttype) `(EQL ,(ds-pseudo-slot-default slot))))))
resulttype)
`(AND (SIMPLE-ARRAY ,(if (consp type) (second type) 'T) (*))
;; Constraints that cannot be represented through ANSI CL
;; type specifiers. We use SATISFIES types with uninterned
;; symbols. This is possible because this function is only
;; used for SUBTYPEP.
,@(when (or (plusp size)
(some #'(lambda (slot) (not (ds-real-slot-p slot)))
slotlist))
(let ((constraint-name (gensym)))
(setf (symbol-function constraint-name)
#'(lambda (x) (typep x symbol)))
`((SATISFIES ,constraint-name)))))))
; The DEFSTRUCT-DESCRIPTION was lost.
'NIL)))
#| (ds-make-pred predname type name slotlist size)
returns the form, that creates the type-test-predicate for
the structure name.
type the type of the structure,
name the name of the structure,
predname the name of the type-test-predicate,
slotlist (only used when type /= T) list of slots
size instance size
|#
(defun ds-make-pred (predname type name slotlist size)
`(,@(if (eq type 'T) `((PROCLAIM '(INLINE ,predname))) '())
(DEFUN ,predname (OBJECT)
,(if (eq type 'T)
`(%STRUCTURE-TYPE-P ',name OBJECT)
(let ((max-offset -1)
(max-name-offset -1))
(dolist (slot+initff slotlist)
(let ((slot (car slot+initff)))
(setq max-offset (max max-offset (clos:slot-definition-location slot)))
(unless (ds-real-slot-p slot)
(setq max-name-offset (max max-name-offset (clos:slot-definition-location slot))))))
; This code is only used when there is at least one named slot.
(assert (<= 0 max-name-offset max-offset))
(assert (< max-offset size))
(if (eq type 'LIST)
`(AND ,@(case size
(0 '())
(1 `((CONSP OBJECT)))
(t `((CONSES-P ,size OBJECT))))
,@(mapcan #'(lambda (slot+initff)
(let ((slot (car slot+initff)))
(unless (ds-real-slot-p slot)
`((EQ (NTH ,(clos:slot-definition-location slot) OBJECT)
',(ds-pseudo-slot-default slot))))))
slotlist))
; This code is only used when there is at least one named slot.
; Therefore the vector's upgraded element type must contain
; SYMBOL, i.e. it must be a general vector.
`(AND (SIMPLE-VECTOR-P OBJECT)
(>= (LENGTH OBJECT) ,size)
,@(mapcan #'(lambda (slot+initff)
(let ((slot (car slot+initff)))
(unless (ds-real-slot-p slot)
`((EQ (SVREF OBJECT ,(clos:slot-definition-location slot))
',(ds-pseudo-slot-default slot))))))
slotlist))))))))
#| auxiliary function for both constructors:
(ds-arg-default arg slot+initff)
returns for an argument arg (part of the argument list) the part of
the argument list, that binds this argument with the default for slot.
|#
(defun ds-arg-default (arg slot+initff)
(let* ((slot (car slot+initff))
(initer (clos::slot-definition-inheritable-initer slot))
(initfunction (clos::inheritable-slot-definition-initfunction initer)))
`(,arg
;; Initial value: If it is not a constant form, must funcall the
;; initfunction. If it is a constant, we can use the initform directly.
;; If no initform has been provided, ANSI CL says that "the consequences
;; are undefined if an attempt is later made to read the slot's value
;; before a value is explicitly assigned", i.e. we could leave the slot
;; uninitialized (= #<UNBOUND> in the structure case). But CLtL2 says
;; "the element's initial value is undefined", which implies that the
;; slot is initialized to an arbitrary value. We use NIL as this value.
,(if ; equivalent to (constantp (clos::inheritable-slot-definition-initform initer))
(or (null initfunction) (constant-initfunction-p initfunction))
(clos::inheritable-slot-definition-initform initer)
`(FUNCALL ,(cdr slot+initff))))))
#| auxiliary function for both constructors:
(ds-make-constructor-body type name names size slotlist get-var)
returns the expression, that creates and fills a structure
of given type.
|#
(defun ds-make-constructor-body (type name names size slotlist varlist)
(if (and (or (eq type 'VECTOR) (eq type 'LIST))
(do ((slotlistr slotlist (cdr slotlistr))
(index 0 (1+ index)))
((null slotlistr) (eql index size))
(let* ((slot+initff (car slotlistr))
(slot (car slot+initff)))
(unless (eq (clos:slot-definition-location slot) index)
(return nil)))))
;; optimize the simple case
`(,type ,@(mapcar #'(lambda (slot+initff var)
(let ((slot (car slot+initff)))
(if (ds-real-slot-p slot)
`(THE ,(clos:slot-definition-type slot) ,var)
`(QUOTE ,(ds-pseudo-slot-default slot)))))
slotlist varlist))
`(LET ((OBJECT
,(cond ((eq type 'T) `(%MAKE-STRUCTURE ,names ,size))
((eq type 'LIST) `(MAKE-LIST ,size))
((consp type)
`(MAKE-ARRAY ,size :ELEMENT-TYPE ',(second type)))
(t `(MAKE-ARRAY ,size)))))
,@(mapcar
#'(lambda (slot+initff var)
(let* ((slot (car slot+initff))
(offset (clos:slot-definition-location slot)))
`(SETF
,(cond ((eq type 'T)
`(%STRUCTURE-REF ',name OBJECT ,offset))
((eq type 'LIST)
`(NTH ,offset OBJECT))
((eq type 'VECTOR)
`(SVREF OBJECT ,offset))
(t `(AREF OBJECT ,offset)))
,(if (or (eq type 'T) (ds-real-slot-p slot))
`(THE ,(clos:slot-definition-type slot) ,var)
`(QUOTE ,(ds-pseudo-slot-default slot))))))
slotlist varlist)
OBJECT)))
#| auxiliary function for ds-make-boa-constructor:
(ds-arg-with-default arg slotlist)
returns for an argument arg (part of the argument list) the part of
the argument list, that binds this argument with the correct default value.
|#
(defun ds-arg-with-default (arg slotlist)
(if (and (listp arg) (consp (cdr arg)))
;; default value is already supplied
arg
;; no default value in the lambda-list
(let* ((var (if (listp arg) (first arg) arg))
(slot+initff (find (if (consp var) (second var) var) slotlist
:key #'(lambda (slot+initff)
(clos:slot-definition-name (car slot+initff)))
:test #'eq)))
(if slot+initff
;; slot found -> take its default value
(ds-arg-default var slot+initff)
;; slot not found, no default value
arg))))
#| (ds-make-boa-constructor descriptor type name names size slotlist whole-form)
returns the form that defines the BOA-constructor.
|#
(defun ds-make-boa-constructor (descriptor type name names size slotlist whole-form)
(let ((constructorname (first descriptor))
(arglist (second descriptor)))
(multiple-value-bind (reqs optvars optinits optsvars rest
keyflag keywords keyvars keyinits keysvars
allow-other-keys auxvars auxinits)
(analyze-lambdalist arglist
#'(lambda (lalist detail errorstring &rest arguments)
(declare (ignore lalist)) ; use WHOLE-FORM instead
(sys::lambda-list-error whole-form detail
(TEXT "~S ~S: In ~S argument list: ~A")
'defstruct name ':constructor
(apply #'format nil errorstring arguments))))
(let* ((argnames
; The list of all arguments that are already supplied with
; values through the parameter list.
(append reqs optvars (if (not (eql rest 0)) (list rest))
keyvars auxvars))
(new-arglist ; new argument list
`(;; required args:
,@reqs
;; optional args:
,@(if optvars
(cons '&optional
(mapcar #'(lambda (arg var init svar)
(declare (ignore var init svar))
(ds-arg-with-default arg slotlist))
(cdr (memq '&optional arglist))
optvars optinits optsvars))
'())
;; &rest arg:
,@(if (not (eql rest 0))
(list '&rest rest)
'())
;; &key args:
,@(if keyflag
(cons '&key
(append
(mapcar #'(lambda (arg symbol var init svar)
(declare (ignore symbol var init svar))
(ds-arg-with-default arg slotlist))
(cdr (memq '&key arglist))
keywords keyvars keyinits keysvars)
(if allow-other-keys '(&allow-other-keys) '())))
'())
;; &aux args:
&aux
,@(mapcar #'(lambda (arg var init)
(declare (ignore var init))
(ds-arg-with-default arg slotlist))
(cdr (memq '&aux arglist))
auxvars auxinits)
,@(let ((slotinitlist nil))
(dolist (slot+initff slotlist)
(let ((slot (car slot+initff)))
(when (or (eq type 'T) (ds-real-slot-p slot))
(unless (memq (clos:slot-definition-name slot) argnames)
(push (ds-arg-with-default
(clos:slot-definition-name slot) slotlist)
slotinitlist)))))
(nreverse slotinitlist)))))
`(DEFUN ,constructorname ,new-arglist
,(ds-make-constructor-body type name names size slotlist
(mapcar #'(lambda (slot+initff)
(clos:slot-definition-name (car slot+initff)))
slotlist)))))))
#| (ds-make-keyword-constructor descriptor type name names size slotlist)
returns the form, that defines the keyword-constructor. |#
(defun ds-make-keyword-constructor (descriptor type name names size slotlist)
(let ((varlist
(mapcar #'(lambda (slot+initff)
(let ((slot (car slot+initff)))
(if (or (eq type 'T) (ds-real-slot-p slot))
(make-symbol
(symbol-name (clos:slot-definition-name slot)))
nil)))
slotlist)))
`(DEFUN ,descriptor
(&KEY
,@(mapcan
#'(lambda (slot+initff var)
(let ((slot (car slot+initff)))
(if (or (eq type 'T) (ds-real-slot-p slot))
(list (ds-arg-default var slot+initff))
'())))
slotlist varlist))
,(ds-make-constructor-body type name names size slotlist varlist))))
(defun ds-make-copier (copiername name type)
(declare (ignore name))
`(,@(if (or (eq type 'T) (eq type 'LIST))
`((PROCLAIM '(INLINE ,copiername)))
'())
(DEFUN ,copiername (STRUCTURE)
,(if (eq type 'T)
'(COPY-STRUCTURE STRUCTURE)
(if (eq type 'LIST)
'(COPY-LIST STRUCTURE)
(if (consp type)
`(LET* ((OBJ-LENGTH (ARRAY-TOTAL-SIZE STRUCTURE))
(OBJECT (MAKE-ARRAY OBJ-LENGTH :ELEMENT-TYPE
(QUOTE ,(second type)))))
(DOTIMES (I OBJ-LENGTH OBJECT)
(SETF (AREF OBJECT I) (AREF STRUCTURE I))))
'(%COPY-SIMPLE-VECTOR STRUCTURE)))))))
(defun ds-accessor-name (slotname concname)
(if concname
(concat-pnames concname slotname)
slotname))
(defun ds-make-readers (name names type concname slotlist)
(mapcap
#'(lambda (slot+initff)
(let ((slot (car slot+initff)))
(when (or (eq type 'T) (ds-real-slot-p slot))
(let ((accessorname (ds-accessor-name (clos:slot-definition-name slot) concname))
(offset (clos:slot-definition-location slot))
(slottype (clos:slot-definition-type slot)))
;; This makes the macroexpansion depend on the current state
;; of the compilation environment, but it doesn't hurt because
;; the included structure's definition must already be
;; present in the compilation environment anyway. We don't expect
;; people to re-DEFUN defstruct accessors.
(unless (memq (get accessorname 'SYSTEM::DEFSTRUCT-READER name)
(cdr names))
`((PROCLAIM '(FUNCTION ,accessorname (,name) ,slottype))
(PROCLAIM '(INLINE ,accessorname))
(DEFUN ,accessorname (OBJECT)
(THE ,slottype
,(cond ((eq type 'T)
`(%STRUCTURE-REF ',name OBJECT ,offset))
((eq type 'LIST) `(NTH ,offset OBJECT))
((consp type) `(AREF OBJECT ,offset))
(t `(SVREF OBJECT ,offset)))))
(SYSTEM::%PUT ',accessorname 'SYSTEM::DEFSTRUCT-READER
',name)))))))
slotlist))
(defun ds-make-writers (name names type concname slotlist)
(mapcap
#'(lambda (slot+initff)
(let ((slot (car slot+initff)))
(when (and (or (eq type 'T) (ds-real-slot-p slot))
(not (clos::structure-effective-slot-definition-readonly slot)))
(let ((accessorname (ds-accessor-name (clos:slot-definition-name slot) concname))
(offset (clos:slot-definition-location slot))
(slottype (clos:slot-definition-type slot)))
;; This makes the macroexpansion depend on the current state
;; of the compilation environment, but it doesn't hurt because
;; the included structure's definition must already be
;; present in the compilation environment anyway. We don't expect
;; people to re-DEFUN or re-DEFSETF defstruct accessors.
(unless (memq (get accessorname 'SYSTEM::DEFSTRUCT-WRITER name)
(cdr names))
`((PROCLAIM '(FUNCTION (SETF ,accessorname) (,slottype ,name) ,slottype))
(PROCLAIM '(INLINE (SETF ,accessorname)))
(DEFUN (SETF ,accessorname) (VALUE OBJECT)
,(if (eq type 'T)
`(%STRUCTURE-STORE ',name
OBJECT
,offset
,(if (eq 'T slottype)
`VALUE
`(THE ,slottype VALUE)))
(if (eq type 'LIST)
`(SETF (NTH ,offset OBJECT) VALUE)
(if (consp type)
`(SETF (AREF OBJECT ,offset) VALUE)
`(SETF (SVREF OBJECT ,offset) VALUE)))))
(SYSTEM::%PUT ',accessorname 'SYSTEM::DEFSTRUCT-WRITER
',name)))))))
slotlist))
(defun find-structure-class-slot-initfunction (classname slotname) ; ABI
(let ((class (find-class classname)))
(unless (clos::structure-class-p class)
(error (TEXT "The class ~S is not a structure class: ~S")
classname class))
(let* ((slots (clos:class-slots class))
(slot
; (find slotname (the list) slots :test #'clos:slot-definition-name)
(dolist (s slots)
(when (eql (clos:slot-definition-name s) slotname) (return s)))))
(unless slot
(error (TEXT "The class ~S has no slot named ~S.")
classname slotname))
(clos:slot-definition-initfunction slot))))
(defun find-structure-slot-initfunction (name slotname) ; ABI
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(unless desc
(if (clos::defined-class-p (get name 'CLOS::CLOSCLASS))
(error (TEXT "The structure type ~S has been defined as a class.")
name)
(error (TEXT "The structure type ~S has not been defined.")
name)))
(let* ((slots (svref desc *defstruct-description-slots-location*))
(slot
; (find slotname (the list) slots :test #'clos:slot-definition-name)
(dolist (s slots)
(when (eql (clos:slot-definition-name s) slotname) (return s)))))
(unless slot
(error (TEXT "The structure type ~S has no slot named ~S.")
name slotname))
(clos:slot-definition-initfunction slot))))
(defun ds-initfunction-fetcher (name type slotname)
(if (eq type 'T)
`(FIND-STRUCTURE-CLASS-SLOT-INITFUNCTION ',name ',slotname)
`(FIND-STRUCTURE-SLOT-INITFUNCTION ',name ',slotname)))
;; A hook for CLOS
(predefun clos::defstruct-remove-print-object-method (name) ; preliminary
(declare (ignore name))
nil)
(defun make-load-form-slot-list (slotlist default-slots default-vars mlf)
(mapcar #'(lambda (slot+initff)
(let ((slot (car slot+initff)))
(funcall mlf
slot
(let ((i (position slot+initff default-slots)))
(if i (nth i default-vars) (cdr slot+initff))))))
slotlist))
(defmacro defstruct (&whole whole-form
name-and-options . docstring-and-slotargs)
(let ((name name-and-options)
(options nil)
(conc-name-option t)
(constructor-option-list nil)
(keyword-constructor nil)
(boa-constructors '())
(copier-option t)
(predicate-option 0)
(include-option nil)
names
namesform
(namesbinding nil)
(print-object-option nil)
(type-option t)
(named-option 0)
(initial-offset-option 0)
(initial-offset 0)
(docstring nil)
(slotargs docstring-and-slotargs)
(directslotlist nil) ; list of (slot . initff)
size
(include-skip 0)
(inherited-slot-count 0)
(slotlist nil) ; list of (slot . initff)
(slotdefaultvars nil)
(slotdefaultfuns nil)
(slotdefaultslots nil) ; list of (slot . initff)
(slotdefaultdirectslots nil) ; list of (slot . initff)
constructor-forms )
;; check name-and-options:
(when (listp name-and-options)
(setq name (first name-and-options))
(setq options (rest name-and-options)))
;; otherwise, name and options are already correct.
(setq name (check-not-declaration name 'defstruct))
;; name is a symbol, options is the list of options.
;; processing the options:
(dolist (option options)
(when (keywordp option) (setq option (list option))) ; option without arguments
(if (listp option)
(if (keywordp (car option))
(case (first option)
(:CONC-NAME
(setq conc-name-option (second option)))
(:CONSTRUCTOR
(if (atom (cdr option))
;; default-keyword-constructor
(push (concat-pnames "MAKE-" name) constructor-option-list)
(let ((arg (second option)))
(setq arg (check-symbol arg 'defstruct))
(push
(if (atom (cddr option))
arg ; keyword-constructor
(if (not (listp (third option)))
(error-of-type 'source-program-error
:form whole-form
:detail (third option)
(TEXT "~S ~S: argument list should be a list: ~S")
'defstruct name (third option))
(rest option))) ; BOA-constructor
constructor-option-list))))
(:COPIER
(when (consp (cdr option))
(let ((arg (second option)))
(setq arg (check-symbol arg 'defstruct))
(setq copier-option arg))))
(:PREDICATE
(when (consp (cdr option))
(let ((arg (second option)))
(setq arg (check-symbol arg 'defstruct))
(setq predicate-option arg))))
((:INCLUDE :INHERIT)
(if (null include-option)
(setq include-option option)
(error-of-type 'source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: At most one :INCLUDE argument may be specified: ~S")
'defstruct name options)))
((:PRINT-FUNCTION :PRINT-OBJECT)
(if (null (cdr option))
(setq print-object-option '(PRINT-STRUCTURE STRUCT STREAM))
(let ((arg (second option)))
(when (and (consp arg) (eq (first arg) 'FUNCTION))
(warn (TEXT "~S: Use of ~S implicitly applies FUNCTION.~@
Therefore using ~S instead of ~S.")
'defstruct (first option) (second arg) arg)
(setq arg (second arg)))
(setq print-object-option
`(,arg STRUCT STREAM
,@(if (eq (first option) ':PRINT-FUNCTION)
'(*PRIN-LEVEL*) '()))))))
(:TYPE (setq type-option (second option)))
(:NAMED (setq named-option t))
(:INITIAL-OFFSET (setq initial-offset-option (or (second option) 0)))
(T (error-of-type 'source-program-error
:form whole-form
:detail (first option)
(TEXT "~S ~S: unknown option ~S")
'defstruct name (first option))))
(error-of-type 'source-program-error
:form whole-form
:detail option
(TEXT "~S ~S: invalid syntax in ~S option: ~S")
'defstruct name 'defstruct option))
(error-of-type 'source-program-error
:form whole-form
:detail option
(TEXT "~S ~S: not a ~S option: ~S")
'defstruct name 'defstruct option)))
;;; conc-name-option is either T or NIL or the :CONC-NAME argument.
;; constructor-option-list is a list of all :CONSTRUCTOR-arguments,
;; each in the form symbol or (symbol arglist . ...).
;; copier-option is either T or the :COPIER-argument.
;; predicate-option is either 0 or the :PREDICATE-argument.
;; include-option is either NIL or the entire
;; :INCLUDE/:INHERIT-option.
;; print-object-option is NIL or a form for the body of the PRINT-OBJECT
;; method.
;; type-option is either T or the :TYPE-argument.
;; named-option is either 0 or T.
;; initial-offset-option is either 0 or the :INITIAL-OFFSET-argument.
;;; inspection of the options:
(setq named-option (or (eq type-option 'T) (eq named-option 'T)))
;; named-option (NIL or T) specifies, if the name is in the structure.
(if named-option
(when (eql predicate-option 0)
(setq predicate-option (concat-pnames name "-P"))) ; defaultname
(if (or (eql predicate-option 0) (eq predicate-option 'NIL))
(setq predicate-option 'NIL)
(error-of-type 'source-program-error
:form whole-form
:detail predicate-option
(TEXT "~S ~S: There is no ~S for unnamed structures.")
'defstruct name :predicate)))
;; predicate-option is
;; if named-option=T: either NIL or the name of the type-test-predicate,
;; if named-option=NIL meaningless.
(when (eq conc-name-option 'T)
(setq conc-name-option (string-concat (string name) "-")))
;; conc-name-option is the name prefix.
(if constructor-option-list
(setq constructor-option-list (remove 'NIL constructor-option-list))
(setq constructor-option-list (list (concat-pnames "MAKE-" name))))
;; constructor-option-list is a list of all constructors that have to be
;; created, each in the form symbol or (symbol arglist . ...).
(if (eq copier-option 'T)
(setq copier-option (concat-pnames "COPY-" name)))
;; copier-option is either NIL or the name of the copy function.
(unless (or (eq type-option 'T)
(eq type-option 'VECTOR)
(eq type-option 'LIST)
(and (consp type-option) (eq (first type-option) 'VECTOR)))
(error-of-type 'source-program-error
:form whole-form
:detail type-option
(TEXT "~S ~S: invalid :TYPE option ~S")
'defstruct name type-option))
;; type-option is either T or LIST or VECTOR or (VECTOR ...)
(unless (and (integerp initial-offset-option) (>= initial-offset-option 0))
(error-of-type 'source-program-error
:form whole-form
:detail initial-offset-option
(TEXT "~S ~S: The :INITIAL-OFFSET must be a nonnegative integer, not ~S")
'defstruct name initial-offset-option))
;; initial-offset-option is an Integer >=0.
(when (and (plusp initial-offset-option) (eq type-option 'T))
(error-of-type 'source-program-error
:form whole-form
:detail options
(TEXT "~S ~S: :INITIAL-OFFSET must not be specified without :TYPE : ~S")
'defstruct name options))
;; if type-option=T, then initial-offset-option=0.
(when (eq type-option 'T) (setq include-skip 1))
;; if type-option=T, include-skip is 1, else 0.
(when (stringp (first docstring-and-slotargs))
(setq docstring (first docstring-and-slotargs))
(setq slotargs (rest docstring-and-slotargs)))
;; else, docstring and slotargs are already correct.
;; docstring is either NIL or a String.
;; slotargs are the remaining arguments.
(if include-option
(let* ((option (rest include-option))
(subname (first option))
(incl-class (get subname 'CLOS::CLOSCLASS))
(incl-desc (get subname 'DEFSTRUCT-DESCRIPTION)))
(unless (clos::defined-class-p incl-class)
(setq incl-class nil))
(when (and (null incl-class) (null incl-desc))
(error-of-type 'source-program-error
:form whole-form
:detail subname
(TEXT "~S ~S: included structure ~S has not been defined.")
'defstruct name subname))
(when (and incl-class (not (clos::structure-class-p incl-class)))
(error-of-type 'source-program-error
:form whole-form
:detail subname
(TEXT "~S ~S: included structure ~S is not a structure type.")
'defstruct name subname))
(when incl-class
(setq names (cons name (clos::class-names incl-class)))
(setq namesbinding
(list
(list
(setq namesform (gensym))
`(CONS ',name (CLOS::CLASS-NAMES (GET ',subname 'CLOS::CLOSCLASS)))))))
(unless (equalp (if incl-class 't (svref incl-desc *defstruct-description-type-location*)) type-option)
(error-of-type 'source-program-error
:form whole-form
:detail subname
(TEXT "~S ~S: included structure ~S must be of the same type ~S.")
'defstruct name subname type-option))
(setq slotlist
(nreverse
(mapcar #'(lambda (slot)
(cons (copy-<structure-effective-slot-definition> slot)
(ds-initfunction-fetcher subname type-option
(clos:slot-definition-name slot))))
(if incl-class
(clos:class-slots incl-class)
(svref incl-desc *defstruct-description-slots-location*)))))
;; slotlist is the reversed list of the inherited slots.
(setq include-skip (if incl-class
(clos::class-instance-size incl-class)
(svref incl-desc *defstruct-description-size-location*)))
(when slotlist
(assert (> include-skip (clos:slot-definition-location (car (first slotlist))))))
;; include-skip >=0 is the number of slots that are already consumend
;; by the substructure, the "size" of the substructure.
;; Process further arguments of the :INCLUDE-option:
(dolist (slotarg (rest option))
(let* ((slotname (if (atom slotarg) slotarg (first slotarg)))
(slot+initff (find slotname slotlist
:key #'(lambda (slot+initff)
(clos:slot-definition-name (car slot+initff)))
:test #'eq)))
(when (null slot+initff)
(error-of-type 'source-program-error
:form whole-form
:detail slotname
(TEXT "~S ~S: included structure ~S has no component with name ~S.")
'defstruct name subname slotname))
(let ((slot (car slot+initff)))
(if (atom slotarg)
; overwrite default to NIL
(progn
(setf (clos::slot-definition-inheritable-initer slot)
(cons 'NIL (make-constant-initfunction 'NIL)))
(setf (cdr slot+initff) `(MAKE-CONSTANT-INITFUNCTION NIL)))
(progn
(let ((initform (second slotarg)))
(if (constantp initform)
(progn
(setf (clos::slot-definition-inheritable-initer slot)
(cons initform (make-constant-initfunction (eval initform))))
(setf (cdr slot+initff) `(MAKE-CONSTANT-INITFUNCTION ,initform)))
(progn
(setf (clos::slot-definition-inheritable-initer slot)
(cons initform nil)) ; FIXME
(setf (cdr slot+initff)
`(FUNCTION ,(concat-pnames "DEFAULT-" slotname)
(LAMBDA () ,initform))))))
;; Process the slot-options of this Slot-Specifier:
(do ((slot-arglistr (cddr slotarg) (cddr slot-arglistr)))
((endp slot-arglistr))
(let ((slot-keyword (first slot-arglistr))
(slot-key-value (second slot-arglistr)))
(cond ((eq slot-keyword ':READ-ONLY)
(if slot-key-value
(setf (clos::structure-effective-slot-definition-readonly slot) t)
(if (clos::structure-effective-slot-definition-readonly slot)
(error-of-type 'source-program-error
:form whole-form
:detail subname
(TEXT "~S ~S: The READ-ONLY slot ~S of the included structure ~S must remain READ-ONLY in ~S.")
'defstruct name slotname subname name)
(setf (clos::structure-effective-slot-definition-readonly slot) nil))))
((eq slot-keyword ':TYPE)
(unless
(subtypep
(type-for-discrimination slot-key-value)
(type-for-discrimination (clos:slot-definition-type slot)))
(error-of-type 'source-program-error
:form whole-form
:detail subname
(TEXT "~S ~S: The type ~S of slot ~S should be a subtype of the type defined for the included strucure ~S, namely ~S.")
'defstruct name slot-key-value slotname subname
(clos:slot-definition-type slot)))
(setf (clos:slot-definition-type slot) slot-key-value))
(t (error-of-type 'source-program-error
:form whole-form
:detail slot-keyword
(TEXT "~S ~S: ~S is not a slot option.")
'defstruct name slot-keyword)))))))
(push (cons
(clos::make-instance-<structure-direct-slot-definition>
clos::<structure-direct-slot-definition>
:name slotname
:initform (clos:slot-definition-initform slot)
:initfunction (clos:slot-definition-initfunction slot)
:initargs (clos:slot-definition-initargs slot)
:type (clos:slot-definition-type slot)
'clos::inheritable-initer (clos::slot-definition-inheritable-initer slot)
;; no readers/writers: these are inherited slots
:readers '()
:writers '())
(cdr slot+initff))
directslotlist))))
(dolist (slot+initff slotlist)
(let* ((slot (car slot+initff))
(initfunction (clos:slot-definition-initfunction slot)))
(unless (or (null initfunction) (constant-initfunction-p initfunction))
(let ((variable (gensym)))
(push (cdr slot+initff) slotdefaultfuns)
(push variable slotdefaultvars)
(push slot+initff slotdefaultslots)
(push nil slotdefaultdirectslots)
(setf (cdr slot+initff) variable)))))
(when (eq (first include-option) ':INHERIT)
(setq inherited-slot-count (length slotlist))))
(if (eq name 'STRUCTURE-OBJECT)
(setq names (list name)
namesform `',names)
(setq names (cons name (clos::class-names (get 'STRUCTURE-OBJECT 'CLOS::CLOSCLASS)))
namesbinding
(list
(list
(setq namesform (gensym))
`(CONS ',name (CLOS::CLASS-NAMES (GET 'STRUCTURE-OBJECT 'CLOS::CLOSCLASS))))))))
;; names is the include-nesting, namesform is the form belonging to it.
;; slotlist is the former slot list, reversed.
;; inherited-slot-count is the number of slots, that have to be ignored
;; when the accessors are created.
(when (and named-option ; named structure
(consp type-option) ; of type (VECTOR ...)
;; must be able to contain the name(s):
(not (typep names (type-for-discrimination (second type-option)))))
(error-of-type 'source-program-error
:form whole-form
:detail type-option
(TEXT "~S ~S: structure of type ~S cannot hold the name.")
'defstruct name type-option))
;; layout of the structure:
;; names, poss. include-slots, initial-offset-option times NIL, slots.
;; layout of vector or list:
;; include-part, initial-offset-option times NIL, poss. name, slots.
(setq initial-offset (+ include-skip initial-offset-option))
(unless (eq type-option 'T)
(when named-option
(push
; the type recognition pseudo-slot
(cons
(make-ds-slot nil
'()
initial-offset
(cons `(QUOTE ,name) (make-constant-initfunction name))
'SYMBOL ; type = symbol
T) ; read-only
`(MAKE-CONSTANT-INITFUNCTION ',name))
slotlist)
(incf initial-offset)))
;; the slots are situated behind initial-offset.
;; If type/=T (i.e vector or list) and named-option, the name is situated
;; in Slot number (1- initial-offset).
;; processing the slots:
(let ((offset initial-offset))
(dolist (slotarg slotargs)
(let (slotname
initform
initfunction
initfunctionform)
(if (atom slotarg)
(setq slotname slotarg initform nil)
(setq slotname (first slotarg) initform (second slotarg)))
;; Here we compare slot names through their symbol-names, not through
;; #'eq, because if we have two slots P::X and Q::X, the two accessor
;; functions would have the same name FOO-X.
(when (find (symbol-name slotname) slotlist
:test #'(lambda (name slot+initff)
(let ((slot (car slot+initff)))
(and (or (eq type-option 'T) (ds-real-slot-p slot))
(string= (clos:slot-definition-name slot) name)))))
(error-of-type 'source-program-error
:form whole-form
:detail slotname
(TEXT "~S ~S: There may be only one slot with the name ~S.")
'defstruct name slotname))
(let ((type t) (read-only nil))
(when (consp slotarg)
(do ((slot-arglistr (cddr slotarg) (cddr slot-arglistr)))
((endp slot-arglistr))
(let ((slot-keyword (first slot-arglistr))
(slot-key-value (second slot-arglistr)))
(cond ((eq slot-keyword ':READ-ONLY)
(setq read-only (if slot-key-value t nil)))
((eq slot-keyword ':TYPE) (setq type slot-key-value))
(t (error-of-type 'source-program-error
:form whole-form
:detail slot-keyword
(TEXT "~S ~S: ~S is not a slot option.")
'defstruct name slot-keyword))))))
(if (constantp initform)
(setq initfunction (make-constant-initfunction (eval initform))
initfunctionform `(MAKE-CONSTANT-INITFUNCTION ,initform))
(let ((variable (gensym)))
(push
`(FUNCTION ,(concat-pnames "DEFAULT-" slotname)
(LAMBDA () ,initform))
slotdefaultfuns)
(push variable slotdefaultvars)
(setq initfunction nil ; FIXME
initfunctionform variable)))
(let ((initer (cons initform initfunction))
(initargs (list (symbol-to-keyword slotname)))
(accessorname (ds-accessor-name slotname conc-name-option)))
(when (eq predicate-option accessorname)
(warn
(TEXT "~S ~S: Slot ~S accessor will shadow the predicate ~S.")
'defstruct name slotname predicate-option)
(setq predicate-option nil))
(push (cons
(clos::make-instance-<structure-direct-slot-definition>
clos::<structure-direct-slot-definition>
:name slotname
:initform initform
:initfunction initfunction
:initargs initargs
:type type
'clos::inheritable-initer initer
;; we cannot recover accessor names later
;; because of the :CONC-NAME option
:writers (if read-only '() (list `(SETF ,accessorname)))
:readers (list accessorname))
initfunctionform)
directslotlist)
(push (cons
(make-ds-slot slotname
initargs
offset ; location
initer
;; The following are defstruct specific.
type read-only)
initfunctionform)
slotlist)
(unless (constantp initform)
(push (car slotlist) slotdefaultslots)
(push (car directslotlist) slotdefaultdirectslots)))))
(incf offset))
(setq size offset))
;; size = total length of the structure
(setq slotlist (nreverse slotlist))
(setq directslotlist (nreverse directslotlist))
(setq slotdefaultfuns (nreverse slotdefaultfuns))
(setq slotdefaultvars (nreverse slotdefaultvars))
(setq slotdefaultslots (nreverse slotdefaultslots))
(setq slotdefaultdirectslots (nreverse slotdefaultdirectslots))
;; the slots in slotlist are now sorted in ascending order again.
(setq constructor-forms
(mapcar
#'(lambda (constructor-option)
(if (consp constructor-option)
(ds-make-boa-constructor
constructor-option type-option name namesform size slotlist whole-form)
(progn
(when (null keyword-constructor)
(setq keyword-constructor constructor-option))
(ds-make-keyword-constructor
constructor-option type-option name namesform size
slotlist))))
constructor-option-list))
(setq boa-constructors
(mapcan #'(lambda (constructor-option)
(when (consp constructor-option)
(list (first constructor-option))))
constructor-option-list))
;; constructor-forms = list of forms, that define the constructors.
(mapc #'(lambda (slot+initff directslot+initff)
(let* ((slot (car slot+initff))
(initfunctionform
(ds-initfunction-fetcher name type-option (clos:slot-definition-name slot))))
(setf (cdr slot+initff) initfunctionform)
(when directslot+initff
(setf (cdr directslot+initff) initfunctionform))))
slotdefaultslots slotdefaultdirectslots)
;; now, slotlist contains no more slotdefaultvars.
`(EVAL-WHEN (LOAD COMPILE EVAL)
(LET ()
(LET ,(append namesbinding (mapcar #'list slotdefaultvars slotdefaultfuns))
;; ANSI CL doesn't specify what happens when a structure is
;; redefined with different specification. We do here what DEFCLASS
;; also does: remove the accessory functions defined by the previous
;; specification.
(STRUCTURE-UNDEFINE-ACCESSORIES ',name)
,(if (eq type-option 'T)
`(REMPROP ',name 'DEFSTRUCT-DESCRIPTION)
`(%PUT ',name 'DEFSTRUCT-DESCRIPTION
(VECTOR ',type-option
,size
',keyword-constructor
(LIST ,@(make-load-form-slot-list
slotlist slotdefaultslots slotdefaultvars
'clos::make-load-form-<structure-effective-slot-definition>))
(LIST ,@(make-load-form-slot-list
directslotlist slotdefaultdirectslots
slotdefaultvars
'clos::make-load-form-<structure-direct-slot-definition>))
',boa-constructors
',copier-option
',predicate-option)))
,(if (eq type-option 'T)
`(CLOS::DEFINE-STRUCTURE-CLASS ',name
,namesform
',keyword-constructor
',boa-constructors
',copier-option
',predicate-option
(LIST ,@(make-load-form-slot-list
slotlist slotdefaultslots slotdefaultvars
'clos::make-load-form-<structure-effective-slot-definition>))
(LIST ,@(make-load-form-slot-list
directslotlist slotdefaultdirectslots slotdefaultvars
'clos::make-load-form-<structure-direct-slot-definition>)))
`(CLOS::UNDEFINE-STRUCTURE-CLASS ',name))
,@constructor-forms)
,@(if (and named-option predicate-option)
(ds-make-pred predicate-option type-option name slotlist size))
,@(if copier-option (ds-make-copier copier-option name type-option))
,@(let ((directslotlist (nthcdr inherited-slot-count slotlist)))
`(,@(ds-make-readers name names type-option conc-name-option
directslotlist)
,@(ds-make-writers name names type-option conc-name-option
directslotlist)))
;; see documentation.lisp: we map STRUCTURE to TYPE
(sys::%set-documentation ',name 'TYPE ,docstring)
,@(when (eq type-option 'T)
(list
(if print-object-option
`(CLOS:DEFMETHOD CLOS:PRINT-OBJECT ((STRUCT ,name) STREAM)
(PROGN ,print-object-option))
`(CLOS::DEFSTRUCT-REMOVE-PRINT-OBJECT-METHOD ',name))))
',name))))
;; A kind of Meta-Object Protocol for structures.
;; These function apply to structures of any representation
;; (structure classes as well as subtypes of LIST or VECTOR).
;; This differs from the CLOS MOP
;; 1. in the use of a structure name (symbol) instead of a class,
;; 2. in the different set of available operations: classes in general
;; don't have kconstructors, boa-constructors, copier, predicate,
;; whereas on the other hand structures in general don't have a prototype
;; and finalization.
(defun structure-slots (name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(svref desc *defstruct-description-slots-location*)
(let ((class (find-class name)))
(clos::accessor-typecheck class 'structure-class 'structure-slots)
(clos::class-slots class)))))
#|
(defun (setf structure-slots) (new-value name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(setf (svref desc *defstruct-description-slots-location*) new-value)
(let ((class (find-class name)))
(clos::accessor-typecheck class 'structure-class '(setf structure-slots))
(setf (clos::class-slots class) new-value)))))
|#
(defun structure-direct-slots (name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(svref desc *defstruct-description-direct-slots-location*)
(let ((class (find-class name)))
(clos::accessor-typecheck class 'structure-class 'structure-direct-slots)
(clos::class-direct-slots class)))))
#|
(defun (setf structure-slots) (new-value name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(setf (svref desc *defstruct-description-direct-slots-location*) new-value)
(let ((class (find-class name)))
(clos::accessor-typecheck class 'structure-class '(setf structure-direct-slots))
(setf (clos::class-direct-slots class) new-value)))))
|#
(defun structure-instance-size (name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(svref desc *defstruct-description-size-location*)
(let ((class (find-class name)))
(clos::accessor-typecheck class 'structure-class 'structure-instance-size)
(clos::class-instance-size class)))))
#|
(defun (setf structure-instance-size) (new-value name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(setf (svref desc *defstruct-description-size-location*) new-value)
(let ((class (find-class name)))
(clos::accessor-typecheck class 'structure-class '(setf structure-instance-size))
(setf (clos::class-instance-size class) new-value)))))
|#
(defun structure-keyword-constructor (name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(svref desc *defstruct-description-kconstructor-location*)
(clos::class-kconstructor (find-class name)))))
#|
(defun (setf structure-keyword-constructor) (new-value name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(setf (svref desc *defstruct-description-kconstructor-location*) new-value)
(setf (clos::class-kconstructor (find-class name)) new-value))))
|#
(defun structure-boa-constructors (name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(svref desc *defstruct-description-boa-constructors-location*)
(clos::class-boa-constructors (find-class name)))))
#|
(defun (setf structure-boa-constructors) (new-value name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(setf (svref desc *defstruct-description-boa-constructors-location*) new-value)
(setf (clos::class-boa-constructors (find-class name)) new-value))))
|#
(defun structure-copier (name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(svref desc *defstruct-description-copier-location*)
(clos::class-copier (find-class name)))))
#|
(defun (setf structure-copier) (new-value name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(setf (svref desc *defstruct-description-copier-location*) new-value)
(setf (clos::class-copier (find-class name)) new-value))))
|#
(defun structure-predicate (name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(svref desc *defstruct-description-predicate-location*)
(clos::class-predicate (find-class name)))))
#|
(defun (setf structure-predicate) (new-value name)
(let ((desc (get name 'DEFSTRUCT-DESCRIPTION)))
(if desc
(setf (svref desc *defstruct-description-predicate-location*) new-value)
(setf (clos::class-predicate (find-class name)) new-value))))
|#
(defun structure-undefine-accessories (name) ; ABI
(when (or (get name 'DEFSTRUCT-DESCRIPTION)
(clos::structure-class-p (find-class name nil)))
(macrolet ((fmakunbound-if-present (symbol-form)
`(let ((symbol ,symbol-form))
(when symbol (fmakunbound symbol)))))
(fmakunbound-if-present (structure-keyword-constructor name))
(mapc #'fmakunbound (structure-boa-constructors name))
(fmakunbound-if-present (structure-copier name))
(fmakunbound-if-present (structure-predicate name))
(dolist (slot (structure-direct-slots name))
(mapc #'fmakunbound (clos::slot-definition-readers slot))
(mapc #'fmakunbound (clos::slot-definition-writers slot))))))
| 62,346 | Common Lisp | .lisp | 1,211 | 37.325351 | 152 | 0.551694 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 4999e017b853660e604187bc6aae0ed55e3d796fef4b8eae4214ad6570c82220 | 11,398 | [
-1
] |
11,399 | clos-class0.lisp | ufasoft_lisp/clisp/clos-class0.lisp | ;;;; Common Lisp Object System for CLISP: Classes
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998 - 2004, 2007
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
;; A vector that looks like a class. Needed to make instance_of_stablehash_p
;; work already during bootstrapping.
(defvar *dummy-class*
(vector nil ; inst_class_version
nil ; $hashcode
nil ; $direct-generic-functions
nil ; $direct-methods
nil ; $classname
nil ; $direct-subclasses
nil ; $direct-superclasses
nil ; $all-superclasses
nil ; $precedence-list
nil ; $direct-slots
nil ; $slots
nil ; $slot-location-table
nil ; $direct-default-initargs
nil ; $default-initargs
nil ; $documentation
nil ; $initialized
t ; $subclass-of-stablehash-p
nil ; $generic-accessors
nil ; $direct-accessors
nil ; $valid-initargs
nil ; $instance-size
) )
;; A new class-version is created each time a class is redefined.
;; Used to keep the instances in sync through lazy updates.
;; Note: Why are the shared-slots an element of the class-version, not of the
;; class? Answer: When a class is redefined in such a way that a shared slot
;; becomes local, the update of the instances of its subclasses needs to
;; access the value of the shared slot before the redefinition. This is
;; prepared by class-version-compute-slotlists for each subclass; but when
;; this is run, the pair (class . index) is not sufficient any more to
;; retrieve the value. Hence we use a pair (class-version . index) instead.
;; Then, storing the shared-slots vector in the class-version avoids an
;; indirection: class-version -> shared-slots
;; instead of class-version -> class -> shared-slots.
#|
(defstruct (class-version (:type vector) (:predicate nil) (:copier nil) (:conc-name "CV-"))
newest-class ; the CLASS object describing the newest available version
class ; the CLASS object describing the slots
shared-slots ; simple-vector with the values of all shared slots, or nil
serial ; serial number of this class version
(next nil) ; next class-version, or nil
(slotlists-valid-p nil) ; true if the following fields are already computed
kept-slot-locations ; plist of old and new slot locations of those slots
; that remain local or were shared and become local
added-slots ; list of local slots that are added in the next version
discarded-slots ; list of local slots that are removed or become
; shared in the next version
discarded-slot-locations ; plist of local slots and their old slot locations
; that are removed or become shared in the next version
)
|#
(defun make-class-version (&key (newest-class *dummy-class*)
(class *dummy-class*)
shared-slots serial next
slotlists-valid-p kept-slot-locations
added-slots discarded-slots discarded-slot-locations)
(vector newest-class class shared-slots serial next
slotlists-valid-p kept-slot-locations
added-slots discarded-slots discarded-slot-locations))
(proclaim '(inline cv-newest-class))
(defun cv-newest-class (object) (svref object 0))
(defsetf cv-newest-class (object) (value) `(setf (svref ,object 0) ,value))
(proclaim '(inline cv-class))
(defun cv-class (object) (svref object 1))
(defsetf cv-class (object) (value) `(setf (svref ,object 1) ,value))
(proclaim '(inline cv-shared-slots))
(defun cv-shared-slots (object) (svref object 2))
(defsetf cv-shared-slots (object) (value) `(setf (svref ,object 2) ,value))
(proclaim '(inline cv-serial))
(defun cv-serial (object) (svref object 3))
(defsetf cv-serial (object) (value) `(setf (svref ,object 3) ,value))
(proclaim '(inline cv-next))
(defun cv-next (object) (svref object 4))
(defsetf cv-next (object) (value) `(setf (svref ,object 4) ,value))
(proclaim '(inline cv-slotlists-valid-p))
(defun cv-slotlists-valid-p (object) (svref object 5))
(defsetf cv-slotlists-valid-p (object) (value) `(setf (svref ,object 5) ,value))
(proclaim '(inline cv-kept-slot-locations))
(defun cv-kept-slot-locations (object) (svref object 6))
(defsetf cv-kept-slot-locations (object) (value) `(setf (svref ,object 6) ,value))
(proclaim '(inline cv-added-slots))
(defun cv-added-slots (object) (svref object 7))
(defsetf cv-added-slots (object) (value) `(setf (svref ,object 7) ,value))
(proclaim '(inline cv-discarded-slots))
(defun cv-discarded-slots (object) (svref object 8))
(defsetf cv-discarded-slots (object) (value) `(setf (svref ,object 8) ,value))
(proclaim '(inline cv-discarded-slot-locations))
(defun cv-discarded-slot-locations (object) (svref object 9))
(defsetf cv-discarded-slot-locations (object) (value) `(setf (svref ,object 9) ,value))
(defun class-version-p (object) (and (simple-vector-p object) (eql (length object) 10)))
;; Indicates whether all class-version instances are filled, so that CLASS-OF
;; works.
(defvar *classes-finished* nil)
;; Preliminary.
;; This is needed so that <standard-object> and <structure-object> instances
;; can be printed as long as 1. some class-versions are not yet filled (delayed
;; defclass) and 2. PRINT-OBJECT is not yet defined.
(predefun print-object (object stream)
(declare (ignore object))
(write-string "#<UNKNOWN>" stream))
(defvar *enable-clos-warnings* nil)
(defun clos-warn (type format &rest args)
;; type MUST be a SIMPLE-* condition!
(when *enable-clos-warnings*
(apply 'sys::warn-of-type type format args)))
(defmacro clos-warning (format &rest args)
`(clos-warn 'simple-clos-warning ,format .,args))
| 6,087 | Common Lisp | .lisp | 115 | 46.721739 | 91 | 0.663594 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 4a64fa45ab7d1e7ad91134bf858a057ae332ed60a8a5b8d7d760ad1d6f382619 | 11,399 | [
-1
] |
11,400 | disassem.lisp | ufasoft_lisp/clisp/disassem.lisp | ;; CLISP disassembler
;; Sam Steingold: converted to CLOS 2001-06-16
(in-package "SYS")
(defun orig-fundef (object)
(unless (fboundp object)
(error-of-type 'undefined-function
:name object (TEXT "Undefined function ~S") object))
(let* ((name (get-funname-symbol object))
(def (or (get name 'sys::traced-definition)
(symbol-function name))))
(if (macrop def) (macro-expander def) def)))
(defgeneric disassemble (object &key qualifiers specializers)
(:documentation "disassemble the OBJECT, which should be a function.
if QUALIFIERS or SPECIALIZERS is given, OBJECT should be a generic function.")
#+UNIX (:method ((object string) &rest junk)
(declare (ignore junk))
(disassemble-machine-code
(sys::program-name) (sys::process-id) nil object))
(:method ((object method) &key &allow-other-keys)
(disassemble (method-function object)))
(:method ((object clos::standard-method) &key &allow-other-keys)
(disassemble (or (clos::std-method-fast-function object)
(clos::std-method-function object))))
(:method ((object standard-generic-function) &key qualifiers specializers)
(if (or qualifiers specializers)
(disassemble (find-method object qualifiers
(mapcar #'find-class specializers)))
(sys::disassemble-closure object)))
(:method ((object symbol) &rest opts)
(apply #'disassemble
(if (ext:symbol-macro-expand object)
(coerce `(lambda () ,object) 'function)
(orig-fundef object))
opts))
(:method ((object cons) &rest opts)
(apply #'disassemble
(if (function-name-p object)
(orig-fundef object)
(coerce (if (eq 'lambda (car object))
object `(lambda () ,object))
'function))
opts))
(:method ((object t) &rest opts)
(disassemble (coerce object 'function) opts))
(:method ((object function) &rest junk)
(declare (ignore junk))
#+UNIX (when (sys::code-address-of object)
(return-from disassemble
(disassemble-machine-code
(sys::program-name) (sys::process-id) object
(format nil "0x~X" (sys::code-address-of object)))))
(unless (sys::closurep object)
(warn (TEXT "Cannot disassemble natively compiled function ~S") object)
(return-from disassemble (describe object)))
;; the object is a closure.
(unless (sys::%compiled-function-p object)
(setq object
(compile-lambda (sys::closure-name object) ; name
(sys::%record-ref object 1) ; lambdabody
(sys::%record-ref object 4) ; venv
(sys::%record-ref object 5) ; fenv
(sys::%record-ref object 6) ; benv
(sys::%record-ref object 7) ; genv
(sys::%record-ref object 8) ; denv
nil))) ; no error even on failure
;; object is a compiled closure.
(sys::disassemble-closure object) ; disassemble
nil))
;; Disassemble machine code.
;; Bruno Haible 1995
;; you may customize it to your needs.
#+UNIX
(defun disassemble-machine-code (program-name pid function address)
;; This uses gdb.
(when (shell "gdb --version > /dev/null 2>&1") ; failed
(when function
;; Show at least some basic information about the function.
(describe function))
(fresh-line)
(format t (TEXT "Cannot show machine instructions: gdb not found."))
(return-from disassemble-machine-code nil))
(unless (stringp address) (setq address (format nil "~A" address)))
(let ((tempfilename (format nil "/tmp/gdbcomm~D" pid))
(outfilename (format nil "/tmp/gdbdis~D" pid))
;; On Windows older than Windows XP, we cannot use gdb on the live
;; process, due to a limitation of the Win32 API.
;; See http://sources.redhat.com/ml/cygwin/2003-06/msg00933.html
(use-live-process *disassemble-use-live-process*))
(with-open-file (f tempfilename :direction :output)
;; inhibit pausing after every 23 lines
;; (remove this if your gdb doesn't understand it)
(format f "set height 100000~%")
;; inhibit line breaking (because we filter the lines later)
(format f "set width 1000~%")
(when use-live-process
;; attach to the lisp.run process
(format f "attach ~D~%" pid))
(if (digit-char-p (char address 0))
;; disassemble at numerical address
(format f "disassemble ~A~%" address)
;; disassemble at symbolic address (the "disassemble" command
;; does not always work for symbolic arguments)
(format f "x/10000i ~A~%" address))
(when use-live-process
;; let lisp.run continue
(format f "detach~%"))
;; quit the debugger
(format f "quit~%"))
;; Run gdb, capture only the lines beginning with 0x.
;; Let lisp.run continue (in case the debugger did not detach properly)
(shell
(if use-live-process
(format nil "~A -n -batch -x ~A ~A < /dev/null | grep '^0' > ~A ; kill -CONT ~D"
"gdb" tempfilename program-name outfilename pid)
(format nil "~A -n -batch -x ~A ~A < /dev/null | grep '^0' > ~A"
"gdb" tempfilename program-name outfilename)))
(delete-file tempfilename)
;; Now let the user view the listing.
(if (or (string= (getenv "TERM") "dumb")
(string= (getenv "TERM") "emacs"))
;; do not call a pager when running under Emacs
(with-open-file (in outfilename :direction :input)
(do ((line (read-line in nil nil) (read-line in nil nil)))
((null line))
(format t "~a~%" line)))
(shell (format nil "~A ~A" (or (getenv "PAGER") "more") outfilename)))
(delete-file outfilename))
#| ;; This uses SunOS dbx. (Untested.)
(let ((tempfilename (format nil "/tmp/dbxcomm~D" pid)))
(with-open-file (f tempfilename :direction :output)
(format f "~A/100i~%" address) ; disassemble
(format f "detach~%") ; let lisp.run continue
(format f "quit~%")) ; quit the debugger
(shell (format nil "~A -s ~A ~A ~D" "dbx"
tempfilename program-name pid))) |#
#| ;; This uses AIX dbx. (Untested.)
(let ((tempfilename (format nil "/tmp/dbxcomm~D" pid)))
(with-open-file (f tempfilename :direction :output)
(format f "~A/100i~%" address) ; disassemble
(format f "detach~%") ; let lisp.run continue
(format f "quit~%")) ; quit the debugger
(shell (format nil "~A -c ~A -a ~D ~A" "dbx"
tempfilename pid program-name))) |#
nil)
| 6,838 | Common Lisp | .lisp | 144 | 38.625 | 88 | 0.602392 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 1dc61440da52f77050c2a1303de8f1329714178282fac105b3778facd0b55c59 | 11,400 | [
-1
] |
11,401 | clos-genfun2b.lisp | ufasoft_lisp/clisp/clos-genfun2b.lisp | ;;;; Common Lisp Object System for CLISP
;;;; Generic Functions
;;;; Part 2: Generic function dispatch and execution
;;;; Bruno Haible 21.8.1993 - 2004
;;;; Sam Steingold 1998-2004, 2007-2008, 2010
;;;; German comments translated into English: Stefan Kain 2002-04-08
(in-package "CLOS")
;; ================ Combination of Applicable Methods, Part 3 ================
;;; Calculate the effective method for the given arguments.
;;; It is actually the effective method for all arguments,
;;; for the same EQL and class restrictions as the given arguments,
;;; therefore compute dispatch is already taken care of.
(defun compute-applicable-methods-effective-method (gf &rest args)
(when (safe-gf-undeterminedp gf)
;; gf has uninitialized lambda-list, hence no methods.
(return-from compute-applicable-methods-effective-method
(no-method-caller 'no-applicable-method gf)))
(let ((req-num (sig-req-num (safe-gf-signature gf))))
(if (>= (length args) req-num)
(let ((req-args (subseq args 0 req-num)))
(multiple-value-bind (methods originator)
;; compute-applicable-methods would be sufficient, but the MOP p. 40
;; specifies a two-step process.
(multiple-value-bind (methods certain)
(funcall (cond ((eq gf |#'compute-applicable-methods-using-classes|)
#'compute-applicable-methods-using-classes-<generic-function>)
(t #'compute-applicable-methods-using-classes))
gf (mapcar #'class-of req-args))
(if certain
(values methods 'compute-applicable-methods-using-classes)
(values
(funcall (cond ((or (eq gf |#'compute-applicable-methods|)
(eq gf |#'compute-effective-method|))
#'compute-applicable-methods-<generic-function>)
(t #'compute-applicable-methods))
gf args)
'compute-applicable-methods)))
; Some checks, to guarantee that user-defined methods on
; compute-applicable-methods or compute-applicable-methods-using-classes
; don't break our CLOS.
(unless (proper-list-p methods)
(error (TEXT "Wrong ~S result for generic function ~S: not a proper list: ~S")
originator gf methods))
(dolist (m methods)
(unless (typep-class m <method>)
(error (TEXT "Wrong ~S result for generic function ~S: list element is not a method: ~S")
originator gf m)))
;; Combine the methods to an effective method:
(or (cdr (assoc methods (std-gf-effective-method-cache gf) :test #'equal))
(let ((effective-method
(compute-effective-method-as-function gf methods args)))
(push (cons methods effective-method) (std-gf-effective-method-cache gf))
effective-method))))
(error (TEXT "~S: ~S has ~S required argument~:P, but only ~S arguments were passed to ~S: ~S")
'compute-applicable-methods-effective-method gf req-num (length args)
'compute-applicable-methods-effective-method args))))
;; compute-applicable-methods-effective-method-for-set
;; is a generalization of compute-applicable-methods-effective-method.
;; For each argument position you can specify a set of possible required
;; arguments through one of:
;; (TYPEP class) [covers direct and indirect instances of class],
;; (INSTANCE-OF-P class) [covers only direct instances of class],
;; (EQL object) [covers the given object only].
;; Returns either the best possible effective-method, the gf itself otherwise.
(defun compute-applicable-methods-effective-method-for-set (gf req-arg-specs tentative-args)
(when (safe-gf-undeterminedp gf)
;; gf has uninitialized lambda-list, hence no methods.
(return-from compute-applicable-methods-effective-method-for-set
(no-method-caller 'no-applicable-method gf)))
(let ((req-num (sig-req-num (safe-gf-signature gf))))
(if (and (= (length req-arg-specs) req-num)
(>= (length tentative-args) req-num))
(multiple-value-bind (methods certain)
(compute-applicable-methods-for-set gf req-arg-specs)
(unless certain
(return-from compute-applicable-methods-effective-method-for-set gf))
;; Combine the methods to an effective method:
(or (cdr (assoc methods (std-gf-effective-method-cache gf) :test #'equal))
(let ((effective-method
(compute-effective-method-as-function gf methods tentative-args)))
(push (cons methods effective-method) (std-gf-effective-method-cache gf))
effective-method)))
(error (TEXT "~S: ~S has ~S required argument~:P")
'compute-applicable-methods-effective-method-for-set gf req-num))))
(defun effective-method-function-name (gf methods)
(sys::symbol-suffix
(sys::closure-name gf)
(ext:string-concat "<EMF-" (princ-to-string (length methods)) ">")))
(defun compute-effective-method-as-function (gf methods args)
(when (null methods)
(return-from compute-effective-method-as-function
(no-method-caller 'no-applicable-method gf)))
;; Apply method combination:
(let ((ef-fun (compute-effective-method-as-function-form
gf (safe-gf-method-combination gf) methods args)))
;; Evaluate or compile the resulting form:
(if (constantp ef-fun) ; constant or self-evaluating form?
;; No need to invoke the compiler for a constant form.
ef-fun
;; For a general form:
;; (eval ef-fun) ; interpreted
;; (eval `(LOCALLY (DECLARE (COMPILE)) ,ef-fun)) ; compiled
(eval `(LET ()
(DECLARE (COMPILE ,(effective-method-function-name gf methods))
(INLINE FUNCALL APPLY))
,ef-fun)))))
(defun no-method-caller (no-method-name gf)
#'(lambda (&rest args) (apply no-method-name gf args)))
;; ======================= Computing the Dispatch Code =======================
;; The dispatch-code for generic functions is formed with
;; `(%GENERIC-FUNCTION-LAMBDA ,@lambdabody)
;; - similar to `(FUNCTION (LAMBDA ,@lambdabody)) -.
;; The following must not occur therein:
;; - access to dynamic variables, binding of dynamic variables,
;; - nontrivial BLOCK, RETURN-FROM, TAGBODY, GO constructions,
;; - invocation of global functions, that are not inline,
;; - formation of non-autonomous functions (closures).
;; So the following is necessary:
;; (declare (inline case eql eq typep
;; arrayp bit-vector-p characterp complexp consp floatp
;; functionp hash-table-p integerp listp null numberp
;; packagep pathnamep sys::logical-pathname-p random-state-p
;; rationalp readtablep realp sys::sequencep
;; clos::std-instance-p streamp sys::file-stream-p
;; sys::synonym-stream-p sys::broadcast-stream-p
;; sys::concatenated-stream-p sys::two-way-stream-p
;; sys::echo-stream-p sys::string-stream-p stringp
;; clos::structure-object-p symbolp vectorp
;; class-of cons gethash funcall apply ...
;; ) )
;; Preliminary.
(predefun compute-discriminating-function (gf)
(compute-discriminating-function-<generic-function> gf))
(defun compile-no-jitc (name &optional suffix)
(cons `(COMPILE ,(if suffix (sys::symbol-suffix name suffix) name))
'((OPTIMIZE (SPEED 0) (SPACE 3)))))
(defun compute-discriminating-function-<generic-function> (gf)
(multiple-value-bind (bindings lambdabody) (compute-dispatch gf)
(let ((preliminary
(eval `(LET ,bindings
(DECLARE ,@(safe-gf-declspecs gf)
,@(compile-no-jitc (sys::closure-name gf)
'preliminary))
(%GENERIC-FUNCTION-LAMBDA ,@lambdabody)))))
(assert (<= (sys::%record-length preliminary) 3))
preliminary)))
;; Calculates the dispatch-code of a generic function.
;; It looks as follows:
;; (LAMBDA (variables) ; the required vars separately, everything else with &rest
;; (DECLARE (INLINE ...)) ; everything inline because of %GENERIC-FUNCTION-LAMBDA
;; If-cascades, where EQL-parameter-specializers and most of the
;; builtin-classes are queried online via TYPEP.
;; CLASS-OF is called for the other required-parameters, the results
;; are gathered and inserted into a hash table as index. There, the effective
;; method is located:
;; (LET ((EM (GETHASH (CONS (CLASS-OF ...) ...) ht1)))
;; (WHEN EM (RETURN-FROM block (APPLY EM Arguments))))
;; If that failed:
;; (APPLY 'COMPUTE-AND-ADD-EFFECTIVE-METHOD gf Arguments)
;; )
;; One does not need to write (APPLY ... Arguments),
;; it is done by %GENERIC-FUNCTION-LAMBDA automatically.
(defun compute-dispatch (gf)
(when (safe-gf-undeterminedp gf)
;; gf has uninitialized lambda-list, hence no methods.
(return-from compute-dispatch
(values
'()
`((&REST ,(gensym))
(DECLARE (INLINE FUNCALL))
(FUNCALL 'NO-METHOD-CALLER 'NO-APPLICABLE-METHOD ',gf)))))
(let* ((signature (safe-gf-signature gf))
(req-vars (gensym-list (sig-req-num signature)))
(restp (gf-sig-restp signature))
(rest-var (if restp (gensym)))
(apply-fun (if restp 'APPLY 'FUNCALL))
(apply-args `(,@req-vars ,@(if restp `(,rest-var) '())))
(arg-order (safe-gf-argorder gf))
(methods (safe-gf-methods gf))
(block-name (gensym))
(maybe-no-applicable nil)
(ht-vars '())) ; list of hashtable variables and their inits
;; We do a recursion over the arguments.
(labels
((recursion (remaining-args ; an nthcdr of arg-order
remaining-methods ; sublist of methods
class-of-exprs) ; list of CLASS-OF expressions
(if (null remaining-methods)
(progn
(setq maybe-no-applicable t)
'NIL) ; nothing to do, call NO-APPLICABLE-METHOD later
(if (null remaining-args)
;; All arguments processed.
#|| ; use GETHASH :
(let ((ht-var (gensym))
(n (length class-of-exprs)) ; index with n-tuples
ht-init ; expression for initialization of ht-var
ht-key-binding ; binding of a variable to an n-tuple
em-expr ; expression for looking up the EM
setf-em-expr) ; expression-part for setting the EM
(if (eql n 0)
(setq ht-init 'NIL
ht-key-binding '()
em-expr ht-var
setf-em-expr `(SETQ ,ht-var))
(let ((tuple-var (gensym)))
(setq ht-init
`(MAKE-HASH-TABLE
; :KEY-TYPE '(CONS ... CLASS ...) :VALUE-TYPE 'FUNCTION
:TEST ',(if (eql n 1) 'EXT:STABLEHASH-EQ 'EXT:STABLEHASH-EQUAL)
:WARN-IF-NEEDS-REHASH-AFTER-GC 'T)
ht-key-binding
`((,tuple-var
,(let ((tuple-fun (hash-tuple-function n)))
(if (member '&rest (second tuple-fun))
`(,tuple-fun ,@(reverse class-of-exprs))
;; no &rest -> can optimize
;; (the compiler is not yet too good at that)
(sublis (mapcar #'cons (second tuple-fun) (reverse class-of-exprs))
(third tuple-fun))))))
em-expr
`(GETHASH ,tuple-var ,ht-var)
setf-em-expr
;; `(SETF (GETHASH ,tuple-var ,ht-var)) would also work;
;; but the following spares two temporary variables:
`(SYSTEM::PUTHASH ,tuple-var ,ht-var))))
(push (list ht-var ht-init) ht-vars)
`(LET ,ht-key-binding
(RETURN-FROM ,block-name
(OR ,em-expr
(,@setf-em-expr
(,apply-fun 'COMPUTE-APPLICABLE-METHODS-EFFECTIVE-METHOD
',gf ,@apply-args))))))
|# ; use CLASS-GETHASH and CLASS-TUPLE-GETHASH :
(let ((ht-var (gensym))
(n (length class-of-exprs)) ; index with n-tuples
ht-init ; expression for initialization of ht-var
em-expr ; expression for looking up the EM
setf-em-expr) ; expression-part for setting the EM
(if (eql n 0)
(setq ht-init 'NIL
em-expr ht-var
setf-em-expr `(SETQ ,ht-var))
(setq class-of-exprs
(reverse class-of-exprs)
ht-init
`(MAKE-HASH-TABLE
; :KEY-TYPE '(CONS ... CLASS ...) :VALUE-TYPE 'FUNCTION
:TEST ',(if (eql n 1) 'EXT:STABLEHASH-EQ 'EXT:STABLEHASH-EQUAL)
:WARN-IF-NEEDS-REHASH-AFTER-GC 'T)
em-expr
(if (eql n 1) ; whatever is faster
;; `(GETHASH ,@class-of-exprs ,ht-var) ==
`(CLASS-GETHASH ,ht-var ,(second (first class-of-exprs)))
`(CLASS-TUPLE-GETHASH ,ht-var ,@(mapcar #'second class-of-exprs)))
setf-em-expr
`(SYSTEM::PUTHASH
,(let ((tuple-fun (hash-tuple-function n)))
(if (memq '&rest (second tuple-fun))
`(,tuple-fun ,@class-of-exprs)
;; no &rest -> can optimize
;; (the compiler is not yet too good at that)
(sublis (mapcar #'cons (second tuple-fun) class-of-exprs)
(third tuple-fun))))
,ht-var)))
(push (list ht-var ht-init) ht-vars)
`(RETURN-FROM ,block-name
(OR ,em-expr
(,@setf-em-expr
(,apply-fun 'COMPUTE-APPLICABLE-METHODS-EFFECTIVE-METHOD
',gf ,@apply-args)))))
;; Process next argument:
(let* ((arg-index (first remaining-args))
(arg-var (nth arg-index req-vars))
(eql-cases ; all EQL-specializers for this argument
(remove-duplicates
(mapcar #'eql-specializer-object
(remove-if-not #'eql-specializer-p
(mapcar #'(lambda (m)
(nth arg-index
(safe-method-specializers m gf)))
remaining-methods)))
:test #'eql))
(eql-caselist ; case-list for CASE
(mapcar
#'(lambda (object)
`((,object)
,(recursion
(cdr remaining-args)
(remove-if-not
#'(lambda (m)
(typep object
(nth arg-index
(safe-method-specializers m gf))))
(the list remaining-methods))
class-of-exprs)))
eql-cases)))
;; Until further notice we do not need to consider the
;; EQL-specialized methods anymore.
(setq remaining-methods
(remove-if
#'(lambda (m)
(eql-specializer-p
(nth arg-index (safe-method-specializers m gf))))
(the list remaining-methods)))
((lambda (other-cases)
(if eql-caselist
`(CASE ,arg-var ,@eql-caselist (T ,other-cases))
other-cases))
(let ((classes
(delete <t>
(delete-duplicates
(mapcar #'(lambda (m)
(nth arg-index
(safe-method-specializers m gf)))
remaining-methods)))))
;; If all classes that are to be tested for are
;; built-in-classes, then we will inline the type-dispatch,
;; because in the hierarchy of the built-in-classes
;; (that does not know multiple inheritance except for NULL
;; and VECTOR) all CPLs are consistent.
;; Hence, we can work with
;; (subclassp (class-of obj) class) == (typep obj class)
;; In the other case a hash-table-access is necessary
;; anyway. Then we spare the test for the built-in-
;; classes and include it into the hash-table.
(if (and (every #'bc-p classes)
(<= (length classes) 5)) ; too many cases -> hash
(labels
((built-in-subtree (class remaining-classes remaining-methods)
;; treats the cases, when the argument belongs to
;; the Class class and affiliation to one of the
;; remaining-classes has to be tested.
;; (One can presume that (bc-and class x) /= nil
;; for all x from remaining-classes.)
(if (null remaining-classes)
;; case differentiation is no longer necessary
(recursion
(cdr remaining-args)
(remove-if-not
#'(lambda (m)
(bc-and class
(nth arg-index
(safe-method-specializers m gf))))
(the list remaining-methods))
class-of-exprs)
;; case differentiation via TYPEP
(let ((test-class (first remaining-classes)))
;; better choose test-class maximal:
(loop
(let ((other-class
(find-if
#'(lambda (x)
(and (subclassp test-class x)
(not (eq test-class x))))
(the list remaining-classes))))
(unless other-class (return))
(setq test-class other-class)))
`(IF (TYPEP ,arg-var ',(class-classname test-class))
,(built-in-subtree
(bc-and class test-class) ; /= nil !
(remove 'nil
(mapcar
#'(lambda (x) (bc-and x test-class))
(remove test-class remaining-classes)))
(remove-if-not
#'(lambda (m)
(bc-and
(nth arg-index
(safe-method-specializers m gf))
test-class))
(the list remaining-methods)))
,(built-in-subtree
(bc-and-not class test-class) ; /= nil !
(remove 'nil
(mapcar
#'(lambda (x) (bc-and-not x test-class))
remaining-classes))
(remove-if-not
#'(lambda (m)
(bc-and-not
(nth arg-index
(safe-method-specializers m gf))
test-class))
(the list remaining-methods))))))))
(built-in-subtree <t> classes remaining-methods))
(recursion
(cdr remaining-args)
remaining-methods
(cons `(CLASS-OF ,arg-var) class-of-exprs))))))))))
(let ((form (recursion arg-order methods '())))
(values
;; bindings
(nreverse ht-vars)
;; lambdabody
`((,@req-vars ,@(if restp `(&REST ,rest-var) '()))
(DECLARE
(INLINE
;; for the case differentiations:
CASE EQL EQ TYPEP
;; at the inline-expansion of TYPEP on built-in-classes:
ARRAYP BIT-VECTOR-P CHARACTERP COMPLEXP CONSP FLOATP
FUNCTIONP HASH-TABLE-P INTEGERP LISTP NULL NUMBERP
PACKAGEP PATHNAMEP SYS::LOGICAL-PATHNAME-P RANDOM-STATE-P
RATIONALP READTABLEP REALP SYS::SEQUENCEP
CLOS::STD-INSTANCE-P STREAMP SYS::FILE-STREAM-P
SYS::SYNONYM-STREAM-P SYS::BROADCAST-STREAM-P
SYS::CONCATENATED-STREAM-P SYS::TWO-WAY-STREAM-P
SYS::ECHO-STREAM-P SYS::STRING-STREAM-P STRINGP
CLOS::STRUCTURE-OBJECT-P SYMBOLP VECTORP
;; looking up and calling of the effective method:
CLASS-OF CONS GETHASH CLASS-GETHASH CLASS-TUPLE-GETHASH
SYS::PUTHASH FUNCALL APPLY))
(BLOCK ,block-name
,form
,@(if maybe-no-applicable
`((FUNCALL 'NO-METHOD-CALLER 'NO-APPLICABLE-METHOD
',gf))))))))))
;; Our EQUAL hash-function looks into cons-trees only upto depth 4.
;; A tuple of at most 16 elements can be turned into such a tree.
(defun hash-tuple-function (n) ; n>0
(case n
(1 '(lambda (t1) t1))
(2 '(lambda (t1 t2) (cons t1 t2)))
(3 '(lambda (t1 t2 t3) (cons t1 (cons t2 t3))))
(4 '(lambda (t1 t2 t3 t4) (cons (cons t1 t2) (cons t3 t4))))
(5 '(lambda (t1 t2 t3 t4 t5) (cons (cons t1 t2) (cons t3 (cons t4 t5)))))
(6 '(lambda (t1 t2 t3 t4 t5 t6)
(cons (cons t1 t2) (cons (cons t3 t4) (cons t5 t6)))))
(7 '(lambda (t1 t2 t3 t4 t5 t6 t7)
(cons (cons t1 (cons t2 t3)) (cons (cons t4 t5) (cons t6 t7)))))
(8 '(lambda (t1 t2 t3 t4 t5 t6 t7 t8)
(cons (cons (cons t1 t2) (cons t3 t4))
(cons (cons t5 t6) (cons t7 t8))) ))
(9 '(lambda (t1 t2 t3 t4 t5 t6 t7 t8 t9)
(cons (cons (cons t1 t2) (cons t3 t4))
(cons (cons t5 t6) (cons t7 (cons t8 t9))))))
(10 '(lambda (t1 t2 t3 t4 t5 t6 t7 t8 t9 t10)
(cons (cons (cons t1 t2) (cons t3 t4))
(cons (cons t5 t6) (cons (cons t7 t8) (cons t9 t10))))))
(11 '(lambda (t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11)
(cons (cons (cons t1 t2) (cons t3 t4))
(cons (cons t5 (cons t6 t7))
(cons (cons t8 t9) (cons t10 t11))))))
(12 '(lambda (t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12)
(cons (cons (cons t1 t2) (cons t3 t4))
(cons (cons (cons t5 t6) (cons t7 t8))
(cons (cons t9 t10) (cons t11 t12))))))
(13 '(lambda (t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12 t13)
(cons (cons (cons t1 t2) (cons t3 (cons t4 t5)))
(cons (cons (cons t6 t7) (cons t8 t9))
(cons (cons t10 t11) (cons t12 t13))))))
(14 '(lambda (t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12 t13 t14)
(cons (cons (cons t1 t2) (cons (cons t3 t4) (cons t5 t6)))
(cons (cons (cons t7 t8) (cons t9 t10))
(cons (cons t11 t12) (cons t13 t14))))))
(15 '(lambda (t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12 t13 t14 t15)
(cons (cons (cons t1 (cons t2 t3)) (cons (cons t4 t5) (cons t6 t7)))
(cons (cons (cons t8 t9) (cons t10 t11))
(cons (cons t12 t13) (cons t14 t15))))))
(16 '(lambda (t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12 t13 t14 t15 t16)
(cons (cons (cons (cons t1 t2) (cons t3 t4))
(cons (cons t5 t6) (cons t7 t8)))
(cons (cons (cons t9 t10) (cons t11 t12))
(cons (cons t13 t14) (cons t15 t16))))))
(t '(lambda (t1 t2 t3 t4 t5 t6 t7 t8 t9 t10 t11 t12 t13 t14 &rest more-t)
(cons (cons (cons (cons t1 t2) (cons t3 t4))
(cons (cons t5 t6) (cons t7 t8)))
(cons (cons (cons t9 t10) (cons t11 t12))
(cons (cons t13 t14) more-t)))))))
;; ===================== Generic Function Initialization =====================
;; Checks a generic-function lambda-list and converts it to a signature.
;; Reports errors through errfunc (a function taking a detail object, an
;; error format string and format string arguments).
(defun generic-function-lambda-list-to-signature (lambdalist errfunc)
(multiple-value-bind (reqvars optvars rest keyp keywords keyvars allowp)
(sys::analyze-generic-function-lambdalist lambdalist errfunc)
(declare (ignore keyvars))
(let ((reqnum (length reqvars))
(optnum (length optvars))
(restp (or (not (eql rest 0)) keyp))) ; &key implies &rest
(make-signature :req-num reqnum :opt-num optnum
:rest-p restp :keys-p keyp
:keywords keywords :allow-p allowp))))
; n --> list (0 ... n-1)
(defun countup (n)
(do* ((count n (1- count))
(l '() (cons count l)))
((eql count 0) l)))
;; Checks an argument-precedence-order list and converts it to a list of
;; indices. reqvars is the required-variables portion of the lambda-list.
;; Reports errors through errfunc (a function taking a detail object, an
;; error format string and format string arguments).
(defun generic-function-argument-precedence-order-to-argorder (argument-precedence-order reqnum reqvars errfunc)
(let ((indices
(mapcar #'(lambda (x)
(or (position x reqvars)
(funcall errfunc x
(TEXT "~S is not one of the required parameters: ~S")
x argument-precedence-order)))
argument-precedence-order)))
;; Is argument-precedence-order a permutation of reqvars?
;; In other words: Is the mapping
;; argument-precedence-order --> reqvars
;; resp. indices --> {0, ..., reqnum-1}
;; bijective?
(unless (or (<= (length indices) 1) (apply #'/= indices)) ; injective?
(funcall errfunc argument-precedence-order
(TEXT "Some variable occurs twice in ~S")
argument-precedence-order))
(unless (eql (length indices) reqnum) ; surjective?
(let ((missing (set-difference reqvars argument-precedence-order)))
(funcall errfunc missing
(TEXT "The variables ~S are missing in ~S")
missing argument-precedence-order)))
indices))
;; Checks a generic-function lambda-list and argument-precedence-order.
;; Returns three values:
;; 1. the lambda-list's signature,
;; 2. the argument-precedence-order, as a list of variables,
;; 3. the argument-precedence-order, as a list of numbers from 0 to reqnum-1.
;; Reports errors through errfunc (a function taking a detail object, an
;; error format string and format string arguments).
(defun check-gf-lambdalist+argorder (lambdalist argument-precedence-order argument-precedence-order-p errfunc)
;; Check the lambda-list.
(let* ((signature
(generic-function-lambda-list-to-signature lambdalist
#'(lambda (lalist detail errorstring &rest arguments)
(funcall errfunc lalist detail
(TEXT "Invalid generic function lambda-list: ~A")
(apply #'format nil errorstring arguments)))))
(reqnum (sig-req-num signature))
(reqvars (subseq lambdalist 0 reqnum)))
(if argument-precedence-order-p
;; Check the argument-precedence-order.
(progn
(unless (proper-list-p argument-precedence-order)
(funcall errfunc argument-precedence-order
(TEXT "The ~S argument should be a proper list, not ~S")
':argument-precedence-order argument-precedence-order))
(let ((indices
(generic-function-argument-precedence-order-to-argorder
argument-precedence-order reqnum reqvars
#'(lambda (detail errorstring &rest arguments)
(funcall errfunc detail
(TEXT "Incorrect ~S argument: ~A")
':argument-precedence-order
(apply #'format nil errorstring arguments))))))
(values signature argument-precedence-order indices)))
(values signature reqvars (countup reqnum)))))
;; Checks a generic-function declspecs list.
(defun check-gf-declspecs (declspecs keyword errfunc)
(unless (proper-list-p declspecs)
(funcall errfunc (TEXT "The ~S argument should be a proper list, not ~S")
keyword declspecs))
(dolist (declspec declspecs)
(unless (and (consp declspec) (eq (first declspec) 'OPTIMIZE))
(funcall errfunc (TEXT "In the ~S argument, only ~S declarations are permitted, not ~S")
keyword 'optimize declspec))))
;; CLtL2 28.1.6.4., ANSI CL 7.6.4. Congruent Lambda-lists
(defun check-signature-congruence (gf method
&optional (gf-sign (safe-gf-signature gf))
(m-sign (method-signature method)))
(unless (= (sig-req-num m-sign) (sig-req-num gf-sign))
(error-of-type 'error
(TEXT "~S has ~D, but ~S has ~D required parameter~:P")
method (sig-req-num m-sign) gf (sig-req-num gf-sign)))
(unless (= (sig-opt-num m-sign) (sig-opt-num gf-sign))
(error-of-type 'error
(TEXT "~S has ~D, but ~S has ~D optional parameter~:P")
method (sig-opt-num m-sign) gf (sig-opt-num gf-sign)))
(when (and (sig-rest-p m-sign) (not (sig-rest-p gf-sign)))
(error-of-type 'error
(TEXT "~S accepts &REST or &KEY, but ~S does not.")
method gf))
(when (and (sig-rest-p gf-sign) (not (sig-rest-p m-sign)))
(error-of-type 'error
(TEXT "~S accepts &REST or &KEY, but ~S does not.")
gf method))
(when (sig-keys-p gf-sign) ; gf has keywords?
;; yes ==> method must accept it
(unless (if (sig-keys-p m-sign)
(or (sig-allow-p m-sign) ; keywords match
(subsetp (sig-keywords gf-sign) (sig-keywords m-sign)))
(sig-rest-p m-sign)) ; method must have &rest!
(error-of-type 'error
(TEXT "~S does not accept the keywords ~S of ~S")
method (sig-keywords gf-sign) gf))))
;; CLtL2 28.1.7.2., 28.1.7.4., ANSI CL 7.6.6.2., 7.6.6.4. Method qualifiers
(defun check-method-qualifiers (gf method
&optional (method-combination (safe-gf-method-combination gf)))
(funcall (method-combination-check-method-qualifiers method-combination)
gf method-combination method))
(defun invalid-method-qualifiers-error (gf method) ; ABI
(error-of-type 'program-error
(TEXT "~S method combination, used by ~S, does not allow the method qualifiers ~:S: ~S")
(method-combination-name (safe-gf-method-combination gf)) gf
(method-qualifiers method) method))
;; Initialization of a <standard-generic-function> instance.
(defun shared-initialize-<standard-generic-function> (gf situation &rest args
&key (name nil name-p)
(lambda-list nil lambda-list-p)
(argument-precedence-order nil argument-precedence-order-p)
(method-class nil method-class-p)
(method-combination nil method-combination-p)
(documentation nil documentation-p)
(declarations nil declarations-p)
(declare nil declare-p)
&allow-other-keys
&aux signature argorder)
(declare (ignore name name-p))
(apply #'shared-initialize-<generic-function> gf situation args)
(when (eq situation 't)
(setf (std-gf-initialized gf) nil))
(when (and argument-precedence-order-p (not lambda-list-p))
(error (TEXT "(~S ~S) for generic function ~S: ~S argument specified without a ~S argument.")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'standard-generic-function (funcallable-name gf)
':argument-precedence-order ':lambda-list))
(when lambda-list-p
; Check the lambda-list and argument-precedence-order.
(multiple-value-setq (signature argument-precedence-order argorder)
(check-gf-lambdalist+argorder lambda-list
argument-precedence-order argument-precedence-order-p
#'(lambda (detail errorstring &rest arguments)
(declare (ignore detail))
(error (TEXT "(~S ~S) for generic function ~S: ~A")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'standard-generic-function (funcallable-name gf)
(apply #'format nil errorstring arguments)))))
(unless (eq situation 't)
;; ANSI CL description of ENSURE-GENERIC-FUNCTION says "If ... the new
;; value [for the :lambda-list argument] is congruent with the lambda
;; lists of all existing methods or there are no methods, the value is
;; changed; otherwise an error is signaled.
(unless (or (safe-gf-undeterminedp gf)
(equalp signature (safe-gf-signature gf)))
(dolist (method (safe-gf-methods gf))
(check-signature-congruence gf method signature)))))
(when (or (eq situation 't) method-class-p)
; Check the method-class.
(unless method-class-p
(setq method-class <standard-method>))
(unless (defined-class-p method-class)
(error (TEXT "(~S ~S) for generic function ~S: The ~S argument should be a class, not ~S")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'standard-generic-function (funcallable-name gf)
':method-class method-class))
(unless (subclassp method-class <method>)
(error (TEXT "(~S ~S) for generic function ~S: The ~S argument should be a subclass of ~S, not ~S")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'standard-generic-function (funcallable-name gf)
':method-class 'method method-class)))
(when (or (eq situation 't) method-combination-p)
; Check the method-combination.
#| ; Not sure whether giving an error here is appropriate.
(unless method-combination-p
(error (TEXT "(~S ~S) for generic function ~S: Missing ~S argument.")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'standard-generic-function (funcallable-name gf)
':method-combination))
|#
(unless method-combination-p
(setq method-combination
(get-method-combination 'STANDARD '(initialize-instance standard-generic-function))))
(unless (typep-class method-combination <method-combination>)
(error (TEXT "(~S ~S) for generic function ~S: The ~S argument should be a ~S object, not ~S")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'standard-generic-function (funcallable-name gf)
':method-combination 'method-combination method-combination))
(unless (eq situation 't)
(unless (eq method-combination (safe-gf-method-combination gf))
(dolist (method (safe-gf-methods gf))
(check-method-qualifiers gf method method-combination)))))
(when (or (eq situation 't) documentation-p)
; Check the documentation.
(unless (or (null documentation) (stringp documentation))
(error (TEXT "(~S ~S) for generic function ~S: The ~S argument should be a string or NIL, not ~S")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'standard-generic-function (funcallable-name gf) ':documentation documentation)))
(when (or (eq situation 't) declarations-p declare-p)
; Check the declarations.
; ANSI CL specifies the keyword :DECLARE for ensure-generic-function, but the
; MOP p. 50 specifies the keyword :DECLARATIONS for ensure-generic-function-using-class.
(when (and declarations-p declare-p)
(error (TEXT "(~S ~S) for generic function ~S: The ~S and ~S arguments cannot be specified together.")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'standard-generic-function (funcallable-name gf)
':declarations ':declare))
(let ((declspecs (if declare-p declare declarations)))
(check-gf-declspecs declspecs (if declare-p ':declare ':declarations)
#'(lambda (errorstring &rest arguments)
(error (TEXT "(~S ~S) for generic function ~S: ~A")
(if (eq situation 't) 'initialize-instance 'shared-initialize)
'standard-generic-function (funcallable-name gf)
(apply #'format nil errorstring arguments))))))
; Fill the slots.
(when lambda-list-p
(setf (std-gf-lambda-list gf) lambda-list)
(setf (std-gf-signature gf) signature)
(setf (std-gf-argorder gf) argorder))
(when (or (eq situation 't) method-class-p)
(setf (std-gf-default-method-class gf) method-class))
(when (or (eq situation 't) method-combination-p)
(setf (std-gf-method-combination gf) method-combination))
(when (or (eq situation 't) documentation-p)
(setf (std-gf-documentation gf) documentation))
(when (or (eq situation 't) declarations-p declare-p)
(setf (std-gf-declspecs gf) (if declare-p declare declarations)))
(when (eq situation 't)
(setf (std-gf-methods gf) '()))
(when (or (eq situation 't)
; When reinitializing a generic-function, we need to clear the
; caches (cf. MOP p. 40 compute-discriminating-function item (ii)).
; But we don't need to do it if we know that all that has changed
; are the name, method-class, documentation, declarations, declare
; initargs. But other, possibly user-defined, initargs can have an
; effect on the discriminating function.
(do ((l args (cddr l)))
((endp l) nil)
(unless (memq (car l) '(:name :method-class :documentation :declarations :declare))
(return t))))
(setf (std-gf-effective-method-cache gf) '()))
; Now allow the user to call the generic-function-xxx accessor functions.
(setf (std-gf-initialized gf) t)
; And allow the user to call gf.
(finalize-fast-gf gf)
gf)
;; ======================== The Set of Methods of a GF ========================
;; Cruel hack (CLtL2 28.1.9.2., ANSI CL 7.1.2.):
;; - MAKE-INSTANCE must be informed about the methods of ALLOCATE-INSTANCE,
;; INITIALIZE-INSTANCE and SHARED-INITIALIZE.
;; - INITIALIZE-INSTANCE must be informed about the methods of
;; INITIALIZE-INSTANCE and SHARED-INITIALIZE.
;; - REINITIALIZE-INSTANCE must be informed about the methods of
;; REINITIALIZE-INSTANCE and SHARED-INITIALIZE.
;; - UPDATE-INSTANCE-FOR-REDEFINED-CLASS must be informed about the methods of
;; UPDATE-INSTANCE-FOR-REDEFINED-CLASS and SHARED-INITIALIZE.
;; - UPDATE-INSTANCE-FOR-DIFFERENT-CLASS must be informed about the methods of
;; UPDATE-INSTANCE-FOR-DIFFERENT-CLASS and SHARED-INITIALIZE.
(defvar |#'allocate-instance| nil)
(defvar |#'initialize-instance| nil)
(defvar |#'reinitialize-instance| nil)
(defvar |#'update-instance-for-redefined-class| nil)
(defvar |#'update-instance-for-different-class| nil)
(defvar |#'shared-initialize| nil)
;; Optimization of SLOT-VALUE and its brothers.
(defvar |#'slot-value-using-class| nil)
(defvar |#'(setf slot-value-using-class)| nil)
(defvar |#'slot-boundp-using-class| nil)
(defvar |#'slot-makunbound-using-class| nil)
;; More general notification.
(defun map-dependents-<generic-function> (gf function)
(dolist (dependent (gf-listeners gf))
(funcall function dependent)))
;; CLtL2 28.1.6.3., ANSI CL 7.6.3.
;; Agreement on Parameter Specializers and Qualifiers
(defun methods-agree-p (method1 method2)
(and (equal (method-qualifiers method1) (method-qualifiers method2))
(specializers-agree-p (method-specializers method1)
(method-specializers method2))))
;; MOP p. 62 says that the lambda-list of a generic function may become
;; determined only at the moment when the first method is added.
(defun gf-lambdalist-from-first-method (m-lambdalist m-signature)
(let* ((req-num (sig-req-num m-signature))
(opt-num (sig-opt-num m-signature))
(rest-p (sig-rest-p m-signature)))
(values
;; The inferred lambda-list:
(append (subseq m-lambdalist 0 req-num)
(if (> opt-num 0)
(cons '&OPTIONAL
(mapcar #'(lambda (item) (if (consp item) (first item) item))
(subseq m-lambdalist (+ req-num 1) (+ req-num 1 opt-num))))
'())
(if rest-p
(list '&REST
(let ((i (position '&REST m-lambdalist)))
(if i (nth (+ i 1) m-lambdalist) (gensym))))
'()))
;; Its corresponding signature:
(make-signature :req-num req-num :opt-num opt-num :rest-p rest-p))))
;; Add a method to a generic function.
(defun std-add-method (gf method)
(if (safe-gf-undeterminedp gf)
;; The first added method determines the generic-function's signature.
(shared-initialize-<standard-generic-function> gf nil
:lambda-list (gf-lambdalist-from-first-method (method-lambda-list method)
(method-signature method)))
(check-signature-congruence gf method))
(when (method-generic-function method)
(error-of-type 'error
"~S: ~S already belongs to ~S, cannot also add it to ~S"
'std-add-method method (method-generic-function method) gf))
(check-method-qualifiers gf method)
;; The method is checked. Now add it:
(warn-if-gf-already-called gf)
(let ((old-method (find method (safe-gf-methods gf) :test #'methods-agree-p)))
(when old-method
(clos-warn 'simple-gf-replacing-method-warning
(TEXT "Replacing method ~S in ~S") old-method gf)
;; Call remove-method without warnings.
(let ((*dynamically-modifiable-generic-function-names*
(cons (sys::closure-name gf) *dynamically-modifiable-generic-function-names*)))
(remove-method gf old-method))
;; Ensure that remove-method really has removed the method.
(when (memq method (safe-gf-methods gf))
(error (TEXT "Wrong ~S behaviour: ~S has not been removed from ~S")
'remove-method old-method gf))))
(cond ((eq gf |#'allocate-instance|) (note-ai-change method))
((eq gf |#'initialize-instance|) (note-ii-change method))
((eq gf |#'reinitialize-instance|) (note-ri-change method))
((eq gf |#'update-instance-for-redefined-class|) (note-uirc-change method))
((eq gf |#'update-instance-for-different-class|) (note-uidc-change method))
((eq gf |#'shared-initialize|) (note-si-change method)))
;; Step 1: Add method to the set.
(setf (std-gf-methods gf) (cons method (safe-gf-methods gf))
(method-generic-function method) gf)
;; Step 2: Call add-direct-method for each specializer.
(dolist (specializer (method-specializers method))
(add-direct-method specializer method))
;; Step 3: Clear the effective method cache and the discriminating function.
;; (Cf. MOP p. 41 compute-discriminating-function item (iii).)
(setf (std-gf-effective-method-cache gf) '())
(finalize-fast-gf gf)
;; Step 4: Update the dependents.
(cond ((eq gf |#'slot-value-using-class|) (note-svuc-change method))
((eq gf |#'(setf slot-value-using-class)|) (note-ssvuc-change method))
((eq gf |#'slot-boundp-using-class|) (note-sbuc-change method))
((eq gf |#'slot-makunbound-using-class|) (note-smuc-change method)))
(funcall (if *classes-finished*
#'map-dependents
#'map-dependents-<generic-function>)
gf
#'(lambda (dependent)
(update-dependent gf dependent 'add-method method)))
;; It's not worth updating the seclass of a generic function, since 1. in
;; most cases, it can signal a NO-APPLICABLE-METHOD error and thus has
;; *seclass-dirty*, 2. the compiler must assume that the seclass doesn't
;; change over time, which we cannot guarantee, since generic functions are
;; not sealed.
gf)
;; Preliminary.
(predefun add-method (gf method)
(std-add-method gf method))
;; Remove a method from a generic function.
(defun std-remove-method (gf method)
(let ((old-method (find method (safe-gf-methods gf))))
(when old-method
(when (need-gf-already-called-warning-p gf)
(gf-already-called-warning gf)
(clos-warning (TEXT "Removing method ~S in ~S") old-method gf))
(cond ((eq gf |#'allocate-instance|) (note-ai-change method))
((eq gf |#'initialize-instance|) (note-ii-change method))
((eq gf |#'reinitialize-instance|) (note-ri-change method))
((eq gf |#'update-instance-for-redefined-class|) (note-uirc-change method))
((eq gf |#'update-instance-for-different-class|) (note-uidc-change method))
((eq gf |#'shared-initialize|) (note-si-change method)))
;; Step 1: Remove method from the set.
(setf (std-gf-methods gf) (remove old-method (safe-gf-methods gf))
(method-generic-function old-method) nil
(method-from-defgeneric old-method) nil)
;; Step 2: Call remove-direct-method for each specializer.
(dolist (specializer (method-specializers method))
(remove-direct-method specializer method))
;; Step 3: Clear the effective method cache and the discriminating function.
;; (Cf. MOP p. 41 compute-discriminating-function item (iii).)
(setf (std-gf-effective-method-cache gf) '())
(finalize-fast-gf gf)
;; Step 4: Update the dependents.
(cond ((eq gf |#'slot-value-using-class|) (note-svuc-change method))
((eq gf |#'(setf slot-value-using-class)|) (note-ssvuc-change method))
((eq gf |#'slot-boundp-using-class|) (note-sbuc-change method))
((eq gf |#'slot-makunbound-using-class|) (note-smuc-change method)))
(funcall (if *classes-finished*
#'map-dependents
#'map-dependents-<generic-function>)
gf
#'(lambda (dependent)
(update-dependent gf dependent 'remove-method method)))))
gf)
;; Preliminary.
(predefun remove-method (gf method)
(std-remove-method gf method))
;; Find a method in a generic function.
(defun std-find-method (gf qualifiers specializers &optional (errorp t))
(unless (listp specializers)
(error-of-type 'error
(TEXT "~S: the specializers argument is not a list: ~S")
'find-method specializers))
(if (safe-gf-undeterminedp gf)
;; Signature not known yet, hence no methods installed.
(assert (null (safe-gf-methods gf)))
(progn
(let ((n (sig-req-num (safe-gf-signature gf))))
(unless (eql (length specializers) n)
(error-of-type 'error
(TEXT "~S: the specializers argument has length ~D, but ~S has ~D required parameter~:P")
'find-method (length specializers) gf n))
; Convert (EQL object) -> #<EQL-SPECIALIZER object>:
(setq specializers
(mapcar #'(lambda (specializer)
(if (and (consp specializer) (eq (car specializer) 'EQL)
(consp (cdr specializer)) (null (cddr specializer)))
(intern-eql-specializer (second specializer))
specializer))
specializers)))
;; Simulate
;; (find hypothetical-method (safe-gf-methods gf) :test #'methods-agree-p)
;; cf. methods-agree-p
(dolist (method (safe-gf-methods gf))
(when (and (equal (method-qualifiers method) qualifiers)
(specializers-agree-p (method-specializers method)
specializers))
(return-from std-find-method method)))))
(if errorp
(error-of-type 'error
(TEXT "~S has no method with qualifiers ~:S and specializers ~:S")
gf qualifiers specializers)
nil))
;; ===================== Generic Function Initialization =====================
(defun initialize-instance-<generic-function> (gf &rest args
&key name
lambda-list
argument-precedence-order
method-class
method-combination
documentation
declarations
declare
((methods methods) nil methods-p) ; from DEFGENERIC
&allow-other-keys)
(declare (ignore name lambda-list argument-precedence-order method-class
method-combination documentation declarations declare))
(if *classes-finished*
(apply #'%initialize-instance gf args) ; == (call-next-method)
;; During bootstrapping, only <standard-generic-function> instances are used.
(apply #'shared-initialize-<standard-generic-function> gf 't args))
(when methods-p
;; When invoked from DEFGENERIC: Install the defgeneric-originated methods.
(dolist (method methods) (add-method gf method)))
gf)
(defun reinitialize-instance-<generic-function> (gf &rest args
&key name
lambda-list
argument-precedence-order
method-class
method-combination
documentation
declarations
declare
((methods methods) nil methods-p) ; from DEFGENERIC
&allow-other-keys)
(declare (ignore name lambda-list argument-precedence-order method-class
method-combination documentation declarations declare))
(when methods-p
;; When invoked from DEFGENERIC:
;; Remove the old defgeneric-originated methods. Instead of calling
;; std-remove-method on each such method, while inhibiting warnings,
;; we can just as well remove the methods directly.
(setf (std-gf-methods gf)
(remove-if #'(lambda (method)
(when (method-from-defgeneric method)
;; Step 1: Remove method from the set.
(setf (method-generic-function method) nil)
(setf (method-from-defgeneric method) nil)
;; Step 2: Call remove-direct-method for each specializer.
(dolist (specializer (method-specializers method))
(remove-direct-method specializer method))
t))
(safe-gf-methods gf))))
(apply (cond ((eq (class-of gf) <standard-generic-function>)
#'shared-initialize-<standard-generic-function>)
(t #'shared-initialize))
gf nil args)
(when methods-p
;; When invoked from DEFGENERIC: Install the defgeneric-originated
;; methods.
(dolist (method methods) (add-method gf method)))
;; Notification of listeners:
(map-dependents gf
#'(lambda (dependent)
(apply #'update-dependent gf dependent args)))
gf)
(defun make-instance-<standard-generic-function> (class &rest args
&key name
lambda-list
argument-precedence-order
method-class
method-combination
documentation
declarations
declare
&allow-other-keys)
;; class = <standard-generic-function>
;; Don't add functionality here! This is a preliminary definition that is
;; replaced with #'make-instance later.
(declare (ignore class name lambda-list argument-precedence-order method-class
method-combination documentation declarations declare))
(let ((gf (%allocate-instance <standard-generic-function>)))
(apply #'initialize-instance-<generic-function> gf args)))
(defun allocate-generic-function-instance (class &rest args
&key &allow-other-keys)
;; During bootstrapping, only <standard-generic-function> instances are used.
(declare (ignore class args))
(%allocate-instance <standard-generic-function>))
(defun make-generic-function-instance (class &rest args ; ABI
&key &allow-other-keys)
;; During bootstrapping, only <standard-generic-function> instances are used.
(apply #'make-instance-<standard-generic-function> class args))
;; Returns an instance of the given generic-function class that is initialized
;; with just the name, without calling user-defined initialize-instance methods.
(defun make-generic-function-prototype (class &rest args &key name) ; ABI
(declare (ignore name))
(let ((instance (allocate-generic-function-instance class)))
(apply #'shared-initialize-<generic-function> instance 't args)))
;; ======================= Installing the Dispatch Code =======================
#||
(defun make-gf (generic-function-class name lambdabody lambda-list argument-precedence-order method-combination user-defined-args methods)
(let ((final
(apply #'make-generic-function-instance generic-function-class
:name name
:lambda-list lambda-list
:argument-precedence-order argument-precedence-order
:method-combination method-combination
(mapcan #'(lambda (option) (list (first option) (rest option)))
user-defined-args)))
(preliminary
(eval `(LET ()
(DECLARE ,@(compile-no-jitc name))
(%GENERIC-FUNCTION-LAMBDA ,@lambdabody)))))
(assert (<= (sys::%record-length preliminary) 3))
(set-funcallable-instance-function final preliminary)
(setf (std-gf-methods final) methods)
final))
||#
#|| ;; Generic functions with primitive dispatch:
(defun make-slow-gf (generic-function-class name lambda-list argument-precedence-order method-class declspecs documentation user-defined-args methods)
(let* ((final
(apply #'make-generic-function-instance generic-function-class
:name name
:lambda-list lambda-list
:argument-precedence-order argument-precedence-order
:method-class method-class
:declarations declspecs
:documentation documentation
(mapcan #'(lambda (option) (list (first option) (rest option)))
user-defined-args)))
(preliminary
(eval `(LET ((GF ',final))
(DECLARE ,@(compile-no-jitc name))
(%GENERIC-FUNCTION-LAMBDA (&REST ARGS)
(DECLARE (INLINE APPLY))
(APPLY 'SLOW-FUNCALL-GF GF ARGS))))))
(assert (<= (sys::%record-length preliminary) 3))
(set-funcallable-instance-function final preliminary)
(setf (std-gf-methods final) methods)
final))
(flet ((prototype-factory (gf)
(declare ,@(compile-no-jitc (sys::closure-name gf)))
(%generic-function-lambda (&rest args)
(declare (inline apply))
(apply 'slow-funcall-gf gf args))))
(assert (<= (sys::%record-length (prototype-factory 'dummy)) 3))
(let ((prototype-code (sys::closure-codevec (prototype-factory 'dummy))))
(defun finalize-slow-gf (gf)
(set-funcallable-instance-function gf (prototype-factory gf)))
(defun gf-never-called-p (gf)
(eq (sys::closure-codevec gf) prototype-code))
(defun warn-if-gf-already-called (gf) )))
;; Call of a generic function.
;; Without any caching: Compute the effective method at each call.
(defun slow-funcall-gf (gf &rest args)
(unless (>= (length args) (sig-req-num (safe-gf-signature gf)))
(error-of-type 'program-error
(TEXT "Too few arguments to ~S: ~S")
gf args))
;; Determine the effective method.
;; Return the effective method. It will then be applied to the arguments.
(apply #'compute-applicable-methods-effective-method gf args))
||#
(defun gf-sig-restp (sig)
(or (sig-rest-p sig) (> (sig-opt-num sig) 0)))
;; Generic functions with optimized dispatch:
;; First optimization: When the generic function is called, the required
;; arguments are not consed up into an argument list, but rather passed on
;; the stack.
(let ((prototype-factory-table
(make-hash-table :key-type '(cons fixnum boolean) :value-type '(cons function (simple-array (unsigned-byte 8) (*)))
:test 'ext:stablehash-equal :warn-if-needs-rehash-after-gc t))
(uninitialized-prototype-factory
(eval `#'(LAMBDA (GF)
(DECLARE ,@(compile-no-jitc 'uninitialized-prototype-factory))
(%GENERIC-FUNCTION-LAMBDA (&REST ARGS)
(DECLARE (INLINE FUNCALL) (IGNORE ARGS))
(FUNCALL 'NO-METHOD-CALLER 'NO-APPLICABLE-METHOD GF))))))
(defun finalize-fast-gf (gf)
(let ((prototype-factory
(if (safe-gf-undeterminedp gf)
;; gf has uninitialized lambda-list, hence no methods.
uninitialized-prototype-factory
(let* ((signature (safe-gf-signature gf))
(reqnum (sig-req-num signature))
(restp (gf-sig-restp signature))
(hash-key (cons reqnum restp)))
(car
(or (gethash hash-key prototype-factory-table)
(setf (gethash hash-key prototype-factory-table)
(let* ((reqvars (gensym-list reqnum))
(prototype-factory
(eval `#'(LAMBDA (GF)
(DECLARE ,@(compile-no-jitc (sys::closure-name gf) 'prototype-factory))
(%GENERIC-FUNCTION-LAMBDA
(,@reqvars ,@(if restp '(&REST ARGS) '()))
(DECLARE (INLINE FUNCALL) (IGNORABLE ,@reqvars ,@(if restp '(ARGS) '())))
(FUNCALL 'INITIAL-FUNCALL-GF GF)))))
(dummy-f (funcall prototype-factory 'dummy)))
(assert (<= (sys::%record-length dummy-f) 3))
(cons prototype-factory
(sys::closure-codevec dummy-f))))))))))
(set-funcallable-instance-function gf (funcall prototype-factory gf))))
(defun gf-never-called-p (gf)
(or (safe-gf-undeterminedp gf)
(let* ((signature (safe-gf-signature gf))
(reqnum (sig-req-num signature))
(restp (gf-sig-restp signature))
(hash-key (cons reqnum restp))
(prototype-factory+codevec (gethash hash-key prototype-factory-table)))
(assert prototype-factory+codevec)
(eq (sys::closure-codevec gf) (cdr prototype-factory+codevec)))))
(defvar *dynamically-modifiable-generic-function-names*
;; A list of names of functions, which ANSI CL explicitly denotes as
;; "Standard Generic Function"s, meaning that the user may add methods.
'(add-method allocate-instance change-class class-name (setf class-name)
compute-applicable-methods describe-object documentation
(setf documentation) find-method function-keywords initialize-instance
make-instance make-instances-obsolete make-load-form method-qualifiers
no-applicable-method no-next-method print-object reinitialize-instance
remove-method shared-initialize slot-missing slot-unbound
update-instance-for-different-class update-instance-for-redefined-class
;; Similar functions from the MOP.
add-dependent remove-dependent map-dependents
add-direct-method remove-direct-method
specializer-direct-generic-functions specializer-direct-methods
add-direct-subclass remove-direct-subclass class-direct-subclasses
compute-applicable-methods-using-classes
compute-class-precedence-list
compute-default-initargs
compute-direct-slot-definition-initargs
compute-discriminating-function
compute-effective-method
compute-effective-slot-definition
compute-effective-slot-definition-initargs
compute-slots
direct-slot-definition-class
effective-slot-definition-class
ensure-class-using-class
ensure-generic-function-using-class
reader-method-class
slot-value-using-class (setf slot-value-using-class)
slot-boundp-using-class slot-makunbound-using-class
validate-superclass
writer-method-class
;; Similar functions that are CLISP extensions.
(setf method-generic-function) no-primary-method))
(defun need-gf-already-called-warning-p (gf)
(and (not (gf-never-called-p gf))
(not (member (sys::closure-name gf)
*dynamically-modifiable-generic-function-names*
:test #'equal))))
(defun gf-already-called-warning (gf)
(clos-warn 'simple-gf-already-called-warning
(TEXT "The generic function ~S is being modified, but has already been called.")
gf))
(defun warn-if-gf-already-called (gf)
(when (need-gf-already-called-warning-p gf) (gf-already-called-warning gf)))
) ; let
;; Second optimization: The actual dispatch-code is calculated at the first
;; call of the function, in order to make successive method definitions not
;; too expensive.
;; First call of a generic function:
(defun initial-funcall-gf (gf)
(install-dispatch gf)
gf)
;; Installs the final dispatch-code into a generic function.
(defun install-dispatch (gf)
(let ((dispatch
(funcall (cond ((or (eq gf |#'compute-discriminating-function|) ; for bootstrapping
(eq gf |#'compute-applicable-methods-using-classes|))
#'compute-discriminating-function-<generic-function>)
(t #'compute-discriminating-function))
gf)))
; Some checks, to guarantee that user-defined methods on
; compute-discriminating-function don't break our CLOS.
(unless (functionp dispatch)
(error (TEXT "Wrong ~S result for generic-function ~S: not a function: ~S")
'compute-discriminating-function gf dispatch))
; Now install it.
(set-funcallable-instance-function gf dispatch)))
| 66,048 | Common Lisp | .lisp | 1,199 | 41.080901 | 151 | 0.566115 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | f37a19ee7343b0503f6a30dde814ae9116708cefba852b3227672a33fbb7b12b | 11,401 | [
-1
] |
11,402 | math.lisp | ufasoft_lisp/src/lisp/code/math.lisp | #|######### Copyright (c) 1997-2012 Ufasoft http://ufasoft.com mailto:[email protected], Sergey Pavlov mailto:[email protected] #################################################################################################
# #
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. #
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. #
# You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/> #
#############################################################################################################################################################################################################################################=|#
(in-package "SYS")
(defconstant SHORT-FLOAT-EPSILON SINGLE-FLOAT-EPSILON)
(defconstant DOUBLE-FLOAT-EPSILON SINGLE-FLOAT-EPSILON)
(defconstant LONG-FLOAT-EPSILON SINGLE-FLOAT-EPSILON)
(defconstant SHORT-FLOAT-NEGATIVE-EPSILON SINGLE-FLOAT-NEGATIVE-EPSILON)
(defconstant DOUBLE-FLOAT-NEGATIVE-EPSILON SINGLE-FLOAT-NEGATIVE-EPSILON)
(defconstant LONG-FLOAT-NEGATIVE-EPSILON SINGLE-FLOAT-NEGATIVE-EPSILON)
(defconstant MOST-POSITIVE-SHORT-FLOAT MOST-POSITIVE-SINGLE-FLOAT)
(defconstant MOST-POSITIVE-DOUBLE-FLOAT MOST-POSITIVE-SINGLE-FLOAT)
(defconstant MOST-POSITIVE-LONG-FLOAT MOST-POSITIVE-SINGLE-FLOAT)
(defconstant LEAST-POSITIVE-SHORT-FLOAT LEAST-POSITIVE-SINGLE-FLOAT)
(defconstant LEAST-POSITIVE-DOUBLE-FLOAT LEAST-POSITIVE-SINGLE-FLOAT)
(defconstant LEAST-POSITIVE-LONG-FLOAT LEAST-POSITIVE-SINGLE-FLOAT)
(defconstant LEAST-POSITIVE-NORMALIZED-SHORT-FLOAT LEAST-POSITIVE-NORMALIZED-SINGLE-FLOAT)
(defconstant LEAST-POSITIVE-NORMALIZED-DOUBLE-FLOAT LEAST-POSITIVE-NORMALIZED-SINGLE-FLOAT)
(defconstant LEAST-POSITIVE-NORMALIZED-LONG-FLOAT LEAST-POSITIVE-NORMALIZED-SINGLE-FLOAT)
(defconstant MOST-NEGATIVE-SHORT-FLOAT MOST-NEGATIVE-SINGLE-FLOAT)
(defconstant MOST-NEGATIVE-DOUBLE-FLOAT MOST-NEGATIVE-SINGLE-FLOAT)
(defconstant MOST-NEGATIVE-LONG-FLOAT MOST-NEGATIVE-SINGLE-FLOAT)
(defconstant LEAST-NEGATIVE-SHORT-FLOAT LEAST-NEGATIVE-SINGLE-FLOAT)
(defconstant LEAST-NEGATIVE-DOUBLE-FLOAT LEAST-NEGATIVE-SINGLE-FLOAT)
(defconstant LEAST-NEGATIVE-LONG-FLOAT LEAST-NEGATIVE-SINGLE-FLOAT)
(defconstant LEAST-NEGATIVE-NORMALIZED-SHORT-FLOAT LEAST-NEGATIVE-NORMALIZED-SINGLE-FLOAT)
(defconstant LEAST-NEGATIVE-NORMALIZED-DOUBLE-FLOAT LEAST-NEGATIVE-NORMALIZED-SINGLE-FLOAT)
(defconstant LEAST-NEGATIVE-NORMALIZED-LONG-FLOAT LEAST-NEGATIVE-NORMALIZED-SINGLE-FLOAT)
(defconstant pi 3.141592653589793)
(defun float-radix (x)
(declare (ignore x))
2)
(defun float-precision (x)
(multiple-value-bind (m e s)
(integer-decode-float x)
(integer-length m)))
(defun _check-floors (n d)
(if (or (not (realp n))
(not (realp d))
(zerop d))
(err)))
#|!!!R
(defun _truncate (n d)
(_check-floors n d)
(cond ((and (rationalp n) (rationalp d))
(let ((q (truncate (* (numerator n) (denominator d))
(* (numerator d) (denominator n)))))
(values q (- n (* q d)))))
(t (truncate (float n) (float d)))))
|#
#|!!!
(defun _floor (n d)
(_check-floors n d)
(let ((i (_floor1 (/ n d))))
(values i (- n (* i d)))))
|#
(defun floor (n &optional (d 1))
(multiple-value-bind (q r) (truncate n d)
(if (or (zerop r)
(if (minusp d) (minusp n) (plusp n)))
(values q r)
(values (1- q) (+ r d)))))
(defun ceiling (n &optional (d 1))
(multiple-value-bind (q r) (truncate n d)
(if (or (zerop r)
(if (minusp d) (plusp n) (minusp n)))
(values q r)
(values (1+ q) (- r d)))))
(macrolet ((frob (name op)
`(defun ,name (n &optional (d 1))
(multiple-value-bind (q r) (,op n d)
(values (float q) r)))))
(frob ffloor floor)
(frob fceiling ceiling)
(frob ftruncate truncate)
(frob fround round))
(defun mod (n d)
(nth-value 1 (floor n d)))
(defun rem (n d)
(nth-value 1 (truncate n d)))
(defun oddp (a)
(not (evenp a)))
(defun _mul-signum (x s)
(if (minusp s) (- x) x))
(defun round (n &optional (d 1))
(multiple-value-bind (q r) (truncate n d)
(let ((k (abs (/ d 2))))
(cond ((or (< (abs r) k) (and (= (abs r) k) (evenp q)))
(values q r))
(t (values (+ q (_mul-signum (_mul-signum 1 n) d))
(if (plusp r) (- r (abs d))
(+ r (abs d)))))))))
(defun expt (b p)
(cond ((zerop p) (coerce 1 (type-of b)))
((= p 1) b)
((integerp p)
(if (minusp p)
(/ (expt b (- p)))
(let ((r (expt (* b b) (ash p -1))))
(if (evenp p) r (* r b)))))
((zerop b) (cond ((plusp (realpart p)) 0)
((error "Return" "Invalid argument"))))
((exp (* p (log b))))))
(defun sqrt (x)
(cond ((complexp x) (exp (/ (log x) 2)))
((minusp x) (complex 0 (sqrt (- x))))
((_sqrt (float x)))))
;;; Newton's method
(defun isqrt (n)
(check-type n (integer 0 *))
(do* ((x (ash 1 (ash (integer-length n) -1)))
(d (truncate n x) (truncate n x)))
((prog1 (< -2 (- x d) 2)
(setq x (ash (+ x d) -1)))
x)))
(defun sin (z)
(if (complexp z) (/ (- (exp (* z #C(0 1))) (exp (* z #C(0 -1)))) #C(0 2))
(_sin (float z))))
(defun cos (z)
(if (complexp z) (/ (+ (exp (* z #C(0 1))) (exp (* z #C(0 -1)))) 2)
(_cos (float z))))
(defun tan (z)
(/ (sin z) (cos z)))
(defun asin (z)
(if (and (realp z) (<= (abs z) 1))
(_asin (float z))
(* #C(0 -1) (log (* #C(0 1) (+ z (sqrt (- (* z z) 1))))))))
(defun acos (z)
(if (and (realp z) (<= (abs z) 1))
(_acos (float z))
(* #C(0 -1) (log (- z (sqrt (- (* z z) 1)))))))
(defun atan (x &optional y)
(cond (y (_atan2 (float x) (float y)))
((realp x) (_atan (float x)))
(* #C(0 -1/2) (log (/ (- #C(0 1) x) (+ #C(0 1) x))))))
(defun sinh (z)
(/ (- (exp z) (exp (- z))) 2))
(defun cosh (z)
(/ (+ (exp z) (exp (- z))) 2))
(defun tanh (z)
(/ (sinh z) (cosh z)))
(defun asinh (z)
(log (+ z (sqrt (1+ (* z z))))))
(defun acosh (z)
(* 2 (log (+ (sqrt (/ (1+ z) 2))
(sqrt (/ (1- z) 2))))))
(defun atanh (z)
(/ (log (/ (1+ z) (- 1 z))) 2))
(defun cis (radians)
(check-type radians real)
(complex (cos radians) (sin radians)))
(defun exp (z)
(cond ((complexp z) (* (exp (realpart z)) (cis (imagpart z))))
((_exp (float z)))))
(defun log (z &optional (b nil b-p))
(if b-p
(/ (log z) (log b))
(cond
((or (complexp z) (minusp z))
(complex (log (abs z))
(phase z)))
((_log (float z))))))
(defun lcm (&rest r)
(if r (let ((a (abs (car r)))
(d (cdr r)))
(if d (let ((b (abs (car d))))
(if (or (zerop a) (zerop b))
0
(apply #'lcm (/ (* a b) (gcd a b)) (cdr d))))
a))
1))
(defun _rational-rationalize (x f)
(if (rationalp x)
x
(multiple-value-bind (m e s) (integer-decode-float x)
(_mul-signum (if (minusp e)
(funcall f m (ash 1 (- e)))
(ash m e))
s))))
(defun rational (x)
(_rational-rationalize x #'(lambda (m ee) (/ m ee))))
(defun _fraction (a b) ; find ratio with smallest denominator between a & b
(let ((c (ceiling a)))
(if (< c b)
c
(let ((k (1- c)))
(+ k (/ 1 (_fraction (/ 1 (- b k))
(/ 1 (- a k)))))))))
(defun rationalize (x)
(_rational-rationalize x #'(lambda (m ee)
(_fraction (/ (- m 1/2) ee)
(/ (+ m 1/2) ee)))))
#|!!!Hardcoded
(defun logcount (x)
(if (not (integerp x)) (err))
(do* ((a (if (minusp x) (lognot x) x) (ash a -1))
(sum (logand a 1) (+ sum (logand a 1))))
((zerop a) sum)
))
|#
(defconstant boole-clr 0)
(defconstant boole-nor 1)
(defconstant boole-andc2 2)
(defconstant boole-c2 3)
(defconstant boole-andc1 4)
(defconstant boole-c1 5)
(defconstant boole-xor 6)
(defconstant boole-nand 7)
(defconstant boole-and 8)
(defconstant boole-eqv 9)
(defconstant boole-1 10)
(defconstant boole-orc2 11)
(defconstant boole-2 12)
(defconstant boole-orc1 13)
(defconstant boole-ior 14)
(defconstant boole-set 15)
(defvar _*boole-funs*
#(#'(lambda (x y) 0)
#'lognor
#'logandc2
#'(lambda (x y) (lognot y))
#'logandc1
#'(lambda (x y) (lognot x))
#'logxor
#'lognand
#'logand
#'logeqv
#'(lambda (x y) x)
#'logorc2
#'(lambda (x y) y)
#'logorc1
#'logior
#'(lambda (x y) -1)
))
(defun boole (op x y)
(check-type op (integer 0 15))
(funcall (svref _*boole-funs* op) x y))
| 9,890 | Common Lisp | .lisp | 240 | 34.316667 | 240 | 0.525045 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 69f75ee04ae43ac3c882879218fb14c68c7cf827c40edf62e5203a0d188b3b5f | 11,402 | [
-1
] |
11,403 | uclos.lisp | ufasoft_lisp/src/lisp/code/uclos.lisp | #|######### Copyright (c) 1997-2012 Ufasoft http://ufasoft.com mailto:[email protected], Sergey Pavlov mailto:[email protected] #################################################################################################
# #
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. #
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. #
# You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/> #
#############################################################################################################################################################################################################################################=|#
(in-package "SYS")
(import '(TEXT error-of-type) "CLOS")
(in-package "CLOS")
(defun find-class (symbol &optional (errorp t) environment)
(declare (ignore environment)) ; what should be the meaning of the environment?
(unless (symbolp symbol)
(error-of-type 'type-error
:datum symbol :expected-type 'symbol
(TEXT "~S: argument ~S is not a symbol")
'find-class symbol))
(let ((class (get symbol 'CLOSCLASS)))
(if (not (potential-class-p class))
(if errorp
(error-of-type 'error
(TEXT "~S: ~S does not name a class")
'find-class symbol)
nil)
class)))
(defun %shared-initialize (instance slot-names &rest initargs)
(dolist (slot (class-slots (class-of instance)) instance)
(let ((slotname (slot-definition-name slot)))
(multiple-value-bind (init-key init-value foundp)
(get-properties initargs (slot-definition-initargs slot))
(declare (ignore init-key))
(if foundp
(set-slot-value instance slotname init-value)
(unless (slot-boundp instance slotname)
(let ((init (slot-definition-initfunction slot)))
(when init
(when (or (eq slot-names 'T)
(member slotname slot-names :test #'eq))
(set-slot-value instance slotname (funcall init)))))))))))
(defun %initialize-instance (instance &rest initargs &key &allow-other-keys)
; (sys::_pr "%initialize-instance:")
; (sys::_pr instance)
(let ((h (gethash (class-of instance) *make-instance-table*)))
(if h
(apply (svref h 3) instance 'T initargs)
(apply #'initial-initialize-instance instance initargs))))
(defun %reinitialize-instance (instance &rest initargs &key &allow-other-keys)
(let ((h (gethash (class-of instance) *reinitialize-instance-table*)))
(if h
(progn
(sys::keyword-test initargs (car h))
(apply (cdr h) instance 'NIL initargs))
(apply #'initial-reinitialize-instance instance initargs))))
(defun %defclos (std-cv struct-cv builtin-cv defined potential v)
(setq *CLASS-VERSION-STANDARD-CLASS* std-cv
*CLASS-VERSION-STRUCTURE-CLASS* struct-cv
*CLASS-BUILT-IN-STANDARD_CLASS* builtin-cv
*CLASS-DEFINED-CLASS* defined
*CLASS-POTENTIAL-CLASS* potential)
(let ((vv (vector 'array 'bit-vector 'character 'complex 'cons 'float 'function
'hash-table 'integer 'list 'null 'package 'pathname
#+LOGICAL-PATHNAMES 'logical-pathname
;!!!if UCFG_LISP_BUILTIN_RANDOM_STATE 'random-state
'ratio 'readtable
'stream 'file-stream 'synonym-stream 'broadcast-stream
'concatenated-stream 'two-way-stream 'echo-stream 'string-stream
'string 'symbol 't 'vector)))
(dotimes (i (length vv))
(setf (get (svref vv i) 'closclass) (svref v i)))))
#|
(let (unbound) (declare (compile)) ; unbound = #<unbound>
(defun u-def-unbound (x) (declare (compile)) (setq unbound x))
(defun slot-value-using-class (class object slot-name)
(no-slot-error class object slot-name))
(defun setf-slot-value-using-class (new-value class object slot-name)
(declare (ignore new-value))
(no-slot-error class object slot-name))
(defun slot-boundp-using-class (class object slot-name)
(no-slot-error class object slot-name))
(defun slot-makunbound-using-class (class object slot-name)
(no-slot-error class object slot-name))
(defun slot-exists-p-using-class (class object slot-name)
(no-slot-error class object slot-name))
(defun no-slot-error (class object slot-name)
(declare (ignore slot-name))
(error-of-type 'error
(TEXT "instance ~S of class ~S has no slots (wrong metaclass)")
object class))
)
|#
| 5,362 | Common Lisp | .lisp | 89 | 52.460674 | 240 | 0.580108 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 78226f7b9bfd0b47a8e6cdcc0a1a269aabf0d8200e6ec870a607c3a5ca270b13 | 11,403 | [
-1
] |
11,404 | cl.lisp | ufasoft_lisp/src/lisp/code/cl.lisp | #|######### Copyright (c) 1997-2012 Ufasoft http://ufasoft.com mailto:[email protected], Sergey Pavlov mailto:[email protected] #################################################################################################
# #
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. #
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. #
# You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/> #
#############################################################################################################################################################################################################################################=|#
(in-package "SYS")
(defmacro ENGLISH (x) x)
;;; Iterate -- Public
;;;
;;; The ultimate iteration macro...
;;;
(defmacro iterate (name binds &body body)
"Iterate Name ({(Var Initial-Value)}*) Declaration* Form*
This is syntactic sugar for Labels. It creates a local function Name with
the specified Vars as its arguments and the Declarations and Forms as its
body. This function is then called with the Initial-Values, and the result
of the call is return from the macro."
(dolist (x binds)
(unless (and (listp x)
(= (length x) 2))
(error "Malformed iterate variable spec: ~S." x)))
`(labels ((,name ,(mapcar #'first binds) ,@body))
(,name ,@(mapcar #'second binds))))
;;; Once-Only -- Interface
;;;
;;; Once-Only is a utility useful in writing source transforms and macros.
;;; It provides an easy way to wrap a let around some code to ensure that some
;;; forms are only evaluated once.
;;;
(defmacro once-only (specs &body body)
"Once-Only ({(Var Value-Expression)}*) Form*
Create a Let* which evaluates each Value-Expression, binding a temporary
variable to the result, and wrapping the Let* around the result of the
evaluation of Body. Within the body, each Var is bound to the corresponding
temporary variable."
(iterate frob
((specs specs)
(body body))
(if (null specs)
`(progn ,@body)
(let ((spec (first specs)))
(when (/= (length spec) 2)
(error "Malformed Once-Only binding spec: ~S." spec))
(let ((name (first spec))
(exp-temp (gensym)))
`(let ((,exp-temp ,(second spec))
(,name (gensym "OO-")))
`(let ((,,name ,,exp-temp))
,,(frob (rest specs) body))))))))
(defun whitespacep (char &optional (rt *readtable*))
(eq (_char-type char rt) :whitespace))
;!!! (test-attribute char whitespace rt))
;;; WITH-ARRAY-DATA -- Interface
;;;
;;; Checks to see if the array is simple and the start and end are in
;;; bounds. If so, it proceeds with those values. Otherwise, it calls
;;; %WITH-ARRAY-DATA. Note that there is a derive-type method for
;;; %WITH-ARRAY-DATA.
;;;
(defmacro with-array-data (((data-var array &key (offset-var (gensym)))
(start-var &optional (svalue 0))
(end-var &optional (evalue nil)))
&rest forms)
"Given any Array, binds Data-Var to the array's data vector and Start-Var and
End-Var to the start and end of the designated portion of the data vector.
Svalue and Evalue are any start and end specified to the original operation,
and are factored into the bindings of Start-Var and End-Var. Offset-Var is
the cumulative offset of all displacements encountered, and does not
include Svalue."
(once-only ((n-array array)
(n-svalue svalue)
(n-evalue evalue))
`(multiple-value-bind
(,data-var ,start-var ,end-var ,offset-var)
(let ((,n-array ,n-array))
(declare (type (simple-array * (*)) ,n-array))
,(once-only ((n-len `(length ,n-array))
(n-end `(or ,n-evalue ,n-len)))
`(if (<= ,n-svalue ,n-end ,n-len)
(values ,n-array ,n-svalue ,n-end 0)
(%with-array-data ,n-array ,n-svalue ,n-evalue))))
(declare (ignorable ,offset-var))
,@forms)))
(defun parse-integer (string &key (start 0) end (radix 10) junk-allowed)
"Examine the substring of string delimited by start and end
(default to the beginning and end of the string) It skips over
whitespace characters and then tries to parse an integer. The
radix parameter must be between 2 and 36."
(with-array-data ((string string)
(start start)
(end (or end (length string))))
(let ((index (do ((i start (1+ i)))
((= i end)
(if junk-allowed
(return-from parse-integer (values nil end))
(error "No non-whitespace characters in number.")))
(declare (fixnum i))
(unless (whitespacep (char string i)) (return i))))
(minusp nil)
(found-digit nil)
(result 0))
(declare (fixnum index))
(let ((char (char string index)))
(cond ((char= char #\-)
(setq minusp t)
(incf index))
((char= char #\+)
(incf index))))
(loop
(when (= index end) (return nil))
(let* ((char (char string index))
(weight (digit-char-p char radix)))
(cond (weight
(setq result (+ weight (* result radix))
found-digit t))
(junk-allowed (return nil))
((whitespacep char)
(do ((jndex (1+ index) (1+ jndex)))
((= jndex end))
(declare (fixnum jndex))
(unless (whitespacep (char string jndex))
(error "There's junk in this string: ~S." string)))
(return nil))
(t
(error "There's junk in this string: ~S." string))))
(incf index))
(values
(if found-digit
(if minusp (- result) result)
(if junk-allowed
nil
(error "There's no digits in this string: ~S" string)))
index))))
#|!!!R
(defun present (s p)
(multiple-value-bind (sym st) (find-symbol (symbol-name s) p)
(and (eq s sym) (memq st '(:internal :external)))))
|#
(import
'(_get-package memq listify _seq-iterate _concs ext:string-concat
_pr)
(find-package "CL"))
;!!!(setq *package* (find-package "CL"))
(setq *_trace_* t)
(defvar _*gentemp-counter* 0)
(defun gentemp (&optional (x "T") (pack *package*))
(do ()
(nil)
(multiple-value-bind (sym st) (intern (ext:string-concat x (write-to-string (incf _*gentemp-counter*))) pack)
(if (null st) (return sym)))))
(defun _elts (seq i)
(if seq (cons (elt (car seq) i) (_elts (cdr seq) i))))
(defun _every (p seq i n)
(if (< i n) (if (apply p (_elts seq i)) (_every p seq (1+ i) n))
t))
(defun _some (p seq i n)
(if (< i n) (cond ((apply p (_elts seq i)))
((_some p seq (1+ i) n)))))
(defun every (p &rest seq)
(_every p seq 0 (apply #'min (mapcar #'length seq))))
(defun some (p &rest seq)
(_some p seq 0 (apply #'min (mapcar #'length seq))))
(defun notany (p &rest seq)
(not (apply #'some p seq)))
(defun notevery (p &rest seq)
(not (apply #'every p seq)))
#|!!! buggy
(defun _rotatef-2 (r n forms)
(if r (let ((x (car r)))
`(let ((,n ,(fifth x)))
,(_rotatef-2 (cdr r) (car (third x)) (cons (fourth x) forms))))
`(progn ,@(nreverse forms)
nil)))
(defmacro rotatef (&body p)
(if p (let* ((r (_setf-expansions p))
(z (car (last r))))
(_rotatef-2 r (car (third z)) nil))))
|#
(defun devalue-form (form)
(if (eq (car form) 'VALUES) (cdr form) (list form))
)
(defmacro rotatef (&rest args &environment env)
(when (null args) (return-from rotatef NIL))
(when (null (cdr args)) (return-from rotatef `(PROGN ,(car args) NIL)))
(do* ((arglist args (cdr arglist))
(res (list 'let* nil nil)) lf
(tail (cdr res)) bindlist stores lv fv)
((null arglist)
(setf (second res) (nreverse bindlist)
(second (third res)) lv
(cdr tail) (nconc (nreverse stores) (devalue-form lf))
(cdr (last res)) (list nil))
res)
(multiple-value-bind (vr vl sv se ge)
(get-setf-expansion (first arglist) env)
(setq bindlist (nreconc (mapcar #'list vr vl) bindlist))
(setf (cadr tail) (list 'MULTIPLE-VALUE-BIND lv ge nil))
(setq tail (cddadr tail))
(if (null fv)
(setq fv sv)
(setq stores (revappend (devalue-form lf) stores))
)
(setq lv sv lf se))))
(defun _shiftf (p n r store-forms z)
(if p (multiple-value-bind (vars vals stores store-form access-form) (get-setf-expansion (car p))
(declare (ignore vars vals))
`(let ((,r ,access-form))
,(_shiftf (cdr p) n (car stores) (append store-forms (list store-form)) z)))
`(let ((,r ,n))
,@store-forms
,z)))
(defmacro shiftf (&body p)
(let ((r (gensym)))
(_shiftf (butlast p) (car (last p)) r nil r)))
;;; mapappend is like mapcar except that the results are appended together:
(defun mapappend (fun &rest args)
(if (some #'null args)
()
(append (apply fun (mapcar #'car args))
(apply #'mapappend fun (mapcar #'cdr args)))))
(defmacro type-specifier-atom (type)
(if (atom type) type (car type)))
(defmacro elt-slice (sequences n)
`(mapcar #'(lambda (seq) (elt seq ,n)) ,sequences))
(defmacro map-for-effect (function sequences)
`(do ((seqs more-sequences (cdr seqs))
(min-length (length first-sequence)))
((null seqs)
(do ((index 0 (1+ index)))
((= index min-length) nil)
(apply ,function (elt-slice ,sequences index))))
(declare (fixnum min-length))
(let ((length (length (car seqs))))
(declare (fixnum length))
(if (< length min-length)
(setq min-length length)))))
#| !!!!
(defmacro map-to-list (function sequences)
`(do ((seqs more-sequences (cdr seqs))
(min-length (length first-sequence)))
((null seqs)
(let ((result (list nil)))
(do ((index 0 (1+ index))
(splice result))
((= index min-length) (cdr result))
(declare (fixnum index))
(setq splice
(cdr (rplacd splice
(list (apply ,function (elt-slice ,sequences
index)))))))))
(declare (fixnum min-length))
(let ((length (length (car seqs))))
(declare (fixnum length))
(if (< length min-length)
(setq min-length length)))))
|#
;;; push-on-end is like push except it uses the other end:
(defmacro push-on-end (value location)
`(setf ,location (nconc ,location (list ,value))))
;;; (setf getf*) is like (setf getf) except that it always changes the list,
;;; which must be non-nil.
(defun (setf getf*) (new-value plist key)
(block body
(do ((x plist (cddr x)))
((null x))
(when (eq (car x) key)
(setf (car (cdr x)) new-value)
(return-from body new-value)))
(push-on-end key plist)
(push-on-end new-value plist)
new-value))
(defun get-properties (p i)
(if p (let ((a (car p))
(r (cdr p)))
(if (memq a i) (values a (car r) p)
(get-properties (cdr r) i)))
(values nil nil nil)))
;;; mapplist is mapcar for property lists:
(defun mapplist (fun x)
(if (null x)
()
(cons (funcall fun (car x) (cadr x))
(mapplist fun (cddr x)))))
(defconstant char-code-limit 65536)
(defconstant base-char-code-limit char-code-limit)
(defun character (x)
(if (characterp x) x
(if (and (or (stringp x) (symbolp x))
(= (length (string x)) 1))
(char (string x) 0)
(error 'type-error :datum x))))
(defun graphic-char-p (ch)
(>= (char-code ch) (char-code #\Space)))
(defun prin1 (x &optional stm)
(write x :stream stm :escape t))
(defun print (x &optional stm)
(prog2 (terpri stm)
(prin1 x stm)
(write-char #\Space stm)))
(defun write-line (string &optional s &key (start 0) end)
(prog1 (write-string string s :start start :end end)
(terpri s)))
(defun keywordp (x)
(eq (type-of x) 'keyword))
(defmacro with-standard-io-syntax (&rest forms)
`(let ((*package* (find-package 'cl-user))
(*print-array* t)
(*print-base 10)
(*print-case :upcase)
(*print-circle* nil)
(*print-escape* t)
(*print-gensym* t)
(*print-length* nil)
(*print-level* nil)
(*print-lines* nil)
(*print-miser-width* nil)
(*print-pprint-dispatch* nil) ;!!!
(*print-pretty* nil)
(*print-radix* nil)
(*print-readably* t)
(*print-rigth-margin* nil)
(*read-base* 10)
(*read-default-float-format* 'single-float)
(*read-eval* t)
(*read-suppress* nil)
(*readtable* (copy-readtable nil))) ;!!!
,@forms))
(defun find-all-symbols (s &aux (str (string s)) r)
(dolist (p (list-all-packages) r)
(let ((sym (find-symbol str p)))
(if sym (pushnew sym r)))))
(defun %in-package (name &rest rest &key (nicknames nil n-p) (use nil u-p) (case-sensitive nil c-p) case-inverted)
(declare (ignore case-sensitive case-inverted c-p))
(let ((p (or (find-package (string name))
(apply #'make-package name :allow-other-keys t rest))))
(if n-p (rename-package p (package-name p) nicknames))
(when u-p
(use-package use p)
(dolist (u (package-use-list p))
(unless (memq u use)
(unuse-package u p))))
p))
(defmacro defpackage (name &rest options)
(let (size
doc
nicks
shadow-list
shadowing-list
(use-list '(cl))
imports
interns)
(declare (ignore size doc shadow-list shadowing-list imports interns))
(dolist (opt options)
(case (car opt)
(:size) ;!!! ignore
(:documentation) ;!!! ignore
(:nicknames (setq nicks (append nicks (cdr opt))))
(:shadow)
(:use (setq use-list (cdr opt)))
(:import-from)
(:intern)
(:export)
(t (error t "Invalid defpackage option"))))
`(EVAL-WHEN (LOAD COMPILE EVAL)
(prog1 (cond ((find-package ',name))
((make-package ',name :nicknames ',nicks :use ',use-list)))))))
(defpackage "COMMON-LISP-USER"
(:nicknames "CL-USER" "USER")
(:use "CL" "EXT"))
(defpackage "I18N"
(:use "CL" "EXT"))
(defpackage "GRAY"
(:use "CL" "EXT"))
#|
(defun _substring (x s)
(let ((n (length x)))
(if (<= n (length s))
(or (string= x (subseq s 0 (length x))) (_substring x (subseq s 1))))))
(defun apropos (s &optional pack)
(let ((name (string s)))
(if pack (do-symbols (sym pack)
(if (_substring name (symbol-name sym)) (print sym)))
(do-all-symbols (sym pack)
(if (_substring name (symbol-name sym)) (print sym)))))
(values))
(defun apropos-list (s &optional pack &aux p)
(let ((name (string s)))
(if pack (do-symbols (sym pack)
(if (_substring name (symbol-name sym)) (push sym p)))
(do-all-symbols (sym pack)
(if (_substring name (symbol-name sym)) (push sym p)))))
p)
|#
(defun conjugate (z)
(complex (realpart z) (- (imagpart z))))
(defun schar (v i)
(if (simple-string-p v)
(aref v i)
(error 'type-error :datum v :expected-type 'simple-string)))
(defun store-schar (s i n)
(if (simple-string-p s)
(setf (aref s i) n)
(error 'type-error :datum s :expected-type 'simple-string)))
(defmacro while (c &body body)
`(do ()
((not ,c))
,@body))
(defmacro forever (&body body)
`(while t ,@body))
#|!!!R
(defun make-hash-table (&key (test 'eql) size (rehash-size 1) (rehash-threshold 1) initial-contents
key-type value-type warn-if-needs-rehash-after-gc weak)
(declare (ignore size key-type value-type warn-if-needs-rehash-after-gc weak))
(let ((ht (_make-hash-table (labels ((_tests (x)
(if x (let ((a (car x)))
(list* (cons a a)
(cons (symbol-function a) a)
(_tests (cdr x)))))))
(let ((r (assoc test (_tests '(eq eql equal equalp fasthash-eq stablehash-eq fasthash-eql stablehash-eql fasthash-equal stablehash-equal)))))
(if r (cdr r)
(err))))
rehash-size rehash-threshold)))
(dolist (e initial-contents ht)
(setf (gethash (car e) ht) (cdr e)))))
|#
(defun (setf gethash) (v key ht &optional def)
(declare (ignore def))
(puthash key ht v))
(defmacro with-hash-table-iterator ((name ht) &body body)
(let ((var (gensym)))
`(let ((,var (hash-table-iterator ,ht)))
(macrolet ((,name () '(hash-table-iterate ,var)))
,@body))))
(defun maphash (f ht)
(with-hash-table-iterator (next ht)
(forever (multiple-value-bind (more key value) (next)
(if more (funcall f key value)
(return))))))
(defun union (p q &rest rest &key key (test #'eql) test-not &aux r)
(declare (ignore test test-not))
(setq key (_key key))
(dolist (x p (nconc r q))
(unless (apply #'member (funcall key x) q rest)
(push x r))))
(defun nunion (p q &rest rest &key key (test #'eql) test-not)
(declare (ignore key test test-not))
(apply #'union p q rest)) ;!!! make more effective
(defun subsetp (p q &rest rest &key key (test #'eql) test-not)
(declare (ignore test test-not))
(setq key (_key key))
(dolist (x p t)
(if (not (apply #'member (funcall key x) q rest)) (return nil))))
(defun set-exclusive-or (list1 list2 &rest rest &key test test-not key)
(declare (ignore key test test-not))
(append (apply #'set-difference list1 list2 rest)
(apply #'set-difference list2 list1 rest)))
(defun nset-exclusive-or (list1 list2 &rest rest &key test test-not key)
(declare (ignore key test test-not))
(nconc (apply #'set-difference list1 list2 rest)
(apply #'nset-difference list2 list1 rest)))
(defun make-string-output-stream (&key (element-type 'character) (line-position 0))
(if (null element-type) (setq element-type 'character)) ;!!! CLISP's incorrect arg
(make-string-push-stream (make-string 0 :element-type element-type) line-position))
(defun lisp-implementation-type ()
"Ufasoft LISP")
(defun short-site-name ()
(machine-instance))
(defun long-site-name ()
(short-site-name))
(defvar *compile-print* nil)
(defvar *compile-verbose* nil)
(defun package-iterator-function (pack-list symbol-types)
(let ((iterstates
(mapcar #'(lambda (pack) (package-iterator pack symbol-types))
(if (listp pack-list) pack-list (list pack-list)))))
; The iterstates list is cdr'ed down during the iteration.
#'(lambda ()
(loop
(if iterstates
(multiple-value-bind (more symb acc)
(package-iterate (car iterstates))
(if more
(return (values more symb acc (svref (car iterstates) 4)))
(pop iterstates)
) )
(return nil))))))
#|!!!
(defmacro with-package-iterator ((name pack-list &rest types) &body body)
(unless types
(error-of-type 'source-program-error
(ENGLISH "missing symbol types (~S/~S/~S) in ~S")
':internal ':external ':inherited 'with-package-iterator))
(dolist (symboltype types)
(case symboltype
((:INTERNAL :EXTERNAL :INHERITED))
(t (error-of-type 'source-program-error
(ENGLISH "~S: flag must be one of the symbols ~S, ~S, ~S, not ~S")
'with-package-iterator ':internal ':external ':inherited symboltype))))
(let ((iterfun (gensym "WPI")))
`(let ((,iterfun (package-iterator-function ,pack-list ',(remove-duplicates types))))
(macrolet ((,name () '(funcall ,iterfun)))
,@body))))
|#
(defconstant y-or-n '((#\N) . (#\Y)))
(defconstant yes-or-no '(("no") . ("yes")))
(defun y-or-n-p (&optional format-string &rest args)
(when format-string
(fresh-line *query-io*)
(apply #'format *query-io* format-string args)
(write-string " (y/n) " *query-io*)
)
(let ((localinfo y-or-n))
(loop
(let ((line (string-left-trim " " (read-line *query-io*))))
(when (plusp (length line))
(let ((first-char (char-upcase (char line 0))))
(when (member first-char (car localinfo)) (return nil))
(when (member first-char (cdr localinfo)) (return t)))))
(terpri *query-io*)
(write-string "Please answer with y or n : " *query-io*))))
(defun yes-or-no-p (&optional format-string &rest args)
(when format-string
(fresh-line *query-io*)
(apply #'format *query-io* format-string args)
(write-string " (yes/no) " *query-io*)
)
(let ((localinfo yes-or-no))
(loop
(clear-input *query-io*)
(let ((line (string-trim " " (read-line *query-io*))))
(when (member line (car localinfo) :test #'string-equal) (return nil))
(when (member line (cdr localinfo) :test #'string-equal) (return t)))
(terpri *query-io*)
(write-string "Please answer with yes or no : " *query-io*))))
(defun file-string-length (stm obj)
(declare (ignore stm obj))
nil)
(defmacro define-compiler-macro (&whole form name args &body body)
(declare (ignore name args body))
(multiple-value-bind (expansion name lambdalist docstring)
(make-macro-expansion (cdr form) 'strip-funcall-form)
(declare (ignore lambdalist))
`(EVAL-WHEN (COMPILE LOAD EVAL)
,@(when docstring
`((SYSTEM::%SET-DOCUMENTATION ',name 'COMPILER-MACRO ,docstring)))
(setf (compiler-macro-function ',name) ,expansion)
',name)))
#|
(defmacro define-symbol-macro (symbol expansion)
(unless (symbolp symbol)
(error-of-type 'source-program-error
(ENGLISH "~S: the name of a symbol macro must be a symbol, not ~S")
'define-symbol-macro symbol
) )
`(LET ()
(EVAL-WHEN (COMPILE LOAD EVAL)
(CHECK-NOT-SPECIAL-VARIABLE-P ',symbol)
(MAKUNBOUND ',symbol)
(SYSTEM::SET-SYMBOL-VALUE ',symbol (SYSTEM::MAKE-SYMBOL-MACRO ',expansion))
)
',symbol
)
)
|#
(macrolet ((frob (name result access src-type &optional typep)
`(DEFUN ,name (object ,@(if typep '(type) ()))
(DO* ((index 0 (1+ index))
(length (length (the ,(case src-type
(:list 'list)
(:vector 'vector))
object)))
(result ,result))
((= index length) result)
(declare (fixnum length index))
(SETF (,access result index) ,(case src-type
(:list '(pop object))
(:vector '(aref object index))))))))
(frob list-to-string* (make-string length) schar :list)
(frob list-to-bit-vector* (make-array length :element-type '(mod 2)) sbit :list)
(frob list-to-vector* (make-sequence-of-type type length) aref :list t)
(frob vector-to-vector* (make-sequence-of-type type length) aref :vector t)
(frob vector-to-string* (make-string length) schar :vector) (frob vector-to-bit-vector* (make-array length :element-type '(mod 2))
sbit :vector)
)
#|
(defun vector-to-list* (object)
(let ((result (list nil))
(length (length object)))
(declare (fixnum length))
(do ((index 0 (1+ index))
(splice result (cdr splice)))
((= index length) (cdr result))
(declare (fixnum index))
(rplacd splice (list (aref object index))))))
|#
(defun specifier-type (spec)
spec)
(defun csubtypep (spec1 spec2)
(subtypep spec1 spec2))
(defun string-to-simple-string* (seq)
(copy-seq seq))
(defun file-stream-p (x)
(eq (type-of x) 'file-stream))
(defun synonym-stream-p (x)
(eq (type-of x) 'synonym-stream))
(defun broadcast-stream-p (x)
(eq (type-of x) 'broadcast-stream))
(defun concatenated-stream-p (x)
(eq (type-of x) 'concatenated-stream))
(defun two-way-stream-p (x)
(eq (type-of x) 'two-way-stream))
(defun echo-stream-p (x)
(eq (type-of x) 'echo-stream))
(defun string-stream-p (x)
(eq (type-of x) 'string-stream))
(defun _as-string (x)
(with-output-to-string (stm)
(prin1 x stm)))
;!!! (if (= (length args) 1) (_err1 cnd code (_as-string (car args)))
; (error t "Invalid _ERR")))
#|!!!R
(defun invalid-method-error (meth formcont &rest args)
(declare (ignore meth formcont args))
(err))
(defun method-combination-error (formcont &rest args)
(declare (ignore formcont args))
(err))
|#
;;; NORMALIZE-TYPE normalizes the type using the DEFTYPE definitions.
;;; The result is always a list.
(defun normalize-type (type &aux tp i )
;; Loops until the car of type has no DEFTYPE definition.
(loop
(if (atom type)
(setq tp type i nil)
(setq tp (car type) i (cdr type)))
(if (get tp 'deftype-expander)
(setq type (apply (get tp 'deftype-expander) i))
(return-from normalize-type (if (atom type) (list type) type)))))
;(defconstant ELTYPE_T 0)
;(defconstant ELTYPE_BIT 1)
;(defconstant ELTYPE_CHARACTER 2)
(defun _eltype-code (x)
(case x
(bit 'ELTYPE_T)
(character 'ELTYPE_CHARACTER)
((t) 'ELTYPE_T)
(nil nil)
(t (multiple-value-bind (low high)
(subtype-integer x)
(if (and (integerp low) (> low 0))
(let ((len (integer-length high)))
(cond ((<= len 1) 'ELTYPE_BIT)
(t 'ELTYPE_T)))
(if (subtypep x 'character) 'ELTYPE_CHARACTER 'ELTYPE_T))))))
(defun coerce (x type)
(if (typep x type)
x
(progn (setq type (expand-deftype type))
(if (clos::potential-class-p type) (setq type (class-name type)))
(if (atom type) (setq type (list type)))
(case (car type)
((t) x)
(and (if (null (cdr type))
x
(let ((n (coerce x (cadr type))))
(if (typep n type) n
(err)))))
((character string-char) (character x))
((float short-float single-float double-float loang-float) (float x))
(complex (complex x))
(function (let ((f (fboundp x)))
(if (function-macro-p f) (setq f (function-macro-function f))))) ;!!! need lamda
; (array simple-array vector simple-vector string simple-string base-string simple-base-string bit-vector simple-bit-vector)
(t (_coerce-seq x (car type) t))))))
(defvar *random-state* (make-random-state t))
| 27,916 | Common Lisp | .lisp | 677 | 33.800591 | 240 | 0.577484 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 8ac85720ecd9c541f02d0e3bb716e17764099e3946734d8e750a4e757c197a37 | 11,404 | [
-1
] |
11,405 | env.lisp | ufasoft_lisp/src/lisp/code/env.lisp | #|######### Copyright (c) 1997-2012 Ufasoft http://ufasoft.com mailto:[email protected], Sergey Pavlov mailto:[email protected] #################################################################################################
# #
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. #
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. #
# You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/> #
#############################################################################################################################################################################################################################################=|#
(in-package "SYS")
;;-----------------------------------------------------------------------------
;; DRIBBLE
; The use of an intermediate synonym-stream is for robustness.
; (Just try dribbling to a file on a full disk partition...)
(defvar *dribble-stream* nil)
(let ((dribble-file nil) (dribbled-input nil) (dribbled-output nil)
(dribbled-error-output nil) (dribbled-trace-output nil)
(dribbled-query-io nil) (dribbled-debug-io nil))
(defun dribble (&optional file)
(if file
(progn
(if dribble-file
(warn (ENGLISH "Already dribbling to ~S")
dribble-file
)
;; Dribbling means to redirect all screen output to the file.
;; We redirect all standard streams. More precisely, those
;; which are #<SYNONYM-STREAM *TERMINAL-IO*>. Those which are
;; synonyms to other standard streams indirectly referring
;; to #<SYNONYM-STREAM *TERMINAL-IO*> are not redirected,
;; because that would cause each output to this stream to
;; be written twice to the dribble-file.
(labels ((goes-to-terminal (stream) ; this is a hack
(and (typep stream 'synonym-stream)
(eq (synonym-stream-symbol stream) '*terminal-io*)
) )
(goes-indirectly-to-terminal (stream) ; an even bigger hack
(and (typep stream 'synonym-stream)
(let ((sym (synonym-stream-symbol stream)))
(and (boundp sym)
(let ((stream (symbol-value sym)))
(or (goes-to-terminal stream)
(goes-indirectly-to-terminal stream)
)) ) ) ) ) )
(setq *dribble-stream* (open file :direction :output
:if-exists :append
:if-does-not-exist :create)
dribble-file (make-synonym-stream '*dribble-stream*)
dribbled-input nil
dribbled-output nil
dribbled-error-output nil
dribbled-trace-output nil
dribbled-query-io nil
dribbled-debug-io nil
)
(unless (goes-indirectly-to-terminal *standard-input*)
(setq dribbled-input *standard-input*)
(setq *standard-input* (make-echo-stream *standard-input* dribble-file))
)
(unless (goes-indirectly-to-terminal *standard-output*)
(setq dribbled-output *standard-output*)
(setq *standard-output* (make-broadcast-stream *standard-output* dribble-file))
)
(when (goes-to-terminal *error-output*)
(setq dribbled-error-output *error-output*)
(setq *error-output* (make-broadcast-stream *error-output* dribble-file))
)
(when (goes-to-terminal *trace-output*)
(setq dribbled-trace-output *trace-output*)
(setq *trace-output* (make-broadcast-stream *trace-output* dribble-file))
)
(when (goes-to-terminal *query-io*)
(setq dribbled-query-io *query-io*)
(setq *query-io*
(make-two-way-stream
(make-echo-stream *query-io* dribble-file)
(make-broadcast-stream *query-io* dribble-file)
) ) )
(when (goes-to-terminal *debug-io*)
(setq dribbled-debug-io *debug-io*)
(setq *debug-io*
(make-two-way-stream
(make-echo-stream *debug-io* dribble-file)
(make-broadcast-stream *debug-io* dribble-file)
) ) )
) )
*dribble-stream*
)
(if dribble-file
(progn
(when dribbled-input (setq *standard-input* dribbled-input))
(when dribbled-output (setq *standard-output* dribbled-output))
(when dribbled-error-output (setq *error-output* dribbled-error-output))
(when dribbled-trace-output (setq *trace-output* dribbled-trace-output))
(when dribbled-query-io (setq *query-io* dribbled-query-io))
(when dribbled-debug-io (setq *debug-io* dribbled-debug-io))
(setq dribble-file nil)
(setq dribbled-input nil)
(setq dribbled-output nil)
(setq dribbled-error-output nil)
(setq dribbled-trace-output nil)
(setq dribbled-query-io nil)
(setq dribbled-debug-io nil)
(prog1
*dribble-stream*
(close *dribble-stream*)
(setq *dribble-stream* (make-broadcast-stream))
) )
(warn (ENGLISH "Currently not dribbling."))
) ) ) )
| 6,468 | Common Lisp | .lisp | 107 | 45.738318 | 240 | 0.492918 | ufasoft/lisp | 9 | 4 | 1 | GPL-3.0 | 9/19/2024, 11:26:49 AM (Europe/Amsterdam) | 31209180dfff54fdedef3f782730c3f617e79f5772b2eecf49eb6b9ff7560808 | 11,405 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.