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