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