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