]> git.draconx.ca Git - cdecl99.git/blob - src/cdecl99.c
Use the newly-minted option generator script from dxcommon.
[cdecl99.git] / src / cdecl99.c
1 /*
2  * Command line utility for making sense of C declarations.
3  * Copyright © 2011-2012, 2020-2021 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 <https://www.gnu.org/licenses/>.
17  */
18
19 #include <config.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stdbool.h>
23 #include <string.h>
24 #include <ctype.h>
25 #include <errno.h>
26 #include <locale.h>
27 #include <assert.h>
28 #include "history.h"
29 #include "cdecl.h"
30
31 #include <getopt.h>
32 #include <gettext.h>
33 #include <readline.h>
34 #include <striconv.h>
35 #include <localcharset.h>
36 #include <mbswidth.h>
37
38 #define _(x) gettext(x)
39
40 static const char *progname = "cdecl99";
41
42 #include "options.h"
43 static const char sopts[] = SOPT_STRING;
44 static const struct option lopts[] = {
45         LOPTS_INITIALIZER,
46         {0}
47 };
48
49 static void print_version(void)
50 {
51         const char *copysign = "(C)";
52         void *convsign = NULL;
53
54         if (ENABLE_NLS) {
55                 convsign = str_iconv("\xc2\xa9", "UTF-8", locale_charset());
56                 if (convsign)
57                         copysign = convsign;
58         }
59
60         puts(PACKAGE_STRING);
61         printf("Copyright %s 2021 Nick Bowler.\n", copysign);
62         puts("License GPLv3+: GNU GPL version 3 or any later version.");
63         puts("This is free software: you are free to change and redistribute it.");
64         puts("There is NO WARRANTY, to the extent permitted by law.");
65
66         free(convsign);
67 }
68
69 static void print_usage(FILE *f)
70 {
71         fprintf(f, _("Usage: %s [options]\n"), progname);
72         if (f != stdout)
73                 fprintf(f, _("Try %s --help for more information.\n"),
74                            progname);
75 }
76
77 static int
78 print_optstring(const struct option *opt, const struct lopt_help *help)
79 {
80         char optstring[100];
81         int w;
82
83         if (!ENABLE_NLS)
84                 goto no_translate;
85
86         if (opt->has_arg) {
87                 w = snprintf(optstring, sizeof optstring,
88                              _("  -%c, --%s=%s"), opt->val, opt->name,
89                              pgettext_expr(opt->name, help->arg));
90         } else {
91                 w = snprintf(optstring, sizeof optstring,
92                              _("  -%c, --%s"), opt->val, opt->name);
93         }
94
95         if (w < 0)
96                 goto no_translate;
97
98         w = mbsnwidth(optstring, w, 0);
99         printf("%s", optstring);
100         goto out;
101
102 no_translate:
103         if (opt->has_arg) {
104                 w = printf("  -%c, --%s=%s", opt->val, opt->name, help->arg);
105         } else {
106                 w = printf("  -%c, --%s", opt->val, opt->name);
107         }
108 out:
109         if (w < 0 || w > 18) {
110                 putchar('\n');
111                 return 0;
112         }
113
114         return w;
115 }
116
117 static void print_help(void)
118 {
119         const struct option *opt;
120
121         print_usage(stdout);
122
123         puts(_("This is \"cdecl99\": a command-line tool for parsing and constructing\n"
124                "complicated C declarations."));
125         putchar('\n');
126
127         puts(_("Options:"));
128         for (opt = lopts; opt->name; opt++) {
129                 struct lopt_help help;
130                 const char *line;
131                 int w;
132
133                 if (!lopt_get_help(opt, &help))
134                         continue;
135
136                 w = print_optstring(opt, &help);
137
138                 if (ENABLE_NLS)
139                         help.desc = pgettext_expr(opt->name, help.desc);
140
141                 for (line = help.desc; *line; w = 0) {
142                         const char *nl = strchr(line, '\n');
143                         int n = (nl ? nl-line : -1);
144
145                         printf("%*s%.*s\n", 20-w, "", n, line);
146                         if (!nl)
147                                 break;
148
149                         line = nl+1;
150                 }
151         }
152         putchar('\n');
153
154         puts(_("For more information, see the cdecl99(1) man page."));
155         putchar('\n');
156
157         /*
158          * TRANSLATORS: Please add *another line* indicating where users should
159          * report translation bugs.
160          */
161         printf(_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
162 }
163
164 /*
165  * Format a declaration according to the given function and return a pointer
166  * to the formatted string.  The returned pointer remains valid until the
167  * next call, after which it must not be re-used.
168  *
169  * Returns NULL on failure.
170  */
171 static const char *
172 do_format(size_t func(char *, size_t, struct cdecl *), struct cdecl *decl)
173 {
174         static size_t bufsz;
175         static char *buf;
176
177         size_t rc;
178
179 retry:
180         rc = func(buf, bufsz, decl);
181         if (rc >= bufsz) {
182                 char *tmp;
183
184                 tmp = realloc(buf, rc + 1);
185                 if (!tmp) {
186                         fprintf(stderr, "%s\n", _("failed to allocate memory"));
187                         return NULL;
188                 }
189
190                 buf = tmp;
191                 bufsz = rc + 1;
192                 goto retry;
193         }
194
195         return buf;
196 }
197
198 static int cmd_explain(const char *cmd, const char *arg)
199 {
200         const struct cdecl_error *err;
201         struct cdecl *decl;
202         const char *str;
203         int ret = -1;
204
205         decl = cdecl_parse_decl(arg);
206         if (!decl) {
207                 err = cdecl_get_error();
208                 fprintf(stderr, "%s\n", err->str);
209                 goto out;
210         }
211
212         for (struct cdecl *i = decl; i; i = i->next) {
213                 str = do_format(cdecl_explain, i);
214                 if (!str)
215                         goto out;
216
217                 printf("%s\n", str);
218         }
219
220         ret = 1;
221 out:
222         cdecl_free(decl);
223         return ret;
224 }
225
226 static int cmd_simplify(const char *cmd, const char *arg)
227 {
228         const struct cdecl_error *err;
229         struct cdecl *decl;
230         const char *str;
231         int ret = -1;
232
233         decl = cdecl_parse_decl(arg);
234         if (!decl) {
235                 err = cdecl_get_error();
236                 fprintf(stderr, "%s\n", err->str);
237                 goto out;
238         }
239
240         for (struct cdecl *i = decl; i; i = i->next) {
241                 struct cdecl_declspec *s = i->specifiers;
242
243                 if (i != decl) {
244                         i->specifiers = NULL;
245                         printf(", ");
246                 }
247
248                 str = do_format(cdecl_declare, i);
249                 i->specifiers = s;
250
251                 if (!str)
252                         goto out;
253
254                 printf("%s", str);
255         }
256
257         putchar('\n');
258
259         ret = 1;
260 out:
261         cdecl_free(decl);
262         return ret;
263 }
264
265 static int cmd_declare(const char *cmd, const char *arg)
266 {
267         const struct cdecl_error *err;
268         struct cdecl *decl;
269         const char *str;
270         int ret = -1;
271
272         /* The name of the command is significant here. */
273         decl = cdecl_parse_english(cmd);
274         if (!decl) {
275                 err = cdecl_get_error();
276                 fprintf(stderr, "%s\n", err->str);
277                 goto out;
278         }
279
280         /*
281          * English parses have at most one full declarator, so no loop is
282          * needed here.
283          */
284         str = do_format(cdecl_declare, decl);
285         if (!str)
286                 goto out;
287
288         printf("%s\n", str);
289         ret = 1;
290 out:
291         cdecl_free(decl);
292         return ret;
293 }
294
295 static int cmd_quit(const char *cmd, const char *arg)
296 {
297         return 0;
298 }
299
300 static int cmd_help(const char *cmd, const char *arg);
301
302 static const struct command {
303         char name[16];
304         int (*func)(const char *cmd, const char *arg);
305         const char *blurb;
306 } commands[] = {
307         { "explain",  cmd_explain,  "Explain a C declaration." },
308         { "simplify", cmd_simplify, "Simplify a C declaration." },
309         { "declare",  cmd_declare,  "Construct a C declaration." },
310         { "type",     cmd_declare,  "Construct a C type name." },
311         { "help",     cmd_help,     "Print this list of commands." },
312         { "quit",     cmd_quit,     "Quit the program." },
313         { "exit",     cmd_quit,     NULL }
314 };
315 static const size_t ncommands = sizeof commands / sizeof commands[0];
316
317 static int cmd_help(const char *cmd, const char *arg)
318 {
319         for (size_t i = 0; i < ncommands; i++) {
320                 if (!commands[i].blurb)
321                         continue;
322
323                 printf("%s -- %s\n", commands[i].name, commands[i].blurb);
324         }
325
326         return 1;
327 }
328
329 /*
330  * Ensure that the first n characters of str equal the entire (null-terminated)
331  * string cmd.
332  */
333 static int cmd_cmp(const char *str, const char *cmd, size_t n)
334 {
335         size_t cmdlen = strlen(cmd);
336
337         if (n < cmdlen)
338                 return -1;
339         if (n > cmdlen)
340                 return 1;
341         return memcmp(str, cmd, n);
342 }
343
344 static int run_command(const char *line)
345 {
346         const char *cmd = line + strspn(line, " \t");
347         const char *arg = cmd  + strcspn(cmd, " \t");
348
349         if (cmd[0] == '\0')
350                 return 1;
351
352         for (size_t i = 0; i < ncommands; i++) {
353                 if (cmd_cmp(cmd, commands[i].name, arg-cmd) != 0)
354                         continue;
355
356                 return commands[i].func(cmd, arg);
357         }
358
359         fprintf(stderr, "Undefined command: %.*s\n", (int)(arg-cmd), cmd);
360         return -1;
361 }
362
363 static bool is_blank_line(const char *line)
364 {
365         for (size_t i = 0; line[i]; i++) {
366                 if (!isblank((unsigned char)line[i]))
367                         return false;
368         }
369
370         return true;
371 }
372
373 static int repl(void)
374 {
375         char *line;
376
377         for (; (line = readline("> ")); free(line)) {
378                 if (!is_blank_line(line))
379                         cdecl_add_history(line);
380
381                 if (!run_command(line))
382                         break;
383         }
384
385         free(line);
386         return 0;
387 }
388
389 static int repl_cmdline(int argc, char **argv)
390 {
391         int opt, rc, ret = 0;
392
393         optind = 1;
394         while ((opt = getopt_long(argc, argv, sopts, lopts, NULL)) != -1) {
395                 if (opt != 'e')
396                         continue;
397
398                 rc = run_command(optarg);
399                 if (rc < 0)
400                         ret = -1;
401                 else if (rc == 0)
402                         break;
403         }
404
405         return ret;
406 }
407
408 static int repl_noninteractive(void)
409 {
410         int rc, ret = 0, saved_errno;
411         char *line = NULL;
412         size_t n;
413
414         while (getline(&line, &n, stdin) >= 0) {
415                 char *c = strchr(line, '\n');
416                 if (c)
417                         *c = '\0';
418
419                 rc = run_command(line);
420                 if (rc < 0)
421                         ret = -1;
422                 else if (rc == 0)
423                         break;
424         }
425
426         saved_errno = errno;
427         free(line);
428
429         if (ferror(stdin)) {
430                 errno = saved_errno;
431                 perror("read error");
432                 return -1;
433         }
434
435         return ret;
436 }
437
438 /* Initialize gettext */
439 static void init_i18n(void)
440 {
441         if (!ENABLE_NLS)
442                 return;
443
444         setlocale(LC_ALL, "");
445         bindtextdomain(PACKAGE, LOCALEDIR);
446         textdomain(PACKAGE);
447 }
448
449 int main(int argc, char **argv)
450 {
451         bool show_intro = true, interactive = true, execute = false;
452         const char *filename = NULL;
453         int i, opt, rc;
454
455         if (argc > 0)
456                 progname = argv[0];
457
458         init_i18n();
459
460         while ((opt = getopt_long(argc, argv, sopts, lopts, NULL)) != -1) {
461                 switch (opt) {
462                 case 'q':
463                         show_intro = false;
464                         break;
465                 case 'b':
466                         interactive = false;
467                         break;
468                 case 'i':
469                         interactive = true;
470                         break;
471                 case 'f':
472                         filename = optarg;
473                         break;
474                 case 'e':
475                         execute = true;
476                         break;
477                 case 'V':
478                         print_version();
479                         return EXIT_SUCCESS;
480                 case 'H':
481                         print_help();
482                         return EXIT_SUCCESS;
483                 default:
484                         print_usage(stderr);
485                         return EXIT_FAILURE;
486                 }
487         }
488
489         if (optind < argc) {
490                 fprintf(stderr, _("%s: excess command-line arguments:"),
491                                 progname);
492                 for (i = optind; i < argc; i++) {
493                         fprintf(stderr, " %s", argv[i]);
494                 }
495                 fprintf(stderr, "\n");
496                 print_usage(stderr);
497                 return EXIT_FAILURE;
498         }
499
500         /* --filename and --execute imply --batch. */
501         if (filename || execute)
502                 interactive = false;
503
504         /* --batch implies --quiet */
505         if (interactive && show_intro)
506                 print_version();
507
508         /* --execute supersedes --filename */
509         if (filename && !execute) {
510                 if (!freopen(filename, "r", stdin)) {
511                         perror(filename);
512                         return EXIT_FAILURE;
513                 }
514         }
515
516         if (interactive)
517                 rc = repl();
518         else if (execute)
519                 rc = repl_cmdline(argc, argv);
520         else
521                 rc = repl_noninteractive();
522
523         if (rc != 0)
524                 return EXIT_FAILURE;
525         return EXIT_SUCCESS;
526 }