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