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 ;; Define a schema named 'type', corresponding to a .proto file of that name
17 (defmacro define-schema (type (&key name syntax package lisp-package import optimize
18 options documentation)
19 &body messages &environment env)
20 "Define a schema named 'type', corresponding to a .proto file of that name.
21 'name' can be used to override the defaultly generated Protobufs name.
22 'syntax' and 'package' are as they would be in a .proto file.
23 'lisp-package' can be used to specify a Lisp package if it is different from
24 the Protobufs package given by 'package'.
25 'import' is a list of pathname strings to be imported.
26 'optimize' can be either :space (the default) or :speed; if it is :speed, the
27 serialization code will be much faster, but much less compact.
28 'options' is a property list, i.e., (\"key1\" \"val1\" \"key2\" \"val2\" ...).
30 The body consists of 'define-enum', 'define-message' or 'define-service' forms."
31 (let* ((name (or name (class-name->proto type)))
32 (package (and package (if (stringp package) package (string-downcase (string package)))))
33 (lisp-pkg (and lisp-package (if (stringp lisp-package) lisp-package (string lisp-package))))
34 (options (remove-options
35 (loop for (key val) on options by #'cddr
36 collect (make-instance 'protobuf-option
37 :name (if (symbolp key) (slot-name->proto key) key)
39 "optimize_for" "lisp_package"))
40 (imports (if (listp import) import (list import)))
41 (schema (make-instance 'protobuf-schema
44 :syntax (or syntax "proto2")
46 :lisp-package (or lisp-pkg (substitute #\- #\_ package))
49 (append options (list (make-instance 'protobuf-option
51 :value (if (eq optimize :speed) "SPEED" "CODE_SIZE")
54 :documentation documentation))
56 (*protobuf-package* (or (find-proto-package lisp-pkg) *package*))
57 (*protobuf-rpc-package* (or (find-proto-package (format nil "~A-~A" lisp-pkg 'rpc)) *package*)))
58 (process-imports schema imports)
59 (with-collectors ((forms collect-form))
60 (dolist (msg messages)
61 (assert (and (listp msg)
62 (member (car msg) '(define-enum define-message define-extend define-service
63 define-type-alias))) ()
64 "The body of ~S must be one of ~{~S~^ or ~}"
66 '(define-enum define-message define-extend define-service define-type-alias))
67 ;; The macro-expander will return a form that consists
68 ;; of 'progn' followed by a symbol naming what we've expanded
69 ;; (define-enum, define-message, define-extend, define-service),
70 ;; followed by the Lisp model object created by the defining form,
71 ;; followed by other defining forms (e.g., deftype, defclass)
72 (destructuring-bind (&optional progn model-type model definers)
73 (macroexpand-1 msg env)
74 (assert (eq progn 'progn) ()
75 "The macroexpansion for ~S failed" msg)
76 (map () #'collect-form definers)
79 (setf (proto-enums schema) (nconc (proto-enums schema) (list model))))
81 (setf (proto-type-aliases schema) (nconc (proto-type-aliases schema) (list model))))
82 ((define-message define-extend)
83 (setf (proto-parent model) schema)
84 (setf (proto-messages schema) (nconc (proto-messages schema) (list model)))
85 (when (eq (proto-message-type model) :extends)
86 (setf (proto-extenders schema) (nconc (proto-extenders schema) (list model)))))
88 (setf (proto-services schema) (nconc (proto-services schema) (list model)))))))
89 (let ((var (intern (format nil "*~A*" type) *protobuf-package*)))
93 (let* ((old-schema ,var)
96 (multiple-value-bind (upgradable warnings)
97 (schema-upgradable old-schema new-schema)
99 (protobufs-warn "The old schema for ~S (~A) can't be safely upgraded; proceeding anyway"
101 (map () #'protobufs-warn warnings))))
102 (setq ,var new-schema)
103 (record-protobuf ,var))
104 ,@(with-collectors ((messages collect-message))
105 (labels ((collect-messages (message)
106 (collect-message message)
107 (map () #'collect-messages (proto-messages message))))
108 (map () #'collect-messages (proto-messages schema)))
110 (mapcar #'(lambda (m) `(record-protobuf ,m)) messages)
111 (when (eq optimize :speed)
112 (append (mapcar #'generate-object-size messages)
113 (mapcar #'generate-serializer messages)
114 (mapcar #'generate-deserializer messages)))))
117 (defmacro with-proto-source-location ((type name definition-type
118 &optional pathname start-pos end-pos)
120 "Establish a context which causes the generated Lisp code to have
121 source location information that points to the .proto file.
122 'type' is the name of the Lisp definition (a symbol).
123 'name' is the name of the Protobufs definition (a string).
124 'definition-type' is the kind of definition, e.g., 'protobuf-enum'.
125 'pathname', 'start-pos' and 'end-pos' give the location of the definition
128 (record-proto-source-location ',type ,name ',definition-type
129 ,pathname ,start-pos ,end-pos)
133 (defun record-proto-source-location (type name definition-type
134 &optional pathname start-pos end-pos)
135 (declare (ignore name))
136 (when (and ccl::*record-source-file*
137 (typep pathname '(or string pathname)))
138 (let ((ccl::*loading-toplevel-location* (ccl::make-source-note :filename pathname
141 (ccl:record-source-file type definition-type))))
144 (defun record-proto-source-location (type name definition-type
145 &optional pathname start-pos end-pos)
146 (declare (ignorable name type definition-type pathname start-pos end-pos)))
148 ;; Define an enum type named 'type' and a Lisp 'deftype'
149 (defmacro define-enum (type (&key name conc-name alias-for options
150 documentation source-location)
152 "Define a Protobufs enum type and a Lisp 'deftype' named 'type'.
153 'name' can be used to override the defaultly generated Protobufs enum name.
154 'conc-name' will be used as the prefix to the Lisp enum names, if it's supplied.
155 If 'alias-for' is given, no Lisp 'deftype' will be defined. Instead, the enum
156 will be used as an alias for an enum type that already exists in Lisp.
157 'options' is a set of keyword/value pairs, both of which are strings.
159 The body consists of the enum values in the form 'name' or (name index)."
160 (let* ((name (or name (class-name->proto type)))
161 (options (loop for (key val) on options by #'cddr
162 collect (make-instance 'protobuf-option
163 :name (if (symbolp key) (slot-name->proto key) key)
165 (conc-name (conc-name-for-type type conc-name))
167 (enum (make-instance 'protobuf-enum
170 :qualified-name (make-qualified-name *protobuf* name)
174 :documentation documentation
175 :source-location source-location)))
176 (with-collectors ((vals collect-val)
177 (forms collect-form))
179 ;; Allow old (name index) and new (name :index index)
180 (let* ((idx (if (listp val)
181 (if (eq (second val) :index) (third val) (second val))
183 (name (if (listp val) (first val) val))
184 (val-name (kintern (if conc-name (format nil "~A~A" conc-name name) (symbol-name name))))
185 (enum-name (if conc-name (format nil "~A~A" conc-name name) (symbol-name name)))
186 (vname (enum-name->proto enum-name))
187 (enum-val (make-instance 'protobuf-enum-value
189 :qualified-name (make-qualified-name enum vname)
193 (collect-val val-name)
194 (setf (proto-values enum) (nconc (proto-values enum) (list enum-val)))))
196 ;; If we've got an alias, define a a type that is the subtype of
197 ;; the Lisp enum so that typep and subtypep work
198 (unless (eq type alias-for)
199 (collect-form `(deftype ,type () ',alias-for)))
200 ;; If no alias, define the Lisp enum type now
201 (collect-form `(deftype ,type () '(member ,@vals))))
205 ((with-proto-source-location (,type ,name protobuf-enum ,@source-location)
208 ;; Define a message named 'name' and a Lisp 'defclass'
209 (defmacro define-message (type (&key name conc-name alias-for options
210 documentation source-location)
211 &body fields &environment env)
212 "Define a message named 'type' and a Lisp 'defclass'.
213 'name' can be used to override the defaultly generated Protobufs message name.
214 The body consists of fields, or 'define-enum' or 'define-message' forms.
215 'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
216 If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
217 used as an alias for a class that already exists in Lisp. This feature is intended
218 to be used to define messages that will be serialized from existing Lisp classes;
219 unless you get the slot names or readers exactly right for each field, it will be
220 the case that trying to (de)serialize into a Lisp object won't work.
221 'options' is a set of keyword/value pairs, both of which are strings.
223 Fields take the form (slot &key type name default reader)
224 'slot' can be either a symbol giving the field name, or a list whose
225 first element is the slot name and whose second element is the index.
226 'type' is the type of the slot.
227 'name' can be used to override the defaultly generated Protobufs field name.
228 'default' is the default value for the slot.
229 'reader' is a Lisp slot reader function to use to get the value, instead of
230 using 'slot-value'; this is often used when aliasing an existing class.
231 'writer' is a Lisp slot writer function to use to set the value."
232 (let* ((name (or name (class-name->proto type)))
233 (options (loop for (key val) on options by #'cddr
234 collect (make-instance 'protobuf-option
235 :name (if (symbolp key) (slot-name->proto key) key)
237 (conc-name (conc-name-for-type type conc-name))
238 (message (make-instance 'protobuf-message
241 :qualified-name (make-qualified-name *protobuf* name)
245 :options (remove-options options "default" "packed")
246 :documentation documentation
247 :source-location source-location))
249 ;; Only now can we bind *protobuf* to the new message
250 (*protobuf* message))
251 (with-collectors ((slots collect-slot)
253 ;; The typedef needs to be first in forms otherwise ccl warns.
254 ;; We'll collect them separately and splice them in first.
255 (type-forms collect-type-form))
256 (dolist (field fields)
258 ((define-enum define-message define-extend define-extension define-group
260 (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
261 (macroexpand-1 field env)
262 (assert (eq progn 'progn) ()
263 "The macroexpansion for ~S failed" field)
264 (map () #'collect-form definers)
267 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
269 (setf (proto-type-aliases message) (nconc (proto-type-aliases message) (list model))))
270 ((define-message define-extend)
271 (setf (proto-parent model) message)
272 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
273 (when (eq (proto-message-type model) :extends)
274 (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
276 (setf (proto-parent model) message)
277 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
279 (collect-slot extra-slot))
280 (setf (proto-fields message) (nconc (proto-fields message) (list extra-field))))
282 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
284 (multiple-value-bind (field slot idx)
285 (process-field field index :conc-name conc-name :alias-for alias-for)
286 (assert (not (find-field message (proto-index field))) ()
287 "The field ~S overlaps with another field in ~S"
288 (proto-value field) (proto-class message))
292 (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
294 ;; If we've got an alias, define a a type that is the subtype of
295 ;; the Lisp class that typep and subtypep work
296 (unless (or (eq type alias-for) (find-class type nil))
297 (collect-type-form `(deftype ,type () ',alias-for)))
298 ;; If no alias, define the class now
299 (collect-type-form `(defclass ,type () (,@slots)
300 ,@(and documentation `((:documentation ,documentation))))))
304 ((with-proto-source-location (,type ,name protobuf-message ,@source-location)
308 (defun conc-name-for-type (type conc-name)
311 ((member t) (format nil "~:@(~A~)-" type))
312 ((or string symbol) (string-upcase (string conc-name)))
315 (defmacro define-extension (from to)
316 "Define an extension range within a message.
317 The \"body\" is the start and end of the range, both inclusive."
318 (let ((to (etypecase to
320 (symbol (if (string-equal to "MAX") #.(1- (ash 1 29)) to)))))
323 ,(make-instance 'protobuf-extension
325 :to (if (eq to 'max) #.(1- (ash 1 29)) to))
328 (defmacro define-extend (type (&key name conc-name options documentation)
329 &body fields &environment env)
330 "Define an extension to the message named 'type'.
331 'name' can be used to override the defaultly generated Protobufs message name.
332 The body consists only of fields.
333 'options' is a set of keyword/value pairs, both of which are strings.
335 Fields take the form (slot &key type name default reader)
336 'slot' can be either a symbol giving the field name, or a list whose
337 first element is the slot name and whose second element is the index.
338 'type' is the type of the slot.
339 'name' can be used to override the defaultly generated Protobufs field name.
340 'default' is the default value for the slot.
341 'reader' is a Lisp slot reader function to use to get the value, instead of
342 using 'slot-value'; this is often used when aliasing an existing class.
343 'writer' is a Lisp slot writer function to use to set the value."
344 (let* ((name (or name (class-name->proto type)))
345 (options (loop for (key val) on options by #'cddr
346 collect (make-instance 'protobuf-option
347 :name (if (symbolp key) (slot-name->proto key) key)
349 (message (find-message *protobuf* type))
350 (conc-name (or (conc-name-for-type type conc-name)
351 (and message (proto-conc-name message))))
352 (alias-for (and message (proto-alias-for message)))
353 (extends (and message
354 (make-instance 'protobuf-message
355 :class (proto-class message)
356 :name (proto-name message)
357 :qualified-name (proto-qualified-name message)
361 :enums (copy-list (proto-enums message))
362 :messages (copy-list (proto-messages message))
363 :fields (copy-list (proto-fields message))
364 :extensions (copy-list (proto-extensions message))
365 :options (remove-options
366 (or options (copy-list (proto-options message))) "default" "packed")
367 :message-type :extends ;this message is an extension
368 :documentation documentation
369 :type-aliases (copy-list (proto-type-aliases message)))))
370 ;; Only now can we bind *protobuf* to the new extended message
374 "There is no message named ~A to extend" name)
375 (assert (eq type (proto-class message)) ()
376 "The type ~S doesn't match the type of the message being extended ~S"
378 (with-collectors ((forms collect-form))
379 (dolist (field fields)
380 (assert (not (member (car field)
381 '(define-enum define-message define-extend define-extension
382 define-type-alias))) ()
383 "The body of ~S can only contain field and group definitions" 'define-extend)
386 (destructuring-bind (&optional progn model-type model definers extra-field extra-slot)
387 (macroexpand-1 field env)
388 (assert (eq progn 'progn) ()
389 "The macroexpansion for ~S failed" field)
390 (map () #'collect-form definers)
393 (setf (proto-parent model) extends)
394 (setf (proto-messages extends) (nconc (proto-messages extends) (list model)))
396 ;;--- Refactor to get rid of all this duplicated code!
397 (let* ((inits (cdr extra-slot))
398 (sname (car extra-slot))
399 (stable (fintern "~A-VALUES" sname))
400 (stype (getf inits :type))
401 (reader (or (getf inits :accessor)
403 (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
404 *protobuf-package*)))
405 (writer (or (getf inits :writer)
406 (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
407 (default (getf inits :initform)))
408 (collect-form `(without-redefinition-warnings ()
409 (let ((,stable #+ccl (make-hash-table :test #'eq :weak t)
410 #+sbcl (make-hash-table :test #'eq :weakness :value)))
411 ,@(and reader `((defmethod ,reader ((object ,type))
412 (gethash object ,stable ,default))))
413 ,@(and writer `((defmethod ,writer ((object ,type) value)
414 (declare (type ,stype value))
415 (setf (gethash object ,stable) value))))
416 ;; For Python compatibility
417 (defmethod get-extension ((object ,type) (slot (eql ',sname)))
418 (values (gethash object ,stable ,default)))
419 (defmethod set-extension ((object ,type) (slot (eql ',sname)) value)
420 (setf (gethash object ,stable) value))
421 (defmethod has-extension ((object ,type) (slot (eql ',sname)))
422 (multiple-value-bind (value foundp)
423 (gethash object ,stable)
424 (declare (ignore value))
426 (defmethod clear-extension ((object ,type) (slot (eql ',sname)))
427 (remhash object ,stable)))
429 ;; 'defsetf' needs to be visible at compile time
430 `((eval-when (:compile-toplevel :load-toplevel :execute)
431 (defsetf ,reader ,writer))))))))
432 (setf (proto-message-type extra-field) :extends) ;this field is an extension
433 (setf (proto-fields extends) (nconc (proto-fields extends) (list extra-field)))
434 (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list extra-field)))))))
436 (multiple-value-bind (field slot idx)
437 (process-field field index :conc-name conc-name :alias-for alias-for)
438 (assert (not (find-field extends (proto-index field))) ()
439 "The field ~S overlaps with another field in ~S"
440 (proto-value field) (proto-class extends))
441 (assert (index-within-extensions-p idx message) ()
442 "The index ~D is not in range for extending ~S"
443 idx (proto-class message))
446 (let* ((inits (cdr slot))
448 (stable (fintern "~A-VALUES" sname))
449 (stype (getf inits :type))
450 (reader (or (getf inits :accessor)
452 (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
453 *protobuf-package*)))
454 (writer (or (getf inits :writer)
455 (intern (format nil "~A-~A" 'set reader) *protobuf-package*)))
456 (default (getf inits :initform)))
457 ;; For the extended slots, each slot gets its own table
458 ;; keyed by the object, which lets us avoid having a slot in each
459 ;; instance that holds a table keyed by the slot name
460 ;; Multiple 'define-extends' on the same class in the same image
461 ;; will result in harmless redefinitions, so squelch the warnings
462 ;;--- Maybe these methods need to be defined in 'define-message'?
463 (collect-form `(without-redefinition-warnings ()
464 (let ((,stable #+ccl (make-hash-table :test #'eq :weak t)
465 #+sbcl (make-hash-table :test #'eq :weakness :value)))
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 (setf (proto-fields extends) (nconc (proto-fields extends) (list field)))
490 (setf (proto-extended-fields extends) (nconc (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-instance 'protobuf-option
534 :name (if (symbolp key) (slot-name->proto key) key)
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 () (,@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-instance 'protobuf-option
659 :name (slot-name->proto key)
661 (loop for (key val) on options by #'cddr
662 collect (make-instance 'protobuf-option
663 :name (if (symbolp key) (slot-name->proto key) key)
665 (multiple-value-bind (ptype pclass)
666 (clos-type-to-protobuf-type type)
667 (multiple-value-bind (reqd vectorp)
668 (clos-type-to-protobuf-required type)
669 (let* ((default (if (eq reqd :repeated)
670 (if vectorp $empty-vector $empty-list) ;to distinguish between list-of and vector-of
671 (if default-p default $empty-default)))
672 (cslot (unless alias-for
677 `(:accessor ,reader)))
680 :initarg ,(kintern (symbol-name slot))
681 ,@(cond ((eq reqd :repeated)
682 ;; Repeated fields get a container for their elements
684 `(:initform (make-array 5 :fill-pointer 0 :adjustable t))
686 ((and (not default-p)
688 ;; Use unbound for booleans only
689 (not (eq pclass :bool)))
692 `(:initform ,(protobuf-default-to-clos-init default type)))))))
693 (field (make-instance 'protobuf-field
694 :name (or name (slot-name->proto slot))
697 :qualified-name (make-qualified-name *protobuf* (or name (slot-name->proto slot)))
699 ;; One of :required, :optional or :repeated
706 ;; Pack the field only if requested and it actually makes sense
707 :packed (and (eq reqd :repeated) packed t)
709 :documentation documentation)))
710 (values field cslot idx)))))))
712 (defparameter *rpc-package* nil
713 "The Lisp package that implements RPC.
714 This should be set when an RPC package that uses CL-Protobufs gets loaded.")
715 (defparameter *rpc-call-function* nil
716 "The Lisp function that implements RPC client-side calls.
717 This should be set when an RPC package that uses CL-Protobufs gets loaded.")
719 ;; Define a service named 'type' with generic functions declared for
720 ;; each of the methods within the service
721 (defmacro define-service (type (&key name options
722 documentation source-location)
724 "Define a service named 'type' and Lisp 'defgeneric' for all its methods.
725 'name' can be used to override the defaultly generated Protobufs service name.
726 'options' is a set of keyword/value pairs, both of which are strings.
728 The body is a set of method specs of the form (name (input-type [=>] output-type) &key options).
729 'input-type' and 'output-type' may also be of the form (type &key name)."
730 (let* ((name (or name (class-name->proto type)))
731 (options (loop for (key val) on options by #'cddr
732 collect (make-instance 'protobuf-option
733 :name (if (symbolp key) (slot-name->proto key) key)
735 (service (make-instance 'protobuf-service
738 :qualified-name (make-qualified-name *protobuf* name)
741 :documentation documentation
742 :source-location source-location))
744 (with-collectors ((forms collect-form))
745 (dolist (method method-specs)
746 (destructuring-bind (function (&rest types)
747 &key name options documentation source-location) method
748 (let* ((input-type (first types))
749 (output-type (if (string= (string (second types)) "=>") (third types) (second types)))
750 (streams-type (if (string= (string (second types)) "=>")
751 (getf (cdddr types) :streams)
752 (getf (cddr types) :streams)))
753 (input-name (and (listp input-type)
754 (getf (cdr input-type) :name)))
755 (input-type (if (listp input-type) (car input-type) input-type))
756 (output-name (and (listp output-type)
757 (getf (cdr output-type) :name)))
758 (output-type (if (listp output-type) (car output-type) output-type))
759 (streams-name (and (listp streams-type)
760 (getf (cdr streams-type) :name)))
761 (streams-type (if (listp streams-type) (car streams-type) streams-type))
762 (options (loop for (key val) on options by #'cddr
763 collect (make-instance 'protobuf-option
764 :name (if (symbolp key) (slot-name->proto key) key)
766 (package *protobuf-rpc-package*)
767 (client-fn (intern (format nil "~A-~A" 'call function) package))
768 (server-fn (intern (format nil "~A-~A" function 'impl) package))
769 (method (make-instance 'protobuf-method
771 :name (or name (class-name->proto function))
772 :qualified-name (make-qualified-name *protobuf* (or name (class-name->proto function)))
774 :client-stub client-fn
775 :server-stub server-fn
776 :input-type input-type
777 :input-name (or input-name (class-name->proto input-type))
778 :output-type output-type
779 :output-name (or output-name (class-name->proto output-type))
780 :streams-type streams-type
781 :streams-name (and streams-type
782 (or streams-name (class-name->proto streams-type)))
785 :documentation documentation
786 :source-location source-location)))
787 (setf (proto-methods service) (nconc (proto-methods service) (list method)))
788 ;; The following are the hooks to an RPC implementation
789 (let* ((vrequest (intern (symbol-name 'request) package))
790 (vchannel (intern (symbol-name 'channel) package))
791 (vcallback (intern (symbol-name 'callback) package)))
792 ;; The client side stub, e.g., 'read-air-reservation'.
793 ;; The expectation is that the RPC implementation will provide code to make it
794 ;; easy to implement a method for this on each kind of channel (HTTP, TCP socket,
795 ;; IPC, etc). Unlike C++/Java/Python, we don't need a client-side subclass,
796 ;; because we can just use multi-methods.
797 ;; The 'do-XXX' method calls the RPC code with the channel, the method
798 ;; (i.e., a 'protobuf-method' object), the request and the callback function.
799 ;; The RPC code should take care of serializing the input, transmitting the
800 ;; request over the wire, waiting for input (or not if it's asynchronous),
801 ;; filling in the output, and either returning the response (if synchronous)
802 ;; or calling the callback with the response as an argument (if asynchronous).
803 ;; It will also deserialize the response so that the client code sees the
804 ;; response as an application object.
805 (collect-form `(defgeneric ,client-fn (,vchannel ,vrequest &key ,vcallback)
806 ,@(and documentation `((:documentation ,documentation)))
807 #-sbcl (declare (values ,output-type))
808 (:method (,vchannel (,vrequest ,input-type) &key ,vcallback)
809 (declare (ignorable ,vchannel ,vcallback))
810 (let ((call (and *rpc-package* *rpc-call-function*)))
812 "There is no RPC package loaded!")
813 (funcall call ,vchannel ',method ,vrequest
814 :callback ,vcallback)))))
815 ;; The server side stub, e.g., 'do-read-air-reservation'.
816 ;; The expectation is that the server-side program will implement
817 ;; a method with the business logic for this on each kind of channel
818 ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
819 ;; of the input class.
820 ;; The business logic is expected to perform the correct operations on
821 ;; the input object, which arrived via Protobufs, and produce an output
822 ;; of the given type, which will be serialized and sent back over the wire.
823 ;; The channel objects hold client identity information, deadline info,
824 ;; etc, and can be side-effected to indicate success or failure.
825 ;; The RPC code provides the channel classes and does (de)serialization, etc
826 (collect-form `(defgeneric ,server-fn (,vchannel ,vrequest)
827 ,@(and documentation `((:documentation ,documentation)))
828 #-sbcl (declare (values ,output-type))))))))
832 ((with-proto-source-location (,type ,name protobuf-service ,@source-location)
836 ;; Lisp-only type aliases
837 (defmacro define-type-alias (type (&key name alias-for documentation source-location)
838 &key lisp-type proto-type serializer deserializer)
839 "Define a Protobufs type alias Lisp 'deftype' named 'type'.
840 'lisp-type' is the name of the Lisp type.
841 'proto-type' is the name of a primitive Protobufs type, e.g., 'int32' or 'string'.
842 'serializer' is a function that takes a Lisp object and generates a Protobufs object.
843 'deserializer' is a function that takes a Protobufs object and generates a Lisp object.
844 If 'alias-for' is given, no Lisp 'deftype' will be defined."
845 (multiple-value-bind (type-str proto)
846 (lisp-type-to-protobuf-type proto-type)
847 (assert (keywordp proto) ()
848 "The alias ~S must resolve to a Protobufs primitive type"
850 (let* ((name (or name (class-name->proto type)))
851 (alias (make-instance 'protobuf-type-alias
856 :proto-type-str type-str
857 :serializer serializer
858 :deserializer deserializer
859 :qualified-name (make-qualified-name *protobuf* name)
861 :documentation documentation
862 :source-location source-location)))
863 (with-collectors ((forms collect-form))
865 ;; If we've got an alias, define a a type that is the subtype of
866 ;; the Lisp enum so that typep and subtypep work
867 (unless (eq type alias-for)
868 (collect-form `(deftype ,type () ',alias-for)))
869 ;; If no alias, define the Lisp enum type now
870 (collect-form `(deftype ,type () ',lisp-type)))
874 ((with-proto-source-location (,type ,name protobuf-type-alias ,@source-location)
878 ;;; Ensure everything in a Protobufs schema is defined
880 (defvar *undefined-messages*)
882 ;; A very useful tool during development...
883 (defun ensure-all-schemas ()
886 (loop for p being the hash-values of *all-schemas*
888 #'string< :key #'proto-name)))
889 (mapcan #'ensure-schema protos)))
891 (defgeneric ensure-schema (schema)
893 "Ensure that all of the types are defined in the Protobufs schema 'schema'.
894 This returns two values:
895 - A list whose elements are (<undefined-type> \"message:field\" ...)
896 - The accumulated warnings table that has the same information as objects.")
897 (:method ((schema protobuf-schema))
898 (let ((*undefined-messages* (make-hash-table))
899 (trace (list schema)))
900 (map () (curry #'ensure-message trace) (proto-messages schema))
901 (map () (curry #'ensure-service trace) (proto-services schema))
902 (loop for type being the hash-keys of *undefined-messages*
903 using (hash-value things)
905 (mapcar #'(lambda (thing)
906 (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
907 things)) into warnings
908 finally (return (values warnings *undefined-messages*))))))
910 (defgeneric ensure-message (trace message)
911 (:method (trace (message protobuf-message))
912 (let ((trace (cons message trace)))
913 (map () (curry #'ensure-message trace) (proto-messages message))
914 (map () (curry #'ensure-field trace message) (proto-fields message)))))
916 (defgeneric ensure-field (trace message field)
917 (:method (trace message (field protobuf-field))
918 (ensure-type trace message field (proto-class field))))
920 (defgeneric ensure-service (trace service)
921 (:method (trace (service protobuf-service))
922 (map () (curry #'ensure-method trace service) (proto-methods service))))
924 (defgeneric ensure-method (trace service method)
925 (:method (trace service (method protobuf-method))
926 (ensure-type trace service method (proto-input-type method))
927 (ensure-type trace service method (proto-output-type method))
928 (ensure-type trace service method (proto-streams-type method))))
930 ;; 'message' and 'field' can be a message and a field or a service and a method
931 (defun ensure-type (trace message field type)
932 (unless (keywordp type)
933 (let ((msg (loop for p in trace
934 thereis (or (find-message p type)
935 (find-enum p type)))))
937 (push (cons message field) (gethash type *undefined-messages*))))))