]> git.draconx.ca Git - cdecl99.git/blob - src/output.c
4590a5cfc60b2fb9c3d1bdead751da7d37b25d9b
[cdecl99.git] / src / output.c
1 /*
2  *  Helper functions for outputting text.
3  *  Copyright © 2011, 2021, 2023 Nick Bowler
4  *
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.
9  *
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.
14  *
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/>.
17  */
18 #include <config.h>
19 #include <stdio.h>
20 #include <assert.h>
21
22 #include "cdecl.h"
23 #include "cdecl-internal.h"
24
25 #include "specstr.h"
26
27 #define MIN(a, b) ((a) < (b) ? (a) : (b))
28
29 size_t cdecl__advance(struct output_state *dst, size_t amount)
30 {
31         size_t x = MIN(amount, dst->dstlen);
32
33         dst->dst    += x;
34         dst->dstlen -= x;
35         dst->accum  += amount;
36
37         return amount;
38 }
39
40 size_t cdecl__emit(struct output_state *dst, const char *src)
41 {
42         size_t rc = snprintf(dst->dst, dst->dstlen, "%s", src);
43         return cdecl__advance(dst, rc);
44 }
45
46 static void explain_spec(struct output_state *dst, struct cdecl_declspec *s)
47 {
48         size_t rc;
49
50         rc = cdecl__emit(dst, spec_string(s->type));
51         if (s->ident) {
52                 cdecl__emit(dst, " " + !rc);
53                 cdecl__emit(dst, s->ident);
54         }
55 }
56
57 /*
58  * Render a list of declaration specifiers.  Only the declaration specifiers
59  * listed in mask, which is the bitwise OR of the desired specifier kinds, are
60  * printed.
61  */
62 const char *cdecl__emit_specs(struct output_state *dst,
63                               struct cdecl_declspec *s,
64                               unsigned mask)
65 {
66         const char *sep = " ";
67         int empty = 1;
68
69         for (; s; s = s->next) {
70                 if (!(s->type & mask))
71                         continue;
72
73                 cdecl__emit(dst, sep + empty);
74                 explain_spec(dst, s);
75                 empty = 0;
76         }
77
78         return sep + empty;
79 }