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