r11097: update date
[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* ((saved-initargs initargs)
238         (parsed (list obj))
239         (name (first initargs) (first initargs))
240         (val (second initargs) (second initargs)))
241       ((null initargs)
242        (apply #'call-next-method parsed))
243     (if (eql name :value-type)
244         (progn
245           (setq val (canonicalize-value-type val))
246           (setq parsed (append parsed (list name val)))
247           (setq parsed (append parsed (list :type
248                                             (value-type-to-lisp-type
249                                              (canonicalize-value-type val))))))
250       (setq parsed (append parsed (list name val))))
251     (setq initargs (cddr initargs))))
252   
253 (defmethod compute-effective-slot-definition :around ((cl hyperobject-class)
254                                                       #+ho-normal-cesd name
255                                                       dsds)
256   (declare (ignore #+ho-normal-cesd name))
257   (let ((esd (call-next-method)))
258     (if (typep esd 'hyperobject-esd)
259         (compute-hyperobject-esd esd dsds)
260         esd)))
261
262 (defun compute-hyperobject-esd (esd dsds)
263   (let* ((dsd (car dsds)))
264     (multiple-value-bind (sql-type sql-length)
265         (value-type-to-sql-type (dsd-value-type dsd))
266       (setf (esd-sql-type esd) sql-type)
267       (setf (esd-sql-length esd) sql-length))
268     (setf (esd-user-name esd)
269           (aif (dsd-user-name dsd)
270                it
271                (string-downcase (symbol-name (slot-definition-name dsd)))))
272     (setf (esd-sql-name esd)
273           (aif (dsd-sql-name dsd)
274                it
275                (lisp-name-to-sql-name (slot-definition-name dsd))))
276     (setf (esd-sql-name esd)
277           (aif (dsd-sql-name dsd)
278                it
279                (lisp-name-to-sql-name (slot-definition-name dsd))))
280     (dolist (name '(value-type print-formatter subobject hyperlink
281                     hyperlink-parameters
282                     description value-constraint indexed null-allowed
283                     unique short-description void-text read-only-groups
284                     hidden-groups unit disable-predicate view-type
285                     list-of-values stored))
286       (setf (slot-value esd name) (slot-value dsd name)))
287     esd))
288
289 (defun lisp-name-to-sql-name (lisp)
290   "Convert a lisp name (atom or list, string or symbol) into a canonical
291 SQL name"
292   (unless (stringp lisp)
293     (setq lisp
294           (typecase lisp
295             (symbol (symbol-name lisp))
296             (t (write-to-string lisp)))))
297   (do* ((len (length lisp))
298         (sql (make-string len))
299         (i 0 (1+ i)))
300       ((= i len) (string-upcase sql))
301     (declare (fixnum i)
302              (simple-string sql))
303     (setf (schar sql i)
304           (let ((c (char lisp i)))
305             (case c
306               ((#\- #\$ #\+ #\#) #\_)
307               (otherwise c))))))
308
309 #+ho-normal-cesd
310 (setq cl:*features* (delete :ho-normal-cesd cl:*features*))
311 #+ho-normal-dsdc
312 (setq cl:*features* (delete :ho-normal-dsdc cl:*features*))
313 #+ho-normal-esdc
314 (setq cl:*features* (delete :ho-normal-esdc cl:*features*))
315
316 (defun lisp-type-is-a-string (type)
317   (or (eq type 'string)
318       (and (listp type) (some #'(lambda (x) (eq x 'string)) type))))
319
320 (defun base-value-type (value-type)
321   (if (atom value-type)
322       value-type
323     (car value-type)))
324
325 (defun value-type-to-lisp-type (value-type)
326   (case (base-value-type value-type)
327     ((:string :cdata :varchar :char)
328      '(or null string))
329     (:datetime
330      '(or null integer))
331     (:character
332      '(or null character))
333     (:fixnum
334      '(or null fixnum))
335     (:boolean
336      '(or null boolean))
337     ((:integer :long-integer)
338      '(or null integer))
339     ((:float :single-float)
340      '(or null single-float))
341     (:double-float
342      '(or null double-float))
343     (otherwise
344      t)))
345
346 (defun value-type-to-sql-type (value-type)
347   "Return two values, the sql type and field length."
348   (let ((type (base-value-type value-type))
349         (length (when (consp value-type)
350                   (cadr value-type))))
351     (values
352      (case type
353        ((:char :character)
354         :char)
355        (:varchar
356         :varchar)
357        ((:fixnum :integer)
358         :integer)
359        (:long-integer
360         :long-integer)
361        (:boolean
362         :boolean)
363        ((:float :single-float)
364         :single-float)
365        (:double-float
366         :double-float)
367        (:datetime
368         :long-integer)
369        (otherwise
370         :text))
371      length)))
372
373 ;;;; Class initialization function
374
375 ;; One entry for each class with lazy readers defined.  The value is a plist mapping
376 ;; slot-name to a lazy reader, each of which is a list of a function and slot-names.
377 (defvar *lazy-readers* (make-hash-table))
378
379 (defmethod slot-unbound ((class hyperobject-class) instance slot-name)
380   (let ((lazy-reader
381          (loop for super in (class-precedence-list class)
382                as lazy-reader = (getf (gethash super *lazy-readers*) slot-name)
383                when lazy-reader return it)))
384     (if lazy-reader
385         (setf (slot-value instance slot-name)
386               (if (atom lazy-reader)
387                   (make-instance lazy-reader)
388                   (apply (car lazy-reader)
389                          (loop for arg-slot-name in (cdr lazy-reader)
390                                collect (slot-value instance arg-slot-name)))))
391         ;; No lazy reader -- defer to regular slot-unbound handling.
392         (call-next-method))))
393
394 ;; The reader is a function and the reader-keys are slot names.  The slot is lazily set to
395 ;; the result of applying the function to the slot-values of those slots, and that value
396 ;; is also returned.
397 (defun ensure-lazy-reader (cl class-name slot-name subobj-class reader
398                            &rest reader-keys)
399   (setf (getf (gethash cl *lazy-readers*) slot-name)
400     (aif subobj-class
401          it
402          (list* reader (copy-list reader-keys)))))
403
404 (defun remove-lazy-reader (class-name slot-name)
405   (setf (getf (gethash (find-class class-name) *lazy-readers*) slot-name)
406     nil))
407
408
409 (defun finalize-subobjects (cl)
410   "Process class subobjects slot"
411   (setf (subobjects cl)
412         (let ((subobjects '()))
413           (dolist (slot (class-slots cl))
414             (let-when
415              (subobj-def (esd-subobject slot))
416              (let ((subobject
417                     (make-instance 'subobject
418                                    :name-class (class-name cl)
419                                    :name-slot (slot-definition-name slot)
420                                    :subobj-class (when (atom subobj-def)
421                                                    subobj-def)
422                                    :lookup (when (listp subobj-def)
423                                              (car subobj-def))
424                                    :lookup-keys (when (listp subobj-def)
425                                                   (cdr subobj-def)))))
426                (unless (eq (lookup subobject) t)
427                  (apply #'ensure-lazy-reader
428                         cl
429                         (name-class subobject) (name-slot subobject)
430                         (subobj-class subobject)
431                         (lookup subobject) (lookup-keys subobject))
432                  (push subobject subobjects)))))
433           ;; sbcl/cmu reverse class-slots compared to the defclass form
434           ;; so re-reverse on cmu/sbcl
435           #+(or cmu sbcl) subobjects
436           #-(or cmu sbcl) (nreverse subobjects)
437           )))
438
439 (defun finalize-class-slots (cl)
440   "Make sure all class slots have an expected value"
441   (unless (user-name cl)
442     (setf (user-name cl) (format nil "~:(~A~)" (class-name cl))))
443
444   (setf (user-name-plural cl)
445         (if (and (consp (user-name cl)) (cadr (user-name cl)))
446             (cadr (user-name cl))
447             (format nil "~A~P" (if (consp (user-name cl))
448                                    (car (user-name cl))
449                                    (user-name cl))
450                     2)))
451
452   (dolist (name '(user-name description version guid sql-name))
453     (awhen (slot-value cl name)
454            (setf (slot-value cl name)
455              (if (listp it)
456                  (car it)
457                it))))
458
459   (unless (sql-name cl)
460     (setf (sql-name cl) (lisp-name-to-sql-name (class-name cl))))
461   )
462
463 (defun finalize-documentation (cl)
464   "Calculate class documentation slot"
465   (let ((*print-circle* nil))
466     (setf (documentation cl 'type)
467           (format nil "Hyperobject~A~A~A~A"
468                   (aif (user-name cl)
469                        (format nil ": ~A" it ""))
470                   (aif (description cl)
471                        (format nil "~%Class description: ~A" it) "")
472                   (aif (subobjects cl)
473                        (format nil "~%Subobjects:~{ ~A~}" (mapcar #'name-slot it)) "")
474                   (aif (default-print-slots cl)
475                        (format nil "~%Default print slots:~{ ~A~}" it) "")
476                   ))))
477
478 (defun finalize-hyperlinks (cl)
479   (let ((hyperlinks '()))
480     (dolist (esd (class-slots cl))
481       (awhen (slot-value esd 'hyperlink)
482              (push
483               (make-instance 'hyperlink
484                              :name (slot-definition-name esd)
485                              :lookup it
486                              :link-parameters (slot-value esd 'hyperlink-parameters))
487               hyperlinks)))
488     ;; cmu/sbcl reverse class-slots compared to the defclass form
489     ;; hyperlinks is already reversed from the dolist/push loop, so re-reverse on sbcl/cmu
490     #-(or cmu sbcl) (setq hyperlinks (nreverse hyperlinks))
491     (setf (slot-value cl 'hyperlinks) hyperlinks)))
492
493 (defun init-hyperobject-class (cl)
494   "Initialize a hyperobject class. Calculates all class slots"
495   (finalize-subobjects cl)
496   (finalize-views cl)
497   (finalize-hyperlinks cl)
498   (finalize-sql cl)
499   (finalize-rules cl)
500   (finalize-class-slots cl)
501   (finalize-documentation cl))
502
503
504 ;;;; *************************************************************************
505 ;;;;  Metaclass Slot Accessors
506 ;;;; *************************************************************************
507
508 (defun find-slot-by-name (cl name)
509   (find name (class-slots cl) :key #'slot-definition-name))
510
511 (defun hyperobject-class-user-name (obj)
512   (user-name (class-of obj)))
513
514 (defun hyperobject-class-user-name-plural (obj)
515   (user-name-plural (class-of obj)))
516
517 (defun hyperobject-class-subobjects (obj)
518   (subobjects (class-of obj)))
519
520 (defun hyperobject-class-hyperlinks (obj)
521   (hyperlinks (class-of obj)))
522
523 (defun hyperobject-class-slots (obj)
524   ;; cmucl/sbcl reverse class-slots
525   #+(or cmu sbcl) (reverse (class-slots (class-of obj)))
526   #-(or cmu sbcl) (class-slots (class-of obj)))
527
528 (defun all-subobjects (obj)
529   "Returns a list of all subobjects in an object"
530   (let ((so-list '()))
531     (dolist (subobj-obj (subobjects (class-of obj)) (nreverse so-list))
532       (dolist (so (funcall (name-slot subobj-obj) obj))
533         (push so so-list)))))