]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - define-proto.lisp
da38d120c55f01f5dfd6d8b4d08747c968f17253
[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 #+ccl  (make-hash-table :test #'eq :weak t)
339                                                     #+sbcl (make-hash-table :test #'eq :weakness :value)))
340                                        ,@(and reader `((defmethod ,reader ((object ,type))
341                                                          (gethash object ,stable ,default))))
342                                        ,@(and writer `((defmethod ,writer ((object ,type) value)
343                                                          (declare (type ,stype value))
344                                                          (setf (gethash object ,stable) value))))
345                                        ,@(and writer `((defsetf ,reader ,writer)))
346                                        ;; For Python compatibility
347                                        (defmethod get-extension ((object ,type) (slot (eql ',sname)))
348                                          (values (gethash object ,stable ,default)))
349                                        (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
350                                          (setf (gethash object ,stable) value))
351                                        (defmethod has-extension ((object ,type) (slot (eql ',sname)))
352                                          (multiple-value-bind (value foundp)
353                                              (gethash object ,stable)
354                                            (declare (ignore value))
355                                            foundp))
356                                        (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
357                                          (remhash object ,stable)))))))
358                 (setf (proto-message-type extra-field) :extends) ;this field is an extension
359                 (setf (proto-fields extends) (nconc (proto-fields extends) (list extra-field)))
360                 (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list extra-field)))))))
361           (otherwise
362            (multiple-value-bind (field slot idx)
363                (process-field field index :conc-name conc-name :alias-for alias-for)
364              (assert (not (find-field extends (proto-index field))) ()
365                      "The field ~S overlaps with another field in ~S"
366                      (proto-value field) (proto-class extends))
367              (assert (index-within-extensions-p idx message) ()
368                      "The index ~D is not in range for extending ~S"
369                      idx (proto-class message))
370              (setq index idx)
371              (when slot
372                (let* ((inits  (cdr slot))
373                       (sname  (car slot))
374                       (stable (fintern "~A-VALUES" sname))
375                       (stype  (getf inits :type))
376                       (reader (or (getf inits :accessor)
377                                   (getf inits :reader)
378                                   (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
379                                           *protobuf-package*)))
380                       (writer (or (getf inits :writer)
381                                   (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
382                       (default (getf inits :initform)))
383                  ;; For the extended slots, each slot gets its own table
384                  ;; keyed by the object, which lets us avoid having a slot in each
385                  ;; instance that holds a table keyed by the slot name
386                  ;; Multiple 'define-extends' on the same class in the same image
387                  ;; will result in harmless redefinitions, so squelch the warnings
388                  ;;--- Maybe these methods need to be defined in 'define-message'?
389                  (collect-form `(without-redefinition-warnings ()
390                                   (let ((,stable #+ccl  (make-hash-table :test #'eq :weak t)
391                                                  #+sbcl (make-hash-table :test #'eq :weakness :value)))
392                                     ,@(and reader `((defmethod ,reader ((object ,type))
393                                                       (gethash object ,stable ,default))))
394                                     ,@(and writer `((defmethod ,writer ((object ,type) value)
395                                                       (declare (type ,stype value))
396                                                       (setf (gethash object ,stable) value))))
397                                     ,@(and writer `((defsetf ,reader ,writer)))
398                                     ;; For Python compatibility
399                                     (defmethod get-extension ((object ,type) (slot (eql ',sname)))
400                                       (values (gethash object ,stable ,default)))
401                                     (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
402                                       (setf (gethash object ,stable) value))
403                                     (defmethod has-extension ((object ,type) (slot (eql ',sname)))
404                                       (multiple-value-bind (value foundp)
405                                           (gethash object ,stable)
406                                         (declare (ignore value))
407                                         foundp))
408                                     (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
409                                       (remhash object ,stable)))))
410                  ;; This so that (de)serialization works
411                  (setf (proto-reader field) reader
412                        (proto-writer field) writer)))
413              (setf (proto-message-type field) :extends)         ;this field is an extension
414              (setf (proto-fields extends) (nconc (proto-fields extends) (list field)))
415              (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list field)))))))
416       `(progn
417          define-extend
418          ,extends
419          ,forms))))
420
421 (defun index-within-extensions-p (index message)
422   (let ((extensions (proto-extensions message)))
423     (some #'(lambda (ext)
424               (and (i>= index (proto-extension-from ext))
425                    (i<= index (proto-extension-to ext))))
426           extensions)))
427
428 (defmacro define-group (type (&key index arity name conc-name alias-for reader options documentation)
429                         &body fields &environment env)
430   "Define a message named 'type' and a Lisp 'defclass', *and* a field named type.
431    This is deprecated in Protobufs, but if you have to use it, you must give
432    'index' as the field index and 'arity' of :required, :optional or :repeated.
433    'name' can be used to override the defaultly generated Protobufs message name.
434    The body consists of fields, or 'define-enum' or 'define-message' forms.
435    'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
436    If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
437    used as an alias for a class that already exists in Lisp. This feature is intended
438    to be used to define messages that will be serialized from existing Lisp classes;
439    unless you get the slot names or readers exactly right for each field, it will be
440    the case that trying to (de)serialize into a Lisp object won't work.
441    'options' is a set of keyword/value pairs, both of which are strings.
442
443    Fields take the form (slot &key type name default reader)
444    'slot' can be either a symbol giving the field name, or a list whose
445    first element is the slot name and whose second element is the index.
446    'type' is the type of the slot.
447    'name' can be used to override the defaultly generated Protobufs field name.
448    'default' is the default value for the slot.
449    'reader' is a Lisp slot reader function to use to get the value, instead of
450    using 'slot-value'; this is often used when aliasing an existing class.
451    'writer' is a Lisp slot writer function to use to set the value."
452   (check-type index integer)
453   (check-type arity (member :required :optional :repeated))
454   (let* ((slot    (or type (and name (proto->slot-name name *protobuf-package*))))
455          (name    (or name (class-name->proto type)))
456          (options (loop for (key val) on options by #'cddr
457                         collect (make-instance 'protobuf-option
458                                   :name  (if (symbolp key) (slot-name->proto key) key)
459                                   :value val)))
460          (conc-name (and conc-name (string conc-name)))
461          (reader  (or reader
462                       (let ((msg-conc (proto-conc-name *protobuf*)))
463                         (and msg-conc
464                              (intern (format nil "~A~A" msg-conc slot) *protobuf-package*)))))
465          (mslot   (unless alias-for
466                     `(,slot ,@(case arity
467                                 (:required
468                                  `(:type ,type))
469                                 (:optional
470                                  `(:type (or ,type null)
471                                    :initform nil))
472                                 (:repeated
473                                  `(:type (list-of ,type)
474                                    :initform ())))
475                             ,@(and reader
476                                    `(:accessor ,reader))
477                             :initarg ,(kintern (symbol-name slot)))))
478          (mfield  (make-instance 'protobuf-field
479                     :name  (slot-name->proto slot)
480                     :type  name
481                     :class type
482                     :required arity
483                     :index index
484                     :value slot
485                     :reader reader
486                     :message-type :group))
487          (message (make-instance 'protobuf-message
488                     :class type
489                     :name  name
490                     :alias-for alias-for
491                     :conc-name conc-name
492                     :options   (remove-options options "default" "packed")
493                     :message-type :group                ;this message is a group
494                     :documentation documentation))
495          (index 0)
496          (*protobuf* message))
497     (with-collectors ((slots collect-slot)
498                       (forms collect-form))
499       (dolist (field fields)
500         (case (car field)
501           ((define-enum define-message define-extend define-extension define-group)
502            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
503                (macroexpand-1 field env)
504              (assert (eq progn 'progn) ()
505                      "The macroexpansion for ~S failed" field)
506              (map () #'collect-form definers)
507              (ecase model-type
508                ((define-enum)
509                 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
510                ((define-message define-extend)
511                 (setf (proto-parent model) message)
512                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
513                 (when (eq (proto-message-type model) :extends)
514                   (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
515                ((define-group)
516                 (setf (proto-parent model) message)
517                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
518                 (when extra-slot
519                   (collect-slot extra-slot))
520                 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
521                ((define-extension)
522                 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
523           (otherwise
524            (multiple-value-bind (field slot idx)
525                (process-field field index :conc-name conc-name :alias-for alias-for)
526              (assert (not (find-field message (proto-index field))) ()
527                      "The field ~S overlaps with another field in ~S"
528                      (proto-value field) (proto-class message))
529              (setq index idx)
530              (when slot
531                (collect-slot slot))
532              (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
533       (if alias-for
534         ;; If we've got an alias, define a a type that is the subtype of
535         ;; the Lisp class that typep and subtypep work
536         (unless (or (eq type alias-for) (find-class type nil))
537           (collect-form `(deftype ,type () ',alias-for)))
538         ;; If no alias, define the class now
539         (collect-form `(defclass ,type () (,@slots)
540                          ,@(and documentation `((:documentation ,documentation))))))
541       `(progn
542          define-group
543          ,message
544          ,forms
545          ,mfield
546          ,mslot))))
547
548 (defun process-field (field index &key conc-name alias-for)
549   "Process one field descriptor within 'define-message' or 'define-extend'.
550    Returns a 'proto-field' object, a CLOS slot form and the incremented field index."
551   (when (i= index 18999)                                ;skip over the restricted range
552     (setq index 19999))
553   (destructuring-bind (slot &rest other-options 
554                        &key type reader writer name (default nil default-p) packed
555                             options documentation &allow-other-keys) field
556     (let* ((idx  (if (listp slot) (second slot) (iincf index)))
557            (slot (if (listp slot) (first slot) slot))
558            (reader (or reader
559                        (and conc-name
560                             (intern (format nil "~A~A" conc-name slot) *protobuf-package*))))
561            (options (append
562                      (loop for (key val) on other-options by #'cddr
563                            unless (member key '(:type :reader :writer :name :default :packed :documentation))
564                              collect (make-instance 'protobuf-option
565                                        :name  (slot-name->proto key)
566                                        :value val))
567                      (loop for (key val) on options by #'cddr
568                          collect (make-instance 'protobuf-option
569                                    :name  (if (symbolp key) (slot-name->proto key) key)
570                                    :value val)))))
571       (multiple-value-bind (ptype pclass)
572           (clos-type-to-protobuf-type type)
573         (multiple-value-bind (reqd vectorp)
574             (clos-type-to-protobuf-required type)
575           (let* ((default (if (eq reqd :repeated)
576                             (if vectorp $empty-vector $empty-list)      ;to distinguish between list-of and vector-of
577                             (if default-p default $empty-default)))
578                  (cslot (unless alias-for
579                           `(,slot :type ,type
580                                   ,@(and reader
581                                          (if writer
582                                            `(:reader ,reader)
583                                            `(:accessor ,reader)))
584                                   ,@(and writer
585                                          `(:writer ,writer))
586                                   :initarg ,(kintern (symbol-name slot))
587                                   ,@(cond ((eq reqd :repeated)
588                                            ;; Repeated fields get a container for their elements
589                                            (if vectorp
590                                              `(:initform (make-array 5 :fill-pointer 0 :adjustable t))
591                                              `(:initform ())))
592                                           ((and (not default-p)
593                                                 (eq reqd :optional)
594                                                 ;; Use unbound for booleans only
595                                                 (not (eq pclass :bool)))
596                                            `(:initform nil))
597                                           (default-p
598                                             `(:initform ,(protobuf-default-to-clos-init default type)))))))
599                  (field (make-instance 'protobuf-field
600                           :name  (or name (slot-name->proto slot))
601                           :type  ptype
602                           :class pclass
603                           ;; One of :required, :optional or :repeated
604                           :required reqd
605                           :index  idx
606                           :value  slot
607                           :reader reader
608                           :writer writer
609                           :default default
610                           ;; Pack the field only if requested and it actually makes sense
611                           :packed  (and (eq reqd :repeated) packed t)
612                           :options options
613                           :documentation documentation)))
614             (values field cslot idx)))))))
615
616 ;; Define a service named 'type' with generic functions declared for
617 ;; each of the methods within the service
618 (defmacro define-service (type (&key name options documentation)
619                           &body method-specs)
620   "Define a service named 'type' and Lisp 'defgeneric' for all its methods.
621    'name' can be used to override the defaultly generated Protobufs service name.
622    'options' is a set of keyword/value pairs, both of which are strings.
623
624    The body is a set of method specs of the form (name (input-type output-type) &key options).
625    'input-type' and 'output-type' may also be of the form (type &key name)."
626   (let* ((name    (or name (class-name->proto type)))
627          (options (loop for (key val) on options by #'cddr
628                         collect (make-instance 'protobuf-option
629                                   :name  (if (symbolp key) (slot-name->proto key) key)
630                                   :value val)))
631          (service (make-instance 'protobuf-service
632                     :class type
633                     :name  name
634                     :options options
635                     :documentation documentation))
636          (index 0))
637     (with-collectors ((forms collect-form))
638       (dolist (method method-specs)
639         (destructuring-bind (function (input-type output-type) &key name options documentation) method
640           (let* ((input-name (and (listp input-type)
641                                   (getf (cdr input-type) :name)))
642                  (input-type (if (listp input-type) (car input-type) input-type))
643                  (output-name (and (listp output-type)
644                                    (getf (cdr output-type) :name)))
645                  (output-type (if (listp output-type) (car output-type) output-type))
646                  (options (loop for (key val) on options by #'cddr
647                                 collect (make-instance 'protobuf-option
648                                           :name  (if (symbolp key) (slot-name->proto key) key)
649                                           :value val)))
650                  (method  (make-instance 'protobuf-method
651                             :class function
652                             :name  (or name (class-name->proto function))
653                             :input-type  input-type
654                             :input-name  (or input-name (class-name->proto input-type))
655                             :output-type output-type
656                             :output-name (or output-name (class-name->proto output-type))
657                             :index (iincf index)
658                             :options options
659                             :documentation documentation)))
660             (setf (proto-methods service) (nconc (proto-methods service) (list method)))
661             ;; The following are the hooks to CL-Stubby
662             (let* ((package   *protobuf-package*)
663                    (client-fn function)
664                    (server-fn (intern (format nil "~A-~A" 'do function) package))
665                    (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 synchronous).
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 &key ,vcallback)
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*))))))