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