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-instance 'protobuf-option
49 :name (if (symbolp key) (slot-name->proto key) key)
51 "optimize_for" "lisp_package"))
52 (imports (if (listp import) import (list import)))
53 (schema (make-instance 'protobuf-schema
56 :syntax (or syntax "proto2")
58 :lisp-package (or lisp-pkg (substitute #\- #\_ package))
61 (append options (list (make-instance 'protobuf-option
63 :value (if (eq optimize :speed) "SPEED" "CODE_SIZE")
66 :documentation documentation))
68 (*protobuf-package* (or (find-proto-package lisp-pkg) *package*))
69 (*protobuf-rpc-package* (or (find-proto-package (format nil "~A-~A" lisp-pkg 'rpc)) *package*)))
70 (process-imports schema imports)
71 (with-collectors ((forms collect-form))
72 (dolist (msg messages)
73 (assert (and (listp msg)
74 (member (car msg) '(define-enum define-message define-extend define-service
75 define-type-alias))) ()
76 "The body of ~S must be one of ~{~S~^ or ~}"
78 '(define-enum define-message define-extend define-service define-type-alias))
79 ;; The macro-expander will return a form that consists
80 ;; of 'progn' followed by a symbol naming what we've expanded
81 ;; (define-enum, define-message, define-extend, define-service),
82 ;; followed by the Lisp model object created by the defining form,
83 ;; followed by other defining forms (e.g., deftype, defclass)
84 (destructuring-bind (&optional progn model-type model definers)
85 (macroexpand-1 msg env)
86 (assert (eq progn 'progn) ()
87 "The macroexpansion for ~S failed" msg)
88 (map () #'collect-form definers)
91 (setf (proto-enums schema) (nconc (proto-enums schema) (list model))))
93 (setf (proto-type-aliases schema) (nconc (proto-type-aliases schema) (list model))))
94 ((define-message define-extend)
95 (setf (proto-parent model) schema)
96 (setf (proto-messages schema) (nconc (proto-messages schema) (list model)))
97 (when (eq (proto-message-type model) :extends)
98 (setf (proto-extenders schema) (nconc (proto-extenders schema) (list model)))))
100 (setf (proto-services schema) (nconc (proto-services schema) (list model)))))))
101 (let ((var (intern (format nil "*~A*" type) *protobuf-package*)))
105 (let* ((old-schema ,var)
106 (new-schema ,schema))
108 (multiple-value-bind (upgradable warnings)
109 (schema-upgradable old-schema new-schema)
111 (protobufs-warn "The old schema for ~S (~A) can't be safely upgraded; proceeding anyway"
113 (map () #'protobufs-warn warnings))))
114 (setq ,var new-schema)
115 (record-protobuf ,var))
116 ,@(with-collectors ((messages collect-message))
117 (labels ((collect-messages (message)
118 (collect-message message)
119 (map () #'collect-messages (proto-messages message))))
120 (map () #'collect-messages (proto-messages schema)))
122 (mapcar #'(lambda (m) `(record-protobuf ,m)) messages)
123 (when (eq optimize :speed)
124 (append (mapcar #'generate-object-size messages)
125 (mapcar #'generate-serializer messages)
126 (mapcar #'generate-deserializer messages)))))
129 (defmacro with-proto-source-location ((type name definition-type
130 &optional pathname start-pos end-pos)
132 "Establish a context which causes the generated Lisp code to have
133 source location information that points to the .proto file.
134 'type' is the name of the Lisp definition (a symbol).
135 'name' is the name of the Protobufs definition (a string).
136 'definition-type' is the kind of definition, e.g., 'protobuf-enum'.
137 'pathname', 'start-pos' and 'end-pos' give the location of the definition
140 (record-proto-source-location ',type ,name ',definition-type
141 ,pathname ,start-pos ,end-pos)
145 (defun record-proto-source-location (type name definition-type
146 &optional pathname start-pos end-pos)
147 (declare (ignore name))
148 (when (and ccl::*record-source-file*
149 (typep pathname '(or string pathname)))
150 (let ((ccl::*loading-toplevel-location* (ccl::make-source-note :filename pathname
153 (ccl:record-source-file type definition-type))))
156 (defun record-proto-source-location (type name definition-type
157 &optional pathname start-pos end-pos)
158 (declare (ignorable name type definition-type pathname start-pos end-pos)))
160 ;; Define an enum type named 'type' and a Lisp 'deftype'
161 (defmacro define-enum (type (&key name conc-name alias-for options
162 documentation source-location)
164 "Define a Protobufs enum type and a Lisp 'deftype' named 'type'.
165 'name' can be used to override the defaultly generated Protobufs enum name.
166 'conc-name' will be used as the prefix to the Lisp enum names, if it's supplied.
167 If 'alias-for' is given, no Lisp 'deftype' will be defined. Instead, the enum
168 will be used as an alias for an enum type that already exists in Lisp.
169 'options' is a set of keyword/value pairs, both of which are strings.
171 The body consists of the enum values in the form 'name' or (name index)."
172 (let* ((name (or name (class-name->proto type)))
173 (options (loop for (key val) on options by #'cddr
174 collect (make-instance 'protobuf-option
175 :name (if (symbolp key) (slot-name->proto key) key)
177 (conc-name (conc-name-for-type type conc-name))
179 (enum (make-instance 'protobuf-enum
182 :qualified-name (make-qualified-name *protobuf* name)
186 :documentation documentation
187 :source-location source-location)))
188 (with-collectors ((vals collect-val)
189 (forms collect-form))
191 ;; Allow old (name index) and new (name :index index)
192 (let* ((idx (if (listp val)
193 (if (eq (second val) :index) (third val) (second val))
195 (name (if (listp val) (first val) val))
196 (val-name (kintern (if conc-name (format nil "~A~A" conc-name name) (symbol-name name))))
197 (enum-name (if conc-name (format nil "~A~A" conc-name name) (symbol-name name)))
198 (vname (enum-name->proto enum-name))
199 (enum-val (make-instance 'protobuf-enum-value
201 :qualified-name (make-qualified-name enum vname)
205 (collect-val val-name)
206 (setf (proto-values enum) (nconc (proto-values enum) (list enum-val)))))
208 ;; If we've got an alias, define a a type that is the subtype of
209 ;; the Lisp enum so that typep and subtypep work
210 (unless (eq type alias-for)
211 (collect-form `(deftype ,type () ',alias-for)))
212 ;; If no alias, define the Lisp enum type now
213 (collect-form `(deftype ,type () '(member ,@vals))))
217 ((with-proto-source-location (,type ,name protobuf-enum ,@source-location)
220 ;; Define a message named 'name' and a Lisp 'defclass'
221 (defmacro define-message (type (&key name conc-name alias-for options
222 documentation source-location)
223 &body fields &environment env)
224 "Define a message named 'type' and a Lisp 'defclass'.
225 'name' can be used to override the defaultly generated Protobufs message name.
226 The body consists of fields, or 'define-enum' or 'define-message' forms.
227 'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
228 If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
229 used as an alias for a class that already exists in Lisp. This feature is intended
230 to be used to define messages that will be serialized from existing Lisp classes;
231 unless you get the slot names or readers exactly right for each field, it will be
232 the case that trying to (de)serialize into a Lisp object won't work.
233 'options' is a set of keyword/value pairs, both of which are strings.
235 Fields take the form (slot &key type name default reader)
236 'slot' can be either a symbol giving the field name, or a list whose
237 first element is the slot name and whose second element is the index.
238 'type' is the type of the slot.
239 'name' can be used to override the defaultly generated Protobufs field name.
240 'default' is the default value for the slot.
241 'reader' is a Lisp slot reader function to use to get the value, instead of
242 using 'slot-value'; this is often used when aliasing an existing class.
243 'writer' is a Lisp slot writer function to use to set the value."
244 (let* ((name (or name (class-name->proto type)))
245 (options (loop for (key val) on options by #'cddr
246 collect (make-instance 'protobuf-option
247 :name (if (symbolp key) (slot-name->proto key) key)
249 (conc-name (conc-name-for-type type conc-name))
250 (message (make-instance 'protobuf-message
253 :qualified-name (make-qualified-name *protobuf* name)
257 :options (remove-options options "default" "packed")
258 :documentation documentation
259 :source-location source-location))
261 ;; Only now can we bind *protobuf* to the new message
262 (*protobuf* message))
263 (with-collectors ((slots collect-slot)
265 ;; The typedef needs to be first in forms otherwise ccl warns.
266 ;; We'll collect them separately and splice them in first.
267 (type-forms collect-type-form))
268 (dolist (field fields)
270 ((define-enum define-message define-extend define-extension define-group
272 (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
273 (macroexpand-1 field env)
274 (assert (eq progn 'progn) ()
275 "The macroexpansion for ~S failed" field)
276 (map () #'collect-form definers)
279 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
281 (setf (proto-type-aliases message) (nconc (proto-type-aliases message) (list model))))
282 ((define-message define-extend)
283 (setf (proto-parent model) message)
284 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
285 (when (eq (proto-message-type model) :extends)
286 (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
288 (setf (proto-parent model) message)
289 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
291 (collect-slot extra-slot))
292 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
294 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
296 (multiple-value-bind (field slot idx)
297 (process-field field index :conc-name conc-name :alias-for alias-for)
298 (assert (not (find-field message (proto-index field))) ()
299 "The field ~S overlaps with another field in ~S"
300 (proto-value field) (proto-class message))
304 (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
306 ;; If we've got an alias, define a a type that is the subtype of
307 ;; the Lisp class that typep and subtypep work
308 (unless (or (eq type alias-for) (find-class type nil))
309 (collect-type-form `(deftype ,type () ',alias-for)))
310 ;; If no alias, define the class now
311 (collect-type-form `(defclass ,type (#+use-base-protobuf-message base-protobuf-message) (,@slots)
312 ,@(and documentation `((:documentation ,documentation))))))
316 ((with-proto-source-location (,type ,name protobuf-message ,@source-location)
320 (defun conc-name-for-type (type conc-name)
323 ((member t) (format nil "~:@(~A~)-" type))
324 ((or string symbol) (string-upcase (string conc-name)))
327 (defmacro define-extension (from to)
328 "Define an extension range within a message.
329 The \"body\" is the start and end of the range, both inclusive."
330 (let ((to (etypecase to
332 (symbol (if (string-equal to "MAX") #.(1- (ash 1 29)) to)))))
335 ,(make-instance 'protobuf-extension
337 :to (if (eq to 'max) #.(1- (ash 1 29)) to))
340 (defmacro define-extend (type (&key name conc-name options documentation)
341 &body fields &environment env)
342 "Define an extension to the message named 'type'.
343 'name' can be used to override the defaultly generated Protobufs message name.
344 The body consists only of fields.
345 'options' is a set of keyword/value pairs, both of which are strings.
347 Fields take the form (slot &key type name default reader)
348 'slot' can be either a symbol giving the field name, or a list whose
349 first element is the slot name and whose second element is the index.
350 'type' is the type of the slot.
351 'name' can be used to override the defaultly generated Protobufs field name.
352 'default' is the default value for the slot.
353 'reader' is a Lisp slot reader function to use to get the value, instead of
354 using 'slot-value'; this is often used when aliasing an existing class.
355 'writer' is a Lisp slot writer function to use to set the value."
356 (let* ((name (or name (class-name->proto type)))
357 (options (loop for (key val) on options by #'cddr
358 collect (make-instance 'protobuf-option
359 :name (if (symbolp key) (slot-name->proto key) key)
361 (message (find-message *protobuf* type))
362 (conc-name (or (conc-name-for-type type conc-name)
363 (and message (proto-conc-name message))))
364 (alias-for (and message (proto-alias-for message)))
365 (extends (and message
366 (make-instance 'protobuf-message
367 :class (proto-class message)
368 :name (proto-name message)
369 :qualified-name (proto-qualified-name message)
373 :enums (copy-list (proto-enums message))
374 :messages (copy-list (proto-messages message))
375 :fields (copy-list (proto-fields message))
376 :extensions (copy-list (proto-extensions message))
377 :options (remove-options
378 (or options (copy-list (proto-options message))) "default" "packed")
379 :message-type :extends ;this message is an extension
380 :documentation documentation
381 :type-aliases (copy-list (proto-type-aliases message)))))
382 ;; Only now can we bind *protobuf* to the new extended message
386 "There is no message named ~A to extend" name)
387 (assert (eq type (proto-class message)) ()
388 "The type ~S doesn't match the type of the message being extended ~S"
390 (with-collectors ((forms collect-form))
391 (dolist (field fields)
392 (assert (not (member (car field)
393 '(define-enum define-message define-extend define-extension
394 define-type-alias))) ()
395 "The body of ~S can only contain field and group definitions" 'define-extend)
398 (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
399 (macroexpand-1 field env)
400 (assert (eq progn 'progn) ()
401 "The macroexpansion for ~S failed" field)
402 (map () #'collect-form definers)
405 (setf (proto-parent model) extends)
406 (setf (proto-messages extends) (nconc (proto-messages extends) (list model)))
408 ;;--- Refactor to get rid of all this duplicated code!
409 (let* ((inits (cdr extra-slot))
410 (sname (car extra-slot))
411 (stable (fintern "~A-VALUES" sname))
412 (stype (getf inits :type))
413 (reader (or (getf inits :accessor)
415 (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
416 *protobuf-package*)))
417 (writer (or (getf inits :writer)
418 (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
419 (default (getf inits :initform)))
420 (collect-form `(without-redefinition-warnings ()
421 (let ((,stable #+ccl (make-hash-table :test #'eq :weak t)
422 #+sbcl (make-hash-table :test #'eq :weakness :value)))
423 ,@(and reader `((defmethod ,reader ((object ,type))
424 (gethash object ,stable ,default))))
425 ,@(and writer `((defmethod ,writer ((object ,type) value)
426 (declare (type ,stype value))
427 (setf (gethash object ,stable) value))))
428 ;; For Python compatibility
429 (defmethod get-extension ((object ,type) (slot (eql ',sname)))
430 (values (gethash object ,stable ,default)))
431 (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
432 (setf (gethash object ,stable) value))
433 (defmethod has-extension ((object ,type) (slot (eql ',sname)))
434 (multiple-value-bind (value foundp)
435 (gethash object ,stable)
436 (declare (ignore value))
438 (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
439 (remhash object ,stable)))
441 ;; 'defsetf' needs to be visible at compile time
442 `((eval-when (:compile-toplevel :load-toplevel :execute)
443 (defsetf ,reader ,writer))))))))
444 (setf (proto-message-type extra-field) :extends) ;this field is an extension
445 (setf (proto-fields extends) (nconc (proto-fields extends) (list extra-field)))
446 (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list extra-field)))))))
448 (multiple-value-bind (field slot idx)
449 (process-field field index :conc-name conc-name :alias-for alias-for)
450 (assert (not (find-field extends (proto-index field))) ()
451 "The field ~S overlaps with another field in ~S"
452 (proto-value field) (proto-class extends))
453 (assert (index-within-extensions-p idx message) ()
454 "The index ~D is not in range for extending ~S"
455 idx (proto-class message))
458 (let* ((inits (cdr slot))
460 (stable (fintern "~A-VALUES" sname))
461 (stype (getf inits :type))
462 (reader (or (getf inits :accessor)
464 (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
465 *protobuf-package*)))
466 (writer (or (getf inits :writer)
467 (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
468 (default (getf inits :initform)))
469 ;; For the extended slots, each slot gets its own table
470 ;; keyed by the object, which lets us avoid having a slot in each
471 ;; instance that holds a table keyed by the slot name
472 ;; Multiple 'define-extends' on the same class in the same image
473 ;; will result in harmless redefinitions, so squelch the warnings
474 ;;--- Maybe these methods need to be defined in 'define-message'?
475 (collect-form `(without-redefinition-warnings ()
476 (let ((,stable #+ccl (make-hash-table :test #'eq :weak t)
477 #+sbcl (make-hash-table :test #'eq :weakness :value)))
478 ,@(and reader `((defmethod ,reader ((object ,type))
479 (gethash object ,stable ,default))))
480 ,@(and writer `((defmethod ,writer ((object ,type) value)
481 (declare (type ,stype value))
482 (setf (gethash object ,stable) value))))
483 (defmethod get-extension ((object ,type) (slot (eql ',sname)))
484 (values (gethash object ,stable ,default)))
485 (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
486 (setf (gethash object ,stable) value))
487 (defmethod has-extension ((object ,type) (slot (eql ',sname)))
488 (multiple-value-bind (value foundp)
489 (gethash object ,stable)
490 (declare (ignore value))
492 (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
493 (remhash object ,stable)))
495 `((eval-when (:compile-toplevel :load-toplevel :execute)
496 (defsetf ,reader ,writer))))))
497 ;; This so that (de)serialization works
498 (setf (proto-reader field) reader
499 (proto-writer field) writer)))
500 (setf (proto-message-type field) :extends) ;this field is an extension
501 (setf (proto-fields extends) (nconc (proto-fields extends) (list field)))
502 (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list field)))))))
508 (defun index-within-extensions-p (index message)
509 (let ((extensions (proto-extensions message)))
510 (some #'(lambda (ext)
511 (and (i>= index (proto-extension-from ext))
512 (i<= index (proto-extension-to ext))))
515 (defmacro define-group (type (&key index arity name conc-name alias-for reader options
516 documentation source-location)
517 &body fields &environment env)
518 "Define a message named 'type' and a Lisp 'defclass', *and* a field named type.
519 This is deprecated in Protobufs, but if you have to use it, you must give
520 'index' as the field index and 'arity' of :required, :optional or :repeated.
521 'name' can be used to override the defaultly generated Protobufs message name.
522 The body consists of fields, or 'define-enum' or 'define-message' forms.
523 'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
524 If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
525 used as an alias for a class that already exists in Lisp. This feature is intended
526 to be used to define messages that will be serialized from existing Lisp classes;
527 unless you get the slot names or readers exactly right for each field, it will be
528 the case that trying to (de)serialize into a Lisp object won't work.
529 'options' is a set of keyword/value pairs, both of which are strings.
531 Fields take the form (slot &key type name default reader)
532 'slot' can be either a symbol giving the field name, or a list whose
533 first element is the slot name and whose second element is the index.
534 'type' is the type of the slot.
535 'name' can be used to override the defaultly generated Protobufs field name.
536 'default' is the default value for the slot.
537 'reader' is a Lisp slot reader function to use to get the value, instead of
538 using 'slot-value'; this is often used when aliasing an existing class.
539 'writer' is a Lisp slot writer function to use to set the value."
540 (check-type index integer)
541 (check-type arity (member :required :optional :repeated))
542 (let* ((slot (or type (and name (proto->slot-name name *protobuf-package*))))
543 (name (or name (class-name->proto type)))
544 (options (loop for (key val) on options by #'cddr
545 collect (make-instance 'protobuf-option
546 :name (if (symbolp key) (slot-name->proto key) key)
548 (conc-name (conc-name-for-type type conc-name))
550 (let ((msg-conc (proto-conc-name *protobuf*)))
552 (intern (format nil "~A~A" msg-conc slot) *protobuf-package*)))))
553 (mslot (unless alias-for
554 `(,slot ,@(case arity
558 `(:type (or ,type null)
561 `(:type (list-of ,type)
564 `(:accessor ,reader))
565 :initarg ,(kintern (symbol-name slot)))))
566 (mfield (make-instance 'protobuf-field
567 :name (slot-name->proto slot)
570 :qualified-name (make-qualified-name *protobuf* (slot-name->proto slot))
576 :message-type :group))
577 (message (make-instance 'protobuf-message
580 :qualified-name (make-qualified-name *protobuf* name)
584 :options (remove-options options "default" "packed")
585 :message-type :group ;this message is a group
586 :documentation documentation
587 :source-location source-location))
589 ;; Only now can we bind *protobuf* to the (group) message
590 (*protobuf* message))
591 (with-collectors ((slots collect-slot)
593 ;; The typedef needs to be first in forms otherwise ccl warns.
594 ;; We'll collect them separately and splice them in first.
595 (type-forms collect-type-form))
596 (dolist (field fields)
598 ((define-enum define-message define-extend define-extension define-group
600 (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
601 (macroexpand-1 field env)
602 (assert (eq progn 'progn) ()
603 "The macroexpansion for ~S failed" field)
604 (map () #'collect-form definers)
607 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
609 (setf (proto-type-aliases message) (nconc (proto-type-aliases message) (list model))))
610 ((define-message define-extend)
611 (setf (proto-parent model) message)
612 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
613 (when (eq (proto-message-type model) :extends)
614 (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
616 (setf (proto-parent model) message)
617 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
619 (collect-slot extra-slot))
620 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
622 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
624 (multiple-value-bind (field slot idx)
625 (process-field field index :conc-name conc-name :alias-for alias-for)
626 (assert (not (find-field message (proto-index field))) ()
627 "The field ~S overlaps with another field in ~S"
628 (proto-value field) (proto-class message))
632 (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
634 ;; If we've got an alias, define a a type that is the subtype of
635 ;; the Lisp class that typep and subtypep work
636 (unless (or (eq type alias-for) (find-class type nil))
637 (collect-type-form `(deftype ,type () ',alias-for)))
638 ;; If no alias, define the class now
639 (collect-type-form `(defclass ,type (#+use-base-protobuf-message base-protobuf-message) (,@slots)
640 ,@(and documentation `((:documentation ,documentation))))))
644 ((with-proto-source-location (,type ,name protobuf-message ,@source-location)
650 (defun process-field (field index &key conc-name alias-for)
651 "Process one field descriptor within 'define-message' or 'define-extend'.
652 Returns a 'proto-field' object, a CLOS slot form and the incremented field index."
653 (when (i= index 18999) ;skip over the restricted range
655 (destructuring-bind (slot &rest other-options
656 &key type reader writer name (default nil default-p) packed
657 ((:index idx)) options documentation &allow-other-keys) field
658 ;; Allow old ((slot index) ...) or new (slot :index ...),
659 ;; but only allow one of those two to be used simultaneously
660 (assert (if idx (not (listp slot)) t) ()
661 "Use either ((slot index) ...) or (slot :index index ...), but not both")
662 (let* ((idx (or idx (if (listp slot) (second slot) (iincf index))))
663 (slot (if (listp slot) (first slot) slot))
666 (intern (format nil "~A~A" conc-name slot) *protobuf-package*))))
668 (loop for (key val) on other-options by #'cddr
669 unless (member key '(:type :reader :writer :name :default :packed :documentation))
670 collect (make-instance 'protobuf-option
671 :name (slot-name->proto key)
673 (loop for (key val) on options by #'cddr
674 collect (make-instance 'protobuf-option
675 :name (if (symbolp key) (slot-name->proto key) key)
677 (multiple-value-bind (ptype pclass)
678 (clos-type-to-protobuf-type type)
679 (multiple-value-bind (reqd vectorp)
680 (clos-type-to-protobuf-required type)
681 (let* ((default (if (eq reqd :repeated)
682 (if vectorp $empty-vector $empty-list) ;to distinguish between list-of and vector-of
683 (if default-p default $empty-default)))
684 (cslot (unless alias-for
689 `(:accessor ,reader)))
692 :initarg ,(kintern (symbol-name slot))
693 ,@(cond ((eq reqd :repeated)
694 ;; Repeated fields get a container for their elements
696 `(:initform (make-array 5 :fill-pointer 0 :adjustable t))
698 ((and (not default-p)
700 ;; Use unbound for booleans only
701 (not (eq pclass :bool)))
704 `(:initform ,(protobuf-default-to-clos-init default type)))))))
705 (field (make-instance 'protobuf-field
706 :name (or name (slot-name->proto slot))
709 :qualified-name (make-qualified-name *protobuf* (or name (slot-name->proto slot)))
711 ;; One of :required, :optional or :repeated
718 ;; Pack the field only if requested and it actually makes sense
719 :packed (and (eq reqd :repeated) packed t)
721 :documentation documentation)))
722 (values field cslot idx)))))))
724 (defparameter *rpc-package* nil
725 "The Lisp package that implements RPC.
726 This should be set when an RPC package that uses CL-Protobufs gets loaded.")
727 (defparameter *rpc-call-function* nil
728 "The Lisp function that implements RPC client-side calls.
729 This should be set when an RPC package that uses CL-Protobufs gets loaded.")
731 ;; Define a service named 'type' with generic functions declared for
732 ;; each of the methods within the service
733 (defmacro define-service (type (&key name options
734 documentation source-location)
736 "Define a service named 'type' and Lisp 'defgeneric' for all its methods.
737 'name' can be used to override the defaultly generated Protobufs service name.
738 'options' is a set of keyword/value pairs, both of which are strings.
740 The body is a set of method specs of the form (name (input-type [=>] output-type) &key options).
741 'input-type' and 'output-type' may also be of the form (type &key name)."
742 (let* ((name (or name (class-name->proto type)))
743 (options (loop for (key val) on options by #'cddr
744 collect (make-instance 'protobuf-option
745 :name (if (symbolp key) (slot-name->proto key) key)
747 (service (make-instance 'protobuf-service
750 :qualified-name (make-qualified-name *protobuf* name)
753 :documentation documentation
754 :source-location source-location))
756 (with-collectors ((forms collect-form))
757 (dolist (method method-specs)
758 (destructuring-bind (function (&rest types)
759 &key name options documentation source-location) method
760 (let* ((input-type (first types))
761 (output-type (if (string= (string (second types)) "=>") (third types) (second types)))
762 (streams-type (if (string= (string (second types)) "=>")
763 (getf (cdddr types) :streams)
764 (getf (cddr types) :streams)))
765 (input-name (and (listp input-type)
766 (getf (cdr input-type) :name)))
767 (input-type (if (listp input-type) (car input-type) input-type))
768 (output-name (and (listp output-type)
769 (getf (cdr output-type) :name)))
770 (output-type (if (listp output-type) (car output-type) output-type))
771 (streams-name (and (listp streams-type)
772 (getf (cdr streams-type) :name)))
773 (streams-type (if (listp streams-type) (car streams-type) streams-type))
774 (options (loop for (key val) on options by #'cddr
775 collect (make-instance 'protobuf-option
776 :name (if (symbolp key) (slot-name->proto key) key)
778 (package *protobuf-rpc-package*)
779 (client-fn (intern (format nil "~A-~A" 'call function) package))
780 (server-fn (intern (format nil "~A-~A" function 'impl) package))
781 (method (make-instance 'protobuf-method
783 :name (or name (class-name->proto function))
784 :qualified-name (make-qualified-name *protobuf* (or name (class-name->proto function)))
786 :client-stub client-fn
787 :server-stub server-fn
788 :input-type input-type
789 :input-name (or input-name (class-name->proto input-type))
790 :output-type output-type
791 :output-name (or output-name (class-name->proto output-type))
792 :streams-type streams-type
793 :streams-name (and streams-type
794 (or streams-name (class-name->proto streams-type)))
797 :documentation documentation
798 :source-location source-location)))
799 (setf (proto-methods service) (nconc (proto-methods service) (list method)))
800 ;; The following are the hooks to an RPC implementation
801 (let* ((vrequest (intern (symbol-name 'request) package))
802 (vchannel (intern (symbol-name 'channel) package))
803 (vcallback (intern (symbol-name 'callback) package)))
804 ;; The client side stub, e.g., 'read-air-reservation'.
805 ;; The expectation is that the RPC implementation will provide code to make it
806 ;; easy to implement a method for this on each kind of channel (HTTP, TCP socket,
807 ;; IPC, etc). Unlike C++/Java/Python, we don't need a client-side subclass,
808 ;; because we can just use multi-methods.
809 ;; The 'do-XXX' method calls the RPC code with the channel, the method
810 ;; (i.e., a 'protobuf-method' object), the request and the callback function.
811 ;; The RPC code should take care of serializing the input, transmitting the
812 ;; request over the wire, waiting for input (or not if it's asynchronous),
813 ;; filling in the output, and either returning the response (if synchronous)
814 ;; or calling the callback with the response as an argument (if asynchronous).
815 ;; It will also deserialize the response so that the client code sees the
816 ;; response as an application object.
817 (collect-form `(defgeneric ,client-fn (,vchannel ,vrequest &key ,vcallback)
818 ,@(and documentation `((:documentation ,documentation)))
819 #-sbcl (declare (values ,output-type))
820 (:method (,vchannel (,vrequest ,input-type) &key ,vcallback)
821 (declare (ignorable ,vchannel ,vcallback))
822 (let ((call (and *rpc-package* *rpc-call-function*)))
824 "There is no RPC package loaded!")
825 (funcall call ,vchannel ',method ,vrequest
826 :callback ,vcallback)))))
827 ;; The server side stub, e.g., 'do-read-air-reservation'.
828 ;; The expectation is that the server-side program will implement
829 ;; a method with the business logic for this on each kind of channel
830 ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
831 ;; of the input class.
832 ;; The business logic is expected to perform the correct operations on
833 ;; the input object, which arrived via Protobufs, and produce an output
834 ;; of the given type, which will be serialized and sent back over the wire.
835 ;; The channel objects hold client identity information, deadline info,
836 ;; etc, and can be side-effected to indicate success or failure.
837 ;; The RPC code provides the channel classes and does (de)serialization, etc
838 (collect-form `(defgeneric ,server-fn (,vchannel ,vrequest)
839 ,@(and documentation `((:documentation ,documentation)))
840 #-sbcl (declare (values ,output-type))))))))
844 ((with-proto-source-location (,type ,name protobuf-service ,@source-location)
848 ;; Lisp-only type aliases
849 (defmacro define-type-alias (type (&key name alias-for documentation source-location)
850 &key lisp-type proto-type serializer deserializer)
851 "Define a Protobufs type alias Lisp 'deftype' named 'type'.
852 'lisp-type' is the name of the Lisp type.
853 'proto-type' is the name of a primitive Protobufs type, e.g., 'int32' or 'string'.
854 'serializer' is a function that takes a Lisp object and generates a Protobufs object.
855 'deserializer' is a function that takes a Protobufs object and generates a Lisp object.
856 If 'alias-for' is given, no Lisp 'deftype' will be defined."
857 (multiple-value-bind (type-str proto)
858 (lisp-type-to-protobuf-type proto-type)
859 (assert (keywordp proto) ()
860 "The alias ~S must resolve to a Protobufs primitive type"
862 (let* ((name (or name (class-name->proto type)))
863 (alias (make-instance 'protobuf-type-alias
868 :proto-type-str type-str
869 :serializer serializer
870 :deserializer deserializer
871 :qualified-name (make-qualified-name *protobuf* name)
873 :documentation documentation
874 :source-location source-location)))
875 (with-collectors ((forms collect-form))
877 ;; If we've got an alias, define a a type that is the subtype of
878 ;; the Lisp enum so that typep and subtypep work
879 (unless (eq type alias-for)
880 (collect-form `(deftype ,type () ',alias-for)))
881 ;; If no alias, define the Lisp enum type now
882 (collect-form `(deftype ,type () ',lisp-type)))
886 ((with-proto-source-location (,type ,name protobuf-type-alias ,@source-location)
890 ;;; Ensure everything in a Protobufs schema is defined
892 (defvar *undefined-messages*)
894 ;; A very useful tool during development...
895 (defun ensure-all-schemas ()
898 (loop for p being the hash-values of *all-schemas*
900 #'string< :key #'proto-name)))
901 (mapcan #'ensure-schema protos)))
903 (defgeneric ensure-schema (schema)
905 "Ensure that all of the types are defined in the Protobufs schema 'schema'.
906 This returns two values:
907 - A list whose elements are (<undefined-type> \"message:field\" ...)
908 - The accumulated warnings table that has the same information as objects.")
909 (:method ((schema protobuf-schema))
910 (let ((*undefined-messages* (make-hash-table))
911 (trace (list schema)))
912 (map () (curry #'ensure-message trace) (proto-messages schema))
913 (map () (curry #'ensure-service trace) (proto-services schema))
914 (loop for type being the hash-keys of *undefined-messages*
915 using (hash-value things)
917 (mapcar #'(lambda (thing)
918 (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
919 things)) into warnings
920 finally (return (values warnings *undefined-messages*))))))
922 (defgeneric ensure-message (trace message)
923 (:method (trace (message protobuf-message))
924 (let ((trace (cons message trace)))
925 (map () (curry #'ensure-message trace) (proto-messages message))
926 (map () (curry #'ensure-field trace message) (proto-fields message)))))
928 (defgeneric ensure-field (trace message field)
929 (:method (trace message (field protobuf-field))
930 (ensure-type trace message field (proto-class field))))
932 (defgeneric ensure-service (trace service)
933 (:method (trace (service protobuf-service))
934 (map () (curry #'ensure-method trace service) (proto-methods service))))
936 (defgeneric ensure-method (trace service method)
937 (:method (trace service (method protobuf-method))
938 (ensure-type trace service method (proto-input-type method))
939 (ensure-type trace service method (proto-output-type method))
940 (ensure-type trace service method (proto-streams-type method))))
942 ;; 'message' and 'field' can be a message and a field or a service and a method
943 (defun ensure-type (trace message field type)
944 (unless (keywordp type)
945 (let ((msg (loop for p in trace
946 thereis (or (find-message p type)
947 (find-enum p type)))))
949 (push (cons message field) (gethash type *undefined-messages*))))))