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