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