]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - define-proto.lisp
At Sergey's request, make some of the names better:
[cl-protobufs.git] / define-proto.lisp
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;;                                                                  ;;;
3 ;;; Confidential and proprietary information of ITA Software, Inc.   ;;;
4 ;;;                                                                  ;;;
5 ;;; Copyright (c) 2012 ITA Software, Inc.  All rights reserved.      ;;;
6 ;;;                                                                  ;;;
7 ;;; Original author: Scott McKay                                     ;;;
8 ;;;                                                                  ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
10
11 (in-package "PROTO-IMPL")
12
13
14 ;;; Protocol buffer defining macros
15
16 ;; Define a schema named 'type', corresponding to a .proto file of that name
17 (defmacro define-schema (type (&key name syntax package lisp-package import optimize
18                                     options documentation)
19                          &body messages &environment env)
20   "Define a schema named 'type', corresponding to a .proto file of that name.
21    'name' can be used to override the defaultly generated Protobufs name.
22    'syntax' and 'package' are as they would be in a .proto file.
23    'lisp-package' can be used to specify a Lisp package if it is different from
24    the Protobufs package given by 'package'.
25    'import' is a list of pathname strings to be imported.
26    'optimize' can be either :space (the default) or :speed; if it is :speed, the
27    serialization code will be much faster, but much less compact.
28    'options' is a property list, i.e., (\"key1\" \"val1\" \"key2\" \"val2\" ...).
29
30    The body consists of 'define-enum', 'define-message' or 'define-service' forms."
31   (let* ((name     (or name (class-name->proto type)))
32          (package  (and package (if (stringp package) package (string-downcase (string package)))))
33          (lisp-pkg (and lisp-package (if (stringp lisp-package) lisp-package (string lisp-package))))
34          (options  (loop for (key val) on options by #'cddr
35                          collect (make-instance 'protobuf-option
36                                    :name  (if (symbolp key) (slot-name->proto key) key)
37                                    :value val)))
38          (imports  (if (listp import) import (list import)))
39          (schema   (make-instance 'protobuf-schema
40                      :class    type
41                      :name     name
42                      :syntax   (or syntax "proto2")
43                      :package  package
44                      :lisp-package (or lisp-pkg package)
45                      :imports  imports
46                      :options  (if optimize
47                                  (append options (list (make-instance 'protobuf-option
48                                                          :name  "optimize_for"
49                                                          :value (if (eq optimize :speed) "SPEED" "CODE_SIZE")
50                                                          :type  'symbol)))
51                                  options)
52                      :documentation documentation))
53          (*protobuf* schema)
54          (*protobuf-package* (or (find-package lisp-pkg)
55                                  (find-package (string-upcase lisp-pkg))
56                                  *package*)))
57     (apply #'process-imports schema imports)
58     (with-collectors ((forms collect-form))
59       (dolist (msg messages)
60         (assert (and (listp msg)
61                      (member (car msg) '(define-enum define-message define-extend define-service))) ()
62                 "The body of ~S must be one of ~{~S~^ or ~}"
63                 'define-schema '(define-enum define-message define-extend define-service))
64         ;; The macro-expander will return a form that consists
65         ;; of 'progn' followed by a symbol naming what we've expanded
66         ;; (define-enum, define-message, define-extend, define-service),
67         ;; followed by the Lisp model object created by the defining form,
68         ;; followed by other defining forms (e.g., deftype, defclass)
69         (destructuring-bind (&optional progn model-type model definers)
70             (macroexpand-1 msg env)
71           (assert (eq progn 'progn) ()
72                   "The macroexpansion for ~S failed" msg)
73           (map () #'collect-form definers)
74           (ecase model-type
75             ((define-enum)
76              (setf (proto-enums schema) (nconc (proto-enums schema) (list model))))
77             ((define-message define-extend)
78              (setf (proto-parent model) schema)
79              (setf (proto-messages schema) (nconc (proto-messages schema) (list model)))
80              (when (eq (proto-message-type model) :extends)
81                (setf (proto-extenders schema) (nconc (proto-extenders schema) (list model)))))
82             ((define-service)
83              (setf (proto-services schema) (nconc (proto-services schema) (list model)))))))
84       (let ((var (intern (format nil "*~A*" type) *protobuf-package*)))
85         `(progn
86            ,@forms
87            (defvar ,var nil)
88            (let* ((old-schema ,var)
89                   (new-schema ,schema))
90              (when old-schema
91                (multiple-value-bind (upgradable warnings)
92                    (schema-upgradable old-schema new-schema)
93                  (unless upgradable
94                    (protobufs-warn "The old schema for ~S (~A) can't be safely upgraded; proceeding anyway"
95                                    ',type ',name)
96                    (map () #'protobufs-warn warnings))))
97              (setq ,var new-schema)
98              (record-protobuf ,var)
99              ,@(with-collectors ((messages collect-message))
100                  (labels ((collect-messages (message)
101                             (collect-message message)
102                             (map () #'collect-messages (proto-messages message))))
103                    (map () #'collect-messages (proto-messages schema)))
104                  (append 
105                    (mapcar #'(lambda (m) `(record-protobuf ,m)) messages)
106                    (when (eq optimize :speed)
107                      (append (mapcar #'generate-object-size  messages)
108                              (mapcar #'generate-serializer   messages)
109                              (mapcar #'generate-deserializer messages)))))
110              ,var))))))
111
112 ;; Define an enum type named 'type' and a Lisp 'deftype'
113 (defmacro define-enum (type (&key name conc-name alias-for options documentation)
114                        &body values)
115   "Define a Protobufs enum type and a Lisp 'deftype' named 'type'.
116    'name' can be used to override the defaultly generated Protobufs enum name.
117    'conc-name' will be used as the prefix to the Lisp enum names, if it's supplied.
118    If 'alias-for' is given, no Lisp 'deftype' will be defined. Instead, the enum
119    will be used as an alias for an enum type that already exists in Lisp.
120    'options' is a set of keyword/value pairs, both of which are strings.
121
122    The body consists of the enum values in the form 'name' or (name index)."
123   (let* ((name    (or name (class-name->proto type)))
124          (options (loop for (key val) on options by #'cddr
125                         collect (make-instance 'protobuf-option
126                                   :name  (if (symbolp key) (slot-name->proto key) key)
127                                   :value val)))
128          (index -1)
129          (enum  (make-instance 'protobuf-enum
130                   :class  type
131                   :name   name
132                   :alias-for alias-for
133                   :options options
134                   :documentation documentation)))
135     (with-collectors ((vals  collect-val)
136                       (forms collect-form))
137       (dolist (val values)
138         (let* ((idx  (if (listp val) (second val) (incf index)))
139                (name (if (listp val) (first val)  val))
140                (val-name  (kintern (if conc-name (format nil "~A~A" conc-name name) (symbol-name name))))
141                (enum-name (if conc-name (format nil "~A~A" conc-name name) (symbol-name name)))
142                (enum-val  (make-instance 'protobuf-enum-value
143                             :name  (enum-name->proto enum-name)
144                             :index idx
145                             :value val-name)))
146           (collect-val val-name)
147           (setf (proto-values enum) (nconc (proto-values enum) (list enum-val)))))
148       (if alias-for
149         ;; If we've got an alias, define a a type that is the subtype of
150         ;; the Lisp enum so that typep and subtypep work
151         (unless (eq type alias-for)
152           (collect-form `(deftype ,type () ',alias-for)))
153         ;; If no alias, define the Lisp enum type now
154         (collect-form `(deftype ,type () '(member ,@vals))))
155       `(progn
156          define-enum
157          ,enum
158          ,forms))))
159
160 ;; Define a message named 'name' and a Lisp 'defclass'
161 (defmacro define-message (type (&key name conc-name alias-for options documentation)
162                           &body fields &environment env)
163   "Define a message named 'type' and a Lisp 'defclass'.
164    'name' can be used to override the defaultly generated Protobufs message name.
165    The body consists of fields, or 'define-enum' or 'define-message' forms.
166    'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
167    If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
168    used as an alias for a class that already exists in Lisp. This feature is intended
169    to be used to define messages that will be serialized from existing Lisp classes;
170    unless you get the slot names or readers exactly right for each field, it will be
171    the case that trying to (de)serialize into a Lisp object won't work.
172    'options' is a set of keyword/value pairs, both of which are strings.
173
174    Fields take the form (slot &key type name default reader)
175    'slot' can be either a symbol giving the field name, or a list whose
176    first element is the slot name and whose second element is the index.
177    'type' is the type of the slot.
178    'name' can be used to override the defaultly generated Protobufs field name.
179    'default' is the default value for the slot.
180    'reader' is a Lisp slot reader function to use to get the value, instead of
181    using 'slot-value'; this is often used when aliasing an existing class.
182    'writer' is a Lisp slot writer function to use to set the value."
183   (let* ((name    (or name (class-name->proto type)))
184          (options (loop for (key val) on options by #'cddr
185                         collect (make-instance 'protobuf-option
186                                   :name  (if (symbolp key) (slot-name->proto key) key)
187                                   :value val)))
188          (message (make-instance 'protobuf-message
189                     :class type
190                     :name  name
191                     :parent *protobuf*
192                     :alias-for alias-for
193                     :conc-name (and conc-name (string conc-name))
194                     :options  options
195                     :documentation documentation))
196          (index 0)
197          (*protobuf* message))
198     (with-collectors ((slots collect-slot)
199                       (forms collect-form))
200       (dolist (field fields)
201         (case (car field)
202           ((define-enum define-message define-extend define-extension define-group)
203            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
204                (macroexpand-1 field env)
205              (assert (eq progn 'progn) ()
206                      "The macroexpansion for ~S failed" field)
207              (map () #'collect-form definers)
208              (ecase model-type
209                ((define-enum)
210                 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
211                ((define-message define-extend)
212                 (setf (proto-parent model) message)
213                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
214                 (when (eq (proto-message-type model) :extends)
215                   (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
216                ((define-group)
217                 (setf (proto-parent model) message)
218                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
219                 (when extra-slot
220                   (collect-slot extra-slot))
221                 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
222                ((define-extension)
223                 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
224           (otherwise
225            (multiple-value-bind (field slot idx)
226                (process-field field index :conc-name conc-name :alias-for alias-for)
227              (assert (not (find (proto-index field) (proto-fields message) :key #'proto-index)) ()
228                      "The field ~S overlaps with another field in ~S"
229                      (proto-value field) (proto-class message))
230              (setq index idx)
231              (when slot
232                (collect-slot slot))
233              (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
234       (if alias-for
235         ;; If we've got an alias, define a a type that is the subtype of
236         ;; the Lisp class that typep and subtypep work
237         (unless (or (eq type alias-for) (find-class type nil))
238           (collect-form `(deftype ,type () ',alias-for)))
239         ;; If no alias, define the class now
240         (collect-form `(defclass ,type () (,@slots)
241                          ,@(and documentation `((:documentation ,documentation))))))
242       `(progn
243          define-message
244          ,message
245          ,forms))))
246
247 (defmacro define-extension (from to)
248   "Define an extension range within a message.
249    The \"body\" is the start and end of the range, both inclusive."
250   `(progn
251      define-extension
252      ,(make-instance 'protobuf-extension
253         :from from
254         :to   (if (eq to 'max) #.(1- (ash 1 29)) to))
255      ()))
256
257 (defmacro define-extend (type (&key name options documentation)
258                          &body fields &environment env)
259   "Define an extension to the message named 'type'.
260    'name' can be used to override the defaultly generated Protobufs message name.
261    The body consists only  of fields.
262    'options' is a set of keyword/value pairs, both of which are strings.
263
264    Fields take the form (slot &key type name default reader)
265    'slot' can be either a symbol giving the field name, or a list whose
266    first element is the slot name and whose second element is the index.
267    'type' is the type of the slot.
268    'name' can be used to override the defaultly generated Protobufs field name.
269    'default' is the default value for the slot.
270    'reader' is a Lisp slot reader function to use to get the value, instead of
271    using 'slot-value'; this is often used when aliasing an existing class.
272    'writer' is a Lisp slot writer function to use to set the value."
273   (let* ((name    (or name (class-name->proto type)))
274          (options (loop for (key val) on options by #'cddr
275                         collect (make-instance 'protobuf-option
276                                   :name  (if (symbolp key) (slot-name->proto key) key)
277                                   :value val)))
278          (message   (find-message *protobuf* name))
279          (conc-name (and message (proto-conc-name message)))
280          (alias-for (and message (proto-alias-for message)))
281          (extends (and message
282                        (make-instance 'protobuf-message
283                          :class  type
284                          :name   name
285                          :parent (proto-parent message)
286                          :conc-name conc-name
287                          :alias-for alias-for
288                          :enums    (copy-list (proto-enums message))
289                          :messages (copy-list (proto-messages message))
290                          :fields   (copy-list (proto-fields message))
291                          :options  (or options (copy-list (proto-options message)))
292                          :extensions (copy-list (proto-extensions message))
293                          :message-type :extends         ;this message is an extension
294                          :documentation documentation)))
295          (*protobuf* extends)
296          (index 0))
297     (assert message ()
298             "There is no message named ~A to extend" name)
299     (assert (eq type (proto-class message)) ()
300             "The type ~S doesn't match the type of the message being extended ~S"
301             type message)
302     (with-collectors ((forms collect-form))
303       (dolist (field fields)
304         (assert (not (member (car field)
305                              '(define-enum define-message define-extend define-extension))) ()
306                 "The body of ~S can only contain field and group definitions" 'define-extend)
307         (case (car field)
308           ((define-group)
309            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
310                (macroexpand-1 field env)
311              (assert (eq progn 'progn) ()
312                      "The macroexpansion for ~S failed" field)
313              (map () #'collect-form definers)
314              (ecase model-type
315                ((define-group)
316                 (setf (proto-parent model) extends)
317                 (setf (proto-messages extends) (nconc (proto-messages extends) (list model)))
318                 (when extra-slot
319                   ;;--- Fix all this duplicated code!
320                   (let* ((inits  (cdr extra-slot))
321                          (sname  (car extra-slot))
322                          (stable (fintern "~A-VALUES" sname))
323                          (stype  (getf inits :type))
324                          (reader (or (getf inits :accessor)
325                                      (getf inits :reader)
326                                      (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
327                                              *protobuf-package*)))
328                          (writer (or (getf inits :writer)
329                                      (intern (format nil "~A-~A" reader 'setter)
330                                              *protobuf-package*)))
331                          (default (getf inits :initform)))
332                     (collect-form `(without-redefinition-warnings ()
333                                      (let ((,stable (make-hash-table :test #'eq :weak t)))
334                                        ,@(and reader `((defmethod ,reader ((object ,type))
335                                                          (gethash object ,stable ,default))))
336                                        ,@(and writer `((defmethod ,writer ((object ,type) value)
337                                                          (declare (type ,stype value))
338                                                          (setf (gethash object ,stable) value))))
339                                        ;; For Python compatibility
340                                        (defmethod get-extension ((object ,type) (slot (eql ',sname)))
341                                          (values (gethash object ,stable ,default)))
342                                        (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
343                                          (setf (gethash object ,stable) value))
344                                        (defmethod has-extension ((object ,type) (slot (eql ',sname)))
345                                          (multiple-value-bind (value foundp)
346                                              (gethash object ,stable ,default)
347                                            (declare (ignore value))
348                                            foundp))
349                                        (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
350                                          (remhash object ,stable))
351                                        ,@(and writer `((defsetf ,reader ,writer))))))))
352                 (setf (proto-message-type extra-field) :extends) ;this field is an extension
353                 (setf (proto-fields extends) (nconc (proto-fields extends) (list extra-field)))
354                 (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list extra-field)))))))
355           (otherwise
356            (multiple-value-bind (field slot idx)
357                (process-field field index :conc-name conc-name :alias-for alias-for)
358              (assert (not (find (proto-index field) (proto-fields extends) :key #'proto-index)) ()
359                      "The field ~S overlaps with another field in ~S"
360                      (proto-value field) (proto-class extends))
361              (assert (index-within-extensions-p idx message) ()
362                      "The index ~D is not in range for extending ~S"
363                      idx (proto-class message))
364              (setq index idx)
365              (when slot
366                (let* ((inits  (cdr slot))
367                       (sname  (car slot))
368                       (stable (fintern "~A-VALUES" sname))
369                       (stype  (getf inits :type))
370                       (reader (or (getf inits :accessor)
371                                   (getf inits :reader)
372                                   (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
373                                           *protobuf-package*)))
374                       (writer (or (getf inits :writer)
375                                   (intern (format nil "~A-~A" reader 'setter)
376                                           *protobuf-package*)))
377                       (default (getf inits :initform)))
378                  ;; For the extended slots, each slot gets its own table
379                  ;; keyed by the object, which lets us avoid having a slot in each
380                  ;; instance that holds a table keyed by the slot name
381                  ;; Multiple 'define-extends' on the same class in the same image
382                  ;; will result in harmless redefinitions, so squelch the warnings
383                  ;;--- Maybe these methods need to be defined in 'define-message'?
384                  (collect-form `(without-redefinition-warnings ()
385                                   (let ((,stable (make-hash-table :test #'eq :weak t)))
386                                     ,@(and reader `((defmethod ,reader ((object ,type))
387                                                       (gethash object ,stable ,default))))
388                                     ,@(and writer `((defmethod ,writer ((object ,type) value)
389                                                       (declare (type ,stype value))
390                                                       (setf (gethash object ,stable) value))))
391                                     ;; For Python compatibility
392                                     (defmethod get-extension ((object ,type) (slot (eql ',sname)))
393                                       (values (gethash object ,stable ,default)))
394                                     (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
395                                       (setf (gethash object ,stable) value))
396                                     (defmethod has-extension ((object ,type) (slot (eql ',sname)))
397                                       (multiple-value-bind (value foundp)
398                                           (gethash object ,stable ,default)
399                                         (declare (ignore value))
400                                         foundp))
401                                     (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
402                                       (remhash object ,stable))
403                                     ,@(and writer `((defsetf ,reader ,writer))))))
404                  ;; This so that (de)serialization works
405                  (setf (proto-reader field) reader
406                        (proto-writer field) writer)))
407              (setf (proto-message-type field) :extends)         ;this field is an extension
408              (setf (proto-fields extends) (nconc (proto-fields extends) (list field)))
409              (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list field)))))))
410       `(progn
411          define-extend
412          ,extends
413          ,forms))))
414
415 (defun index-within-extensions-p (index message)
416   (let ((extensions (proto-extensions message)))
417     (some #'(lambda (ext)
418               (and (i>= index (proto-extension-from ext))
419                    (i<= index (proto-extension-to ext))))
420           extensions)))
421
422 (defmacro define-group (type (&key index arity name conc-name alias-for options documentation)
423                         &body fields &environment env)
424   "Define a message named 'type' and a Lisp 'defclass', *and* a field named type.
425    This is deprecated in Protobufs, but if you have to use it, you must give
426    'index' as the field index and 'arity' of :required, :optional or :repeated.
427    'name' can be used to override the defaultly generated Protobufs message name.
428    The body consists of fields, or 'define-enum' or 'define-message' forms.
429    'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
430    If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
431    used as an alias for a class that already exists in Lisp. This feature is intended
432    to be used to define messages that will be serialized from existing Lisp classes;
433    unless you get the slot names or readers exactly right for each field, it will be
434    the case that trying to (de)serialize into a Lisp object won't work.
435    'options' is a set of keyword/value pairs, both of which are strings.
436
437    Fields take the form (slot &key type name default reader)
438    'slot' can be either a symbol giving the field name, or a list whose
439    first element is the slot name and whose second element is the index.
440    'type' is the type of the slot.
441    'name' can be used to override the defaultly generated Protobufs field name.
442    'default' is the default value for the slot.
443    'reader' is a Lisp slot reader function to use to get the value, instead of
444    using 'slot-value'; this is often used when aliasing an existing class.
445    'writer' is a Lisp slot writer function to use to set the value."
446   (check-type index integer)
447   (check-type arity (member :required :optional :repeated))
448   (let* ((slot    (or (and name (proto->slot-name name *protobuf-package*)) type))
449          (name    (or name (class-name->proto type)))
450          (options (loop for (key val) on options by #'cddr
451                         collect (make-instance 'protobuf-option
452                                   :name  (if (symbolp key) (slot-name->proto key) key)
453                                   :value val)))
454          (mslot   (unless alias-for
455                     `(,slot ,@(case arity
456                                 (:required
457                                  `(:type ,type))
458                                 (:optional
459                                  `(:type (or ,type null)
460                                    :initform nil))
461                                 (:repeated
462                                  `(:type (list-of ,type)
463                                    :initform ())))
464                             :initarg ,(kintern (symbol-name slot)))))
465          (mfield  (make-instance 'protobuf-field
466                     :name  (slot-name->proto slot)
467                     :value slot
468                     :type  name
469                     :class type
470                     ;; One of :required, :optional or :repeated
471                     :required arity
472                     :index index
473                     :message-type :group))
474          (message (make-instance 'protobuf-message
475                     :class type
476                     :name  name
477                     :alias-for alias-for
478                     :conc-name (and conc-name (string conc-name))
479                     :options  options
480                     :message-type :group                ;this message is a group
481                     :documentation documentation))
482          (index 0)
483          (*protobuf* message))
484     (with-collectors ((slots collect-slot)
485                       (forms collect-form))
486       (dolist (field fields)
487         (case (car field)
488           ((define-enum define-message define-extend define-extension define-group)
489            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
490                (macroexpand-1 field env)
491              (assert (eq progn 'progn) ()
492                      "The macroexpansion for ~S failed" field)
493              (map () #'collect-form definers)
494              (ecase model-type
495                ((define-enum)
496                 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
497                ((define-message define-extend)
498                 (setf (proto-parent model) message)
499                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
500                 (when (eq (proto-message-type model) :extends)
501                   (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
502                ((define-group)
503                 (setf (proto-parent model) message)
504                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
505                 (when extra-slot
506                   (collect-slot extra-slot))
507                 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
508                ((define-extension)
509                 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
510           (otherwise
511            (multiple-value-bind (field slot idx)
512                (process-field field index :conc-name conc-name :alias-for alias-for)
513              (assert (not (find (proto-index field) (proto-fields message) :key #'proto-index)) ()
514                      "The field ~S overlaps with another field in ~S"
515                      (proto-value field) (proto-class message))
516              (setq index idx)
517              (when slot
518                (collect-slot slot))
519              (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
520       (if alias-for
521         ;; If we've got an alias, define a a type that is the subtype of
522         ;; the Lisp class that typep and subtypep work
523         (unless (or (eq type alias-for) (find-class type nil))
524           (collect-form `(deftype ,type () ',alias-for)))
525         ;; If no alias, define the class now
526         (collect-form `(defclass ,type () (,@slots)
527                          ,@(and documentation `((:documentation ,documentation))))))
528       `(progn
529          define-group
530          ,message
531          ,forms
532          ,mfield
533          ,mslot))))
534
535 (defun process-field (field index &key conc-name alias-for)
536   "Process one field descriptor within 'define-message' or 'define-extend'.
537    Returns a 'proto-field' object, a CLOS slot form and the incremented field index."
538   (when (i= index 18999)                                ;skip over the restricted range
539     (setq index 19999))
540   (destructuring-bind (slot &rest other-options 
541                        &key type reader writer name (default nil default-p) packed
542                             options documentation &allow-other-keys) field
543     (let* ((idx  (if (listp slot) (second slot) (iincf index)))
544            (slot (if (listp slot) (first slot) slot))
545            (reqd (clos-type-to-protobuf-required type))
546            (reader (if (eq reader 't)
547                      (intern (if conc-name (format nil "~A~A" conc-name slot) (symbol-name slot))
548                              *protobuf-package*)
549                      reader))
550            (options (append
551                      (loop for (key val) on other-options by #'cddr
552                            unless (member key '(:type :reader :writer :name  :default :packed :documentation))
553                              collect (make-instance 'protobuf-option
554                                        :name  (slot-name->proto key)
555                                        :value val))
556                      (loop for (key val) on options by #'cddr
557                          collect (make-instance 'protobuf-option
558                                    :name  (if (symbolp key) (slot-name->proto key) key)
559                                    :value val)))))
560       (multiple-value-bind (ptype pclass)
561           (clos-type-to-protobuf-type type)
562         (let ((slot (unless alias-for
563                       `(,slot :type ,type
564                               ,@(and reader
565                                      (if writer
566                                        `(:reader ,reader)
567                                        `(:accessor ,reader)))
568                               ,@(and writer
569                                      `(:writer ,writer))
570                               :initarg ,(kintern (symbol-name slot))
571                               ,@(cond ((and (not default-p) 
572                                             (eq reqd :repeated))
573                                        `(:initform ()))
574                                       ((and (not default-p)
575                                             (eq reqd :optional)
576                                             ;; Use unbound for booleans only
577                                             (not (eq pclass :bool)))
578                                        `(:initform nil))
579                                       (default-p
580                                         `(:initform ,(protobuf-default-to-clos-init default type)))))))
581               (field (make-instance 'protobuf-field
582                        :name  (or name (slot-name->proto slot))
583                        :type  ptype
584                        :class pclass
585                        :required reqd
586                        :index  idx
587                        :value  slot
588                        :reader reader
589                        :writer writer
590                        :default default
591                        ;; Pack the field only if requested and it actually makes sense
592                        :packed  (and (eq reqd :repeated) packed t)
593                        :options options
594                        :documentation documentation)))
595           (values field slot idx))))))
596
597 ;; Define a service named 'type' with generic functions declared for
598 ;; each of the methods within the service
599 (defmacro define-service (type (&key name options documentation)
600                           &body method-specs)
601   "Define a service named 'type' and Lisp 'defgeneric' for all its methods.
602    'name' can be used to override the defaultly generated Protobufs service name.
603    'options' is a set of keyword/value pairs, both of which are strings.
604
605    The body is a set of method specs of the form (name (input-type output-type) &key options).
606    'input-type' and 'output-type' may also be of the form (type &key name)."
607   (let* ((name    (or name (class-name->proto type)))
608          (options (loop for (key val) on options by #'cddr
609                         collect (make-instance 'protobuf-option
610                                   :name  (if (symbolp key) (slot-name->proto key) key)
611                                   :value val)))
612          (service (make-instance 'protobuf-service
613                     :class type
614                     :name  name
615                     :options options
616                     :documentation documentation)))
617     (with-collectors ((forms collect-form))
618       (dolist (method method-specs)
619         (destructuring-bind (function (input-type output-type) &key name options documentation) method
620           (let* ((input-name (and (listp input-type)
621                                   (getf (cdr input-type) :name)))
622                  (input-type (if (listp input-type) (car input-type) input-type))
623                  (output-name (and (listp output-type)
624                                    (getf (cdr output-type) :name)))
625                  (output-type (if (listp output-type) (car output-type) output-type))
626                  (options (loop for (key val) on options by #'cddr
627                                 collect (make-instance 'protobuf-option
628                                           :name  (if (symbolp key) (slot-name->proto key) key)
629                                           :value val)))
630                  (method  (make-instance 'protobuf-method
631                             :class function
632                             :name  (or name (class-name->proto function))
633                             :input-type  input-type
634                             :input-name  (or input-name (class-name->proto input-type))
635                             :output-type output-type
636                             :output-name (or output-name (class-name->proto output-type))
637                             :options options
638                             :documentation documentation)))
639             (setf (proto-methods service) (nconc (proto-methods service) (list method)))
640             ;; The following are the hooks to CL-Stubby
641             (let* ((package   *protobuf-package*)
642                    (client-fn function)
643                    (server-fn (intern (format nil "~A-~A" 'do function) package))
644                    (vinput    (intern (format nil "~A-~A" (symbol-name input-type) 'in) package))
645                    (voutput   (intern (format nil "~A-~A" (symbol-name output-type) 'out) package))
646                    (vchannel  (intern (symbol-name 'channel) package))
647                    (vcallback (intern (symbol-name 'callback) package)))
648               ;; The client side stub, e.g., 'read-air-reservation'.
649               ;; The expectation is that CL-Stubby will provide macrology to make it
650               ;; easy to implement a method for this on each kind of channel (HTTP, TCP socket,
651               ;; IPC, etc). Unlike C++/Java/Python, we don't need a client-side subclass,
652               ;; because we can just use multi-methods.
653               ;; The CL-Stubby macros take care of serializing the input, transmitting the
654               ;; request over the wire, waiting for input (or not if it's asynchronous),
655               ;; filling in the output, and calling the callback (if it's synchronous).
656               ;; It's not very Lispy to side-effect an output object, but it makes
657               ;; asynchronous calls simpler.
658               (collect-form `(defgeneric ,client-fn (,vchannel ,vinput ,voutput &key ,vcallback)
659                                ,@(and documentation `((:documentation ,documentation)))
660                                (declare (values ,output-type))))
661               ;; The server side stub, e.g., 'do-read-air-reservation'.
662               ;; The expectation is that the server-side program will implement
663               ;; a method with the business logic for this on each kind of channel
664               ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
665               ;; of the input class
666               ;; The business logic is expected to perform the correct operations on
667               ;; the input object, which arrived via Protobufs, and produce an output
668               ;; of the given type, which will be serialized as a result.
669               ;; The channel objects hold client identity information, deadline info,
670               ;; etc, and can be side-effected to indicate success or failure
671               ;; CL-Stubby provides the channel classes and does (de)serialization, etc
672               (collect-form `(defgeneric ,server-fn (,vchannel ,vinput ,voutput &key ,vcallback)
673                                ,@(and documentation `((:documentation ,documentation)))
674                                (declare (values ,output-type))))))))
675       `(progn
676          define-service
677          ,service
678          ,forms))))
679
680 \f
681 ;;; Ensure everything in a Protobufs schema is defined
682
683 (defvar *undefined-messages*)
684
685 ;; A very useful tool during development...
686 (defun ensure-all-schemas ()
687   (let ((protos (sort
688                  (delete-duplicates
689                   (loop for p being the hash-values of *all-schemas*
690                         collect p))
691                  #'string< :key #'proto-name)))
692     (mapcan #'ensure-schema protos)))
693
694 (defmethod ensure-schema ((schema protobuf-schema))
695   "Ensure that all of the types are defined in the Protobufs schema 'schema'.
696    This returns two values:
697     - A list whose elements are (<undefined-type> \"message:field\" ...)
698     - The accumulated warnings table that has the same information as objects."
699   (let ((*undefined-messages* (make-hash-table))
700         (trace (list schema)))
701     (map () (curry #'ensure-message trace) (proto-messages schema))
702     (map () (curry #'ensure-service trace) (proto-services schema))
703     (loop for type being the hash-keys of *undefined-messages*
704             using (hash-value things)
705           collect (list* type
706                          (mapcar #'(lambda (thing)
707                                      (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
708                                  things)) into warnings
709           finally (return (values warnings *undefined-messages*)))))
710
711 (defmethod ensure-message (trace (message protobuf-message))
712   (let ((trace (cons message trace)))
713     (map () (curry #'ensure-message trace) (proto-messages message))
714     (map () (curry #'ensure-field trace message) (proto-fields message))))
715
716 (defmethod ensure-field (trace message (field protobuf-field))
717   (ensure-type trace message field (proto-class field)))
718
719 (defmethod ensure-service (trace (service protobuf-service))
720   (map () (curry #'ensure-method trace service) (proto-methods service)))
721
722 (defmethod ensure-method (trace service (method protobuf-method))
723   (ensure-type trace service method (proto-input-type method))
724   (ensure-type trace service method (proto-output-type method)))
725
726 ;; 'message' and 'field' can be a message and a field or a service and a method
727 (defun ensure-type (trace message field type)
728   (unless (keywordp type)
729     (let ((msg (loop for p in trace
730                      thereis (or (find-message p type)
731                                  (find-enum p type)))))
732       (unless msg
733         (push (cons message field) (gethash type *undefined-messages*))))))