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