]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - define-proto.lisp
Fully implement 'extends'
[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          (protobuf (make-instance 'protobuf
38                      :class    type
39                      :name     name
40                      :syntax   (or syntax "proto2")
41                      :package  package
42                      :lisp-package (or lisp-pkg package)
43                      ;;---*** This needs to parse the imported file(s)
44                      :imports  (if (listp import) import (list import))
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     (with-collectors ((forms collect-form))
52       (dolist (msg messages)
53         (assert (and (listp msg)
54                      (member (car msg) '(define-enum define-message define-extends define-service))) ()
55                 "The body of ~S must be one of ~{~S~^ or ~}"
56                 'define-proto '(define-enum define-message define-extends 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-extends, 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)
67           (ecase type
68             ((define-enum)
69              (setf (proto-enums protobuf) (nconc (proto-messages protobuf) (list model))))
70             ((define-message define-extends)
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)))))
75             ((define-service)
76              (setf (proto-services protobuf) (nconc (proto-services protobuf) (list model)))))))
77       (let ((var (fintern "*~A*" type)))
78         `(progn
79            ,@forms
80            (defvar ,var nil)
81            (let* ((old-proto ,var)
82                   (new-proto ,protobuf))
83              (when old-proto
84                (multiple-value-bind (upgradable warnings)
85                    (protobuf-upgradable old-proto new-proto)
86                  (unless upgradable
87                    (protobufs-warn "The old schema for ~S (~A) can't be safely upgraded; proceeding anyway"
88                                    ',type ',name)
89                    (map () #'protobufs-warn warnings))))
90              (setq ,var new-proto)
91              #+++ignore (
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))) )
98              new-proto))))))
99
100 ;; Define an enum type named 'type' and a Lisp 'deftype'
101 (defmacro define-enum (type (&key name conc-name alias-for options documentation)
102                        &body values)
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.
109
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
114                                   :name  key
115                                   :value val)))
116          (index 0)
117          (enum  (make-instance 'protobuf-enum
118                   :class  type
119                   :name   name
120                   :alias-for alias-for
121                   :options options
122                   :documentation documentation)))
123     (with-collectors ((vals  collect-val)
124                       (forms collect-form))
125       (dolist (val values)
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)
132                             :index idx
133                             :value val-name)))
134           (collect-val val-name)
135           (setf (proto-values enum) (nconc (proto-values enum) (list enum-val)))))
136       (if alias-for
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))))
143       `(progn
144          define-enum
145          ,enum
146          ,forms))))
147
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.
161
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
174                                   :name  key
175                                   :value val)))
176          (index   0)
177          (message (make-instance 'protobuf-message
178                     :class type
179                     :name  name
180                     :alias-for alias-for
181                     :conc-name (and conc-name (string conc-name))
182                     :options  options
183                     :documentation documentation))
184          (*protobuf* message))
185     (with-collectors ((slots collect-slot)
186                       (forms collect-form))
187       (dolist (field fields)
188         (case (car field)
189           ((define-enum define-message define-extends 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)
195              (ecase type
196                ((define-enum)
197                 (setf (proto-enums message) (nconc (proto-messages message) (list model))))
198                ((define-message define-extends)
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)))))
203                ((define-extension)
204                 (setf (proto-extensions message) (nconc (proto-extensions message) (list model)))))))
205           (otherwise
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))
211              (when slot
212                (collect-slot slot))
213              (setf (proto-fields message) (nconc (proto-fields message) (list field)))
214              (setq index idx)))))
215       (if alias-for
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))))))
223       `(progn
224          define-message
225          ,message
226          ,forms))))
227
228 (defmacro define-extends (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.
234
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
248                                   :name  key
249                                   :value val)))
250          (index   0)
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
256                          :class  type
257                          :name   name
258                          :parent (proto-parent message)
259                          :conc-name conc-name
260                          :alias-for alias-for
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))))
267     (assert message ()
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"
271             type message)
272     (with-collectors ((forms collect-form))
273       (dolist (field fields)
274         (assert (not (member (car field)
275                              '(define-enum define-message define-extends define-extension))) ()
276                 "The body of ~S can only contain field definitions" 'define-extends)
277         (multiple-value-bind (field slot idx)
278             (process-field field index :conc-name conc-name :alias-for alias-for)
279           ;;--- Make sure extension field's index is allowable within 'proto-extensions'
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           (when slot
284             (let* ((inits (cdr slot))
285                    (sname (car slot))
286                    (stype (getf inits :type))
287                    (reader (or (getf inits :accessor)
288                                (getf inits :reader)
289                                (intern (if conc-name (format nil "~A~A" conc-name sname) (symbol-name sname))
290                                        (symbol-package sname))))
291                    (writer (or (getf inits :writer) `(setf ,reader)))
292                    (default (getf inits :initform)))
293               ;;--- Can we avoid having to use a hash table?
294               (collect-form `(let ((,sname (make-hash-table :test #'eq :weak t)))
295                                (defmethod ,reader ((object ,type))
296                                  (gethash object ,sname ,default))
297                                (defmethod ,writer (value (object ,type))
298                                  (declare (type ,stype value))
299                                  (setf (gethash object ,sname) value))))
300               ;; This so that (de)serialization works
301               (setf (proto-reader field) reader
302                     (proto-writer field) writer)))
303           (setf (proto-extension-p field) t)            ;this field is an extension
304           (setf (proto-fields extends) (nconc (proto-fields extends) (list field)))
305           (setq index idx)))
306       `(progn
307          define-extends
308          ,extends
309          ,forms))))
310
311 (defun process-field (field index &key conc-name alias-for)
312   "Process one field descriptor within 'define-message' or 'define-extends'.
313    Returns a 'proto-field' object, a CLOS slot form and the incremented field index."
314   (when (i= index 18999)                                ;skip over the restricted range
315     (setq index 19999))
316   (destructuring-bind (slot &key type (default nil default-p) reader writer name documentation) field
317     (let* ((idx  (if (listp slot) (second slot) (iincf index)))
318            (slot (if (listp slot) (first slot) slot))
319            (reqd (clos-type-to-protobuf-required type))
320            (reader (if (eq reader 't)
321                      (intern (if conc-name (format nil "~A~A" conc-name slot) (symbol-name slot))
322                              (symbol-package slot))
323                      reader)))
324       (multiple-value-bind (ptype pclass)
325           (clos-type-to-protobuf-type type)
326         (let ((slot (unless alias-for
327                       `(,slot :type ,type
328                               ,@(and reader
329                                      (if writer
330                                        `(:reader ,reader)
331                                        `(:accessor ,reader)))
332                               ,@(and writer
333                                      `(:writer ,writer))
334                               :initarg ,(kintern (symbol-name slot))
335                               ,@(cond ((and (not default-p) (eq reqd :repeated))
336                                        `(:initform ()))
337                                       ((and (not default-p) (eq reqd :optional))
338                                        `(:initform nil))
339                                       (default-p
340                                         `(:initform ,default))))))
341               (field (make-instance 'protobuf-field
342                        :name  (or name (slot-name->proto slot))
343                        :type  ptype
344                        :class pclass
345                        :required reqd
346                        :index  idx
347                        :value  slot
348                        :reader reader
349                        :writer writer
350                        :default (and default (format nil "~A" default))
351                        :packed  (and (eq reqd :repeated)
352                                      (packed-type-p pclass))
353                        :documentation documentation)))
354           (values field slot index))))))
355
356 (defmacro define-extension (from to)
357   "Define an extension range within a message.
358    The \"body\" is the start and end of the range, both inclusive."
359   `(progn
360      define-extension
361      ,(make-instance 'protobuf-extension
362         :from from
363         :to   (if (eql to 'max) #.(1- (ash 1 29)) to))
364      ()))
365
366 ;; Define a service named 'type' with generic functions declared for
367 ;; each of the methods within the service
368 (defmacro define-service (type (&key name options documentation)
369                           &body method-specs)
370   "Define a service named 'type' and Lisp 'defgeneric' for all its methods.
371    'name' can be used to override the defaultly generated Protobufs service name.
372    'options' is a set of keyword/value pairs, both of which are strings.
373
374    The body is a set of method specs of the form (name (input-type output-type) &key options).
375    'input-type' and 'output-type' may also be of the form (type &key name)."
376   (let* ((name    (or name (class-name->proto type)))
377          (options (loop for (key val) on options by #'cddr
378                         collect (make-instance 'protobuf-option
379                                   :name  key
380                                   :value val)))
381          (service (make-instance 'protobuf-service
382                     :class type
383                     :name  name
384                     :options options
385                     :documentation documentation)))
386     (with-collectors ((forms collect-form))
387       (dolist (method method-specs)
388         (destructuring-bind (function (input-type output-type) &key name options documentation) method
389           (let* ((input-name (and (listp input-type)
390                                   (getf (cdr input-type) :name)))
391                  (input-type (if (listp input-type) (car input-type) input-type))
392                  (output-name (and (listp output-type)
393                                    (getf (cdr output-type) :name)))
394                  (output-type (if (listp output-type) (car output-type) output-type))
395                  (options (loop for (key val) on options by #'cddr
396                                 collect (make-instance 'protobuf-option
397                                           :name  key
398                                           :value val)))
399                  (method  (make-instance 'protobuf-method
400                             :class function
401                             :name  (or name (class-name->proto function))
402                             :input-type  input-type
403                             :input-name  (or input-name (class-name->proto input-type))
404                             :output-type output-type
405                             :output-name (or output-name (class-name->proto output-type))
406                             :options options
407                             :documentation documentation)))
408             (setf (proto-methods service) (nconc (proto-methods service) (list method)))
409             ;; The following are the hooks to CL-Stubby
410             (let* ((package   (symbol-package function))
411                    (client-fn function)
412                    (server-fn (intern (format nil "~A-~A" 'do function) package))
413                    (vinput    (intern (format nil "~A-~A" (symbol-name input-type) 'in) package))
414                    (voutput   (intern (format nil "~A-~A" (symbol-name output-type) 'out) package))
415                    (vchannel  (intern (symbol-name 'channel) package))
416                    (vcallback (intern (symbol-name 'callback) package)))
417               ;; The client side stub, e.g., 'read-air-reservation'.
418               ;; The expectation is that CL-Stubby will provide macrology to make it
419               ;; easy to implement a method for this on each kind of channel (HTTP, TCP socket,
420               ;; IPC, etc). Unlike C++/Java/Python, we don't need a client-side subclass,
421               ;; because we can just use multi-methods.
422               ;; The CL-Stubby macros take care of serializing the input, transmitting the
423               ;; request over the wire, waiting for input (or not if it's asynchronous),
424               ;; filling in the output, and calling the callback (if it's synchronous).
425               ;; It's not very Lispy to side-effect an output object, but it makes
426               ;; asynchronous calls simpler.
427               (collect-form `(defgeneric ,client-fn (,vchannel ,vinput ,voutput &key ,vcallback)
428                                ,@(and documentation `((:documentation ,documentation)))
429                                (declare (values ,output-type))))
430               ;; The server side stub, e.g., 'do-read-air-reservation'.
431               ;; The expectation is that the server-side program will implement
432               ;; a method with the business logic for this on each kind of channel
433               ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
434               ;; of the input class
435               ;; The business logic is expected to perform the correct operations on
436               ;; the input object, which arrived via Protobufs, and produce an output
437               ;; of the given type, which will be serialized as a result.
438               ;; The channel objects hold client identity information, deadline info,
439               ;; etc, and can be side-effected to indicate success or failure
440               ;; CL-Stubby provides the channel classes and does (de)serialization, etc
441               (collect-form `(defgeneric ,server-fn (,vchannel ,vinput ,voutput &key ,vcallback)
442                                ,@(and documentation `((:documentation ,documentation)))
443                                (declare (values ,output-type))))))))
444       `(progn
445          define-service
446          ,service
447          ,forms))))
448
449 \f
450 ;;; Ensure everything in a Protobufs schema is defined
451
452 (defvar *undefined-messages*)
453
454 ;; A very useful tool during development...
455 (defun ensure-all-protobufs ()
456   (let ((protos (sort
457                  (delete-duplicates
458                   (loop for p being the hash-values of *all-protobufs*
459                         collect p))
460                  #'string< :key #'proto-name)))
461     (mapcan #'ensure-protobuf protos)))
462
463 (defmethod ensure-protobuf ((proto protobuf))
464   "Ensure that all of the types are defined in the Protobufs schema 'proto'.
465    This returns two values:
466     - A list whose elements are (<undefined-type> \"message:field\" ...)
467     - The accumulated warnings table that has the same information as objects."
468   (let ((*undefined-messages* (make-hash-table))
469         (trace (list proto)))
470     (map () (curry #'ensure-message trace) (proto-messages proto))
471     (map () (curry #'ensure-service trace) (proto-services proto))
472     (loop for type being the hash-keys of *undefined-messages*
473             using (hash-value things)
474           collect (list* type
475                          (mapcar #'(lambda (thing)
476                                      (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
477                                  things)) into warnings
478           finally (return (values warnings *undefined-messages*)))))
479
480 (defmethod ensure-message (trace (message protobuf-message))
481   (let ((trace (cons message trace)))
482     (map () (curry #'ensure-message trace) (proto-messages message))
483     (map () (curry #'ensure-field trace message) (proto-fields message))))
484
485 (defmethod ensure-field (trace message (field protobuf-field))
486   (ensure-type trace message field (proto-class field)))
487
488 (defmethod ensure-service (trace (service protobuf-service))
489   (map () (curry #'ensure-method trace service) (proto-methods service)))
490
491 (defmethod ensure-method (trace service (method protobuf-method))
492   (ensure-type trace service method (proto-input-type method))
493   (ensure-type trace service method (proto-output-type method)))
494
495 ;; 'message' and 'field' can be a message and a field or a service and a method
496 (defun ensure-type (trace message field type)
497   (unless (keywordp type)
498     (let ((msg (loop for p in trace
499                      thereis (or (find-message p type)
500                                  (find-enum p type)))))
501       (unless msg
502         (push (cons message field) (gethash type *undefined-messages*))))))