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 (protobuf (make-instance 'protobuf
40 :syntax (or syntax "proto2")
42 :lisp-package (or lisp-pkg package)
43 ;;---*** This needs to parse the imported file(s)
44 :imports (if (listp import) import (list import))
47 :documentation documentation))
49 (*protobuf-package* (or (find-package lisp-pkg)
50 (find-package (string-upcase lisp-pkg)))))
51 (with-collectors ((forms collect-form))
52 (dolist (msg messages)
53 (assert (and (listp msg)
54 (member (car msg) '(define-enum define-message define-extend define-service))) ()
55 "The body of ~S must be one of ~{~S~^ or ~}"
56 'define-proto '(define-enum define-message define-extend define-service))
57 ;; The macro-expander will return a form that consists
58 ;; of 'progn' followed by a symbol naming what we've expanded
59 ;; (define-enum, define-message, define-extend, define-service),
60 ;; followed by the Lisp model object created by the defining form,
61 ;; followed by other defining forms (e.g., deftype, defclass)
62 (destructuring-bind (&optional progn type model definers)
63 (macroexpand-1 msg env)
64 (assert (eq progn 'progn) ()
65 "The macroexpansion for ~S failed" msg)
66 (map () #'collect-form definers)
69 (setf (proto-enums protobuf) (nconc (proto-messages protobuf) (list model))))
70 ((define-message define-extend)
71 (setf (proto-parent model) protobuf)
72 (setf (proto-messages protobuf) (nconc (proto-messages protobuf) (list model)))
73 (when (proto-extension-p model)
74 (setf (proto-extenders protobuf) (nconc (proto-extenders protobuf) (list model)))))
76 (setf (proto-services protobuf) (nconc (proto-services protobuf) (list model)))))))
77 (let ((var (fintern "*~A*" type)))
81 (let* ((old-proto ,var)
82 (new-proto ,protobuf))
84 (multiple-value-bind (upgradable warnings)
85 (protobuf-upgradable old-proto new-proto)
87 (protobufs-warn "The old schema for ~S (~A) can't be safely upgraded; proceeding anyway"
89 (map () #'protobufs-warn warnings))))
92 ,@(when (eq optimize :speed)
93 (mapcar #'generate-object-size (proto-messages protobuf)))
94 ,@(when (eq optimize :speed)
95 (mapcar #'generate-serializer (proto-messages protobuf)))
96 ,@(when (eq optimize :speed)
97 (mapcar #'generate-deserializer (proto-messages protobuf))) )
100 ;; Define an enum type named 'type' and a Lisp 'deftype'
101 (defmacro define-enum (type (&key name conc-name alias-for options documentation)
103 "Define a Protobufs enum type and a Lisp 'deftype' named 'type'.
104 'name' can be used to override the defaultly generated Protobufs enum name.
105 'conc-name' will be used as the prefix to the Lisp enum names, if it's supplied.
106 If 'alias-for' is given, no Lisp 'deftype' will be defined. Instead, the enum
107 will be used as an alias for an enum type that already exists in Lisp.
108 'options' is a set of keyword/value pairs, both of which are strings.
110 The body consists of the enum values in the form 'name' or (name index)."
111 (let* ((name (or name (class-name->proto type)))
112 (options (loop for (key val) on options by #'cddr
113 collect (make-instance 'protobuf-option
117 (enum (make-instance 'protobuf-enum
122 :documentation documentation)))
123 (with-collectors ((vals collect-val)
124 (forms collect-form))
126 (let* ((idx (if (listp val) (second val) (incf index)))
127 (name (if (listp val) (first val) val))
128 (val-name (kintern (if conc-name (format nil "~A~A" conc-name name) (symbol-name name))))
129 (enum-name (if conc-name (format nil "~A~A" conc-name name) (symbol-name name)))
130 (enum-val (make-instance 'protobuf-enum-value
131 :name (enum-name->proto enum-name)
134 (collect-val val-name)
135 (setf (proto-values enum) (nconc (proto-values enum) (list enum-val)))))
137 ;; If we've got an alias, define a a type that is the subtype of
138 ;; the Lisp enum so that typep and subtypep work
139 (unless (eq type alias-for)
140 (collect-form `(deftype ,type () ',alias-for)))
141 ;; If no alias, define the Lisp enum type now
142 (collect-form `(deftype ,type () '(member ,@vals))))
148 ;; Define a message named 'name' and a Lisp 'defclass'
149 (defmacro define-message (type (&key name conc-name alias-for options documentation)
150 &body fields &environment env)
151 "Define a message named 'type' and a Lisp 'defclass'.
152 'name' can be used to override the defaultly generated Protobufs message name.
153 The body consists of fields, or 'define-enum' or 'define-message' forms.
154 'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
155 If 'alias-for' is given, no Lisp class is defined. Instead, the message will be
156 used as an alias for a class that already exists in Lisp. This feature is intended
157 to be used to define messages that will be serialized from existing Lisp classes;
158 unless you get the slot names or readers exactly right for each field, it will be
159 the case that trying to (de)serialize into a Lisp object won't work.
160 'options' is a set of keyword/value pairs, both of which are strings.
162 Fields take the form (slot &key type name default reader)
163 'slot' can be either a symbol giving the field name, or a list whose
164 first element is the slot name and whose second element is the index.
165 'type' is the type of the slot.
166 'name' can be used to override the defaultly generated Protobufs field name.
167 'default' is the default value for the slot.
168 'reader' is a Lisp slot reader function to use to get the value, instead of
169 using 'slot-value'; this is often used when aliasing an existing class.
170 'writer' is a Lisp slot writer function to use to set the value."
171 (let* ((name (or name (class-name->proto type)))
172 (options (loop for (key val) on options by #'cddr
173 collect (make-instance 'protobuf-option
177 (message (make-instance 'protobuf-message
181 :conc-name (and conc-name (string conc-name))
183 :documentation documentation))
184 (*protobuf* message))
185 (with-collectors ((slots collect-slot)
186 (forms collect-form))
187 (dolist (field fields)
189 ((define-enum define-message define-extend define-extension)
190 (destructuring-bind (&optional progn type model definers)
191 (macroexpand-1 field env)
192 (assert (eq progn 'progn) ()
193 "The macroexpansion for ~S failed" field)
194 (map () #'collect-form definers)
197 (setf (proto-enums message) (nconc (proto-messages message) (list model))))
198 ((define-message define-extend)
199 (setf (proto-parent model) message)
200 (setf (proto-messages message) (nconc (proto-messages message) (list model)))
201 (when (proto-extension-p model)
202 (setf (proto-extenders message) (nconc (proto-extenders message) (list model)))))
204 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
206 (multiple-value-bind (field slot idx)
207 (process-field field index :conc-name conc-name :alias-for alias-for)
208 (assert (not (find (proto-index field) (proto-fields message) :key #'proto-index)) ()
209 "The field ~S overlaps with another field in ~S"
210 (proto-value field) (proto-class message))
214 (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
216 ;; If we've got an alias, define a a type that is the subtype of
217 ;; the Lisp class that typep and subtypep work
218 (unless (or (eq type alias-for) (find-class type nil))
219 (collect-form `(deftype ,type () ',alias-for)))
220 ;; If no alias, define the class now
221 (collect-form `(defclass ,type () (,@slots)
222 ,@(and documentation `((:documentation ,documentation))))))
228 (defmacro define-extend (type (&key name options documentation)
229 &body fields &environment env)
230 "Define an extension to the message named 'type'.
231 'name' can be used to override the defaultly generated Protobufs message name.
232 The body consists only of fields.
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 (declare (ignore env))
245 (let* ((name (or name (class-name->proto type)))
246 (options (loop for (key val) on options by #'cddr
247 collect (make-instance 'protobuf-option
251 (message (find-message *protobuf* name))
252 (conc-name (and message (proto-conc-name message)))
253 (alias-for (and message (proto-alias-for message)))
254 (extends (and message
255 (make-instance 'protobuf-message
258 :parent (proto-parent message)
261 :enums (copy-list (proto-enums message))
262 :messages (copy-list (proto-messages message))
263 :fields (copy-list (proto-fields message))
264 :options (or options (copy-list (proto-options message)))
265 :extension-p t ;this message is an extension
266 :documentation documentation))))
268 "There is no message named ~A to extend" name)
269 (assert (eq type (proto-class message)) ()
270 "The type ~S doesn't match the type of the message being extended ~S"
272 (with-collectors ((forms collect-form))
273 (dolist (field fields)
274 (assert (not (member (car field)
275 '(define-enum define-message define-extend define-extension))) ()
276 "The body of ~S can only contain field definitions" 'define-extend)
277 (multiple-value-bind (field slot idx)
278 (process-field field index :conc-name conc-name :alias-for alias-for)
279 (assert (not (find (proto-index field) (proto-fields extends) :key #'proto-index)) ()
280 "The field ~S overlaps with another field in ~S"
281 (proto-value field) (proto-class extends))
282 (assert (index-within-extensions-p idx message) ()
283 "The index ~D is not in range for extending ~S"
284 idx (proto-class message))
287 (let* ((inits (cdr slot))
289 (stype (getf inits :type))
290 (reader (or (getf inits :accessor)
292 (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
293 (symbol-package sname))))
294 (writer (or (getf inits :writer)
295 (intern (format nil "~A-~A" reader 'setter)
296 (symbol-package sname))))
297 (default (getf inits :initform)))
298 ;;--- Can we avoid having to use a hash table?
299 ;;--- Maybe the table should be in each instance, keyed by slot name?
300 (collect-form `(let ((,sname (make-hash-table :test #'eq :weak t)))
301 (defmethod ,reader ((object ,type))
302 (gethash object ,sname ,default))
303 (defmethod ,writer ((object ,type) value)
304 (declare (type ,stype value))
305 (setf (gethash object ,sname) value))
306 (defsetf ,reader ,writer)))
307 ;; This so that (de)serialization works
308 (setf (proto-reader field) reader
309 (proto-writer field) writer)))
310 (setf (proto-extension-p field) t) ;this field is an extension
311 (setf (proto-fields extends) (nconc (proto-fields extends) (list field)))))
317 (defun process-field (field index &key conc-name alias-for)
318 "Process one field descriptor within 'define-message' or 'define-extend'.
319 Returns a 'proto-field' object, a CLOS slot form and the incremented field index."
320 (when (i= index 18999) ;skip over the restricted range
322 (destructuring-bind (slot &key type (default nil default-p) reader writer name documentation) field
323 (let* ((idx (if (listp slot) (second slot) (iincf index)))
324 (slot (if (listp slot) (first slot) slot))
325 (reqd (clos-type-to-protobuf-required type))
326 (reader (if (eq reader 't)
327 (intern (if conc-name (format nil "~A~A" conc-name slot) (symbol-name slot))
328 (symbol-package slot))
330 (multiple-value-bind (ptype pclass)
331 (clos-type-to-protobuf-type type)
332 (let ((slot (unless alias-for
337 `(:accessor ,reader)))
340 :initarg ,(kintern (symbol-name slot))
341 ,@(cond ((and (not default-p) (eq reqd :repeated))
343 ((and (not default-p) (eq reqd :optional))
346 `(:initform ,default))))))
347 (field (make-instance 'protobuf-field
348 :name (or name (slot-name->proto slot))
356 :default (and default (format nil "~A" default))
357 :packed (and (eq reqd :repeated)
358 (packed-type-p pclass))
359 :documentation documentation)))
360 (values field slot idx))))))
362 (defun index-within-extensions-p (index message)
363 (let ((extensions (proto-extensions message)))
364 (some #'(lambda (ext)
365 (and (i>= index (proto-extension-from ext))
366 (i<= index (proto-extension-to ext))))
369 (defmacro define-extension (from to)
370 "Define an extension range within a message.
371 The \"body\" is the start and end of the range, both inclusive."
374 ,(make-instance 'protobuf-extension
376 :to (if (eql to 'max) #.(1- (ash 1 29)) to))
379 ;; Define a service named 'type' with generic functions declared for
380 ;; each of the methods within the service
381 (defmacro define-service (type (&key name options documentation)
383 "Define a service named 'type' and Lisp 'defgeneric' for all its methods.
384 'name' can be used to override the defaultly generated Protobufs service name.
385 'options' is a set of keyword/value pairs, both of which are strings.
387 The body is a set of method specs of the form (name (input-type output-type) &key options).
388 'input-type' and 'output-type' may also be of the form (type &key name)."
389 (let* ((name (or name (class-name->proto type)))
390 (options (loop for (key val) on options by #'cddr
391 collect (make-instance 'protobuf-option
394 (service (make-instance 'protobuf-service
398 :documentation documentation)))
399 (with-collectors ((forms collect-form))
400 (dolist (method method-specs)
401 (destructuring-bind (function (input-type output-type) &key name options documentation) method
402 (let* ((input-name (and (listp input-type)
403 (getf (cdr input-type) :name)))
404 (input-type (if (listp input-type) (car input-type) input-type))
405 (output-name (and (listp output-type)
406 (getf (cdr output-type) :name)))
407 (output-type (if (listp output-type) (car output-type) output-type))
408 (options (loop for (key val) on options by #'cddr
409 collect (make-instance 'protobuf-option
412 (method (make-instance 'protobuf-method
414 :name (or name (class-name->proto function))
415 :input-type input-type
416 :input-name (or input-name (class-name->proto input-type))
417 :output-type output-type
418 :output-name (or output-name (class-name->proto output-type))
420 :documentation documentation)))
421 (setf (proto-methods service) (nconc (proto-methods service) (list method)))
422 ;; The following are the hooks to CL-Stubby
423 (let* ((package (symbol-package function))
425 (server-fn (intern (format nil "~A-~A" 'do function) package))
426 (vinput (intern (format nil "~A-~A" (symbol-name input-type) 'in) package))
427 (voutput (intern (format nil "~A-~A" (symbol-name output-type) 'out) package))
428 (vchannel (intern (symbol-name 'channel) package))
429 (vcallback (intern (symbol-name 'callback) package)))
430 ;; The client side stub, e.g., 'read-air-reservation'.
431 ;; The expectation is that CL-Stubby will provide macrology to make it
432 ;; easy to implement a method for this on each kind of channel (HTTP, TCP socket,
433 ;; IPC, etc). Unlike C++/Java/Python, we don't need a client-side subclass,
434 ;; because we can just use multi-methods.
435 ;; The CL-Stubby macros take care of serializing the input, transmitting the
436 ;; request over the wire, waiting for input (or not if it's asynchronous),
437 ;; filling in the output, and calling the callback (if it's synchronous).
438 ;; It's not very Lispy to side-effect an output object, but it makes
439 ;; asynchronous calls simpler.
440 (collect-form `(defgeneric ,client-fn (,vchannel ,vinput ,voutput &key ,vcallback)
441 ,@(and documentation `((:documentation ,documentation)))
442 (declare (values ,output-type))))
443 ;; The server side stub, e.g., 'do-read-air-reservation'.
444 ;; The expectation is that the server-side program will implement
445 ;; a method with the business logic for this on each kind of channel
446 ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
447 ;; of the input class
448 ;; The business logic is expected to perform the correct operations on
449 ;; the input object, which arrived via Protobufs, and produce an output
450 ;; of the given type, which will be serialized as a result.
451 ;; The channel objects hold client identity information, deadline info,
452 ;; etc, and can be side-effected to indicate success or failure
453 ;; CL-Stubby provides the channel classes and does (de)serialization, etc
454 (collect-form `(defgeneric ,server-fn (,vchannel ,vinput ,voutput &key ,vcallback)
455 ,@(and documentation `((:documentation ,documentation)))
456 (declare (values ,output-type))))))))
463 ;;; Ensure everything in a Protobufs schema is defined
465 (defvar *undefined-messages*)
467 ;; A very useful tool during development...
468 (defun ensure-all-protobufs ()
471 (loop for p being the hash-values of *all-protobufs*
473 #'string< :key #'proto-name)))
474 (mapcan #'ensure-protobuf protos)))
476 (defmethod ensure-protobuf ((proto protobuf))
477 "Ensure that all of the types are defined in the Protobufs schema 'proto'.
478 This returns two values:
479 - A list whose elements are (<undefined-type> \"message:field\" ...)
480 - The accumulated warnings table that has the same information as objects."
481 (let ((*undefined-messages* (make-hash-table))
482 (trace (list proto)))
483 (map () (curry #'ensure-message trace) (proto-messages proto))
484 (map () (curry #'ensure-service trace) (proto-services proto))
485 (loop for type being the hash-keys of *undefined-messages*
486 using (hash-value things)
488 (mapcar #'(lambda (thing)
489 (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
490 things)) into warnings
491 finally (return (values warnings *undefined-messages*)))))
493 (defmethod ensure-message (trace (message protobuf-message))
494 (let ((trace (cons message trace)))
495 (map () (curry #'ensure-message trace) (proto-messages message))
496 (map () (curry #'ensure-field trace message) (proto-fields message))))
498 (defmethod ensure-field (trace message (field protobuf-field))
499 (ensure-type trace message field (proto-class field)))
501 (defmethod ensure-service (trace (service protobuf-service))
502 (map () (curry #'ensure-method trace service) (proto-methods service)))
504 (defmethod ensure-method (trace service (method protobuf-method))
505 (ensure-type trace service method (proto-input-type method))
506 (ensure-type trace service method (proto-output-type method)))
508 ;; 'message' and 'field' can be a message and a field or a service and a method
509 (defun ensure-type (trace message field type)
510 (unless (keywordp type)
511 (let ((msg (loop for p in trace
512 thereis (or (find-message p type)
513 (find-enum p type)))))
515 (push (cons message field) (gethash type *undefined-messages*))))))