2 * Render C declarations.
3 * Copyright © 2011, 2021, 2023-2024 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 <http://www.gnu.org/licenses/>.
26 #include "cdecl-internal.h"
29 declare_declarator(struct output_state *dst, struct cdecl_declarator *d);
31 static void declare_decl(struct output_state *dst, struct cdecl *decl)
33 struct cdecl_declarator *d = decl->declarators;
36 sep = cdecl__emit_specs(dst, decl->specifiers, -1);
37 if (d->type != CDECL_DECL_NULL)
38 cdecl__emit(dst, sep);
40 declare_declarator(dst, d);
44 declare_postfix_child(struct output_state *dst, struct cdecl_declarator *d)
46 bool need_parens = (d->type == CDECL_DECL_POINTER);
48 if (need_parens) cdecl__emit(dst, "(");
49 declare_declarator(dst, d);
50 if (need_parens) cdecl__emit(dst, ")");
53 static void declare_pointer(struct output_state *dst, struct cdecl_declarator *d)
55 struct cdecl_declspec *q = d->u.pointer.qualifiers;
60 cdecl__emit(dst, "* ");
61 sep = cdecl__emit_specs(dst, q, -1);
62 if (d->child->type != CDECL_DECL_NULL)
63 cdecl__emit(dst, sep);
65 cdecl__emit(dst, "*");
69 static void declare_array(struct output_state *dst, struct cdecl_array *a)
71 cdecl__emit(dst, "[");
74 const char *s = a->vla[0] ? a->vla : "*";
77 cdecl__emit_uint(dst, a->length);
80 cdecl__emit(dst, "]");
84 declare_function(struct output_state *dst, struct cdecl_function *f)
88 cdecl__emit(dst, "(");
90 for (p = f->parameters; p; p = p->next) {
94 cdecl__emit(dst, ", ");
96 cdecl__emit(dst, ", ...");
99 cdecl__emit(dst, ")");
103 declare_declarator(struct output_state *dst, struct cdecl_declarator *d)
105 for (; d; d = d->child) {
107 case CDECL_DECL_NULL:
109 case CDECL_DECL_IDENT:
110 cdecl__emit(dst, d->u.ident);
112 case CDECL_DECL_POINTER:
113 declare_pointer(dst, d);
116 * Arrays and functions are special: since they are postfix,
117 * we need to render the children before rendering their
120 case CDECL_DECL_ARRAY:
121 declare_postfix_child(dst, d->child);
122 declare_array(dst, &d->u.array);
124 case CDECL_DECL_FUNCTION:
125 declare_postfix_child(dst, d->child);
126 declare_function(dst, &d->u.function);
134 size_t cdecl_declare(char *buf, size_t n, struct cdecl *decl)
136 struct output_state dst = { buf, n };
138 declare_decl(&dst, decl);