]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - clos-transform.lisp
Move Protobufs to lisp/libs/cl-protobufs as a standalone system
[cl-protobufs.git] / clos-transform.lisp
1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2 ;;;                                                                  ;;;
3 ;;; Free Software published under an MIT-like license. See LICENSE   ;;;
4 ;;;                                                                  ;;;
5 ;;; Copyright (c) 2012 Google, Inc.  All rights reserved.            ;;;
6 ;;;                                                                  ;;;
7 ;;; Original author: Scott McKay                                     ;;;
8 ;;;                                                                  ;;;
9 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
10
11 (in-package "PROTO-IMPL")
12
13
14 ;;; Protocol buffer generation from ordinary CLOS classes
15
16 ;; Controls whether or not to use ':alias-for' for the Protobuf generated
17 ;; for an existing Lisp class
18 ;; The default is presently true because, at least initially, we'll be using
19 ;; the generated Protobufs code in the Lisp world that includes that classes
20 ;; from which the code was generated
21 (defvar *alias-existing-classes* t)
22
23 ;; Doing this can't really work perfectly, there's not enough information
24 ;;  - How do we decide if there's an ownership hierarchy that should produce embedded messages?
25 ;;  - How do we decide if there are volatile slots that should not be included in the message?
26 (defun write-schema-for-classes (classes
27                                  &key (stream *standard-output*) (type :proto)
28                                       name package lisp-package install
29                                       slot-filter type-filter enum-filter value-filter
30                                       (alias-existing-classes *alias-existing-classes*))
31   "Given a set of CLOS classes, generates a Protobufs schema for the classes
32    and pretty prints the schema to the stream.
33    The return value is the schema."
34   (let ((schema (generate-schema-for-classes classes
35                   :name name
36                   :package package
37                   :lisp-package (or lisp-package package)
38                   :install install
39                   :slot-filter slot-filter
40                   :type-filter type-filter
41                   :enum-filter enum-filter
42                   :value-filter value-filter
43                   :alias-existing-classes alias-existing-classes)))
44     (fresh-line stream)
45     (write-schema schema :stream stream :type type)
46     (terpri stream)
47     schema))
48
49 (defun generate-schema-for-classes (classes
50                                     &key name package lisp-package install
51                                          slot-filter type-filter enum-filter value-filter
52                                          (alias-existing-classes *alias-existing-classes*))
53   "Given a set of CLOS classes, generates a Protobufs schema for the classes.
54    The return value is the schema."
55   (let* ((*alias-existing-classes* alias-existing-classes)
56          (package  (and package (if (stringp package) package (string-downcase (string package)))))
57          (lisp-pkg (string (or lisp-package package)))
58          (schema   (make-instance 'protobuf-schema
59                      :name name
60                      :package package
61                      :lisp-package lisp-pkg
62                      :syntax "proto2"))
63          (messages (mapcar #'(lambda (c)
64                                (class-to-protobuf-message c schema
65                                 :slot-filter slot-filter
66                                 :type-filter type-filter
67                                 :enum-filter enum-filter
68                                 :value-filter value-filter))
69                            classes)))
70     (setf (proto-messages schema) messages)
71     (when install
72       (record-protobuf schema)
73       (with-collectors ((messages collect-message))
74         (labels ((collect-messages (message)
75                    (collect-message message)
76                    (map () #'collect-messages (proto-messages message))))
77           (map () #'collect-messages (proto-messages schema)))
78         (map () #'record-protobuf messages)))
79     schema))
80
81
82 (defun class-to-protobuf-message (class schema
83                                   &key slot-filter type-filter enum-filter value-filter)
84   "Given a CLOS class, return a Protobufs model object for it."
85   (let* ((class (find-class class))
86          (slots (class-slots class)))
87     (with-collectors ((enums  collect-enum)
88                       (msgs   collect-msg)
89                       (fields collect-field))
90       (loop with index = 1
91             for s in slots doing
92         (multiple-value-bind (field msg enum)
93             (slot-to-protobuf-field class s index slots
94               :slot-filter slot-filter
95               :type-filter type-filter
96               :enum-filter enum-filter
97               :value-filter value-filter)
98           (when enum
99             (collect-enum enum))
100           (when msg
101             (collect-msg msg))
102           (when field
103             (incf index 1)                              ;don't worry about the 19000-19999 restriction
104             (collect-field field))))
105       (make-instance 'protobuf-message
106         :class (class-name class)
107         :name  (class-name->proto (class-name class))
108         :parent schema
109         :alias-for (and *alias-existing-classes* (class-name class))
110         :enums    (delete-duplicates enums :key #'proto-name :test #'string=)
111         :messages (delete-duplicates msgs :key #'proto-name :test #'string=)
112         :fields   fields))))
113
114 ;; Returns a field, (optionally) an inner message, and (optionally) an inner enum
115 (defun slot-to-protobuf-field (class slot index slots
116                                &key slot-filter type-filter enum-filter value-filter)
117   "Given a CLOS slot, return a Protobufs model object for it."
118   (when (or (null slot-filter)
119             (funcall slot-filter slot slots))
120     (multiple-value-bind (expanded-type unexpanded-type)
121        (find-slot-definition-type class slot)
122       (multiple-value-bind (type pclass packed enums)
123           (clos-type-to-protobuf-type expanded-type type-filter enum-filter)
124         (multiple-value-bind (reqd vectorp)
125             (clos-type-to-protobuf-required (find-slot-definition-type class slot) type-filter)
126           (let* ((ename (and enums
127                              (if (and unexpanded-type (symbolp unexpanded-type))
128                                (symbol-name unexpanded-type)
129                                (format nil "~A-~A" 'enum (slot-definition-name slot)))))
130                  (etype (and enums
131                              (if (and unexpanded-type (symbolp unexpanded-type))
132                                unexpanded-type
133                                (intern ename (symbol-package (slot-definition-name slot))))))
134                  (enum  (and enums
135                              (let* ((names (mapcar #'enum-name->proto enums))
136                                     (prefix (and (> (length names) 1)
137                                                  (subseq (first names)
138                                                          0 (mismatch (first names) (car (last names)))))))
139                                (when (and prefix (> (length prefix) 2)
140                                           (every #'(lambda (name) (starts-with name prefix)) names))
141                                  (setq names (mapcar #'(lambda (name) (subseq name (length prefix))) names)))
142                                (unless (and unexpanded-type (symbolp unexpanded-type))
143                                  #+ignore         ;this happens constantly, the warning is not useful
144                                  (protobufs-warn "Use DEFTYPE to define a MEMBER type instead of directly using ~S"
145                                                  expanded-type))
146                                (make-instance 'protobuf-enum
147                                  :class  etype
148                                  :name   (class-name->proto ename)
149                                  :values (loop for name in names
150                                                for val in enums
151                                                for index upfrom 0
152                                                collect (make-instance 'protobuf-enum-value
153                                                          :name name
154                                                          :index index
155                                                          :value val))))))
156                  (default (if (slot-definition-initfunction slot)
157                             (clos-init-to-protobuf-default
158                              (slot-definition-initform slot) expanded-type value-filter)
159                             (if (eq reqd :repeated)
160                               (if vectorp $empty-vector $empty-list)
161                               $empty-default)))
162                  (field   (make-instance 'protobuf-field
163                             :name  (slot-name->proto (slot-definition-name slot))
164                             :type  (if enum (class-name->proto ename) type)
165                             :class (if enum etype pclass)
166                             :required reqd
167                             :index  index
168                             :value  (slot-definition-name slot)
169                             :reader (let ((reader (find-slot-definition-reader class slot)))
170                                       ;; Only use the reader if it is "interesting"
171                                       (unless (string= (symbol-name reader)
172                                                        (format nil "~A-~A" 
173                                                                (class-name class) (slot-definition-name slot)))
174                                         reader))
175                             :default default
176                             :packed  packed)))
177             (values field nil enum)))))))
178
179 (defun find-slot-definition-type (class slotd)
180   "Given a class and a slot descriptor, find the \"best\" type definition for the slot."
181   (let* ((slot-name    (slot-definition-name slotd))
182          (direct-slotd (some #'(lambda (c)
183                                  (find slot-name (class-direct-slots c) :key #'slot-definition-name))
184                              (class-precedence-list class))))
185     (if direct-slotd
186       ;; The direct slotd will have an unexpanded definition
187       ;; Prefer it for 'list-of' so we can get the base type
188       (let ((type (slot-definition-type direct-slotd))
189             (quux-list-of (and (find-package :quux)
190                                (intern "LIST-OF" (find-package :quux)))))
191         (values (if (and (listp type) (member (car type) `(list-of vector-of ,quux-list-of)))
192                   type
193                   (slot-definition-type slotd))
194                 (if (symbolp type)
195                   type
196                   (when (and (listp type)
197                              (eq (car type) 'or)
198                              (member 'null (cdr type)))
199                     (find-if-not #'(lambda (s) (eq s 'null)) (cdr type))))))
200       (values (slot-definition-type slotd) nil))))
201
202 (defun find-slot-definition-reader (class slotd)
203   "Given a class and a slot descriptor, find the name of a reader method for the slot."
204   (let* ((slot-name    (slot-definition-name slotd))
205          (direct-slotd (some #'(lambda (c)
206                                  (find slot-name (class-direct-slots c) :key #'slot-definition-name))
207                              (class-precedence-list class))))
208     (and direct-slotd (first (slot-definition-readers direct-slotd)))))
209
210 (defun clos-type-to-protobuf-type (type &optional type-filter enum-filter)
211   "Given a Lisp type, returns a Protobuf type, a class or primitive type,
212    whether or not to pack the field, and (optionally) a set of enum values."
213   (let ((type (if type-filter (funcall type-filter type) type))
214         ;; Hideous, but useful, kludge for those of us at ITA-by-Google
215         (quux-list-of (and (find-package :quux)
216                            (intern "LIST-OF" (find-package :quux)))))
217     (flet ((type->protobuf-type (type)
218              (case type
219                ((int32)    (values "int32" :int32))
220                ((int64)    (values "int64" :int64))
221                ((uint32)   (values "uint32" :uint32))
222                ((uint64)   (values "uint64" :uint64))
223                ((sint32)   (values "sint32" :sint32))
224                ((sint64)   (values "sint64" :sint64))
225                ((fixed32)  (values "fixed32" :fixed32))
226                ((fixed64)  (values "fixed64" :fixed64))
227                ((sfixed32) (values "sfixed32" :sfixed32))
228                ((sfixed64) (values "sfixed64" :sfixed64))
229                ((integer)  (values "int64" :int64))
230                ((single-float float)
231                 (values "float" :float))
232                ((double-float)
233                 (values "double" :double))
234                ((boolean)
235                 (values "bool" :bool))
236                ((symbol keyword)
237                 (values "string" :symbol))
238                (otherwise
239                 (cond ((ignore-errors
240                         (or (eql type 'symbol)
241                             (subtypep type '(or string character))))
242                        (values "string" :string))
243                       ((ignore-errors
244                         (subtypep type 'byte-vector))
245                        (values "bytes" :bytes))
246                       (t
247                        (values (class-name->proto type) type)))))))
248       (if (listp type)
249         (destructuring-bind (head &rest tail) type
250           (case head
251             ((or)
252              (when (or (> (length tail) 2)
253                        (not (member 'null tail)))
254                (protobufs-warn "The OR type ~S is too complicated, proceeding anyway" type))
255              (if (eq (first tail) 'null)
256                (clos-type-to-protobuf-type (second tail))
257                (clos-type-to-protobuf-type (first tail))))
258             ((and)
259              (cond ((and quux-list-of
260                          (ignore-errors
261                           (subtypep type `(,quux-list-of t))))
262                     ;; Special knowledge of 'quux:list-of', which uses (and list (satisfies <t>))
263                     (let* ((satisfies (find 'satisfies tail :key #'car))
264                            (pred (second satisfies))
265                            (type (if (starts-with (string pred) "LIST-OF-")
266                                    (intern (subseq (string pred) #.(length "LIST-OF-")) (symbol-package pred))
267                                    pred)))
268                       (multiple-value-bind (type class)
269                           (type->protobuf-type type)
270                         (values type class (packed-type-p class)))))
271                    (t
272                     (let ((new-tail (remove-if #'(lambda (x) (and (listp x) (eq (car x) 'satisfies))) tail)))
273                       (when (> (length new-tail) 1)
274                         (protobufs-warn "The AND type ~S is too complicated, proceeding anyway" type))
275                       (type->protobuf-type (first tail))))))
276             ((member)                           ;maybe generate an enum type
277              (if (or (equal type '(member t nil))
278                      (equal type '(member nil t)))
279                (values "bool" :bool)
280                (let ((values (if enum-filter (funcall enum-filter tail) tail)))
281                  (cond ((every #'(lambda (x)
282                                    (or (null x) (characterp x) (stringp x))) values)
283                         (values "string" :string))
284                        ((every #'(lambda (x)
285                                    (or (null x) (and (integerp x) (>= x 0)))) values)
286                         (values "uint32" :uint32))
287                        ((every #'(lambda (x)
288                                    (or (null x) (integerp x))) values)
289                         (values "int32" :int32))
290                        ((every #'(lambda (x) (symbolp x)) values)
291                         (let ((values (remove-if #'null values)))
292                           (values (class-name->proto (format nil "~A" type))
293                                   type
294                                   nil           ;don't pack enums
295                                   (if enum-filter (funcall enum-filter values) values))))
296                        (t
297                         (error "The MEMBER type ~S is too complicated" type))))))
298             ((list-of vector-of)
299              (multiple-value-bind (type class)
300                  (type->protobuf-type (first tail))
301                (values type class (packed-type-p class))))
302             ((integer)
303              (let ((lo (or (first tail) '*))
304                    (hi (or (second tail) '*)))
305                (if (or (eq lo '*) (< lo 0))
306                  (if (eq hi '*)
307                    (values "int64" :int64)
308                    (if (<= (integer-length hi) 32)
309                      (values "int32" :int32)
310                      (values "int64" :int64)))
311                  (if (eq hi '*)
312                    (values "uint64" :uint64)
313                    (if (<= (integer-length hi) 32)
314                      (values "uint32" :uint32)
315                      (values "uint64" :uint64))))))
316             ((signed-byte)
317              (let ((len (first tail)))
318                (if (<= len 32)
319                  (values "int32" :int32)
320                  (values "int64" :int64))))
321             ((unsigned-byte)
322              (let ((len (first tail)))
323                (if (<= len 32)
324                  (values "uint32" :uint32)
325                  (values "uint64" :uint64))))
326             ((float single-float double-float)
327              (type->protobuf-type head))
328             (otherwise
329              (if (eq head quux-list-of)
330                (multiple-value-bind (type class)
331                    (type->protobuf-type (first tail))
332                  (values type class (packed-type-p class)))
333                (type->protobuf-type type)))))
334         (type->protobuf-type type)))))
335
336 (defun packed-type-p (type)
337   "Returns true if the given Protobufs type can use a packed field."
338   (not (null (member type '(:int32 :int64 :uint32 :uint64 :sint32 :sint64
339                             :fixed32 :fixed64 :sfixed32 :sfixed64
340                             :bool :float :double)))))
341
342 (defun clos-type-to-protobuf-required (type &optional type-filter)
343   "Given a Lisp type, returns a \"cardinality\": :required, :optional or :repeated.
344    If the sceond returned value is true, it's a repeated field that should use a vector."
345   (let ((type (if type-filter (funcall type-filter type) type))
346         (quux-list-of (and (find-package :quux)
347                            (intern "LIST-OF" (find-package :quux)))))
348     (if (listp type)
349       (destructuring-bind (head &rest tail) type
350         (case head
351           ((or)
352            (let ((optional (member 'null tail))
353                  (repeated (find-if #'(lambda (r)
354                                         (eq (clos-type-to-protobuf-required r) :repeated)) tail)))
355              (if repeated
356                (clos-type-to-protobuf-required repeated)
357                (values (if optional :optional :required) nil))))
358           ((and)
359            (cond ((or (subtypep type '(list-of t))
360                       (and quux-list-of (subtypep type `(,quux-list-of t))))
361                   (values :repeated nil))
362                  ((subtypep type '(vector-of t))
363                   (values :repeated t))
364                  (t
365                   (values :required nil))))
366           ((member)
367            (if (or (equal type '(member t nil))
368                    (equal type '(member nil t)))
369              (values :required nil)
370              (values (if (member nil tail) :optional :required) nil)))
371           ((list-of)
372            (values :repeated nil))
373           ((vector-of)
374            (values :repeated t))
375           (otherwise
376            (if (eq head quux-list-of)
377              (values :repeated nil)
378              (values :required nil)))))
379       (values :required nil))))
380
381 (defun clos-init-to-protobuf-default (value type &optional value-filter)
382   "Given an initform and a Lisp type, returns a plausible default value.
383    Don't call this if the default is empty, because that will confuse 'nil' with 'unbound'."
384   (let ((value (if value-filter (funcall value-filter value) value)))
385     (and (constantp value)
386          (ignore-errors (typep value type))
387          (values value t))))
388
389 (defun protobuf-default-to-clos-init (default type)
390   "Given a Protobufs type and default, return a CLOS initform value.
391    Don't call this if the default is empty, because that will confuse 'nil' with 'unbound'."
392   (cond ((ignore-errors (typep default type))
393          default)
394         ((symbolp default)
395          (cond ((eq type :bool)
396                 (boolean-true-p default))
397                ;; If we've got a symbol, it must be to initialize an enum type
398                ;; whose values are represented by keywords in Lisp
399                (t (kintern (symbol-name default)))))
400         ((stringp default)
401          (cond ((eq type :bool)
402                 (boolean-true-p default))
403                ((member type '(:int32 :uint32 :int64 :uint64 :sint32 :sint64
404                                :fixed32 :sfixed32 :fixed64 :sfixed64))
405                 (let ((default (read-from-string default)))
406                   (and (integerp default) default)))
407                ((member type '(:float :double))
408                 (let ((default (read-from-string default)))
409                   (and (floatp default) default)))
410                (t default)))))
411
412 (defun boolean-true-p (x)
413   "Returns t or nil given a value that might be a boolean."
414   (etypecase x
415     ((member t nil) x)
416     (integer   (not (eql x 0)))
417     (character (char-equal x #\t))
418     (string    (or (string-equal x "true")
419                    (string-equal x "yes")
420                    (string-equal x "t")
421                    (string-equal x "1")))
422     (symbol    (string-equal (string x) "true"))))