2 * Render C declarations.
3 * Copyright © 2011, 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 <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 cdecl__emit_specs(dst, decl->specifiers, -1);
34 if (decl->declarators->type != CDECL_DECL_NULL)
35 cdecl__emit(dst, " ");
37 declare_declarator(dst, decl->declarators);
41 declare_postfix_child(struct output_state *dst, struct cdecl_declarator *d)
43 if (d->type == CDECL_DECL_POINTER)
44 cdecl__emit(dst, "(");
46 declare_declarator(dst, d);
48 if (d->type == CDECL_DECL_POINTER)
49 cdecl__emit(dst, ")");
52 static void declare_pointer(struct output_state *dst, struct cdecl_pointer *p)
54 struct cdecl_declspec *q = p->qualifiers;
57 cdecl__emit(dst, "* ");
58 cdecl__emit_specs(dst, q, -1);
59 cdecl__emit(dst, " ");
61 cdecl__emit(dst, "*");
65 static void declare_array(struct output_state *dst, struct cdecl_array *a)
67 cdecl__emit(dst, "[");
70 const char *s = a->vla[0] ? a->vla : "*";
73 size_t rc = snprintf(dst->dst, dst->dstlen, "%.0" PRIuMAX, a->length);
74 cdecl__advance(dst, rc);
77 cdecl__emit(dst, "]");
81 declare_function(struct output_state *dst, struct cdecl_function *f)
85 cdecl__emit(dst, "(");
87 for (p = f->parameters; p; p = p->next) {
91 cdecl__emit(dst, ", ");
93 cdecl__emit(dst, ", ...");
96 cdecl__emit(dst, ")");
100 declare_declarator(struct output_state *dst, struct cdecl_declarator *d)
102 for (; d; d = d->child) {
104 case CDECL_DECL_NULL:
106 case CDECL_DECL_IDENT:
107 cdecl__emit(dst, d->u.ident);
109 case CDECL_DECL_POINTER:
110 declare_pointer(dst, &d->u.pointer);
113 * Arrays and functions are special: since they are postfix,
114 * we need to render the children before rendering their
117 case CDECL_DECL_ARRAY:
118 declare_postfix_child(dst, d->child);
119 declare_array(dst, &d->u.array);
121 case CDECL_DECL_FUNCTION:
122 declare_postfix_child(dst, d->child);
123 declare_function(dst, &d->u.function);
131 size_t cdecl_declare(char *buf, size_t n, struct cdecl *decl)
133 struct output_state dst = { buf, n };
135 declare_decl(&dst, decl);