]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - define-proto.lisp
Still better support for qualified names:
[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 ;; Define an enum type named 'type' and a Lisp 'deftype'
113 (defmacro define-enum (type (&key name conc-name alias-for options documentation)
114                        &body values)
115   "Define a Protobufs enum type and a Lisp 'deftype' named 'type'.
116    'name' can be used to override the defaultly generated Protobufs enum name.
117    'conc-name' will be used as the prefix to the Lisp enum names, if it's supplied.
118    If 'alias-for' is given, no Lisp 'deftype' will be defined. Instead, the enum
119    will be used as an alias for an enum type that already exists in Lisp.
120    'options' is a set of keyword/value pairs, both of which are strings.
121
122    The body consists of the enum values in the form 'name' or (name index)."
123   (let* ((name    (or name (class-name->proto type)))
124          (options (loop for (key val) on options by #'cddr
125                         collect (make-instance 'protobuf-option
126                                   :name  (if (symbolp key) (slot-name->proto key) key)
127                                   :value val)))
128          (conc-name (conc-name-for-type type conc-name))
129          (index -1)
130          (enum  (make-instance 'protobuf-enum
131                   :class  type
132                   :name   name
133                   :qualified-name (make-qualified-name *protobuf* name)
134                   :alias-for alias-for
135                   :options options
136                   :documentation documentation)))
137     (with-collectors ((vals  collect-val)
138                       (forms collect-form))
139       (dolist (val values)
140         (let* ((idx  (if (listp val) (second val) (incf index)))
141                (name (if (listp val) (first val)  val))
142                (val-name  (kintern (if conc-name (format nil "~A~A" conc-name name) (symbol-name name))))
143                (enum-name (if conc-name (format nil "~A~A" conc-name name) (symbol-name name)))
144                (enum-val  (make-instance 'protobuf-enum-value
145                             :name  (enum-name->proto enum-name)
146                             :index idx
147                             :value val-name)))
148           (collect-val val-name)
149           (setf (proto-values enum) (nconc (proto-values enum) (list enum-val)))))
150       (if alias-for
151         ;; If we've got an alias, define a a type that is the subtype of
152         ;; the Lisp enum so that typep and subtypep work
153         (unless (eq type alias-for)
154           (collect-form `(deftype ,type () ',alias-for)))
155         ;; If no alias, define the Lisp enum type now
156         (collect-form `(deftype ,type () '(member ,@vals))))
157       `(progn
158          define-enum
159          ,enum
160          ,forms))))
161
162 ;; Define a message named 'name' and a Lisp 'defclass'
163 (defmacro define-message (type (&key name conc-name alias-for options documentation)
164                           &body fields &environment env)
165   "Define a message named 'type' and a Lisp 'defclass'.
166    'name' can be used to override the defaultly generated Protobufs message name.
167    The body consists of fields, or 'define-enum' or 'define-message' forms.
168    'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
169    If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
170    used as an alias for a class that already exists in Lisp. This feature is intended
171    to be used to define messages that will be serialized from existing Lisp classes;
172    unless you get the slot names or readers exactly right for each field, it will be
173    the case that trying to (de)serialize into a Lisp object won't work.
174    'options' is a set of keyword/value pairs, both of which are strings.
175
176    Fields take the form (slot &key type name default reader)
177    'slot' can be either a symbol giving the field name, or a list whose
178    first element is the slot name and whose second element is the index.
179    'type' is the type of the slot.
180    'name' can be used to override the defaultly generated Protobufs field name.
181    'default' is the default value for the slot.
182    'reader' is a Lisp slot reader function to use to get the value, instead of
183    using 'slot-value'; this is often used when aliasing an existing class.
184    'writer' is a Lisp slot writer function to use to set the value."
185   (let* ((name    (or name (class-name->proto type)))
186          (options (loop for (key val) on options by #'cddr
187                         collect (make-instance 'protobuf-option
188                                   :name  (if (symbolp key) (slot-name->proto key) key)
189                                   :value val)))
190          (conc-name (conc-name-for-type type conc-name))
191          (message (make-instance 'protobuf-message
192                     :class type
193                     :name  name
194                     :qualified-name (make-qualified-name *protobuf* name)
195                     :parent *protobuf*
196                     :alias-for alias-for
197                     :conc-name conc-name
198                     :options   (remove-options options "default" "packed")
199                     :documentation documentation))
200          (index 0)
201          (*protobuf* message))
202     (with-collectors ((slots collect-slot)
203                       (forms collect-form))
204       (dolist (field fields)
205         (case (car field)
206           ((define-enum define-message define-extend define-extension define-group)
207            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
208                (macroexpand-1 field env)
209              (assert (eq progn 'progn) ()
210                      "The macroexpansion for ~S failed" field)
211              (map () #'collect-form definers)
212              (ecase model-type
213                ((define-enum)
214                 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
215                ((define-message define-extend)
216                 (setf (proto-parent model) message)
217                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
218                 (when (eq (proto-message-type model) :extends)
219                   (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
220                ((define-group)
221                 (setf (proto-parent model) message)
222                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
223                 (when extra-slot
224                   (collect-slot extra-slot))
225                 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
226                ((define-extension)
227                 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
228           (otherwise
229            (multiple-value-bind (field slot idx)
230                (process-field field index :conc-name conc-name :alias-for alias-for)
231              (assert (not (find-field message (proto-index field))) ()
232                      "The field ~S overlaps with another field in ~S"
233                      (proto-value field) (proto-class message))
234              (setq index idx)
235              (when slot
236                (collect-slot slot))
237              (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
238       (if alias-for
239         ;; If we've got an alias, define a a type that is the subtype of
240         ;; the Lisp class that typep and subtypep work
241         (unless (or (eq type alias-for) (find-class type nil))
242           (collect-form `(deftype ,type () ',alias-for)))
243         ;; If no alias, define the class now
244         (collect-form `(defclass ,type () (,@slots)
245                          ,@(and documentation `((:documentation ,documentation))))))
246       `(progn
247          define-message
248          ,message
249          ,forms))))
250
251 (defun conc-name-for-type (type conc-name)
252   (and conc-name
253        (typecase conc-name
254          ((member t) (format nil "~A-" type))
255          ((or string symbol) (string conc-name))
256          (t nil))))
257
258 (defmacro define-extension (from to)
259   "Define an extension range within a message.
260    The \"body\" is the start and end of the range, both inclusive."
261   (let ((to (etypecase to
262               (integer to)
263               (symbol (if (string-equal to "MAX") #.(1- (ash 1 29)) to)))))
264     `(progn
265        define-extension
266        ,(make-instance 'protobuf-extension
267           :from from
268           :to   (if (eq to 'max) #.(1- (ash 1 29)) to))
269        ())))
270
271 (defmacro define-extend (type (&key name conc-name options documentation)
272                          &body fields &environment env)
273   "Define an extension to the message named 'type'.
274    'name' can be used to override the defaultly generated Protobufs message name.
275    The body consists only  of fields.
276    'options' is a set of keyword/value pairs, both of which are strings.
277
278    Fields take the form (slot &key type name default reader)
279    'slot' can be either a symbol giving the field name, or a list whose
280    first element is the slot name and whose second element is the index.
281    'type' is the type of the slot.
282    'name' can be used to override the defaultly generated Protobufs field name.
283    'default' is the default value for the slot.
284    'reader' is a Lisp slot reader function to use to get the value, instead of
285    using 'slot-value'; this is often used when aliasing an existing class.
286    'writer' is a Lisp slot writer function to use to set the value."
287   (let* ((name    (or name (class-name->proto type)))
288          (options (loop for (key val) on options by #'cddr
289                         collect (make-instance 'protobuf-option
290                                   :name  (if (symbolp key) (slot-name->proto key) key)
291                                   :value val)))
292          (message   (find-message *protobuf* name))
293          (conc-name (or (conc-name-for-type type conc-name)
294                         (and message (proto-conc-name message))))
295          (alias-for (and message (proto-alias-for message)))
296          (extends (and message
297                        (make-instance 'protobuf-message
298                          :class  type
299                          :name   name
300                          :qualified-name (make-qualified-name *protobuf* name)
301                          :parent (proto-parent message)
302                          :alias-for alias-for
303                          :conc-name conc-name
304                          :enums    (copy-list (proto-enums message))
305                          :messages (copy-list (proto-messages message))
306                          :fields   (copy-list (proto-fields message))
307                          :options  (remove-options
308                                      (or options (copy-list (proto-options message))) "default" "packed")
309                          :extensions (copy-list (proto-extensions message))
310                          :message-type :extends         ;this message is an extension
311                          :documentation documentation)))
312          (*protobuf* extends)
313          (index 0))
314     (assert message ()
315             "There is no message named ~A to extend" name)
316     (assert (eq type (proto-class message)) ()
317             "The type ~S doesn't match the type of the message being extended ~S"
318             type message)
319     (with-collectors ((forms collect-form))
320       (dolist (field fields)
321         (assert (not (member (car field)
322                              '(define-enum define-message define-extend define-extension))) ()
323                 "The body of ~S can only contain field and group definitions" 'define-extend)
324         (case (car field)
325           ((define-group)
326            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
327                (macroexpand-1 field env)
328              (assert (eq progn 'progn) ()
329                      "The macroexpansion for ~S failed" field)
330              (map () #'collect-form definers)
331              (ecase model-type
332                ((define-group)
333                 (setf (proto-parent model) extends)
334                 (setf (proto-messages extends) (nconc (proto-messages extends) (list model)))
335                 (when extra-slot
336                   ;;--- Refactor to get rid of all this duplicated code!
337                   (let* ((inits  (cdr extra-slot))
338                          (sname  (car extra-slot))
339                          (stable (fintern "~A-VALUES" sname))
340                          (stype  (getf inits :type))
341                          (reader (or (getf inits :accessor)
342                                      (getf inits :reader)
343                                      (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
344                                              *protobuf-package*)))
345                          (writer (or (getf inits :writer)
346                                      (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
347                          (default (getf inits :initform)))
348                     (collect-form `(without-redefinition-warnings ()
349                                      (let ((,stable #+ccl  (make-hash-table :test #'eq :weak t)
350                                                     #+sbcl (make-hash-table :test #'eq :weakness :value)))
351                                        ,@(and reader `((defmethod ,reader ((object ,type))
352                                                          (gethash object ,stable ,default))))
353                                        ,@(and writer `((defmethod ,writer ((object ,type) value)
354                                                          (declare (type ,stype value))
355                                                          (setf (gethash object ,stable) value))))
356                                        ,@(and writer `((defsetf ,reader ,writer)))
357                                        ;; For Python compatibility
358                                        (defmethod get-extension ((object ,type) (slot (eql ',sname)))
359                                          (values (gethash object ,stable ,default)))
360                                        (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
361                                          (setf (gethash object ,stable) value))
362                                        (defmethod has-extension ((object ,type) (slot (eql ',sname)))
363                                          (multiple-value-bind (value foundp)
364                                              (gethash object ,stable)
365                                            (declare (ignore value))
366                                            foundp))
367                                        (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
368                                          (remhash object ,stable)))))))
369                 (setf (proto-message-type extra-field) :extends) ;this field is an extension
370                 (setf (proto-fields extends) (nconc (proto-fields extends) (list extra-field)))
371                 (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list extra-field)))))))
372           (otherwise
373            (multiple-value-bind (field slot idx)
374                (process-field field index :conc-name conc-name :alias-for alias-for)
375              (assert (not (find-field extends (proto-index field))) ()
376                      "The field ~S overlaps with another field in ~S"
377                      (proto-value field) (proto-class extends))
378              (assert (index-within-extensions-p idx message) ()
379                      "The index ~D is not in range for extending ~S"
380                      idx (proto-class message))
381              (setq index idx)
382              (when slot
383                (let* ((inits  (cdr slot))
384                       (sname  (car slot))
385                       (stable (fintern "~A-VALUES" sname))
386                       (stype  (getf inits :type))
387                       (reader (or (getf inits :accessor)
388                                   (getf inits :reader)
389                                   (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
390                                           *protobuf-package*)))
391                       (writer (or (getf inits :writer)
392                                   (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
393                       (default (getf inits :initform)))
394                  ;; For the extended slots, each slot gets its own table
395                  ;; keyed by the object, which lets us avoid having a slot in each
396                  ;; instance that holds a table keyed by the slot name
397                  ;; Multiple 'define-extends' on the same class in the same image
398                  ;; will result in harmless redefinitions, so squelch the warnings
399                  ;;--- Maybe these methods need to be defined in 'define-message'?
400                  (collect-form `(without-redefinition-warnings ()
401                                   (let ((,stable #+ccl  (make-hash-table :test #'eq :weak t)
402                                                  #+sbcl (make-hash-table :test #'eq :weakness :value)))
403                                     ,@(and reader `((defmethod ,reader ((object ,type))
404                                                       (gethash object ,stable ,default))))
405                                     ,@(and writer `((defmethod ,writer ((object ,type) value)
406                                                       (declare (type ,stype value))
407                                                       (setf (gethash object ,stable) value))))
408                                     ,@(and writer `((defsetf ,reader ,writer)))
409                                     ;; For Python compatibility
410                                     (defmethod get-extension ((object ,type) (slot (eql ',sname)))
411                                       (values (gethash object ,stable ,default)))
412                                     (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
413                                       (setf (gethash object ,stable) value))
414                                     (defmethod has-extension ((object ,type) (slot (eql ',sname)))
415                                       (multiple-value-bind (value foundp)
416                                           (gethash object ,stable)
417                                         (declare (ignore value))
418                                         foundp))
419                                     (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
420                                       (remhash object ,stable)))))
421                  ;; This so that (de)serialization works
422                  (setf (proto-reader field) reader
423                        (proto-writer field) writer)))
424              (setf (proto-message-type field) :extends)         ;this field is an extension
425              (setf (proto-fields extends) (nconc (proto-fields extends) (list field)))
426              (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list field)))))))
427       `(progn
428          define-extend
429          ,extends
430          ,forms))))
431
432 (defun index-within-extensions-p (index message)
433   (let ((extensions (proto-extensions message)))
434     (some #'(lambda (ext)
435               (and (i>= index (proto-extension-from ext))
436                    (i<= index (proto-extension-to ext))))
437           extensions)))
438
439 (defmacro define-group (type (&key index arity name conc-name alias-for reader options documentation)
440                         &body fields &environment env)
441   "Define a message named 'type' and a Lisp 'defclass', *and* a field named type.
442    This is deprecated in Protobufs, but if you have to use it, you must give
443    'index' as the field index and 'arity' of :required, :optional or :repeated.
444    'name' can be used to override the defaultly generated Protobufs message name.
445    The body consists of fields, or 'define-enum' or 'define-message' forms.
446    'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
447    If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
448    used as an alias for a class that already exists in Lisp. This feature is intended
449    to be used to define messages that will be serialized from existing Lisp classes;
450    unless you get the slot names or readers exactly right for each field, it will be
451    the case that trying to (de)serialize into a Lisp object won't work.
452    'options' is a set of keyword/value pairs, both of which are strings.
453
454    Fields take the form (slot &key type name default reader)
455    'slot' can be either a symbol giving the field name, or a list whose
456    first element is the slot name and whose second element is the index.
457    'type' is the type of the slot.
458    'name' can be used to override the defaultly generated Protobufs field name.
459    'default' is the default value for the slot.
460    'reader' is a Lisp slot reader function to use to get the value, instead of
461    using 'slot-value'; this is often used when aliasing an existing class.
462    'writer' is a Lisp slot writer function to use to set the value."
463   (check-type index integer)
464   (check-type arity (member :required :optional :repeated))
465   (let* ((slot    (or type (and name (proto->slot-name name *protobuf-package*))))
466          (name    (or name (class-name->proto type)))
467          (options (loop for (key val) on options by #'cddr
468                         collect (make-instance 'protobuf-option
469                                   :name  (if (symbolp key) (slot-name->proto key) key)
470                                   :value val)))
471          (conc-name (conc-name-for-type type conc-name))
472          (reader  (or reader
473                       (let ((msg-conc (proto-conc-name *protobuf*)))
474                         (and msg-conc
475                              (intern (format nil "~A~A" msg-conc slot) *protobuf-package*)))))
476          (mslot   (unless alias-for
477                     `(,slot ,@(case arity
478                                 (:required
479                                  `(:type ,type))
480                                 (:optional
481                                  `(:type (or ,type null)
482                                    :initform nil))
483                                 (:repeated
484                                  `(:type (list-of ,type)
485                                    :initform ())))
486                             ,@(and reader
487                                    `(:accessor ,reader))
488                             :initarg ,(kintern (symbol-name slot)))))
489          (mfield  (make-instance 'protobuf-field
490                     :name  (slot-name->proto slot)
491                     :type  name
492                     :class type
493                     :qualified-name (make-qualified-name *protobuf* (slot-name->proto slot))
494                     :required arity
495                     :index index
496                     :value slot
497                     :reader reader
498                     :message-type :group))
499          (message (make-instance 'protobuf-message
500                     :class type
501                     :name  name
502                     :qualified-name (make-qualified-name *protobuf* name)
503                     :alias-for alias-for
504                     :conc-name conc-name
505                     :options   (remove-options options "default" "packed")
506                     :message-type :group                ;this message is a group
507                     :documentation documentation))
508          (index 0)
509          (*protobuf* message))
510     (with-collectors ((slots collect-slot)
511                       (forms collect-form))
512       (dolist (field fields)
513         (case (car field)
514           ((define-enum define-message define-extend define-extension define-group)
515            (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
516                (macroexpand-1 field env)
517              (assert (eq progn 'progn) ()
518                      "The macroexpansion for ~S failed" field)
519              (map () #'collect-form definers)
520              (ecase model-type
521                ((define-enum)
522                 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
523                ((define-message define-extend)
524                 (setf (proto-parent model) message)
525                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
526                 (when (eq (proto-message-type model) :extends)
527                   (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
528                ((define-group)
529                 (setf (proto-parent model) message)
530                 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
531                 (when extra-slot
532                   (collect-slot extra-slot))
533                 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
534                ((define-extension)
535                 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
536           (otherwise
537            (multiple-value-bind (field slot idx)
538                (process-field field index :conc-name conc-name :alias-for alias-for)
539              (assert (not (find-field message (proto-index field))) ()
540                      "The field ~S overlaps with another field in ~S"
541                      (proto-value field) (proto-class message))
542              (setq index idx)
543              (when slot
544                (collect-slot slot))
545              (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
546       (if alias-for
547         ;; If we've got an alias, define a a type that is the subtype of
548         ;; the Lisp class that typep and subtypep work
549         (unless (or (eq type alias-for) (find-class type nil))
550           (collect-form `(deftype ,type () ',alias-for)))
551         ;; If no alias, define the class now
552         (collect-form `(defclass ,type () (,@slots)
553                          ,@(and documentation `((:documentation ,documentation))))))
554       `(progn
555          define-group
556          ,message
557          ,forms
558          ,mfield
559          ,mslot))))
560
561 (defun process-field (field index &key conc-name alias-for)
562   "Process one field descriptor within 'define-message' or 'define-extend'.
563    Returns a 'proto-field' object, a CLOS slot form and the incremented field index."
564   (when (i= index 18999)                                ;skip over the restricted range
565     (setq index 19999))
566   (destructuring-bind (slot &rest other-options 
567                        &key type reader writer name (default nil default-p) packed
568                             options documentation &allow-other-keys) field
569     (let* ((idx  (if (listp slot) (second slot) (iincf index)))
570            (slot (if (listp slot) (first slot) slot))
571            (reader (or reader
572                        (and conc-name
573                             (intern (format nil "~A~A" conc-name slot) *protobuf-package*))))
574            (options (append
575                      (loop for (key val) on other-options by #'cddr
576                            unless (member key '(:type :reader :writer :name :default :packed :documentation))
577                              collect (make-instance 'protobuf-option
578                                        :name  (slot-name->proto key)
579                                        :value val))
580                      (loop for (key val) on options by #'cddr
581                          collect (make-instance 'protobuf-option
582                                    :name  (if (symbolp key) (slot-name->proto key) key)
583                                    :value val)))))
584       (multiple-value-bind (ptype pclass)
585           (clos-type-to-protobuf-type type)
586         (multiple-value-bind (reqd vectorp)
587             (clos-type-to-protobuf-required type)
588           (let* ((default (if (eq reqd :repeated)
589                             (if vectorp $empty-vector $empty-list)      ;to distinguish between list-of and vector-of
590                             (if default-p default $empty-default)))
591                  (cslot (unless alias-for
592                           `(,slot :type ,type
593                                   ,@(and reader
594                                          (if writer
595                                            `(:reader ,reader)
596                                            `(:accessor ,reader)))
597                                   ,@(and writer
598                                          `(:writer ,writer))
599                                   :initarg ,(kintern (symbol-name slot))
600                                   ,@(cond ((eq reqd :repeated)
601                                            ;; Repeated fields get a container for their elements
602                                            (if vectorp
603                                              `(:initform (make-array 5 :fill-pointer 0 :adjustable t))
604                                              `(:initform ())))
605                                           ((and (not default-p)
606                                                 (eq reqd :optional)
607                                                 ;; Use unbound for booleans only
608                                                 (not (eq pclass :bool)))
609                                            `(:initform nil))
610                                           (default-p
611                                             `(:initform ,(protobuf-default-to-clos-init default type)))))))
612                  (field (make-instance 'protobuf-field
613                           :name  (or name (slot-name->proto slot))
614                           :type  ptype
615                           :class pclass
616                           :qualified-name (make-qualified-name *protobuf* (or name (slot-name->proto slot)))
617                           ;; One of :required, :optional or :repeated
618                           :required reqd
619                           :index  idx
620                           :value  slot
621                           :reader reader
622                           :writer writer
623                           :default default
624                           ;; Pack the field only if requested and it actually makes sense
625                           :packed  (and (eq reqd :repeated) packed t)
626                           :options options
627                           :documentation documentation)))
628             (values field cslot idx)))))))
629
630 ;; Define a service named 'type' with generic functions declared for
631 ;; each of the methods within the service
632 (defmacro define-service (type (&key name options documentation)
633                           &body method-specs)
634   "Define a service named 'type' and Lisp 'defgeneric' for all its methods.
635    'name' can be used to override the defaultly generated Protobufs service name.
636    'options' is a set of keyword/value pairs, both of which are strings.
637
638    The body is a set of method specs of the form (name (input-type output-type) &key options).
639    'input-type' and 'output-type' may also be of the form (type &key name)."
640   (let* ((name    (or name (class-name->proto type)))
641          (options (loop for (key val) on options by #'cddr
642                         collect (make-instance 'protobuf-option
643                                   :name  (if (symbolp key) (slot-name->proto key) key)
644                                   :value val)))
645          (service (make-instance 'protobuf-service
646                     :class type
647                     :name  name
648                     :qualified-name (make-qualified-name *protobuf* name)
649                     :options options
650                     :documentation documentation))
651          (index 0))
652     (with-collectors ((forms collect-form))
653       (dolist (method method-specs)
654         (destructuring-bind (function (input-type output-type) &key name options documentation) method
655           (let* ((input-name (and (listp input-type)
656                                   (getf (cdr input-type) :name)))
657                  (input-type (if (listp input-type) (car input-type) input-type))
658                  (output-name (and (listp output-type)
659                                    (getf (cdr output-type) :name)))
660                  (output-type (if (listp output-type) (car output-type) output-type))
661                  (options (loop for (key val) on options by #'cddr
662                                 collect (make-instance 'protobuf-option
663                                           :name  (if (symbolp key) (slot-name->proto key) key)
664                                           :value val)))
665                  (package   *protobuf-package*)
666                  (client-fn function)
667                  (server-fn (intern (format nil "~A-~A" 'do function) package))
668                  (method  (make-instance 'protobuf-method
669                             :class function
670                             :name  (or name (class-name->proto function))
671                             :qualified-name (make-qualified-name *protobuf* (or name (class-name->proto function)))
672                             :client-stub client-fn
673                             :server-stub server-fn
674                             :input-type  input-type
675                             :input-name  (or input-name (class-name->proto input-type))
676                             :output-type output-type
677                             :output-name (or output-name (class-name->proto output-type))
678                             :index (iincf index)
679                             :options options
680                             :documentation documentation)))
681             (setf (proto-methods service) (nconc (proto-methods service) (list method)))
682             ;; The following are the hooks to CL-Stubby
683             (let* ((vinput    (intern (format nil "~A-~A" (symbol-name input-type) 'in) package))
684                    (voutput   (intern (format nil "~A-~A" (symbol-name output-type) 'out) package))
685                    (vchannel  (intern (symbol-name 'channel) package))
686                    (vcallback (intern (symbol-name 'callback) package)))
687               ;; The client side stub, e.g., 'read-air-reservation'.
688               ;; The expectation is that CL-Stubby will provide macrology to make it
689               ;; easy to implement a method for this on each kind of channel (HTTP, TCP socket,
690               ;; IPC, etc). Unlike C++/Java/Python, we don't need a client-side subclass,
691               ;; because we can just use multi-methods.
692               ;; The CL-Stubby macros take care of serializing the input, transmitting the
693               ;; request over the wire, waiting for input (or not if it's asynchronous),
694               ;; filling in the output, and calling the callback (if it's asynchronous).
695               ;; It's not very Lispy to side-effect an output object, but it makes
696               ;; asynchronous calls simpler.
697               (collect-form `(defgeneric ,client-fn (,vchannel ,vinput ,voutput &key ,vcallback)
698                                ,@(and documentation `((:documentation ,documentation)))
699                                #-sbcl (declare (values ,output-type))))
700               ;; The server side stub, e.g., 'do-read-air-reservation'.
701               ;; The expectation is that the server-side program will implement
702               ;; a method with the business logic for this on each kind of channel
703               ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
704               ;; of the input class
705               ;; The business logic is expected to perform the correct operations on
706               ;; the input object, which arrived via Protobufs, and produce an output
707               ;; of the given type, which will be serialized as a result.
708               ;; The channel objects hold client identity information, deadline info,
709               ;; etc, and can be side-effected to indicate success or failure
710               ;; CL-Stubby provides the channel classes and does (de)serialization, etc
711               (collect-form `(defgeneric ,server-fn (,vchannel ,vinput ,voutput)
712                                ,@(and documentation `((:documentation ,documentation)))
713                                #-sbcl (declare (values ,output-type))))))))
714       `(progn
715          define-service
716          ,service
717          ,forms))))
718
719 \f
720 ;;; Ensure everything in a Protobufs schema is defined
721
722 (defvar *undefined-messages*)
723
724 ;; A very useful tool during development...
725 (defun ensure-all-schemas ()
726   (let ((protos (sort
727                  (delete-duplicates
728                   (loop for p being the hash-values of *all-schemas*
729                         collect p))
730                  #'string< :key #'proto-name)))
731     (mapcan #'ensure-schema protos)))
732
733 (defgeneric ensure-schema (schema)
734   (:documentation
735    "Ensure that all of the types are defined in the Protobufs schema 'schema'.
736     This returns two values:
737      - A list whose elements are (<undefined-type> \"message:field\" ...)
738      - The accumulated warnings table that has the same information as objects.")
739   (:method ((schema protobuf-schema))
740     (let ((*undefined-messages* (make-hash-table))
741           (trace (list schema)))
742       (map () (curry #'ensure-message trace) (proto-messages schema))
743       (map () (curry #'ensure-service trace) (proto-services schema))
744       (loop for type being the hash-keys of *undefined-messages*
745               using (hash-value things)
746             collect (list* type
747                            (mapcar #'(lambda (thing)
748                                        (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
749                                    things)) into warnings
750             finally (return (values warnings *undefined-messages*))))))
751
752 (defgeneric ensure-message (trace message)
753   (:method (trace (message protobuf-message))
754     (let ((trace (cons message trace)))
755       (map () (curry #'ensure-message trace) (proto-messages message))
756       (map () (curry #'ensure-field trace message) (proto-fields message)))))
757
758 (defgeneric ensure-field (trace message field)
759   (:method (trace message (field protobuf-field))
760     (ensure-type trace message field (proto-class field))))
761
762 (defgeneric ensure-service (trace service)
763   (:method (trace (service protobuf-service))
764     (map () (curry #'ensure-method trace service) (proto-methods service))))
765
766 (defgeneric ensure-method (trace service method)
767   (:method (trace service (method protobuf-method))
768     (ensure-type trace service method (proto-input-type method))
769     (ensure-type trace service method (proto-output-type method))))
770
771 ;; 'message' and 'field' can be a message and a field or a service and a method
772 (defun ensure-type (trace message field type)
773   (unless (keywordp type)
774     (let ((msg (loop for p in trace
775                      thereis (or (find-message p type)
776                                  (find-enum p type)))))
777       (unless msg
778         (push (cons message field) (gethash type *undefined-messages*))))))