]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - define-proto.lisp
Beef up the generated client-side stub so that calls into an RPC
[cl-protobufs.git] / define-proto.lisp
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;;                                                                  ;;;
3 ;;; Free Software published under an MIT-like license. See LICENSE   ;;;
4 ;;;                                                                  ;;;
5 ;;; Copyright (c) 2012 Google, 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-proto-package lisp-pkg) *package*)))
57     (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          (conc-name (conc-name-for-type type conc-name))
129          (index -1)
130          (enum  (make-instance 'protobuf-enum
131                   :class  type
132                   :name   name
133                   :qualified-name (make-qualified-name *protobuf* 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          (conc-name (conc-name-for-type type conc-name))
191          (message (make-instance 'protobuf-message
192                     :class type
193                     :name  name
194                     :qualified-name (make-qualified-name *protobuf* name)
195                     :parent *protobuf*
196                     :alias-for alias-for
197                     :conc-name conc-name
198                     :options   (remove-options options "default" "packed")
199                     :documentation documentation))
200          (index 0)
201          ;; Only now can we bind *protobuf* to the new message
202          (*protobuf* message))
203     (with-collectors ((slots collect-slot)
204                       (forms collect-form))
205       (dolist (field fields)
206         (case (car field)
207           ((define-enum define-message define-extend define-extension define-group)
208            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
209                (macroexpand-1 field env)
210              (assert (eq progn 'progn) ()
211                      "The macroexpansion for ~S failed" field)
212              (map () #'collect-form definers)
213              (ecase model-type
214                ((define-enum)
215                 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
216                ((define-message define-extend)
217                 (setf (proto-parent model) message)
218                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
219                 (when (eq (proto-message-type model) :extends)
220                   (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
221                ((define-group)
222                 (setf (proto-parent model) message)
223                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
224                 (when extra-slot
225                   (collect-slot extra-slot))
226                 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
227                ((define-extension)
228                 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
229           (otherwise
230            (multiple-value-bind (field slot idx)
231                (process-field field index :conc-name conc-name :alias-for alias-for)
232              (assert (not (find-field message (proto-index field))) ()
233                      "The field ~S overlaps with another field in ~S"
234                      (proto-value field) (proto-class message))
235              (setq index idx)
236              (when slot
237                (collect-slot slot))
238              (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
239       (if alias-for
240         ;; If we've got an alias, define a a type that is the subtype of
241         ;; the Lisp class that typep and subtypep work
242         (unless (or (eq type alias-for) (find-class type nil))
243           (collect-form `(deftype ,type () ',alias-for)))
244         ;; If no alias, define the class now
245         (collect-form `(defclass ,type () (,@slots)
246                          ,@(and documentation `((:documentation ,documentation))))))
247       `(progn
248          define-message
249          ,message
250          ,forms))))
251
252 (defun conc-name-for-type (type conc-name)
253   (and conc-name
254        (typecase conc-name
255          ((member t) (format nil "~A-" type))
256          ((or string symbol) (string conc-name))
257          (t nil))))
258
259 (defmacro define-extension (from to)
260   "Define an extension range within a message.
261    The \"body\" is the start and end of the range, both inclusive."
262   (let ((to (etypecase to
263               (integer to)
264               (symbol (if (string-equal to "MAX") #.(1- (ash 1 29)) to)))))
265     `(progn
266        define-extension
267        ,(make-instance 'protobuf-extension
268           :from from
269           :to   (if (eq to 'max) #.(1- (ash 1 29)) to))
270        ())))
271
272 (defmacro define-extend (type (&key name conc-name options documentation)
273                          &body fields &environment env)
274   "Define an extension to the message named 'type'.
275    'name' can be used to override the defaultly generated Protobufs message name.
276    The body consists only  of fields.
277    'options' is a set of keyword/value pairs, both of which are strings.
278
279    Fields take the form (slot &key type name default reader)
280    'slot' can be either a symbol giving the field name, or a list whose
281    first element is the slot name and whose second element is the index.
282    'type' is the type of the slot.
283    'name' can be used to override the defaultly generated Protobufs field name.
284    'default' is the default value for the slot.
285    'reader' is a Lisp slot reader function to use to get the value, instead of
286    using 'slot-value'; this is often used when aliasing an existing class.
287    'writer' is a Lisp slot writer function to use to set the value."
288   (let* ((name    (or name (class-name->proto type)))
289          (options (loop for (key val) on options by #'cddr
290                         collect (make-instance 'protobuf-option
291                                   :name  (if (symbolp key) (slot-name->proto key) key)
292                                   :value val)))
293          (message   (find-message *protobuf* name))
294          (conc-name (or (conc-name-for-type type conc-name)
295                         (and message (proto-conc-name message))))
296          (alias-for (and message (proto-alias-for message)))
297          (extends (and message
298                        (make-instance 'protobuf-message
299                          :class  type
300                          :name   name
301                          :qualified-name (make-qualified-name *protobuf* name)
302                          :parent (proto-parent message)
303                          :alias-for alias-for
304                          :conc-name conc-name
305                          :enums    (copy-list (proto-enums message))
306                          :messages (copy-list (proto-messages message))
307                          :fields   (copy-list (proto-fields message))
308                          :options  (remove-options
309                                      (or options (copy-list (proto-options message))) "default" "packed")
310                          :extensions (copy-list (proto-extensions message))
311                          :message-type :extends         ;this message is an extension
312                          :documentation documentation)))
313          ;; Only now can we bind *protobuf* to the new extended message
314          (*protobuf* extends)
315          (index 0))
316     (assert message ()
317             "There is no message named ~A to extend" name)
318     (assert (eq type (proto-class message)) ()
319             "The type ~S doesn't match the type of the message being extended ~S"
320             type message)
321     (with-collectors ((forms collect-form))
322       (dolist (field fields)
323         (assert (not (member (car field)
324                              '(define-enum define-message define-extend define-extension))) ()
325                 "The body of ~S can only contain field and group definitions" 'define-extend)
326         (case (car field)
327           ((define-group)
328            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
329                (macroexpand-1 field env)
330              (assert (eq progn 'progn) ()
331                      "The macroexpansion for ~S failed" field)
332              (map () #'collect-form definers)
333              (ecase model-type
334                ((define-group)
335                 (setf (proto-parent model) extends)
336                 (setf (proto-messages extends) (nconc (proto-messages extends) (list model)))
337                 (when extra-slot
338                   ;;--- Refactor to get rid of all this duplicated code!
339                   (let* ((inits  (cdr extra-slot))
340                          (sname  (car extra-slot))
341                          (stable (fintern "~A-VALUES" sname))
342                          (stype  (getf inits :type))
343                          (reader (or (getf inits :accessor)
344                                      (getf inits :reader)
345                                      (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
346                                              *protobuf-package*)))
347                          (writer (or (getf inits :writer)
348                                      (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
349                          (default (getf inits :initform)))
350                     (collect-form `(without-redefinition-warnings ()
351                                      (let ((,stable #+ccl  (make-hash-table :test #'eq :weak t)
352                                                     #+sbcl (make-hash-table :test #'eq :weakness :value)))
353                                        ,@(and reader `((defmethod ,reader ((object ,type))
354                                                          (gethash object ,stable ,default))))
355                                        ,@(and writer `((defmethod ,writer ((object ,type) value)
356                                                          (declare (type ,stype value))
357                                                          (setf (gethash object ,stable) value))))
358                                        ;; For Python compatibility
359                                        (defmethod get-extension ((object ,type) (slot (eql ',sname)))
360                                          (values (gethash object ,stable ,default)))
361                                        (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
362                                          (setf (gethash object ,stable) value))
363                                        (defmethod has-extension ((object ,type) (slot (eql ',sname)))
364                                          (multiple-value-bind (value foundp)
365                                              (gethash object ,stable)
366                                            (declare (ignore value))
367                                            foundp))
368                                        (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
369                                          (remhash object ,stable)))
370                                      ,@(and writer
371                                             ;; 'defsetf' needs to be visible at compile time
372                                             `((eval-when (:compile-toplevel :load-toplevel :execute)
373                                                 (defsetf ,reader ,writer))))))))
374                 (setf (proto-message-type extra-field) :extends) ;this field is an extension
375                 (setf (proto-fields extends) (nconc (proto-fields extends) (list extra-field)))
376                 (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list extra-field)))))))
377           (otherwise
378            (multiple-value-bind (field slot idx)
379                (process-field field index :conc-name conc-name :alias-for alias-for)
380              (assert (not (find-field extends (proto-index field))) ()
381                      "The field ~S overlaps with another field in ~S"
382                      (proto-value field) (proto-class extends))
383              (assert (index-within-extensions-p idx message) ()
384                      "The index ~D is not in range for extending ~S"
385                      idx (proto-class message))
386              (setq index idx)
387              (when slot
388                (let* ((inits  (cdr slot))
389                       (sname  (car slot))
390                       (stable (fintern "~A-VALUES" sname))
391                       (stype  (getf inits :type))
392                       (reader (or (getf inits :accessor)
393                                   (getf inits :reader)
394                                   (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
395                                           *protobuf-package*)))
396                       (writer (or (getf inits :writer)
397                                   (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
398                       (default (getf inits :initform)))
399                  ;; For the extended slots, each slot gets its own table
400                  ;; keyed by the object, which lets us avoid having a slot in each
401                  ;; instance that holds a table keyed by the slot name
402                  ;; Multiple 'define-extends' on the same class in the same image
403                  ;; will result in harmless redefinitions, so squelch the warnings
404                  ;;--- Maybe these methods need to be defined in 'define-message'?
405                  (collect-form `(without-redefinition-warnings ()
406                                   (let ((,stable #+ccl  (make-hash-table :test #'eq :weak t)
407                                                  #+sbcl (make-hash-table :test #'eq :weakness :value)))
408                                     ,@(and reader `((defmethod ,reader ((object ,type))
409                                                       (gethash object ,stable ,default))))
410                                     ,@(and writer `((defmethod ,writer ((object ,type) value)
411                                                       (declare (type ,stype value))
412                                                       (setf (gethash object ,stable) value))))
413                                     (defmethod get-extension ((object ,type) (slot (eql ',sname)))
414                                       (values (gethash object ,stable ,default)))
415                                     (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
416                                       (setf (gethash object ,stable) value))
417                                     (defmethod has-extension ((object ,type) (slot (eql ',sname)))
418                                       (multiple-value-bind (value foundp)
419                                           (gethash object ,stable)
420                                         (declare (ignore value))
421                                         foundp))
422                                     (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
423                                       (remhash object ,stable)))
424                                   ,@(and writer
425                                          `((eval-when (:compile-toplevel :load-toplevel :execute)
426                                              (defsetf ,reader ,writer))))))
427                  ;; This so that (de)serialization works
428                  (setf (proto-reader field) reader
429                        (proto-writer field) writer)))
430              (setf (proto-message-type field) :extends)         ;this field is an extension
431              (setf (proto-fields extends) (nconc (proto-fields extends) (list field)))
432              (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list field)))))))
433       `(progn
434          define-extend
435          ,extends
436          ,forms))))
437
438 (defun index-within-extensions-p (index message)
439   (let ((extensions (proto-extensions message)))
440     (some #'(lambda (ext)
441               (and (i>= index (proto-extension-from ext))
442                    (i<= index (proto-extension-to ext))))
443           extensions)))
444
445 (defmacro define-group (type (&key index arity name conc-name alias-for reader options documentation)
446                         &body fields &environment env)
447   "Define a message named 'type' and a Lisp 'defclass', *and* a field named type.
448    This is deprecated in Protobufs, but if you have to use it, you must give
449    'index' as the field index and 'arity' of :required, :optional or :repeated.
450    'name' can be used to override the defaultly generated Protobufs message name.
451    The body consists of fields, or 'define-enum' or 'define-message' forms.
452    'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
453    If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
454    used as an alias for a class that already exists in Lisp. This feature is intended
455    to be used to define messages that will be serialized from existing Lisp classes;
456    unless you get the slot names or readers exactly right for each field, it will be
457    the case that trying to (de)serialize into a Lisp object won't work.
458    'options' is a set of keyword/value pairs, both of which are strings.
459
460    Fields take the form (slot &key type name default reader)
461    'slot' can be either a symbol giving the field name, or a list whose
462    first element is the slot name and whose second element is the index.
463    'type' is the type of the slot.
464    'name' can be used to override the defaultly generated Protobufs field name.
465    'default' is the default value for the slot.
466    'reader' is a Lisp slot reader function to use to get the value, instead of
467    using 'slot-value'; this is often used when aliasing an existing class.
468    'writer' is a Lisp slot writer function to use to set the value."
469   (check-type index integer)
470   (check-type arity (member :required :optional :repeated))
471   (let* ((slot    (or type (and name (proto->slot-name name *protobuf-package*))))
472          (name    (or name (class-name->proto type)))
473          (options (loop for (key val) on options by #'cddr
474                         collect (make-instance 'protobuf-option
475                                   :name  (if (symbolp key) (slot-name->proto key) key)
476                                   :value val)))
477          (conc-name (conc-name-for-type type conc-name))
478          (reader  (or reader
479                       (let ((msg-conc (proto-conc-name *protobuf*)))
480                         (and msg-conc
481                              (intern (format nil "~A~A" msg-conc slot) *protobuf-package*)))))
482          (mslot   (unless alias-for
483                     `(,slot ,@(case arity
484                                 (:required
485                                  `(:type ,type))
486                                 (:optional
487                                  `(:type (or ,type null)
488                                    :initform nil))
489                                 (:repeated
490                                  `(:type (list-of ,type)
491                                    :initform ())))
492                             ,@(and reader
493                                    `(:accessor ,reader))
494                             :initarg ,(kintern (symbol-name slot)))))
495          (mfield  (make-instance 'protobuf-field
496                     :name  (slot-name->proto slot)
497                     :type  name
498                     :class type
499                     :qualified-name (make-qualified-name *protobuf* (slot-name->proto slot))
500                     :required arity
501                     :index index
502                     :value slot
503                     :reader reader
504                     :message-type :group))
505          (message (make-instance 'protobuf-message
506                     :class type
507                     :name  name
508                     :qualified-name (make-qualified-name *protobuf* name)
509                     :parent *protobuf*
510                     :alias-for alias-for
511                     :conc-name conc-name
512                     :options   (remove-options options "default" "packed")
513                     :message-type :group                ;this message is a group
514                     :documentation documentation))
515          (index 0)
516          ;; Only now can we bind *protobuf* to the (group) message
517          (*protobuf* message))
518     (with-collectors ((slots collect-slot)
519                       (forms collect-form))
520       (dolist (field fields)
521         (case (car field)
522           ((define-enum define-message define-extend define-extension define-group)
523            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
524                (macroexpand-1 field env)
525              (assert (eq progn 'progn) ()
526                      "The macroexpansion for ~S failed" field)
527              (map () #'collect-form definers)
528              (ecase model-type
529                ((define-enum)
530                 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
531                ((define-message define-extend)
532                 (setf (proto-parent model) message)
533                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
534                 (when (eq (proto-message-type model) :extends)
535                   (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
536                ((define-group)
537                 (setf (proto-parent model) message)
538                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
539                 (when extra-slot
540                   (collect-slot extra-slot))
541                 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
542                ((define-extension)
543                 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
544           (otherwise
545            (multiple-value-bind (field slot idx)
546                (process-field field index :conc-name conc-name :alias-for alias-for)
547              (assert (not (find-field message (proto-index field))) ()
548                      "The field ~S overlaps with another field in ~S"
549                      (proto-value field) (proto-class message))
550              (setq index idx)
551              (when slot
552                (collect-slot slot))
553              (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
554       (if alias-for
555         ;; If we've got an alias, define a a type that is the subtype of
556         ;; the Lisp class that typep and subtypep work
557         (unless (or (eq type alias-for) (find-class type nil))
558           (collect-form `(deftype ,type () ',alias-for)))
559         ;; If no alias, define the class now
560         (collect-form `(defclass ,type () (,@slots)
561                          ,@(and documentation `((:documentation ,documentation))))))
562       `(progn
563          define-group
564          ,message
565          ,forms
566          ,mfield
567          ,mslot))))
568
569 (defun process-field (field index &key conc-name alias-for)
570   "Process one field descriptor within 'define-message' or 'define-extend'.
571    Returns a 'proto-field' object, a CLOS slot form and the incremented field index."
572   (when (i= index 18999)                                ;skip over the restricted range
573     (setq index 19999))
574   (destructuring-bind (slot &rest other-options 
575                        &key type reader writer name (default nil default-p) packed
576                             options documentation &allow-other-keys) field
577     (let* ((idx  (if (listp slot) (second slot) (iincf index)))
578            (slot (if (listp slot) (first slot) slot))
579            (reader (or reader
580                        (and conc-name
581                             (intern (format nil "~A~A" conc-name slot) *protobuf-package*))))
582            (options (append
583                      (loop for (key val) on other-options by #'cddr
584                            unless (member key '(:type :reader :writer :name :default :packed :documentation))
585                              collect (make-instance 'protobuf-option
586                                        :name  (slot-name->proto key)
587                                        :value val))
588                      (loop for (key val) on options by #'cddr
589                          collect (make-instance 'protobuf-option
590                                    :name  (if (symbolp key) (slot-name->proto key) key)
591                                    :value val)))))
592       (multiple-value-bind (ptype pclass)
593           (clos-type-to-protobuf-type type)
594         (multiple-value-bind (reqd vectorp)
595             (clos-type-to-protobuf-required type)
596           (let* ((default (if (eq reqd :repeated)
597                             (if vectorp $empty-vector $empty-list)      ;to distinguish between list-of and vector-of
598                             (if default-p default $empty-default)))
599                  (cslot (unless alias-for
600                           `(,slot :type ,type
601                                   ,@(and reader
602                                          (if writer
603                                            `(:reader ,reader)
604                                            `(:accessor ,reader)))
605                                   ,@(and writer
606                                          `(:writer ,writer))
607                                   :initarg ,(kintern (symbol-name slot))
608                                   ,@(cond ((eq reqd :repeated)
609                                            ;; Repeated fields get a container for their elements
610                                            (if vectorp
611                                              `(:initform (make-array 5 :fill-pointer 0 :adjustable t))
612                                              `(:initform ())))
613                                           ((and (not default-p)
614                                                 (eq reqd :optional)
615                                                 ;; Use unbound for booleans only
616                                                 (not (eq pclass :bool)))
617                                            `(:initform nil))
618                                           (default-p
619                                             `(:initform ,(protobuf-default-to-clos-init default type)))))))
620                  (field (make-instance 'protobuf-field
621                           :name  (or name (slot-name->proto slot))
622                           :type  ptype
623                           :class pclass
624                           :qualified-name (make-qualified-name *protobuf* (or name (slot-name->proto slot)))
625                           ;; One of :required, :optional or :repeated
626                           :required reqd
627                           :index  idx
628                           :value  slot
629                           :reader reader
630                           :writer writer
631                           :default default
632                           ;; Pack the field only if requested and it actually makes sense
633                           :packed  (and (eq reqd :repeated) packed t)
634                           :options options
635                           :documentation documentation)))
636             (values field cslot idx)))))))
637
638 (defparameter *rpc-package* nil
639   "The Lisp package that implements RPC.")
640 (defparameter *rpc-call-function* nil
641   "The Lisp function that implements RPC client-side calls.")
642
643 ;; Define a service named 'type' with generic functions declared for
644 ;; each of the methods within the service
645 (defmacro define-service (type (&key name options documentation)
646                           &body method-specs)
647   "Define a service named 'type' and Lisp 'defgeneric' for all its methods.
648    'name' can be used to override the defaultly generated Protobufs service name.
649    'options' is a set of keyword/value pairs, both of which are strings.
650
651    The body is a set of method specs of the form (name (input-type output-type) &key options).
652    'input-type' and 'output-type' may also be of the form (type &key name)."
653   (let* ((name    (or name (class-name->proto type)))
654          (options (loop for (key val) on options by #'cddr
655                         collect (make-instance 'protobuf-option
656                                   :name  (if (symbolp key) (slot-name->proto key) key)
657                                   :value val)))
658          (service (make-instance 'protobuf-service
659                     :class type
660                     :name  name
661                     :qualified-name (make-qualified-name *protobuf* name)
662                     :options options
663                     :documentation documentation))
664          (index 0))
665     (with-collectors ((forms collect-form))
666       (dolist (method method-specs)
667         (destructuring-bind (function (input-type output-type) &key name options documentation) method
668           (let* ((input-name (and (listp input-type)
669                                   (getf (cdr input-type) :name)))
670                  (input-type (if (listp input-type) (car input-type) input-type))
671                  (output-name (and (listp output-type)
672                                    (getf (cdr output-type) :name)))
673                  (output-type (if (listp output-type) (car output-type) output-type))
674                  (options (loop for (key val) on options by #'cddr
675                                 collect (make-instance 'protobuf-option
676                                           :name  (if (symbolp key) (slot-name->proto key) key)
677                                           :value val)))
678                  (package   *protobuf-package*)
679                  (client-fn function)
680                  (server-fn (intern (format nil "~A-~A" 'do function) package))
681                  (method  (make-instance 'protobuf-method
682                             :class function
683                             :name  (or name (class-name->proto function))
684                             :qualified-name (make-qualified-name *protobuf* (or name (class-name->proto function)))
685                             :client-stub client-fn
686                             :server-stub server-fn
687                             :input-type  input-type
688                             :input-name  (or input-name (class-name->proto input-type))
689                             :output-type output-type
690                             :output-name (or output-name (class-name->proto output-type))
691                             :index (iincf index)
692                             :options options
693                             :documentation documentation)))
694             (setf (proto-methods service) (nconc (proto-methods service) (list method)))
695             ;; The following are the hooks to CL-Stubby
696             (let* ((vinput    (intern (format nil "~A-~A" (symbol-name input-type) 'in) package))
697                    (voutput   (intern (format nil "~A-~A" (symbol-name output-type) 'out) package))
698                    (vchannel  (intern (symbol-name 'channel) package))
699                    (vcallback (intern (symbol-name 'callback) package)))
700               ;; The client side stub, e.g., 'read-air-reservation'.
701               ;; The expectation is that CL-Stubby will provide macrology to make it
702               ;; easy to implement a method for this on each kind of channel (HTTP, TCP socket,
703               ;; IPC, etc). Unlike C++/Java/Python, we don't need a client-side subclass,
704               ;; because we can just use multi-methods.
705               ;; The CL-Stubby macros take care of serializing the input, transmitting the
706               ;; request over the wire, waiting for input (or not if it's asynchronous),
707               ;; filling in the output, and calling the callback (if it's asynchronous).
708               ;; It's not very Lispy to side-effect an output object, but it makes
709               ;; asynchronous calls simpler.
710               (collect-form `(defgeneric ,client-fn (,vchannel ,vinput ,voutput &key ,vcallback)
711                                ,@(and documentation `((:documentation ,documentation)))
712                                #-sbcl (declare (values ,output-type))
713                                (:method (,vchannel (,vinput ,input-type) (,voutput ,output-type) &key ,vcallback)
714                                  (declare (ignorable ,vchannel ,vcallback))
715                                  (let ((call (and *rpc-package* *rpc-call-function*
716                                                   (find-symbol *rpc-call-function* *rpc-package*))))
717                                    (assert call ()
718                                            "There is no RPC package loaded!")
719                                    (funcall call ,vchannel ',method ,vinput ,voutput
720                                             :callback ,vcallback)))))
721               ;; The server side stub, e.g., 'do-read-air-reservation'.
722               ;; The expectation is that the server-side program will implement
723               ;; a method with the business logic for this on each kind of channel
724               ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
725               ;; of the input class
726               ;; The business logic is expected to perform the correct operations on
727               ;; the input object, which arrived via Protobufs, and produce an output
728               ;; of the given type, which will be serialized as a result.
729               ;; The channel objects hold client identity information, deadline info,
730               ;; etc, and can be side-effected to indicate success or failure
731               ;; CL-Stubby provides the channel classes and does (de)serialization, etc
732               (collect-form `(defgeneric ,server-fn (,vchannel ,vinput ,voutput)
733                                ,@(and documentation `((:documentation ,documentation)))
734                                #-sbcl (declare (values ,output-type))))))))
735       `(progn
736          define-service
737          ,service
738          ,forms))))
739
740 \f
741 ;;; Ensure everything in a Protobufs schema is defined
742
743 (defvar *undefined-messages*)
744
745 ;; A very useful tool during development...
746 (defun ensure-all-schemas ()
747   (let ((protos (sort
748                  (delete-duplicates
749                   (loop for p being the hash-values of *all-schemas*
750                         collect p))
751                  #'string< :key #'proto-name)))
752     (mapcan #'ensure-schema protos)))
753
754 (defgeneric ensure-schema (schema)
755   (:documentation
756    "Ensure that all of the types are defined in the Protobufs schema 'schema'.
757     This returns two values:
758      - A list whose elements are (<undefined-type> \"message:field\" ...)
759      - The accumulated warnings table that has the same information as objects.")
760   (:method ((schema protobuf-schema))
761     (let ((*undefined-messages* (make-hash-table))
762           (trace (list schema)))
763       (map () (curry #'ensure-message trace) (proto-messages schema))
764       (map () (curry #'ensure-service trace) (proto-services schema))
765       (loop for type being the hash-keys of *undefined-messages*
766               using (hash-value things)
767             collect (list* type
768                            (mapcar #'(lambda (thing)
769                                        (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
770                                    things)) into warnings
771             finally (return (values warnings *undefined-messages*))))))
772
773 (defgeneric ensure-message (trace message)
774   (:method (trace (message protobuf-message))
775     (let ((trace (cons message trace)))
776       (map () (curry #'ensure-message trace) (proto-messages message))
777       (map () (curry #'ensure-field trace message) (proto-fields message)))))
778
779 (defgeneric ensure-field (trace message field)
780   (:method (trace message (field protobuf-field))
781     (ensure-type trace message field (proto-class field))))
782
783 (defgeneric ensure-service (trace service)
784   (:method (trace (service protobuf-service))
785     (map () (curry #'ensure-method trace service) (proto-methods service))))
786
787 (defgeneric ensure-method (trace service method)
788   (:method (trace service (method protobuf-method))
789     (ensure-type trace service method (proto-input-type method))
790     (ensure-type trace service method (proto-output-type method))))
791
792 ;; 'message' and 'field' can be a message and a field or a service and a method
793 (defun ensure-type (trace message field type)
794   (unless (keywordp type)
795     (let ((msg (loop for p in trace
796                      thereis (or (find-message p type)
797                                  (find-enum p type)))))
798       (unless msg
799         (push (cons message field) (gethash type *undefined-messages*))))))