Correct return types for all of the action handling functions in actions, so it's...
[open-adventure.git] / misc.c
1 /*
2  * I/O and support riutines.
3  *
4  * Copyright (c) 1977, 2005 by Will Crowther and Don Woods
5  * Copyright (c) 2017 by Eric S. Raymond
6  * SPDX-License-Identifier: BSD-2-clause
7  */
8
9 #include <unistd.h>
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdarg.h>
14 #include <sys/time.h>
15 #include <ctype.h>
16 #include <editline/readline.h>
17 #include <inttypes.h>
18
19 #include "advent.h"
20 #include "dungeon.h"
21
22 static void* xcalloc(size_t size)
23 {
24     void* ptr = calloc(size, 1);
25     if (ptr == NULL) {
26         // LCOV_EXCL_START
27         // exclude from coverage analysis because we can't simulate an out of memory error in testing
28         fprintf(stderr, "Out of memory!\n");
29         exit(EXIT_FAILURE);
30         // LCOV_EXCL_STOP
31     }
32     return (ptr);
33 }
34
35 /*  I/O routines (speak, pspeak, rspeak, sspeak, get_input, yes) */
36
37 static void vspeak(const char* msg, bool blank, va_list ap)
38 {
39     // Do nothing if we got a null pointer.
40     if (msg == NULL)
41         return;
42
43     // Do nothing if we got an empty string.
44     if (strlen(msg) == 0)
45         return;
46
47     if (blank == true)
48         printf("\n");
49
50     int msglen = strlen(msg);
51
52     // Rendered string
53     ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
54     char* rendered = xcalloc(size);
55     char* renderp = rendered;
56
57     // Handle format specifiers (including the custom %S) by
58     // adjusting the parameter accordingly, and replacing the
59     // specifier with %s.
60     bool pluralize = false;
61     for (int i = 0; i < msglen; i++) {
62         if (msg[i] != '%') {
63             /* Ugh.  Least obtrusive way to deal with artifacts "on the floor"
64              * being dropped outside of both cave and building. */
65             if (strncmp(msg + i, "floor", 5) == 0 && strchr(" .", msg[i + 5]) && !INSIDE(game.loc)) {
66                 strcpy(renderp, "ground");
67                 renderp += 6;
68                 i += 4;
69                 size -= 5;
70             } else {
71                 *renderp++ = msg[i];
72                 size--;
73             }
74         } else {
75             i++;
76             // Integer specifier.
77             if (msg[i] == 'd') {
78                 int32_t arg = va_arg(ap, int32_t);
79                 int ret = snprintf(renderp, size, "%" PRId32, arg);
80                 if (ret < size) {
81                     renderp += ret;
82                     size -= ret;
83                 }
84                 pluralize = (arg != 1);
85             }
86
87             // Unmodified string specifier.
88             if (msg[i] == 's') {
89                 char *arg = va_arg(ap, char *);
90                 strncat(renderp, arg, size - 1);
91                 size_t len = strlen(renderp);
92                 renderp += len;
93                 size -= len;
94             }
95
96             // Singular/plural specifier.
97             if (msg[i] == 'S') {
98                 // look at the *previous* numeric parameter
99                 if (pluralize) {
100                     *renderp++ = 's';
101                     size--;
102                 }
103             }
104
105             // LCOV_EXCL_START - doesn't occur in test suite.
106             /* Version specifier */
107             if (msg[i] == 'V') {
108                 strcpy(renderp, VERSION);
109                 size_t len = strlen(VERSION);
110                 renderp += len;
111                 size -= len;
112             }
113             // LCOV_EXCL_STOP
114         }
115     }
116     *renderp = 0;
117
118     // Print the message.
119     printf("%s\n", rendered);
120
121     free(rendered);
122 }
123
124 void speak(const char* msg, ...)
125 {
126     va_list ap;
127     va_start(ap, msg);
128     vspeak(msg, true, ap);
129     va_end(ap);
130 }
131
132 void sspeak(const int msg, ...)
133 {
134     va_list ap;
135     va_start(ap, msg);
136     fputc('\n', stdout);
137     vprintf(arbitrary_messages[msg], ap);
138     fputc('\n', stdout);
139     va_end(ap);
140 }
141
142 void pspeak(vocab_t msg, enum speaktype mode, bool blank, int skip, ...)
143 /* Find the skip+1st message from msg and print it.  Modes are:
144  * feel = for inventory, what you can touch
145  * look = the full description for the state the object is in
146  * listen = the sound for the state the object is in
147  * study = text on the object. */
148 {
149     va_list ap;
150     va_start(ap, skip);
151     switch (mode) {
152     case touch:
153         vspeak(objects[msg].inventory, blank, ap);
154         break;
155     case look:
156         vspeak(objects[msg].descriptions[skip], blank, ap);
157         break;
158     case hear:
159         vspeak(objects[msg].sounds[skip], blank, ap);
160         break;
161     case study:
162         vspeak(objects[msg].texts[skip], blank, ap);
163         break;
164     case change:
165         vspeak(objects[msg].changes[skip], blank, ap);
166         break;
167     }
168     va_end(ap);
169 }
170
171 void rspeak(vocab_t i, ...)
172 /* Print the i-th "random" message (section 6 of database). */
173 {
174     va_list ap;
175     va_start(ap, i);
176     vspeak(arbitrary_messages[i], true, ap);
177     va_end(ap);
178 }
179
180 void echo_input(FILE* destination, const char* input_prompt, const char* input)
181 {
182     size_t len = strlen(input_prompt) + strlen(input) + 1;
183     char* prompt_and_input = (char*) xcalloc(len);
184     strcpy(prompt_and_input, input_prompt);
185     strcat(prompt_and_input, input);
186     fprintf(destination, "%s\n", prompt_and_input);
187     free(prompt_and_input);
188 }
189
190 static int word_count(char* str)
191 {
192     char delims[] = " \t";
193     int count = 0;
194     int inblanks = true;
195
196     for (char *s = str; *s; s++)
197         if (inblanks) {
198             if (strchr(delims, *s) == 0) {
199                 ++count;
200                 inblanks = false;
201             }
202         } else {
203             if (strchr(delims, *s) != 0) {
204                 inblanks = true;
205             }
206         }
207
208     return (count);
209 }
210
211 static char* get_input(void)
212 {
213     // Set up the prompt
214     char input_prompt[] = "> ";
215     if (!settings.prompt)
216         input_prompt[0] = '\0';
217
218     // Print a blank line
219     printf("\n");
220
221     char* input;
222     while (true) {
223         input = readline(input_prompt);
224
225         if (input == NULL) // Got EOF; return with it.
226             return (input);
227         if (input[0] == '#') { // Ignore comments.
228             free(input);
229             continue;
230         }
231         // We have a 'normal' line; leave the loop.
232         break;
233     }
234
235     // Strip trailing newlines from the input
236     input[strcspn(input, "\n")] = 0;
237
238     add_history(input);
239
240     if (!isatty(0))
241         echo_input(stdout, input_prompt, input);
242
243     if (settings.logfp)
244         echo_input(settings.logfp, "", input);
245
246     return (input);
247 }
248
249 bool silent_yes(void)
250 {
251     bool outcome = false;
252
253     for (;;) {
254         char* reply = get_input();
255         if (reply == NULL) {
256             // LCOV_EXCL_START
257             // Should be unreachable. Reply should never be NULL
258             free(reply);
259             exit(EXIT_SUCCESS);
260             // LCOV_EXCL_STOP
261         }
262         if (strlen(reply) == 0) {
263             free(reply);
264             rspeak(PLEASE_ANSWER);
265             continue;
266         }
267
268         char* firstword = (char*) xcalloc(strlen(reply) + 1);
269         sscanf(reply, "%s", firstword);
270
271         free(reply);
272
273         for (int i = 0; i < (int)strlen(firstword); ++i)
274             firstword[i] = tolower(firstword[i]);
275
276         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
277         int y = strncmp("y", firstword, sizeof("y") - 1);
278         int no = strncmp("no", firstword, sizeof("no") - 1);
279         int n = strncmp("n", firstword, sizeof("n") - 1);
280
281         free(firstword);
282
283         if (yes == 0 ||
284             y == 0) {
285             outcome = true;
286             break;
287         } else if (no == 0 ||
288                    n == 0) {
289             outcome = false;
290             break;
291         } else
292             rspeak(PLEASE_ANSWER);
293     }
294     return (outcome);
295 }
296
297
298 bool yes(const char* question, const char* yes_response, const char* no_response)
299 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
300  *  if no, print Z and return false. */
301 {
302     bool outcome = false;
303
304     for (;;) {
305         speak(question);
306
307         char* reply = get_input();
308         if (reply == NULL) {
309             // LCOV_EXCL_START
310             // Should be unreachable. Reply should never be NULL
311             free(reply);
312             exit(EXIT_SUCCESS);
313             // LCOV_EXCL_STOP
314         }
315
316         if (strlen(reply) == 0) {
317             free(reply);
318             rspeak(PLEASE_ANSWER);
319             continue;
320         }
321
322         char* firstword = (char*) xcalloc(strlen(reply) + 1);
323         sscanf(reply, "%s", firstword);
324
325         free(reply);
326
327         for (int i = 0; i < (int)strlen(firstword); ++i)
328             firstword[i] = tolower(firstword[i]);
329
330         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
331         int y = strncmp("y", firstword, sizeof("y") - 1);
332         int no = strncmp("no", firstword, sizeof("no") - 1);
333         int n = strncmp("n", firstword, sizeof("n") - 1);
334
335         free(firstword);
336
337         if (yes == 0 ||
338             y == 0) {
339             speak(yes_response);
340             outcome = true;
341             break;
342         } else if (no == 0 ||
343                    n == 0) {
344             speak(no_response);
345             outcome = false;
346             break;
347         } else
348             rspeak(PLEASE_ANSWER);
349
350     }
351
352     return (outcome);
353 }
354
355 /*  Data structure  routines */
356
357 static int get_motion_vocab_id(const char* word)
358 // Return the first motion number that has 'word' as one of its words.
359 {
360     for (int i = 0; i < NMOTIONS; ++i) {
361         for (int j = 0; j < motions[i].words.n; ++j) {
362             if (strncasecmp(word, motions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
363                     strchr(ignore, word[0]) == NULL ||
364                     !settings.oldstyle))
365                 return (i);
366         }
367     }
368     // If execution reaches here, we didn't find the word.
369     return (WORD_NOT_FOUND);
370 }
371
372 static int get_object_vocab_id(const char* word)
373 // Return the first object number that has 'word' as one of its words.
374 {
375     for (int i = 0; i < NOBJECTS + 1; ++i) { // FIXME: the + 1 should go when 1-indexing for objects is removed
376         for (int j = 0; j < objects[i].words.n; ++j) {
377             if (strncasecmp(word, objects[i].words.strs[j], TOKLEN) == 0)
378                 return (i);
379         }
380     }
381     // If execution reaches here, we didn't find the word.
382     return (WORD_NOT_FOUND);
383 }
384
385 static int get_action_vocab_id(const char* word)
386 // Return the first motion number that has 'word' as one of its words.
387 {
388     for (int i = 0; i < NACTIONS; ++i) {
389         for (int j = 0; j < actions[i].words.n; ++j) {
390             if (strncasecmp(word, actions[i].words.strs[j], TOKLEN) == 0 && (strlen(word) > 1 ||
391                     strchr(ignore, word[0]) == NULL ||
392                     !settings.oldstyle))
393                 return (i);
394         }
395     }
396     // If execution reaches here, we didn't find the word.
397     return (WORD_NOT_FOUND);
398 }
399
400 static bool is_valid_int(const char *str)
401 /* Returns true if the string passed in is represents a valid integer,
402  * that could then be parsed by atoi() */
403 {
404     // Handle negative number
405     if (*str == '-')
406         ++str;
407
408     // Handle empty string or just "-". Should never reach this
409     // point, because this is only used with transitive verbs.
410     if (!*str)
411         return false; // LCOV_EXCL_LINE
412
413     // Check for non-digit chars in the rest of the stirng.
414     while (*str) {
415         if (!isdigit(*str))
416             return false;
417         else
418             ++str;
419     }
420
421     return true;
422 }
423
424 static void get_vocab_metadata(const char* word, vocab_t* id, word_type_t* type)
425 {
426     /* Check for an empty string */
427     if (strncmp(word, "", sizeof("")) == 0) {
428         *id = WORD_EMPTY;
429         *type = NO_WORD_TYPE;
430         return;
431     }
432
433     vocab_t ref_num;
434
435     ref_num = get_motion_vocab_id(word);
436     if (ref_num != WORD_NOT_FOUND) {
437         *id = ref_num;
438         *type = MOTION;
439         return;
440     }
441
442     ref_num = get_object_vocab_id(word);
443     if (ref_num != WORD_NOT_FOUND) {
444         *id = ref_num;
445         *type = OBJECT;
446         return;
447     }
448
449     ref_num = get_action_vocab_id(word);
450     if (ref_num != WORD_NOT_FOUND) {
451         *id = ref_num;
452         *type = ACTION;
453         return;
454     }
455
456     // Check for the reservoir magic word.
457     if (strcasecmp(word, game.zzword) == 0) {
458         *id = PART;
459         *type = ACTION;
460         return;
461     }
462
463     // Check words that are actually numbers.
464     if (is_valid_int(word)) {
465         *id = WORD_EMPTY;
466         *type = NUMERIC;
467         return;
468     }
469
470     *id = WORD_NOT_FOUND;
471     *type = NO_WORD_TYPE;
472     return;
473 }
474
475 static void tokenize(char* raw, command_t *cmd)
476 {
477     /*
478      * Be caereful about modifing this. We do not want to nuke the
479      * the speech part or ID from the previous turn.
480      */
481     memset(&cmd->word[0].raw, '\0', sizeof(cmd->word[0].raw));
482     memset(&cmd->word[1].raw, '\0', sizeof(cmd->word[1].raw));
483
484     /* Bound prefix on the %s would be needed to prevent buffer
485      * overflow.  but we shortstop this more simply by making each
486      * raw-input buffer as long as the entire input buffer. */
487     sscanf(raw, "%s%s", cmd->word[0].raw, cmd->word[1].raw);
488
489     /* (ESR) In oldstyle mode, simulate the uppercasing and truncating
490      * effect on raw tokens of packing them into sixbit characters, 5
491      * to a 32-bit word.  This is something the FORTRAN version did
492      * becuse archaic FORTRAN had no string types.  Don Wood's
493      * mechanical translation of 2.5 to C retained the packing and
494      * thus this misfeature.
495      *
496      * It's philosophically questionable whether this is the right
497      * thing to do even in oldstyle mode.  On one hand, the text
498      * mangling was not authorial intent, but a result of limitations
499      * in their tools. On the other, not simulating this misbehavior
500      * goes against the goal of making oldstyle as accurate as
501      * possible an emulation of the original UI.
502      */
503     if (settings.oldstyle) {
504         cmd->word[0].raw[TOKLEN + TOKLEN] = cmd->word[1].raw[TOKLEN + TOKLEN] = '\0';
505         for (size_t i = 0; i < strlen(cmd->word[0].raw); i++)
506             cmd->word[0].raw[i] = toupper(cmd->word[0].raw[i]);
507         for (size_t i = 0; i < strlen(cmd->word[1].raw); i++)
508             cmd->word[1].raw[i] = toupper(cmd->word[1].raw[i]);
509     }
510
511     /* populate command with parsed vocabulary metadata */
512     get_vocab_metadata(cmd->word[0].raw, &(cmd->word[0].id), &(cmd->word[0].type));
513     get_vocab_metadata(cmd->word[1].raw, &(cmd->word[1].id), &(cmd->word[1].type));
514     cmd->state = TOKENIZED;
515 }
516
517 bool get_command_input(command_t *command)
518 /* Get user input on stdin, parse and map to command */
519 {
520     char inputbuf[LINESIZE];
521     char* input;
522
523     for (;;) {
524         input = get_input();
525         if (input == NULL)
526             return false;
527         if (word_count(input) > 2) {
528             rspeak(TWO_WORDS);
529             free(input);
530             continue;
531         }
532         if (strcmp(input, "") != 0)
533             break;
534         free(input);
535     }
536
537     strncpy(inputbuf, input, LINESIZE - 1);
538     free(input);
539
540     tokenize(inputbuf, command);
541
542 #ifdef GDEBUG
543     /* Needs to stay synced with enum word_type_t */
544     const char *types[] = {"NO_WORD_TYPE", "MOTION", "OBJECT", "ACTION", "NUMERIC"};
545     /* needs to stay synced with enum speechpart */
546     const char *roles[] = {"unknown", "intransitive", "transitive"};
547     printf("Command: role = %s type1 = %s, id1 = %ld, type2 = %s, id2 = %ld\n",
548            roles[command->part],
549            types[command->word[0].type],
550            command->word[0].id,
551            types[command->word[1].type],
552            command->word[1].id);
553 #endif
554
555     command->state = GIVEN;
556     return true;
557 }
558
559 void clear_command(command_t *cmd)
560 /* Resets the state of the command to empty */
561 {
562     cmd->verb = ACT_NULL;
563     cmd->part = unknown;
564     game.oldobj = cmd->obj;
565     cmd->obj = NO_OBJECT;
566     cmd->state = EMPTY;
567 }
568
569
570 void juggle(obj_t object)
571 /*  Juggle an object by picking it up and putting it down again, the purpose
572  *  being to get the object to the front of the chain of things at its loc. */
573 {
574     loc_t i, j;
575
576     i = game.place[object];
577     j = game.fixed[object];
578     move(object, i);
579     move(object + NOBJECTS, j);
580 }
581
582 void move(obj_t object, loc_t where)
583 /*  Place any object anywhere by picking it up and dropping it.  May
584  *  already be toting, in which case the carry is a no-op.  Mustn't
585  *  pick up objects which are not at any loc, since carry wants to
586  *  remove objects from game.atloc chains. */
587 {
588     loc_t from;
589
590     if (object > NOBJECTS)
591         from = game.fixed[object - NOBJECTS];
592     else
593         from = game.place[object];
594     /* (ESR) Used to check for !SPECIAL(from). I *think* that was wrong... */
595     if (from != LOC_NOWHERE && from != CARRIED)
596         carry(object, from);
597     drop(object, where);
598 }
599
600 loc_t put(obj_t object, loc_t where, long pval)
601 /*  put() is the same as move(), except it returns a value used to set up the
602  *  negated game.prop values for the repository objects. */
603 {
604     move(object, where);
605     return STASHED(pval);
606 }
607
608 void carry(obj_t object, loc_t where)
609 /*  Start toting an object, removing it from the list of things at its former
610  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
611  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
612 {
613     long temp;
614
615     if (object <= NOBJECTS) {
616         if (game.place[object] == CARRIED)
617             return;
618         game.place[object] = CARRIED;
619
620         if (object != BIRD)
621             ++game.holdng;
622     }
623     if (game.atloc[where] == object) {
624         game.atloc[where] = game.link[object];
625         return;
626     }
627     temp = game.atloc[where];
628     while (game.link[temp] != object) {
629         temp = game.link[temp];
630     }
631     game.link[temp] = game.link[object];
632 }
633
634 void drop(obj_t object, loc_t where)
635 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
636  *  game.holdng if the object was being toted. */
637 {
638     if (object > NOBJECTS)
639         game.fixed[object - NOBJECTS] = where;
640     else {
641         if (game.place[object] == CARRIED)
642             if (object != BIRD)
643                 /* The bird has to be weightless.  This ugly hack (and the
644                  * corresponding code in the drop function) brought to you
645                  * by the fact that when the bird is caged, we need to be able
646                  * to either 'take bird' or 'take cage' and have the right thing
647                  * happen.
648                  */
649                 --game.holdng;
650         game.place[object] = where;
651     }
652     if (where == LOC_NOWHERE ||
653         where == CARRIED)
654         return;
655     game.link[object] = game.atloc[where];
656     game.atloc[where] = object;
657 }
658
659 int atdwrf(loc_t where)
660 /*  Return the index of first dwarf at the given location, zero if no dwarf is
661  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
662  *  the pirate (6th dwarf). */
663 {
664     int at;
665
666     at = 0;
667     if (game.dflag < 2)
668         return at;
669     at = -1;
670     for (long i = 1; i <= NDWARVES - 1; i++) {
671         if (game.dloc[i] == where)
672             return i;
673         if (game.dloc[i] != 0)
674             at = 0;
675     }
676     return at;
677 }
678
679 /*  Utility routines (setbit, tstbit, set_seed, get_next_lcg_value,
680  *  randrange) */
681
682 long setbit(int bit)
683 /*  Returns 2**bit for use in constructing bit-masks. */
684 {
685     return (1L << bit);
686 }
687
688 bool tstbit(long mask, int bit)
689 /*  Returns true if the specified bit is set in the mask. */
690 {
691     return (mask & (1 << bit)) != 0;
692 }
693
694 void set_seed(int32_t seedval)
695 /* Set the LCG seed */
696 {
697     game.lcg_x = seedval % LCG_M;
698     if (game.lcg_x < 0) {
699         game.lcg_x = LCG_M + game.lcg_x;
700     }
701     // once seed is set, we need to generate the Z`ZZZ word
702     for (int i = 0; i < 5; ++i) {
703         game.zzword[i] = 'A' + randrange(26);
704     }
705     game.zzword[1] = '\''; // force second char to apostrophe
706     game.zzword[5] = '\0';
707 }
708
709 static int32_t get_next_lcg_value(void)
710 /* Return the LCG's current value, and then iterate it. */
711 {
712     int32_t old_x = game.lcg_x;
713     game.lcg_x = (LCG_A * game.lcg_x + LCG_C) % LCG_M;
714     return old_x;
715 }
716
717 int32_t randrange(int32_t range)
718 /* Return a random integer from [0, range). */
719 {
720     return range * get_next_lcg_value() / LCG_M;
721 }
722
723 // LCOV_EXCL_START
724 void bug(enum bugtype num, const char *error_string)
725 {
726     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
727     exit(EXIT_FAILURE);
728 }
729 // LCOV_EXCL_STOP
730
731 /* end */
732
733 void state_change(obj_t obj, int state)
734 /* Object must have a change-message list for this to be useful; only some do */
735 {
736     game.prop[obj] = state;
737     pspeak(obj, change, true, state);
738 }
739
740 /* end */