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