]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - define-proto.lisp
Make sure extended indexes are in range
[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-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)
67           (ecase type
68             ((define-enum)
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)))))
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-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)
195              (ecase type
196                ((define-enum)
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)))))
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              (setq index idx)
212              (when slot
213                (collect-slot slot))
214              (setf (proto-fields message) (nconc (proto-fields message) (list field)))))))
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-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.
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-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))
285           (setq index idx)
286           (when slot
287             (let* ((inits (cdr slot))
288                    (sname (car slot))
289                    (stype (getf inits :type))
290                    (reader (or (getf inits :accessor)
291                                (getf inits :reader)
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)))))
312       `(progn
313          define-extend
314          ,extends
315          ,forms))))
316
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
321     (setq index 19999))
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))
329                      reader)))
330       (multiple-value-bind (ptype pclass)
331           (clos-type-to-protobuf-type type)
332         (let ((slot (unless alias-for
333                       `(,slot :type ,type
334                               ,@(and reader
335                                      (if writer
336                                        `(:reader ,reader)
337                                        `(:accessor ,reader)))
338                               ,@(and writer
339                                      `(:writer ,writer))
340                               :initarg ,(kintern (symbol-name slot))
341                               ,@(cond ((and (not default-p) (eq reqd :repeated))
342                                        `(:initform ()))
343                                       ((and (not default-p) (eq reqd :optional))
344                                        `(:initform nil))
345                                       (default-p
346                                         `(:initform ,default))))))
347               (field (make-instance 'protobuf-field
348                        :name  (or name (slot-name->proto slot))
349                        :type  ptype
350                        :class pclass
351                        :required reqd
352                        :index  idx
353                        :value  slot
354                        :reader reader
355                        :writer writer
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))))))
361
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))))
367           extensions)))
368
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."
372   `(progn
373      define-extension
374      ,(make-instance 'protobuf-extension
375         :from from
376         :to   (if (eql to 'max) #.(1- (ash 1 29)) to))
377      ()))
378
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)
382                           &body method-specs)
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.
386
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
392                                   :name  key
393                                   :value val)))
394          (service (make-instance 'protobuf-service
395                     :class type
396                     :name  name
397                     :options options
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
410                                           :name  key
411                                           :value val)))
412                  (method  (make-instance 'protobuf-method
413                             :class function
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))
419                             :options options
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))
424                    (client-fn 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))))))))
457       `(progn
458          define-service
459          ,service
460          ,forms))))
461
462 \f
463 ;;; Ensure everything in a Protobufs schema is defined
464
465 (defvar *undefined-messages*)
466
467 ;; A very useful tool during development...
468 (defun ensure-all-protobufs ()
469   (let ((protos (sort
470                  (delete-duplicates
471                   (loop for p being the hash-values of *all-protobufs*
472                         collect p))
473                  #'string< :key #'proto-name)))
474     (mapcan #'ensure-protobuf protos)))
475
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)
487           collect (list* type
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*)))))
492
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))))
497
498 (defmethod ensure-field (trace message (field protobuf-field))
499   (ensure-type trace message field (proto-class field)))
500
501 (defmethod ensure-service (trace (service protobuf-service))
502   (map () (curry #'ensure-method trace service) (proto-methods service)))
503
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)))
507
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)))))
514       (unless msg
515         (push (cons message field) (gethash type *undefined-messages*))))))