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