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