]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - parser.lisp
Add a lighter weight version of 'list-of' just for Protobufs
[cl-protobufs.git] / parser.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 ;;; .proto file parsing
15
16 ;;; Parsing utilities
17
18 (declaim (inline proto-whitespace-char-p))
19 (defun proto-whitespace-char-p (ch)
20   (locally (declare (optimize (speed 3) (safety 0) (debug 0)))
21     (and ch (member ch '(#\space #\tab #\return #\newline)))))
22
23 (declaim (inline proto-eol-char-p))
24 (defun proto-eol-char-p (ch)
25   (locally (declare (optimize (speed 3) (safety 0) (debug 0)))
26     (and ch (member ch '(#\return #\newline)))))
27
28 (declaim (inline proto-token-char-p))
29 (defun proto-token-char-p (ch)
30   (locally (declare (optimize (speed 3) (safety 0) (debug 0)))
31     (and ch (or (alpha-char-p ch)
32                 (digit-char-p ch)
33                 (member ch '(#\_ #\.))))))
34
35
36 (defun skip-whitespace (stream)
37   "Skip all the whitespace characters that are coming up in the stream."
38   (loop for ch = (peek-char nil stream nil)
39         until (or (null ch) (not (proto-whitespace-char-p ch)))
40         do (read-char stream nil)))
41
42 ;;--- Collect the comment so we can attach it to its associated object
43 (defun maybe-skip-comments (stream)
44   "If what appears next in the stream is a comment, skip it and any following comments,
45    then skip any following whitespace."
46   (loop
47     (unless (eql (peek-char nil stream nil) #\/)
48       (return)
49       (read-char stream)
50       (case (peek-char nil stream nil)
51         ((#\/)
52          (skip-line-comment stream))
53         ((#\*)
54          (skip-block-comment stream))
55         (otherwise
56          (error "Found a '~C' at position ~D to start a comment, but no following '~C' or '~C'"
57                 #\/ (file-position stream) #\/ #\*)))))
58   (skip-whitespace stream))
59
60 (defun skip-line-comment (stream)
61   "Skip to the end of a line comment, that is, to the end of the line.
62    Then skip any following whitespace."
63   (loop for ch = (read-char stream nil)
64         until (or (null ch) (proto-eol-char-p ch)))
65   (skip-whitespace stream))
66
67 (defun skip-block-comment (stream)
68   "Skip to the end of a block comment, that is, until a '*/' is seen.
69    Then skip any following whitespace."
70   (loop for ch = (read-char stream nil)
71         do (cond ((null ch)
72                   (error "Premature end of file while skipping block comment"))
73                  ((and (eql ch #\*)
74                        (eql (peek-char nil stream nil) #\/))
75                   (read-char stream nil)
76                   (return))))
77   (skip-whitespace stream))
78
79
80 (defun expect-char (stream ch &optional within)
81   "Expect to see 'ch' as the next character in the stream; signal an error if it's not there.
82    Then skip all of the following whitespace."
83   (if (if (listp ch)
84         (member (peek-char nil stream) ch)
85         (eql (peek-char nil stream) ch))
86     (read-char stream)
87     (error "No '~C' found~@[ within '~A'~] at position ~D"
88            ch within (file-position stream)))
89   (skip-whitespace stream))
90
91
92 (defun parse-token (stream)
93   "Parse the next token in the stream, then skip the following whitespace.
94    The returned value is the token."
95   (when (proto-token-char-p (peek-char nil stream nil))
96     (loop for ch = (read-char stream nil)
97           for ch1 = (peek-char nil stream nil)
98           collect ch into token
99           until (or (null ch1) (not (proto-token-char-p ch1)))
100           finally (progn
101                     (skip-whitespace stream)
102                     (return (coerce token 'string))))))
103
104 (defun parse-string (stream)
105   "Parse the next quoted string in the stream, then skip the following whitespace.
106    The returned value is the string, without the quotation marks."
107   (loop with ch0 = (read-char stream nil)
108         for ch = (read-char stream nil)
109         until (or (null ch) (char= ch ch0))
110         collect ch into string
111         finally (progn
112                   (skip-whitespace stream)
113                   (return (coerce string 'string)))))
114
115 (defun parse-int (stream)
116   "Parse the next token in the stream as an integer, then skip the following whitespace.
117    The returned value is the integer."
118   (when (digit-char-p (peek-char nil stream nil))
119     (loop for ch = (read-char stream nil)
120           for ch1 = (peek-char nil stream nil)
121           collect ch into token
122           until (or (null ch1) (not (digit-char-p ch1)))
123           finally (progn
124                     (skip-whitespace stream)
125                     (return (parse-integer (coerce token 'string)))))))
126
127 (defun parse-float (stream)
128   "Parse the next token in the stream as a float, then skip the following whitespace.                                     The returned value is the float."
129   (when (let ((ch (peek-char nil stream nil)))
130             (or (digit-char-p ch) (eql ch #\-)))
131     (let ((token (parse-token stream)))
132       (when token
133         (skip-whitespace stream)
134         (coerce (read-from-string token) 'float)))))
135
136
137 ;;; The parser itself
138
139 (defun parse-protobuf-from-file (filename)
140   "Parses the named file as a .proto file, and returns the Protobufs schema."
141   (with-open-file (stream filename
142                    :direction :input
143                    :external-format :utf-8
144                    :element-type 'character)
145     (parse-protobuf-from-stream stream
146                                 :name  (class-name->proto (pathname-name (pathname stream)))
147                                 :class (pathname-name (pathname stream)))))
148
149 ;; The syntax for Protocol Buffers is so simple that it doesn't seem worth
150 ;; writing a sophisticated parser
151 ;; Note that we don't put the result into *all-protobufs*; do that at a higher level
152 (defun parse-protobuf-from-stream (stream &key name class)
153   "Parses a top-level .proto file from the stream 'stream'.
154    Returns the protobuf schema that describes the .proto file."
155   (let* ((protobuf   (make-instance 'protobuf
156                        :class class
157                        :name  name))
158          (*protobuf* protobuf)
159          (*protobuf-package* nil))
160     (loop
161       (skip-whitespace stream)
162       (maybe-skip-comments stream)
163       (let ((char (peek-char nil stream nil)))
164         (cond ((null char)
165                (return-from parse-protobuf-from-stream protobuf))
166               ((proto-token-char-p char)
167                (let ((token (parse-token stream)))
168                  (cond ((string= token "syntax")
169                         (parse-proto-syntax stream protobuf))
170                        ((string= token "package")
171                         (parse-proto-package stream protobuf))
172                        ((string= token "import")
173                         (parse-proto-import stream protobuf))
174                        ((string= token "option")
175                         (parse-proto-option stream protobuf))
176                        ((string= token "enum")
177                         (parse-proto-enum stream protobuf))
178                        ((string= token "message")
179                         (parse-proto-message stream protobuf))
180                        ((string= token "service")
181                         (parse-proto-service stream protobuf)))))
182               (t
183                (error "Syntax error at position ~D" (file-position stream))))))))
184
185 (defun parse-proto-syntax (stream protobuf &optional (terminator #\;))
186   "Parse a Protobufs syntax line from 'stream'.
187    Updates the 'protobuf' object to use the syntax."
188   (let ((syntax (prog1 (parse-token stream)
189                   (expect-char stream terminator "syntax")
190                   (maybe-skip-comments stream))))
191     (setf (proto-syntax protobuf) syntax)))
192
193 (defun parse-proto-package (stream protobuf &optional (terminator #\;))
194   "Parse a Protobufs package line from 'stream'.
195    Updates the 'protobuf' object to use the package."
196   (let* ((package  (prog1 (substitute #\- #\_ (parse-token stream))
197                      (expect-char stream terminator "package")
198                      (maybe-skip-comments stream)))
199          (lisp-pkg (or (find-package package)
200                        (find-package (string-upcase package)))))
201     (setq *protobuf-package* lisp-pkg)
202     (setf (proto-package protobuf) package)))
203
204 (defun parse-proto-import (stream protobuf &optional (terminator #\;))
205   "Parse a Protobufs import line from 'stream'.
206    Updates the 'protobuf' object to use the package."
207   (let ((import (prog1 (parse-string stream)
208                   (expect-char stream terminator "package")
209                   (maybe-skip-comments stream))))
210     (setf (proto-imports protobuf) (nconc (proto-imports protobuf) (list import)))))
211
212 (defun parse-proto-option (stream protobuf &optional (terminator #\;))
213   "Parse a Protobufs option from 'stream'.
214    Updates the 'protobuf' (or message, service, RPC) to have the option."
215   (let* ((key (prog1 (parse-token stream)
216                 (expect-char stream #\= "option")))
217          (val (prog1 (if (eql (peek-char nil stream nil) #\")
218                        (parse-string stream)
219                        (parse-token stream))
220                 (expect-char stream terminator "option")
221                 (maybe-skip-comments stream)))
222          (option (make-instance 'protobuf-option
223                    :name  key
224                    :value val)))
225     (cond (protobuf
226            (setf (proto-options protobuf) (nconc (proto-options protobuf) (list option)))
227            (when (and (string= key "optimize_for")
228                       (typep protobuf 'protobuf))
229              (let ((value (cond ((string= val "SPEED") :speed)
230                                 ((string= val "CODE_SIZE") :space)
231                                 (t nil))))
232                (setf (proto-optimize protobuf) value))))
233           (t
234            ;; If nothing to graft the option into, just return it as the value
235            option))))
236
237
238 (defun parse-proto-enum (stream protobuf)
239   "Parse a Protobufs enum from 'stream'.
240    Updates the 'protobuf' or 'protobuf-message' object to have the enum."
241   (let* ((name (prog1 (parse-token stream)
242                  (expect-char stream #\{ "enum")
243                  (maybe-skip-comments stream)))
244          (enum (make-instance 'protobuf-enum
245                  :class (proto->class-name name *protobuf-package*)
246                  :name name)))
247     (loop
248       (let ((name (parse-token stream)))
249         (when (null name)
250           (expect-char stream #\} "enum")
251           (maybe-skip-comments stream)
252           (setf (proto-enums protobuf) (nconc (proto-messages protobuf) (list enum)))
253           (let ((type (find-option enum "lisp_name")))
254             (when type
255               (setf (proto-class enum) (make-lisp-symbol type))))
256           (let ((alias (find-option enum "lisp_alias")))
257             (when alias
258               (setf (proto-alias-for enum) (make-lisp-symbol alias))))
259           (return-from parse-proto-enum))
260         (if (string= name "option")
261           (parse-proto-option stream enum #\;)
262           (parse-proto-enum-value stream enum name))))))
263
264 (defun parse-proto-enum-value (stream enum name)
265   "Parse a Protobufs enum vvalue from 'stream'.
266    Updates the 'protobuf-enum' object to have the enum value."
267   (expect-char stream #\= "enum")
268   (let* ((idx  (prog1 (parse-int stream)
269                  (expect-char stream #\; "enum")
270                  (maybe-skip-comments stream)))
271          (value (make-instance 'protobuf-enum-value
272                   :name  name
273                   :index idx
274                   :value (proto->enum-name name *protobuf-package*))))
275     (setf (proto-values enum) (nconc (proto-values enum) (list value)))))
276
277
278 (defun parse-proto-message (stream protobuf)
279   "Parse a Protobufs message from 'stream'.
280    Updates the 'protobuf' or 'protobuf-message' object to have the message."
281   (let* ((name (prog1 (parse-token stream)
282                  (expect-char stream #\{ "message")
283                  (maybe-skip-comments stream)))
284          (message (make-instance 'protobuf-message
285                     :class (proto->class-name name *protobuf-package*)
286                     :name name)))
287     (loop
288       (let ((token (parse-token stream)))
289         (when (null token)
290           (expect-char stream #\} "message")
291           (maybe-skip-comments stream)
292           (setf (proto-messages protobuf) (nconc (proto-messages protobuf) (list message)))
293           (let ((type (find-option message "lisp_name")))
294             (when type
295               (setf (proto-class message) (make-lisp-symbol type))))
296           (let ((alias (find-option message "lisp_alias")))
297             (when alias
298               (setf (proto-alias-for message) (make-lisp-symbol alias))))
299           (return-from parse-proto-message))
300         (cond ((string= token "enum")
301                (parse-proto-enum stream message))
302               ((string= token "message")
303                (parse-proto-message stream message))
304               ((string= token "option")
305                (parse-proto-option stream message #\;))
306               ((member token '("required" "optional" "repeated") :test #'string=)
307                (parse-proto-field stream message token))
308               (t
309                (error "Unrecognized token ~A at position ~D"
310                       token (file-position stream))))))))
311
312 (defun parse-proto-field (stream message required)
313   "Parse a Protobufs field from 'stream'.
314    Updates the 'protobuf-message' object to have the field."
315   (let* ((type (parse-token stream))
316          (name (prog1 (parse-token stream)
317                  (expect-char stream #\= "message")))
318          (idx  (parse-int stream))
319          (opts (prog1 (parse-proto-field-options stream)
320                  (expect-char stream #\; "message")
321                  (maybe-skip-comments stream)))
322          (dflt   (find-option opts "default"))
323          (packed (find-option opts "packed"))
324          (ptype  (if (member type '("int32" "int64" "uint32" "uint64" "sint32" "sint64"
325                                     "fixed32" "fixed64" "sfixed32" "sfixed64"
326                                     "string" "bytes" "bool" "float" "double") :test #'string=)
327                    (kintern type)
328                    type))
329          (class  (if (keywordp ptype) ptype (proto->class-name type *protobuf-package*)))
330          (field  (make-instance 'protobuf-field
331                    :name  name
332                    :value (proto->slot-name name *protobuf-package*)
333                    :type  type
334                    :class class
335                    ;; One of :required, :optional or :repeated
336                    :required (kintern required)
337                    :index idx
338                    :default dflt
339                    :packed  (and packed (string= packed "true")))))
340     (let ((slot (find-option opts "lisp_name")))
341       (when slot
342         (setf (proto-value field) (make-lisp-symbol type))))
343     (setf (proto-fields message) (nconc (proto-fields message) (list field)))))
344
345 (defun parse-proto-field-options (stream)
346   "Parse any options in a Protobufs field from 'stream'.
347    Returns a list of 'protobuf-option' objects."
348   (with-collectors ((options collect-option))
349     (loop
350       (unless (eql (peek-char nil stream) #\[)
351         (return-from parse-proto-field-options options))
352       (expect-char stream #\[ "message")
353       (collect-option (parse-proto-option stream nil #\])))
354     options))
355
356
357 (defun parse-proto-service (stream protobuf)
358   "Parse a Protobufs service from 'stream'.
359    Updates the 'protobuf-message' object to have the service."
360   (let* ((name (prog1 (parse-token stream)
361                  (expect-char stream #\{ "service")
362                  (maybe-skip-comments stream)))
363          (service (make-instance 'protobuf-service
364                     :class (proto->class-name name *protobuf-package*)
365                     :name name)))
366     (loop
367       (let ((token (parse-token stream)))
368         (when (null token)
369           (expect-char stream #\} "service")
370           (maybe-skip-comments stream)
371           (setf (proto-services protobuf) (nconc (proto-services protobuf) (list service)))
372           (return-from parse-proto-service))
373         (cond ((string= token "option")
374                (parse-proto-option stream service #\;))
375               ((string= token "rpc")
376                (parse-proto-rpc stream service token))
377               (t
378                (error "Unrecognized token ~A at position ~D"
379                       token (file-position stream))))))))
380
381 (defun parse-proto-rpc (stream service rpc)
382   "Parse a Protobufs enum vvalue from 'stream'.
383    Updates the 'protobuf-enum' object to have the enum value."
384   (declare (ignore rpc))
385   (let* ((name (parse-token stream))
386          (in   (prog2 (expect-char stream #\( "service")
387                    (parse-token stream)
388                  (expect-char stream #\) "service")))
389          (ret  (parse-token stream))
390          (out  (prog2 (expect-char stream #\( "service")
391                    (parse-token stream)
392                  (expect-char stream #\) "service")))
393          (opts (let ((opts (parse-proto-rpc-options stream)))
394                  (when (or (null opts) (eql (peek-char nil stream) #\;))
395                    (expect-char stream #\; "service"))
396                  (maybe-skip-comments stream)
397                  opts))
398          (rpc (make-instance 'protobuf-rpc
399                 :class (proto->class-name name *protobuf-package*)
400                 :name  name
401                 :input-type  (proto->class-name in *protobuf-package*)
402                 :input-name  in
403                 :output-type (proto->class-name out *protobuf-package*)
404                 :output-name out
405                 :options opts)))
406     (let ((name (find-option rpc "lisp_name")))
407       (when name
408         (setf (proto-function rpc) (make-lisp-symbol name))))
409     (assert (string= ret "returns") ()
410             "Syntax error in 'message' at position ~D" (file-position stream))
411     (setf (proto-rpcs service) (nconc (proto-rpcs service) (list rpc)))))
412
413 (defun parse-proto-rpc-options (stream)
414   "Parse any options in a Protobufs RPC from 'stream'.
415    Returns a list of 'protobuf-option' objects."
416   (when (eql (peek-char nil stream) #\{)
417     (expect-char stream #\{ "service")
418     (maybe-skip-comments stream)
419     (with-collectors ((options collect-option))
420       (loop
421         (when (eql (peek-char nil stream) #\})
422           (return))
423         (assert (string= (parse-token stream) "option") ()
424                 "Syntax error in 'message' at position ~D" (file-position stream))
425         (collect-option (parse-proto-option stream nil #\;)))
426       (expect-char stream #\} "service")
427       (maybe-skip-comments stream)
428       options)))