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