]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - parser.lisp
printer.lisp: better preserve proto names
[cl-protobufs.git] / parser.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 ;;; .proto file parsing
15
16 ;;; Parsing utilities
17
18 (declaim (inline proto-whitespace-char-p))
19 (defun proto-whitespace-char-p (ch)
20   (declare #.$optimize-fast-unsafe)
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   (declare #.$optimize-fast-unsafe)   
26   (and ch (member ch '(#\return #\newline))))
27
28 (declaim (inline proto-token-char-p))
29 (defun proto-token-char-p (ch)
30   (declare #.$optimize-fast-unsafe)
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 (defun expect-char (stream char &optional chars within)
43   "Expect to see 'char' as the next character in the stream; signal an error if it's not there.
44    Then skip all of the following whitespace.
45    The return value is the character that was eaten."
46   (let (ch)
47     (if (if (listp char)
48           (member (peek-char nil stream nil) char)
49           (eql (peek-char nil stream nil) char))
50       (setq ch (read-char stream))
51       (error "No '~C' found~@[ within '~A'~] at position ~D"
52              char within (file-position stream)))
53     (maybe-skip-chars stream chars)
54     ch))
55
56 (defun maybe-skip-chars (stream chars)
57   "Skip some optional characters in the stream,
58    then skip all of the following whitespace."
59   (skip-whitespace stream)
60   (when chars
61     (loop
62       (let ((ch (peek-char nil stream nil)))
63         (when (or (null ch) (not (member ch chars)))
64           (skip-whitespace stream)
65           (return-from maybe-skip-chars)))
66       (read-char stream))))
67
68
69 ;;--- Collect the comment so we can attach it to its associated object
70 (defun maybe-skip-comments (stream)
71   "If what appears next in the stream is a comment, skip it and any following comments,
72    then skip any following whitespace."
73   (loop
74     (let ((ch (peek-char nil stream nil)))
75       (when (or (null ch) (not (eql ch #\/)))
76         (return-from maybe-skip-comments))
77       (read-char stream)
78       (case (peek-char nil stream nil)
79         ((#\/)
80          (skip-line-comment stream))
81         ((#\*)
82          (skip-block-comment stream))
83         ((nil)
84          (skip-whitespace stream)
85          (return-from maybe-skip-comments))
86         (otherwise
87          (error "Found a '~C' at position ~D to start a comment, but no following '~C' or '~C'"
88                 #\/ (file-position stream) #\/ #\*))))))
89
90 (defun skip-line-comment (stream)
91   "Skip to the end of a line comment, that is, to the end of the line.
92    Then skip any following whitespace."
93   (loop for ch = (read-char stream nil)
94         until (or (null ch) (proto-eol-char-p ch)))
95   (skip-whitespace stream))
96
97 (defun skip-block-comment (stream)
98   "Skip to the end of a block comment, that is, until a '*/' is seen.
99    Then skip any following whitespace."
100   (loop for ch = (read-char stream nil)
101         do (cond ((null ch)
102                   (error "Premature end of file while skipping block comment"))
103                  ((and (eql ch #\*)
104                        (eql (peek-char nil stream nil) #\/))
105                   (read-char stream nil)
106                   (return))))
107   (skip-whitespace stream))
108
109
110 (defun parse-token (stream &optional additional-chars)
111   "Parse the next token in the stream, then skip the following whitespace.
112    The returned value is the token."
113   (when (let ((ch (peek-char nil stream nil)))
114           (or (proto-token-char-p ch) (member ch additional-chars)))
115     (loop for ch = (read-char stream nil)
116           for ch1 = (peek-char nil stream nil)
117           collect ch into token
118           until (or (null ch1)
119                     (and (not (proto-token-char-p ch1))
120                          (not (member ch1 additional-chars))))
121           finally (progn
122                     (skip-whitespace stream)
123                     (return (coerce token 'string))))))
124
125 (defun parse-parenthesized-token (stream)
126   "Parse the next token in the stream, then skip the following whitespace.
127    The token might be surrounded by parentheses.
128    The returned value is the token."
129   (let ((left (peek-char nil stream nil)))
130     (when (eql left #\()
131       (read-char stream))
132     (when (proto-token-char-p (peek-char nil stream nil))
133       (loop for ch = (read-char stream nil)
134             for ch1 = (peek-char nil stream nil)
135             collect ch into token
136             until (or (null ch1) (not (proto-token-char-p ch1)))
137             finally (progn
138                       (skip-whitespace stream)
139                       (when (eql left #\()
140                         (expect-char stream #\)))
141                       (return (coerce token 'string)))))))
142
143 (defun parse-token-or-string (stream)
144   (if (eql (peek-char nil stream nil) #\")
145     (values (parse-string stream) 'string)
146     (values (parse-token stream) 'symbol)))
147
148 (defun parse-string (stream)
149   "Parse the next quoted string in the stream, then skip the following whitespace.
150    The returned value is the string, without the quotation marks."
151   (loop with ch0 = (read-char stream nil)
152         for ch = (read-char stream nil)
153         until (or (null ch) (char= ch ch0))
154         when (eql ch #\\)
155           do (setq ch (unescape-char stream))
156         collect ch into string
157         finally (progn
158                   (skip-whitespace stream)
159                   (if (eql (peek-char nil stream nil) ch0)
160                     ;; If the next character is a quote character, that means
161                     ;; we should go parse another string and concatenate it
162                     (return (strcat (coerce string 'string) (parse-string stream)))
163                     (return (coerce string 'string))))))
164
165 (defun unescape-char (stream)
166   "Parse the next \"escaped\" character from the stream."
167   (let ((ch (read-char stream nil)))
168     (assert (not (null ch)) ()
169             "End of stream reached while reading escaped character")
170     (case ch
171       ((#\x)
172        ;; Two hex digits
173        (let* ((d1 (digit-char-p (read-char stream) 16))
174               (d2 (digit-char-p (read-char stream) 16)))
175          (code-char (+ (* d1 16) d2))))
176       ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
177        (if (not (digit-char-p (peek-char nil stream nil)))
178          #\null
179          ;; Three octal digits
180          (let* ((d1 (digit-char-p ch 8))
181                 (d2 (digit-char-p (read-char stream) 8))
182                 (d3 (digit-char-p (read-char stream) 8)))
183            (code-char (+ (* d1 64) (* d2 8) d3)))))
184       ((#\t) #\tab)
185       ((#\n) #\newline)
186       ((#\r) #\return)
187       ((#\f) #\page)
188       ((#\b) #\backspace)
189       ((#\a) #\bell)
190       ((#\e) #\esc)
191       (otherwise ch))))
192
193 (defun escape-char (ch)
194   "The inverse of 'unescape-char', for printing."
195   (if (and (standard-char-p ch) (graphic-char-p ch))
196     ch
197     (case ch
198       ((#\null)      "\\0")
199       ((#\tab)       "\\t")
200       ((#\newline)   "\\n")
201       ((#\return)    "\\r")
202       ((#\page)      "\\f")
203       ((#\backspace) "\\b")
204       ((#\bell)      "\\a")
205       ((#\esc)       "\\e")
206       (otherwise
207        (format nil "\\x~2,'0X" (char-code ch))))))
208
209 (defun parse-signed-int (stream)
210   "Parse the next token in the stream as an integer, then skip the following whitespace.
211    The returned value is the integer."
212   (let* ((sign (if (eql (peek-char nil stream nil) #\-)
213                  (progn (read-char stream) -1)
214                  1))
215          (int  (parse-unsigned-int stream)))
216     (* int sign)))
217
218 (defun parse-unsigned-int (stream)
219   "Parse the next token in the stream as an integer, then skip the following whitespace.
220    The returned value is the integer."
221   (when (digit-char-p (peek-char nil stream nil))
222     (loop for ch = (read-char stream nil)
223           for ch1 = (peek-char nil stream nil)
224           collect ch into token
225           until (or (null ch1) (and (not (digit-char-p ch1)) (not (eql ch #\x))))
226           finally (progn
227                     (skip-whitespace stream)
228                     (let ((token (coerce token 'string)))
229                       (if (starts-with token "0x")
230                         (let ((*read-base* 16))
231                           (return (parse-integer (subseq token 2))))
232                         (return (parse-integer token))))))))
233
234 (defun parse-float (stream)
235   "Parse the next token in the stream as a float, then skip the following whitespace.
236    The returned value is the float."
237   (let ((number (parse-number stream)))
238     (when number
239       (coerce number 'float))))
240
241 (defun parse-number (stream)
242   (when (let ((ch (peek-char nil stream nil)))
243           (or (digit-char-p ch) (member ch '(#\- #\+ #\.))))
244     (let ((token (parse-token stream '(#\- #\+ #\.))))
245       (when token
246         (skip-whitespace stream)
247         (parse-numeric-string token)))))
248
249 (defun parse-numeric-string (string)
250   (cond ((starts-with string "0x")
251          (parse-integer (subseq string 2) :radix 16))
252         ((starts-with string "-0x")
253          (- (parse-integer (subseq string 3) :radix 16)))
254         (t
255          (read-from-string string))))
256
257
258 ;;; The parser itself
259
260 (defun parse-schema-from-file (filename &key name class (conc-name ""))
261   "Parses the named file as a .proto file, and returns the Protobufs schema."
262   (with-open-file (stream filename
263                    :direction :input
264                    :external-format :utf-8
265                    :element-type 'character)
266     (let ((*protobuf-pathname* (pathname stream))
267           (*compile-file-pathname* (pathname stream))
268           (*compile-file-truename* (truename stream)))
269       (parse-schema-from-stream stream
270                                 :name  (or name (class-name->proto (pathname-name (pathname stream))))
271                                 :class (or class (kintern (pathname-name (pathname stream))))
272                                 :conc-name conc-name))))
273
274 ;; 'with-proto-source-location' counts on this being a 3-element list
275 ;; Yeah, it's a kludge, but we really don't need anything complicated for this
276 (defstruct (source-location (:type list) (:constructor %make-source-location))
277   pathname
278   start-pos
279   end-pos)
280
281 (defun make-source-location (stream start end)
282   "Create a \"source locator\" for the stream at the current position.
283    With any luck, we can get meta-dot to pay attention to it."
284   (declare (ignore stream))
285   ;; Don't record source locations if we're not parsing from a file
286   (and *protobuf-pathname*
287        (%make-source-location :pathname *protobuf-pathname*
288                               :start-pos start :end-pos end)))
289
290 (defgeneric resolve-lisp-names (protobuf)
291   (:documentation
292    "Second pass of schema parsing which recursively resolves Protobuf type names
293     to Lisp type names in all messages and services contained within 'protobuf'.
294     No return value."))
295
296 ;; The syntax for Protocol Buffers is so simple that it doesn't seem worth
297 ;; writing a sophisticated parser
298 ;; Note that we don't put the result into *all-schemas*; that's done in 'define-schema'
299 (defun parse-schema-from-stream (stream &key name class (conc-name ""))
300   "Parses a top-level .proto file from the stream 'stream'.
301    Returns the protobuf schema that describes the .proto file."
302   (let* ((schema (make-instance 'protobuf-schema
303                    :class class
304                    :name  name))
305          (*protobuf* schema)
306          *protobuf-package*
307          (*protobuf-conc-name* conc-name))
308     (flet ((ensure-package ()
309              "Find a fallback for our Lisp package if we don't have an obvious one already.
310               * java_package
311               * *package*"
312              (unless *protobuf-package*
313                (let ((java-package (find-option schema "java_package")))
314                  (if java-package
315                      (set-lisp-package schema java-package)
316                      (setq *protobuf-package* *package*))))))
317       (loop
318         (skip-whitespace stream)
319         (maybe-skip-comments stream)
320         (let ((char (peek-char nil stream nil)))
321           (cond ((null char)
322                  (remove-options schema "lisp_package")
323                  (resolve-lisp-names schema)
324                  (return-from parse-schema-from-stream schema))
325                 ((proto-token-char-p char)
326                  (let ((token (parse-token stream)))
327                    (cond ((string= token "syntax")
328                           (parse-proto-syntax stream schema))
329                          ((string= token "package")
330                           (parse-proto-package stream schema))
331                          ((string= token "import")
332                           (parse-proto-import stream schema))
333                          ((string= token "option")
334                           (let* ((option (parse-proto-option stream schema))
335                                  (name   (and option (proto-name option)))
336                                  (value  (and option (proto-value option))))
337                             (when (and option (option-name= name "lisp_package"))
338                               (set-lisp-package schema value))))
339                          ((string= token "enum")
340                           (ensure-package)
341                           (parse-proto-enum stream schema))
342                          ((string= token "extend")
343                           (ensure-package)
344                           (parse-proto-extend stream schema))
345                          ((string= token "message")
346                           (ensure-package)
347                           (parse-proto-message stream schema))
348                          ((string= token "service")
349                           (ensure-package)
350                           (parse-proto-service stream schema)))))
351                 (t
352                  (error "Syntax error at position ~D" (file-position stream)))))))))
353
354 (defun set-lisp-package (schema lisp-package-name)
355   "Set the package for generated lisp names of 'schema'."
356   (check-type schema protobuf-schema)
357   (check-type lisp-package-name string)
358   (let ((package (or (find-proto-package lisp-package-name)
359                      ;; Try to put symbols into the right package
360                      (make-package (string-upcase lisp-package-name) :use ())
361                      *protobuf-package*)))
362     (setf (proto-lisp-package schema) lisp-package-name)
363     (setq *protobuf-package* package)))
364
365 (defmethod resolve-lisp-names ((schema protobuf-schema))
366   "Recursively resolves Protobuf type names to Lisp type names in the messages and services in 'schema'."
367   (map () #'resolve-lisp-names (proto-messages schema))
368   (map () #'resolve-lisp-names (proto-services schema)))
369
370 (defun parse-proto-syntax (stream schema &optional (terminator #\;))
371   "Parse a Protobufs syntax line from 'stream'.
372    Updates the 'protobuf-schema' object to use the syntax."
373   (let ((syntax (prog2 (expect-char stream #\= () "syntax")
374                     (parse-string stream)
375                   (expect-char stream terminator () "syntax")
376                   (maybe-skip-comments stream))))
377     (setf (proto-syntax schema) syntax)))
378
379 (defun parse-proto-package (stream schema &optional (terminator #\;))
380   "Parse a Protobufs package line from 'stream'.
381    Updates the 'protobuf-schema' object to use the package."
382   (check-type schema protobuf-schema)
383   (let* ((package  (prog1 (parse-token stream)
384                      (expect-char stream terminator () "package")
385                      (maybe-skip-comments stream)))
386          (lisp-pkg (or (proto-lisp-package schema)
387                        (substitute #\- #\_ package))))
388     (setf (proto-package schema) package)
389     (unless (proto-lisp-package schema)
390       (set-lisp-package schema lisp-pkg))))
391
392 (defun parse-proto-import (stream schema &optional (terminator #\;))
393   "Parse a Protobufs import line from 'stream'.
394    Updates the 'protobuf-schema' object to use the import."
395   (check-type schema protobuf-schema)
396   (let ((import (prog1 (parse-string stream)
397                   (expect-char stream terminator () "import")
398                   (maybe-skip-comments stream))))
399     (process-imports schema (list import))
400     (setf (proto-imports schema) (nconc (proto-imports schema) (list import)))))
401
402 (defun parse-proto-option (stream protobuf &optional (terminators '(#\;)))
403   "Parse a Protobufs option line from 'stream'.
404    Updates the 'protobuf-schema' (or message, service, method) to have the option."
405   (check-type protobuf (or null base-protobuf))
406   (let* (terminator
407          (key (prog1 (parse-parenthesized-token stream)
408                 (expect-char stream #\= () "option")))
409          (val (prog1 (let ((ch (peek-char nil stream nil)))
410                        (cond ((eql ch #\")
411                               (parse-string stream))
412                              ((or (digit-char-p ch) (member ch '(#\- #\+ #\.)))
413                               (parse-number stream))
414                              ((eql ch #\{)
415                               ;;---bwagner: This is incorrect
416                               ;;   We need to find the field name in the locally-extended version of
417                               ;;   google.protobuf.[File,Message,Field,Enum,EnumValue,Service,Method]Options
418                               ;;   and get its type
419                               (let ((message (find-message (or protobuf *protobuf*) key)))
420                                 (if message
421                                   ;; We've got a complex message as a value to an option
422                                   ;; This only shows up in custom options
423                                   (parse-text-format message :stream stream :parse-name nil)
424                                   ;; Who knows what to do? Skip the value
425                                   (skip-field stream))))
426                              (t (kintern (parse-token stream)))))
427                 (setq terminator (expect-char stream terminators () "option"))
428                 (maybe-skip-comments stream)))
429          (option (make-instance 'protobuf-option
430                    :name  key
431                    :value val)))
432     (cond (protobuf
433            (setf (proto-options protobuf) (nconc (proto-options protobuf) (list option)))
434            (values option terminator))
435           (t
436            ;; If nothing to graft the option into, just return it as the value
437            (values option terminator)))))
438
439
440 (defun parse-proto-enum (stream protobuf)
441   "Parse a Protobufs 'enum' from 'stream'.
442    Updates the 'protobuf-schema' or 'protobuf-message' object to have the enum."
443   (check-type protobuf (or protobuf-schema protobuf-message))
444   (let* ((loc  (file-position stream))
445          (name (prog1 (parse-token stream)
446                  (expect-char stream #\{ () "enum")
447                  (maybe-skip-comments stream)))
448          (enum (make-instance 'protobuf-enum
449                  :class (proto->class-name name *protobuf-package*)
450                  :name name
451                  :qualified-name (make-qualified-name protobuf name)
452                  :parent protobuf
453                  :source-location (make-source-location stream loc (i+ loc (length name))))))
454     (loop
455       (let ((name (parse-token stream)))
456         (when (null name)
457           (expect-char stream #\} '(#\;) "enum")
458           (maybe-skip-comments stream)
459           (setf (proto-enums protobuf) (nconc (proto-enums protobuf) (list enum)))
460           (let ((type (find-option enum "lisp_name")))
461             (when type
462               (setf (proto-class enum) (make-lisp-symbol type))))
463           (let ((alias (find-option enum "lisp_alias")))
464             (when alias
465               (setf (proto-alias-for enum) (make-lisp-symbol alias))))
466           (return-from parse-proto-enum enum))
467         (if (string= name "option")
468           (parse-proto-option stream enum)
469           (parse-proto-enum-value stream protobuf enum name))))))
470
471 (defun parse-proto-enum-value (stream protobuf enum name)
472   "Parse a Protobufs enum value from 'stream'.
473    Updates the 'protobuf-enum' object to have the enum value."
474   (declare (ignore protobuf))
475   (check-type enum protobuf-enum)
476   (expect-char stream #\= () "enum")
477   (let* ((idx  (prog1 (parse-signed-int stream)
478                  (expect-char stream #\; () "enum")
479                  (maybe-skip-comments stream)))
480          (value (make-instance 'protobuf-enum-value
481                   :name  name
482                   :qualified-name (make-qualified-name enum name)
483                   :index idx
484                   :value (proto->enum-name name *protobuf-package*)
485                   :parent enum)))
486     (setf (proto-values enum) (nconc (proto-values enum) (list value)))
487     value))
488
489
490 (defun parse-proto-message (stream protobuf &optional name)
491   "Parse a Protobufs 'message' from 'stream'.
492    Updates the 'protobuf-schema' or 'protobuf-message' object to have the message."
493   (check-type protobuf (or protobuf-schema protobuf-message))
494   (let* ((loc  (file-position stream))
495          (name (prog1 (or name (parse-token stream))
496                  (expect-char stream #\{ () "message")
497                  (maybe-skip-comments stream)))
498          (class (proto->class-name name *protobuf-package*))
499          (message (make-instance 'protobuf-message
500                     :class class
501                     :name  name
502                     :qualified-name (make-qualified-name protobuf name)
503                     :parent protobuf
504                     ;; Maybe force accessors for all slots
505                     :conc-name (conc-name-for-type class *protobuf-conc-name*)
506                     :source-location (make-source-location stream loc (i+ loc (length name)))))
507          (*protobuf* message))
508     (loop
509       (let ((token (parse-token stream)))
510         (when (null token)
511           (expect-char stream #\} '(#\;) "message")
512           (maybe-skip-comments stream)
513           (setf (proto-messages protobuf) (nconc (proto-messages protobuf) (list message)))
514           (let ((type (find-option message "lisp_name")))
515             (when type
516               (setf (proto-class message) (make-lisp-symbol type))))
517           (let ((alias (find-option message "lisp_alias")))
518             (when alias
519               (setf (proto-alias-for message) (make-lisp-symbol alias))))
520           (return-from parse-proto-message message))
521         (cond ((string= token "enum")
522                (parse-proto-enum stream message))
523               ((string= token "extend")
524                (parse-proto-extend stream message))
525               ((string= token "message")
526                (parse-proto-message stream message))
527               ((member token '("required" "optional" "repeated") :test #'string=)
528                (parse-proto-field stream message token))
529               ((string= token "option")
530                (parse-proto-option stream message))
531               ((string= token "extensions")
532                (parse-proto-extension stream message))
533               (t
534                (error "Unrecognized token ~A at position ~D"
535                       token (file-position stream))))))))
536
537 (defmethod resolve-lisp-names ((message protobuf-message))
538   "Recursively resolves protobuf type names to lisp type names in nested messages and fields of 'message'."
539   (map () #'resolve-lisp-names (proto-messages message))
540   (map () #'resolve-lisp-names (proto-fields message)))
541
542 (defun parse-proto-extend (stream protobuf)
543   "Parse a Protobufs 'extend' from 'stream'.
544    Updates the 'protobuf-schema' or 'protobuf-message' object to have the message."
545   (check-type protobuf (or protobuf-schema protobuf-message))
546   (let* ((loc  (file-position stream))
547          (name (prog1 (parse-token stream)
548                  (expect-char stream #\{ () "extend")
549                  (maybe-skip-comments stream)))
550          ;;---bwagner: Is 'extend' allowed to use a forward reference to a message?
551          (message (find-message protobuf name))
552          (extends (and message
553                        (make-instance 'protobuf-message
554                          :class (proto-class message)
555                          :name  (proto-name message)
556                          :qualified-name (proto-qualified-name message)
557                          :parent protobuf
558                          :alias-for (proto-alias-for message)
559                          :conc-name (proto-conc-name message)
560                          :enums    (copy-list (proto-enums message))
561                          :messages (copy-list (proto-messages message))
562                          :fields   (copy-list (proto-fields message))
563                          :extensions (copy-list (proto-extensions message))
564                          :message-type :extends         ;this message is an extension
565                          :source-location (make-source-location stream loc (i+ loc (length name))))))
566          (*protobuf* extends))
567     (assert message ()
568             "There is no message named ~A to extend" name)
569     (loop
570       (let ((token (parse-token stream)))
571         (when (null token)
572           (expect-char stream #\} '(#\;) "extend")
573           (maybe-skip-comments stream)
574           (setf (proto-messages protobuf) (nconc (proto-messages protobuf) (list extends)))
575           (setf (proto-extenders protobuf) (nconc (proto-extenders protobuf) (list extends)))
576           (let ((type (find-option extends "lisp_name")))
577             (when type
578               (setf (proto-class extends) (make-lisp-symbol type))))
579           (let ((alias (find-option extends "lisp_alias")))
580             (when alias
581               (setf (proto-alias-for extends) (make-lisp-symbol alias))))
582           (return-from parse-proto-extend extends))
583         (cond ((member token '("required" "optional" "repeated") :test #'string=)
584                (let ((field (parse-proto-field stream extends token message)))
585                  (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list field)))))
586               ((string= token "option")
587                (parse-proto-option stream extends))
588               (t
589                (error "Unrecognized token ~A at position ~D"
590                       token (file-position stream))))))))
591
592 (defun parse-proto-field (stream message required &optional extended-from)
593   "Parse a Protobufs field from 'stream'.
594    Updates the 'protobuf-message' object to have the field."
595   (check-type message protobuf-message)
596   (let ((type (parse-token stream)))
597     (if (string= type "group")
598       (parse-proto-group stream message required extended-from)
599       (let* ((name (prog1 (parse-token stream)
600                      (expect-char stream #\= () "message")))
601              (idx  (parse-unsigned-int stream))
602              (opts (prog1 (parse-proto-field-options stream)
603                      (expect-char stream #\; () "message")
604                      (maybe-skip-comments stream)))
605              (packed (find-option opts "packed"))
606              (slot   (proto->slot-name name *protobuf-package*))
607              (reqd   (kintern required))
608              (field  (make-instance 'protobuf-field
609                        :name  name
610                        :type  type
611                        :qualified-name (make-qualified-name message name)
612                        :parent message
613                        ;; One of :required, :optional or :repeated
614                        :required reqd
615                        :index idx
616                        :value slot
617                        ;; Fields parsed from .proto files usually get an accessor
618                        :reader (let ((conc-name (proto-conc-name message)))
619                                  (and conc-name
620                                       (intern (format nil "~A~A" conc-name slot) *protobuf-package*)))
621                        :default (multiple-value-bind (default type default-p)
622                                     (find-option opts "default")
623                                   (declare (ignore type))
624                                   (if default-p
625                                     default
626                                     (if (eq reqd :repeated) $empty-list $empty-default)))
627                        :packed  (and packed (boolean-true-p packed))
628                        :message-type (proto-message-type message)
629                        :options (remove-options opts "default" "packed"))))
630         (when extended-from
631           (assert (index-within-extensions-p idx extended-from) ()
632                   "The index ~D is not in range for extending ~S"
633                   idx (proto-class extended-from)))
634         (let ((slot (find-option opts "lisp_name")))
635           (when slot
636             (setf (proto-value field) (make-lisp-symbol type))))
637         (setf (proto-fields message) (nconc (proto-fields message) (list field)))
638         field))))
639
640 (defmethod resolve-lisp-names ((field protobuf-field))
641   "Resolves the field's protobuf type to a lisp type and sets `proto-class' for 'field'."
642   (let* ((type  (proto-type field))
643          (ptype (when (member type '("int32" "int64" "uint32" "uint64" "sint32" "sint64"
644                                      "fixed32" "fixed64" "sfixed32" "sfixed64"
645                                      "string" "bytes" "bool" "float" "double") :test #'string=)
646                   (kintern type)))
647          (message (unless ptype
648                     (or (find-message (proto-parent field) type)
649                         (find-enum (proto-parent field) type)))))
650     (unless (or ptype message)
651       (error 'undefined-field-type
652         :type-name type
653         :field field))
654     (setf (proto-class field) (or ptype (proto-class message))))
655   nil)
656
657 (defun parse-proto-group (stream message required &optional extended-from)
658   "Parse a (deprecated) Protobufs group from 'stream'.
659    Updates the 'protobuf-message' object to have the group type and field."
660   (check-type message protobuf-message)
661   (let* ((type (prog1 (parse-token stream)
662                  (expect-char stream #\= () "message")))
663          (name (slot-name->proto (proto->slot-name type)))
664          (idx  (parse-unsigned-int stream))
665          (msg  (parse-proto-message stream message type))
666          (slot  (proto->slot-name name *protobuf-package*))
667          (field (make-instance 'protobuf-field
668                   :name  name
669                   :type  type
670                   :qualified-name (make-qualified-name message name)
671                   :parent message
672                   :required (kintern required)
673                   :index idx
674                   :value slot
675                   ;; Groups parsed from .proto files usually get an accessor
676                   :reader (let ((conc-name (proto-conc-name message)))
677                             (and conc-name
678                                  (intern (format nil "~A~A" conc-name slot) *protobuf-package*)))
679                   :message-type :group)))
680     (setf (proto-message-type msg) :group)
681     (when extended-from
682       (assert (index-within-extensions-p idx extended-from) ()
683               "The index ~D is not in range for extending ~S"
684               idx (proto-class extended-from)))
685     (setf (proto-fields message) (nconc (proto-fields message) (list field)))
686     field))
687
688 (defun parse-proto-field-options (stream)
689   "Parse any options in a Protobufs field from 'stream'.
690    Returns a list of 'protobuf-option' objects."
691   (with-collectors ((options collect-option))
692     (let ((terminator nil))
693       (loop
694         (cond ((eql (peek-char nil stream nil) #\[)
695                (expect-char stream #\[ () "message"))
696               ((eql terminator #\,))
697               (t
698                (return-from parse-proto-field-options options)))
699         (multiple-value-bind (option term)
700             (parse-proto-option stream nil '(#\] #\,))
701           (setq terminator term)
702           (collect-option option))))))
703
704 (defun parse-proto-extension (stream message)
705   (check-type message protobuf-message)
706   (let* ((from  (parse-unsigned-int stream))
707          (token (parse-token stream))
708          (to    (let ((ch (peek-char nil stream nil)))
709                   (cond ((digit-char-p (peek-char nil stream nil))
710                          (parse-unsigned-int stream))
711                         ((eql ch #\;) from)
712                         (t (parse-token stream))))))
713     (expect-char stream #\; () "message")
714     (assert (or (null token) (string= token "to")) ()
715             "Expected 'to' in 'extensions' at position ~D" (file-position stream))
716     (assert (or (integerp to) (string= to "max")) ()
717             "Extension value is not an integer or 'max' as position ~D" (file-position stream))
718     (let ((extension (make-instance 'protobuf-extension
719                        :from from
720                        :to   (if (integerp to) to #.(1- (ash 1 29))))))
721       (setf (proto-extensions message)
722             (nconc (proto-extensions message)
723                    (list extension)))
724       extension)))
725
726
727 (defun parse-proto-service (stream schema)
728   "Parse a Protobufs 'service' from 'stream'.
729    Updates the 'protobuf-schema' object to have the service."
730   (check-type schema protobuf-schema)
731   (let* ((loc  (file-position stream))
732          (name (prog1 (parse-token stream)
733                  (expect-char stream #\{ () "service")
734                  (maybe-skip-comments stream)))
735          (service (make-instance 'protobuf-service
736                     :class (proto->class-name name *protobuf-package*)
737                     :name name
738                     :qualified-name (make-qualified-name *protobuf* name)
739                     :parent schema
740                     :source-location (make-source-location stream loc (i+ loc (length name)))))
741          (index 0))
742     (loop
743       (let ((token (parse-token stream)))
744         (when (null token)
745           (expect-char stream #\} '(#\;) "service")
746           (maybe-skip-comments stream)
747           (setf (proto-services schema) (nconc (proto-services schema) (list service)))
748           (return-from parse-proto-service service))
749         (cond ((string= token "option")
750                (parse-proto-option stream service))
751               ((string= token "rpc")
752                (parse-proto-method stream service (iincf index)))
753               (t
754                (error "Unrecognized token ~A at position ~D"
755                       token (file-position stream))))))))
756
757 (defmethod resolve-lisp-names ((service protobuf-service))
758   "Recursively resolves protobuf type names to lisp type names for all methods of 'service'."
759   (map () #'resolve-lisp-names (proto-methods service)))
760
761 (defun parse-proto-method (stream service index)
762   "Parse a Protobufs method from 'stream'.
763    Updates the 'protobuf-service' object to have the method."
764   (check-type service protobuf-service)
765   (let* ((loc  (file-position stream))
766          (name (parse-token stream))
767          (in   (prog2 (expect-char stream #\( () "service")
768                    (parse-token stream)
769                  (expect-char stream #\) () "service")))
770          (ret  (parse-token stream))            ;should be "=>"
771          (out  (prog2 (expect-char stream #\( () "service")
772                    (parse-token stream)
773                  (expect-char stream #\) () "service")))
774          (opts (let ((opts (parse-proto-method-options stream)))
775                  (when (or (null opts) (eql (peek-char nil stream nil) #\;))
776                    (expect-char stream #\; () "service"))
777                  (maybe-skip-comments stream)
778                  opts))
779          (stub   (proto->class-name name *protobuf-package*))
780          (method (make-instance 'protobuf-method
781                    :class stub
782                    :name  name
783                    :qualified-name (make-qualified-name *protobuf* name)
784                    :parent service
785                    :input-name  in
786                    :output-name out
787                    :index index
788                    :options opts
789                    :source-location (make-source-location stream loc (i+ loc (length name))))))
790     (assert (string= ret "returns") ()
791             "Syntax error in 'message' at position ~D" (file-position stream))
792     (let* ((name (find-option method "lisp_name"))
793            (stub (or (and name (make-lisp-symbol name))
794                      stub)))
795       (setf (proto-class method) stub
796             (proto-client-stub method) stub
797             (proto-server-stub method) (intern (format nil "~A-~A" 'do stub) *protobuf-package*)))
798     (let ((strm (find-option method "stream_type")))
799       (when strm
800         (setf (proto-streams-name method) strm)))
801     (setf (proto-methods service) (nconc (proto-methods service) (list method)))
802     method))
803
804 (defmethod resolve-lisp-names ((method protobuf-method))
805   "Resolves input, output, and streams protobuf type names to lisp type names and sets
806    `proto-input-type', `proto-output-type', and, if `proto-streams-name' is set,
807    `proto-streams-type' on 'method'."
808   (let* ((input-name   (proto-input-name method))
809          (output-name  (proto-output-name method))
810          (streams-name (proto-streams-name method))
811          (service (proto-parent method))
812          (schema  (proto-parent service))
813          (input-message   (find-message schema input-name))
814          (output-message  (find-message schema output-name))
815          (streams-message (and streams-name
816                                ;; This is supposed to be the fully-qualified name,
817                                ;; but we don't require that
818                                (find-message schema streams-name))))
819     (unless input-message
820       (error 'undefined-input-type
821         :type-name input-name
822         :method method))
823     (unless output-message
824       (error 'undefined-output-type
825         :type-name output-name
826         :method method))
827     (setf (proto-input-type method) (proto-class input-message))
828     (setf (proto-output-type method) (proto-class output-message))
829     (when streams-name
830       (unless streams-message
831         (error 'undefined-stream-type
832           :type-name streams-name
833           :method method))
834       (setf (proto-streams-type method) (proto-class streams-message))))
835   nil)
836
837 (defun parse-proto-method-options (stream)
838   "Parse any options in a Protobufs method from 'stream'.
839    Returns a list of 'protobuf-option' objects."
840   (when (eql (peek-char nil stream nil) #\{)
841     (expect-char stream #\{ () "service")
842     (maybe-skip-comments stream)
843     (with-collectors ((options collect-option))
844       (loop
845         (when (eql (peek-char nil stream nil) #\})
846           (return))
847         (assert (string= (parse-token stream) "option") ()
848                 "Syntax error in 'message' at position ~D" (file-position stream))
849         (collect-option (parse-proto-option stream nil)))
850       (expect-char stream #\} '(#\;) "service")
851       (maybe-skip-comments stream)
852       options)))