]> git.draconx.ca Git - cdecl99.git/blob - src/cdecl99.c
Improve usage messages a bit.
[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
37 #define _(x) gettext(x)
38 #define N_(x) x
39 #define PN_(c, x) x
40
41 static const char *progname = "cdecl99";
42 static const char sopts[] = "qbif:e:VH";
43 #define RAW_LOPTS \
44         { PN_("longopt", "quiet"),       0, NULL, 'q' }, \
45         { PN_("longopt", "batch"),       0, NULL, 'b' }, \
46         { PN_("longopt", "interactive"), 0, NULL, 'i' }, \
47         { PN_("longopt", "file"),        1, NULL, 'f' }, \
48         { PN_("longopt", "execute"),     1, NULL, 'e' }, \
49         { PN_("longopt", "version"),     0, NULL, 'V' }, \
50         { PN_("longopt", "help"),        0, NULL, 'H' }
51
52 /*
53  * With NLS, we need a buffer big enough to store the translated options.
54  * The translations will be filled in at program startup.
55  */
56 enum { NOPTS = sizeof (struct option[]){RAW_LOPTS} / sizeof (struct option) };
57 static struct option lopts[NOPTS + !!ENABLE_NLS * NOPTS + 1] = { RAW_LOPTS };
58
59 static struct helptext {
60         int val;
61         const char *text;
62         const char *argname;
63 } helptext[] = {
64         /*
65          * TRANSLATORS: Help messages are indented 20 spaces and thus should
66          * not have lines longer than 60 columns.
67          */
68         { 'q', N_("Suppress the welcome message.\n") },
69         { 'b', N_("Execute commands as normal, but do not print any prompts.\n") },
70         { 'i', N_("Run in interactive mode.  This is the default.\n") },
71         { 'f', N_("Read commands from FILE instead of standard input.\n"),
72                PN_("longopt|file", "FILE") },
73         { 'e', N_("Execute COMMAND as if it were entered at the prompt.\n"
74                   "This can be specified multiple times.\n"),
75                PN_("longopt|execute", "COMMAND") },
76         { 'V', N_("Print a version message and then exit.\n") },
77         { 'H', N_("Print this message.\n") },
78
79         /* TRANSLATORS: ARG is only used for options without help text. */
80         { 0, NULL, PN_("longopt", "ARG") }
81 };
82
83 static void print_version(void)
84 {
85         const char *copysign = "(C)";
86         void *convsign = NULL;
87
88         if (ENABLE_NLS) {
89                 convsign = str_iconv("\xc2\xa9", "UTF-8", locale_charset());
90                 if (convsign)
91                         copysign = convsign;
92         }
93
94         puts(PACKAGE_STRING);
95         printf("Copyright %s 2021 Nick Bowler.\n", copysign);
96         puts("License GPLv3+: GNU GPL version 3 or any later version.");
97         puts("This is free software: you are free to change and redistribute it.");
98         puts("There is NO WARRANTY, to the extent permitted by law.");
99
100         free(convsign);
101 }
102
103 static void print_usage(FILE *f)
104 {
105         fprintf(f, "Usage: %s [options]\n", progname);
106         if (f != stdout)
107                 fprintf(f, _("Try %s --help for more information.\n"),
108                            progname);
109 }
110
111 /*
112  * Print the help description of a particular command-line option, identified
113  * by its short option name.
114  */
115 static void print_option(int val)
116 {
117         const struct option *tmp[2];
118         const struct helptext *help;
119         const char *argname;
120         char context[32];
121         size_t rc, n = 0;
122         int w;
123
124         /* Find the options and help text corresponding to val. */
125         for (const struct option *o = lopts; o->val; o++) {
126                 if (o->val == val) {
127                         assert(n < sizeof tmp / sizeof tmp[0]);
128                         tmp[n++] = o;
129                 }
130         }
131
132         for (help = helptext; help->val; help++) {
133                 if (help->val == val)
134                         break;
135         }
136
137         /* Prepare translations. */
138         if (!ENABLE_NLS) {
139                 argname = help->argname;
140         } else if (n > 0) {
141                 rc = snprintf(context, sizeof context, "longopt%c%s",
142                               help->text ? '|' : '\0', tmp[0]->name);
143                 assert(rc < sizeof context);
144
145                 if (help->argname)
146                         argname = pgettext_expr(context, help->argname);
147         }
148
149         switch (n) {
150         case 0:
151                 w = printf(_("  -%c"), val);
152                 break;
153         case 1:
154                 w = printf(tmp[0]->has_arg ? _("  -%c, --%s=%s")
155                                            : _("  -%c, --%s"),
156                            val, tmp[0]->name, argname);
157                 break;
158         case 2:
159                 if (tmp[0]->has_arg) {
160                         w = printf(_("  -%c, --%s=%s, --%s=%s"), val,
161                                    tmp[0]->name, argname,
162                                    tmp[1]->name, argname);
163                 } else {
164                         w = printf(_("  -%c, --%s, --%s"), val,
165                                    tmp[0]->name, tmp[1]->name);
166                 }
167                 break;
168         default:
169                 assert(0);
170         }
171
172         if (!help->text) {
173                 putchar('\n');
174                 return;
175         }
176
177         if (w > 18) {
178                 putchar('\n');
179                 w = 0;
180         }
181
182         for (const char *line = gettext(help->text); *line;) {
183                 const char *nl = strchr(line, '\n');
184
185                 if (!nl) {
186                         printf("%*s%s\n", 20-w, "", line);
187                         break;
188                 }
189
190                 printf("%*s%.*s\n", 20-w, "", (int)(nl-line), line);
191                 line = nl+1;
192         }
193 }
194
195 static void print_help(void)
196 {
197         print_usage(stdout);
198
199         puts(_(
200 "This is \"cdecl99\": a command-line tool for parsing and constructing\n"
201 "complicated C declarations.\n"));
202
203         puts(_("Options:"));
204         for (const char *c = sopts; *c; c++) {
205                 if (*c == ':' || *c == '+' || *c == '-')
206                         continue;
207
208                 print_option(*c);
209         }
210         putchar('\n');
211
212         puts(_("For more information, see the cdecl99(1) man page.\n"));
213
214         /*
215          * TRANSLATORS: Please add *another line* indicating where users should
216          * report translation bugs.
217          */
218         printf(_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);
219 }
220
221 /*
222  * Format a declaration according to the given function and return a pointer
223  * to the formatted string.  The returned pointer remains valid until the
224  * next call, after which it must not be re-used.
225  *
226  * Returns NULL on failure.
227  */
228 static const char *
229 do_format(size_t func(char *, size_t, struct cdecl *), struct cdecl *decl)
230 {
231         static size_t bufsz;
232         static char *buf;
233
234         size_t rc;
235
236 retry:
237         rc = func(buf, bufsz, decl);
238         if (rc >= bufsz) {
239                 char *tmp;
240
241                 tmp = realloc(buf, rc + 1);
242                 if (!tmp) {
243                         fprintf(stderr, "%s\n", _("failed to allocate memory"));
244                         return NULL;
245                 }
246
247                 buf = tmp;
248                 bufsz = rc + 1;
249                 goto retry;
250         }
251
252         return buf;
253 }
254
255 static int cmd_explain(const char *cmd, const char *arg)
256 {
257         const struct cdecl_error *err;
258         struct cdecl *decl;
259         const char *str;
260         int ret = -1;
261
262         decl = cdecl_parse_decl(arg);
263         if (!decl) {
264                 err = cdecl_get_error();
265                 fprintf(stderr, "%s\n", err->str);
266                 goto out;
267         }
268
269         for (struct cdecl *i = decl; i; i = i->next) {
270                 str = do_format(cdecl_explain, i);
271                 if (!str)
272                         goto out;
273
274                 printf("%s\n", str);
275         }
276
277         ret = 1;
278 out:
279         cdecl_free(decl);
280         return ret;
281 }
282
283 static int cmd_simplify(const char *cmd, const char *arg)
284 {
285         const struct cdecl_error *err;
286         struct cdecl *decl;
287         const char *str;
288         int ret = -1;
289
290         decl = cdecl_parse_decl(arg);
291         if (!decl) {
292                 err = cdecl_get_error();
293                 fprintf(stderr, "%s\n", err->str);
294                 goto out;
295         }
296
297         for (struct cdecl *i = decl; i; i = i->next) {
298                 struct cdecl_declspec *s = i->specifiers;
299
300                 if (i != decl) {
301                         i->specifiers = NULL;
302                         printf(", ");
303                 }
304
305                 str = do_format(cdecl_declare, i);
306                 i->specifiers = s;
307
308                 if (!str)
309                         goto out;
310
311                 printf("%s", str);
312         }
313
314         putchar('\n');
315
316         ret = 1;
317 out:
318         cdecl_free(decl);
319         return ret;
320 }
321
322 static int cmd_declare(const char *cmd, const char *arg)
323 {
324         const struct cdecl_error *err;
325         struct cdecl *decl;
326         const char *str;
327         int ret = -1;
328
329         /* The name of the command is significant here. */
330         decl = cdecl_parse_english(cmd);
331         if (!decl) {
332                 err = cdecl_get_error();
333                 fprintf(stderr, "%s\n", err->str);
334                 goto out;
335         }
336
337         /*
338          * English parses have at most one full declarator, so no loop is
339          * needed here.
340          */
341         str = do_format(cdecl_declare, decl);
342         if (!str)
343                 goto out;
344
345         printf("%s\n", str);
346         ret = 1;
347 out:
348         cdecl_free(decl);
349         return ret;
350 }
351
352 static int cmd_quit(const char *cmd, const char *arg)
353 {
354         return 0;
355 }
356
357 static int cmd_help(const char *cmd, const char *arg);
358
359 static const struct command {
360         char name[16];
361         int (*func)(const char *cmd, const char *arg);
362         const char *blurb;
363 } commands[] = {
364         { "explain",  cmd_explain,  "Explain a C declaration." },
365         { "simplify", cmd_simplify, "Simplify a C declaration." },
366         { "declare",  cmd_declare,  "Construct a C declaration." },
367         { "type",     cmd_declare,  "Construct a C type name." },
368         { "help",     cmd_help,     "Print this list of commands." },
369         { "quit",     cmd_quit,     "Quit the program." },
370         { "exit",     cmd_quit,     NULL }
371 };
372 static const size_t ncommands = sizeof commands / sizeof commands[0];
373
374 static int cmd_help(const char *cmd, const char *arg)
375 {
376         for (size_t i = 0; i < ncommands; i++) {
377                 if (!commands[i].blurb)
378                         continue;
379
380                 printf("%s -- %s\n", commands[i].name, commands[i].blurb);
381         }
382
383         return 1;
384 }
385
386 /*
387  * Ensure that the first n characters of str equal the entire (null-terminated)
388  * string cmd.
389  */
390 static int cmd_cmp(const char *str, const char *cmd, size_t n)
391 {
392         size_t cmdlen = strlen(cmd);
393
394         if (n < cmdlen)
395                 return -1;
396         if (n > cmdlen)
397                 return 1;
398         return memcmp(str, cmd, n);
399 }
400
401 static int run_command(const char *line)
402 {
403         const char *cmd = line + strspn(line, " \t");
404         const char *arg = cmd  + strcspn(cmd, " \t");
405
406         if (cmd[0] == '\0')
407                 return 1;
408
409         for (size_t i = 0; i < ncommands; i++) {
410                 if (cmd_cmp(cmd, commands[i].name, arg-cmd) != 0)
411                         continue;
412
413                 return commands[i].func(cmd, arg);
414         }
415
416         fprintf(stderr, "Undefined command: %.*s\n", (int)(arg-cmd), cmd);
417         return -1;
418 }
419
420 static bool is_blank_line(const char *line)
421 {
422         for (size_t i = 0; line[i]; i++) {
423                 if (!isblank((unsigned char)line[i]))
424                         return false;
425         }
426
427         return true;
428 }
429
430 static int repl(void)
431 {
432         char *line;
433
434         for (; (line = readline("> ")); free(line)) {
435                 if (!is_blank_line(line))
436                         cdecl_add_history(line);
437
438                 if (!run_command(line))
439                         break;
440         }
441
442         free(line);
443         return 0;
444 }
445
446 static int repl_cmdline(int argc, char **argv)
447 {
448         int opt, rc, ret = 0;
449
450         optind = 1;
451         while ((opt = getopt_long(argc, argv, sopts, lopts, NULL)) != -1) {
452                 if (opt != 'e')
453                         continue;
454
455                 rc = run_command(optarg);
456                 if (rc < 0)
457                         ret = -1;
458                 else if (rc == 0)
459                         break;
460         }
461
462         return ret;
463 }
464
465 static int repl_noninteractive(void)
466 {
467         int rc, ret = 0, saved_errno;
468         char *line = NULL;
469         size_t n;
470
471         while (getline(&line, &n, stdin) >= 0) {
472                 char *c = strchr(line, '\n');
473                 if (c)
474                         *c = '\0';
475
476                 rc = run_command(line);
477                 if (rc < 0)
478                         ret = -1;
479                 else if (rc == 0)
480                         break;
481         }
482
483         saved_errno = errno;
484         free(line);
485
486         if (ferror(stdin)) {
487                 errno = saved_errno;
488                 perror("read error");
489                 return -1;
490         }
491
492         return ret;
493 }
494
495 /* Initialize gettext and setup translated long options. */
496 static void init_i18n(void)
497 {
498         if (!ENABLE_NLS)
499                 return;
500
501         setlocale(LC_ALL, "");
502         bindtextdomain(PACKAGE, LOCALEDIR);
503         textdomain(PACKAGE);
504
505         for (int i = 0, j = NOPTS; i < NOPTS; i++) {
506                 const char *tname = pgettext_expr("longopt", lopts[i].name);
507
508                 if (strcmp(tname, lopts[i].name) != 0) {
509                         lopts[j] = lopts[i];
510                         lopts[j].name = tname;
511                         j++;
512                 }
513         }
514 }
515
516 int main(int argc, char **argv)
517 {
518         bool show_intro = true, interactive = true, execute = false;
519         const char *filename = NULL;
520         int i, opt, rc;
521
522         if (argc > 0)
523                 progname = argv[0];
524
525         init_i18n();
526
527         while ((opt = getopt_long(argc, argv, sopts, lopts, NULL)) != -1) {
528                 switch (opt) {
529                 case 'q':
530                         show_intro = false;
531                         break;
532                 case 'b':
533                         interactive = false;
534                         break;
535                 case 'i':
536                         interactive = true;
537                         break;
538                 case 'f':
539                         filename = optarg;
540                         break;
541                 case 'e':
542                         execute = true;
543                         break;
544                 case 'V':
545                         print_version();
546                         return EXIT_SUCCESS;
547                 case 'H':
548                         print_help();
549                         return EXIT_SUCCESS;
550                 default:
551                         print_usage(stderr);
552                         return EXIT_FAILURE;
553                 }
554         }
555
556         if (optind < argc) {
557                 fprintf(stderr, _("%s: excess command-line arguments:"),
558                                 progname);
559                 for (i = optind; i < argc; i++) {
560                         fprintf(stderr, " %s", argv[i]);
561                 }
562                 fprintf(stderr, "\n");
563                 print_usage(stderr);
564                 return EXIT_FAILURE;
565         }
566
567         /* --filename and --execute imply --batch. */
568         if (filename || execute)
569                 interactive = false;
570
571         /* --batch implies --quiet */
572         if (interactive && show_intro)
573                 print_version();
574
575         /* --execute supersedes --filename */
576         if (filename && !execute) {
577                 if (!freopen(filename, "r", stdin)) {
578                         perror(filename);
579                         return EXIT_FAILURE;
580                 }
581         }
582
583         if (interactive)
584                 rc = repl();
585         else if (execute)
586                 rc = repl_cmdline(argc, argv);
587         else
588                 rc = repl_noninteractive();
589
590         if (rc != 0)
591                 return EXIT_FAILURE;
592         return EXIT_SUCCESS;
593 }