]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - define-proto.lisp
Get some stuff working better for Stubby purposes.
[cl-protobufs.git] / define-proto.lisp
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;;                                                                  ;;;
3 ;;; Confidential and proprietary information of ITA Software, Inc.   ;;;
4 ;;;                                                                  ;;;
5 ;;; Copyright (c) 2012 ITA Software, Inc.  All rights reserved.      ;;;
6 ;;;                                                                  ;;;
7 ;;; Original author: Scott McKay                                     ;;;
8 ;;;                                                                  ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
10
11 (in-package "PROTO-IMPL")
12
13
14 ;;; Protocol buffer defining macros
15
16 ;; Define a schema named 'type', corresponding to a .proto file of that name
17 (defmacro define-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-package lisp-pkg)
57                                  (find-package (string-upcase lisp-pkg))
58                                  *package*)))
59     (apply #'process-imports schema imports)
60     (with-collectors ((forms collect-form))
61       (dolist (msg messages)
62         (assert (and (listp msg)
63                      (member (car msg) '(define-enum define-message define-extend define-service))) ()
64                 "The body of ~S must be one of ~{~S~^ or ~}"
65                 'define-schema '(define-enum define-message define-extend define-service))
66         ;; The macro-expander will return a form that consists
67         ;; of 'progn' followed by a symbol naming what we've expanded
68         ;; (define-enum, define-message, define-extend, define-service),
69         ;; followed by the Lisp model object created by the defining form,
70         ;; followed by other defining forms (e.g., deftype, defclass)
71         (destructuring-bind (&optional progn model-type model definers)
72             (macroexpand-1 msg env)
73           (assert (eq progn 'progn) ()
74                   "The macroexpansion for ~S failed" msg)
75           (map () #'collect-form definers)
76           (ecase model-type
77             ((define-enum)
78              (setf (proto-enums schema) (nconc (proto-enums schema) (list model))))
79             ((define-message define-extend)
80              (setf (proto-parent model) schema)
81              (setf (proto-messages schema) (nconc (proto-messages schema) (list model)))
82              (when (eq (proto-message-type model) :extends)
83                (setf (proto-extenders schema) (nconc (proto-extenders schema) (list model)))))
84             ((define-service)
85              (setf (proto-services schema) (nconc (proto-services schema) (list model)))))))
86       (let ((var (intern (format nil "*~A*" type) *protobuf-package*)))
87         `(progn
88            ,@forms
89            (defvar ,var nil)
90            (let* ((old-schema ,var)
91                   (new-schema ,schema))
92              (when old-schema
93                (multiple-value-bind (upgradable warnings)
94                    (schema-upgradable old-schema new-schema)
95                  (unless upgradable
96                    (protobufs-warn "The old schema for ~S (~A) can't be safely upgraded; proceeding anyway"
97                                    ',type ',name)
98                    (map () #'protobufs-warn warnings))))
99              (setq ,var new-schema)
100              (record-protobuf ,var)
101              ,@(with-collectors ((messages collect-message))
102                  (labels ((collect-messages (message)
103                             (collect-message message)
104                             (map () #'collect-messages (proto-messages message))))
105                    (map () #'collect-messages (proto-messages schema)))
106                  (append 
107                    (mapcar #'(lambda (m) `(record-protobuf ,m)) messages)
108                    (when (eq optimize :speed)
109                      (append (mapcar #'generate-object-size  messages)
110                              (mapcar #'generate-serializer   messages)
111                              (mapcar #'generate-deserializer messages)))))
112              ,var))))))
113
114 ;; Define an enum type named 'type' and a Lisp 'deftype'
115 (defmacro define-enum (type (&key name conc-name alias-for options documentation)
116                        &body values)
117   "Define a Protobufs enum type and a Lisp 'deftype' named 'type'.
118    'name' can be used to override the defaultly generated Protobufs enum name.
119    'conc-name' will be used as the prefix to the Lisp enum names, if it's supplied.
120    If 'alias-for' is given, no Lisp 'deftype' will be defined. Instead, the enum
121    will be used as an alias for an enum type that already exists in Lisp.
122    'options' is a set of keyword/value pairs, both of which are strings.
123
124    The body consists of the enum values in the form 'name' or (name index)."
125   (let* ((name    (or name (class-name->proto type)))
126          (options (loop for (key val) on options by #'cddr
127                         collect (make-instance 'protobuf-option
128                                   :name  (if (symbolp key) (slot-name->proto key) key)
129                                   :value val)))
130          (conc-name (and conc-name (string conc-name)))
131          (index -1)
132          (enum  (make-instance 'protobuf-enum
133                   :class  type
134                   :name   name
135                   :alias-for alias-for
136                   :options options
137                   :documentation documentation)))
138     (with-collectors ((vals  collect-val)
139                       (forms collect-form))
140       (dolist (val values)
141         (let* ((idx  (if (listp val) (second val) (incf index)))
142                (name (if (listp val) (first val)  val))
143                (val-name  (kintern (if conc-name (format nil "~A~A" conc-name name) (symbol-name name))))
144                (enum-name (if conc-name (format nil "~A~A" conc-name name) (symbol-name name)))
145                (enum-val  (make-instance 'protobuf-enum-value
146                             :name  (enum-name->proto enum-name)
147                             :index idx
148                             :value val-name)))
149           (collect-val val-name)
150           (setf (proto-values enum) (nconc (proto-values enum) (list enum-val)))))
151       (if alias-for
152         ;; If we've got an alias, define a a type that is the subtype of
153         ;; the Lisp enum so that typep and subtypep work
154         (unless (eq type alias-for)
155           (collect-form `(deftype ,type () ',alias-for)))
156         ;; If no alias, define the Lisp enum type now
157         (collect-form `(deftype ,type () '(member ,@vals))))
158       `(progn
159          define-enum
160          ,enum
161          ,forms))))
162
163 ;; Define a message named 'name' and a Lisp 'defclass'
164 (defmacro define-message (type (&key name conc-name alias-for options documentation)
165                           &body fields &environment env)
166   "Define a message named 'type' and a Lisp 'defclass'.
167    'name' can be used to override the defaultly generated Protobufs message name.
168    The body consists of fields, or 'define-enum' or 'define-message' forms.
169    'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
170    If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
171    used as an alias for a class that already exists in Lisp. This feature is intended
172    to be used to define messages that will be serialized from existing Lisp classes;
173    unless you get the slot names or readers exactly right for each field, it will be
174    the case that trying to (de)serialize into a Lisp object won't work.
175    'options' is a set of keyword/value pairs, both of which are strings.
176
177    Fields take the form (slot &key type name default reader)
178    'slot' can be either a symbol giving the field name, or a list whose
179    first element is the slot name and whose second element is the index.
180    'type' is the type of the slot.
181    'name' can be used to override the defaultly generated Protobufs field name.
182    'default' is the default value for the slot.
183    'reader' is a Lisp slot reader function to use to get the value, instead of
184    using 'slot-value'; this is often used when aliasing an existing class.
185    'writer' is a Lisp slot writer function to use to set the value."
186   (let* ((name    (or name (class-name->proto type)))
187          (options (loop for (key val) on options by #'cddr
188                         collect (make-instance 'protobuf-option
189                                   :name  (if (symbolp key) (slot-name->proto key) key)
190                                   :value val)))
191          (conc-name (and conc-name (string conc-name)))
192          (message (make-instance 'protobuf-message
193                     :class type
194                     :name  name
195                     :parent *protobuf*
196                     :alias-for alias-for
197                     :conc-name conc-name
198                     :options   (remove-options options "default" "packed")
199                     :documentation documentation))
200          (index 0)
201          (*protobuf* message))
202     (with-collectors ((slots collect-slot)
203                       (forms collect-form))
204       (dolist (field fields)
205         (case (car field)
206           ((define-enum define-message define-extend define-extension define-group)
207            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
208                (macroexpand-1 field env)
209              (assert (eq progn 'progn) ()
210                      "The macroexpansion for ~S failed" field)
211              (map () #'collect-form definers)
212              (ecase model-type
213                ((define-enum)
214                 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
215                ((define-message define-extend)
216                 (setf (proto-parent model) message)
217                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
218                 (when (eq (proto-message-type model) :extends)
219                   (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
220                ((define-group)
221                 (setf (proto-parent model) message)
222                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
223                 (when extra-slot
224                   (collect-slot extra-slot))
225                 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
226                ((define-extension)
227                 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
228           (otherwise
229            (multiple-value-bind (field slot idx)
230                (process-field field index :conc-name conc-name :alias-for alias-for)
231              (assert (not (find-field message (proto-index field))) ()
232                      "The field ~S overlaps with another field in ~S"
233                      (proto-value field) (proto-class message))
234              (setq index idx)
235              (when slot
236                (collect-slot slot))
237              (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
238       (if alias-for
239         ;; If we've got an alias, define a a type that is the subtype of
240         ;; the Lisp class that typep and subtypep work
241         (unless (or (eq type alias-for) (find-class type nil))
242           (collect-form `(deftype ,type () ',alias-for)))
243         ;; If no alias, define the class now
244         (collect-form `(defclass ,type () (,@slots)
245                          ,@(and documentation `((:documentation ,documentation))))))
246       `(progn
247          define-message
248          ,message
249          ,forms))))
250
251 (defmacro define-extension (from to)
252   "Define an extension range within a message.
253    The \"body\" is the start and end of the range, both inclusive."
254   `(progn
255      define-extension
256      ,(make-instance 'protobuf-extension
257         :from from
258         :to   (if (eq to 'max) #.(1- (ash 1 29)) to))
259      ()))
260
261 (defmacro define-extend (type (&key name conc-name options documentation)
262                          &body fields &environment env)
263   "Define an extension to the message named 'type'.
264    'name' can be used to override the defaultly generated Protobufs message name.
265    The body consists only  of fields.
266    'options' is a set of keyword/value pairs, both of which are strings.
267
268    Fields take the form (slot &key type name default reader)
269    'slot' can be either a symbol giving the field name, or a list whose
270    first element is the slot name and whose second element is the index.
271    'type' is the type of the slot.
272    'name' can be used to override the defaultly generated Protobufs field name.
273    'default' is the default value for the slot.
274    'reader' is a Lisp slot reader function to use to get the value, instead of
275    using 'slot-value'; this is often used when aliasing an existing class.
276    'writer' is a Lisp slot writer function to use to set the value."
277   (let* ((name    (or name (class-name->proto type)))
278          (options (loop for (key val) on options by #'cddr
279                         collect (make-instance 'protobuf-option
280                                   :name  (if (symbolp key) (slot-name->proto key) key)
281                                   :value val)))
282          (message   (find-message *protobuf* name))
283          (conc-name (or (and conc-name (string conc-name))
284                         (and message (proto-conc-name message))))
285          (alias-for (and message (proto-alias-for message)))
286          (extends (and message
287                        (make-instance 'protobuf-message
288                          :class  type
289                          :name   name
290                          :parent (proto-parent message)
291                          :alias-for alias-for
292                          :conc-name conc-name
293                          :enums    (copy-list (proto-enums message))
294                          :messages (copy-list (proto-messages message))
295                          :fields   (copy-list (proto-fields message))
296                          :options  (remove-options
297                                      (or options (copy-list (proto-options message))) "default" "packed")
298                          :extensions (copy-list (proto-extensions message))
299                          :message-type :extends         ;this message is an extension
300                          :documentation documentation)))
301          (*protobuf* extends)
302          (index 0))
303     (assert message ()
304             "There is no message named ~A to extend" name)
305     (assert (eq type (proto-class message)) ()
306             "The type ~S doesn't match the type of the message being extended ~S"
307             type message)
308     (with-collectors ((forms collect-form))
309       (dolist (field fields)
310         (assert (not (member (car field)
311                              '(define-enum define-message define-extend define-extension))) ()
312                 "The body of ~S can only contain field and group definitions" 'define-extend)
313         (case (car field)
314           ((define-group)
315            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
316                (macroexpand-1 field env)
317              (assert (eq progn 'progn) ()
318                      "The macroexpansion for ~S failed" field)
319              (map () #'collect-form definers)
320              (ecase model-type
321                ((define-group)
322                 (setf (proto-parent model) extends)
323                 (setf (proto-messages extends) (nconc (proto-messages extends) (list model)))
324                 (when extra-slot
325                   ;;--- Refactor to get rid of all this duplicated code!
326                   (let* ((inits  (cdr extra-slot))
327                          (sname  (car extra-slot))
328                          (stable (fintern "~A-VALUES" sname))
329                          (stype  (getf inits :type))
330                          (reader (or (getf inits :accessor)
331                                      (getf inits :reader)
332                                      (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
333                                              *protobuf-package*)))
334                          (writer (or (getf inits :writer)
335                                      (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
336                          (default (getf inits :initform)))
337                     (collect-form `(without-redefinition-warnings ()
338                                      (let ((,stable (make-hash-table :test #'eq :weak t)))
339                                        ,@(and reader `((defmethod ,reader ((object ,type))
340                                                          (gethash object ,stable ,default))))
341                                        ,@(and writer `((defmethod ,writer ((object ,type) value)
342                                                          (declare (type ,stype value))
343                                                          (setf (gethash object ,stable) value))))
344                                        ,@(and writer `((defsetf ,reader ,writer)))
345                                        ;; For Python compatibility
346                                        (defmethod get-extension ((object ,type) (slot (eql ',sname)))
347                                          (values (gethash object ,stable ,default)))
348                                        (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
349                                          (setf (gethash object ,stable) value))
350                                        (defmethod has-extension ((object ,type) (slot (eql ',sname)))
351                                          (multiple-value-bind (value foundp)
352                                              (gethash object ,stable)
353                                            (declare (ignore value))
354                                            foundp))
355                                        (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
356                                          (remhash object ,stable)))))))
357                 (setf (proto-message-type extra-field) :extends) ;this field is an extension
358                 (setf (proto-fields extends) (nconc (proto-fields extends) (list extra-field)))
359                 (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list extra-field)))))))
360           (otherwise
361            (multiple-value-bind (field slot idx)
362                (process-field field index :conc-name conc-name :alias-for alias-for)
363              (assert (not (find-field extends (proto-index field))) ()
364                      "The field ~S overlaps with another field in ~S"
365                      (proto-value field) (proto-class extends))
366              (assert (index-within-extensions-p idx message) ()
367                      "The index ~D is not in range for extending ~S"
368                      idx (proto-class message))
369              (setq index idx)
370              (when slot
371                (let* ((inits  (cdr slot))
372                       (sname  (car slot))
373                       (stable (fintern "~A-VALUES" sname))
374                       (stype  (getf inits :type))
375                       (reader (or (getf inits :accessor)
376                                   (getf inits :reader)
377                                   (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
378                                           *protobuf-package*)))
379                       (writer (or (getf inits :writer)
380                                   (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
381                       (default (getf inits :initform)))
382                  ;; For the extended slots, each slot gets its own table
383                  ;; keyed by the object, which lets us avoid having a slot in each
384                  ;; instance that holds a table keyed by the slot name
385                  ;; Multiple 'define-extends' on the same class in the same image
386                  ;; will result in harmless redefinitions, so squelch the warnings
387                  ;;--- Maybe these methods need to be defined in 'define-message'?
388                  (collect-form `(without-redefinition-warnings ()
389                                   (let ((,stable (make-hash-table :test #'eq :weak t)))
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                  (method  (make-instance 'protobuf-method
649                             :class function
650                             :name  (or name (class-name->proto function))
651                             :input-type  input-type
652                             :input-name  (or input-name (class-name->proto input-type))
653                             :output-type output-type
654                             :output-name (or output-name (class-name->proto output-type))
655                             :index (iincf index)
656                             :options options
657                             :documentation documentation)))
658             (setf (proto-methods service) (nconc (proto-methods service) (list method)))
659             ;; The following are the hooks to CL-Stubby
660             (let* ((package   *protobuf-package*)
661                    (client-fn function)
662                    (server-fn (intern (format nil "~A-~A" 'do function) package))
663                    (vinput    (intern (format nil "~A-~A" (symbol-name input-type) 'in) package))
664                    (voutput   (intern (format nil "~A-~A" (symbol-name output-type) 'out) package))
665                    (vchannel  (intern (symbol-name 'channel) package))
666                    (vcallback (intern (symbol-name 'callback) package)))
667               ;; The client side stub, e.g., 'read-air-reservation'.
668               ;; The expectation is that CL-Stubby will provide macrology to make it
669               ;; easy to implement a method for this on each kind of channel (HTTP, TCP socket,
670               ;; IPC, etc). Unlike C++/Java/Python, we don't need a client-side subclass,
671               ;; because we can just use multi-methods.
672               ;; The CL-Stubby macros take care of serializing the input, transmitting the
673               ;; request over the wire, waiting for input (or not if it's asynchronous),
674               ;; filling in the output, and calling the callback (if it's synchronous).
675               ;; It's not very Lispy to side-effect an output object, but it makes
676               ;; asynchronous calls simpler.
677               (collect-form `(defgeneric ,client-fn (,vchannel ,vinput ,voutput &key ,vcallback)
678                                ,@(and documentation `((:documentation ,documentation)))
679                                (declare (values ,output-type))))
680               ;; The server side stub, e.g., 'do-read-air-reservation'.
681               ;; The expectation is that the server-side program will implement
682               ;; a method with the business logic for this on each kind of channel
683               ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
684               ;; of the input class
685               ;; The business logic is expected to perform the correct operations on
686               ;; the input object, which arrived via Protobufs, and produce an output
687               ;; of the given type, which will be serialized as a result.
688               ;; The channel objects hold client identity information, deadline info,
689               ;; etc, and can be side-effected to indicate success or failure
690               ;; CL-Stubby provides the channel classes and does (de)serialization, etc
691               (collect-form `(defgeneric ,server-fn (,vchannel ,vinput ,voutput &key ,vcallback)
692                                ,@(and documentation `((:documentation ,documentation)))
693                                (declare (values ,output-type))))))))
694       `(progn
695          define-service
696          ,service
697          ,forms))))
698
699 \f
700 ;;; Ensure everything in a Protobufs schema is defined
701
702 (defvar *undefined-messages*)
703
704 ;; A very useful tool during development...
705 (defun ensure-all-schemas ()
706   (let ((protos (sort
707                  (delete-duplicates
708                   (loop for p being the hash-values of *all-schemas*
709                         collect p))
710                  #'string< :key #'proto-name)))
711     (mapcan #'ensure-schema protos)))
712
713 (defmethod ensure-schema ((schema protobuf-schema))
714   "Ensure that all of the types are defined in the Protobufs schema 'schema'.
715    This returns two values:
716     - A list whose elements are (<undefined-type> \"message:field\" ...)
717     - The accumulated warnings table that has the same information as objects."
718   (let ((*undefined-messages* (make-hash-table))
719         (trace (list schema)))
720     (map () (curry #'ensure-message trace) (proto-messages schema))
721     (map () (curry #'ensure-service trace) (proto-services schema))
722     (loop for type being the hash-keys of *undefined-messages*
723             using (hash-value things)
724           collect (list* type
725                          (mapcar #'(lambda (thing)
726                                      (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
727                                  things)) into warnings
728           finally (return (values warnings *undefined-messages*)))))
729
730 (defmethod ensure-message (trace (message protobuf-message))
731   (let ((trace (cons message trace)))
732     (map () (curry #'ensure-message trace) (proto-messages message))
733     (map () (curry #'ensure-field trace message) (proto-fields message))))
734
735 (defmethod ensure-field (trace message (field protobuf-field))
736   (ensure-type trace message field (proto-class field)))
737
738 (defmethod ensure-service (trace (service protobuf-service))
739   (map () (curry #'ensure-method trace service) (proto-methods service)))
740
741 (defmethod ensure-method (trace service (method protobuf-method))
742   (ensure-type trace service method (proto-input-type method))
743   (ensure-type trace service method (proto-output-type method)))
744
745 ;; 'message' and 'field' can be a message and a field or a service and a method
746 (defun ensure-type (trace message field type)
747   (unless (keywordp type)
748     (let ((msg (loop for p in trace
749                      thereis (or (find-message p type)
750                                  (find-enum p type)))))
751       (unless msg
752         (push (cons message field) (gethash type *undefined-messages*))))))