More work. Highlights:
[sod] / lex.lisp
1 ;;; -*-lisp-*-
2 ;;;
3 ;;; Lexical analysis of a vaguely C-like language
4 ;;;
5 ;;; (c) 2009 Straylight/Edgeware
6 ;;;
7
8 ;;;----- Licensing notice ---------------------------------------------------
9 ;;;
10 ;;; This file is part of the Simple Object Definition system.
11 ;;;
12 ;;; SOD is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 2 of the License, or
15 ;;; (at your option) any later version.
16 ;;;
17 ;;; SOD is distributed in the hope that it will be useful,
18 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;;; GNU General Public License for more details.
21 ;;;
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with SOD; if not, write to the Free Software Foundation,
24 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
26 (cl:in-package #:sod)
27
28 ;;;--------------------------------------------------------------------------
29 ;;; Basic lexical analyser infrastructure.
30
31 ;; Class definition.
32
33 (defclass lexer ()
34 ((stream :initarg :stream :type stream :reader lexer-stream)
35 (char :initform nil :type (or character null) :reader lexer-char)
36 (pushback-chars :initform nil :type list)
37 (token-type :initform nil :accessor token-type)
38 (token-value :initform nil :accessor token-value)
39 (pushback-tokens :initform nil :type list))
40 (:documentation
41 "Base class for lexical analysers.
42
43 The lexer reads characters from STREAM, which, for best results, wants to
44 be a POSITION-AWARE-INPUT-STREAM.
45
46 The lexer provides one-character lookahead by default: the current
47 lookahead character is available to subclasses in the slot CHAR. Before
48 beginning lexical analysis, the lookahead character needs to be
49 established with NEXT-CHAR. If one-character lookahead is insufficient,
50 the analyser can push back an arbitrary number of characters using
51 PUSHBACK-CHAR.
52
53 The NEXT-TOKEN function scans and returns the next token from the STREAM,
54 and makes it available as TOKEN-TYPE and TOKEN-VALUE, providing one-token
55 lookahead. A parser using the lexical analyser can push back tokens using
56 PUSHBACK-TOKENS.
57
58 For convenience, the lexer implements a FILE-LOCATION method (delegated to
59 the underlying stream)."))
60
61 ;; Lexer protocol.
62
63 (defgeneric scan-token (lexer)
64 (:documentation
65 "Internal function for scanning tokens from an input stream.
66
67 Implementing a method on this function is the main responsibility of LEXER
68 subclasses; it is called by the user-facing NEXT-TOKEN function.
69
70 The method should consume characters (using NEXT-CHAR) as necessary, and
71 return two values: a token type and token value. These will be stored in
72 the corresponding slots in the lexer object in order to provide the user
73 with one-token lookahead."))
74
75 (defgeneric next-token (lexer)
76 (:documentation
77 "Scan a token from an input stream.
78
79 This function scans a token from an input stream. Two values are
80 returned: a `token type' and a `token value'. These are opaque to the
81 LEXER base class, but the intent is that the token type be significant to
82 determining the syntax of the input, while the token value carries any
83 additional information about the token's semantic content. The token type
84 and token value are also made available for lookahead via accessors
85 TOKEN-TYPE and TOKEN-NAME on the LEXER object.
86
87 If tokens have been pushed back (see PUSHBACK-TOKEN) then they are
88 returned one by one instead of scanning the stream.")
89
90 (:method ((lexer lexer))
91 (with-slots (pushback-tokens token-type token-value) lexer
92 (setf (values token-type token-value)
93 (if pushback-tokens
94 (let ((pushback (pop pushback-tokens)))
95 (values (car pushback) (cdr pushback)))
96 (scan-token lexer))))))
97
98 (defgeneric pushback-token (lexer token-type &optional token-value)
99 (:documentation
100 "Push a token back into the lexer.
101
102 Make the given TOKEN-TYPE and TOKEN-VALUE be the current lookahead token.
103 The previous lookahead token is pushed down, and will be made available
104 agan once this new token is consumed by NEXT-TOKEN. The FILE-LOCATION is
105 not affected by pushing tokens back. The TOKEN-TYPE and TOKEN-VALUE be
106 anything at all: for instance, they need not be values which can actually
107 be returned by NEXT-TOKEN.")
108
109 (:method ((lexer lexer) new-token-type &optional new-token-value)
110 (with-slots (pushback-tokens token-type token-value) lexer
111 (push (cons token-type token-value) pushback-tokens)
112 (setf token-type new-token-type
113 token-value new-token-value))))
114
115 (defgeneric next-char (lexer)
116 (:documentation
117 "Fetch the next character from the LEXER's input stream.
118
119 Read a character from the input stream, and store it in the LEXER's CHAR
120 slot. The character stored is returned. If characters have been pushed
121 back then pushed-back characters are used instead of the input stream.
122
123 (This function is primarily intended for the use of lexer subclasses.)")
124
125 (:method ((lexer lexer))
126 (with-slots (stream char pushback-chars) lexer
127 (setf char (if pushback-chars
128 (pop pushback-chars)
129 (read-char stream nil))))))
130
131 (defgeneric pushback-char (lexer char)
132 (:documentation
133 "Push the CHAR back into the lexer.
134
135 Make CHAR be the current lookahead character (stored in the LEXER's CHAR
136 slot). The previous lookahead character is pushed down, and will be made
137 available again once this character is consumed by NEXT-CHAR.
138
139 (This function is primarily intended for the use of lexer subclasses.)")
140
141 (:method ((lexer lexer) new-char)
142 (with-slots (char pushback-chars) lexer
143 (push char pushback-chars)
144 (setf char new-char))))
145
146 (defgeneric fixup-stream* (lexer thunk)
147 (:documentation
148 "Helper function for WITH-LEXER-STREAM.
149
150 This function does the main work for WITH-LEXER-STREAM. The THUNK is
151 invoked on a single argument, the LEXER's underlying STREAM.")
152
153 (:method ((lexer lexer) thunk)
154 (with-slots (stream char pushback-chars) lexer
155 (when pushback-chars
156 (error "Lexer has pushed-back characters."))
157 (unread-char char stream)
158 (unwind-protect
159 (funcall thunk stream)
160 (setf char (read-char stream nil))))))
161
162 (defmacro with-lexer-stream ((streamvar lexer) &body body)
163 "Evaluate BODY with STREAMVAR bound to the LEXER's input stream.
164
165 The STREAM is fixed up so that the next character read (e.g., using
166 READ-CHAR) will be the lexer's current lookahead character. Once the BODY
167 completes, the next character in the stream is read and set as the
168 lookahead character. It is an error if the lexer has pushed-back
169 characters (since these can't be pushed back into the input stream
170 properly)."
171
172 `(fixup-stream* ,lexer
173 (lambda (,streamvar)
174 ,@body)))
175
176 (defmethod file-location ((lexer lexer))
177 (with-slots (stream) lexer
178 (file-location stream)))
179
180 (defgeneric skip-spaces (lexer)
181 (:documentation
182 "Skip over whitespace characters in the LEXER.")
183 (:method ((lexer lexer))
184 (do ((ch (lexer-char lexer) (next-char lexer)))
185 ((not (whitespace-char-p ch))))))
186
187 ;;;--------------------------------------------------------------------------
188 ;;; Lexer utilities.
189
190 (defun require-token
191 (lexer wanted-token-type &key (errorp t) (consumep t) default)
192 (with-slots (token-type token-value) lexer
193 (cond ((eql token-type wanted-token-type)
194 (prog1 token-value
195 (when consumep (next-token lexer))))
196 (errorp
197 (cerror* "Expected ~A but found ~A"
198 (format-token wanted-token-type)
199 (format-token token-type token-value))
200 default)
201 (t
202 default))))
203
204 ;;;--------------------------------------------------------------------------
205 ;;; Our main lexer.
206
207 (defun make-keyword-table (&rest keywords)
208 "Construct a keyword table for the lexical analyser.
209
210 The KEYWORDS arguments are individual keywords, either as strings or as
211 (WORD . VALUE) pairs. A string argument is equivalent to a pair listing
212 the string itself as WORD and the corresponding keyword symbol (forced to
213 uppercase) as the VALUE."
214
215 (let ((table (make-hash-table :test #'equal)))
216 (dolist (item keywords)
217 (multiple-value-bind (word keyword)
218 (if (consp item)
219 (values (car item) (cdr item))
220 (values item (intern (string-upcase item) :keyword)))
221 (setf (gethash word table) keyword)))
222 table))
223
224 (defparameter *sod-keywords*
225 (make-keyword-table
226
227 ;; Words with a meaning to C's type system.
228 "char" "int" "float" "void"
229 "long" "short" "signed" "unsigned" "double"
230 "const" "volatile" "restrict"
231 "struct" "union" "enum"))
232
233 (defclass sod-lexer (lexer)
234 ((keywords :initarg :keywords :initform *sod-keywords*
235 :type hash-table :reader lexer-keywords))
236 (:documentation
237 "Lexical analyser for the SOD lanuage.
238
239 See the LEXER class for the gory details about the lexer protocol."))
240
241 (defun format-token (token-type &optional token-value)
242 (when (typep token-type 'lexer)
243 (let ((lexer token-type))
244 (setf token-type (token-type lexer)
245 token-value (token-value lexer))))
246 (etypecase token-type
247 ((eql :eof) "<end-of-file>")
248 ((eql :string) "<string-literal>")
249 ((eql :char) "<character-literal>")
250 ((eql :id) (format nil "<identifier~@[ `~A'~]>" token-value))
251 (keyword (format nil "`~(~A~)'" token-type))
252 (character (format nil "~:[<~:C>~;`~C'~]"
253 (and (graphic-char-p token-type)
254 (char/= token-type #\space))
255 token-type))))
256
257 (defmethod scan-token ((lexer sod-lexer))
258 (with-slots (stream char keywords) lexer
259 (prog ((ch char))
260
261 consider
262 (cond
263
264 ;; End-of-file brings its own peculiar joy.
265 ((null ch) (return (values :eof t)))
266
267 ;; Ignore whitespace and continue around for more.
268 ((whitespace-char-p ch) (go scan))
269
270 ;; Strings.
271 ((or (char= ch #\") (char= ch #\'))
272 (with-default-error-location ((file-location lexer))
273 (let* ((quote ch)
274 (string
275 (with-output-to-string (out)
276 (loop
277 (flet ((getch ()
278 (setf ch (next-char lexer))
279 (when (null ch)
280 (cerror*
281 "Unexpected end of file in string/character constant")
282 (return))))
283 (getch)
284 (cond ((char= ch quote) (return))
285 ((char= ch #\\) (getch)))
286 (write-char ch out))))))
287 (setf ch (next-char lexer))
288 (ecase quote
289 (#\" (return (values :string string)))
290 (#\' (case (length string)
291 (0 (cerror* "Empty character constant")
292 (return (values :char #\?)))
293 (1 (return (values :char (char string 0))))
294 (t (cerror*
295 "Multiple characters in character constant")
296 (return (values :char (char string 0))))))))))
297
298 ;; Pick out identifiers and keywords.
299 ((or (alpha-char-p ch) (char= ch #\_))
300
301 ;; Scan a sequence of alphanumerics and underscores. We could
302 ;; allow more interesting identifiers, but it would damage our C
303 ;; lexical compatibility.
304 (let ((id (with-output-to-string (out)
305 (loop
306 (write-char ch out)
307 (setf ch (next-char lexer))
308 (when (or (null ch)
309 (not (or (alphanumericp ch)
310 (char= ch #\_))))
311 (return))))))
312
313 ;; Check to see whether we match any keywords.
314 (multiple-value-bind (keyword foundp) (gethash id keywords)
315 (return (values (if foundp keyword :id) id)))))
316
317 ;; Pick out numbers. Currently only integers, but we support
318 ;; multiple bases.
319 ((digit-char-p ch)
320
321 ;; Sort out the prefix. If we're looking at `0b', `0o' or `0x'
322 ;; (maybe uppercase) then we've got a funny radix to deal with.
323 ;; Otherwise, a leading zero signifies octal (daft, I know), else
324 ;; we're left with decimal.
325 (multiple-value-bind (radix skip-char)
326 (if (char/= ch #\0)
327 (values 10 nil)
328 (case (and (setf ch (next-char lexer))
329 (char-downcase ch))
330 (#\b (values 2 t))
331 (#\o (values 8 t))
332 (#\x (values 16 t))
333 (t (values 8 nil))))
334
335 ;; If we last munched an interesting letter, we need to skip over
336 ;; it. That's what the SKIP-CHAR flag is for.
337 ;;
338 ;; Danger, Will Robinson! If we're' just about to eat a radix
339 ;; letter, then the next thing must be a digit. For example,
340 ;; `0xfatenning' parses as a hex number followed by an identifier
341 ;; `0xfa ttening', but `0xturning' is an octal number followed
342 ;; by an identifier `0 xturning'.
343 (when skip-char
344 (let ((peek (next-char lexer)))
345 (unless (digit-char-p peek radix)
346 (pushback-char lexer ch)
347 (return-from scan-token (values :integer 0)))
348 (setf ch peek)))
349
350 ;; Scan an integer. While there are digits, feed them into the
351 ;; accumulator.
352 (do ((accum 0 (+ (* accum radix) digit))
353 (digit (and ch (digit-char-p ch radix))
354 (and ch (digit-char-p ch radix))))
355 ((null digit) (return-from scan-token
356 (values :integer accum)))
357 (setf ch (next-char lexer)))))
358
359 ;; A slash might be the start of a comment.
360 ((char= ch #\/)
361 (setf ch (next-char lexer))
362 (case ch
363
364 ;; Comment up to the end of the line.
365 (#\/
366 (loop
367 (setf ch (next-char lexer))
368 (when (or (null ch) (char= ch #\newline))
369 (go scan))))
370
371 ;; Comment up to the next `*/'.
372 (#\*
373 (tagbody
374 top
375 (case (setf ch (next-char lexer))
376 (#\* (go star))
377 ((nil) (go done))
378 (t (go top)))
379 star
380 (case (setf ch (next-char lexer))
381 (#\* (go star))
382 (#\/ (setf ch (next-char lexer))
383 (go done))
384 ((nil) (go done))
385 (t (go top)))
386 done)
387 (go consider))
388
389 ;; False alarm. (The next character is already set up.)
390 (t
391 (return (values #\/ t)))))
392
393 ;; A dot: might be `...'. Tread carefully! We need more lookahead
394 ;; than is good for us.
395 ((char= ch #\.)
396 (setf ch (next-char lexer))
397 (cond ((eql ch #\.)
398 (setf ch (next-char lexer))
399 (cond ((eql ch #\.) (return (values :ellpisis nil)))
400 (t (pushback-char lexer #\.)
401 (return (values #\. t)))))
402 (t
403 (return (values #\. t)))))
404
405 ;; Anything else is a lone delimiter.
406 (t
407 (return (multiple-value-prog1
408 (values ch t)
409 (next-char lexer)))))
410
411 scan
412 ;; Scan a new character and try again.
413 (setf ch (next-char lexer))
414 (go consider))))
415
416 ;;;--------------------------------------------------------------------------
417 ;;; C fragments.
418
419 (defclass c-fragment ()
420 ((location :initarg :location :type file-location
421 :accessor c-fragment-location)
422 (text :initarg :text :type string :accessor c-fragment-text))
423 (:documentation
424 "Represents a fragment of C code to be written to an output file.
425
426 A C fragment is aware of its original location, and will bear proper #line
427 markers when written out."))
428
429 (defun output-c-excursion (stream location thunk)
430 "Invoke THUNK surrounding it by writing #line markers to STREAM.
431
432 The first marker describes LOCATION; the second refers to the actual
433 output position in STREAM. If LOCATION doesn't provide a line number then
434 no markers are output after all. If the output stream isn't
435 position-aware then no final marker is output."
436
437 (let* ((location (file-location location))
438 (line (file-location-line location))
439 (pathname (file-location-pathname location))
440 (namestring (and pathname (namestring pathname))))
441 (cond (line
442 (format stream "~&#line ~D~@[ ~S~]~%" line namestring)
443 (funcall thunk)
444 (when (typep stream 'position-aware-stream)
445 (fresh-line stream)
446 (format stream "~&#line ~D ~S~%"
447 (1+ (position-aware-stream-line stream))
448 (namestring (stream-pathname stream)))))
449 (t
450 (funcall thunk)))))
451
452 (defmethod print-object ((fragment c-fragment) stream)
453 (let ((text (c-fragment-text fragment))
454 (location (c-fragment-location fragment)))
455 (if *print-escape*
456 (print-unreadable-object (fragment stream :type t)
457 (when location
458 (format stream "~A " location))
459 (cond ((< (length text) 40)
460 (prin1 text stream) stream)
461 (t
462 (prin1 (subseq text 0 40) stream)
463 (write-string "..." stream))))
464 (output-c-excursion stream location
465 (lambda () (write-string text stream))))))
466
467 (defmethod make-load-form ((fragment c-fragment) &optional environment)
468 (make-load-form-saving-slots fragment :environment environment))
469
470 (defun scan-c-fragment (lexer end-chars)
471 "Snarfs a sequence of C tokens with balanced brackets.
472
473 Reads and consumes characters from the LEXER's stream, and returns them as
474 a string. The string will contain whole C tokens, up as far as an
475 occurrence of one of the END-CHARS (a list) which (a) is not within a
476 string or character literal or comment, and (b) appears at the outer level
477 of nesting of brackets (whether round, curly or square -- again counting
478 only brackets which aren't themselves within string/character literals or
479 comments. The final END-CHAR is not consumed.
480
481 An error is signalled if either the stream ends before an occurrence of
482 one of the END-CHARS, or if mismatching brackets are encountered. No
483 other attempt is made to ensure that the characters read are in fact a
484 valid C fragment.
485
486 Both original /*...*/ and new //... comments are recognized. Trigraphs
487 and digraphs are currently not recognized."
488
489 (let ((output (make-string-output-stream))
490 (ch (lexer-char lexer))
491 (start-floc (file-location lexer))
492 (delim nil)
493 (stack nil))
494
495 ;; Main loop. At the top of this loop, we've already read a
496 ;; character into CH. This is usually read at the end of processing
497 ;; the individual character, though sometimes (following `/', for
498 ;; example) it's read speculatively because we need one-character
499 ;; lookahead.
500 (block loop
501 (labels ((getch ()
502 "Read the next character into CH; complain if we hit EOF."
503 (unless (setf ch (next-char lexer))
504 (cerror*-with-location start-floc
505 "Unexpected end-of-file in C fragment")
506 (return-from loop))
507 ch)
508 (putch ()
509 "Write the character to the output buffer."
510 (write-char ch output))
511 (push-delim (d)
512 "Push a closing delimiter onto the stack."
513 (push delim stack)
514 (setf delim d)
515 (getch)))
516
517 ;; Hack: if the first character is a newline, discard it. Otherwise
518 ;; (a) the output fragment will look funny, and (b) the location
519 ;; information will be wrong.
520 (when (eql ch #\newline)
521 (getch))
522
523 ;; And fetch characters.
524 (loop
525
526 ;; Here we're outside any string or character literal, though we
527 ;; may be nested within brackets. So, if there's no delimiter, and
528 ;; we've found the end character, we're done.
529 (when (and (null delim) (member ch end-chars))
530 (return))
531
532 ;; Otherwise take a copy of the character, and work out what to do
533 ;; next.
534 (putch)
535 (case ch
536
537 ;; Starting a literal. Continue until we find a matching
538 ;; character not preceded by a `\'.
539 ((#\" #\')
540 (let ((quote ch))
541 (loop
542 (getch)
543 (putch)
544 (when (eql ch quote)
545 (return))
546 (when (eql ch #\\)
547 (getch)
548 (putch)))
549 (getch)))
550
551 ;; Various kinds of opening bracket. Stash the current
552 ;; delimiter, and note that we're looking for a new one.
553 (#\( (push-delim #\)))
554 (#\[ (push-delim #\]))
555 (#\{ (push-delim #\}))
556
557 ;; Various kinds of closing bracket. If it matches the current
558 ;; delimeter then unstack the next one along. Otherwise
559 ;; something's gone wrong: C syntax doesn't allow unmatched
560 ;; brackets.
561 ((#\) #\] #\})
562 (if (eql ch delim)
563 (setf delim (pop stack))
564 (cerror* "Unmatched `~C'." ch))
565 (getch))
566
567 ;; A slash. Maybe a comment next. But maybe not...
568 (#\/
569
570 ;; Examine the next character to find out how to proceed.
571 (getch)
572 (case ch
573
574 ;; A second slash -- eat until the end of the line.
575 (#\/
576 (putch)
577 (loop
578 (getch)
579 (putch)
580 (when (eql ch #\newline)
581 (return)))
582 (getch))
583
584 ;; A star -- eat until we find a star-slash. Since the star
585 ;; might be preceded by another star, we use a little state
586 ;; machine.
587 (#\*
588 (putch)
589 (tagbody
590
591 main
592 ;; Main state. If we read a star, switch to star state;
593 ;; otherwise eat the character and try again.
594 (getch)
595 (putch)
596 (case ch
597 (#\* (go star))
598 (t (go main)))
599
600 star
601 ;; Star state. If we read a slash, we're done; if we read
602 ;; another star, stay in star state; otherwise go back to
603 ;; main.
604 (getch)
605 (putch)
606 (case ch
607 (#\* (go star))
608 (#\/ (go done))
609 (t (go main)))
610
611 done
612 (getch)))))
613
614 ;; Something else. Eat it and continue.
615 (t (getch)))))
616
617 ;; Return the fragment we've collected.
618 (make-instance 'c-fragment
619 :location start-floc
620 :text (get-output-stream-string output)))))
621
622 (defun c-fragment-reader (stream char arg)
623 "Reader for C-fragment syntax #{ ... stuff ... }."
624 (declare (ignore char arg))
625 (let ((lexer (make-instance 'sod-lexer
626 :stream stream)))
627 (next-char lexer)
628 (scan-c-fragment lexer '(#\}))))
629
630 #+interactive
631 (set-dispatch-macro-character #\# #\{ 'c-fragment-reader)
632
633 ;;;--------------------------------------------------------------------------
634 ;;; Testing cruft.
635
636 #+test
637 (with-input-from-string (in "
638 { foo } 'x' /?/***/!
639 123 0432 0b010123 0xc0ffee __burp_32 class
640
641 0xturning 0xfattening
642 ...
643
644 class integer : integral_domain {
645 something here;
646 }
647
648 ")
649 (let* ((stream (make-instance 'position-aware-input-stream
650 :stream in
651 :file #p"magic"))
652 (lexer (make-instance 'sod-lexer
653 :stream stream
654 :keywords *sod-keywords*))
655 (list nil))
656 (next-char lexer)
657 (loop
658 (multiple-value-bind (tokty tokval) (next-token lexer)
659 (push (list tokty tokval) list)
660 (when (eql tokty :eof)
661 (return))))
662 (nreverse list)))
663
664 ;;;----- That's all, folks --------------------------------------------------