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