src/c-types-parse.lisp, src/c-types-proto.lisp: Some minor cleanups.
[sod] / src / c-types-parse.lisp
CommitLineData
dea4d055
MW
1;;; -*-lisp-*-
2;;;
3;;; Parser for C types
4;;;
5;;; (c) 2009 Straylight/Edgeware
6;;;
7
8;;;----- Licensing notice ---------------------------------------------------
9;;;
e0808c47 10;;; This file is part of the Sensible Object Design, an object system for C.
dea4d055
MW
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;;; Declaration specifiers.
bf090e02
MW
30;;;
31;;; This stuff is distressingly complicated.
32;;;
33;;; Parsing a (single) declaration specifier is quite easy, and a declaration
34;;; is just a sequence of these things. Except that there are a stack of
35;;; rules about which ones are allowed to go together, and the language
36;;; doesn't require them to appear in any particular order.
37;;;
38;;; A collection of declaration specifiers is carried about in a purpose-made
39;;; object with a number of handy operations defined on it, and then I build
40;;; some parsers in terms of them. The basic strategy is to parse
41;;; declaration specifiers while they're valid, and keep track of what we've
42;;; read. When I've reached the end, we'll convert what we've got into a
43;;; `canonical form', and then convert that into a C type object of the
44;;; appropriate kind. The whole business is rather more complicated than it
45;;; really ought to be.
46
47;; Firstly, a table of interesting things about the various declaration
48;; specifiers that I might encounter. I categorize declaration specifiers
49;; into four kinds.
50;;
51;; * `Type specifiers' describe the actual type, whether that's integer,
52;; character, floating point, or some tagged or user-named type.
53;;
54;; * `Size specifiers' distinguish different sizes of the same basic type.
55;; This is how we tell the difference between `int' and `long'.
56;;
57;; * `Sign specifiers' distinguish different signednesses. This is how we
58;; tell the difference between `int' and `unsigned'.
59;;
60;; * `Qualifiers' are our old friends `const', `restrict' and `volatile'.
61;;
62;; These groupings are for my benefit here, in determining whether a
63;; particular declaration specifier is valid in the current context. I don't
64;; accept `function specifiers' (of which the only current example is
65;; `inline') since it's meaningless to me.
dea4d055
MW
66
67(defclass declspec ()
239fa5bd
MW
68 ;; Despite the fact that it looks pretty trivial, this can't be done with
69 ;; `defstruct' for the simple reason that we add more methods to the
70 ;; accessor functions later.
dea4d055
MW
71 ((label :type keyword :initarg :label :reader ds-label)
72 (name :type string :initarg :name :reader ds-name)
1645e433 73 (kind :type (member type complexity sign size qualifier)
bf090e02
MW
74 :initarg :kind :reader ds-kind)
75 (taggedp :type boolean :initarg :taggedp
76 :initform nil :reader ds-taggedp))
77 (:documentation
78 "Represents the important components of a declaration specifier.
79
8d3d1674
MW
80 The only interesting instances of this class are in the table
81 `*declspec-map*'."))
dea4d055
MW
82
83(defmethod shared-initialize :after ((ds declspec) slot-names &key)
bf090e02
MW
84 "If no name is provided then derive one from the label.
85
86 Most declaration specifiers have simple names for which this works well."
dea4d055
MW
87 (default-slot (ds 'name slot-names)
88 (string-downcase (ds-label ds))))
89
dea4d055
MW
90(defparameter *declspec-map*
91 (let ((map (make-hash-table :test #'equal)))
0e7cdea0
MW
92 (dolist (item '((type :void :char :int :float :double
93 (:bool :name "_Bool"))
94 (complexity (:complex :name "_Complex")
95 (:imaginary :name "_Imaginary"))
bf090e02
MW
96 ((type :taggedp t) :enum :struct :union)
97 (size :short :long (:long-long :name "long long"))
dea4d055 98 (sign :signed :unsigned)
bf090e02
MW
99 (qualifier :const :restrict :volatile)))
100 (destructuring-bind (kind &key (taggedp nil))
101 (let ((spec (car item)))
102 (if (consp spec) spec (list spec)))
dea4d055 103 (dolist (spec (cdr item))
bf090e02
MW
104 (destructuring-bind (label
105 &key
106 (name (string-downcase label))
107 (taggedp taggedp))
108 (if (consp spec) spec (list spec))
dea4d055 109 (let ((ds (make-instance 'declspec
bf090e02
MW
110 :label label
111 :name name
112 :kind kind
113 :taggedp taggedp)))
dea4d055
MW
114 (setf (gethash name map) ds
115 (gethash label map) ds))))))
0e7cdea0
MW
116 (dolist (label '(:complex :imaginary :bool))
117 (setf (gethash (string-downcase label) map) (gethash label map)))
bf090e02 118 map)
3109662a 119 "Maps symbolic labels and textual names to `declspec' instances.")
bf090e02
MW
120
121;; A collection of declaration specifiers, and how to merge them together.
122
123(defclass declspecs ()
239fa5bd
MW
124 ;; This could have been done with `defstruct' just as well, but a
125 ;; `defclass' can be tweaked interactively, which is a win at the moment.
bf090e02 126 ((type :initform nil :initarg :type :reader ds-type)
0e7cdea0 127 (complexity :initform nil :initarg :complexity :reader ds-complexity)
bf090e02
MW
128 (sign :initform nil :initarg :sign :reader ds-sign)
129 (size :initform nil :initarg :size :reader ds-size)
130 (qualifier :initform nil :initarg :qualifiers :reader ds-qualifiers))
8d3d1674
MW
131 (:documentation "Represents a collection of declaration specifiers.
132
133 This is used during type parsing to represent the type under construction.
134 Instances are immutable: we build new ones rather than modifying existing
135 ones. This leads to a certain amount of churn, but we'll just have to
136 live with that.
137
138 (Why are instances immutable? Because it's much easier to merge a new
139 specifier into an existing collection and then check that the resulting
140 thing is valid, rather than having to deal with all of the possible
141 special cases of what the new thing might be. And if the merged
142 collection isn't good, I must roll back to the previous version. So I
143 don't get to take advantage of a mutable structure.)"))
dea4d055
MW
144
145(defmethod ds-label ((ty c-type)) :c-type)
146(defmethod ds-name ((ty c-type)) (princ-to-string ty))
147(defmethod ds-kind ((ty c-type)) 'type)
148
149(defparameter *good-declspecs*
0e7cdea0
MW
150 '(((:int) (:signed :unsigned) (:short :long :long-long) ())
151 ((:char) (:signed :unsigned) () ())
152 ((:double) () (:long) (:complex :imaginary))
153 (t () () ()))
dea4d055
MW
154 "List of good collections of declaration specifiers.
155
0e7cdea0
MW
156 Each item is a list of the form (TYPES SIGNS SIZES COMPLEXITIES). Each of
157 TYPES, SIGNS, SIZES, and COMPLEXITIES, is either a list of acceptable
158 specifiers of the appropriate kind, or T, which matches any specifier.")
dea4d055 159
dea4d055
MW
160(defun good-declspecs-p (specs)
161 "Are SPECS a good collection of declaration specifiers?"
0e7cdea0
MW
162 (let ((speclist (list (ds-type specs)
163 (ds-sign specs)
164 (ds-size specs)
165 (ds-complexity specs))))
dea4d055
MW
166 (some (lambda (it)
167 (every (lambda (spec pat)
168 (or (eq pat t) (null spec)
169 (member (ds-label spec) pat)))
170 speclist it))
171 *good-declspecs*)))
172
173(defun combine-declspec (specs ds)
174 "Combine the declspec DS with the existing SPECS.
175
176 Returns new DECLSPECS if they're OK, or `nil' if not. The old SPECS are
177 not modified."
bf090e02 178
dea4d055
MW
179 (let* ((kind (ds-kind ds))
180 (old (slot-value specs kind)))
181 (multiple-value-bind (ok new)
182 (case kind
183 (qualifier (values t (adjoin ds old)))
184 (size (cond ((not old) (values t ds))
185 ((and (eq (ds-label old) :long) (eq ds old))
186 (values t (gethash :long-long *declspec-map*)))
187 (t (values nil nil))))
188 (t (values (not old) ds)))
189 (if ok
190 (let ((copy (copy-instance specs)))
191 (setf (slot-value copy kind) new)
192 (and (good-declspecs-p copy) copy))
193 nil))))
194
dea4d055 195(defun declspecs-type (specs)
bf090e02 196 "Convert `declspecs' SPECS into a standalone C type object."
dea4d055
MW
197 (let ((type (ds-type specs))
198 (size (ds-size specs))
bf090e02 199 (sign (ds-sign specs))
5ce911a0 200 (cplx (ds-complexity specs))
bf090e02
MW
201 (quals (mapcar #'ds-label (ds-qualifiers specs))))
202 (cond ((typep type 'c-type)
203 (qualify-c-type type quals))
5ce911a0 204 ((or type size sign cplx)
bf090e02 205 (when (and sign (eq (ds-label sign) :signed)
dea4d055
MW
206 (eq (ds-label type) :int))
207 (setf sign nil))
208 (cond ((and (or (null type) (eq (ds-label type) :int))
209 (or size sign))
210 (setf type nil))
211 ((null type)
212 (setf type (gethash :int *declspec-map*))))
213 (make-simple-type (format nil "~{~@[~A~^ ~]~}"
239fa5bd 214 (mapcar #'ds-name
dea4d055 215 (remove nil
5ce911a0
MW
216 (list sign cplx
217 size type))))
bf090e02 218 quals))
dea4d055
MW
219 (t
220 nil))))
221
bf090e02 222;; Parsing declaration specifiers.
dea4d055 223
bf090e02 224(define-indicator :declspec "<declaration-specifier>")
dea4d055 225
bf090e02
MW
226(defun scan-declspec
227 (scanner &key (predicate (constantly t)) (indicator :declspec))
3109662a 228 "Scan a `declspec' from SCANNER.
dea4d055 229
bf090e02
MW
230 If PREDICATE is provided then only succeed if (funcall PREDICATE DECLSPEC)
231 is true, where DECLSPEC is the raw declaration specifier or C-type object,
232 so we won't have fetched the tag for a tagged type yet. If the PREDICATE
233 returns false then the scan fails without consuming input.
dea4d055 234
bf090e02
MW
235 If we couldn't find an acceptable declaration specifier then issue
236 INDICATOR as the failure indicator. Value on success is either a
237 `declspec' object or a `c-type' object."
dea4d055 238
bf090e02
MW
239 ;; Turns out to be easier to do this by hand.
240 (let ((ds (and (eq (token-type scanner) :id)
241 (let ((kw (token-value scanner)))
ec5cb3ca
MW
242 (or (and (boundp '*module-type-map*)
243 (gethash kw *module-type-map*))
bf090e02
MW
244 (gethash kw *declspec-map*))))))
245 (cond ((or (not ds) (and predicate (not (funcall predicate ds))))
246 (values (list indicator) nil nil))
8293b90a 247 ((and (typep ds 'declspec) (ds-taggedp ds))
bf090e02
MW
248 (scanner-step scanner)
249 (if (eq (token-type scanner) :id)
250 (let ((ty (make-c-tagged-type (ds-label ds)
251 (token-value scanner))))
252 (scanner-step scanner)
253 (values ty t t))
254 (values :tag nil t)))
255 (t
256 (scanner-step scanner)
257 (values ds t t)))))
dea4d055 258
bf090e02
MW
259(defun scan-and-merge-declspec (scanner specs)
260 "Scan a declaration specifier and merge it with SPECS.
261
262 This is a parser function. If it succeeds, it returns the merged
263 `declspecs' object. It can fail either if no valid declaration specifier
264 is found or it cannot merge the declaration specifier with the existing
265 SPECS."
266
267 (with-parser-context (token-scanner-context :scanner scanner)
268 (if-parse (:consumedp consumedp) (scan-declspec scanner)
269 (aif (combine-declspec specs it)
270 (values it t consumedp)
271 (values (list :declspec) nil consumedp)))))
272
239fa5bd 273(export 'parse-c-type)
bf090e02
MW
274(defun parse-c-type (scanner)
275 "Parse a C type from declaration specifiers.
dea4d055 276
bf090e02
MW
277 This is a parser function. If it succeeds then the result is a `c-type'
278 object representing the type it found. Note that this function won't try
279 to parse a C declarator."
dea4d055 280
bf090e02
MW
281 (with-parser-context (token-scanner-context :scanner scanner)
282 (if-parse (:result specs :consumedp cp)
283 (many (specs (make-instance 'declspecs) it :min 1)
284 (peek (scan-and-merge-declspec scanner specs)))
285 (let ((type (declspecs-type specs)))
286 (if type (values type t cp)
287 (values (list :declspec) nil cp))))))
dea4d055 288
bf090e02
MW
289;;;--------------------------------------------------------------------------
290;;; Parsing declarators.
291;;;
292;;; The syntax of declaration specifiers was horrific. Declarators are a
293;;; very simple expression syntax, but this time the semantics are awful. In
294;;; particular, they're inside-out. If <> denotes mumble of foo, then op <>
295;;; is something like mumble of op of foo. Unfortunately, the expression
296;;; parser engine wants to apply op of mumble of foo, so I'll have to do some
297;;; work to fix the impedance mismatch.
298;;;
299;;; The currency we'll use is a pair (FUNC . NAME), with the semantics that
300;;; (funcall FUNC TYPE) returns the derived type. The result of
301;;; `parse-declarator' will be of this form.
dea4d055 302
239fa5bd 303(export 'parse-declarator)
ea578bb4 304(defun parse-declarator (scanner base-type &key kernel abstractp)
239fa5bd 305 "Parse a C declarator, returning a pair (C-TYPE . NAME).
dea4d055 306
239fa5bd
MW
307 The SCANNER is a token scanner to read from. The BASE-TYPE is the type
308 extracted from the preceding declaration specifiers, as parsed by
309 `parse-c-type'.
310
311 The result contains both the resulting constructed C-TYPE (with any
312 qualifiers etc. as necessary), and the name from the middle of the
ea578bb4 313 declarator. The name is parsed using the KERNEL parser provided, and
239fa5bd
MW
314 defaults to matching a simple identifier `:id'. This might, e.g., be
315 (? :id) to parse an `abstract declarator' which has optional names.
316
ea578bb4 317 There's an annoying ambiguity in the syntax, if an empty KERNEL is
239fa5bd
MW
318 permitted. In this case, you must ensure that ABSTRACTP is true so that
319 the appropriate heuristic can be applied. As a convenience, if ABSTRACTP
ea578bb4 320 is true then `(? :id)' is used as the default KERNEL."
239fa5bd 321 (with-parser-context (token-scanner-context :scanner scanner)
ea578bb4 322 (let ((kernel-parser (cond (kernel kernel)
239fa5bd
MW
323 (abstractp (parser () (? :id)))
324 (t (parser () :id)))))
325
326 (labels ((qualifiers ()
327 ;; qualifier*
328
329 (parse
330 (seq ((quals (list ()
331 (scan-declspec
332 scanner
333 :indicator :qualifier
334 :predicate (lambda (ds)
335 (and (typep ds 'declspec)
336 (eq (ds-kind ds)
337 'qualifier)))))))
338 (mapcar #'ds-label quals))))
339
340 (star ()
341 ;; Prefix: `*' qualifiers
342
343 (parse (seq (#\* (quals (qualifiers)))
344 (preop "*" (state 9)
345 (cons (lambda (type)
346 (funcall (car state)
347 (make-pointer-type type quals)))
348 (cdr state))))))
349
c28f6ae9
MW
350 (predict-argument-list-p ()
351 ;; See `prefix-lparen'. Predict an argument list rather
352 ;; than a nested declarator if (a) abstract declarators are
353 ;; permitted and (b) the next token is a declaration
354 ;; specifier or ellipsis.
355 (let ((type (token-type scanner))
356 (value (token-value scanner)))
357 (and abstractp
358 (or (eq type :ellipsis)
359 (and (eq type :id)
360 (or (gethash value *module-type-map*)
361 (gethash value *declspec-map*)))))))
239fa5bd
MW
362
363 (prefix-lparen ()
364 ;; Prefix: `('
365 ;;
366 ;; Opening parentheses are treated as prefix operators by
367 ;; the expression parsing engine. There's an annoying
368 ;; ambiguity in the syntax if abstract declarators are
369 ;; permitted: a `(' might be either the start of a nested
370 ;; subdeclarator or the start of a postfix function argument
371 ;; list. The two are disambiguated by stating that if the
372 ;; token following the `(' is a `)' or a declaration
373 ;; specifier, then we have a postfix argument list.
374 (parse
375 (peek (seq (#\(
c28f6ae9 376 (nil (if (predict-argument-list-p)
239fa5bd
MW
377 (values nil nil nil)
378 (values t t nil))))
379 (lparen #\))))))
380
ea578bb4
MW
381 (kernel ()
382 (parse (seq ((name (funcall kernel-parser)))
239fa5bd
MW
383 (cons #'identity name))))
384
385 (argument-list ()
63a86f42 386 ;; [argument [`,' argument]* [`,' `...']] | `...'
b0ff693c
MW
387 ;;
388 ;; The possibility of a trailing `,' `...' means that we
389 ;; can't use the standard `list' parser. Note that, unlike
390 ;; `real' C, we allow an ellipsis even if there are no
391 ;; explicit arguments.
392
393 (let ((args nil))
394 (loop
395 (when (eq (token-type scanner) :ellipsis)
396 (push :ellipsis args)
397 (scanner-step scanner)
398 (return))
399 (multiple-value-bind (arg winp consumedp)
400 (parse (seq ((base-type (parse-c-type scanner))
401 (dtor (parse-declarator scanner
402 base-type
403 :abstractp t)))
404 (make-argument (cdr dtor) (car dtor))))
405 (unless winp
406 (if (or consumedp args)
407 (return-from argument-list (values arg nil t))
408 (return)))
409 (push arg args))
410 (unless (eq (token-type scanner) #\,)
411 (return))
412 (scanner-step scanner))
413 (values (nreverse args) t args)))
239fa5bd
MW
414
415 (postfix-lparen ()
416 ;; Postfix: `(' argument-list `)'
417
418 (parse (seq (#\( (args (argument-list)) #\))
419 (postop "()" (state 10)
420 (cons (lambda (type)
421 (funcall (car state)
422 (make-function-type type args)))
423 (cdr state))))))
424
425 (dimension ()
426 ;; `[' c-fragment ']'
427
428 (parse (seq ((frag (parse-delimited-fragment
429 scanner #\[ #\])))
430 (c-fragment-text frag))))
431
432 (lbracket ()
433 ;; Postfix: dimension+
434
435 (parse (seq ((dims (list (:min 1) (dimension))))
436 (postop "[]" (state 10)
437 (cons (lambda (type)
438 (funcall (car state)
439 (make-array-type type dims)))
440 (cdr state)))))))
441
442 ;; And now we actually do the declarator parsing.
443 (parse (seq ((value (expr (:nestedp nestedp)
444
445 ;; An actual operand.
ea578bb4 446 (kernel)
239fa5bd
MW
447
448 ;; Binary operators. There aren't any.
449 nil
450
451 ;; Prefix operators.
452 (or (star)
453 (prefix-lparen))
454
455 ;; Postfix operators.
456 (or (postfix-lparen)
457 (lbracket)
458 (when nestedp (seq (#\)) (rparen #\))))))))
459 (cons (funcall (car value) base-type) (cdr value))))))))
dea4d055
MW
460
461;;;----- That's all, folks --------------------------------------------------