Automated commit for debian release 2.13-1
[hyperobject.git] / mop.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          mop.lisp
6 ;;;; Purpose:       Metaobject Protocol Interface
7 ;;;; Programmer:    Kevin M. Rosenberg
8 ;;;; Date Started:  Apr 2000
9 ;;;;
10 ;;;; This metaclass as functions to classes to allow display
11 ;;;; in Text, HTML, and XML formats. This includes hyperlinking
12 ;;;; capability and sub-objects.
13 ;;;;
14 ;;;; This file is Copyright (c) 2000-2006 by Kevin M. Rosenberg
15 ;;;; *************************************************************************
16
17 (in-package #:hyperobject)
18
19 ;; Main class
20
21 (defclass hyperobject-class (standard-class)
22   ( ;; slots initialized in defclass
23    (user-name :initarg :user-name :initform nil
24               :accessor user-name
25               :documentation "User name for class")
26    (user-name-plural :initarg :user-name-plural :initform nil
27                      :accessor user-name-plural
28                      :documentation "Plural user name for class")
29    (default-print-slots :initarg :default-print-slots :type list :initform nil
30                         :accessor default-print-slots
31                         :documentation "Defaults slots for a view")
32    (description :initarg :description :initform nil
33                 :accessor description
34                 :documentation "Class description")
35    (version :initarg :version :initform nil
36             :accessor version
37             :documentation "Version number for class")
38    (closures :initarg :closures :initform nil
39              :accessor closures
40              :documentation "Closures to call on slot chnages")
41    (sql-name :initarg :sql-name :accessor sql-name :initform nil
42              :documentation "SQL Name for this class")
43    (guid :initarg :guid :accessor guid :initform nil
44          :documentation "ID string for this class")
45
46    ;;; The remainder of these fields are calculated one time
47    ;;; in finalize-inheritence.
48
49    (subobjects :initform nil :accessor subobjects
50                :documentation
51                "List of fields that contain a list of subobjects objects.")
52    (compute-cached-values :initform nil :accessor compute-cached-values
53                          :documentation
54                          "List of fields that contain a list of compute-cached-value objects.")
55    (hyperlinks :type list :initform nil :accessor hyperlinks
56                :documentation "List of fields that have hyperlinks")
57    (direct-rules :type list :initform nil :initarg :direct-rules
58                  :accessor direct-rules
59                  :documentation "List of rules to fire on slot changes.")
60    (direct-views :type list :initform nil :initarg :direct-views
61                  :accessor direct-views
62                  :documentation "List of views")
63    (class-id :type integer :initform (+ (* 1000000 (get-universal-time)) (random 1000000))
64              :accessor class-id
65              :documentation "Unique ID for the class")
66    (default-view :initform nil :initarg :default-view :accessor default-view
67                  :documentation "The default view for a class")
68    (documementation :initform nil :initarg :documentation
69                     :documentation "Documentation string for hyperclass.")
70
71    ;; SQL commands
72    (create-table-cmd :initform nil :reader create-table-cmd)
73    (create-indices-cmds :initform nil :reader create-index-cmds)
74    (drop-table-cmd :initform nil :reader drop-table-cmd)
75
76    (views :type list :initform nil :initarg :views :accessor views
77           :documentation "List of views")
78    (rules :type list :initform nil :initarg :rules :accessor rules
79           :documentation "List of rules")
80    )
81   (:documentation "Metaclass for Markup Language classes."))
82
83 (defclass subobject ()
84   ((name-class :type symbol :initarg :name-class :reader name-class)
85    (name-slot :type symbol :initarg :name-slot :reader name-slot)
86    (lazy-class :type symbol :initarg :lazy-class :reader lazy-class)
87    (lookup :type (or function symbol) :initarg :lookup :reader lookup)
88    (lookup-keys :type list :initarg :lookup-keys :reader lookup-keys))
89   (:documentation "subobject information")
90   (:default-initargs :name-class nil :name-slot nil :lazy-class nil
91                      :lookup nil :lookup-keys nil))
92
93 (defclass compute-cached-value ()
94   ((name-class :type symbol :initarg :name-class :reader name-class)
95    (name-slot :type symbol :initarg :name-slot :reader name-slot)
96    (lazy-class :type symbol :initarg :lazy-class
97                               :reader lazy-class)
98    (lookup :type (or function symbol) :initarg :lookup :reader lookup)
99    (lookup-keys :type list :initarg :lookup-keys :reader lookup-keys))
100   (:documentation "subobject information")
101   (:default-initargs :name-class nil :name-slot nil :lazy-class nil
102                      :lookup nil :lookup-keys nil))
103
104
105 (defmethod print-object ((obj subobject) s)
106   (print-unreadable-object (obj s :type t)
107     (format s "~S" (name-slot obj))))
108
109 (defclass hyperlink ()
110   ((name :type symbol :initform nil :initarg :name :reader name)
111    (lookup
112     ;; The type specifier seems to break sbcl
113     :type (or function symbol)
114     ;;    :type t
115     :initform nil :initarg :lookup :reader lookup)
116    (link-parameters :type list :initform nil :initarg :link-parameters
117                     :reader link-parameters)))
118
119 (defmethod print-object ((obj hyperlink) s)
120   (print-unreadable-object (obj s :type t :identity t)
121     (format s "~S" (name obj))))
122
123 (defmethod validate-superclass ((class hyperobject-class) (superclass standard-class))
124   t)
125
126
127 (declaim (inline delistify))
128 (defun delistify (list)
129   "Some MOPs, like openmcl 0.14.2, cons attribute values in a list."
130   (if (listp list)
131       (car list)
132     list))
133
134 (defun remove-keyword-arg (arglist akey)
135   (let ((mylist arglist)
136         (newlist ()))
137     (labels ((pop-arg (alist)
138              (let ((arg (pop alist))
139                    (val (pop alist)))
140                (unless (equal arg akey)
141                  (setf newlist (append (list arg val) newlist)))
142                (when alist (pop-arg alist)))))
143       (pop-arg mylist))
144     newlist))
145
146 (defun remove-keyword-args (arglist akeys)
147   (let ((mylist arglist)
148         (newlist ()))
149     (labels ((pop-arg (alist)
150              (let ((arg (pop alist))
151                    (val (pop alist)))
152                (unless (find arg akeys)
153                  (setf newlist (append (list arg val) newlist)))
154                (when alist (pop-arg alist)))))
155       (pop-arg mylist))
156     newlist))
157
158
159 (defmethod shared-initialize :around ((class hyperobject-class) slot-names
160                                         &rest initargs
161                                         &key direct-superclasses
162                                         user-name sql-name name description
163                                         &allow-other-keys)
164   ;(format t "ii ~S ~S ~S ~S ~S~%" initargs base-table direct-superclasses user-name sql-name)
165   (let ((root-class (find-class 'hyperobject nil))
166         (vmc 'hyperobject-class)
167         user-name-plural user-name-str sql-name-str)
168     ;; when does CLSQL pass :qualifier to initialize instance?
169     (setq user-name-str
170           (if user-name
171               (delistify user-name)
172             (and name (format nil "~:(~A~)" name))))
173
174     (setq sql-name-str
175           (if sql-name
176               (delistify sql-name)
177             (and name (lisp-name-to-sql-name name))))
178
179     (if sql-name
180         (delistify sql-name)
181       (and name (lisp-name-to-sql-name name)))
182
183     (setq description (delistify description))
184
185     (setq user-name-plural
186       (if (and (consp user-name) (second user-name))
187           (second user-name)
188         (and user-name-str (format nil "~A~P" user-name-str 2))))
189
190     (flet ((do-call-next-method (direct-superclasses)
191                                 (let ((fn-args (list class slot-names :direct-superclasses direct-superclasses))
192                                       (rm-args '(:direct-superclasses)))
193                                   (when user-name-str
194                                     (setq fn-args (nconc fn-args (list :user-name user-name-str)))
195                                     (push :user-name rm-args))
196                                   (when user-name-plural
197                                     (setq fn-args (nconc fn-args (list :user-name-plural user-name-plural)))
198                                     (push :user-name-plural rm-args))
199                                   (when sql-name-str
200                                     (setq fn-args (nconc fn-args (list :sql-name sql-name-str)))
201                                     (push :sql-name rm-args))
202                                   (when description
203                                     (setq fn-args (nconc fn-args (list :description description)))
204                                     (push :description rm-args))
205                                   (setq fn-args (nconc fn-args (remove-keyword-args initargs rm-args)))
206                                   (apply #'call-next-method fn-args))))
207       (if root-class
208           (if (some #'(lambda (super) (typep super vmc))
209                     direct-superclasses)
210               (do-call-next-method direct-superclasses)
211             (do-call-next-method          direct-superclasses #+nil (append (list root-class)
212                                                                             direct-superclasses)))
213         (do-call-next-method direct-superclasses)))))
214
215
216 (defmethod finalize-inheritance :after ((cl hyperobject-class))
217   "Initialize a hyperobject class. Calculates all class slots"
218   (finalize-subobjects cl)
219   (finalize-compute-cached cl)
220   (init-hyperobject-class cl))
221
222 (eval-when (:compile-toplevel :load-toplevel :execute)
223   (when (>= (length (generic-function-lambda-list
224                      (ensure-generic-function
225                       'compute-effective-slot-definition)))
226             3)
227     (pushnew :ho-normal-cesd cl:*features*))
228
229     (when (>= (length (generic-function-lambda-list
230                        (ensure-generic-function
231                         'direct-slot-definition-class)))
232             3)
233       (pushnew :ho-normal-dsdc cl:*features*))
234
235     (when (>= (length (generic-function-lambda-list
236                        (ensure-generic-function
237                         'effective-slot-definition-class)))
238               3)
239       (pushnew :ho-normal-esdc cl:*features*)))
240
241 (defmethod direct-slot-definition-class ((cl hyperobject-class)
242                                          #+ho-normal-dsdc &rest iargs)
243   (declare (ignore iargs))
244   (find-class 'hyperobject-dsd))
245
246 (defmethod effective-slot-definition-class ((cl hyperobject-class)
247                                             #+ho-normal-esdc &rest iargs)
248   (declare (ignore iargs))
249   (find-class 'hyperobject-esd))
250
251 ;;; Slot definitions
252
253 (eval-when (:compile-toplevel :load-toplevel :execute)
254   (defmacro process-class-option (slot-name &optional required)
255     #+lispworks
256     `(defmethod clos:process-a-class-option ((class hyperobject-class)
257                                              (name (eql ,slot-name))
258                                              value)
259       (when (and ,required (null value))
260         (error "hyperobject class slot ~A must have a value" name))
261       (list name `',value))
262     #+(or allegro sbcl cmu scl openmcl)
263     (declare (ignore slot-name required))
264     )
265
266   (defmacro process-slot-option (slot-name)
267     #+lispworks
268     `(defmethod clos:process-a-slot-option ((class hyperobject-class)
269                                             (option (eql ,slot-name))
270                                             value
271                                             already-processed-options
272                                             slot)
273       (list* option `',value already-processed-options))
274     #-lispworks
275     (declare (ignore slot-name))
276     )
277
278   (dolist (option *class-options*)
279     (eval `(process-class-option ,option)))
280   (dolist (option *slot-options*)
281     (eval `(process-slot-option ,option)))
282
283   (eval
284    `(defclass hyperobject-dsd (standard-direct-slot-definition)
285      (,@(mapcar #'(lambda (x)
286                     `(,(intern (symbol-name x))
287                       :initform nil))
288                 *slot-options-no-initarg*)
289       ,@(mapcar #'(lambda (x)
290                     `(,(intern (symbol-name x))
291                       :initarg
292                       ,(intern (symbol-name x) (symbol-name :keyword))
293                       :initform nil
294                       :accessor
295                       ,(intern (concatenate 'string
296                                             (symbol-name :dsd-)
297                                             (symbol-name x)))))
298                 *slot-options*))))
299   (eval
300    `(defclass hyperobject-esd (standard-effective-slot-definition)
301      (,@(mapcar #'(lambda (x)
302                     `(,(intern (symbol-name x))
303                       :initarg
304                       ,(intern (symbol-name x) (symbol-name :keyword))
305                       :initform nil
306                       :accessor
307                       ,(intern (concatenate 'string
308                                             (symbol-name :esd-)
309                                             (symbol-name x)))))
310                 (append *slot-options* *slot-options-no-initarg*)))))
311   ) ;; eval-when
312
313 (defun intern-in-keyword (obj)
314   (cond
315     ((null obj)
316      nil)
317     ((eq t obj)
318      t)
319     ((atom obj)
320      (intern (symbol-name obj) (find-package 'keyword)))
321     ((consp obj)
322      (cons (intern-in-keyword (car obj) ) (intern-in-keyword (cdr obj))))
323     (t
324      obj)))
325
326 (defun canonicalize-value-type (vt)
327   (typecase vt
328     (atom
329      (ensure-keyword vt))
330     (cons
331      (list (ensure-keyword (car vt)) (cadr vt)))
332     (t
333      t)))
334
335
336 (defmethod compute-effective-slot-definition :around ((cl hyperobject-class)
337                                                       #+ho-normal-cesd name
338                                                       dsds)
339   (declare (ignore #+ho-normal-cesd name))
340   (let ((esd (call-next-method)))
341     (if (typep esd 'hyperobject-esd)
342         (compute-hyperobject-esd esd dsds)
343         esd)))
344
345 (defun compute-hyperobject-esd (esd dsds)
346   (let* ((dsd (car dsds)))
347     (multiple-value-bind (sql-type sql-length)
348         (value-type-to-sql-type (dsd-value-type dsd))
349       (setf (esd-sql-type esd) sql-type)
350       (setf (esd-sql-length esd) sql-length))
351     (setf (esd-user-name esd)
352           (aif (dsd-user-name dsd)
353                it
354                (string-downcase (symbol-name (slot-definition-name dsd)))))
355     (setf (esd-sql-name esd)
356           (aif (dsd-sql-name dsd)
357                it
358                (lisp-name-to-sql-name (slot-definition-name dsd))))
359     (setf (esd-sql-name esd)
360           (aif (dsd-sql-name dsd)
361                it
362                (lisp-name-to-sql-name (slot-definition-name dsd))))
363     (dolist (name '(value-type print-formatter subobject hyperlink
364                     hyperlink-parameters unbound-lookup
365                     description value-constraint indexed null-allowed
366                     unique short-description void-text read-only-groups
367                     hidden-groups unit disable-predicate view-type
368                     list-of-values compute-cached-value stored))
369       (setf (slot-value esd name) (slot-value dsd name)))
370     esd))
371
372 (defun lisp-name-to-sql-name (lisp)
373   "Convert a lisp name (atom or list, string or symbol) into a canonical
374 SQL name"
375   (unless (stringp lisp)
376     (setq lisp
377           (typecase lisp
378             (symbol (symbol-name lisp))
379             (t (write-to-string lisp)))))
380   (do* ((len (length lisp))
381         (sql (make-string len))
382         (i 0 (1+ i)))
383       ((= i len) (string-upcase sql))
384     (declare (fixnum i)
385              (simple-string sql))
386     (setf (schar sql i)
387           (let ((c (char lisp i)))
388             (case c
389               ((#\- #\$ #\+ #\#) #\_)
390               (otherwise c))))))
391
392 #+ho-normal-cesd
393 (setq cl:*features* (delete :ho-normal-cesd cl:*features*))
394 #+ho-normal-dsdc
395 (setq cl:*features* (delete :ho-normal-dsdc cl:*features*))
396 #+ho-normal-esdc
397 (setq cl:*features* (delete :ho-normal-esdc cl:*features*))
398
399 (defun lisp-type-is-a-string (type)
400   (or (eq type 'string)
401       (and (listp type) (some #'(lambda (x) (eq x 'string)) type))))
402
403 (defun value-type-is-a-string (type)
404   (or (eq type 'string)
405       (eq type 'cdata)
406       (and (listp type) (some #'(lambda (x) (or (eq x 'string)
407                                                 (eq x 'cdata)))
408                               type))))
409
410 (defun base-value-type (value-type)
411   (if (atom value-type)
412       value-type
413     (car value-type)))
414
415 (defun value-type-to-lisp-type (value-type)
416   (case (base-value-type value-type)
417     ((:string :cdata :varchar :char)
418      '(or null string))
419     (:datetime
420      '(or null integer))
421     (:character
422      '(or null character))
423     (:fixnum
424      '(or null fixnum))
425     (:boolean
426      '(or null boolean))
427     ((:integer :long-integer)
428      '(or null integer))
429     ((:float :single-float)
430      '(or null single-float))
431     (:double-float
432      '(or null double-float))
433     (otherwise
434      t)))
435
436 (defun value-type-to-sql-type (value-type)
437   "Return two values, the sql type and field length."
438   (let ((type (base-value-type value-type))
439         (length (when (consp value-type)
440                   (cadr value-type))))
441     (values
442      (case type
443        ((:char :character)
444         :char)
445        (:varchar
446         :varchar)
447        ((:fixnum :integer)
448         :integer)
449        (:long-integer
450         :long-integer)
451        (:boolean
452         :boolean)
453        ((:float :single-float)
454         :single-float)
455        (:double-float
456         :double-float)
457        (:datetime
458         :long-integer)
459        (otherwise
460         :text))
461      length)))
462
463 ;;;; Class initialization function
464
465 ;; One entry for each class with lazy readers defined.  The value is a plist mapping
466 ;; slot-name to a lazy reader, each of which is a list of a function and slot-names.
467 (defvar *lazy-readers* (make-hash-table))
468
469 (defmethod slot-unbound ((class hyperobject-class) instance slot-name)
470   (let ((lazy-reader
471          (loop for super in (class-precedence-list class)
472                as lazy-reader = (getf (gethash super *lazy-readers*) slot-name)
473                when lazy-reader return it)))
474     (if lazy-reader
475         (setf (slot-value instance slot-name)
476               (if (atom lazy-reader)
477                   (make-instance lazy-reader)
478                   (apply (car lazy-reader)
479                          (loop for arg-slot-name in (cdr lazy-reader)
480                                collect (slot-value instance arg-slot-name)))))
481         ;; No lazy reader -- defer to regular slot-unbound handling.
482         (call-next-method))))
483
484 ;; The reader is a function and the reader-keys are slot names.  The slot is lazily set to
485 ;; the result of applying the function to the slot-values of those slots, and that value
486 ;; is also returned.
487 (defun ensure-lazy-reader (cl class-name slot-name lazy-class reader
488                            &rest reader-keys)
489   (declare (ignore class-name))
490   (setf (getf (gethash cl *lazy-readers*) slot-name)
491     (aif lazy-class
492          it
493          (list* reader (copy-list reader-keys)))))
494
495 (defun remove-lazy-reader (class-name slot-name)
496   (setf (getf (gethash (find-class class-name) *lazy-readers*) slot-name)
497     nil))
498
499
500 (defun store-lazily-computed-objects (cl slot esd-accessor obj-class)
501   (setf (slot-value cl slot)
502         (let ((objs '()))
503           (dolist (slot (class-slots cl))
504             (let-when
505              (def (funcall esd-accessor slot))
506              (let ((obj (make-instance obj-class
507                                        :name-class (class-name cl)
508                                        :name-slot (slot-definition-name slot)
509                                        :lazy-class (when (atom def)
510                                                      def)
511                                        :lookup (when (listp def)
512                                                  (car def))
513                                        :lookup-keys (when (listp def)
514                                                       (cdr def)))))
515                (unless (eq (lookup obj) t)
516                  (apply #'ensure-lazy-reader
517                   cl
518                   (name-class obj) (name-slot obj)
519                   (lazy-class obj)
520                   (lookup obj) (lookup-keys obj))
521                  (push obj objs)))))
522           ;; sbcl/cmu reverse class-slots compared to the defclass form
523           ;; so re-reverse on cmu/sbcl
524           #+(or cmu sbcl) objs
525           #-(or cmu sbcl) (nreverse objs)
526           )))
527
528 (defun finalize-subobjects (cl)
529   (store-lazily-computed-objects cl 'subobjects 'esd-subobject 'subobject))
530
531 (defun finalize-compute-cached (cl)
532   (store-lazily-computed-objects cl 'compute-cached-values
533                                  'esd-compute-cached-value 'compute-cached-value))
534
535
536 (defun finalize-documentation (cl)
537   "Calculate class documentation slot"
538   (let ((*print-circle* nil))
539     (setf (documentation cl 'type)
540           (format nil "Hyperobject~A~A~A~A"
541                   (aif (user-name cl)
542                        (format nil ": ~A" it) "")
543                   (aif (description cl)
544                        (format nil "~%Class description: ~A" it) "")
545                   (aif (subobjects cl)
546                        (format nil "~%Subobjects:~{ ~A~}" (mapcar #'name-slot it)) "")
547                   (aif (default-print-slots cl)
548                        (format nil "~%Default print slots:~{ ~A~}" it) "")
549                   ))))
550
551 (defun finalize-hyperlinks (cl)
552   (let ((hyperlinks '()))
553     (dolist (esd (class-slots cl))
554       (awhen (slot-value esd 'hyperlink)
555              (push
556               (make-instance 'hyperlink
557                              :name (slot-definition-name esd)
558                              :lookup it
559                              :link-parameters (slot-value esd 'hyperlink-parameters))
560               hyperlinks)))
561     ;; cmu/sbcl reverse class-slots compared to the defclass form
562     ;; hyperlinks is already reversed from the dolist/push loop, so re-reverse on sbcl/cmu
563     #-(or cmu sbcl) (setq hyperlinks (nreverse hyperlinks))
564     (setf (slot-value cl 'hyperlinks) hyperlinks)))
565
566 (defun init-hyperobject-class (cl)
567   "Initialize a hyperobject class. Calculates all class slots"
568   (finalize-views cl)
569   (finalize-hyperlinks cl)
570   (finalize-sql cl)
571   (finalize-rules cl)
572   (finalize-documentation cl))
573
574
575
576
577 ;;;; *************************************************************************
578 ;;;;  Metaclass Slot Accessors
579 ;;;; *************************************************************************
580
581 (defun find-slot-by-name (cl name)
582   (find name (class-slots cl) :key #'slot-definition-name))
583
584 (defun hyperobject-class-user-name (obj)
585   (user-name (class-of obj)))
586
587 (defun hyperobject-class-user-name-plural (obj)
588   (user-name-plural (class-of obj)))
589
590 (defun hyperobject-class-subobjects (obj)
591   (subobjects (class-of obj)))
592
593 (defun hyperobject-class-hyperlinks (obj)
594   (hyperlinks (class-of obj)))
595
596 (defun hyperobject-class-slots (obj)
597   ;; cmucl/sbcl reverse class-slots
598   #+(or cmu sbcl) (reverse (class-slots (class-of obj)))
599   #-(or cmu sbcl) (class-slots (class-of obj)))
600
601 (defun all-subobjects (obj)
602   "Returns a list of all subobjects in an object"
603   (let ((so-list '()))
604     (dolist (subobj-obj (subobjects (class-of obj)) (nreverse so-list))
605       (dolist (so (funcall (name-slot subobj-obj) obj))
606         (push so so-list)))))