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