]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - define-proto.lisp
Make the CLOS->Proto conversion a bit smarter
[cl-protobufs.git] / define-proto.lisp
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;;                                                                  ;;;
3 ;;; Confidential and proprietary information of ITA Software, Inc.   ;;;
4 ;;;                                                                  ;;;
5 ;;; Copyright (c) 2012 ITA Software, Inc.  All rights reserved.      ;;;
6 ;;;                                                                  ;;;
7 ;;; Original author: Scott McKay                                     ;;;
8 ;;;                                                                  ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
10
11 (in-package "PROTO-IMPL")
12
13
14 ;;; Protocol buffer defining macros
15
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\" ...).
28
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
35                                    :name  key
36                                    :value val)))
37          (imports  (if (listp import) import (list import)))
38          (protobuf (make-instance 'protobuf
39                      :class    type
40                      :name     name
41                      :syntax   (or syntax "proto2")
42                      :package  package
43                      :lisp-package (or lisp-pkg package)
44                      :imports  imports
45                      :options  options
46                      :optimize optimize
47                      :documentation documentation))
48          (*protobuf* protobuf)
49          (*protobuf-package* (or (find-package lisp-pkg)
50                                  (find-package (string-upcase lisp-pkg)))))
51     (apply #'process-imports imports)
52     (with-collectors ((forms collect-form))
53       (dolist (msg messages)
54         (assert (and (listp msg)
55                      (member (car msg) '(define-enum define-message define-extend define-service))) ()
56                 "The body of ~S must be one of ~{~S~^ or ~}"
57                 'define-proto '(define-enum define-message define-extend define-service))
58         ;; The macro-expander will return a form that consists
59         ;; of 'progn' followed by a symbol naming what we've expanded
60         ;; (define-enum, define-message, define-extend, define-service),
61         ;; followed by the Lisp model object created by the defining form,
62         ;; followed by other defining forms (e.g., deftype, defclass)
63         (destructuring-bind (&optional progn type model definers)
64             (macroexpand-1 msg env)
65           (assert (eq progn 'progn) ()
66                   "The macroexpansion for ~S failed" msg)
67           (map () #'collect-form definers)
68           (ecase type
69             ((define-enum)
70              (setf (proto-enums protobuf) (nconc (proto-enums protobuf) (list model))))
71             ((define-message define-extend)
72              (setf (proto-parent model) protobuf)
73              (setf (proto-messages protobuf) (nconc (proto-messages protobuf) (list model)))
74              (when (proto-extension-p model)
75                (setf (proto-extenders protobuf) (nconc (proto-extenders protobuf) (list model)))))
76             ((define-service)
77              (setf (proto-services protobuf) (nconc (proto-services protobuf) (list model)))))))
78       (let ((var (fintern "*~A*" type)))
79         `(progn
80            ,@forms
81            (defvar ,var nil)
82            (let* ((old-proto ,var)
83                   (new-proto ,protobuf))
84              (when old-proto
85                (multiple-value-bind (upgradable warnings)
86                    (protobuf-upgradable old-proto new-proto)
87                  (unless upgradable
88                    (protobufs-warn "The old schema for ~S (~A) can't be safely upgraded; proceeding anyway"
89                                    ',type ',name)
90                    (map () #'protobufs-warn warnings))))
91              (setq ,var new-proto)
92              #+++ignore (
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))) )
99              new-proto))))))
100
101 ;; Define an enum type named 'type' and a Lisp 'deftype'
102 (defmacro define-enum (type (&key name conc-name alias-for options documentation)
103                        &body values)
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.
110
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
115                                   :name  key
116                                   :value val)))
117          (index 0)
118          (enum  (make-instance 'protobuf-enum
119                   :class  type
120                   :name   name
121                   :alias-for alias-for
122                   :options options
123                   :documentation documentation)))
124     (with-collectors ((vals  collect-val)
125                       (forms collect-form))
126       (dolist (val values)
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)
133                             :index idx
134                             :value val-name)))
135           (collect-val val-name)
136           (setf (proto-values enum) (nconc (proto-values enum) (list enum-val)))))
137       (if alias-for
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))))
144       `(progn
145          define-enum
146          ,enum
147          ,forms))))
148
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.
162
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
175                                   :name  key
176                                   :value val)))
177          (index   0)
178          (message (make-instance 'protobuf-message
179                     :class type
180                     :name  name
181                     :alias-for alias-for
182                     :conc-name (and conc-name (string conc-name))
183                     :options  options
184                     :documentation documentation))
185          (*protobuf* message))
186     (with-collectors ((slots collect-slot)
187                       (forms collect-form))
188       (dolist (field fields)
189         (case (car field)
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)
196              (ecase type
197                ((define-enum)
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)))))
204                ((define-extension)
205                 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
206           (otherwise
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))
212              (setq index idx)
213              (when slot
214                (collect-slot slot))
215              (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
216       (if alias-for
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))))))
224       `(progn
225          define-message
226          ,message
227          ,forms))))
228
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.
235
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
249                                   :name  key
250                                   :value val)))
251          (index   0)
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
257                          :class  type
258                          :name   name
259                          :parent (proto-parent message)
260                          :conc-name conc-name
261                          :alias-for alias-for
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))))
268     (assert message ()
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"
272             type message)
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))
286           (setq index idx)
287           (when slot
288             (let* ((inits (cdr slot))
289                    (sname (car slot))
290                    (stype (getf inits :type))
291                    (reader (or (getf inits :accessor)
292                                (getf inits :reader)
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)))))
313       `(progn
314          define-extend
315          ,extends
316          ,forms))))
317
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
322     (setq index 19999))
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))
330                      reader)))
331       (multiple-value-bind (ptype pclass)
332           (clos-type-to-protobuf-type type)
333         (let ((slot (unless alias-for
334                       `(,slot :type ,type
335                               ,@(and reader
336                                      (if writer
337                                        `(:reader ,reader)
338                                        `(:accessor ,reader)))
339                               ,@(and writer
340                                      `(:writer ,writer))
341                               :initarg ,(kintern (symbol-name slot))
342                               ,@(cond ((and (not default-p) (eq reqd :repeated))
343                                        `(:initform ()))
344                                       ((and (not default-p) (eq reqd :optional))
345                                        `(:initform nil))
346                                       (default-p
347                                         `(:initform ,default))))))
348               (field (make-instance 'protobuf-field
349                        :name  (or name (slot-name->proto slot))
350                        :type  ptype
351                        :class pclass
352                        :required reqd
353                        :index  idx
354                        :value  slot
355                        :reader reader
356                        :writer writer
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))))))
362
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))))
368           extensions)))
369
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."
373   `(progn
374      define-extension
375      ,(make-instance 'protobuf-extension
376         :from from
377         :to   (if (eql to 'max) #.(1- (ash 1 29)) to))
378      ()))
379
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)
383                           &body method-specs)
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.
387
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
393                                   :name  key
394                                   :value val)))
395          (service (make-instance 'protobuf-service
396                     :class type
397                     :name  name
398                     :options options
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
411                                           :name  key
412                                           :value val)))
413                  (method  (make-instance 'protobuf-method
414                             :class function
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))
420                             :options options
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))
425                    (client-fn 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))))))))
458       `(progn
459          define-service
460          ,service
461          ,forms))))
462
463 \f
464 ;;; Ensure everything in a Protobufs schema is defined
465
466 (defvar *undefined-messages*)
467
468 ;; A very useful tool during development...
469 (defun ensure-all-protobufs ()
470   (let ((protos (sort
471                  (delete-duplicates
472                   (loop for p being the hash-values of *all-protobufs*
473                         collect p))
474                  #'string< :key #'proto-name)))
475     (mapcan #'ensure-protobuf protos)))
476
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)
488           collect (list* type
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*)))))
493
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))))
498
499 (defmethod ensure-field (trace message (field protobuf-field))
500   (ensure-type trace message field (proto-class field)))
501
502 (defmethod ensure-service (trace (service protobuf-service))
503   (map () (curry #'ensure-method trace service) (proto-methods service)))
504
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)))
508
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)))))
515       (unless msg
516         (push (cons message field) (gethash type *undefined-messages*))))))