1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
3 ;;; Confidential and proprietary information of ITA Software, Inc. ;;;
5 ;;; Copyright (c) 2012 ITA Software, 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-proto (type (&key name syntax package lisp-package import optimize options documentation)
18 &body messages &environment env)
19 "Define a schema named 'type', corresponding to a .proto file of that name.
20 'name' can be used to override the defaultly generated Protobufs name.
21 'syntax' and 'package' are as they would be in a .proto file.
22 'lisp-package' can be used to specify a Lisp package if it is different from
23 the Protobufs package given by 'package'.
24 'import' is a list of pathname strings to be imported.
25 'optimize' can be either :space (the default) or :speed; if it is :speed, the
26 serialization code will be much faster, but much less compact.
27 'options' is a property list, i.e., (\"key1\" \"val1\" \"key2\" \"val2\" ...).
29 The body consists of 'define-enum', 'define-message' or 'define-service' forms."
30 (let* ((name (or name (class-name->proto type)))
31 (package (and package (if (stringp package) package (string-downcase (string package)))))
32 (lisp-pkg (and lisp-package (if (stringp lisp-package) lisp-package (string lisp-package))))
33 (options (loop for (key val) on options by #'cddr
34 collect (make-instance 'protobuf-option
37 (imports (if (listp import) import (list import)))
38 (protobuf (make-instance 'protobuf
41 :syntax (or syntax "proto2")
43 :lisp-package (or lisp-pkg package)
47 :documentation documentation))
49 (*protobuf-package* (or (find-package lisp-pkg)
50 (find-package (string-upcase lisp-pkg))
52 (apply #'process-imports imports)
53 (with-collectors ((forms collect-form))
54 (dolist (msg messages)
55 (assert (and (listp msg)
56 (member (car msg) '(define-enum define-message define-extend define-service))) ()
57 "The body of ~S must be one of ~{~S~^ or ~}"
58 'define-proto '(define-enum define-message define-extend define-service))
59 ;; The macro-expander will return a form that consists
60 ;; of 'progn' followed by a symbol naming what we've expanded
61 ;; (define-enum, define-message, define-extend, define-service),
62 ;; followed by the Lisp model object created by the defining form,
63 ;; followed by other defining forms (e.g., deftype, defclass)
64 (destructuring-bind (&optional progn type model definers)
65 (macroexpand-1 msg env)
66 (assert (eq progn 'progn) ()
67 "The macroexpansion for ~S failed" msg)
68 (map () #'collect-form definers)
71 (setf (proto-enums protobuf) (nconc (proto-enums protobuf) (list model))))
72 ((define-message define-extend)
73 (setf (proto-parent model) protobuf)
74 (setf (proto-messages protobuf) (nconc (proto-messages protobuf) (list model)))
75 (when (proto-extension-p model)
76 (setf (proto-extenders protobuf) (nconc (proto-extenders protobuf) (list model)))))
78 (setf (proto-services protobuf) (nconc (proto-services protobuf) (list model)))))))
79 (let ((var (intern (format nil "*~A*" type) *protobuf-package*)))
83 (let* ((old-proto ,var)
84 (new-proto ,protobuf))
86 (multiple-value-bind (upgradable warnings)
87 (protobuf-upgradable old-proto new-proto)
89 (protobufs-warn "The old schema for ~S (~A) can't be safely upgraded; proceeding anyway"
91 (map () #'protobufs-warn warnings))))
93 ,@(when (eq optimize :speed)
94 (mapcar #'generate-object-size (proto-messages protobuf)))
95 ,@(when (eq optimize :speed)
96 (mapcar #'generate-serializer (proto-messages protobuf)))
97 ,@(when (eq optimize :speed)
98 (mapcar #'generate-deserializer (proto-messages protobuf)))
101 ;; Define an enum type named 'type' and a Lisp 'deftype'
102 (defmacro define-enum (type (&key name conc-name alias-for options documentation)
104 "Define a Protobufs enum type and a Lisp 'deftype' named 'type'.
105 'name' can be used to override the defaultly generated Protobufs enum name.
106 'conc-name' will be used as the prefix to the Lisp enum names, if it's supplied.
107 If 'alias-for' is given, no Lisp 'deftype' will be defined. Instead, the enum
108 will be used as an alias for an enum type that already exists in Lisp.
109 'options' is a set of keyword/value pairs, both of which are strings.
111 The body consists of the enum values in the form 'name' or (name index)."
112 (let* ((name (or name (class-name->proto type)))
113 (options (loop for (key val) on options by #'cddr
114 collect (make-instance 'protobuf-option
118 (enum (make-instance 'protobuf-enum
123 :documentation documentation)))
124 (with-collectors ((vals collect-val)
125 (forms collect-form))
127 (let* ((idx (if (listp val) (second val) (incf index)))
128 (name (if (listp val) (first val) val))
129 (val-name (kintern (if conc-name (format nil "~A~A" conc-name name) (symbol-name name))))
130 (enum-name (if conc-name (format nil "~A~A" conc-name name) (symbol-name name)))
131 (enum-val (make-instance 'protobuf-enum-value
132 :name (enum-name->proto enum-name)
135 (collect-val val-name)
136 (setf (proto-values enum) (nconc (proto-values enum) (list enum-val)))))
138 ;; If we've got an alias, define a a type that is the subtype of
139 ;; the Lisp enum so that typep and subtypep work
140 (unless (eq type alias-for)
141 (collect-form `(deftype ,type () ',alias-for)))
142 ;; If no alias, define the Lisp enum type now
143 (collect-form `(deftype ,type () '(member ,@vals))))
149 ;; Define a message named 'name' and a Lisp 'defclass'
150 (defmacro define-message (type (&key name conc-name alias-for options documentation)
151 &body fields &environment env)
152 "Define a message named 'type' and a Lisp 'defclass'.
153 'name' can be used to override the defaultly generated Protobufs message name.
154 The body consists of fields, or 'define-enum' or 'define-message' forms.
155 'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
156 If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
157 used as an alias for a class that already exists in Lisp. This feature is intended
158 to be used to define messages that will be serialized from existing Lisp classes;
159 unless you get the slot names or readers exactly right for each field, it will be
160 the case that trying to (de)serialize into a Lisp object won't work.
161 'options' is a set of keyword/value pairs, both of which are strings.
163 Fields take the form (slot &key type name default reader)
164 'slot' can be either a symbol giving the field name, or a list whose
165 first element is the slot name and whose second element is the index.
166 'type' is the type of the slot.
167 'name' can be used to override the defaultly generated Protobufs field name.
168 'default' is the default value for the slot.
169 'reader' is a Lisp slot reader function to use to get the value, instead of
170 using 'slot-value'; this is often used when aliasing an existing class.
171 'writer' is a Lisp slot writer function to use to set the value."
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
178 (message (make-instance 'protobuf-message
182 :conc-name (and conc-name (string conc-name))
184 :documentation documentation))
185 (*protobuf* message))
186 (with-collectors ((slots collect-slot)
187 (forms collect-form))
188 (dolist (field fields)
190 ((define-enum define-message define-extend define-extension)
191 (destructuring-bind (&optional progn type model definers)
192 (macroexpand-1 field env)
193 (assert (eq progn 'progn) ()
194 "The macroexpansion for ~S failed" field)
195 (map () #'collect-form definers)
198 (setf (proto-enums message) (nconc (proto-enums message) (list model))))
199 ((define-message define-extend)
200 (setf (proto-parent model) message)
201 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
202 (when (proto-extension-p model)
203 (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
205 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
207 (multiple-value-bind (field slot idx)
208 (process-field field index :conc-name conc-name :alias-for alias-for)
209 (assert (not (find (proto-index field) (proto-fields message) :key #'proto-index)) ()
210 "The field ~S overlaps with another field in ~S"
211 (proto-value field) (proto-class message))
215 (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
217 ;; If we've got an alias, define a a type that is the subtype of
218 ;; the Lisp class that typep and subtypep work
219 (unless (or (eq type alias-for) (find-class type nil))
220 (collect-form `(deftype ,type () ',alias-for)))
221 ;; If no alias, define the class now
222 (collect-form `(defclass ,type () (,@slots)
223 ,@(and documentation `((:documentation ,documentation))))))
229 (defmacro define-extend (type (&key name options documentation)
230 &body fields &environment env)
231 "Define an extension to the message named 'type'.
232 'name' can be used to override the defaultly generated Protobufs message name.
233 The body consists only of fields.
234 'options' is a set of keyword/value pairs, both of which are strings.
236 Fields take the form (slot &key type name default reader)
237 'slot' can be either a symbol giving the field name, or a list whose
238 first element is the slot name and whose second element is the index.
239 'type' is the type of the slot.
240 'name' can be used to override the defaultly generated Protobufs field name.
241 'default' is the default value for the slot.
242 'reader' is a Lisp slot reader function to use to get the value, instead of
243 using 'slot-value'; this is often used when aliasing an existing class.
244 'writer' is a Lisp slot writer function to use to set the value."
245 (declare (ignore env))
246 (let* ((name (or name (class-name->proto type)))
247 (options (loop for (key val) on options by #'cddr
248 collect (make-instance 'protobuf-option
252 (message (find-message *protobuf* name))
253 (conc-name (and message (proto-conc-name message)))
254 (alias-for (and message (proto-alias-for message)))
255 (extends (and message
256 (make-instance 'protobuf-message
259 :parent (proto-parent message)
262 :enums (copy-list (proto-enums message))
263 :messages (copy-list (proto-messages message))
264 :fields (copy-list (proto-fields message))
265 :options (or options (copy-list (proto-options message)))
266 :extension-p t ;this message is an extension
267 :documentation documentation))))
269 "There is no message named ~A to extend" name)
270 (assert (eq type (proto-class message)) ()
271 "The type ~S doesn't match the type of the message being extended ~S"
273 (with-collectors ((forms collect-form))
274 (dolist (field fields)
275 (assert (not (member (car field)
276 '(define-enum define-message define-extend define-extension))) ()
277 "The body of ~S can only contain field definitions" 'define-extend)
278 (multiple-value-bind (field slot idx)
279 (process-field field index :conc-name conc-name :alias-for alias-for)
280 (assert (not (find (proto-index field) (proto-fields extends) :key #'proto-index)) ()
281 "The field ~S overlaps with another field in ~S"
282 (proto-value field) (proto-class extends))
283 (assert (index-within-extensions-p idx message) ()
284 "The index ~D is not in range for extending ~S"
285 idx (proto-class message))
288 (let* ((inits (cdr slot))
290 (stype (getf inits :type))
291 (reader (or (getf inits :accessor)
293 (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
294 (symbol-package sname))))
295 (writer (or (getf inits :writer)
296 (intern (format nil "~A-~A" reader 'setter)
297 (symbol-package sname))))
298 (default (getf inits :initform)))
299 ;;--- Can we avoid having to use a hash table?
300 ;;--- Maybe the table should be in each instance, keyed by slot name?
301 (collect-form `(let ((,sname (make-hash-table :test #'eq :weak t)))
302 (defmethod ,reader ((object ,type))
303 (gethash object ,sname ,default))
304 (defmethod ,writer ((object ,type) value)
305 (declare (type ,stype value))
306 (setf (gethash object ,sname) value))
307 (defsetf ,reader ,writer)))
308 ;; This so that (de)serialization works
309 (setf (proto-reader field) reader
310 (proto-writer field) writer)))
311 (setf (proto-extension-p field) t) ;this field is an extension
312 (setf (proto-fields extends) (nconc (proto-fields extends) (list field)))))
318 (defun process-field (field index &key conc-name alias-for)
319 "Process one field descriptor within 'define-message' or 'define-extend'.
320 Returns a 'proto-field' object, a CLOS slot form and the incremented field index."
321 (when (i= index 18999) ;skip over the restricted range
323 (destructuring-bind (slot &key type (default nil default-p) reader writer name documentation) field
324 (let* ((idx (if (listp slot) (second slot) (iincf index)))
325 (slot (if (listp slot) (first slot) slot))
326 (reqd (clos-type-to-protobuf-required type))
327 (reader (if (eq reader 't)
328 (intern (if conc-name (format nil "~A~A" conc-name slot) (symbol-name slot))
329 (symbol-package slot))
331 (multiple-value-bind (ptype pclass)
332 (clos-type-to-protobuf-type type)
333 (let ((slot (unless alias-for
338 `(:accessor ,reader)))
341 :initarg ,(kintern (symbol-name slot))
342 ,@(cond ((and (not default-p) (eq reqd :repeated))
344 ((and (not default-p) (eq reqd :optional))
347 `(:initform ,default))))))
348 (field (make-instance 'protobuf-field
349 :name (or name (slot-name->proto slot))
357 :default (and default (format nil "~A" default))
358 :packed (and (eq reqd :repeated)
359 (packed-type-p pclass))
360 :documentation documentation)))
361 (values field slot idx))))))
363 (defun index-within-extensions-p (index message)
364 (let ((extensions (proto-extensions message)))
365 (some #'(lambda (ext)
366 (and (i>= index (proto-extension-from ext))
367 (i<= index (proto-extension-to ext))))
370 (defmacro define-extension (from to)
371 "Define an extension range within a message.
372 The \"body\" is the start and end of the range, both inclusive."
375 ,(make-instance 'protobuf-extension
377 :to (if (eql to 'max) #.(1- (ash 1 29)) to))
380 ;; Define a service named 'type' with generic functions declared for
381 ;; each of the methods within the service
382 (defmacro define-service (type (&key name options documentation)
384 "Define a service named 'type' and Lisp 'defgeneric' for all its methods.
385 'name' can be used to override the defaultly generated Protobufs service name.
386 'options' is a set of keyword/value pairs, both of which are strings.
388 The body is a set of method specs of the form (name (input-type output-type) &key options).
389 'input-type' and 'output-type' may also be of the form (type &key name)."
390 (let* ((name (or name (class-name->proto type)))
391 (options (loop for (key val) on options by #'cddr
392 collect (make-instance 'protobuf-option
395 (service (make-instance 'protobuf-service
399 :documentation documentation)))
400 (with-collectors ((forms collect-form))
401 (dolist (method method-specs)
402 (destructuring-bind (function (input-type output-type) &key name options documentation) method
403 (let* ((input-name (and (listp input-type)
404 (getf (cdr input-type) :name)))
405 (input-type (if (listp input-type) (car input-type) input-type))
406 (output-name (and (listp output-type)
407 (getf (cdr output-type) :name)))
408 (output-type (if (listp output-type) (car output-type) output-type))
409 (options (loop for (key val) on options by #'cddr
410 collect (make-instance 'protobuf-option
413 (method (make-instance 'protobuf-method
415 :name (or name (class-name->proto function))
416 :input-type input-type
417 :input-name (or input-name (class-name->proto input-type))
418 :output-type output-type
419 :output-name (or output-name (class-name->proto output-type))
421 :documentation documentation)))
422 (setf (proto-methods service) (nconc (proto-methods service) (list method)))
423 ;; The following are the hooks to CL-Stubby
424 (let* ((package (symbol-package function))
426 (server-fn (intern (format nil "~A-~A" 'do function) package))
427 (vinput (intern (format nil "~A-~A" (symbol-name input-type) 'in) package))
428 (voutput (intern (format nil "~A-~A" (symbol-name output-type) 'out) package))
429 (vchannel (intern (symbol-name 'channel) package))
430 (vcallback (intern (symbol-name 'callback) package)))
431 ;; The client side stub, e.g., 'read-air-reservation'.
432 ;; The expectation is that CL-Stubby will provide macrology to make it
433 ;; easy to implement a method for this on each kind of channel (HTTP, TCP socket,
434 ;; IPC, etc). Unlike C++/Java/Python, we don't need a client-side subclass,
435 ;; because we can just use multi-methods.
436 ;; The CL-Stubby macros take care of serializing the input, transmitting the
437 ;; request over the wire, waiting for input (or not if it's asynchronous),
438 ;; filling in the output, and calling the callback (if it's synchronous).
439 ;; It's not very Lispy to side-effect an output object, but it makes
440 ;; asynchronous calls simpler.
441 (collect-form `(defgeneric ,client-fn (,vchannel ,vinput ,voutput &key ,vcallback)
442 ,@(and documentation `((:documentation ,documentation)))
443 (declare (values ,output-type))))
444 ;; The server side stub, e.g., 'do-read-air-reservation'.
445 ;; The expectation is that the server-side program will implement
446 ;; a method with the business logic for this on each kind of channel
447 ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
448 ;; of the input class
449 ;; The business logic is expected to perform the correct operations on
450 ;; the input object, which arrived via Protobufs, and produce an output
451 ;; of the given type, which will be serialized as a result.
452 ;; The channel objects hold client identity information, deadline info,
453 ;; etc, and can be side-effected to indicate success or failure
454 ;; CL-Stubby provides the channel classes and does (de)serialization, etc
455 (collect-form `(defgeneric ,server-fn (,vchannel ,vinput ,voutput &key ,vcallback)
456 ,@(and documentation `((:documentation ,documentation)))
457 (declare (values ,output-type))))))))
464 ;;; Ensure everything in a Protobufs schema is defined
466 (defvar *undefined-messages*)
468 ;; A very useful tool during development...
469 (defun ensure-all-protobufs ()
472 (loop for p being the hash-values of *all-protobufs*
474 #'string< :key #'proto-name)))
475 (mapcan #'ensure-protobuf protos)))
477 (defmethod ensure-protobuf ((proto protobuf))
478 "Ensure that all of the types are defined in the Protobufs schema 'proto'.
479 This returns two values:
480 - A list whose elements are (<undefined-type> \"message:field\" ...)
481 - The accumulated warnings table that has the same information as objects."
482 (let ((*undefined-messages* (make-hash-table))
483 (trace (list proto)))
484 (map () (curry #'ensure-message trace) (proto-messages proto))
485 (map () (curry #'ensure-service trace) (proto-services proto))
486 (loop for type being the hash-keys of *undefined-messages*
487 using (hash-value things)
489 (mapcar #'(lambda (thing)
490 (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
491 things)) into warnings
492 finally (return (values warnings *undefined-messages*)))))
494 (defmethod ensure-message (trace (message protobuf-message))
495 (let ((trace (cons message trace)))
496 (map () (curry #'ensure-message trace) (proto-messages message))
497 (map () (curry #'ensure-field trace message) (proto-fields message))))
499 (defmethod ensure-field (trace message (field protobuf-field))
500 (ensure-type trace message field (proto-class field)))
502 (defmethod ensure-service (trace (service protobuf-service))
503 (map () (curry #'ensure-method trace service) (proto-methods service)))
505 (defmethod ensure-method (trace service (method protobuf-method))
506 (ensure-type trace service method (proto-input-type method))
507 (ensure-type trace service method (proto-output-type method)))
509 ;; 'message' and 'field' can be a message and a field or a service and a method
510 (defun ensure-type (trace message field type)
511 (unless (keywordp type)
512 (let ((msg (loop for p in trace
513 thereis (or (find-message p type)
514 (find-enum p type)))))
516 (push (cons message field) (gethash type *undefined-messages*))))))