raz / sbcl / src / scan.lisp

282 lines · 14.9 KiB · raw · history · last change 55bc6c0d

1;;;; scan.lisp -- the scanner: a file's bytes into a vector of tokens.
2;;;;
3;;;; Report, section 2. The whole file is checked to be UTF-8 first, then
4;;;; cut into tokens, each with its line and column (counted in
5;;;; characters), which the parser reads by index. Reading the whole file
6;;;; at once lets the parser go back, as it does to read a generic
7;;;; module's type arguments where the instance is made (section 3).
8;;;;
9;;;; A code procedure's body (section 8) isn't raz: after the word `code`
10;;;; the scanner takes each instruction, up to its `;`, as raw text, until
11;;;; an instruction that starts with `end`.
12
13(in-package :raz)
14
15;;; Errors. Every error the compiler finds is a RAZ-ERROR, whose text
16;;; already says where it is; the driver prints it and stops (appendix A
17;;; lets an implementation report as few errors as one).
18
19(define-condition raz-error (error)
20 ((text :initarg :text :reader raz-error-text))
21 (:report (lambda (c s) (write-string (raz-error-text c) s))))
22
23(defvar *file* "?" "The name of the file being read, for messages.")
24
25(defun fail-at (line col fmt &rest args)
26 (error 'raz-error
27 :text (format nil "~a:~d:~d: ~?" *file* line col fmt args)))
28
29;;; Tokens. KIND is :ident, :int, :real, :char, :string, :code, :blank,
30;;; :eof, or a keyword naming a reserved word or an operator, such as
31;;; :begin or :|:=|. VAL is an identifier's text, a number's value, a
32;;; string's bytes, or a code body's instructions.
33
34(defstruct (tok (:constructor make-tok (kind val line col)))
35 kind val line col)
36
37(defparameter *reserved*
38 '("and" "begin" "break" "by" "code" "const" "defer" "div" "do" "else"
39 "elsif" "end" "extern" "for" "forward" "if" "import" "in" "link"
40 "match" "mod" "module" "not" "of" "or" "packed" "proc" "record"
41 "repeat" "return" "set" "shl" "shr" "then" "to" "try" "type" "until"
42 "var" "variant" "VOLATILE" "while" "xor"))
43
44;;; Operators, longest first, so that `:=` is found before `:`.
45(defparameter *operators*
46 '("..." ".." ":=" "<=" ">=" "+" "-" "*" "/" "&" "|" "~" "=" "#" "<" ">"
47 ":" ";" "," "." "(" ")" "[" "]" "{" "}" "^"))
48
49(defun keyword-of (text) (intern text :keyword))
50
51;;; UTF-8. Section 2: no malformed or overlong sequence, no surrogate,
52;;; nothing past 10FFFFH, and no NUL byte anywhere.
53
54(defun check-utf8 (bytes)
55 (let ((i 0) (n (length bytes)) (line 1))
56 (flet ((bad () (fail-at line 1 "the file isn't valid UTF-8")))
57 (loop while (< i n) do
58 (let* ((b (aref bytes i))
59 (len (cond ((< b #x80) 1) ((< b #xC2) 0) ((< b #xE0) 2)
60 ((< b #xF0) 3) ((< b #xF5) 4) (t 0))))
61 (when (= b 0) (fail-at line 1 "the file has a NUL byte"))
62 (when (= b 10) (incf line))
63 (when (or (= len 0) (> (+ i len) n)) (bad))
64 (let ((cp (if (= len 1) b (logand b (ash #x7F (- len))))))
65 (loop for k from 1 below len
66 for c = (aref bytes (+ i k))
67 do (unless (= (logand c #xC0) #x80) (bad))
68 (setf cp (logior (ash cp 6) (logand c #x3F))))
69 ;; the least code point each length may hold, against overlong forms
70 (when (or (< cp (aref #(0 0 #x80 #x800 #x10000) len))
71 (<= #xD800 cp #xDFFF) (> cp #x10FFFF))
72 (bad)))
73 (incf i len))))))
74
75(defun utf8-encode (cp)
76 "The UTF-8 bytes of code point CP, as a list."
77 (cond ((< cp #x80) (list cp))
78 ((< cp #x800) (list (logior #xC0 (ash cp -6)) (logior #x80 (logand cp #x3F))))
79 ((< cp #x10000) (list (logior #xE0 (ash cp -12))
80 (logior #x80 (logand (ash cp -6) #x3F))
81 (logior #x80 (logand cp #x3F))))
82 (t (list (logior #xF0 (ash cp -18))
83 (logior #x80 (logand (ash cp -12) #x3F))
84 (logior #x80 (logand (ash cp -6) #x3F))
85 (logior #x80 (logand cp #x3F))))))
86
87;;; The scanner proper. It walks the bytes with POS, keeping LINE and the
88;;; column COL of the byte at POS, in characters.
89
90(defun scan (bytes)
91 "The tokens of BYTES, a file's contents, ending in an :eof token."
92 (check-utf8 bytes)
93 (let ((pos 0) (line 1) (col 1) (toks '()) (n (length bytes)))
94 (labels ((peek (&optional (k 0))
95 (if (< (+ pos k) n) (aref bytes (+ pos k)) 0))
96 (next ()
97 (let ((b (aref bytes pos)))
98 (incf pos)
99 (cond ((= b 10) (incf line) (setf col 1))
100 ;; a continuation byte doesn't start a character
101 ((/= (logand b #xC0) #x80) (incf col)))
102 b))
103 (err (fmt &rest args) (apply #'fail-at line col fmt args))
104 (letter-p (b) (or (<= 65 b 90) (<= 97 b 122) (= b 95)))
105 (digit-p (b) (<= 48 b 57))
106 (hex-p (b) (or (digit-p b) (<= 65 b 70)))
107 (any-hex-p (b) (or (hex-p b) (<= 97 b 102)))
108 (hex-value (b) (digit-char-p (code-char b) 16))
109 (skip-space-and-comments ()
110 (loop
111 (cond ((member (peek) '(32 9 10 13)) (next))
112 ((and (= (peek) 40) (= (peek 1) 42)) (comment))
113 (t (return)))))
114 (comment ()
115 ;; comments nest: `(*` opens one more, `*)` closes one
116 (let ((l line) (c col) (depth 0))
117 (loop
118 (cond ((>= pos n) (fail-at l c "the comment never ends"))
119 ((and (= (peek) 40) (= (peek 1) 42)) (next) (next) (incf depth))
120 ((and (= (peek) 42) (= (peek 1) 41)) (next) (next)
121 (when (= (decf depth) 0) (return)))
122 (t (next))))))
123 (add (kind val l c) (push (make-tok kind val l c) toks))
124 (word (l c)
125 (let ((start pos))
126 (loop while (or (letter-p (peek)) (digit-p (peek))) do (next))
127 (let ((text (map 'string #'code-char (subseq bytes start pos))))
128 (when (> (length text) 63)
129 (fail-at l c "the name ~a... is longer than 63 characters" (subseq text 0 20)))
130 (cond ((string= text "_") (add :blank nil l c))
131 ((member text *reserved* :test #'string=)
132 (add (keyword-of (string-upcase text)) nil l c)
133 ;; a code body follows `code` after a signature's `;`
134 (when (and (string= text "code") (rest toks)
135 (eq (tok-kind (second toks)) :|;|))
136 (code-body)))
137 (t (add :ident text l c))))))
138 (number (l c)
139 ;; digits and capitals A-F; then H for hexadecimal, or a
140 ;; point and a digit for a real
141 (let ((start pos))
142 (loop while (hex-p (peek)) do (next))
143 (let ((text (map 'string #'code-char (subseq bytes start pos))))
144 (cond ((= (peek) 72) ; H
145 (next)
146 (let ((v (parse-integer text :radix 16)))
147 (when (>= v (expt 2 64))
148 (fail-at l c "the number ~aH is above the largest U64" text))
149 (add :int v l c)))
150 ((find-if (lambda (ch) (char<= #\A ch #\F)) text)
151 (fail-at l c "a hexadecimal number ends in H: ~a" text))
152 ((and (= (peek) 46) (digit-p (peek 1)))
153 (real-number text l c))
154 ((or (letter-p (peek)))
155 (err "a number is followed by a letter"))
156 (t (let ((v (parse-integer text)))
157 (when (>= v (expt 2 63))
158 (fail-at l c "the number ~a is above the largest I64" text))
159 (add :int v l c)))))))
160 (real-number (whole l c)
161 ;; the value as an exact fraction, rounded once to an F64
162 (next) ; the point
163 (let ((start pos) (exp 0))
164 (loop while (digit-p (peek)) do (next))
165 (let* ((frac (map 'string #'code-char (subseq bytes start pos)))
166 (mant (parse-integer (concatenate 'string whole frac))))
167 (when (= (peek) 69) ; E
168 (next)
169 (let ((sign 1) (s pos))
170 (cond ((= (peek) 43) (next)) ((= (peek) 45) (next) (setf sign -1)))
171 (setf s pos)
172 (unless (digit-p (peek)) (err "an exponent needs digits"))
173 (loop while (digit-p (peek)) do (next))
174 (setf exp (* sign (parse-integer (map 'string #'code-char (subseq bytes s pos)))))))
175 (when (or (letter-p (peek)) (digit-p (peek)))
176 (err "a real is followed by ~a" (code-char (peek))))
177 ;; an exponent too far out either way needn't be computed
178 (let ((value (cond ((= mant 0) 0d0)
179 ((> (+ exp (length whole)) 400) nil)
180 ((< (+ exp (length whole)) -400) 0d0)
181 (t (let ((r (* mant (expt 10 (- exp (length frac))))))
182 (if (> r most-positive-double-float)
183 nil
184 (coerce r 'double-float)))))))
185 (unless value (fail-at l c "the real is above the largest F64"))
186 (add :real value l c)))))
187 (escape (in-string)
188 ;; after a backslash: the code point, or (:byte b) for \xHH
189 (let ((b (if (< pos n) (next) 0)))
190 (case (code-char b)
191 (#\n 10) (#\t 9) (#\r 13) (#\0 0) (#\\ 92) (#\' 39) (#\" 34)
192 (#\x (unless in-string (err "\\x is for strings only"))
193 (unless (and (any-hex-p (peek)) (any-hex-p (peek 1)))
194 (err "\\x takes two hexadecimal digits"))
195 (list :byte (+ (* 16 (hex-value (next))) (hex-value (next)))))
196 (#\u (unless (= (next) 123) (err "\\u is followed by {"))
197 (let ((v 0) (k 0))
198 (loop while (any-hex-p (peek))
199 do (setf v (+ (* v 16) (hex-value (next)))) (incf k)
200 (when (> v #x10FFFF) (err "\\u{...} is above 10FFFFH")))
201 (unless (and (> k 0) (= (peek) 125)) (err "\\u{...} wants hexadecimal digits and }"))
202 (next)
203 (when (<= #xD800 v #xDFFF) (err "\\u{...} is a surrogate"))
204 v))
205 (t (err "unknown escape \\~a" (code-char b))))))
206 (char-code-at ()
207 ;; the code point of the UTF-8 character at pos
208 (let* ((b (next)) (len (cond ((< b #x80) 1) ((< b #xE0) 2) ((< b #xF0) 3) (t 4)))
209 (cp (if (= len 1) b (logand b (ash #x7F (- len))))))
210 (loop repeat (1- len) do (setf cp (logior (ash cp 6) (logand (next) #x3F))))
211 cp))
212 (char-literal (l c)
213 (next)
214 (when (member (peek) '(39 10 0)) (fail-at l c "a character literal holds one character"))
215 (let ((v (if (= (peek) 92) (progn (next) (escape nil)) (char-code-at))))
216 (unless (= (peek) 39) (fail-at l c "the character literal isn't closed"))
217 (next)
218 (add :char v l c)))
219 (string-literal (l c)
220 (next)
221 (let ((out (make-array 0 :element-type '(unsigned-byte 8) :adjustable t :fill-pointer 0)))
222 (loop
223 (let ((b (peek)))
224 (cond ((or (>= pos n) (= b 10)) (fail-at l c "the string isn't closed on its line"))
225 ((= b 34) (next) (return))
226 ((= b 92) (next)
227 (let ((e (escape t)))
228 (if (consp e)
229 (vector-push-extend (second e) out)
230 (dolist (x (utf8-encode e)) (vector-push-extend x out)))))
231 (t (vector-push-extend (next) out)))))
232 (add :string (coerce out '(simple-array (unsigned-byte 8) (*))) l c)))
233 (code-body ()
234 ;; raw instructions up to the one that starts with `end`
235 (let ((instrs '()))
236 (loop
237 ;; only spaces: `(*` here is Lisp's multiplication
238 (loop while (member (peek) '(32 9 10 13)) do (next))
239 (when (>= pos n) (err "the code procedure never ends"))
240 (let ((l line) (c col) (start pos) (depth 0) (in-str nil))
241 (loop while (< pos n)
242 do (let ((b (peek)))
243 (cond (in-str (when (= b 92) (next)) (when (= b 34) (setf in-str nil)))
244 ((= b 34) (setf in-str t))
245 ((= b 40) (incf depth))
246 ((= b 41) (decf depth))
247 ((and (= b 59) (= depth 0)) (return)))
248 (next)))
249 (let ((text (string-trim '(#\Space #\Tab #\Newline #\Return)
250 (sb-ext:octets-to-string (subseq bytes start pos) :external-format :utf-8))))
251 (when (and (>= (length text) 3) (string= "end" text :end2 3)
252 (or (= (length text) 3) (not (alphanumericp (char text 3)))))
253 ;; give back the `end` for the parser
254 (setf pos start line l col c)
255 (return))
256 (push (list text l c) instrs)
257 (when (< pos n) (next)))))
258 (add :code (nreverse instrs) line col)))
259 (operator (l c)
260 (dolist (op *operators* (err "unknown character ~a" (code-char (peek))))
261 (when (loop for k below (length op)
262 always (= (peek k) (char-code (char op k))))
263 (loop repeat (length op) do (next))
264 (return (add (keyword-of op) nil l c))))))
265 (loop
266 (skip-space-and-comments)
267 (when (>= pos n) (return))
268 (let ((b (peek)) (l line) (c col))
269 (cond ((letter-p b) (word l c))
270 ((digit-p b) (number l c))
271 ((= b 39) (char-literal l c))
272 ((= b 34) (string-literal l c))
273 ((>= b 128) (err "a character outside ASCII, outside a string or a comment"))
274 (t (operator l c)))))
275 (add :eof nil line col)
276 (coerce (nreverse toks) 'vector))))
277
278(defun read-bytes (path)
279 (with-open-file (s path :element-type '(unsigned-byte 8))
280 (let ((v (make-array (file-length s) :element-type '(unsigned-byte 8))))
281 (read-sequence v s)
282 v)))