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