]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - define-proto.lisp
integer encoding/decoding tests
[cl-protobufs.git] / define-proto.lisp
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;;                                                                  ;;;
3 ;;; Free Software published under an MIT-like license. See LICENSE   ;;;
4 ;;;                                                                  ;;;
5 ;;; Copyright (c) 2012 Google, Inc.  All rights reserved.            ;;;
6 ;;;                                                                  ;;;
7 ;;; Original author: Scott McKay                                     ;;;
8 ;;;                                                                  ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
10
11 (in-package "PROTO-IMPL")
12
13
14 ;;; Protocol buffer defining macros
15
16 ;; Define a schema named 'type', corresponding to a .proto file of that name
17 (defmacro define-schema (type (&key name syntax package lisp-package import optimize
18                                     options documentation)
19                          &body messages &environment env)
20   "Define a schema named 'type', corresponding to a .proto file of that name.
21    'name' can be used to override the defaultly generated Protobufs name.
22    'syntax' and 'package' are as they would be in a .proto file.
23    'lisp-package' can be used to specify a Lisp package if it is different from
24    the Protobufs package given by 'package'.
25    'import' is a list of pathname strings to be imported.
26    'optimize' can be either :space (the default) or :speed; if it is :speed, the
27    serialization code will be much faster, but much less compact.
28    'options' is a property list, i.e., (\"key1\" \"val1\" \"key2\" \"val2\" ...).
29
30    The body consists of 'define-enum', 'define-message' or 'define-service' forms."
31   (let* ((name     (or name (class-name->proto type)))
32          (package  (and package (if (stringp package) package (string-downcase (string package)))))
33          (lisp-pkg (and lisp-package (if (stringp lisp-package) lisp-package (string lisp-package))))
34          (options  (remove-options
35                      (loop for (key val) on options by #'cddr
36                            collect (make-instance 'protobuf-option
37                                      :name  (if (symbolp key) (slot-name->proto key) key)
38                                      :value val))
39                      "optimize_for" "lisp_package"))
40          (imports  (if (listp import) import (list import)))
41          (schema   (make-instance 'protobuf-schema
42                      :class    type
43                      :name     name
44                      :syntax   (or syntax "proto2")
45                      :package  package
46                      :lisp-package (or lisp-pkg (substitute #\- #\_ package))
47                      :imports  imports
48                      :options  (if optimize
49                                  (append options (list (make-instance 'protobuf-option
50                                                          :name  "optimize_for"
51                                                          :value (if (eq optimize :speed) "SPEED" "CODE_SIZE")
52                                                          :type  'symbol)))
53                                  options)
54                      :documentation documentation))
55          (*protobuf* schema)
56          (*protobuf-package* (or (find-proto-package lisp-pkg) *package*)))
57     (process-imports schema imports)
58     (with-collectors ((forms collect-form))
59       (dolist (msg messages)
60         (assert (and (listp msg)
61                      (member (car msg) '(define-enum define-message define-extend define-service
62                                          define-type-alias))) ()
63                 "The body of ~S must be one of ~{~S~^ or ~}"
64                 'define-schema
65                 '(define-enum define-message define-extend define-service define-type-alias))
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-type-alias)
80              (setf (proto-type-aliases schema) (nconc (proto-type-aliases schema) (list model))))
81             ((define-message define-extend)
82              (setf (proto-parent model) schema)
83              (setf (proto-messages schema) (nconc (proto-messages schema) (list model)))
84              (when (eq (proto-message-type model) :extends)
85                (setf (proto-extenders schema) (nconc (proto-extenders schema) (list model)))))
86             ((define-service)
87              (setf (proto-services schema) (nconc (proto-services schema) (list model)))))))
88       (let ((var (intern (format nil "*~A*" type) *protobuf-package*)))
89         `(progn
90            ,@forms
91            (defvar ,var nil)
92            (let* ((old-schema ,var)
93                   (new-schema ,schema))
94              (when old-schema
95                (multiple-value-bind (upgradable warnings)
96                    (schema-upgradable old-schema new-schema)
97                  (unless upgradable
98                    (protobufs-warn "The old schema for ~S (~A) can't be safely upgraded; proceeding anyway"
99                                    ',type ',name)
100                    (map () #'protobufs-warn warnings))))
101              (setq ,var new-schema)
102              (record-protobuf ,var))
103            ,@(with-collectors ((messages collect-message))
104                (labels ((collect-messages (message)
105                           (collect-message message)
106                           (map () #'collect-messages (proto-messages message))))
107                  (map () #'collect-messages (proto-messages schema)))
108                (append 
109                 (mapcar #'(lambda (m) `(record-protobuf ,m)) messages)
110                 (when (eq optimize :speed)
111                   (append (mapcar #'generate-object-size  messages)
112                           (mapcar #'generate-serializer   messages)
113                           (mapcar #'generate-deserializer messages)))))
114            ,var)))))
115
116 (defmacro with-proto-source-location ((type name definition-type
117                                        &optional pathname start-pos end-pos)
118                                       &body body)
119   "Establish a context which causes the generated Lisp code to have
120    source location information that points to the .proto file.
121    'type' is the name of the Lisp definition (a symbol).
122    'name' is the name of the Protobufs definition (a string).
123    'definition-type' is the kind of definition, e.g., 'protobuf-enum'.
124    'pathname', 'start-pos' and 'end-pos' give the location of the definition
125    in the .proto file."
126   `(progn
127      (record-proto-source-location ',type ,name ',definition-type
128                                    ,pathname ,start-pos ,end-pos)
129      ,@body))
130
131 #+ccl
132 (defun record-proto-source-location (type name definition-type
133                                      &optional pathname start-pos end-pos)
134   (declare (ignore name))
135   (when (and ccl::*record-source-file*
136              (typep pathname '(or string pathname)))
137     (let ((ccl::*loading-toplevel-location* (ccl::make-source-note :filename  pathname
138                                                                    :start-pos start-pos
139                                                                    :end-pos   end-pos)))
140       (ccl:record-source-file type definition-type))))
141
142 #-(or ccl)
143 (defun record-proto-source-location (type name definition-type
144                                      &optional pathname start-pos end-pos)
145   (declare (ignorable name type definition-type pathname start-pos end-pos)))
146
147 ;; Define an enum type named 'type' and a Lisp 'deftype'
148 (defmacro define-enum (type (&key name conc-name alias-for options
149                                   documentation source-location)
150                        &body values)
151   "Define a Protobufs enum type and a Lisp 'deftype' named 'type'.
152    'name' can be used to override the defaultly generated Protobufs enum name.
153    'conc-name' will be used as the prefix to the Lisp enum names, if it's supplied.
154    If 'alias-for' is given, no Lisp 'deftype' will be defined. Instead, the enum
155    will be used as an alias for an enum type that already exists in Lisp.
156    'options' is a set of keyword/value pairs, both of which are strings.
157
158    The body consists of the enum values in the form 'name' or (name index)."
159   (let* ((name    (or name (class-name->proto type)))
160          (options (loop for (key val) on options by #'cddr
161                         collect (make-instance 'protobuf-option
162                                   :name  (if (symbolp key) (slot-name->proto key) key)
163                                   :value val)))
164          (conc-name (conc-name-for-type type conc-name))
165          (index -1)
166          (enum  (make-instance 'protobuf-enum
167                   :class  type
168                   :name   name
169                   :qualified-name (make-qualified-name *protobuf* name)
170                   :parent *protobuf*
171                   :alias-for alias-for
172                   :options options
173                   :documentation documentation
174                   :source-location source-location)))
175     (with-collectors ((vals  collect-val)
176                       (forms collect-form))
177       (dolist (val values)
178         ;; Allow old (name index) and new (name :index index)
179         (let* ((idx  (if (listp val)
180                        (if (eq (second val) :index) (third val) (second val))
181                        (incf index)))
182                (name (if (listp val) (first val)  val))
183                (val-name  (kintern (if conc-name (format nil "~A~A" conc-name name) (symbol-name name))))
184                (enum-name (if conc-name (format nil "~A~A" conc-name name) (symbol-name name)))
185                (vname     (enum-name->proto enum-name))
186                (enum-val  (make-instance 'protobuf-enum-value
187                             :name   vname
188                             :qualified-name (make-qualified-name enum vname)
189                             :index  idx
190                             :value  val-name
191                             :parent enum)))
192           (collect-val val-name)
193           (setf (proto-values enum) (nconc (proto-values enum) (list enum-val)))))
194       (if alias-for
195         ;; If we've got an alias, define a a type that is the subtype of
196         ;; the Lisp enum so that typep and subtypep work
197         (unless (eq type alias-for)
198           (collect-form `(deftype ,type () ',alias-for)))
199         ;; If no alias, define the Lisp enum type now
200         (collect-form `(deftype ,type () '(member ,@vals))))
201       `(progn
202          define-enum
203          ,enum
204          ((with-proto-source-location (,type ,name protobuf-enum ,@source-location)
205             ,@forms))))))
206
207 ;; Define a message named 'name' and a Lisp 'defclass'
208 (defmacro define-message (type (&key name conc-name alias-for options
209                                      documentation source-location)
210                           &body fields &environment env)
211   "Define a message named 'type' and a Lisp 'defclass'.
212    'name' can be used to override the defaultly generated Protobufs message name.
213    The body consists of fields, or 'define-enum' or 'define-message' forms.
214    'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
215    If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
216    used as an alias for a class that already exists in Lisp. This feature is intended
217    to be used to define messages that will be serialized from existing Lisp classes;
218    unless you get the slot names or readers exactly right for each field, it will be
219    the case that trying to (de)serialize into a Lisp object won't work.
220    'options' is a set of keyword/value pairs, both of which are strings.
221
222    Fields take the form (slot &key type name default reader)
223    'slot' can be either a symbol giving the field name, or a list whose
224    first element is the slot name and whose second element is the index.
225    'type' is the type of the slot.
226    'name' can be used to override the defaultly generated Protobufs field name.
227    'default' is the default value for the slot.
228    'reader' is a Lisp slot reader function to use to get the value, instead of
229    using 'slot-value'; this is often used when aliasing an existing class.
230    'writer' is a Lisp slot writer function to use to set the value."
231   (let* ((name    (or name (class-name->proto type)))
232          (options (loop for (key val) on options by #'cddr
233                         collect (make-instance 'protobuf-option
234                                   :name  (if (symbolp key) (slot-name->proto key) key)
235                                   :value val)))
236          (conc-name (conc-name-for-type type conc-name))
237          (message (make-instance 'protobuf-message
238                     :class type
239                     :name  name
240                     :qualified-name (make-qualified-name *protobuf* name)
241                     :parent *protobuf*
242                     :alias-for alias-for
243                     :conc-name conc-name
244                     :options   (remove-options options "default" "packed")
245                     :documentation documentation
246                     :source-location source-location))
247          (index 0)
248          ;; Only now can we bind *protobuf* to the new message
249          (*protobuf* message))
250     (with-collectors ((slots collect-slot)
251                       (forms collect-form)
252                       ;; The typedef needs to be first in forms otherwise ccl warns.
253                       ;; We'll collect them separately and splice them in first.
254                       (type-forms collect-type-form))
255       (dolist (field fields)
256         (case (car field)
257           ((define-enum define-message define-extend define-extension define-group
258             define-type-alias)
259            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
260                (macroexpand-1 field env)
261              (assert (eq progn 'progn) ()
262                      "The macroexpansion for ~S failed" field)
263              (map () #'collect-form definers)
264              (ecase model-type
265                ((define-enum)
266                 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
267                ((define-type-alias)
268                 (setf (proto-type-aliases message) (nconc (proto-type-aliases message) (list model))))
269                ((define-message define-extend)
270                 (setf (proto-parent model) message)
271                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
272                 (when (eq (proto-message-type model) :extends)
273                   (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
274                ((define-group)
275                 (setf (proto-parent model) message)
276                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
277                 (when extra-slot
278                   (collect-slot extra-slot))
279                 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
280                ((define-extension)
281                 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
282           (otherwise
283            (multiple-value-bind (field slot idx)
284                (process-field field index :conc-name conc-name :alias-for alias-for)
285              (assert (not (find-field message (proto-index field))) ()
286                      "The field ~S overlaps with another field in ~S"
287                      (proto-value field) (proto-class message))
288              (setq index idx)
289              (when slot
290                (collect-slot slot))
291              (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
292       (if alias-for
293         ;; If we've got an alias, define a a type that is the subtype of
294         ;; the Lisp class that typep and subtypep work
295         (unless (or (eq type alias-for) (find-class type nil))
296           (collect-type-form `(deftype ,type () ',alias-for)))
297         ;; If no alias, define the class now
298         (collect-type-form `(defclass ,type () (,@slots)
299                          ,@(and documentation `((:documentation ,documentation))))))
300       `(progn
301          define-message
302          ,message
303          ((with-proto-source-location (,type ,name protobuf-message ,@source-location)
304             ,@type-forms
305             ,@forms))))))
306
307 (defun conc-name-for-type (type conc-name)
308   (and conc-name
309        (typecase conc-name
310          ((member t) (format nil "~:@(~A~)-" type))
311          ((or string symbol) (string-upcase (string conc-name)))
312          (t nil))))
313
314 (defmacro define-extension (from to)
315   "Define an extension range within a message.
316    The \"body\" is the start and end of the range, both inclusive."
317   (let ((to (etypecase to
318               (integer to)
319               (symbol (if (string-equal to "MAX") #.(1- (ash 1 29)) to)))))
320     `(progn
321        define-extension
322        ,(make-instance 'protobuf-extension
323           :from from
324           :to   (if (eq to 'max) #.(1- (ash 1 29)) to))
325        ())))
326
327 (defmacro define-extend (type (&key name conc-name options documentation)
328                          &body fields &environment env)
329   "Define an extension to the message named 'type'.
330    'name' can be used to override the defaultly generated Protobufs message name.
331    The body consists only  of fields.
332    'options' is a set of keyword/value pairs, both of which are strings.
333
334    Fields take the form (slot &key type name default reader)
335    'slot' can be either a symbol giving the field name, or a list whose
336    first element is the slot name and whose second element is the index.
337    'type' is the type of the slot.
338    'name' can be used to override the defaultly generated Protobufs field name.
339    'default' is the default value for the slot.
340    'reader' is a Lisp slot reader function to use to get the value, instead of
341    using 'slot-value'; this is often used when aliasing an existing class.
342    'writer' is a Lisp slot writer function to use to set the value."
343   (let* ((name    (or name (class-name->proto type)))
344          (options (loop for (key val) on options by #'cddr
345                         collect (make-instance 'protobuf-option
346                                   :name  (if (symbolp key) (slot-name->proto key) key)
347                                   :value val)))
348          (message   (find-message *protobuf* type))
349          (conc-name (or (conc-name-for-type type conc-name)
350                         (and message (proto-conc-name message))))
351          (alias-for (and message (proto-alias-for message)))
352          (extends (and message
353                        (make-instance 'protobuf-message
354                          :class  (proto-class message)
355                          :name   (proto-name message)
356                          :qualified-name (proto-qualified-name message)
357                          :parent *protobuf*
358                          :alias-for alias-for
359                          :conc-name conc-name
360                          :enums    (copy-list (proto-enums message))
361                          :messages (copy-list (proto-messages message))
362                          :fields   (copy-list (proto-fields message))
363                          :extensions (copy-list (proto-extensions message))
364                          :options  (remove-options
365                                      (or options (copy-list (proto-options message))) "default" "packed")
366                          :message-type :extends         ;this message is an extension
367                          :documentation documentation
368                          :type-aliases  (copy-list (proto-type-aliases message)))))
369          ;; Only now can we bind *protobuf* to the new extended message
370          (*protobuf* extends)
371          (index 0))
372     (assert message ()
373             "There is no message named ~A to extend" name)
374     (assert (eq type (proto-class message)) ()
375             "The type ~S doesn't match the type of the message being extended ~S"
376             type message)
377     (with-collectors ((forms collect-form))
378       (dolist (field fields)
379         (assert (not (member (car field)
380                              '(define-enum define-message define-extend define-extension
381                                define-type-alias))) ()
382                 "The body of ~S can only contain field and group definitions" 'define-extend)
383         (case (car field)
384           ((define-group)
385            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
386                (macroexpand-1 field env)
387              (assert (eq progn 'progn) ()
388                      "The macroexpansion for ~S failed" field)
389              (map () #'collect-form definers)
390              (ecase model-type
391                ((define-group)
392                 (setf (proto-parent model) extends)
393                 (setf (proto-messages extends) (nconc (proto-messages extends) (list model)))
394                 (when extra-slot
395                   ;;--- Refactor to get rid of all this duplicated code!
396                   (let* ((inits  (cdr extra-slot))
397                          (sname  (car extra-slot))
398                          (stable (fintern "~A-VALUES" sname))
399                          (stype  (getf inits :type))
400                          (reader (or (getf inits :accessor)
401                                      (getf inits :reader)
402                                      (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
403                                              *protobuf-package*)))
404                          (writer (or (getf inits :writer)
405                                      (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
406                          (default (getf inits :initform)))
407                     (collect-form `(without-redefinition-warnings ()
408                                      (let ((,stable #+ccl  (make-hash-table :test #'eq :weak t)
409                                                     #+sbcl (make-hash-table :test #'eq :weakness :value)))
410                                        ,@(and reader `((defmethod ,reader ((object ,type))
411                                                          (gethash object ,stable ,default))))
412                                        ,@(and writer `((defmethod ,writer ((object ,type) value)
413                                                          (declare (type ,stype value))
414                                                          (setf (gethash object ,stable) value))))
415                                        ;; For Python compatibility
416                                        (defmethod get-extension ((object ,type) (slot (eql ',sname)))
417                                          (values (gethash object ,stable ,default)))
418                                        (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
419                                          (setf (gethash object ,stable) value))
420                                        (defmethod has-extension ((object ,type) (slot (eql ',sname)))
421                                          (multiple-value-bind (value foundp)
422                                              (gethash object ,stable)
423                                            (declare (ignore value))
424                                            foundp))
425                                        (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
426                                          (remhash object ,stable)))
427                                      ,@(and writer
428                                             ;; 'defsetf' needs to be visible at compile time
429                                             `((eval-when (:compile-toplevel :load-toplevel :execute)
430                                                 (defsetf ,reader ,writer))))))))
431                 (setf (proto-message-type extra-field) :extends) ;this field is an extension
432                 (setf (proto-fields extends) (nconc (proto-fields extends) (list extra-field)))
433                 (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list extra-field)))))))
434           (otherwise
435            (multiple-value-bind (field slot idx)
436                (process-field field index :conc-name conc-name :alias-for alias-for)
437              (assert (not (find-field extends (proto-index field))) ()
438                      "The field ~S overlaps with another field in ~S"
439                      (proto-value field) (proto-class extends))
440              (assert (index-within-extensions-p idx message) ()
441                      "The index ~D is not in range for extending ~S"
442                      idx (proto-class message))
443              (setq index idx)
444              (when slot
445                (let* ((inits  (cdr slot))
446                       (sname  (car slot))
447                       (stable (fintern "~A-VALUES" sname))
448                       (stype  (getf inits :type))
449                       (reader (or (getf inits :accessor)
450                                   (getf inits :reader)
451                                   (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
452                                           *protobuf-package*)))
453                       (writer (or (getf inits :writer)
454                                   (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
455                       (default (getf inits :initform)))
456                  ;; For the extended slots, each slot gets its own table
457                  ;; keyed by the object, which lets us avoid having a slot in each
458                  ;; instance that holds a table keyed by the slot name
459                  ;; Multiple 'define-extends' on the same class in the same image
460                  ;; will result in harmless redefinitions, so squelch the warnings
461                  ;;--- Maybe these methods need to be defined in 'define-message'?
462                  (collect-form `(without-redefinition-warnings ()
463                                   (let ((,stable #+ccl  (make-hash-table :test #'eq :weak t)
464                                                  #+sbcl (make-hash-table :test #'eq :weakness :value)))
465                                     ,@(and reader `((defmethod ,reader ((object ,type))
466                                                       (gethash object ,stable ,default))))
467                                     ,@(and writer `((defmethod ,writer ((object ,type) value)
468                                                       (declare (type ,stype value))
469                                                       (setf (gethash object ,stable) value))))
470                                     (defmethod get-extension ((object ,type) (slot (eql ',sname)))
471                                       (values (gethash object ,stable ,default)))
472                                     (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
473                                       (setf (gethash object ,stable) value))
474                                     (defmethod has-extension ((object ,type) (slot (eql ',sname)))
475                                       (multiple-value-bind (value foundp)
476                                           (gethash object ,stable)
477                                         (declare (ignore value))
478                                         foundp))
479                                     (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
480                                       (remhash object ,stable)))
481                                   ,@(and writer
482                                          `((eval-when (:compile-toplevel :load-toplevel :execute)
483                                              (defsetf ,reader ,writer))))))
484                  ;; This so that (de)serialization works
485                  (setf (proto-reader field) reader
486                        (proto-writer field) writer)))
487              (setf (proto-message-type field) :extends)         ;this field is an extension
488              (setf (proto-fields extends) (nconc (proto-fields extends) (list field)))
489              (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list field)))))))
490       `(progn
491          define-extend
492          ,extends
493          ,forms))))
494
495 (defun index-within-extensions-p (index message)
496   (let ((extensions (proto-extensions message)))
497     (some #'(lambda (ext)
498               (and (i>= index (proto-extension-from ext))
499                    (i<= index (proto-extension-to ext))))
500           extensions)))
501
502 (defmacro define-group (type (&key index arity name conc-name alias-for reader options
503                                    documentation source-location)
504                         &body fields &environment env)
505   "Define a message named 'type' and a Lisp 'defclass', *and* a field named type.
506    This is deprecated in Protobufs, but if you have to use it, you must give
507    'index' as the field index and 'arity' of :required, :optional or :repeated.
508    'name' can be used to override the defaultly generated Protobufs message name.
509    The body consists of fields, or 'define-enum' or 'define-message' forms.
510    'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
511    If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
512    used as an alias for a class that already exists in Lisp. This feature is intended
513    to be used to define messages that will be serialized from existing Lisp classes;
514    unless you get the slot names or readers exactly right for each field, it will be
515    the case that trying to (de)serialize into a Lisp object won't work.
516    'options' is a set of keyword/value pairs, both of which are strings.
517
518    Fields take the form (slot &key type name default reader)
519    'slot' can be either a symbol giving the field name, or a list whose
520    first element is the slot name and whose second element is the index.
521    'type' is the type of the slot.
522    'name' can be used to override the defaultly generated Protobufs field name.
523    'default' is the default value for the slot.
524    'reader' is a Lisp slot reader function to use to get the value, instead of
525    using 'slot-value'; this is often used when aliasing an existing class.
526    'writer' is a Lisp slot writer function to use to set the value."
527   (check-type index integer)
528   (check-type arity (member :required :optional :repeated))
529   (let* ((slot    (or type (and name (proto->slot-name name *protobuf-package*))))
530          (name    (or name (class-name->proto type)))
531          (options (loop for (key val) on options by #'cddr
532                         collect (make-instance 'protobuf-option
533                                   :name  (if (symbolp key) (slot-name->proto key) key)
534                                   :value val)))
535          (conc-name (conc-name-for-type type conc-name))
536          (reader  (or reader
537                       (let ((msg-conc (proto-conc-name *protobuf*)))
538                         (and msg-conc
539                              (intern (format nil "~A~A" msg-conc slot) *protobuf-package*)))))
540          (mslot   (unless alias-for
541                     `(,slot ,@(case arity
542                                 (:required
543                                  `(:type ,type))
544                                 (:optional
545                                  `(:type (or ,type null)
546                                    :initform nil))
547                                 (:repeated
548                                  `(:type (list-of ,type)
549                                    :initform ())))
550                             ,@(and reader
551                                    `(:accessor ,reader))
552                             :initarg ,(kintern (symbol-name slot)))))
553          (mfield  (make-instance 'protobuf-field
554                     :name  (slot-name->proto slot)
555                     :type  name
556                     :class type
557                     :qualified-name (make-qualified-name *protobuf* (slot-name->proto slot))
558                     :parent *protobuf*
559                     :required arity
560                     :index index
561                     :value slot
562                     :reader reader
563                     :message-type :group))
564          (message (make-instance 'protobuf-message
565                     :class type
566                     :name  name
567                     :qualified-name (make-qualified-name *protobuf* name)
568                     :parent *protobuf*
569                     :alias-for alias-for
570                     :conc-name conc-name
571                     :options   (remove-options options "default" "packed")
572                     :message-type :group                ;this message is a group
573                     :documentation documentation
574                     :source-location source-location))
575          (index 0)
576          ;; Only now can we bind *protobuf* to the (group) message
577          (*protobuf* message))
578     (with-collectors ((slots collect-slot)
579                       (forms collect-form)
580                       ;; The typedef needs to be first in forms otherwise ccl warns.
581                       ;; We'll collect them separately and splice them in first.
582                       (type-forms collect-type-form))
583       (dolist (field fields)
584         (case (car field)
585           ((define-enum define-message define-extend define-extension define-group
586             define-type-alias)
587            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
588                (macroexpand-1 field env)
589              (assert (eq progn 'progn) ()
590                      "The macroexpansion for ~S failed" field)
591              (map () #'collect-form definers)
592              (ecase model-type
593                ((define-enum)
594                 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
595                ((define-type-alias)
596                 (setf (proto-type-aliases message) (nconc (proto-type-aliases message) (list model))))
597                ((define-message define-extend)
598                 (setf (proto-parent model) message)
599                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
600                 (when (eq (proto-message-type model) :extends)
601                   (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
602                ((define-group)
603                 (setf (proto-parent model) message)
604                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
605                 (when extra-slot
606                   (collect-slot extra-slot))
607                 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
608                ((define-extension)
609                 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
610           (otherwise
611            (multiple-value-bind (field slot idx)
612                (process-field field index :conc-name conc-name :alias-for alias-for)
613              (assert (not (find-field message (proto-index field))) ()
614                      "The field ~S overlaps with another field in ~S"
615                      (proto-value field) (proto-class message))
616              (setq index idx)
617              (when slot
618                (collect-slot slot))
619              (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
620       (if alias-for
621         ;; If we've got an alias, define a a type that is the subtype of
622         ;; the Lisp class that typep and subtypep work
623         (unless (or (eq type alias-for) (find-class type nil))
624           (collect-type-form `(deftype ,type () ',alias-for)))
625         ;; If no alias, define the class now
626         (collect-type-form `(defclass ,type () (,@slots)
627                          ,@(and documentation `((:documentation ,documentation))))))
628       `(progn
629          define-group
630          ,message
631          ((with-proto-source-location (,type ,name protobuf-message ,@source-location)
632             ,@type-forms
633             ,@forms))
634          ,mfield
635          ,mslot))))
636
637 (defun process-field (field index &key conc-name alias-for)
638   "Process one field descriptor within 'define-message' or 'define-extend'.
639    Returns a 'proto-field' object, a CLOS slot form and the incremented field index."
640   (when (i= index 18999)                                ;skip over the restricted range
641     (setq index 19999))
642   (destructuring-bind (slot &rest other-options 
643                        &key type reader writer name (default nil default-p) packed
644                             ((:index idx)) options documentation &allow-other-keys) field
645     ;; Allow old ((slot index) ...) or new (slot :index ...),
646     ;; but only allow one of those two to be used simultaneously
647     (assert (if idx (not (listp slot)) t) ()
648             "Use either ((slot index) ...)  or (slot :index index ...), but not both")
649     (let* ((idx  (or idx (if (listp slot) (second slot) (iincf index))))
650            (slot (if (listp slot) (first slot) slot))
651            (reader (or reader
652                        (and conc-name
653                             (intern (format nil "~A~A" conc-name slot) *protobuf-package*))))
654            (options (append
655                      (loop for (key val) on other-options by #'cddr
656                            unless (member key '(:type :reader :writer :name :default :packed :documentation))
657                              collect (make-instance 'protobuf-option
658                                        :name  (slot-name->proto key)
659                                        :value val))
660                      (loop for (key val) on options by #'cddr
661                          collect (make-instance 'protobuf-option
662                                    :name  (if (symbolp key) (slot-name->proto key) key)
663                                    :value val)))))
664       (multiple-value-bind (ptype pclass)
665           (clos-type-to-protobuf-type type)
666         (multiple-value-bind (reqd vectorp)
667             (clos-type-to-protobuf-required type)
668           (let* ((default (if (eq reqd :repeated)
669                             (if vectorp $empty-vector $empty-list)      ;to distinguish between list-of and vector-of
670                             (if default-p default $empty-default)))
671                  (cslot (unless alias-for
672                           `(,slot :type ,type
673                                   ,@(and reader
674                                          (if writer
675                                            `(:reader ,reader)
676                                            `(:accessor ,reader)))
677                                   ,@(and writer
678                                          `(:writer ,writer))
679                                   :initarg ,(kintern (symbol-name slot))
680                                   ,@(cond ((eq reqd :repeated)
681                                            ;; Repeated fields get a container for their elements
682                                            (if vectorp
683                                              `(:initform (make-array 5 :fill-pointer 0 :adjustable t))
684                                              `(:initform ())))
685                                           ((and (not default-p)
686                                                 (eq reqd :optional)
687                                                 ;; Use unbound for booleans only
688                                                 (not (eq pclass :bool)))
689                                            `(:initform nil))
690                                           (default-p
691                                             `(:initform ,(protobuf-default-to-clos-init default type)))))))
692                  (field (make-instance 'protobuf-field
693                           :name  (or name (slot-name->proto slot))
694                           :type  ptype
695                           :class pclass
696                           :qualified-name (make-qualified-name *protobuf* (or name (slot-name->proto slot)))
697                           :parent *protobuf*
698                           ;; One of :required, :optional or :repeated
699                           :required reqd
700                           :index  idx
701                           :value  slot
702                           :reader reader
703                           :writer writer
704                           :default default
705                           ;; Pack the field only if requested and it actually makes sense
706                           :packed  (and (eq reqd :repeated) packed t)
707                           :options options
708                           :documentation documentation)))
709             (values field cslot idx)))))))
710
711 (defparameter *rpc-package* nil
712   "The Lisp package that implements RPC.
713    This should be set when an RPC package that uses CL-Protobufs gets loaded.")
714 (defparameter *rpc-call-function* nil
715   "The Lisp function that implements RPC client-side calls.
716    This should be set when an RPC package that uses CL-Protobufs gets loaded.")
717
718 ;; Define a service named 'type' with generic functions declared for
719 ;; each of the methods within the service
720 (defmacro define-service (type (&key name options
721                                      documentation source-location)
722                           &body method-specs)
723   "Define a service named 'type' and Lisp 'defgeneric' for all its methods.
724    'name' can be used to override the defaultly generated Protobufs service name.
725    'options' is a set of keyword/value pairs, both of which are strings.
726
727    The body is a set of method specs of the form (name (input-type [=>] output-type) &key options).
728    'input-type' and 'output-type' may also be of the form (type &key name)."
729   (let* ((name    (or name (class-name->proto type)))
730          (options (loop for (key val) on options by #'cddr
731                         collect (make-instance 'protobuf-option
732                                   :name  (if (symbolp key) (slot-name->proto key) key)
733                                   :value val)))
734          (service (make-instance 'protobuf-service
735                     :class type
736                     :name  name
737                     :qualified-name (make-qualified-name *protobuf* name)
738                     :parent *protobuf*
739                     :options options
740                     :documentation documentation
741                     :source-location source-location))
742          (index 0))
743     (with-collectors ((forms collect-form))
744       (dolist (method method-specs)
745         (destructuring-bind (function (&rest types)
746                              &key name options documentation source-location) method
747           (let* ((input-type   (first types))
748                  (output-type  (if (string= (string (second types)) "=>") (third types) (second types)))
749                  (streams-type (if (string= (string (second types)) "=>")
750                                  (getf (cdddr types) :streams)
751                                  (getf (cddr  types) :streams)))
752                  (input-name (and (listp input-type)
753                                   (getf (cdr input-type) :name)))
754                  (input-type (if (listp input-type) (car input-type) input-type))
755                  (output-name (and (listp output-type)
756                                    (getf (cdr output-type) :name)))
757                  (output-type (if (listp output-type) (car output-type) output-type))
758                  (streams-name (and (listp streams-type)
759                                     (getf (cdr streams-type) :name)))
760                  (streams-type (if (listp streams-type) (car streams-type) streams-type))
761                  (options (loop for (key val) on options by #'cddr
762                                 collect (make-instance 'protobuf-option
763                                           :name  (if (symbolp key) (slot-name->proto key) key)
764                                           :value val)))
765                  (package   *protobuf-package*)
766                  (client-fn function)
767                  (server-fn (intern (format nil "~A-~A" 'do function) package))
768                  (method  (make-instance 'protobuf-method
769                             :class function
770                             :name  (or name (class-name->proto function))
771                             :qualified-name (make-qualified-name *protobuf* (or name (class-name->proto function)))
772                             :parent service
773                             :client-stub client-fn
774                             :server-stub server-fn
775                             :input-type  input-type
776                             :input-name  (or input-name (class-name->proto input-type))
777                             :output-type output-type
778                             :output-name (or output-name (class-name->proto output-type))
779                             :streams-type streams-type
780                             :streams-name (and streams-type
781                                                (or streams-name (class-name->proto streams-type)))
782                             :index (iincf index)
783                             :options options
784                             :documentation documentation
785                             :source-location source-location)))
786             (setf (proto-methods service) (nconc (proto-methods service) (list method)))
787             ;; The following are the hooks to an RPC implementation
788             (let* ((vrequest  (intern (symbol-name 'request) package))
789                    (vchannel  (intern (symbol-name 'channel) package))
790                    (vcallback (intern (symbol-name 'callback) package)))
791               ;; The client side stub, e.g., 'read-air-reservation'.
792               ;; The expectation is that the RPC implementation will provide code to make it
793               ;; easy to implement a method for this on each kind of channel (HTTP, TCP socket,
794               ;; IPC, etc). Unlike C++/Java/Python, we don't need a client-side subclass,
795               ;; because we can just use multi-methods.
796               ;; The 'do-XXX' method calls the RPC code with the channel, the method
797               ;; (i.e., a 'protobuf-method' object), the request and the callback function.
798               ;; The RPC code should take care of serializing the input, transmitting the
799               ;; request over the wire, waiting for input (or not if it's asynchronous),
800               ;; filling in the output, and either returning the response (if synchronous)
801               ;; or calling the callback with the response as an argument (if asynchronous).
802               ;; It will also deserialize the response so that the client code sees the
803               ;; response as an application object.
804               (collect-form `(defgeneric ,client-fn (,vchannel ,vrequest &key ,vcallback)
805                                ,@(and documentation `((:documentation ,documentation)))
806                                #-sbcl (declare (values ,output-type))
807                                (:method (,vchannel (,vrequest ,input-type) &key ,vcallback)
808                                  (declare (ignorable ,vchannel ,vcallback))
809                                  (let ((call (and *rpc-package* *rpc-call-function*)))
810                                    (assert call ()
811                                            "There is no RPC package loaded!")
812                                    (funcall call ,vchannel ',method ,vrequest
813                                             :callback ,vcallback)))))
814               ;; The server side stub, e.g., 'do-read-air-reservation'.
815               ;; The expectation is that the server-side program will implement
816               ;; a method with the business logic for this on each kind of channel
817               ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
818               ;; of the input class.
819               ;; The business logic is expected to perform the correct operations on
820               ;; the input object, which arrived via Protobufs, and produce an output
821               ;; of the given type, which will be serialized and sent back over the wire.
822               ;; The channel objects hold client identity information, deadline info,
823               ;; etc, and can be side-effected to indicate success or failure.
824               ;; The RPC code provides the channel classes and does (de)serialization, etc
825               (collect-form `(defgeneric ,server-fn (,vchannel ,vrequest)
826                                ,@(and documentation `((:documentation ,documentation)))
827                                #-sbcl (declare (values ,output-type))))))))
828       `(progn
829          define-service
830          ,service
831          ((with-proto-source-location (,type ,name protobuf-service ,@source-location)
832             ,@forms))))))
833
834
835 ;; Lisp-only type aliases
836 (defmacro define-type-alias (type (&key name alias-for documentation source-location)
837                              &key lisp-type proto-type serializer deserializer)
838   "Define a Protobufs type alias Lisp 'deftype' named 'type'.
839    'lisp-type' is the name of the Lisp type.
840    'proto-type' is the name of a primitive Protobufs type, e.g., 'int32' or 'string'.
841    'serializer' is a function that takes a Lisp object and generates a Protobufs object.
842    'deserializer' is a function that takes a Protobufs object and generates a Lisp object.
843    If 'alias-for' is given, no Lisp 'deftype' will be defined."
844   (multiple-value-bind (type-str proto)
845       (lisp-type-to-protobuf-type proto-type)
846     (assert (keywordp proto) ()
847             "The alias ~S must resolve to a Protobufs primitive type"
848             type)
849     (let* ((name  (or name (class-name->proto type)))
850            (alias (make-instance 'protobuf-type-alias
851                     :class  type
852                     :name   name
853                     :lisp-type  lisp-type
854                     :proto-type proto
855                     :proto-type-str type-str
856                     :serializer   serializer
857                     :deserializer deserializer
858                     :qualified-name (make-qualified-name *protobuf* name)
859                     :parent *protobuf*
860                     :documentation documentation
861                     :source-location source-location)))
862       (with-collectors ((forms collect-form))
863         (if alias-for
864             ;; If we've got an alias, define a a type that is the subtype of
865             ;; the Lisp enum so that typep and subtypep work
866             (unless (eq type alias-for)
867               (collect-form `(deftype ,type () ',alias-for)))
868             ;; If no alias, define the Lisp enum type now
869             (collect-form `(deftype ,type () ',lisp-type)))
870         `(progn
871            define-type-alias
872            ,alias
873            ((with-proto-source-location (,type ,name protobuf-type-alias ,@source-location)
874               ,@forms)))))))
875
876 \f
877 ;;; Ensure everything in a Protobufs schema is defined
878
879 (defvar *undefined-messages*)
880
881 ;; A very useful tool during development...
882 (defun ensure-all-schemas ()
883   (let ((protos (sort
884                  (delete-duplicates
885                   (loop for p being the hash-values of *all-schemas*
886                         collect p))
887                  #'string< :key #'proto-name)))
888     (mapcan #'ensure-schema protos)))
889
890 (defgeneric ensure-schema (schema)
891   (:documentation
892    "Ensure that all of the types are defined in the Protobufs schema 'schema'.
893     This returns two values:
894      - A list whose elements are (<undefined-type> \"message:field\" ...)
895      - The accumulated warnings table that has the same information as objects.")
896   (:method ((schema protobuf-schema))
897     (let ((*undefined-messages* (make-hash-table))
898           (trace (list schema)))
899       (map () (curry #'ensure-message trace) (proto-messages schema))
900       (map () (curry #'ensure-service trace) (proto-services schema))
901       (loop for type being the hash-keys of *undefined-messages*
902               using (hash-value things)
903             collect (list* type
904                            (mapcar #'(lambda (thing)
905                                        (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
906                                    things)) into warnings
907             finally (return (values warnings *undefined-messages*))))))
908
909 (defgeneric ensure-message (trace message)
910   (:method (trace (message protobuf-message))
911     (let ((trace (cons message trace)))
912       (map () (curry #'ensure-message trace) (proto-messages message))
913       (map () (curry #'ensure-field trace message) (proto-fields message)))))
914
915 (defgeneric ensure-field (trace message field)
916   (:method (trace message (field protobuf-field))
917     (ensure-type trace message field (proto-class field))))
918
919 (defgeneric ensure-service (trace service)
920   (:method (trace (service protobuf-service))
921     (map () (curry #'ensure-method trace service) (proto-methods service))))
922
923 (defgeneric ensure-method (trace service method)
924   (:method (trace service (method protobuf-method))
925     (ensure-type trace service method (proto-input-type method))
926     (ensure-type trace service method (proto-output-type method))
927     (ensure-type trace service method (proto-streams-type method))))
928
929 ;; 'message' and 'field' can be a message and a field or a service and a method
930 (defun ensure-type (trace message field type)
931   (unless (keywordp type)
932     (let ((msg (loop for p in trace
933                      thereis (or (find-message p type)
934                                  (find-enum p type)))))
935       (unless msg
936         (push (cons message field) (gethash type *undefined-messages*))))))