From 237066ccfc3155ec951d99a781ff4e00ff3d34cd Mon Sep 17 00:00:00 2001 From: Nick Bowler Date: Wed, 22 Jun 2011 20:30:50 -0400 Subject: [PATCH] Add initial command parser. --- src/cdecl99.c | 76 +++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 71 insertions(+), 5 deletions(-) diff --git a/src/cdecl99.c b/src/cdecl99.c index 76e64bc..6e15712 100644 --- a/src/cdecl99.c +++ b/src/cdecl99.c @@ -1,6 +1,7 @@ #include #include #include +#include #include #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) -- 2.43.2