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