2 * Parse and validate C declarations.
3 * Copyright © 2011-2012, 2020-2021, 2023 Nick Bowler
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25 #include "cdecl-internal.h"
31 * Allocate a "parse item", which is a union of several parse tree
32 * structure types, together with a string buffer. The s_sz argument
33 * specifies the size of the string (including its terminator), which
36 * The union's declarator member is pre-initialized to a valid "identifier"
37 * declarator, which shares several interesting offsets with the "declspec"
38 * structure for an "identifier" type specifier.
40 struct parse_item *cdecl__alloc_item(size_t s_sz)
42 struct parse_item *ret;
44 ret = malloc(offsetof(struct parse_item, s) + s_sz);
46 cdecl__errmsg(CDECL__ENOMEM);
50 ret->u.declarator.child = NULL;
51 ret->u.declarator.type = CDECL_DECL_IDENT;
52 ret->u.declarator.u.ident = ret->s;
58 * We can represent type specifiers as a bitmap, which gives us a finite
59 * list of acceptable bitmap values according to the C standard. However,
60 * the "long" specifier is allowed to occur more than once, but only at most
61 * 2 times. Treat it as a special case, assigning an unused bit to represent
64 #define MAP_LLONG_BIT 31
65 #define MAP_LONG_BIT (CDECL_TYPE_LONG-CDECL_SPEC_TYPE)
66 #define CDECL_TYPE_LLONG (CDECL_SPEC_TYPE+MAP_LLONG_BIT)
71 * Convert the declaration specifiers to a bitmap with each bit
72 * corresponding to one specific type specifier.
74 static int valid_typespec(struct cdecl_declspec *s)
76 unsigned long map = 0;
78 for (struct cdecl_declspec *c = s; c; c = c->next) {
81 if (cdecl_spec_kind(c) != CDECL_SPEC_TYPE)
84 bit = c->type - CDECL_SPEC_TYPE;
85 assert(bit < MAP_LLONG_BIT);
88 /* "long" special case */
89 if ((map & bit) == 1ul << MAP_LONG_BIT)
90 bit = 1ul << MAP_LLONG_BIT;
93 if (bit == 1ul << MAP_LLONG_BIT)
94 cdecl__errmsg(CDECL__ETOOLONG);
96 cdecl__errmsg(CDECL__EDUPTYPE);
102 if (typemap_is_valid(map))
106 cdecl__errmsg(CDECL__ENOTYPE);
108 cdecl__errmsg(CDECL__EBADTYPE);
114 * Verify the declaration specifiers of a declaration. If top is true, treat
115 * this as a top-level declaration. Otherwise, treat this as a function
116 * parameter (which carries additional constraints).
118 static bool valid_declspecs(struct cdecl *decl, bool top)
120 struct cdecl_declspec *specs = decl->specifiers;
121 struct cdecl_declarator *d = decl->declarators;
122 bool abstract = cdecl_is_abstract(d);
123 unsigned num_storage = 0;
125 if (!valid_typespec(specs))
128 for (struct cdecl_declspec *c = specs; c; c = c->next) {
129 switch (cdecl_spec_kind(c)) {
130 case CDECL_SPEC_TYPE:
131 if (c->type == CDECL_TYPE_VOID &&
132 (d->type == CDECL_DECL_IDENT
133 || d->type == CDECL_DECL_ARRAY)) {
134 cdecl__errmsg(CDECL__EBADVOID);
138 case CDECL_SPEC_STOR:
139 if (top && abstract) {
140 cdecl__errmsg(CDECL__ETYPESTOR);
144 if (!top && c->type != CDECL_STOR_REGISTER) {
145 cdecl__errmsg(CDECL__EFUNCSTOR);
149 if (++num_storage > 1) {
150 cdecl__errmsg(CDECL__EMANYSTOR);
154 case CDECL_SPEC_QUAL:
156 * Restrict qualifiers are only valid in the
157 * pointer qualifier list, which isn't checked here.
159 if (c->type == CDECL_QUAL_RESTRICT) {
160 cdecl__errmsg(CDECL__EBADQUAL);
164 case CDECL_SPEC_FUNC:
165 if (abstract || !top || d->type != CDECL_DECL_FUNCTION) {
166 cdecl__errmsg(CDECL__ENOTFUNC);
180 * The C grammar leaves ambiguous some cases where parentheses represent a
181 * function declarator or just parentheses. The language uses additional
182 * context (whether or not a typedef is in scope, etc.) to resolve these
183 * ambiguities, but we don't have access to that kind of information.
185 * The cdecl99 parser uses an unambiguous grammar which treats almost
186 * everything as a function, and thus considers things like 'int (x)' to
187 * be a function type with a single parameter of type 'x' (a typedef name),
188 * returning int. This can result in very complicated types for simple
189 * declarations. Ideally, cdecl99 should try and find the "simplest"
190 * explanation for a given declaration.
192 * Whether or not it achieves the simplest explanation, we apply a simple rule:
193 * if a declarator could be interpreted as something other than a function,
196 * Since cdecl99 supports things like [*] in any context (in C, such constructs
197 * are only valid in function parameter lists), we don't treat them specially
201 static struct cdecl_declarator *reduce_function(struct cdecl *param)
203 struct cdecl_declarator *d, **p = ¶m->declarators;
204 struct parse_item *spec = (void *)param->specifiers;
206 while ((d = *p)->child)
209 if (d->type != CDECL_DECL_NULL)
213 * The child and u.ident members of cdecl_declarator are expected
214 * to be located at identical offsets as, respectively, the next
215 * and ident members within cdecl_declspec, so the expectation is
216 * that the compiler can elide both assignments.
218 spec->u.declarator.child = (void *)spec->u.declspec.next;
219 spec->u.declarator.u.ident = spec->u.declspec.ident;
220 spec->u.declarator.type = CDECL_DECL_IDENT;
221 *p = &spec->u.declarator;
223 d = param->declarators;
228 static bool function_is_reducible(struct cdecl_declarator *d)
230 if (d->type != CDECL_DECL_FUNCTION)
232 if (d->child->type != CDECL_DECL_NULL)
233 return false; /* e.g., int (*)(x) */
235 if (!d->u.function.parameters)
236 return false; /* e.g., int f() */
237 if (d->u.function.parameters->next)
238 return false; /* e.g., int (x, y) */
239 if (d->u.function.variadic)
240 return false; /* e.g., int (x, ...) */
242 if (d->u.function.parameters->specifiers->type != CDECL_TYPE_IDENT)
243 return false; /* e.g. int (int) */
244 if (d->u.function.parameters->specifiers->next)
245 return false; /* e.g. int (size_t const) */
246 if (d->u.function.parameters->declarators->type == CDECL_DECL_POINTER)
247 return false; /* e.g. int (x *) */
253 simplify_functions(struct cdecl_declarator **p, struct cdecl_declarator *d)
255 struct cdecl_declarator *new;
257 if (!function_is_reducible(d))
260 new = reduce_function(d->u.function.parameters);
262 return 0; /* e.g. int (foo bar) */
270 * The main parser's bias towards considering things as functions whenever
271 * possible makes nested parentheses tricky. "(x)" is considered to be part
272 * of a function declarator until simplify_functions converts it. The problem
273 * is that "(((x)))" is not valid as part of a function declarator, but it _is_
274 * valid as either an identifier enclosed thrice in parentheses, or an abstract
275 * function declarator enclosed twice in parentheses.
277 * To avoid ambiguities, the main parser actually returns a function declarator
278 * for every pair of parentheses. The ones we need to look at consist of a
279 * single parameter with an empty specifier list (noting that every real
280 * function parameter will have at least one type specifier).
282 * There are two cases:
284 * - For (), the parser emits a parameter with a lone null declarator.
285 * This fake parameter simply gets deleted, leaving us with a normal
286 * function declarator with an empty identifier list.
288 * - Otherwise, the parameter's outermost declarator is not null. The
289 * function itself is deleted, replaced in the parse tree with the
290 * fake parameter's declarator.
292 * Repeating until there no fake parameters, this reduction transforms, for
293 * example, "(((x)))" into "(x)", an abstract function declarator. The result
294 * is then subject to the function simplification step, which will turn "(x)"
295 * into x (declaring an identifier).
297 * The whole process is repeated until no more changes are made to the parse
298 * tree, or a syntax error is detected.
300 static struct cdecl *fake_function_param(struct cdecl_declarator *d)
304 if (d->type != CDECL_DECL_FUNCTION)
307 param = d->u.function.parameters;
308 if (!param || param->specifiers)
311 assert(!param->next);
316 reduce_parentheses(struct cdecl_declarator **p, struct cdecl_declarator *d)
322 while ((param = fake_function_param(d))) {
323 struct cdecl_declarator *decl = param->declarators;
324 d->u.function.parameters = NULL;
326 if (decl->type != CDECL_DECL_NULL) {
327 if (d->child->type != CDECL_DECL_NULL) {
328 /* Fake parameter on real function. */
329 d->u.function.parameters = param;
330 cdecl__errmsg(CDECL__EBADPARAM);
334 param->declarators = d;
340 } while (simplify_functions(p, d));
346 * Returns nonzero iff the given specifier list contains a specifier
347 * of the indicated type.
349 static int have_specifier(struct cdecl_declspec *s, unsigned type)
351 for (; s; s = s->next)
358 * Check syntax restrictions on a function declarator's child declarator.
359 * That is, "pointer to function", "array of function" and "function
360 * returning function".
362 * Returns -1 if the declaration is invalid, or 0 otherwise.
364 static int check_function_child(struct cdecl_declarator *d)
366 struct cdecl_pointer *ptr;
369 case CDECL_DECL_POINTER:
371 if (have_specifier(ptr->qualifiers, CDECL_QUAL_RESTRICT)) {
372 /* pointer to function cannot be restrict qualified. */
373 cdecl__errmsg(CDECL__ERESTRICTFUNC);
377 case CDECL_DECL_FUNCTION:
378 /* function returning function is never allowed. */
379 cdecl__errmsg(CDECL__ERETFUNC);
381 case CDECL_DECL_ARRAY:
382 /* array of function is never allowed. */
383 cdecl__errmsg(CDECL__EFUNCARRAY);
391 * Check a function parameter declaration for validity, which means it has a
392 * valid combination of declaration specifiers and, if it is a void parameter,
393 * that it is the one special case where this is allowed.
395 * Returns -1 if the declaration is invalid, or 0 otherwise.
397 static int check_function_param(struct cdecl_function *f, struct cdecl *param)
399 if (!valid_declspecs(param, false))
402 /* Check for "void" function parameters as a special case. */
403 if (param->declarators->type == CDECL_DECL_NULL
404 && have_specifier(param->specifiers, CDECL_TYPE_VOID))
406 struct cdecl *fp = f->parameters;
408 if (f->variadic || fp->next || fp->specifiers->next) {
409 cdecl__errmsg(CDECL__EVOIDPARAM);
418 * Normalize the specifier lists for function parameters, and then check the
419 * function declarator for validity.
421 * Returns -1 if the declaration is invalid, or 0 otherwise.
423 static int postproc_function(struct cdecl_declarator *d)
425 struct cdecl_function *func = &d->u.function;
429 for (param = func->parameters; param; param = param->next) {
430 param->specifiers = cdecl__normalize_specs(param->specifiers);
432 if ((rc = check_function_param(func, param)) < 0)
436 return check_function_child(d->child);
440 postproc_common(struct cdecl_declarator **p, struct cdecl_declarator *d)
442 struct cdecl_pointer *ptr;
445 case CDECL_DECL_POINTER:
447 ptr->qualifiers = cdecl__normalize_specs(ptr->qualifiers);
449 case CDECL_DECL_FUNCTION:
450 return postproc_function(d);
451 case CDECL_DECL_ARRAY:
452 if (d->child && d->child->type == CDECL_DECL_FUNCTION) {
453 /* function returning array is never allowed. */
454 cdecl__errmsg(CDECL__ERETARRAY);
464 * Traverse the parse tree, calling a function on every declarator in a
465 * depth-first preorder traversal. The function is given a pointer to the
466 * declarator as well as to the pointer which was used to reach that
467 * declarator: this can be used to rewrite entire subtrees.
469 * The called function may return a negative value to indicate an error
470 * which terminates traversal.
472 * Returns 0 on success, or a negative value on failure.
474 static int forall_declarators(struct cdecl *decl,
475 int f(struct cdecl_declarator **, struct cdecl_declarator *))
477 struct cdecl_declarator *d, **p;
479 for (p = &decl->declarators; *p; p = &d->child) {
487 if (d->type == CDECL_DECL_FUNCTION) {
490 for (i = d->u.function.parameters; i; i = i->next) {
491 rc = forall_declarators(i, f);
501 static struct cdecl *do_parse(const char *str, int english_mode)
503 struct cdecl *decl = NULL;
504 YY_BUFFER_STATE state;
508 extern int cdecl__yydebug;
513 if (cdecl__yylex_init_extra(english_mode, &scanner) != 0)
516 state = cdecl__yy_scan_string(str, scanner);
517 if (cdecl__yyparse(scanner, &decl) != 0) {
519 * If the input consists of a complete, valid declaration
520 * followed by some garbage, that parsed declaration will
521 * be output by the parser and we need to free it here.
526 cdecl__yy_delete_buffer(state, scanner);
527 cdecl__yylex_destroy(scanner);
532 static int do_postprocess(struct cdecl *decl, int english_mode)
534 struct cdecl_declspec *norm_specs;
538 * For a C declaration with more than one full declarator, the
539 * specifier list is common to all of them. Normalize it once,
540 * then propagate that to all the linked cdecl structures.
542 * In english mode, the cdecl structure list always has exactly
543 * one entry so we don't need to do anything differently.
545 norm_specs = cdecl__normalize_specs(decl->specifiers);
546 for (i = decl; i; i = i->next)
547 i->specifiers = norm_specs;
549 for (i = decl; i; i = i->next) {
551 if (forall_declarators(i, reduce_parentheses) < 0)
555 if (forall_declarators(i, postproc_common) < 0)
558 if (!valid_declspecs(i, true))
561 if (decl->next && cdecl_is_abstract(i->declarators)) {
562 /* Abstract full declarators: there can only be one. */
563 cdecl__errmsg(CDECL__EDECLTYPE);
571 static struct cdecl *parse_common(const char *str, int english_mode)
575 if (!(decl = do_parse(str, english_mode)))
578 if (!do_postprocess(decl, english_mode)) {
586 struct cdecl *cdecl_parse_decl(const char *declstr)
588 return parse_common(declstr, false);
591 struct cdecl *cdecl_parse_english(const char *english)
593 return parse_common(english, true);
596 void cdecl_free(struct cdecl *decl)