1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3 ;;; Free Software published under an MIT-like license. See LICENSE ;;;
5 ;;; Copyright (c) 2012-2013 Google, Inc. All rights reserved. ;;;
7 ;;; Original author: Scott McKay ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
11 (in-package "PROTO-IMPL")
14 ;;; Protocol buffer defining macros
16 ;;; Base class for all Protobufs-defined classes
18 (defclass base-protobuf-message ()
19 ;; Just one slot, to hold a size cached by 'object-size'
20 ((%cached-size :type (or null fixnum)
23 "The base class for all user-defined Protobufs messages."))
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\" ...).
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
54 :syntax (or syntax "proto2")
56 :lisp-package (or lisp-pkg (substitute #\- #\_ package))
60 (list (make-option "optimize_for" (if (eq optimize :speed) "SPEED" "CODE_SIZE") 'symbol)))
62 :documentation documentation))
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 ~}"
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)
87 (appendf (proto-enums schema) (list model)))
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))))
96 (appendf (proto-services schema) (list model))))))
97 (let ((var (intern (format nil "*~A*" type) *protobuf-package*)))
101 (let* ((old-schema ,var)
102 (new-schema ,schema))
104 (multiple-value-bind (upgradable warnings)
105 (schema-upgradable old-schema new-schema)
107 (protobufs-warn "The old schema for ~S (~A) can't be safely upgraded; proceeding anyway"
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)))
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)))))
125 (defmacro with-proto-source-location ((type name definition-type
126 &optional pathname start-pos end-pos)
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
136 (record-proto-source-location ',type ,name ',definition-type
137 ,pathname ,start-pos ,end-pos)
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
149 (ccl:record-source-file type definition-type))))
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)))
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)
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.
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))
173 (enum (make-instance 'protobuf-enum
176 :qualified-name (make-qualified-name *protobuf* name)
180 :documentation documentation
181 :source-location source-location)))
182 (with-collectors ((vals collect-val)
183 (forms collect-form))
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))
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
195 :qualified-name (make-qualified-name enum vname)
199 (collect-val val-name)
200 (appendf (proto-values enum) (list enum-val))))
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))))
211 ((with-proto-source-location (,type ,name protobuf-enum ,@source-location)
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.
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
245 :qualified-name (make-qualified-name *protobuf* name)
249 :options (remove-options options "default" "packed")
250 :documentation documentation
251 :source-location source-location))
253 ;; Only now can we bind *protobuf* to the new message
254 (*protobuf* message))
255 (with-collectors ((slots collect-slot)
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)
262 ((define-enum define-message define-extend define-extension define-group
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)
271 (appendf (proto-enums message) (list model)))
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))))
280 (setf (proto-parent model) message)
281 (appendf (proto-messages message) (list model))
283 (collect-slot extra-slot))
284 (appendf (proto-fields message) (list extra-field)))
286 (appendf (proto-extensions message) (list model))))))
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))
296 (appendf (proto-fields message) (list field))))))
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))))))
308 ((with-proto-source-location (,type ,name protobuf-message ,@source-location)
312 (defun conc-name-for-type (type conc-name)
315 ((member t) (format nil "~:@(~A~)-" type))
316 ((or string symbol) (string-upcase (string conc-name)))
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
324 (symbol (if (string-equal to "MAX") #.(1- (ash 1 29)) to)))))
327 ,(make-instance 'protobuf-extension
329 :to (if (eq to 'max) #.(1- (ash 1 29)) to))
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.
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)
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
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"
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)
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)
395 (setf (proto-parent model) extends)
396 (appendf (proto-messages extends) (list model))
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)
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))
427 (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
428 (remhash object ,stable)))
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))))))
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))
447 (let* ((inits (cdr slot))
449 (stable (fintern "~A-VALUES" sname))
450 (stype (getf inits :type))
451 (reader (or (getf inits :accessor)
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))
480 (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
481 (remhash object ,stable)))
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))))))
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))))
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.
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))
536 (let ((msg-conc (proto-conc-name *protobuf*)))
538 (intern (format nil "~A~A" msg-conc slot) *protobuf-package*)))))
539 (mslot (unless alias-for
540 `(,slot ,@(case arity
544 `(:type (or ,type null)
547 `(:type (list-of ,type)
550 `(:accessor ,reader))
551 :initarg ,(kintern (symbol-name slot)))))
552 (mfield (make-instance 'protobuf-field
553 :name (slot-name->proto slot)
556 :qualified-name (make-qualified-name *protobuf* (slot-name->proto slot))
562 :message-type :group))
563 (message (make-instance 'protobuf-message
566 :qualified-name (make-qualified-name *protobuf* 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))
575 ;; Only now can we bind *protobuf* to the (group) message
576 (*protobuf* message))
577 (with-collectors ((slots collect-slot)
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)
584 ((define-enum define-message define-extend define-extension define-group
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)
593 (appendf (proto-enums message) (list model)))
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))))
602 (setf (proto-parent model) message)
603 (appendf (proto-messages message) (list model))
605 (collect-slot extra-slot))
606 (appendf (proto-fields message) (list extra-field)))
608 (appendf (proto-extensions message) (list model))))))
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))
618 (appendf (proto-fields message) (list field))))))
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))))))
630 ((with-proto-source-location (,type ,name protobuf-message ,@source-location)
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
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))
652 (intern (format nil "~A~A" conc-name slot) *protobuf-package*))))
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
671 `(:accessor ,reader)))
674 :initarg ,(kintern (symbol-name slot))
675 ,@(cond ((eq reqd :repeated)
676 ;; Repeated fields get a container for their elements
678 `(:initform (make-array 5 :fill-pointer 0 :adjustable t))
680 ((and (not default-p)
682 ;; Use unbound for booleans only
683 (not (eq pclass :bool)))
686 `(:initform ,(protobuf-default-to-clos-init default type)))))))
687 (field (make-instance 'protobuf-field
688 :name (or name (slot-name->proto slot))
691 :qualified-name (make-qualified-name *protobuf* (or name (slot-name->proto slot)))
693 ;; One of :required, :optional or :repeated
700 ;; Pack the field only if requested and it actually makes sense
701 :packed (and (eq reqd :repeated) packed t)
703 :documentation documentation)))
704 (values field cslot idx)))))))
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.")
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)
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.
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
730 :qualified-name (make-qualified-name *protobuf* name)
733 :documentation documentation
734 :source-location source-location))
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
761 :name (or name (class-name->proto function))
762 :qualified-name (make-qualified-name *protobuf* (or name (class-name->proto function)))
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)))
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 #-sbcl (declare (values ,output-type))
798 (:method (,vchannel (,vrequest ,input-type) &key ,vcallback)
799 (declare (ignorable ,vchannel ,vcallback))
800 (let ((call (and *rpc-package* *rpc-call-function*)))
802 "There is no RPC package loaded!")
803 (funcall call ,vchannel ',method ,vrequest
804 :callback ,vcallback)))))
805 ;; The server side stub, e.g., 'do-read-air-reservation'.
806 ;; The expectation is that the server-side program will implement
807 ;; a method with the business logic for this on each kind of channel
808 ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
809 ;; of the input class.
810 ;; The business logic is expected to perform the correct operations on
811 ;; the input object, which arrived via Protobufs, and produce an output
812 ;; of the given type, which will be serialized and sent back over the wire.
813 ;; The channel objects hold client identity information, deadline info,
814 ;; etc, and can be side-effected to indicate success or failure.
815 ;; The RPC code provides the channel classes and does (de)serialization, etc
816 (collect-form `(defgeneric ,server-fn (,vchannel ,vrequest)
817 ,@(and documentation `((:documentation ,documentation)))
818 #-sbcl (declare (values ,output-type))))))))
822 ((with-proto-source-location (,type ,name protobuf-service ,@source-location)
826 ;; Lisp-only type aliases
827 (defmacro define-type-alias (type (&key name alias-for documentation source-location)
828 &key lisp-type proto-type serializer deserializer)
829 "Define a Protobufs type alias Lisp 'deftype' named 'type'.
830 'lisp-type' is the name of the Lisp type.
831 'proto-type' is the name of a primitive Protobufs type, e.g., 'int32' or 'string'.
832 'serializer' is a function that takes a Lisp object and generates a Protobufs object.
833 'deserializer' is a function that takes a Protobufs object and generates a Lisp object.
834 If 'alias-for' is given, no Lisp 'deftype' will be defined."
835 (multiple-value-bind (type-str proto)
836 (lisp-type-to-protobuf-type proto-type)
837 (assert (keywordp proto) ()
838 "The alias ~S must resolve to a Protobufs primitive type"
840 (let* ((name (or name (class-name->proto type)))
841 (alias (make-instance 'protobuf-type-alias
846 :proto-type-str type-str
847 :serializer serializer
848 :deserializer deserializer
849 :qualified-name (make-qualified-name *protobuf* name)
851 :documentation documentation
852 :source-location source-location)))
853 (with-collectors ((forms collect-form))
855 ;; If we've got an alias, define a a type that is the subtype of
856 ;; the Lisp enum so that typep and subtypep work
857 (unless (eq type alias-for)
858 (collect-form `(deftype ,type () ',alias-for)))
859 ;; If no alias, define the Lisp enum type now
860 (collect-form `(deftype ,type () ',lisp-type)))
864 ((with-proto-source-location (,type ,name protobuf-type-alias ,@source-location)
868 ;;; Ensure everything in a Protobufs schema is defined
870 (defvar *undefined-messages* nil
871 "Bound to a list of undefined messages during schame validation.")
873 ;; A very useful tool during development...
874 (defun ensure-all-schemas ()
877 (loop for p being the hash-values of *all-schemas*
879 #'string< :key #'proto-name)))
880 (mapcan #'ensure-schema protos)))
882 (defgeneric ensure-schema (schema)
884 "Ensure that all of the types are defined in the Protobufs schema 'schema'.
885 This returns two values:
886 - A list whose elements are (<undefined-type> \"message:field\" ...)
887 - The accumulated warnings table that has the same information as objects.")
888 (:method ((schema protobuf-schema))
889 (let ((*undefined-messages* (make-hash-table))
890 (trace (list schema)))
891 (map () (curry #'ensure-message trace) (proto-messages schema))
892 (map () (curry #'ensure-service trace) (proto-services schema))
893 (loop for type being the hash-keys of *undefined-messages*
894 using (hash-value things)
896 (mapcar #'(lambda (thing)
897 (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
898 things)) into warnings
899 finally (return (values warnings *undefined-messages*))))))
901 (defgeneric ensure-message (trace message)
902 (:method (trace (message protobuf-message))
903 (let ((trace (cons message trace)))
904 (map () (curry #'ensure-message trace) (proto-messages message))
905 (map () (curry #'ensure-field trace message) (proto-fields message)))))
907 (defgeneric ensure-field (trace message field)
908 (:method (trace message (field protobuf-field))
909 (ensure-type trace message field (proto-class field))))
911 (defgeneric ensure-service (trace service)
912 (:method (trace (service protobuf-service))
913 (map () (curry #'ensure-method trace service) (proto-methods service))))
915 (defgeneric ensure-method (trace service method)
916 (:method (trace service (method protobuf-method))
917 (ensure-type trace service method (proto-input-type method))
918 (ensure-type trace service method (proto-output-type method))
919 (ensure-type trace service method (proto-streams-type method))))
921 ;; 'message' and 'field' can be a message and a field or a service and a method
922 (defun ensure-type (trace message field type)
923 (unless (keywordp type)
924 (let ((msg (loop for p in trace
925 thereis (or (find-message p type)
926 (find-enum p type)))))
928 (push (cons message field) (gethash type *undefined-messages*))))))