From 45b8159cc39792ddc4e989b11036f026d49f33e7 Mon Sep 17 00:00:00 2001 From: zlg Date: Sat, 5 Dec 2015 21:46:57 -0800 Subject: Solve Exercise 6-6: A simple `#define` processor This exercise is probably the most challenging "function puzzle" thus far. Modifying getword(), using various states, and the hashtable all create an example of how small building blocks can work together to make something. The implementation is very simple and nowhere near completely supporting '#define', but that's not the point. To properly support it, you'd need to build an entire preprocessor/parser, and that's far beyond the scope of both the exercise and book. --- ch6/6-05_undef.c | 3 +- ch6/6-06_define-processor.c | 199 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 200 insertions(+), 2 deletions(-) create mode 100644 ch6/6-06_define-processor.c (limited to 'ch6') diff --git a/ch6/6-05_undef.c b/ch6/6-05_undef.c index 9ffd248..d65f435 100644 --- a/ch6/6-05_undef.c +++ b/ch6/6-05_undef.c @@ -5,7 +5,7 @@ /* The C Programming Language: 2nd Edition * * Exercise 6-5: Write a function `undef` that will remove a name and - * definition from the table maintai\ed by lookup() and install(). + * definition from the table maintained by lookup() and install(). * * Notes: since undef() operates on the same data structure as lookup() * and install(), I chose to depend on lookup() to find the correct node @@ -27,7 +27,6 @@ unsigned hash(char *); struct nlist *install(char *, char *); struct nlist *lookup(char *); int undef(char *); -void print_table(struct nlist *); int main(int argc, char **argv) { /* Install a few words */ diff --git a/ch6/6-06_define-processor.c b/ch6/6-06_define-processor.c new file mode 100644 index 0000000..d26ddbc --- /dev/null +++ b/ch6/6-06_define-processor.c @@ -0,0 +1,199 @@ +#include +#include // strdup, strcmp +#include // malloc, free + +/* The C Programming Language: 2nd Edition + * + * Exercise 6-6: Implement a simple version of the `#define` processor + * (i.e., no arguments) suitable for use with C programs, based on the + * routines of this section. You may also find getch() and ungetch() + * helpful. + * + * Notes: The routines this exercise is talking about are lookup() and + * install(), which were used in 6-5. It also depends on the 'nlist' + * data structure that those functions used. It's unclear what is meant + * by "#define processor", so I opted for a simple string replacement + * implementation. It only accepts one alpha-numeric name and one alpha- + * numeric replacement, so nowhere *near* correctly supporting #define, + * but it fulfills the requirements. There's room for improvement here, + * for sure. + */ + +#define HASHSIZE 101 +#define MAXWORD 65 +#define BUFSIZE 40 + +struct nlist { + struct nlist *next; + char *name; + char *defn; +}; + +static struct nlist *hashtab[HASHSIZE]; +enum states { + NORMAL, + INQUOTE, + COMMENT_PART_IN, + COMMENT_PART_OUT, + ONELINE_COMMENT, + INCOMMENT +}; +static char buf[BUFSIZE]; +static int bufp = 0; +int state = NORMAL; + +unsigned hash(char *); +struct nlist *install(char *, char *); +struct nlist *lookup(char *); +int getch(void); +void ungetch(int); +int getword(char *, int); + +int main() { + char *word = malloc(sizeof(char) * MAXWORD); + struct nlist *def; + int define_phase = 0; + char *name; + char *desc; + while (getword(word, MAXWORD) != EOF) { + if (state == NORMAL && strcmp(word, "#define") == 0) { + define_phase = 1; + printf("%s", word); + continue; + } + if (define_phase == 1) { + name = strdup(word); + define_phase = 2; + printf("%s", word); + continue; + } + if (define_phase == 2) { + desc = strdup(word); + define_phase = 0; + printf("%s", word); + install(name, desc); + continue; + } + if (state == NORMAL && (def = lookup(word)) != NULL) { + printf("%s", def->defn); + continue; + } + printf("%s", word); + } +} + +/* form hash value for string s */ +unsigned hash(char *s) { + unsigned hashval; + for (hashval = 0; *s != '\0'; s++) { + hashval = *s + 31 * hashval; + } + return hashval % HASHSIZE; +} + +/* Look for s in hashtab */ +struct nlist *lookup(char *s) { + struct nlist *np; + for (np = hashtab[hash(s)]; np != NULL; np = np->next) { + if (strcmp(s, np->name) == 0) { + return np; + } + } + return NULL; +} + +/* put name and defn in hashtab */ +struct nlist *install(char *name, char *defn) { + struct nlist *np; + unsigned hashval; + if ((np = lookup(name)) == NULL) { + np = (struct nlist *) malloc(sizeof(*np)); + if (np == NULL || (np->name = strdup(name)) == NULL) { + return NULL; + } + hashval = hash(name); + np->next = hashtab[hashval]; + hashtab[hashval] = np; + } else { + free ((void *) np->defn); + } + if ((np->defn = strdup(defn)) == NULL) { + return NULL; + } + return np; +} + +int getch(void) { + return (bufp > 0) ? buf[--bufp] : getchar(); +} + +void ungetch(int c) { + if (bufp >= BUFSIZE) { + printf("ungetch: Too many characters.\n"); + } else { + buf[bufp++] = c; + } +} + +int getword(char *word, int lim) { + int c; + char *w = word; + while (isspace(c = getch())) { + if (c == '\n' && state == ONELINE_COMMENT) { + state = NORMAL; + } + putchar(c); + } + if (c != EOF) { + *w++ = c; + } else { + return EOF; + } + switch (c) { + case '/': + switch (state) { + case NORMAL: + state = COMMENT_PART_IN; + break; + case COMMENT_PART_IN: + state = ONELINE_COMMENT; + break; + case COMMENT_PART_OUT: + state = NORMAL; + break; + } + break; + case '*': + switch (state) { + case INCOMMENT: + state = COMMENT_PART_OUT; + break; + case COMMENT_PART_IN: + state = INCOMMENT; + break; + } + break; + case '"': + switch (state) { + case NORMAL: + state = INQUOTE; + break; + case INQUOTE: + state = NORMAL; + break; + } + break; + } + if (!isalnum(c) && c != '#') { + *w = '\0'; + return c; + } + for ( ; --lim > 0; w++) { + if (!isalnum(*w = getch())) { + ungetch(*w); + break; + } + } + *w = '\0'; + return word[0]; +} -- cgit v1.2.3-70-g09d2 2018-09-29cli: Add pretty printing to 'list' commandzlg3-17/+107 Also add the "--width" option to specify the maximum width of the table. 2018-09-08setup.py: Bump to alpha4 for PyPIzlg1-1/+1 2018-09-08cli: add '--raw' option to list commandzlg2-9/+45 Add '--raw' option to the list command, in addition to proper note expansion. Newline characters in notes are escaped to be friendly to scripting. This option may be shortened to '-r' at the user's convenience. In raw output mode, the information is formatted in plain pipe-delimited strings, one line per row: title|system|ownership|progress|notes ownership and progress are printed in their numeric form, consistent with the OWNERSHIP and PROGRESS dictionaries in the vgstash package. An empty notes field will result in a line ending with a pipe and no whitespace following it. 2018-09-08Add remaining filters to vgstash packagezlg1-2/+11 2018-09-04Update LICENSE to match setup.pyzlg1-80/+67 Whoops. 2018-09-03Branch off from master with pytest, tox, clickzlg16-778/+779 This commit is huge, but contains everything needed for a "proper" build system built on pytest + tox and a CLI built with click. For now, this branch will contain all new vgstash development activity until it reaches feature parity with master. The CLI is installed to pip's PATH. Only the 'init', 'add', and 'list' commands work, with only two filters. This is pre-alpha software, and is therefore not stable yet. 2018-03-18Flesh out filter types and ownership statuszlg3-82/+144 It's time for a refactor to a module; the functionality and interface are clashing. 2018-03-18README.mdown: break line correctlyzlg1-1/+1 2018-03-18add 'playlog' list filterzlg2-2/+9 This filter is used to get an idea of which games you're currently playing through, so you can prioritize games to play when you're bored and detect it when you've beaten a game but haven't marked it as such. 2018-03-13Update helpers a bitzlg1-2/+9 At present, user modification is needed to make these seamless. vgup() may need to be axed in favor of telling the user to make an alias. 2018-03-13Make VGSTASH_DB_LOCATION point to a filezlg2-21/+20 It used to point to a directory, which would then look for .vgstash.db. This behavior was kind of backwards and I don't remember why I did it that way. This change gives users more control over where they put their DB. Be sure to update your environment variable if you have it set! 2016-11-18Remove settings from helpers.shZe Libertine Gamer1-5/+0 Sourcing them in .bash_profile screws up login if they're set. 2016-11-15Correct phrasing in README.Ze Libertine Gamer1-4/+4 2016-11-13DerpZe Libertine Gamer1-0/+1 2016-11-03Improve error handling in shell scriptsZe Libertine Gamer4-3/+23 2016-10-24Correct run_again, add recursionZe Libertine Gamer1-0/+4 Loops and functions -- oh my, what a useful combination. :) 2016-10-21Add quotes to correct behavior for arglistZe Libertine Gamer1-1/+1 2016-10-14updater.sh: add recursion, error handlingZe Libertine Gamer1-43/+101 2016-10-14Correct pipe-handling behaviorZe Libertine Gamer1-1/+9 2016-10-12Clarify a method to move between platformsZe Libertine Gamer1-2/+5 Also correct a typo.