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