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 (setf (proto-enums schema) (nconc (proto-enums schema) (list model))))
89 (setf (proto-type-aliases schema) (nconc (proto-type-aliases schema) (list model))))
90 ((define-message define-extend)
91 (setf (proto-parent model) schema)
92 (setf (proto-messages schema) (nconc (proto-messages schema) (list model)))
93 (when (eq (proto-message-type model) :extends)
94 (setf (proto-extenders schema) (nconc (proto-extenders schema) (list model)))))
96 (setf (proto-services schema) (nconc (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 (setf (proto-values enum) (nconc (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 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
273 (setf (proto-type-aliases message) (nconc (proto-type-aliases message) (list model))))
274 ((define-message define-extend)
275 (setf (proto-parent model) message)
276 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
277 (when (eq (proto-message-type model) :extends)
278 (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
280 (setf (proto-parent model) message)
281 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
283 (collect-slot extra-slot))
284 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
286 (setf (proto-extensions message) (nconc (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 (setf (proto-fields message) (nconc (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 (setf (proto-messages extends) (nconc (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 #+ccl (make-hash-table :test #'eq :weak t)
412 #+sbcl (make-hash-table :test #'eq :weakness :value)))
413 ,@(and reader `((defmethod ,reader ((object ,type))
414 (gethash object ,stable ,default))))
415 ,@(and writer `((defmethod ,writer ((object ,type) value)
416 (declare (type ,stype value))
417 (setf (gethash object ,stable) value))))
418 ;; For Python compatibility
419 (defmethod get-extension ((object ,type) (slot (eql ',sname)))
420 (values (gethash object ,stable ,default)))
421 (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
422 (setf (gethash object ,stable) value))
423 (defmethod has-extension ((object ,type) (slot (eql ',sname)))
424 (multiple-value-bind (value foundp)
425 (gethash object ,stable)
426 (declare (ignore value))
428 (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
429 (remhash object ,stable)))
431 ;; 'defsetf' needs to be visible at compile time
432 `((eval-when (:compile-toplevel :load-toplevel :execute)
433 (defsetf ,reader ,writer))))))))
434 (setf (proto-message-type extra-field) :extends) ;this field is an extension
435 (setf (proto-fields extends) (nconc (proto-fields extends) (list extra-field)))
436 (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list extra-field)))))))
438 (multiple-value-bind (field slot idx)
439 (process-field field index :conc-name conc-name :alias-for alias-for)
440 (assert (not (find-field extends (proto-index field))) ()
441 "The field ~S overlaps with another field in ~S"
442 (proto-value field) (proto-class extends))
443 (assert (index-within-extensions-p idx message) ()
444 "The index ~D is not in range for extending ~S"
445 idx (proto-class message))
448 (let* ((inits (cdr slot))
450 (stable (fintern "~A-VALUES" sname))
451 (stype (getf inits :type))
452 (reader (or (getf inits :accessor)
454 (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
455 *protobuf-package*)))
456 (writer (or (getf inits :writer)
457 (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
458 (default (getf inits :initform)))
459 ;; For the extended slots, each slot gets its own table
460 ;; keyed by the object, which lets us avoid having a slot in each
461 ;; instance that holds a table keyed by the slot name
462 ;; Multiple 'define-extends' on the same class in the same image
463 ;; will result in harmless redefinitions, so squelch the warnings
464 ;;--- Maybe these methods need to be defined in 'define-message'?
465 (collect-form `(without-redefinition-warnings ()
466 (let ((,stable #+ccl (make-hash-table :test #'eq :weak t)
467 #+sbcl (make-hash-table :test #'eq :weakness :value)))
468 ,@(and reader `((defmethod ,reader ((object ,type))
469 (gethash object ,stable ,default))))
470 ,@(and writer `((defmethod ,writer ((object ,type) value)
471 (declare (type ,stype value))
472 (setf (gethash object ,stable) value))))
473 (defmethod get-extension ((object ,type) (slot (eql ',sname)))
474 (values (gethash object ,stable ,default)))
475 (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
476 (setf (gethash object ,stable) value))
477 (defmethod has-extension ((object ,type) (slot (eql ',sname)))
478 (multiple-value-bind (value foundp)
479 (gethash object ,stable)
480 (declare (ignore value))
482 (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
483 (remhash object ,stable)))
485 `((eval-when (:compile-toplevel :load-toplevel :execute)
486 (defsetf ,reader ,writer))))))
487 ;; This so that (de)serialization works
488 (setf (proto-reader field) reader
489 (proto-writer field) writer)))
490 (setf (proto-message-type field) :extends) ;this field is an extension
491 (setf (proto-fields extends) (nconc (proto-fields extends) (list field)))
492 (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list field)))))))
498 (defun index-within-extensions-p (index message)
499 (let ((extensions (proto-extensions message)))
500 (some #'(lambda (ext)
501 (and (i>= index (proto-extension-from ext))
502 (i<= index (proto-extension-to ext))))
505 (defmacro define-group (type (&key index arity name conc-name alias-for reader options
506 documentation source-location)
507 &body fields &environment env)
508 "Define a message named 'type' and a Lisp 'defclass', *and* a field named type.
509 This is deprecated in Protobufs, but if you have to use it, you must give
510 'index' as the field index and 'arity' of :required, :optional or :repeated.
511 'name' can be used to override the defaultly generated Protobufs message name.
512 The body consists of fields, or 'define-enum' or 'define-message' forms.
513 'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
514 If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
515 used as an alias for a class that already exists in Lisp. This feature is intended
516 to be used to define messages that will be serialized from existing Lisp classes;
517 unless you get the slot names or readers exactly right for each field, it will be
518 the case that trying to (de)serialize into a Lisp object won't work.
519 'options' is a set of keyword/value pairs, both of which are strings.
521 Fields take the form (slot &key type name default reader)
522 'slot' can be either a symbol giving the field name, or a list whose
523 first element is the slot name and whose second element is the index.
524 'type' is the type of the slot.
525 'name' can be used to override the defaultly generated Protobufs field name.
526 'default' is the default value for the slot.
527 'reader' is a Lisp slot reader function to use to get the value, instead of
528 using 'slot-value'; this is often used when aliasing an existing class.
529 'writer' is a Lisp slot writer function to use to set the value."
530 (check-type index integer)
531 (check-type arity (member :required :optional :repeated))
532 (let* ((slot (or type (and name (proto->slot-name name *protobuf-package*))))
533 (name (or name (class-name->proto type)))
534 (options (loop for (key val) on options by #'cddr
535 collect (make-option (if (symbolp key) (slot-name->proto key) key) val)))
536 (conc-name (conc-name-for-type type conc-name))
538 (let ((msg-conc (proto-conc-name *protobuf*)))
540 (intern (format nil "~A~A" msg-conc slot) *protobuf-package*)))))
541 (mslot (unless alias-for
542 `(,slot ,@(case arity
546 `(:type (or ,type null)
549 `(:type (list-of ,type)
552 `(:accessor ,reader))
553 :initarg ,(kintern (symbol-name slot)))))
554 (mfield (make-instance 'protobuf-field
555 :name (slot-name->proto slot)
558 :qualified-name (make-qualified-name *protobuf* (slot-name->proto slot))
564 :message-type :group))
565 (message (make-instance 'protobuf-message
568 :qualified-name (make-qualified-name *protobuf* name)
572 :options (remove-options options "default" "packed")
573 :message-type :group ;this message is a group
574 :documentation documentation
575 :source-location source-location))
577 ;; Only now can we bind *protobuf* to the (group) message
578 (*protobuf* message))
579 (with-collectors ((slots collect-slot)
581 ;; The typedef needs to be first in forms otherwise ccl warns.
582 ;; We'll collect them separately and splice them in first.
583 (type-forms collect-type-form))
584 (dolist (field fields)
586 ((define-enum define-message define-extend define-extension define-group
588 (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
589 (macroexpand-1 field env)
590 (assert (eq progn 'progn) ()
591 "The macroexpansion for ~S failed" field)
592 (map () #'collect-form definers)
595 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
597 (setf (proto-type-aliases message) (nconc (proto-type-aliases message) (list model))))
598 ((define-message define-extend)
599 (setf (proto-parent model) message)
600 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
601 (when (eq (proto-message-type model) :extends)
602 (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
604 (setf (proto-parent model) message)
605 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
607 (collect-slot extra-slot))
608 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
610 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
612 (multiple-value-bind (field slot idx)
613 (process-field field index :conc-name conc-name :alias-for alias-for)
614 (assert (not (find-field message (proto-index field))) ()
615 "The field ~S overlaps with another field in ~S"
616 (proto-value field) (proto-class message))
620 (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
622 ;; If we've got an alias, define a a type that is the subtype of
623 ;; the Lisp class that typep and subtypep work
624 (unless (or (eq type alias-for) (find-class type nil))
625 (collect-type-form `(deftype ,type () ',alias-for)))
626 ;; If no alias, define the class now
627 (collect-type-form `(defclass ,type (#+use-base-protobuf-message base-protobuf-message) (,@slots)
628 ,@(and documentation `((:documentation ,documentation))))))
632 ((with-proto-source-location (,type ,name protobuf-message ,@source-location)
638 (defun process-field (field index &key conc-name alias-for)
639 "Process one field descriptor within 'define-message' or 'define-extend'.
640 Returns a 'proto-field' object, a CLOS slot form and the incremented field index."
641 (when (i= index 18999) ;skip over the restricted range
643 (destructuring-bind (slot &rest other-options
644 &key type reader writer name (default nil default-p) packed
645 ((:index idx)) options documentation &allow-other-keys) field
646 ;; Allow old ((slot index) ...) or new (slot :index ...),
647 ;; but only allow one of those two to be used simultaneously
648 (assert (if idx (not (listp slot)) t) ()
649 "Use either ((slot index) ...) or (slot :index index ...), but not both")
650 (let* ((idx (or idx (if (listp slot) (second slot) (iincf index))))
651 (slot (if (listp slot) (first slot) slot))
654 (intern (format nil "~A~A" conc-name slot) *protobuf-package*))))
656 (loop for (key val) on other-options by #'cddr
657 unless (member key '(:type :reader :writer :name :default :packed :documentation))
658 collect (make-option (slot-name->proto key) val))
659 (loop for (key val) on options by #'cddr
660 collect (make-option (if (symbolp key) (slot-name->proto key) key) val)))))
661 (multiple-value-bind (ptype pclass)
662 (clos-type-to-protobuf-type type)
663 (multiple-value-bind (reqd vectorp)
664 (clos-type-to-protobuf-required type)
665 (let* ((default (if (eq reqd :repeated)
666 (if vectorp $empty-vector $empty-list) ;to distinguish between list-of and vector-of
667 (if default-p default $empty-default)))
668 (cslot (unless alias-for
673 `(:accessor ,reader)))
676 :initarg ,(kintern (symbol-name slot))
677 ,@(cond ((eq reqd :repeated)
678 ;; Repeated fields get a container for their elements
680 `(:initform (make-array 5 :fill-pointer 0 :adjustable t))
682 ((and (not default-p)
684 ;; Use unbound for booleans only
685 (not (eq pclass :bool)))
688 `(:initform ,(protobuf-default-to-clos-init default type)))))))
689 (field (make-instance 'protobuf-field
690 :name (or name (slot-name->proto slot))
693 :qualified-name (make-qualified-name *protobuf* (or name (slot-name->proto slot)))
695 ;; One of :required, :optional or :repeated
702 ;; Pack the field only if requested and it actually makes sense
703 :packed (and (eq reqd :repeated) packed t)
705 :documentation documentation)))
706 (values field cslot idx)))))))
708 (defparameter *rpc-package* nil
709 "The Lisp package that implements RPC.
710 This should be set when an RPC package that uses CL-Protobufs gets loaded.")
711 (defparameter *rpc-call-function* nil
712 "The Lisp function that implements RPC client-side calls.
713 This should be set when an RPC package that uses CL-Protobufs gets loaded.")
715 ;; Define a service named 'type' with generic functions declared for
716 ;; each of the methods within the service
717 (defmacro define-service (type (&key name options
718 documentation source-location)
720 "Define a service named 'type' and Lisp 'defgeneric' for all its methods.
721 'name' can be used to override the defaultly generated Protobufs service name.
722 'options' is a set of keyword/value pairs, both of which are strings.
724 The body is a set of method specs of the form (name (input-type [=>] output-type) &key options).
725 'input-type' and 'output-type' may also be of the form (type &key name)."
726 (let* ((name (or name (class-name->proto type)))
727 (options (loop for (key val) on options by #'cddr
728 collect (make-option (if (symbolp key) (slot-name->proto key) key) val)))
729 (service (make-instance 'protobuf-service
732 :qualified-name (make-qualified-name *protobuf* name)
735 :documentation documentation
736 :source-location source-location))
738 (with-collectors ((forms collect-form))
739 (dolist (method method-specs)
740 (destructuring-bind (function (&rest types)
741 &key name options documentation source-location) method
742 (let* ((input-type (first types))
743 (output-type (if (string= (string (second types)) "=>") (third types) (second types)))
744 (streams-type (if (string= (string (second types)) "=>")
745 (getf (cdddr types) :streams)
746 (getf (cddr types) :streams)))
747 (input-name (and (listp input-type)
748 (getf (cdr input-type) :name)))
749 (input-type (if (listp input-type) (car input-type) input-type))
750 (output-name (and (listp output-type)
751 (getf (cdr output-type) :name)))
752 (output-type (if (listp output-type) (car output-type) output-type))
753 (streams-name (and (listp streams-type)
754 (getf (cdr streams-type) :name)))
755 (streams-type (if (listp streams-type) (car streams-type) streams-type))
756 (options (loop for (key val) on options by #'cddr
757 collect (make-option (if (symbolp key) (slot-name->proto key) key) val)))
758 (package *protobuf-rpc-package*)
759 (client-fn (intern (format nil "~A-~A" 'call function) package))
760 (server-fn (intern (format nil "~A-~A" function 'impl) package))
761 (method (make-instance 'protobuf-method
763 :name (or name (class-name->proto function))
764 :qualified-name (make-qualified-name *protobuf* (or name (class-name->proto function)))
766 :client-stub client-fn
767 :server-stub server-fn
768 :input-type input-type
769 :input-name (or input-name (class-name->proto input-type))
770 :output-type output-type
771 :output-name (or output-name (class-name->proto output-type))
772 :streams-type streams-type
773 :streams-name (and streams-type
774 (or streams-name (class-name->proto streams-type)))
777 :documentation documentation
778 :source-location source-location)))
779 (setf (proto-methods service) (nconc (proto-methods service) (list method)))
780 ;; The following are the hooks to an RPC implementation
781 (let* ((vrequest (intern (symbol-name 'request) package))
782 (vchannel (intern (symbol-name 'channel) package))
783 (vcallback (intern (symbol-name 'callback) package)))
784 ;; The client side stub, e.g., 'read-air-reservation'.
785 ;; The expectation is that the RPC implementation will provide code to make it
786 ;; easy to implement a method for this on each kind of channel (HTTP, TCP socket,
787 ;; IPC, etc). Unlike C++/Java/Python, we don't need a client-side subclass,
788 ;; because we can just use multi-methods.
789 ;; The 'do-XXX' method calls the RPC code with the channel, the method
790 ;; (i.e., a 'protobuf-method' object), the request and the callback function.
791 ;; The RPC code should take care of serializing the input, transmitting the
792 ;; request over the wire, waiting for input (or not if it's asynchronous),
793 ;; filling in the output, and either returning the response (if synchronous)
794 ;; or calling the callback with the response as an argument (if asynchronous).
795 ;; It will also deserialize the response so that the client code sees the
796 ;; response as an application object.
797 (collect-form `(defgeneric ,client-fn (,vchannel ,vrequest &key ,vcallback)
798 ,@(and documentation `((:documentation ,documentation)))
799 #-sbcl (declare (values ,output-type))
800 (:method (,vchannel (,vrequest ,input-type) &key ,vcallback)
801 (declare (ignorable ,vchannel ,vcallback))
802 (let ((call (and *rpc-package* *rpc-call-function*)))
804 "There is no RPC package loaded!")
805 (funcall call ,vchannel ',method ,vrequest
806 :callback ,vcallback)))))
807 ;; The server side stub, e.g., 'do-read-air-reservation'.
808 ;; The expectation is that the server-side program will implement
809 ;; a method with the business logic for this on each kind of channel
810 ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
811 ;; of the input class.
812 ;; The business logic is expected to perform the correct operations on
813 ;; the input object, which arrived via Protobufs, and produce an output
814 ;; of the given type, which will be serialized and sent back over the wire.
815 ;; The channel objects hold client identity information, deadline info,
816 ;; etc, and can be side-effected to indicate success or failure.
817 ;; The RPC code provides the channel classes and does (de)serialization, etc
818 (collect-form `(defgeneric ,server-fn (,vchannel ,vrequest)
819 ,@(and documentation `((:documentation ,documentation)))
820 #-sbcl (declare (values ,output-type))))))))
824 ((with-proto-source-location (,type ,name protobuf-service ,@source-location)
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"
842 (let* ((name (or name (class-name->proto type)))
843 (alias (make-instance 'protobuf-type-alias
848 :proto-type-str type-str
849 :serializer serializer
850 :deserializer deserializer
851 :qualified-name (make-qualified-name *protobuf* name)
853 :documentation documentation
854 :source-location source-location)))
855 (with-collectors ((forms collect-form))
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)))
866 ((with-proto-source-location (,type ,name protobuf-type-alias ,@source-location)
870 ;;; Ensure everything in a Protobufs schema is defined
872 (defvar *undefined-messages*)
874 ;; A very useful tool during development...
875 (defun ensure-all-schemas ()
878 (loop for p being the hash-values of *all-schemas*
880 #'string< :key #'proto-name)))
881 (mapcan #'ensure-schema protos)))
883 (defgeneric ensure-schema (schema)
885 "Ensure that all of the types are defined in the Protobufs schema 'schema'.
886 This returns two values:
887 - A list whose elements are (<undefined-type> \"message:field\" ...)
888 - The accumulated warnings table that has the same information as objects.")
889 (:method ((schema protobuf-schema))
890 (let ((*undefined-messages* (make-hash-table))
891 (trace (list schema)))
892 (map () (curry #'ensure-message trace) (proto-messages schema))
893 (map () (curry #'ensure-service trace) (proto-services schema))
894 (loop for type being the hash-keys of *undefined-messages*
895 using (hash-value things)
897 (mapcar #'(lambda (thing)
898 (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
899 things)) into warnings
900 finally (return (values warnings *undefined-messages*))))))
902 (defgeneric ensure-message (trace message)
903 (:method (trace (message protobuf-message))
904 (let ((trace (cons message trace)))
905 (map () (curry #'ensure-message trace) (proto-messages message))
906 (map () (curry #'ensure-field trace message) (proto-fields message)))))
908 (defgeneric ensure-field (trace message field)
909 (:method (trace message (field protobuf-field))
910 (ensure-type trace message field (proto-class field))))
912 (defgeneric ensure-service (trace service)
913 (:method (trace (service protobuf-service))
914 (map () (curry #'ensure-method trace service) (proto-methods service))))
916 (defgeneric ensure-method (trace service method)
917 (:method (trace service (method protobuf-method))
918 (ensure-type trace service method (proto-input-type method))
919 (ensure-type trace service method (proto-output-type method))
920 (ensure-type trace service method (proto-streams-type method))))
922 ;; 'message' and 'field' can be a message and a field or a service and a method
923 (defun ensure-type (trace message field type)
924 (unless (keywordp type)
925 (let ((msg (loop for p in trace
926 thereis (or (find-message p type)
927 (find-enum p type)))))
929 (push (cons message field) (gethash type *undefined-messages*))))))