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