Test coverage: make LCOV ignore code unreachable without interactive shell
[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
9 #include "advent.h"
10 #include "database.h"
11 #include "linenoise/linenoise.h"
12 #include "newdb.h"
13
14 void* xmalloc(size_t size)
15 {
16     void* ptr = malloc(size);
17     if (ptr == NULL) {
18         // LCOV_EXCL_START
19         // exclude from coverage analysis because we can't simulate an out of memory error in testing
20         fprintf(stderr, "Out of memory!\n");
21         exit(EXIT_FAILURE);
22         // LCOV_EXCL_STOP 
23     }
24     return (ptr);
25 }
26
27 void packed_to_token(long packed, char token[6])
28 {
29     // Unpack and map back to ASCII.
30     for (int i = 0; i < 5; ++i) {
31         char advent = (packed >> i * 6) & 63;
32         token[4 - i] = advent_to_ascii[(int) advent];
33     }
34
35     // Ensure the last character is \0.
36     token[5] = '\0';
37
38     // Replace trailing whitespace with \0.
39     for (int i = 4; i >= 0; --i) {
40         if (token[i] == ' ' || token[i] == '\t')
41             token[i] = '\0';
42         else
43             break;
44     }
45 }
46
47 /* Hide the fact that wods are corrently packed longs */
48
49 bool wordeq(token_t a, token_t b)
50 {
51     return a == b;
52 }
53
54 bool wordempty(token_t a)
55 {
56     return a == 0;
57 }
58
59 void wordclear(token_t *v)
60 {
61     *v = 0;
62 }
63
64 /*  I/O routines (speak, pspeak, rspeak, GETIN, YES) */
65
66 void vspeak(const char* msg, va_list ap)
67 {
68     // Do nothing if we got a null pointer.
69     if (msg == NULL)
70         return;
71
72     // Do nothing if we got an empty string.
73     if (strlen(msg) == 0)
74         return;
75
76     // Print a newline if the global game.blklin says to.
77     if (game.blklin == true)
78         printf("\n");
79
80     int msglen = strlen(msg);
81
82     // Rendered string
83     ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
84     char* rendered = xmalloc(size);
85     char* renderp = rendered;
86
87     // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
88     long previous_arg = 0;
89     for (int i = 0; i < msglen; i++) {
90         if (msg[i] != '%') {
91             *renderp++ = msg[i];
92             size--;
93         } else {
94             long arg = va_arg(ap, long);
95             if (arg == -1)
96               arg = 0;
97             i++;
98             // Integer specifier. In order to accommodate the fact that PARMS can have both legitimate integers *and* packed tokens, stringify everything. Future work may eliminate the need for this.
99             if (msg[i] == 'd') {
100                 int ret = snprintf(renderp, size, "%ld", arg);
101                 if (ret < size) {
102                     renderp += ret;
103                     size -= ret;
104                 }
105             }
106
107             // Unmodified string specifier.
108             if (msg[i] == 's') {
109                 packed_to_token(arg, renderp); /* unpack directly to destination */
110                 size_t len = strlen(renderp);
111                 renderp += len;
112                 size -= len;
113             }
114
115             // Singular/plural specifier.
116             if (msg[i] == 'S') {
117                 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
118                     *renderp++ = 's';
119                     size--;
120                 }
121             }
122
123             // All-lowercase specifier.
124             if (msg[i] == 'L' || msg[i] == 'C') {
125                 packed_to_token(arg, renderp); /* unpack directly to destination */
126                 int len = strlen(renderp);
127                 for (int j = 0; j < len; ++j) {
128                     renderp[j] = tolower(renderp[j]);
129                 }
130                 if (msg[i] == 'C') // First char uppercase, rest lowercase.
131                     renderp[0] = toupper(renderp[0]);
132                 renderp += len;
133                 size -= len;
134             }
135
136             previous_arg = arg;
137         }
138     }
139     *renderp = 0;
140
141     // Print the message.
142     printf("%s\n", rendered);
143
144     free(rendered);
145 }
146
147 void speak(const char* msg, ...)
148 {
149     va_list ap;
150     va_start(ap, msg);
151     vspeak(msg, ap);
152     va_end(ap);
153 }
154
155 void pspeak(vocab_t msg, enum speaktype mode, int skip, ...)
156 /* Find the skip+1st message from msg and print it.  Modes are:
157  * feel = for inventory, what you can touch
158  * look = the long description for the state the object is in
159  * listen = the sound for the state the object is in
160  * study = text on the object. */
161 {
162     va_list ap;
163     va_start(ap, skip);
164     switch (mode) {
165     case touch:
166         vspeak(objects[msg].inventory, ap);
167         break;
168     case look: 
169         vspeak(objects[msg].longs[skip], ap);
170         break;
171     case hear:
172         vspeak(objects[msg].sounds[skip], ap);
173         break;
174     case study:
175         vspeak(objects[msg].texts[skip], ap);
176         break;
177     }
178     va_end(ap);
179 }
180
181 void rspeak(vocab_t i, ...)
182 /* Print the i-th "random" message (section 6 of database). */
183 {
184     va_list ap;
185     va_start(ap, i);
186     vspeak(arbitrary_messages[i], ap);
187     va_end(ap);
188 }
189
190 bool GETIN(FILE *input,
191            long *pword1, long *pword1x,
192            long *pword2, long *pword2x)
193 /*  Get a command from the adventurer.  Snarf out the first word, pad it with
194  *  blanks, and return it in WORD1.  Chars 6 thru 10 are returned in WORD1X, in
195  *  case we need to print out the whole word in an error message.  Any number of
196  *  blanks may follow the word.  If a second word appears, it is returned in
197  *  WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
198 {
199     long junk;
200
201     for (;;) {
202         if (game.blklin)
203             fputc('\n', stdout);;
204         if (!MAPLIN(input))
205             return false;
206         *pword1 = GETTXT(true, true, true);
207         if (game.blklin && *pword1 < 0)
208             continue;
209         *pword1x = GETTXT(false, true, true);
210         do {
211             junk = GETTXT(false, true, true);
212         } while
213         (junk > 0);
214         *pword2 = GETTXT(true, true, true);
215         *pword2x = GETTXT(false, true, true);
216         do {
217             junk = GETTXT(false, true, true);
218         } while
219         (junk > 0);
220         if (GETTXT(true, true, true) <= 0)
221             return true;
222         rspeak(TWO_WORDS);
223     }
224 }
225
226 void echo_input(FILE* destination, char* input_prompt, char* input)
227 {
228     size_t len = strlen(input_prompt) + strlen(input) + 1;
229     char* prompt_and_input = (char*) xmalloc(len);
230     strcpy(prompt_and_input, input_prompt);
231     strcat(prompt_and_input, input);
232     fprintf(destination, "%s\n", prompt_and_input);
233     free(prompt_and_input);
234 }
235
236 char* get_input()
237 {
238     // Set up the prompt
239     char input_prompt[] = "> ";
240     if (!prompt)
241         input_prompt[0] = '\0';
242
243     // Print a blank line if game.blklin tells us to.
244     if (game.blklin == true)
245         printf("\n");
246
247     char* input;
248     while (true) {
249         if (editline)
250             input = linenoise(input_prompt);
251         else {
252             input = NULL;
253             size_t n = 0;
254             if (isatty(0))
255             // LCOV_EXCL_START
256             // Should be unreachable in tests, as they will use a non-interactive shell.
257                 printf("%s", input_prompt);
258             // LCOV_EXCL_STOP 
259             IGNORE(getline(&input, &n, stdin));
260         }
261
262         if (input == NULL) // Got EOF; return with it.
263             return(input);
264         else if (input[0] == '#') // Ignore comments.
265             continue;
266         else // We have a 'normal' line; leave the loop.
267             break;
268     }
269
270     // Strip trailing newlines from the input
271     input[strcspn(input, "\n")] = 0;
272
273     linenoiseHistoryAdd(input);
274
275     if (!isatty(0))
276         echo_input(stdout, input_prompt, input);
277
278     if (logfp)
279         echo_input(logfp, input_prompt, input);
280
281     return (input);
282 }
283
284 bool yes(const char* question, const char* yes_response, const char* no_response)
285 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
286  *  if no, print Z and return false. */
287 {
288     char* reply;
289     bool outcome;
290
291     for (;;) {
292         speak(question);
293
294         reply = get_input();
295         if (reply == NULL) {
296             // LCOV_EXCL_START
297             // Should be unreachable. Reply should never be NULL
298             linenoiseFree(reply);
299             exit(EXIT_SUCCESS);
300             // LCOV_EXCL_STOP 
301         }
302
303         char* firstword = (char*) xmalloc(strlen(reply)+1);
304         sscanf(reply, "%s", firstword);
305
306         for (int i = 0; i < (int)strlen(firstword); ++i)
307             firstword[i] = tolower(firstword[i]);
308
309         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
310         int y = strncmp("y", firstword, sizeof("y") - 1);
311         int no = strncmp("no", firstword, sizeof("no") - 1);
312         int n = strncmp("n", firstword, sizeof("n") - 1);
313
314         free(firstword);
315
316         if (yes == 0 || y == 0) {
317             speak(yes_response);
318             outcome = true;
319             break;
320         } else if (no == 0 || n == 0) {
321             speak(no_response);
322             outcome = false;
323             break;
324         } else
325             rspeak(PLEASE_ANSWER);
326     }
327     linenoiseFree(reply);
328     return (outcome);
329 }
330
331 /*  Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT) */
332
333 long GETTXT(bool skip, bool onewrd, bool upper)
334 /*  Take characters from an input line and pack them into 30-bit words.
335  *  Skip says to skip leading blanks.  ONEWRD says stop if we come to a
336  *  blank.  UPPER says to map all letters to uppercase.  If we reach the
337  *  end of the line, the word is filled up with blanks (which encode as 0's).
338  *  If we're already at end of line when TEXT is called, we return -1. */
339 {
340     long text;
341     static long splitting = -1;
342
343     if (LNPOSN != splitting)
344         splitting = -1;
345     text = -1;
346     while (true) {
347         if (LNPOSN > LNLENG)
348             return (text);
349         if ((!skip) || INLINE[LNPOSN] != 0)
350             break;
351         ++LNPOSN;
352     }
353
354     text = 0;
355     for (int I = 1; I <= TOKLEN; I++) {
356         text = text * 64;
357         if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
358             continue;
359         char current = INLINE[LNPOSN];
360         if (current < ascii_to_advent['%']) {
361             splitting = -1;
362             if (upper && current >= ascii_to_advent['a'])
363                 current = current - 26;
364             text = text + current;
365             ++LNPOSN;
366             continue;
367         }
368         if (splitting != LNPOSN) {
369             text = text + ascii_to_advent['%'];
370             splitting = LNPOSN;
371             continue;
372         }
373
374         text = text + current - ascii_to_advent['%'];
375         splitting = -1;
376         ++LNPOSN;
377     }
378
379     return text;
380 }
381
382 token_t MAKEWD(long letters)
383 /*  Combine TOKLEN (currently 5) uppercase letters (represented by
384  *  pairs of decimal digits in lettrs) to form a 30-bit value matching
385  *  the one that GETTXT would return given those characters plus
386  *  trailing blanks.  Caution: lettrs will overflow 31 bits if
387  *  5-letter word starts with V-Z.  As a kludgey workaround, you can
388  *  increment a letter by 5 by adding 50 to the next pair of
389  *  digits. */
390 {
391     long i = 1, word = 0;
392
393     for (long k = letters; k != 0; k = k / 100) {
394         word = word + i * (MOD(k, 50) + 10);
395         i = i * 64;
396         if (MOD(k, 100) > 50)word = word + i * 5;
397     }
398     i = 64L * 64L * 64L * 64L * 64L / i;
399     word = word * i;
400     return word;
401 }
402
403 /*  Data structure  routines */
404
405 long vocab(long id, long init)
406 /*  Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
407  *  -1 if not found.  If INIT is positive, this is an initialisation call setting
408  *  up a keyword variable, and not finding it constitutes a bug.  It also means
409  *  that only KTAB values which taken over 1000 equal INIT may be considered.
410  *  (Thus "STEPS", which is a motion verb as well as an object, may be located
411  *  as an object.)  And it also means the KTAB value is taken modulo 1000. */
412 {
413     long lexeme;
414
415     for (long i = 1; i <= TABSIZ; i++) {
416         if (KTAB[i] == -1) {
417             lexeme = -1;
418             if (init < 0)
419                 return (lexeme);
420             BUG(REQUIRED_VOCABULARY_WORD_NOT_FOUND); // LCOV_EXCL_LINE
421         }
422         if (init >= 0 && KTAB[i] / 1000 != init)
423             continue;
424         if (ATAB[i] == id) {
425             lexeme = KTAB[i];
426             if (init >= 0)
427                 lexeme = MOD(lexeme, 1000);
428             return (lexeme);
429         }
430     }
431     BUG(RAN_OFF_END_OF_VOCABULARY_TABLE); // LCOV_EXCL_LINE
432 }
433
434 void juggle(long object)
435 /*  Juggle an object by picking it up and putting it down again, the purpose
436  *  being to get the object to the front of the chain of things at its loc. */
437 {
438     long i, j;
439
440     i = game.place[object];
441     j = game.fixed[object];
442     move(object, i);
443     move(object + NOBJECTS, j);
444 }
445
446 void move(long object, long where)
447 /*  Place any object anywhere by picking it up and dropping it.  May
448  *  already be toting, in which case the carry is a no-op.  Mustn't
449  *  pick up objects which are not at any loc, since carry wants to
450  *  remove objects from game.atloc chains. */
451 {
452     long from;
453
454     if (object > NOBJECTS)
455         from = game.fixed[object - NOBJECTS];
456     else
457         from = game.place[object];
458     if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
459         carry(object, from);
460     drop(object, where);
461 }
462
463 long put(long object, long where, long pval)
464 /*  PUT is the same as MOVE, except it returns a value used to set up the
465  *  negated game.prop values for the repository objects. */
466 {
467     move(object, where);
468     return (-1) - pval;;
469 }
470
471 void carry(long object, long where)
472 /*  Start toting an object, removing it from the list of things at its former
473  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
474  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
475 {
476     long temp;
477
478     if (object <= NOBJECTS) {
479         if (game.place[object] == CARRIED)
480             return;
481         game.place[object] = CARRIED;
482         ++game.holdng;
483     }
484     if (game.atloc[where] == object) {
485         game.atloc[where] = game.link[object];
486         return;
487     }
488     temp = game.atloc[where];
489     while (game.link[temp] != object) {
490         temp = game.link[temp];
491     }
492     game.link[temp] = game.link[object];
493 }
494
495 void drop(long object, long where)
496 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
497  *  game.holdng if the object was being toted. */
498 {
499     if (object > NOBJECTS)
500         game.fixed[object - NOBJECTS] = where;
501     else {
502         if (game.place[object] == CARRIED)
503             --game.holdng;
504         game.place[object] = where;
505     }
506     if (where <= 0)
507         return;
508     game.link[object] = game.atloc[where];
509     game.atloc[where] = object;
510 }
511
512 long atdwrf(long where)
513 /*  Return the index of first dwarf at the given location, zero if no dwarf is
514  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
515  *  the pirate (6th dwarf). */
516 {
517     long at;
518
519     at = 0;
520     if (game.dflag < 2)
521         return (at);
522     at = -1;
523     for (long i = 1; i <= NDWARVES - 1; i++) {
524         if (game.dloc[i] == where)
525             return i;
526         if (game.dloc[i] != 0)
527             at = 0;
528     }
529     return (at);
530 }
531
532 /*  Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
533  *  randrange, RNDVOC) */
534
535 long setbit(long bit)
536 /*  Returns 2**bit for use in constructing bit-masks. */
537 {
538     return (1 << bit);
539 }
540
541 bool tstbit(long mask, int bit)
542 /*  Returns true if the specified bit is set in the mask. */
543 {
544     return (mask & (1 << bit)) != 0;
545 }
546
547 void set_seed(long seedval)
548 /* Set the LCG seed */
549 {
550     game.lcg_x = (unsigned long) seedval % game.lcg_m;
551 }
552
553 unsigned long get_next_lcg_value(void)
554 /* Return the LCG's current value, and then iterate it. */
555 {
556     unsigned long old_x = game.lcg_x;
557     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
558     return old_x;
559 }
560
561 long randrange(long range)
562 /* Return a random integer from [0, range). */
563 {
564     return range * get_next_lcg_value() / game.lcg_m;
565 }
566
567 long rndvoc(long second, long force)
568 /*  Searches the vocabulary ATAB for a word whose second character is
569  *  char, and changes that word such that each of the other four
570  *  characters is a random letter.  If force is non-zero, it is used
571  *  as the new word.  Returns the new word. */
572 {
573     long rnd = force;
574
575     if (rnd == 0) {
576         for (int i = 1; i <= 5; i++) {
577             long j = 11 + randrange(26);
578             if (i == 2)
579                 j = second;
580             rnd = rnd * 64 + j;
581         }
582     }
583
584     long div = 64L * 64L * 64L;
585     for (int i = 1; i <= TABSIZ; i++) {
586         if (MOD(ATAB[i] / div, 64L) == second) {
587             ATAB[i] = rnd;
588             break;
589         }
590     }
591
592     return rnd;
593 }
594
595
596 /*  Machine dependent routines (MAPLIN, SAVEIO) */
597
598 bool MAPLIN(FILE *fp)
599 {
600     bool eof;
601
602     /* Read a line of input, from the specified input source.
603      * This logic is complicated partly because it has to serve
604      * several cases with different requirements and partly because
605      * of a quirk in linenoise().
606      *
607      * The quirk shows up when you paste a test log from the clipboard
608      * to the program's command prompt.  While fgets (as expected)
609      * consumes it a line at a time, linenoise() returns the first
610      * line and discards the rest.  Thus, there needs to be an
611      * editline (-s) option to fall back to fgets while still
612      * prompting.  Note that linenoise does behave properly when
613      * fed redirected stdin.
614      *
615      * The logging is a bit of a mess because there are two distinct cases
616      * in which you want to echo commands.  One is when shipping them to
617      * a log under the -l option, in which case you want to suppress
618      * prompt generation (so test logs are unadorned command sequences).
619      * On the other hand, if you redirected stdin and are feeding the program
620      * a logfile, you *do* want prompt generation - it makes checkfiles
621      * easier to read when the commands are marked by a preceding prompt.
622      */
623     do {
624         if (!editline) {
625             if (prompt)
626                 fputs("> ", stdout);
627             IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
628             eof = (feof(fp));
629         } else {
630             char *cp = linenoise("> ");
631             eof = (cp == NULL);
632             if (!eof) {
633                 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
634                 linenoiseHistoryAdd(rawbuf);
635                 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
636                 linenoiseFree(cp);
637             }
638         }
639     } while
640     (!eof && rawbuf[0] == '#');
641     if (eof) {
642         if (logfp && fp == stdin)
643             fclose(logfp);
644         return false;
645     } else {
646         FILE *efp = NULL;
647         if (logfp && fp == stdin)
648             efp = logfp;
649         else if (!isatty(0))
650             efp = stdout;
651         if (efp != NULL) {
652             if (prompt && efp == stdout)
653                 fputs("> ", efp);
654             IGNORE(fputs(rawbuf, efp));
655         }
656         strcpy(INLINE + 1, rawbuf);
657         /*  translate the chars to integers in the range 0-126 and store
658          *  them in the common array "INLINE".  Integer values are as follows:
659          *     0   = space [ASCII CODE 40 octal, 32 decimal]
660          *    1-2  = !" [ASCII 41-42 octal, 33-34 decimal]
661          *    3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
662          *   11-36 = upper-case letters
663          *   37-62 = lower-case letters
664          *    63   = percent (%) [ASCII 45 octal, 37 decimal]
665          *   64-73 = digits, 0 through 9
666          *  Remaining characters can be translated any way that is convenient;
667          *  The above mappings are required so that certain special
668          *  characters are known to fit in 6 bits and/or can be easily spotted.
669          *  Array elements beyond the end of the line should be filled with 0,
670          *  and LNLENG should be set to the index of the last character.
671          *
672          *  If the data file uses a character other than space (e.g., tab) to
673          *  separate numbers, that character should also translate to 0.
674          *
675          *  This procedure may use the map1,map2 arrays to maintain
676          *  static data for he mapping.  MAP2(1) is set to 0 when the
677          *  program starts and is not changed thereafter unless the
678          *  routines in this module choose to do so. */
679         LNLENG = 0;
680         for (long i = 1; i <= (long)sizeof(INLINE) && INLINE[i] != 0; i++) {
681             long val = INLINE[i];
682             INLINE[i] = ascii_to_advent[val];
683             if (INLINE[i] != 0)
684                 LNLENG = i;
685         }
686         LNPOSN = 1;
687         return true;
688     }
689 }
690
691 void datime(long* d, long* t)
692 {
693     struct timeval tv;
694     gettimeofday(&tv, NULL);
695     *d = (long) tv.tv_sec;
696     *t = (long) tv.tv_usec;
697 }
698
699 // LCOV_EXCL_START
700 void bug(enum bugtype num, const char *error_string)
701 {
702     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
703     exit(EXIT_FAILURE);
704 }
705 // LCOV_EXCL_STOP
706
707 /* end */