]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - define-proto.lisp
f09d24d71fc12747de23aa81b6b989641beda01c
[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   (with-collectors ((enums collect-enum)
31                     (msgs  collect-msg)
32                     (svcs  collect-svc)
33                     (forms collect-form))
34     (dolist (msg messages)
35       (assert (and (listp msg)
36                    (member (car msg) '(define-enum define-message define-service))) ()
37               "The body of ~S must be one of ~{~S~^ or ~}"
38               'define-proto '(define-enum define-message define-service))
39       ;; The macro-expander will return a form that consists
40       ;; of 'progn' followed by a symbol naming what we've expanded
41       ;; (define-enum, define-message, define-service), followed by
42       ;; by a (optional) Lisp defining form (deftype, defclass),
43       ;; followed by a form that creates the model object
44       (destructuring-bind (&optional progn type model definers)
45           (macroexpand-1 msg env)
46         (assert (eq progn 'progn) ()
47                 "The macroexpansion for ~S failed" msg)
48         (map () #'collect-form definers)
49         (ecase type
50           ((define-enum)
51            (collect-enum model))
52           ((define-message define-extends)
53            (collect-msg model))
54           ((define-service)
55            (collect-svc model)))))
56     (let ((var  (fintern "*~A*" type))
57           (name (or name (class-name->proto type)))
58           (package  (and package (if (stringp package) package (string-downcase (string package)))))
59           (lisp-pkg (and lisp-package (if (stringp lisp-package) lisp-package (string lisp-package))))
60           (options (loop for (key val) on options by #'cddr
61                          collect (make-instance 'protobuf-option
62                                    :name  key
63                                    :value val))))
64       `(progn
65          ,@forms
66          (defvar ,var nil)
67          (let* ((old ,var)
68                 (protobuf ,(make-instance 'protobuf
69                              :class    type
70                              :name     name
71                              :syntax   (or syntax "proto2")
72                              :package  package
73                              :lisp-package (or lisp-pkg package)
74                              ;;---*** This needs to parse the imported file(s)
75                              :imports  (if (listp import) import (list import))
76                              :options  options
77                              :optimize optimize
78                              :enums    enums
79                              :messages msgs
80                              :services svcs
81                              :documentation documentation)))
82            (when old
83              (multiple-value-bind (upgradable warnings)
84                  (protobuf-upgradable old protobuf)
85                (unless upgradable
86                  (protobufs-warn "The old schema for ~S (~A) can't be safely upgraded; proceeding anyway"
87                                  ',type ',name)
88                  (map () #'protobufs-warn warnings))))
89            (setq ,var protobuf)
90            #+++ignore (
91            ,@(when (eq optimize :speed)
92                (mapcar #'generate-object-size (proto-messages protobuf)))
93            ,@(when (eq optimize :speed)
94                (mapcar #'generate-serializer (proto-messages protobuf)))
95            ,@(when (eq optimize :speed)
96                (mapcar #'generate-deserializer (proto-messages protobuf))) )
97            protobuf)))))
98
99 ;; Define an enum type named 'type' and a Lisp 'deftype'
100 (defmacro define-enum (type (&key name conc-name alias-for options documentation)
101                        &body values)
102   "Define a Protobufs enum type and a Lisp 'deftype' named 'type'.
103    'name' can be used to override the defaultly generated Protobufs enum name.
104    'conc-name' will be used as the prefix to the Lisp enum names, if it's supplied.
105    If 'alias-for' is given, no Lisp 'deftype' will be defined. Instead, the enum
106    will be used as an alias for an enum type that already exists in Lisp.
107    'options' is a set of keyword/value pairs, both of which are strings.
108
109    The body consists of the enum values in the form 'name' or (name index)."
110   (with-collectors ((vals  collect-val)
111                     (evals collect-eval)
112                     (forms collect-form))
113     (let ((index 0))
114       (dolist (val values)
115         (let* ((idx  (if (listp val) (second val) (incf index)))
116                (name (if (listp val) (first val)  val))
117                (val-name  (kintern (if conc-name (format nil "~A~A" conc-name name) (symbol-name name))))
118                (enum-name (if conc-name (format nil "~A~A" conc-name name) (symbol-name name))))
119           (collect-val val-name)
120           (collect-eval (make-instance 'protobuf-enum-value
121                           :name  (enum-name->proto enum-name)
122                           :index idx
123                           :value val-name)))))
124
125     (if alias-for
126       ;; If we've got an alias, define a a type that is the subtype of
127       ;; the Lisp enum so that typep and subtypep work
128       (unless (eq type alias-for)
129         (collect-form `(deftype ,type () ',alias-for)))
130       ;; If no alias, define the Lisp enum type now
131       (collect-form `(deftype ,type () '(member ,@vals))))
132     (let ((name (or name (class-name->proto type)))
133           (options (loop for (key val) on options by #'cddr
134                          collect (make-instance 'protobuf-option
135                                    :name  key
136                                    :value val))))
137       `(progn
138          define-enum
139          ,(make-instance 'protobuf-enum
140             :class  type
141             :name   name
142             :alias-for alias-for
143             :options options
144             :values  evals
145             :documentation documentation)
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   (with-collectors ((enums collect-enum)
172                     (msgs  collect-msg)
173                     (flds  collect-field)
174                     (slots collect-slot)
175                     (exts  collect-extension)
176                     (forms collect-form))
177     (let ((index 0))
178       (declare (type fixnum index))
179       (dolist (fld fields)
180         (case (car fld)
181           ((define-enum define-message define-extension)
182            (destructuring-bind (&optional progn type model definers)
183                (macroexpand-1 fld env)
184              (assert (eq progn 'progn) ()
185                      "The macroexpansion for ~S failed" fld)
186              (map () #'collect-form definers)
187              (ecase type
188                ((define-enum)
189                 (collect-enum model))
190                ((define-message define-extends)
191                 (collect-msg model))
192                ((define-extension)
193                 (collect-extension model)))))
194           (otherwise
195            (when (i= index 18999)                       ;skip over the restricted range
196              (setq index 19999))
197            (destructuring-bind (slot &key type (default nil default-p) reader writer name documentation) fld
198              (let* ((idx  (if (listp slot) (second slot) (iincf index)))
199                     (slot (if (listp slot) (first slot) slot))
200                     (reqd (clos-type-to-protobuf-required type))
201                     (reader (if (eq reader 't)
202                               (intern (if conc-name (format nil "~A~A" conc-name slot) (symbol-name slot))
203                                       (symbol-package slot))
204                               reader)))
205                (multiple-value-bind (ptype pclass)
206                    (clos-type-to-protobuf-type type)
207                  (unless alias-for
208                    (collect-slot `(,slot :type ,type
209                                          ,@(and reader
210                                                 (if writer
211                                                   `(:reader ,reader)
212                                                   `(:accessor ,reader)))
213                                          ,@(and writer
214                                                 `(:writer ,writer))
215                                          :initarg ,(kintern (symbol-name slot))
216                                          ,@(cond ((and (not default-p) (eq reqd :repeated))
217                                                   `(:initform ()))
218                                                  ((and (not default-p) (eq reqd :optional))
219                                                   `(:initform nil))
220                                                  (default-p
221                                                    `(:initform ,default))))))
222                  (collect-field (make-instance 'protobuf-field
223                                   :name  (or name (slot-name->proto slot))
224                                   :type  ptype
225                                   :class pclass
226                                   :required reqd
227                                   :index  idx
228                                   :value  slot
229                                   :reader reader
230                                   :writer writer
231                                   :default (and default (format nil "~A" default))
232                                   :packed  (and (eq reqd :repeated)
233                                                 (packed-type-p pclass))
234                                   :documentation documentation)))))))))
235     (if alias-for
236       ;; If we've got an alias, define a a type that is the subtype of
237       ;; the Lisp class that typep and subtypep work
238       (unless (or (eq type alias-for) (find-class type nil))
239         (collect-form `(deftype ,type () ',alias-for)))
240       ;; If no alias, define the class now
241       (collect-form `(defclass ,type () (,@slots)
242                        ,@(and documentation `((:documentation ,documentation))))))
243     (let ((name (or name (class-name->proto type)))
244           (options (loop for (key val) on options by #'cddr
245                          collect (make-instance 'protobuf-option
246                                    :name  key
247                                    :value val))))
248       `(progn
249          define-message
250          ,(make-instance 'protobuf-message
251             :class type
252             :name  name
253             :alias-for alias-for
254             :conc-name (and conc-name (string conc-name))
255             :options  options
256             :enums    enums
257             :messages msgs
258             :fields   flds
259             :extensions exts
260             :documentation documentation)
261          ,forms))))
262
263 (defmacro define-extends (type (&key name options documentation)
264                           &body fields &environment env)
265   ;;---*** Handle 'define-extends' here (factor out field "parsing" from above)
266   ;;---*** Note that it handles only fields, not nested message or enums
267   type name options documentation fields env
268   `(progn define-extends nil nil))
269
270 (defmacro define-extension (from to)
271   "Define an extension range within a message.
272    The \"body\" is the start and end of the range, both inclusive."
273   `(progn
274      define-extension
275      ,(make-instance 'protobuf-extension
276         :from from
277         :to   to)
278      ()))
279
280 ;; Define a service named 'type' with generic functions declared for
281 ;; each of the methods within the service
282 (defmacro define-service (type (&key name options documentation)
283                           &body method-specs)
284   "Define a service named 'type' and Lisp 'defgeneric' for all its methods.
285    'name' can be used to override the defaultly generated Protobufs service name.
286    'options' is a set of keyword/value pairs, both of which are strings.
287
288    The body is a set of method specs of the form (name (input-type output-type) &key options).
289    'input-type' and 'output-type' may also be of the form (type &key name)."
290   (with-collectors ((methods collect-method)
291                     (forms collect-form))
292     (dolist (method method-specs)
293       (destructuring-bind (function (input-type output-type) &key name options documentation) method
294         (let* ((input-name (and (listp input-type)
295                                 (getf (cdr input-type) :name)))
296                (input-type (if (listp input-type) (car input-type) input-type))
297                (output-name (and (listp output-type)
298                                  (getf (cdr output-type) :name)))
299                (output-type (if (listp output-type) (car output-type) output-type))
300                (options (loop for (key val) on options by #'cddr
301                               collect (make-instance 'protobuf-option
302                                         :name  key
303                                         :value val))))
304           (collect-method (make-instance 'protobuf-method
305                             :class function
306                             :name  (or name (class-name->proto function))
307                             :input-type  input-type
308                             :input-name  (or input-name (class-name->proto input-type))
309                             :output-type output-type
310                             :output-name (or output-name (class-name->proto output-type))
311                             :options options
312                             :documentation documentation))
313           ;; The following are the hooks to CL-Stubby
314           (let ((client-fn function)
315                 (server-fn (intern (format nil "~A-~A" 'do function) (symbol-package function)))
316                 (vchannel  (intern (symbol-name 'channel) (symbol-package function)))
317                 (vcallback (intern (symbol-name 'callback) (symbol-package function))))
318             ;; The client side stub, e.g., 'read-air-reservation'.
319             ;; The expectation is that CL-Stubby will provide macrology to make it
320             ;; easy to implement a method for this on each kind of channel (HTTP, TCP socket,
321             ;; IPC, etc). Unlike C++/Java/Python, we don't need a client-side subclass,
322             ;; because we can just use multi-methods.
323             ;; The CL-Stubby macros take care of serializing the input, transmitting the
324             ;; request over the wire, waiting for input (or not if it's asynchronous),
325             ;; filling in the output, and calling the callback (if it's synchronous).
326             ;; It's not very Lispy to side-effect an output object, but it makes
327             ;; asynchronous calls simpler.
328             (collect-form `(defgeneric ,client-fn (,vchannel ,input-type ,output-type &key ,vcallback)
329                              ,@(and documentation `((:documentation ,documentation)))
330                              (declare (values ,output-type))))
331             ;; The server side stub, e.g., 'do-read-air-reservation'.
332             ;; The expectation is that the server-side program will implement
333             ;; a method with the business logic for this on each kind of channel
334             ;; (HTTP, TCP socket, IPC, etc), possibly on a server-side subclass
335             ;; of the input class
336             ;; The business logic is expected to perform the correct operations on
337             ;; the input object, which arrived via Protobufs, and produce an output
338             ;; of the given type, which will be serialized as a result.
339             ;; The channel objects hold client identity information, deadline info,
340             ;; etc, and can be side-effected to indicate success or failure
341             ;; CL-Stubby provides the channel classes and does (de)serialization, etc
342             (collect-form `(defgeneric ,server-fn (,vchannel ,input-type ,output-type &key ,vcallback)
343                              ,@(and documentation `((:documentation ,documentation)))
344                              (declare (values ,output-type))))))))
345     (let ((name (or name (class-name->proto type)))
346           (options (loop for (key val) on options by #'cddr
347                          collect (make-instance 'protobuf-option
348                                    :name  key
349                                    :value val))))
350       `(progn
351          define-service
352          ,(make-instance 'protobuf-service
353             :class type
354             :name  name
355             :options options
356             :methods methods
357             :documentation documentation)
358          ,forms))))
359
360 \f
361 ;;; Ensure everything in a Protobufs schema is defined
362
363 (defvar *undefined-messages*)
364
365 ;; A very useful tool during development...
366 (defun ensure-all-protobufs ()
367   (let ((protos (sort
368                  (delete-duplicates
369                   (loop for p being the hash-values of *all-protobufs*
370                         collect p))
371                  #'string< :key #'proto-name)))
372     (mapcan #'ensure-protobuf protos)))
373
374 (defmethod ensure-protobuf ((proto protobuf))
375   "Ensure that all of the types are defined in the Protobufs schema 'proto'.
376    This returns two values:
377     - A list whose elements are (<undefined-type> \"message:field\" ...)
378     - The accumulated warnings table that has the same information as objects."
379   (let ((*undefined-messages* (make-hash-table))
380         (trace (list proto)))
381     (map () (curry #'ensure-message trace) (proto-messages proto))
382     (map () (curry #'ensure-service trace) (proto-services proto))
383     (loop for type being the hash-keys of *undefined-messages*
384             using (hash-value things)
385           collect (list* type
386                          (mapcar #'(lambda (thing)
387                                      (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
388                                  things)) into warnings
389           finally (return (values warnings *undefined-messages*)))))
390
391 (defmethod ensure-message (trace (message protobuf-message))
392   (let ((trace (cons message trace)))
393     (map () (curry #'ensure-message trace) (proto-messages message))
394     (map () (curry #'ensure-field trace message) (proto-fields message))))
395
396 (defmethod ensure-field (trace message (field protobuf-field))
397   (ensure-type trace message field (proto-class field)))
398
399 (defmethod ensure-service (trace (service protobuf-service))
400   (map () (curry #'ensure-method trace service) (proto-methods service)))
401
402 (defmethod ensure-method (trace service (method protobuf-method))
403   (ensure-type trace service method (proto-input-type method))
404   (ensure-type trace service method (proto-output-type method)))
405
406 ;; 'message' and 'field' can be a message and a field or a service and a method
407 (defun ensure-type (trace message field type)
408   (unless (keywordp type)
409     (let ((msg (loop for p in trace
410                      thereis (or (find-message p type)
411                                  (find-enum p type)))))
412       (unless msg
413         (push (cons message field) (gethash type *undefined-messages*))))))