]> git.draconx.ca Git - cdecl99.git/commitdiff
Add initial command parser.
authorNick Bowler <nbowler@draconx.ca>
Thu, 23 Jun 2011 00:30:50 +0000 (20:30 -0400)
committerNick Bowler <nbowler@draconx.ca>
Thu, 23 Jun 2011 00:30:50 +0000 (20:30 -0400)
src/cdecl99.c

index 76e64bc4d1932d91c0eaa6148a4169b77143562a..6e15712780106619ebf226d9ed73d24e2e916eec 100644 (file)
@@ -1,6 +1,7 @@
 #include <config.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 #include <getopt.h>
 #include "readline.h"
 #include "cdecl.h"
@@ -33,17 +34,82 @@ static void print_help(void)
        puts("Detailed help coming soon.");
 }
 
-static int repl(void)
+static int cmd_explain(char *cmd, char *arg)
 {
        struct cdecl *decl;
+
+       decl = cdecl_parse_decl(arg);
+       cdecl_free(decl);
+
+       return 1;
+}
+
+static int cmd_quit(char *cmd, char *arg)
+{
+       return 0;
+}
+
+static int cmd_help(char *cmd, char *arg);
+
+static const struct command {
+       char name[16];
+       int (*func)(char *cmd, char *arg);
+       const char *blurb;
+} commands[] = {
+       { "explain", cmd_explain, "Explain a C declaration." },
+       { "help",    cmd_help,    "Print this list of commands." },
+       { "quit",    cmd_quit,    "Quit the program." },
+       { "exit",    cmd_quit,    NULL }
+};
+static const size_t ncommands = sizeof commands / sizeof commands[0];
+
+static int cmd_help(char *cmd, char *arg)
+{
+       for (size_t i = 0; i < ncommands; i++) {
+               if (!commands[i].blurb)
+                       continue;
+
+               printf("%s -- %s\n", commands[i].name, commands[i].blurb);
+       }
+
+       return 1;
+}
+
+static int repl(void)
+{
+       char *line;
+       int ret;
+
        print_version();
 
-       for (char *line; (line = readline("> ")); free(line)) {
-               decl = cdecl_parse_decl(line);
-               cdecl_free(decl);
+       for (; (line = readline("> ")); free(line)) {
+               char *cmd = line + strspn(line, " \t");
+               char *arg = cmd  + strcspn(cmd, " \t");
+
+               if (cmd[0] == '\0')
+                       continue;
+               if (arg[0] != '\0')
+                       *arg++ = '\0';
+
+               for (size_t i = 0; i < ncommands; i++) {
+                       if (strcmp(cmd, commands[i].name) != 0)
+                               continue;
+
+                       ret = commands[i].func(cmd, arg);
+                       if (ret <= 0)
+                               goto out;
+                       goto next;
+               }
+
+               fprintf(stderr, "Undefined command: %s\n", cmd);
+       next:
+               ;
        }
 
-       return 0;
+       ret = 0;
+out:
+       free(line);
+       return ret;
 }
 
 int main(int argc, char **argv)