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