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