Simplify tokenization code.
[open-adventure.git] / misc.c
1 #include <unistd.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <stdarg.h>
6 #include <sys/time.h>
7 #include <ctype.h>
8 #include <editline/readline.h>
9
10 #include "advent.h"
11 #include "dungeon.h"
12
13 char* xstrdup(const char* s)
14 {
15     char* ptr = strdup(s);
16     if (ptr == NULL) {
17         // LCOV_EXCL_START
18         // exclude from coverage analysis because we can't simulate an out of memory error in testing
19         fprintf(stderr, "Out of memory!\n");
20         exit(EXIT_FAILURE);
21     }
22     return (ptr);
23 }
24
25 void* xmalloc(size_t size)
26 {
27     void* ptr = malloc(size);
28     if (ptr == NULL) {
29         // LCOV_EXCL_START
30         // exclude from coverage analysis because we can't simulate an out of memory error in testing
31         fprintf(stderr, "Out of memory!\n");
32         exit(EXIT_FAILURE);
33         // LCOV_EXCL_STOP
34     }
35     return (ptr);
36 }
37
38 void packed_to_token(long packed, char token[TOKLEN+1])
39 {
40     // The advent->ascii mapping.
41     const char advent_to_ascii[] = {
42         ' ', '!', '"', '#', '$', '%', '&', '\'',
43         '(', ')', '*', '+', ',', '-', '.', '/',
44         '0', '1', '2', '3', '4', '5', '6', '7',
45         '8', '9', ':', ';', '<', '=', '>', '?',
46         '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
47         'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
48         'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
49         'X', 'Y', 'Z', '\0', '\0', '\0', '\0', '\0',
50     };
51
52     // Unpack and map back to ASCII.
53     for (int i = 0; i < 5; ++i) {
54         char advent = (packed >> i * 6) & 63;
55         token[i] = advent_to_ascii[(int) advent];
56     }
57
58     // Ensure the last character is \0.
59     token[5] = '\0';
60
61     // Replace trailing whitespace with \0.
62     for (int i = 4; i >= 0; --i) {
63         if (token[i] == ' ' ||
64             token[i] == '\t')
65             token[i] = '\0';
66         else
67             break;
68     }
69 }
70
71 long token_to_packed(const char token[])
72 {
73     const char ascii_to_advent[] = {
74         63, 63, 63, 63, 63, 63, 63, 63,
75         63, 63, 63, 63, 63, 63, 63, 63,
76         63, 63, 63, 63, 63, 63, 63, 63,
77         63, 63, 63, 63, 63, 63, 63, 63,
78
79         0, 1, 2, 3, 4, 5, 6, 7,
80         8, 9, 10, 11, 12, 13, 14, 15,
81         16, 17, 18, 19, 20, 21, 22, 23,
82         24, 25, 26, 27, 28, 29, 30, 31,
83         32, 33, 34, 35, 36, 37, 38, 39,
84         40, 41, 42, 43, 44, 45, 46, 47,
85         48, 49, 50, 51, 52, 53, 54, 55,
86         56, 57, 58, 59, 60, 61, 62, 63,
87
88         63, 63, 63, 63, 63, 63, 63, 63,
89         63, 63, 63, 63, 63, 63, 63, 63,
90         63, 63, 63, 63, 63, 63, 63, 63,
91         63, 63, 63, 63, 63, 63, 63, 63,
92     };
93
94     size_t t_len = strlen(token);
95     if (t_len > TOKLEN)
96         t_len = TOKLEN;
97     long packed = 0;
98     for (size_t i = 0; i < t_len; ++i) {
99         char mapped = ascii_to_advent[(int) toupper(token[i])];
100         packed |= (mapped << (6 * i));
101     }
102     return (packed);
103 }
104
105 void tokenize(char* raw, struct command_t *cmd)
106 {
107     memset(cmd, '\0', sizeof(struct command_t));
108
109     /* FIXME: put a bound prefix on the %s to prevent buffer overflow */
110     int word_count = sscanf(raw, "%s%s", cmd->raw1, cmd->raw2);
111
112     // pack the substrings
113     cmd->wd1  = token_to_packed(cmd->raw1);
114     cmd->wd2  = token_to_packed(cmd->raw2);
115 }
116
117 /* Hide the fact that wods are corrently packed longs */
118
119 bool wordeq(token_t a, token_t b)
120 {
121     return a == b;
122 }
123
124 bool wordempty(token_t a)
125 {
126     return a == 0;
127 }
128
129 void wordclear(token_t *v)
130 {
131     *v = 0;
132 }
133
134 /*  I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
135
136 void vspeak(const char* msg, bool blank, va_list ap)
137 {
138     // Do nothing if we got a null pointer.
139     if (msg == NULL)
140         return;
141
142     // Do nothing if we got an empty string.
143     if (strlen(msg) == 0)
144         return;
145
146     if (blank == true)
147         printf("\n");
148
149     int msglen = strlen(msg);
150
151     // Rendered string
152     ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
153     char* rendered = xmalloc(size);
154     char* renderp = rendered;
155
156     // Handle format specifiers (including the custom %C, %L, %S) by
157     // adjusting the parameter accordingly, and replacing the
158     // specifier with %s.
159     long previous_arg = 0;
160     for (int i = 0; i < msglen; i++) {
161         if (msg[i] != '%') {
162             *renderp++ = msg[i];
163             size--;
164         } else {
165             long arg = va_arg(ap, long);
166             if (arg == -1)
167                 arg = 0; // LCOV_EXCL_LINE - don't think we can get here.
168             i++;
169             // Integer specifier. In order to accommodate the fact
170             // that PARMS can have both legitimate integers *and*
171             // packed tokens, stringify everything. Future work may
172             // eliminate the need for this.
173             if (msg[i] == 'd') {
174                 int ret = snprintf(renderp, size, "%ld", arg);
175                 if (ret < size) {
176                     renderp += ret;
177                     size -= ret;
178                 }
179             }
180
181             // Unmodified string specifier.
182             if (msg[i] == 's') {
183                 packed_to_token(arg, renderp); /* unpack directly to destination */
184                 size_t len = strlen(renderp);
185                 renderp += len;
186                 size -= len;
187             }
188
189             // Singular/plural specifier.
190             if (msg[i] == 'S') {
191                 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
192                     *renderp++ = 's';
193                     size--;
194                 }
195             }
196
197             /* Version specifier */
198             if (msg[i] == 'V') {
199                 strcpy(renderp, VERSION);
200                 size_t len = strlen(VERSION);
201                 renderp += len;
202                 size -= len;
203             }
204
205             // All-lowercase specifier.
206             if (msg[i] == 'L' ||
207                 msg[i] == 'C') {
208                 packed_to_token(arg, renderp); /* unpack directly to destination */
209                 int len = strlen(renderp);
210                 for (int j = 0; j < len; ++j) {
211                     renderp[j] = tolower(renderp[j]);
212                 }
213                 if (msg[i] == 'C') // First char uppercase, rest lowercase.
214                     renderp[0] = toupper(renderp[0]);
215                 renderp += len;
216                 size -= len;
217             }
218
219             previous_arg = arg;
220         }
221     }
222     *renderp = 0;
223
224     // Print the message.
225     printf("%s\n", rendered);
226
227     free(rendered);
228 }
229
230 void speak(const char* msg, ...)
231 {
232     va_list ap;
233     va_start(ap, msg);
234     vspeak(msg, true, ap);
235     va_end(ap);
236 }
237
238 void sspeak(const long msg, ...)
239 {
240     va_list ap;
241     va_start(ap, msg);
242     fputc('\n', stdout);
243     vprintf(arbitrary_messages[msg], ap);
244     fputc('\n', stdout);
245     va_end(ap);
246 }
247
248 void pspeak(vocab_t msg, enum speaktype mode, int skip, bool blank, ...)
249 /* Find the skip+1st message from msg and print it.  Modes are:
250  * feel = for inventory, what you can touch
251  * look = the long description for the state the object is in
252  * listen = the sound for the state the object is in
253  * study = text on the object. */
254 {
255     va_list ap;
256     va_start(ap, blank);
257     switch (mode) {
258     case touch:
259         vspeak(objects[msg].inventory, blank, ap);
260         break;
261     case look:
262         vspeak(objects[msg].descriptions[skip], blank, ap);
263         break;
264     case hear:
265         vspeak(objects[msg].sounds[skip], blank, ap);
266         break;
267     case study:
268         vspeak(objects[msg].texts[skip], blank, ap);
269         break;
270     case change:
271         vspeak(objects[msg].changes[skip], blank, ap);
272         break;
273     }
274     va_end(ap);
275 }
276
277 void rspeak(vocab_t i, ...)
278 /* Print the i-th "random" message (section 6 of database). */
279 {
280     va_list ap;
281     va_start(ap, i);
282     vspeak(arbitrary_messages[i], true, ap);
283     va_end(ap);
284 }
285
286 void echo_input(FILE* destination, const char* input_prompt, const char* input)
287 {
288     size_t len = strlen(input_prompt) + strlen(input) + 1;
289     char* prompt_and_input = (char*) xmalloc(len);
290     strcpy(prompt_and_input, input_prompt);
291     strcat(prompt_and_input, input);
292     fprintf(destination, "%s\n", prompt_and_input);
293     free(prompt_and_input);
294 }
295
296 int word_count(char* s)
297 {
298     char* copy = xstrdup(s);
299     char delims[] = " \t";
300     int count = 0;
301     char* word;
302
303     word = strtok(copy, delims);
304     while (word != NULL) {
305         word = strtok(NULL, delims);
306         ++count;
307     }
308     free(copy);
309     return (count);
310 }
311
312 char* get_input()
313 {
314     // Set up the prompt
315     char input_prompt[] = "> ";
316     if (!settings.prompt)
317         input_prompt[0] = '\0';
318
319     // Print a blank line
320     printf("\n");
321
322     char* input;
323     while (true) {
324         input = readline(input_prompt);
325
326         if (input == NULL) // Got EOF; return with it.
327             return (input);
328         else if (input[0] == '#') { // Ignore comments.
329             free(input);
330             continue;
331         } else // We have a 'normal' line; leave the loop.
332             break;
333     }
334
335     // Strip trailing newlines from the input
336     input[strcspn(input, "\n")] = 0;
337
338     add_history(input);
339
340     if (!isatty(0))
341         echo_input(stdout, input_prompt, input);
342
343     if (settings.logfp)
344         echo_input(settings.logfp, "", input);
345
346     return (input);
347 }
348
349 bool silent_yes()
350 {
351     char* reply;
352     bool outcome;
353
354     for (;;) {
355         reply = get_input();
356         if (reply == NULL) {
357             // LCOV_EXCL_START
358             // Should be unreachable. Reply should never be NULL
359             free(reply);
360             exit(EXIT_SUCCESS);
361             // LCOV_EXCL_STOP
362         }
363
364         char* firstword = (char*) xmalloc(strlen(reply) + 1);
365         sscanf(reply, "%s", firstword);
366
367         free(reply);
368
369         for (int i = 0; i < (int)strlen(firstword); ++i)
370             firstword[i] = tolower(firstword[i]);
371
372         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
373         int y = strncmp("y", firstword, sizeof("y") - 1);
374         int no = strncmp("no", firstword, sizeof("no") - 1);
375         int n = strncmp("n", firstword, sizeof("n") - 1);
376
377         free(firstword);
378
379         if (yes == 0 ||
380             y == 0) {
381             outcome = true;
382             break;
383         } else if (no == 0 ||
384                    n == 0) {
385             outcome = false;
386             break;
387         } else
388             rspeak(PLEASE_ANSWER);
389     }
390     return (outcome);
391 }
392
393
394 bool yes(const char* question, const char* yes_response, const char* no_response)
395 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
396  *  if no, print Z and return false. */
397 {
398     char* reply;
399     bool outcome;
400
401     for (;;) {
402         speak(question);
403
404         reply = get_input();
405         if (reply == NULL) {
406             // LCOV_EXCL_START
407             // Should be unreachable. Reply should never be NULL
408             free(reply);
409             exit(EXIT_SUCCESS);
410             // LCOV_EXCL_STOP
411         }
412
413         char* firstword = (char*) xmalloc(strlen(reply) + 1);
414         sscanf(reply, "%s", firstword);
415
416         free(reply);
417
418         for (int i = 0; i < (int)strlen(firstword); ++i)
419             firstword[i] = tolower(firstword[i]);
420
421         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
422         int y = strncmp("y", firstword, sizeof("y") - 1);
423         int no = strncmp("no", firstword, sizeof("no") - 1);
424         int n = strncmp("n", firstword, sizeof("n") - 1);
425
426         free(firstword);
427
428         if (yes == 0 ||
429             y == 0) {
430             speak(yes_response);
431             outcome = true;
432             break;
433         } else if (no == 0 ||
434                    n == 0) {
435             speak(no_response);
436             outcome = false;
437             break;
438         } else
439             rspeak(PLEASE_ANSWER);
440
441     }
442
443     return (outcome);
444 }
445
446 /*  Data structure  routines */
447
448 int get_motion_vocab_id(const char* word)
449 // Return the first motion number that has 'word' as one of its words.
450 {
451     for (int i = 0; i < NMOTIONS; ++i) {
452         for (int j = 0; j < motions[i].words.n; ++j) {
453             if (strcasecmp(word, motions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
454                     strchr(ignore, word[0]) == NULL ||
455                     !settings.oldstyle))
456                 return (i);
457         }
458     }
459     // If execution reaches here, we didn't find the word.
460     return (WORD_NOT_FOUND);
461 }
462
463 int get_object_vocab_id(const char* word)
464 // Return the first object number that has 'word' as one of its words.
465 {
466     for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
467         for (int j = 0; j < objects[i].words.n; ++j) {
468             if (strcasecmp(word, objects[i].words.strs[j]) == 0)
469                 return (i);
470         }
471     }
472     // If execution reaches here, we didn't find the word.
473     return (WORD_NOT_FOUND);
474 }
475
476 int get_action_vocab_id(const char* word)
477 // Return the first motion number that has 'word' as one of its words.
478 {
479     for (int i = 0; i < NACTIONS; ++i) {
480         for (int j = 0; j < actions[i].words.n; ++j) {
481             if (strcasecmp(word, actions[i].words.strs[j]) == 0 && (strlen(word) > 1 ||
482                     strchr(ignore, word[0]) == NULL ||
483                     !settings.oldstyle))
484                 return (i);
485         }
486     }
487     // If execution reaches here, we didn't find the word.
488     return (WORD_NOT_FOUND);
489 }
490
491 int get_special_vocab_id(const char* word)
492 // Return the first special number that has 'word' as one of its words.
493 {
494     for (int i = 0; i < NSPECIALS; ++i) {
495         for (int j = 0; j < specials[i].words.n; ++j) {
496             if (strcasecmp(word, specials[i].words.strs[j]) == 0)
497                 return (i);
498         }
499     }
500     // If execution reaches here, we didn't find the word.
501     return (WORD_NOT_FOUND);
502 }
503
504 long get_vocab_id(const char* word)
505 // Search the vocab categories in order for the supplied word.
506 {
507     long ref_num;
508
509     /* FIXME: Magic numbers related to vocabulary */
510     ref_num = get_motion_vocab_id(word);
511     if (ref_num != WORD_NOT_FOUND)
512         return (ref_num + 0); // FIXME: replace with a proper hash
513
514     ref_num = get_object_vocab_id(word);
515     if (ref_num != WORD_NOT_FOUND)
516         return (ref_num + 1000); // FIXME: replace with a proper hash
517
518     ref_num = get_action_vocab_id(word);
519     if (ref_num != WORD_NOT_FOUND)
520         return (ref_num + 2000); // FIXME: replace with a proper hash
521
522     ref_num = get_special_vocab_id(word);
523     if (ref_num != WORD_NOT_FOUND)
524         return (ref_num + 3000); // FIXME: replace with a proper hash
525
526     // Check for the reservoir magic word.
527     if (strcasecmp(word, game.zzword) == 0)
528         return (PART + 2000); // FIXME: replace with a proper hash
529
530     return (WORD_NOT_FOUND);
531 }
532
533 void juggle(long object)
534 /*  Juggle an object by picking it up and putting it down again, the purpose
535  *  being to get the object to the front of the chain of things at its loc. */
536 {
537     long i, j;
538
539     i = game.place[object];
540     j = game.fixed[object];
541     move(object, i);
542     move(object + NOBJECTS, j);
543 }
544
545 void move(long object, long where)
546 /*  Place any object anywhere by picking it up and dropping it.  May
547  *  already be toting, in which case the carry is a no-op.  Mustn't
548  *  pick up objects which are not at any loc, since carry wants to
549  *  remove objects from game.atloc chains. */
550 {
551     long from;
552
553     if (object > NOBJECTS)
554         from = game.fixed[object - NOBJECTS];
555     else
556         from = game.place[object];
557     if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
558         carry(object, from);
559     drop(object, where);
560 }
561
562 long put(long object, long where, long pval)
563 /*  PUT is the same as MOVE, except it returns a value used to set up the
564  *  negated game.prop values for the repository objects. */
565 {
566     move(object, where);
567     return (-1) - pval;;
568 }
569
570 void carry(long object, long where)
571 /*  Start toting an object, removing it from the list of things at its former
572  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
573  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
574 {
575     long temp;
576
577     if (object <= NOBJECTS) {
578         if (game.place[object] == CARRIED)
579             return;
580         game.place[object] = CARRIED;
581         ++game.holdng;
582     }
583     if (game.atloc[where] == object) {
584         game.atloc[where] = game.link[object];
585         return;
586     }
587     temp = game.atloc[where];
588     while (game.link[temp] != object) {
589         temp = game.link[temp];
590     }
591     game.link[temp] = game.link[object];
592 }
593
594 void drop(long object, long where)
595 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
596  *  game.holdng if the object was being toted. */
597 {
598     if (object > NOBJECTS)
599         game.fixed[object - NOBJECTS] = where;
600     else {
601         if (game.place[object] == CARRIED)
602             --game.holdng;
603         game.place[object] = where;
604     }
605     if (where <= 0)
606         return;
607     game.link[object] = game.atloc[where];
608     game.atloc[where] = object;
609 }
610
611 long atdwrf(long where)
612 /*  Return the index of first dwarf at the given location, zero if no dwarf is
613  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
614  *  the pirate (6th dwarf). */
615 {
616     long at;
617
618     at = 0;
619     if (game.dflag < 2)
620         return (at);
621     at = -1;
622     for (long i = 1; i <= NDWARVES - 1; i++) {
623         if (game.dloc[i] == where)
624             return i;
625         if (game.dloc[i] != 0)
626             at = 0;
627     }
628     return (at);
629 }
630
631 /*  Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
632  *  randrange) */
633
634 long setbit(long bit)
635 /*  Returns 2**bit for use in constructing bit-masks. */
636 {
637     return (1L << bit);
638 }
639
640 bool tstbit(long mask, int bit)
641 /*  Returns true if the specified bit is set in the mask. */
642 {
643     return (mask & (1 << bit)) != 0;
644 }
645
646 void set_seed(long seedval)
647 /* Set the LCG seed */
648 {
649     game.lcg_x = (unsigned long) seedval % game.lcg_m;
650
651     // once seed is set, we need to generate the Z`ZZZ word
652     make_zzword(game.zzword);
653 }
654
655 unsigned long get_next_lcg_value(void)
656 /* Return the LCG's current value, and then iterate it. */
657 {
658     unsigned long old_x = game.lcg_x;
659     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
660     return old_x;
661 }
662
663 long randrange(long range)
664 /* Return a random integer from [0, range). */
665 {
666     return range * get_next_lcg_value() / game.lcg_m;
667 }
668
669 void make_zzword(char zzword[TOKLEN+1])
670 {
671     for (int i = 0; i < 5; ++i) {
672         zzword[i] = 'A' + randrange(26);
673     }
674     zzword[1] = '\''; // force second char to apostrophe
675     zzword[5] = '\0';
676 }
677
678 // LCOV_EXCL_START
679 void bug(enum bugtype num, const char *error_string)
680 {
681     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
682     exit(EXIT_FAILURE);
683 }
684 // LCOV_EXCL_STOP
685
686 /* end */