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