]> asedeno.scripts.mit.edu Git - cl-protobufs.git/blob - parser.lisp
Merge branch 'master' of git://common-lisp.net/projects/qitab/cl-protobufs
[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* *package*)
307          (*protobuf-conc-name* conc-name))
308     (loop
309       (skip-whitespace stream)
310       (maybe-skip-comments stream)
311       (let ((char (peek-char nil stream nil)))
312         (cond ((null char)
313                (remove-options schema "lisp_package")
314                (resolve-lisp-names schema)
315                (return-from parse-schema-from-stream schema))
316               ((proto-token-char-p char)
317                (let ((token (parse-token stream)))
318                  (cond ((string= token "syntax")
319                         (parse-proto-syntax stream schema))
320                        ((string= token "package")
321                         (parse-proto-package stream schema))
322                        ((string= token "import")
323                         (parse-proto-import stream schema))
324                        ((string= token "option")
325                         (let* ((option (parse-proto-option stream schema))
326                                (name   (and option (proto-name option)))
327                                (value  (and option (proto-value option))))
328                           (when (and option (option-name= name "lisp_package"))
329                             (set-lisp-package schema value))))
330                        ((string= token "enum")
331                         (parse-proto-enum stream schema))
332                        ((string= token "extend")
333                         (parse-proto-extend stream schema))
334                        ((string= token "message")
335                         (parse-proto-message stream schema))
336                        ((string= token "service")
337                         (parse-proto-service stream schema)))))
338               (t
339                (error "Syntax error at position ~D" (file-position stream))))))))
340
341 (defun set-lisp-package (schema lisp-package-name)
342   "Set the package for generated lisp names of 'schema'."
343   (check-type schema protobuf-schema)
344   (check-type lisp-package-name string)
345   (let ((package (or (find-proto-package lisp-package-name)
346                      ;; Try to put symbols into the right package
347                      (make-package (string-upcase lisp-package-name) :use ())
348                      *protobuf-package*)))
349     (setf (proto-lisp-package schema) lisp-package-name)
350     (setq *protobuf-package* package)))
351
352 (defmethod resolve-lisp-names ((schema protobuf-schema))
353   "Recursively resolves Protobuf type names to Lisp type names in the messages and services in 'schema'."
354   (map () #'resolve-lisp-names (proto-messages schema))
355   (map () #'resolve-lisp-names (proto-services schema)))
356
357 (defun parse-proto-syntax (stream schema &optional (terminator #\;))
358   "Parse a Protobufs syntax line from 'stream'.
359    Updates the 'protobuf-schema' object to use the syntax."
360   (let ((syntax (prog2 (expect-char stream #\= () "syntax")
361                     (parse-string stream)
362                   (expect-char stream terminator () "syntax")
363                   (maybe-skip-comments stream))))
364     (setf (proto-syntax schema) syntax)))
365
366 (defun parse-proto-package (stream schema &optional (terminator #\;))
367   "Parse a Protobufs package line from 'stream'.
368    Updates the 'protobuf-schema' object to use the package."
369   (check-type schema protobuf-schema)
370   (let* ((package  (prog1 (parse-token stream)
371                      (expect-char stream terminator () "package")
372                      (maybe-skip-comments stream)))
373          (lisp-pkg (or (proto-lisp-package schema)
374                        (substitute #\- #\_ package))))
375     (setf (proto-package schema) package)
376     (unless (proto-lisp-package schema)
377       (set-lisp-package schema lisp-pkg))))
378
379 (defun parse-proto-import (stream schema &optional (terminator #\;))
380   "Parse a Protobufs import line from 'stream'.
381    Updates the 'protobuf-schema' object to use the import."
382   (check-type schema protobuf-schema)
383   (let ((import (prog1 (parse-string stream)
384                   (expect-char stream terminator () "import")
385                   (maybe-skip-comments stream))))
386     (process-imports schema (list import))
387     (setf (proto-imports schema) (nconc (proto-imports schema) (list import)))))
388
389 (defun parse-proto-option (stream protobuf &optional (terminators '(#\;)))
390   "Parse a Protobufs option line from 'stream'.
391    Updates the 'protobuf-schema' (or message, service, method) to have the option."
392   (check-type protobuf (or null base-protobuf))
393   (let* (terminator
394          (key (prog1 (parse-parenthesized-token stream)
395                 (expect-char stream #\= () "option")))
396          (val (prog1 (let ((ch (peek-char nil stream nil)))
397                        (cond ((eql ch #\")
398                               (parse-string stream))
399                              ((or (digit-char-p ch) (member ch '(#\- #\+ #\.)))
400                               (parse-number stream))
401                              ((eql ch #\{)
402                               ;;---bwagner: This is incorrect
403                               ;;   We need to find the field name in the locally-extended version of
404                               ;;   google.protobuf.[File,Message,Field,Enum,EnumValue,Service,Method]Options
405                               ;;   and get its type
406                               (let ((message (find-message (or protobuf *protobuf*) key)))
407                                 (if message
408                                   ;; We've got a complex message as a value to an option
409                                   ;; This only shows up in custom options
410                                   (parse-text-format message :stream stream :parse-name nil)
411                                   ;; Who knows what to do? Skip the value
412                                   (skip-field stream))))
413                              (t (kintern (parse-token stream)))))
414                 (setq terminator (expect-char stream terminators () "option"))
415                 (maybe-skip-comments stream)))
416          (option (make-instance 'protobuf-option
417                    :name  key
418                    :value val)))
419     (cond (protobuf
420            (setf (proto-options protobuf) (nconc (proto-options protobuf) (list option)))
421            (values option terminator))
422           (t
423            ;; If nothing to graft the option into, just return it as the value
424            (values option terminator)))))
425
426
427 (defun parse-proto-enum (stream protobuf)
428   "Parse a Protobufs 'enum' from 'stream'.
429    Updates the 'protobuf-schema' or 'protobuf-message' object to have the enum."
430   (check-type protobuf (or protobuf-schema protobuf-message))
431   (let* ((loc  (file-position stream))
432          (name (prog1 (parse-token stream)
433                  (expect-char stream #\{ () "enum")
434                  (maybe-skip-comments stream)))
435          (enum (make-instance 'protobuf-enum
436                  :class (proto->class-name name *protobuf-package*)
437                  :name name
438                  :qualified-name (make-qualified-name protobuf name)
439                  :parent protobuf
440                  :source-location (make-source-location stream loc (i+ loc (length name))))))
441     (loop
442       (let ((name (parse-token stream)))
443         (when (null name)
444           (expect-char stream #\} '(#\;) "enum")
445           (maybe-skip-comments stream)
446           (setf (proto-enums protobuf) (nconc (proto-enums protobuf) (list enum)))
447           (let ((type (find-option enum "lisp_name")))
448             (when type
449               (setf (proto-class enum) (make-lisp-symbol type))))
450           (let ((alias (find-option enum "lisp_alias")))
451             (when alias
452               (setf (proto-alias-for enum) (make-lisp-symbol alias))))
453           (return-from parse-proto-enum enum))
454         (if (string= name "option")
455           (parse-proto-option stream enum)
456           (parse-proto-enum-value stream protobuf enum name))))))
457
458 (defun parse-proto-enum-value (stream protobuf enum name)
459   "Parse a Protobufs enum value from 'stream'.
460    Updates the 'protobuf-enum' object to have the enum value."
461   (declare (ignore protobuf))
462   (check-type enum protobuf-enum)
463   (expect-char stream #\= () "enum")
464   (let* ((idx  (prog1 (parse-signed-int stream)
465                  (expect-char stream #\; () "enum")
466                  (maybe-skip-comments stream)))
467          (value (make-instance 'protobuf-enum-value
468                   :name  name
469                   :qualified-name (make-qualified-name enum name)
470                   :index idx
471                   :value (proto->enum-name name *protobuf-package*)
472                   :parent enum)))
473     (setf (proto-values enum) (nconc (proto-values enum) (list value)))
474     value))
475
476
477 (defun parse-proto-message (stream protobuf &optional name)
478   "Parse a Protobufs 'message' from 'stream'.
479    Updates the 'protobuf-schema' or 'protobuf-message' object to have the message."
480   (check-type protobuf (or protobuf-schema protobuf-message))
481   (let* ((loc  (file-position stream))
482          (name (prog1 (or name (parse-token stream))
483                  (expect-char stream #\{ () "message")
484                  (maybe-skip-comments stream)))
485          (class (proto->class-name name *protobuf-package*))
486          (message (make-instance 'protobuf-message
487                     :class class
488                     :name  name
489                     :qualified-name (make-qualified-name protobuf name)
490                     :parent protobuf
491                     ;; Maybe force accessors for all slots
492                     :conc-name (conc-name-for-type class *protobuf-conc-name*)
493                     :source-location (make-source-location stream loc (i+ loc (length name)))))
494          (*protobuf* message))
495     (loop
496       (let ((token (parse-token stream)))
497         (when (null token)
498           (expect-char stream #\} '(#\;) "message")
499           (maybe-skip-comments stream)
500           (setf (proto-messages protobuf) (nconc (proto-messages protobuf) (list message)))
501           (let ((type (find-option message "lisp_name")))
502             (when type
503               (setf (proto-class message) (make-lisp-symbol type))))
504           (let ((alias (find-option message "lisp_alias")))
505             (when alias
506               (setf (proto-alias-for message) (make-lisp-symbol alias))))
507           (return-from parse-proto-message message))
508         (cond ((string= token "enum")
509                (parse-proto-enum stream message))
510               ((string= token "extend")
511                (parse-proto-extend stream message))
512               ((string= token "message")
513                (parse-proto-message stream message))
514               ((member token '("required" "optional" "repeated") :test #'string=)
515                (parse-proto-field stream message token))
516               ((string= token "option")
517                (parse-proto-option stream message))
518               ((string= token "extensions")
519                (parse-proto-extension stream message))
520               (t
521                (error "Unrecognized token ~A at position ~D"
522                       token (file-position stream))))))))
523
524 (defmethod resolve-lisp-names ((message protobuf-message))
525   "Recursively resolves protobuf type names to lisp type names in nested messages and fields of 'message'."
526   (map () #'resolve-lisp-names (proto-messages message))
527   (map () #'resolve-lisp-names (proto-fields message)))
528
529 (defun parse-proto-extend (stream protobuf)
530   "Parse a Protobufs 'extend' from 'stream'.
531    Updates the 'protobuf-schema' or 'protobuf-message' object to have the message."
532   (check-type protobuf (or protobuf-schema protobuf-message))
533   (let* ((loc  (file-position stream))
534          (name (prog1 (parse-token stream)
535                  (expect-char stream #\{ () "extend")
536                  (maybe-skip-comments stream)))
537          ;;---bwagner: Is 'extend' allowed to use a forward reference to a message?
538          (message (find-message protobuf name))
539          (extends (and message
540                        (make-instance 'protobuf-message
541                          :class (proto-class message)
542                          :name  (proto-name message)
543                          :qualified-name (proto-qualified-name message)
544                          :parent protobuf
545                          :alias-for (proto-alias-for message)
546                          :conc-name (proto-conc-name message)
547                          :enums    (copy-list (proto-enums message))
548                          :messages (copy-list (proto-messages message))
549                          :fields   (copy-list (proto-fields message))
550                          :extensions (copy-list (proto-extensions message))
551                          :message-type :extends         ;this message is an extension
552                          :source-location (make-source-location stream loc (i+ loc (length name))))))
553          (*protobuf* extends))
554     (assert message ()
555             "There is no message named ~A to extend" name)
556     (loop
557       (let ((token (parse-token stream)))
558         (when (null token)
559           (expect-char stream #\} '(#\;) "extend")
560           (maybe-skip-comments stream)
561           (setf (proto-messages protobuf) (nconc (proto-messages protobuf) (list extends)))
562           (setf (proto-extenders protobuf) (nconc (proto-extenders protobuf) (list extends)))
563           (let ((type (find-option extends "lisp_name")))
564             (when type
565               (setf (proto-class extends) (make-lisp-symbol type))))
566           (let ((alias (find-option extends "lisp_alias")))
567             (when alias
568               (setf (proto-alias-for extends) (make-lisp-symbol alias))))
569           (return-from parse-proto-extend extends))
570         (cond ((member token '("required" "optional" "repeated") :test #'string=)
571                (let ((field (parse-proto-field stream extends token message)))
572                  (setf (proto-extended-fields extends) (nconc (proto-extended-fields extends) (list field)))))
573               ((string= token "option")
574                (parse-proto-option stream extends))
575               (t
576                (error "Unrecognized token ~A at position ~D"
577                       token (file-position stream))))))))
578
579 (defun parse-proto-field (stream message required &optional extended-from)
580   "Parse a Protobufs field from 'stream'.
581    Updates the 'protobuf-message' object to have the field."
582   (check-type message protobuf-message)
583   (let ((type (parse-token stream)))
584     (if (string= type "group")
585       (parse-proto-group stream message required extended-from)
586       (let* ((name (prog1 (parse-token stream)
587                      (expect-char stream #\= () "message")))
588              (idx  (parse-unsigned-int stream))
589              (opts (prog1 (parse-proto-field-options stream)
590                      (expect-char stream #\; () "message")
591                      (maybe-skip-comments stream)))
592              (packed (find-option opts "packed"))
593              (slot   (proto->slot-name name *protobuf-package*))
594              (reqd   (kintern required))
595              (field  (make-instance 'protobuf-field
596                        :name  name
597                        :type  type
598                        :qualified-name (make-qualified-name message name)
599                        :parent message
600                        ;; One of :required, :optional or :repeated
601                        :required reqd
602                        :index idx
603                        :value slot
604                        ;; Fields parsed from .proto files usually get an accessor
605                        :reader (let ((conc-name (proto-conc-name message)))
606                                  (and conc-name
607                                       (intern (format nil "~A~A" conc-name slot) *protobuf-package*)))
608                        :default (multiple-value-bind (default type default-p)
609                                     (find-option opts "default")
610                                   (declare (ignore type))
611                                   (if default-p
612                                     default
613                                     (if (eq reqd :repeated) $empty-list $empty-default)))
614                        :packed  (and packed (boolean-true-p packed))
615                        :message-type (proto-message-type message)
616                        :options (remove-options opts "default" "packed"))))
617         (when extended-from
618           (assert (index-within-extensions-p idx extended-from) ()
619                   "The index ~D is not in range for extending ~S"
620                   idx (proto-class extended-from)))
621         (let ((slot (find-option opts "lisp_name")))
622           (when slot
623             (setf (proto-value field) (make-lisp-symbol type))))
624         (setf (proto-fields message) (nconc (proto-fields message) (list field)))
625         field))))
626
627 (defmethod resolve-lisp-names ((field protobuf-field))
628   "Resolves the field's protobuf type to a lisp type and sets `proto-class' for 'field'."
629   (let* ((type  (proto-type field))
630          (ptype (when (member type '("int32" "int64" "uint32" "uint64" "sint32" "sint64"
631                                      "fixed32" "fixed64" "sfixed32" "sfixed64"
632                                      "string" "bytes" "bool" "float" "double") :test #'string=)
633                   (kintern type)))
634          (message (unless ptype
635                     (or (find-message (proto-parent field) type)
636                         (find-enum (proto-parent field) type)))))
637     (unless (or ptype message)
638       (error 'undefined-field-type
639         :type-name type
640         :field field))
641     (setf (proto-class field) (or ptype (proto-class message))))
642   nil)
643
644 (defun parse-proto-group (stream message required &optional extended-from)
645   "Parse a (deprecated) Protobufs group from 'stream'.
646    Updates the 'protobuf-message' object to have the group type and field."
647   (check-type message protobuf-message)
648   (let* ((type (prog1 (parse-token stream)
649                  (expect-char stream #\= () "message")))
650          (name (slot-name->proto (proto->slot-name type)))
651          (idx  (parse-unsigned-int stream))
652          (msg  (parse-proto-message stream message type))
653          (slot  (proto->slot-name name *protobuf-package*))
654          (field (make-instance 'protobuf-field
655                   :name  name
656                   :type  type
657                   :qualified-name (make-qualified-name message name)
658                   :parent message
659                   :required (kintern required)
660                   :index idx
661                   :value slot
662                   ;; Groups parsed from .proto files usually get an accessor
663                   :reader (let ((conc-name (proto-conc-name message)))
664                             (and conc-name
665                                  (intern (format nil "~A~A" conc-name slot) *protobuf-package*)))
666                   :message-type :group)))
667     (setf (proto-message-type msg) :group)
668     (when extended-from
669       (assert (index-within-extensions-p idx extended-from) ()
670               "The index ~D is not in range for extending ~S"
671               idx (proto-class extended-from)))
672     (setf (proto-fields message) (nconc (proto-fields message) (list field)))
673     field))
674
675 (defun parse-proto-field-options (stream)
676   "Parse any options in a Protobufs field from 'stream'.
677    Returns a list of 'protobuf-option' objects."
678   (with-collectors ((options collect-option))
679     (let ((terminator nil))
680       (loop
681         (cond ((eql (peek-char nil stream nil) #\[)
682                (expect-char stream #\[ () "message"))
683               ((eql terminator #\,))
684               (t
685                (return-from parse-proto-field-options options)))
686         (multiple-value-bind (option term)
687             (parse-proto-option stream nil '(#\] #\,))
688           (setq terminator term)
689           (collect-option option))))))
690
691 (defun parse-proto-extension (stream message)
692   (check-type message protobuf-message)
693   (let* ((from  (parse-unsigned-int stream))
694          (token (parse-token stream))
695          (to    (let ((ch (peek-char nil stream nil)))
696                   (cond ((digit-char-p (peek-char nil stream nil))
697                          (parse-unsigned-int stream))
698                         ((eql ch #\;) from)
699                         (t (parse-token stream))))))
700     (expect-char stream #\; () "message")
701     (assert (or (null token) (string= token "to")) ()
702             "Expected 'to' in 'extensions' at position ~D" (file-position stream))
703     (assert (or (integerp to) (string= to "max")) ()
704             "Extension value is not an integer or 'max' as position ~D" (file-position stream))
705     (let ((extension (make-instance 'protobuf-extension
706                        :from from
707                        :to   (if (integerp to) to #.(1- (ash 1 29))))))
708       (setf (proto-extensions message)
709             (nconc (proto-extensions message)
710                    (list extension)))
711       extension)))
712
713
714 (defun parse-proto-service (stream schema)
715   "Parse a Protobufs 'service' from 'stream'.
716    Updates the 'protobuf-schema' object to have the service."
717   (check-type schema protobuf-schema)
718   (let* ((loc  (file-position stream))
719          (name (prog1 (parse-token stream)
720                  (expect-char stream #\{ () "service")
721                  (maybe-skip-comments stream)))
722          (service (make-instance 'protobuf-service
723                     :class (proto->class-name name *protobuf-package*)
724                     :name name
725                     :qualified-name (make-qualified-name *protobuf* name)
726                     :parent schema
727                     :source-location (make-source-location stream loc (i+ loc (length name)))))
728          (index 0))
729     (loop
730       (let ((token (parse-token stream)))
731         (when (null token)
732           (expect-char stream #\} '(#\;) "service")
733           (maybe-skip-comments stream)
734           (setf (proto-services schema) (nconc (proto-services schema) (list service)))
735           (return-from parse-proto-service service))
736         (cond ((string= token "option")
737                (parse-proto-option stream service))
738               ((string= token "rpc")
739                (parse-proto-method stream service (iincf index)))
740               (t
741                (error "Unrecognized token ~A at position ~D"
742                       token (file-position stream))))))))
743
744 (defmethod resolve-lisp-names ((service protobuf-service))
745   "Recursively resolves protobuf type names to lisp type names for all methods of 'service'."
746   (map () #'resolve-lisp-names (proto-methods service)))
747
748 (defun parse-proto-method (stream service index)
749   "Parse a Protobufs method from 'stream'.
750    Updates the 'protobuf-service' object to have the method."
751   (check-type service protobuf-service)
752   (let* ((loc  (file-position stream))
753          (name (parse-token stream))
754          (in   (prog2 (expect-char stream #\( () "service")
755                    (parse-token stream)
756                  (expect-char stream #\) () "service")))
757          (ret  (parse-token stream))            ;should be "=>"
758          (out  (prog2 (expect-char stream #\( () "service")
759                    (parse-token stream)
760                  (expect-char stream #\) () "service")))
761          (opts (let ((opts (parse-proto-method-options stream)))
762                  (when (or (null opts) (eql (peek-char nil stream nil) #\;))
763                    (expect-char stream #\; () "service"))
764                  (maybe-skip-comments stream)
765                  opts))
766          (stub   (proto->class-name name *protobuf-package*))
767          (method (make-instance 'protobuf-method
768                    :class stub
769                    :name  name
770                    :qualified-name (make-qualified-name *protobuf* name)
771                    :parent service
772                    :input-name  in
773                    :output-name out
774                    :index index
775                    :options opts
776                    :source-location (make-source-location stream loc (i+ loc (length name))))))
777     (assert (string= ret "returns") ()
778             "Syntax error in 'message' at position ~D" (file-position stream))
779     (let* ((name (find-option method "lisp_name"))
780            (stub (or (and name (make-lisp-symbol name))
781                      stub)))
782       (setf (proto-class method) stub
783             (proto-client-stub method) stub
784             (proto-server-stub method) (intern (format nil "~A-~A" 'do stub) *protobuf-package*)))
785     (let ((strm (find-option method "stream_type")))
786       (when strm
787         (setf (proto-streams-name method) strm)))
788     (setf (proto-methods service) (nconc (proto-methods service) (list method)))
789     method))
790
791 (defmethod resolve-lisp-names ((method protobuf-method))
792   "Resolves input, output, and streams protobuf type names to lisp type names and sets
793    `proto-input-type', `proto-output-type', and, if `proto-streams-name' is set,
794    `proto-streams-type' on 'method'."
795   (let* ((input-name   (proto-input-name method))
796          (output-name  (proto-output-name method))
797          (streams-name (proto-streams-name method))
798          (service (proto-parent method))
799          (schema  (proto-parent service))
800          (input-message   (find-message schema input-name))
801          (output-message  (find-message schema output-name))
802          (streams-message (and streams-name
803                                ;; This is supposed to be the fully-qualified name,
804                                ;; but we don't require that
805                                (find-message schema streams-name))))
806     (unless input-message
807       (error 'undefined-input-type
808         :type-name input-name
809         :method method))
810     (unless output-message
811       (error 'undefined-output-type
812         :type-name output-name
813         :method method))
814     (setf (proto-input-type method) (proto-class input-message))
815     (setf (proto-output-type method) (proto-class output-message))
816     (when streams-name
817       (unless streams-message
818         (error 'undefined-stream-type
819           :type-name streams-name
820           :method method))
821       (setf (proto-streams-type method) (proto-class streams-message))))
822   nil)
823
824 (defun parse-proto-method-options (stream)
825   "Parse any options in a Protobufs method from 'stream'.
826    Returns a list of 'protobuf-option' objects."
827   (when (eql (peek-char nil stream nil) #\{)
828     (expect-char stream #\{ () "service")
829     (maybe-skip-comments stream)
830     (with-collectors ((options collect-option))
831       (loop
832         (when (eql (peek-char nil stream nil) #\})
833           (return))
834         (assert (string= (parse-token stream) "option") ()
835                 "Syntax error in 'message' at position ~D" (file-position stream))
836         (collect-option (parse-proto-option stream nil)))
837       (expect-char stream #\} '(#\;) "service")
838       (maybe-skip-comments stream)
839       options)))