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