]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - define-proto.lisp
Fix a problem in which 'define-message' could define a circular type.
[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 'name', corresponding to a .proto file of that name
17 (defmacro define-proto (name (&key proto-name syntax package import options documentation)
18                         &body messages &environment env)
19   "Define a schema named 'name', corresponding to a .proto file of that name.
20    'proto-name' can be used to override the defaultly generated name.
21    'syntax' and 'package' are as they would be in a .proto file.
22    'imports' is a list of pathname strings to be imported.
23    'options' is a property list, i.e., (\"key1\" \"val1\" \"key2\" \"val2\" ...).
24    The body consists of 'define-enum', 'define-message' or 'define-service' forms."
25   (with-collectors ((enums collect-enum)
26                     (msgs  collect-msg)
27                     (svcs  collect-svc)
28                     (forms collect-form))
29     (dolist (msg messages)
30       (assert (and (listp msg)
31                    (member (car msg) '(define-enum define-message define-service))) ()
32               "The body of ~S must be one of ~{~S~^ or ~}"
33               'define-proto '(define-enum define-message define-service))
34       ;; The macro-expander will return a form that consists
35       ;; of 'progn' followed by a symbol naming what we've expanded
36       ;; (define-enum, define-message, define-service), followed by
37       ;; by a (optional) Lisp defining form (deftype, defclass),
38       ;; followed by a form that creates the model object
39       (destructuring-bind (&optional progn type model definers)
40           (macroexpand-1 msg env)
41         (assert (eq progn 'progn) ()
42                 "The macroexpansion for ~S failed" msg)
43         (map () #'collect-form definers)
44         (ecase type
45           ((define-enum)
46            (collect-enum model))
47           ((define-message)
48            (collect-msg model))
49           ((define-service)
50            (collect-svc model)))))
51     (let ((vname (fintern "*~A*" name))
52           (pname (or proto-name (class-name->proto name)))
53           (cname name)
54           (options (loop for (key val) on options by #'cddr
55                          collect `(make-instance 'protobuf-option
56                                     :name ,key
57                                     :value ,val))))
58       `(progn
59          ,@forms
60          (defvar ,vname nil)
61          (let ((old      ,vname)
62                (protobuf (make-instance 'protobuf
63                            :name     ',pname
64                            :class    ',cname
65                            :package  ,(if (stringp package) package (string-downcase (string package)))
66                            :imports  ',(if (listp import) import (list import))
67                            :syntax   ,(or syntax "proto2")
68                            :options  (list ,@options)
69                            :enums    (list ,@enums)
70                            :messages (list ,@msgs)
71                            :services (list ,@svcs)
72                            :documentation ,documentation)))
73            (when old
74              (multiple-value-bind (upgradable warnings)
75                  (protobuf-upgradable old protobuf)
76                (unless upgradable
77                  (protobufs-warn "The old schema for ~S (~A) can't be safely upgraded; proceeding anyway"
78                                  ',cname ',pname)
79                  (map () #'protobufs-warn warnings))))
80            (setq ,vname protobuf)
81            (setf (gethash ',pname *all-protobufs*) protobuf)
82            (setf (gethash ',cname *all-protobufs*) protobuf)
83            protobuf)))))
84
85 ;; Define an enum type named 'name' and a Lisp 'deftype'
86 (defmacro define-enum (name (&key proto-name conc-name type options documentation)
87                        &body values)
88   "Define an enum type named 'name' and a Lisp 'deftype'.
89    'proto-name' can be used to override the defaultly generated Protobufs name.
90    'conc-name' will be used as the prefix to the Lisp enum names, if it's supplied.
91    If 'type' is given, no Lisp deftype is defined. This feature is intended to be used
92    to model enum types that already exist in Lisp.
93    'options' is a set of keyword/value pairs, both of which are strings.
94    The body consists of the enum values in the form (name &key index)."
95   (with-collectors ((vals  collect-val)
96                     (evals collect-eval)
97                     (forms collect-form))
98     (let ((index 0))
99       (dolist (val values)
100         (let* ((idx  (if (listp val) (second val) (incf index)))
101                (name (if (listp val) (first val)  val))
102                (val-name  (kintern (if conc-name (format nil "~A~A" conc-name name) (symbol-name name))))
103                (enum-name (if conc-name (format nil "~A~A" conc-name name) (symbol-name name))))
104           (collect-val val-name)
105           (collect-eval `(make-instance 'protobuf-enum-value
106                            :name  ,(enum-name->proto enum-name)
107                            :index ,idx
108                            :value ,val-name)))))
109
110     (if type
111       ;; If we've got a type override, define a type matching the Lisp name
112       ;; of this message so that typep and subtypep work
113       (unless (eq name type)
114         (collect-form `(deftype ,name () ',type)))
115       ;; If no type override, define the type now
116       (collect-form `(deftype ,name () '(member ,@vals))))
117     (let ((options (loop for (key val) on options by #'cddr
118                          collect `(make-instance 'protobuf-option
119                                     :name ,key
120                                     :value ,val))))
121       `(progn
122          define-enum
123          (make-instance 'protobuf-enum
124            :name   ,(or proto-name (class-name->proto name))
125            :class  ',name
126            :class-override ',type
127            :options (list ,@options)
128            :values  (list ,@evals)
129            :documentation ,documentation)
130          ,forms))))
131
132 ;; Define a message named 'name' and a Lisp 'defclass'
133 (defmacro define-message (name (&key proto-name conc-name class options documentation)
134                           &body fields &environment env)
135   "Define a message named 'name' and a Lisp 'defclass'.
136    'proto-name' can be used to override the defaultly generated Protobufs name.
137    The body consists of fields, or 'define-enum' or 'define-message' forms.
138    'conc-name' will be used as the prefix to the Lisp slot accessors, if it's supplied.
139    If 'class' is given, no Lisp class is defined. This feature is intended to be used
140    to model messages that will be serialized from existing Lisp classes; unless you
141    get the slot names correct in each field, it will be the case that trying to
142    deserialize into a Lisp object won't work.
143    'options' is a set of keyword/value pairs, both of which are strings.
144    Fields take the form (name &key type default reader)
145    'name' can be either a symbol giving the field name, or a list whose
146    first element is the field name and whose second element is the index."
147   (with-collectors ((enums collect-enum)
148                     (msgs  collect-msg)
149                     (flds  collect-field)
150                     (slots collect-slot)
151                     (forms collect-form))
152     (let ((index 0))
153       (declare (type fixnum index))
154       (dolist (fld fields)
155         (case (car fld)
156           ((define-enum define-message define-extension)
157            (destructuring-bind (&optional progn type model definers)
158                (macroexpand-1 fld env)
159              (assert (eq progn 'progn) ()
160                      "The macroexpansion for ~S failed" fld)
161              (map () #'collect-form definers)
162              (ecase type
163                ((define-enum)
164                 (collect-enum model))
165                ((define-message)
166                 (collect-msg model))
167                ((define-extension)
168                 (collect-msg model)))))
169           (otherwise
170            (when (i= index 18999)                       ;skip over the restricted range
171              (setq index 19999))
172            (destructuring-bind (slot &key type default reader proto-name) fld
173              (let* ((idx  (if (listp slot) (second slot) (iincf index)))
174                     (slot (if (listp slot) (first slot) slot))
175                     (reqd (clos-type-to-protobuf-required type))
176                     (accessor (intern (if conc-name (format nil "~A~A" conc-name slot) (symbol-name slot))
177                                       (symbol-package slot))))
178                (multiple-value-bind (ptype pclass)
179                    (clos-type-to-protobuf-type type)
180                  (unless class
181                    (collect-slot `(,slot :type ,type
182                                          :accessor ,accessor
183                                          :initarg ,(kintern (symbol-name slot))
184                                          ,@(and default (list :initform default)))))
185                  (collect-field `(make-instance 'protobuf-field
186                                    :name  ,(or proto-name (slot-name->proto slot))
187                                    :type  ,ptype
188                                    :class ',pclass
189                                    :required ,reqd
190                                    :index  ,idx
191                                    :value  ',slot
192                                    :reader ',reader
193                                    :default ,(and default (format nil "~A" default))
194                                    :packed  ,(and (eq reqd :repeated)
195                                                   (packed-type-p pclass)))))))))))
196     (if class
197       ;; If we've got a class override, define a type matching the Lisp name
198       ;; of this message so that typep and subtypep work
199       (unless (eq name class)
200         (collect-form `(deftype ,name () ',class)))
201       ;; If no class override, define the class now
202       (collect-form `(defclass ,name () (,@slots))))
203     (let ((options (loop for (key val) on options by #'cddr
204                          collect `(make-instance 'protobuf-option
205                                     :name ,key
206                                     :value ,val))))
207       `(progn
208          define-message
209          (make-instance 'protobuf-message
210            :name  ,(or proto-name (class-name->proto name))
211            :class ',name
212            :class-override ',class
213            :conc-name ,(and conc-name (string conc-name))
214            :options  (list ,@options)
215            :enums    (list ,@enums)
216            :messages (list ,@msgs)
217            :fields   (list ,@flds)
218            :documentation ,documentation)
219          ,forms))))
220
221 (defmacro define-extension (from to)
222   "Define an extension range within a message.
223    The \"body\" is the start and end of the range, both inclusive."
224   `(progn
225      define-extension
226      (make-instance 'protobuf-extension
227        :from ,from
228        :to   ,to)
229      ()))
230
231 ;; Define a service named 'name' with generic functions declared for
232 ;; each of the RPCs within the service
233 (defmacro define-service (name (&key proto-name options documentation)
234                           &body rpc-specs)
235   "Define a service named 'name' and a Lisp 'defgeneric'.
236    'proto-name' can be used to override the defaultly generated Protobufs name.
237    'options' is a set of keyword/value pairs, both of which are strings.
238    The body is a set of RPC specs of the form (name (input-type output-type) &key options)."
239   (with-collectors ((rpcs collect-rpc)
240                     (forms collect-form))
241     (dolist (rpc rpc-specs)
242       (destructuring-bind (name (input-class output-class) &key options) rpc
243         (let ((options (loop for (key val) on options by #'cddr
244                              collect `(make-instance 'protobuf-option
245                                         :name ,key
246                                         :value ,val))))
247           (collect-rpc `(make-instance 'protobuf-rpc
248                           :name ,(class-name->proto name)
249                           :class ',name
250                           :input-type  ,(and input-class  (class-name->proto input-class))
251                           :input-class ',input-class
252                           :output-type  ,(and output-class (class-name->proto output-class))
253                           :output-class ',output-class
254                           :options (list ,@options)))
255           ;;--- Is this really all we need as the stub for the RPC?
256           (collect-form `(defgeneric ,name (,@(and input-class (list input-class)))
257                            (declare (values ,output-class)))))))
258     (let ((options (loop for (key val) on options by #'cddr
259                          collect `(make-instance 'protobuf-option
260                                     :name ,key
261                                     :value ,val))))
262       `(progn
263          define-service
264          (make-instance 'protobuf-service
265            :name ,(or proto-name (class-name->proto name))
266            :class ',name
267            :options  (list ,@options)
268            :rpcs (list ,@rpcs)
269            :documentation ,documentation)
270          ,forms))))
271
272 \f
273 ;;; Ensure everything in a Protobufs schema is defined
274
275 (defvar *undefined-messages*)
276
277 ;; A very useful tool during development...
278 (defun ensure-all-protobufs ()
279   (let ((protos (sort
280                  (delete-duplicates
281                   (loop for p being the hash-values of *all-protobufs*
282                         collect p))
283                  #'string< :key #'proto-name)))
284     (mapcan #'ensure-protobuf protos)))
285
286 (defmethod ensure-protobuf ((proto protobuf))
287   "Ensure that all of the types are defined in the Protobufs schema 'proto'.
288    This returns two values:
289     - A list whose elements are (<undefined-type> \"message:field\" ...)
290     - The accumulated warnings table that has the same information as objects."
291   (let ((*undefined-messages* (make-hash-table))
292         (trace (list proto)))
293     (map () (curry #'ensure-message trace) (proto-messages proto))
294     (map () (curry #'ensure-service trace) (proto-services proto))
295     (loop for type being the hash-keys of *undefined-messages*
296             using (hash-value things)
297           collect (list* type
298                          (mapcar #'(lambda (thing)
299                                      (format nil "~A:~A" (proto-name (car thing)) (proto-name (cdr thing))))
300                                  things)) into warnings
301           finally (return (values warnings *undefined-messages*)))))
302
303 (defmethod ensure-message (trace (message protobuf-message))
304   (let ((trace (cons message trace)))
305     (map () (curry #'ensure-message trace) (proto-messages message))
306     (map () (curry #'ensure-field trace message) (proto-fields message))))
307
308 (defmethod ensure-field (trace message (field protobuf-field))
309   (ensure-type trace message field (proto-class field)))
310
311 (defmethod ensure-service (trace (service protobuf-service))
312   (map () (curry #'ensure-rpc trace service) (proto-rpcs service)))
313
314 (defmethod ensure-rpc (trace service (rpc protobuf-rpc))
315   (ensure-type trace service rpc (proto-input-type rpc))
316   (ensure-type trace service rpc (proto-output-type rpc)))
317
318 ;; 'message' and 'field' can be a message and a field or a service and an RPC
319 (defun ensure-type (trace message field type)
320   (unless (keywordp type)
321     (let ((msg (loop for p in trace
322                      thereis (or (find-message-for-class p type)
323                                  (find-enum-for-type p type)))))
324       (unless msg
325         (push (cons message field) (gethash type *undefined-messages*))))))