Test coverage: make LCOV ignore bug() and all calls to BUG()
[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                 printf("%s", input_prompt);
256             IGNORE(getline(&input, &n, stdin));
257         }
258
259         if (input == NULL) // Got EOF; return with it.
260             return(input);
261         else if (input[0] == '#') // Ignore comments.
262             continue;
263         else // We have a 'normal' line; leave the loop.
264             break;
265     }
266
267     // Strip trailing newlines from the input
268     input[strcspn(input, "\n")] = 0;
269
270     linenoiseHistoryAdd(input);
271
272     if (!isatty(0))
273         echo_input(stdout, input_prompt, input);
274
275     if (logfp)
276         echo_input(logfp, input_prompt, input);
277
278     return (input);
279 }
280
281 bool yes(const char* question, const char* yes_response, const char* no_response)
282 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
283  *  if no, print Z and return false. */
284 {
285     char* reply;
286     bool outcome;
287
288     for (;;) {
289         speak(question);
290
291         reply = get_input();
292         if (reply == NULL) {
293           linenoiseFree(reply);
294           exit(EXIT_SUCCESS);
295         }
296
297         char* firstword = (char*) xmalloc(strlen(reply)+1);
298         sscanf(reply, "%s", firstword);
299
300         for (int i = 0; i < (int)strlen(firstword); ++i)
301             firstword[i] = tolower(firstword[i]);
302
303         int yes = strncmp("yes", firstword, sizeof("yes") - 1);
304         int y = strncmp("y", firstword, sizeof("y") - 1);
305         int no = strncmp("no", firstword, sizeof("no") - 1);
306         int n = strncmp("n", firstword, sizeof("n") - 1);
307
308         free(firstword);
309
310         if (yes == 0 || y == 0) {
311             speak(yes_response);
312             outcome = true;
313             break;
314         } else if (no == 0 || n == 0) {
315             speak(no_response);
316             outcome = false;
317             break;
318         } else
319             rspeak(PLEASE_ANSWER);
320     }
321     linenoiseFree(reply);
322     return (outcome);
323 }
324
325 /*  Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT) */
326
327 long GETTXT(bool skip, bool onewrd, bool upper)
328 /*  Take characters from an input line and pack them into 30-bit words.
329  *  Skip says to skip leading blanks.  ONEWRD says stop if we come to a
330  *  blank.  UPPER says to map all letters to uppercase.  If we reach the
331  *  end of the line, the word is filled up with blanks (which encode as 0's).
332  *  If we're already at end of line when TEXT is called, we return -1. */
333 {
334     long text;
335     static long splitting = -1;
336
337     if (LNPOSN != splitting)
338         splitting = -1;
339     text = -1;
340     while (true) {
341         if (LNPOSN > LNLENG)
342             return (text);
343         if ((!skip) || INLINE[LNPOSN] != 0)
344             break;
345         ++LNPOSN;
346     }
347
348     text = 0;
349     for (int I = 1; I <= TOKLEN; I++) {
350         text = text * 64;
351         if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
352             continue;
353         char current = INLINE[LNPOSN];
354         if (current < ascii_to_advent['%']) {
355             splitting = -1;
356             if (upper && current >= ascii_to_advent['a'])
357                 current = current - 26;
358             text = text + current;
359             ++LNPOSN;
360             continue;
361         }
362         if (splitting != LNPOSN) {
363             text = text + ascii_to_advent['%'];
364             splitting = LNPOSN;
365             continue;
366         }
367
368         text = text + current - ascii_to_advent['%'];
369         splitting = -1;
370         ++LNPOSN;
371     }
372
373     return text;
374 }
375
376 token_t MAKEWD(long letters)
377 /*  Combine TOKLEN (currently 5) uppercase letters (represented by
378  *  pairs of decimal digits in lettrs) to form a 30-bit value matching
379  *  the one that GETTXT would return given those characters plus
380  *  trailing blanks.  Caution: lettrs will overflow 31 bits if
381  *  5-letter word starts with V-Z.  As a kludgey workaround, you can
382  *  increment a letter by 5 by adding 50 to the next pair of
383  *  digits. */
384 {
385     long i = 1, word = 0;
386
387     for (long k = letters; k != 0; k = k / 100) {
388         word = word + i * (MOD(k, 50) + 10);
389         i = i * 64;
390         if (MOD(k, 100) > 50)word = word + i * 5;
391     }
392     i = 64L * 64L * 64L * 64L * 64L / i;
393     word = word * i;
394     return word;
395 }
396
397 /*  Data structure  routines */
398
399 long vocab(long id, long init)
400 /*  Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
401  *  -1 if not found.  If INIT is positive, this is an initialisation call setting
402  *  up a keyword variable, and not finding it constitutes a bug.  It also means
403  *  that only KTAB values which taken over 1000 equal INIT may be considered.
404  *  (Thus "STEPS", which is a motion verb as well as an object, may be located
405  *  as an object.)  And it also means the KTAB value is taken modulo 1000. */
406 {
407     long lexeme;
408
409     for (long i = 1; i <= TABSIZ; i++) {
410         if (KTAB[i] == -1) {
411             lexeme = -1;
412             if (init < 0)
413                 return (lexeme);
414             BUG(REQUIRED_VOCABULARY_WORD_NOT_FOUND); // LCOV_EXCL_LINE
415         }
416         if (init >= 0 && KTAB[i] / 1000 != init)
417             continue;
418         if (ATAB[i] == id) {
419             lexeme = KTAB[i];
420             if (init >= 0)
421                 lexeme = MOD(lexeme, 1000);
422             return (lexeme);
423         }
424     }
425     BUG(RAN_OFF_END_OF_VOCABULARY_TABLE); // LCOV_EXCL_LINE
426 }
427
428 void juggle(long object)
429 /*  Juggle an object by picking it up and putting it down again, the purpose
430  *  being to get the object to the front of the chain of things at its loc. */
431 {
432     long i, j;
433
434     i = game.place[object];
435     j = game.fixed[object];
436     move(object, i);
437     move(object + NOBJECTS, j);
438 }
439
440 void move(long object, long where)
441 /*  Place any object anywhere by picking it up and dropping it.  May
442  *  already be toting, in which case the carry is a no-op.  Mustn't
443  *  pick up objects which are not at any loc, since carry wants to
444  *  remove objects from game.atloc chains. */
445 {
446     long from;
447
448     if (object > NOBJECTS)
449         from = game.fixed[object - NOBJECTS];
450     else
451         from = game.place[object];
452     if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
453         carry(object, from);
454     drop(object, where);
455 }
456
457 long put(long object, long where, long pval)
458 /*  PUT is the same as MOVE, except it returns a value used to set up the
459  *  negated game.prop values for the repository objects. */
460 {
461     move(object, where);
462     return (-1) - pval;;
463 }
464
465 void carry(long object, long where)
466 /*  Start toting an object, removing it from the list of things at its former
467  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
468  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
469 {
470     long temp;
471
472     if (object <= NOBJECTS) {
473         if (game.place[object] == CARRIED)
474             return;
475         game.place[object] = CARRIED;
476         ++game.holdng;
477     }
478     if (game.atloc[where] == object) {
479         game.atloc[where] = game.link[object];
480         return;
481     }
482     temp = game.atloc[where];
483     while (game.link[temp] != object) {
484         temp = game.link[temp];
485     }
486     game.link[temp] = game.link[object];
487 }
488
489 void drop(long object, long where)
490 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
491  *  game.holdng if the object was being toted. */
492 {
493     if (object > NOBJECTS)
494         game.fixed[object - NOBJECTS] = where;
495     else {
496         if (game.place[object] == CARRIED)
497             --game.holdng;
498         game.place[object] = where;
499     }
500     if (where <= 0)
501         return;
502     game.link[object] = game.atloc[where];
503     game.atloc[where] = object;
504 }
505
506 long atdwrf(long where)
507 /*  Return the index of first dwarf at the given location, zero if no dwarf is
508  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
509  *  the pirate (6th dwarf). */
510 {
511     long at;
512
513     at = 0;
514     if (game.dflag < 2)
515         return (at);
516     at = -1;
517     for (long i = 1; i <= NDWARVES - 1; i++) {
518         if (game.dloc[i] == where)
519             return i;
520         if (game.dloc[i] != 0)
521             at = 0;
522     }
523     return (at);
524 }
525
526 /*  Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
527  *  randrange, RNDVOC) */
528
529 long setbit(long bit)
530 /*  Returns 2**bit for use in constructing bit-masks. */
531 {
532     return (1 << bit);
533 }
534
535 bool tstbit(long mask, int bit)
536 /*  Returns true if the specified bit is set in the mask. */
537 {
538     return (mask & (1 << bit)) != 0;
539 }
540
541 void set_seed(long seedval)
542 /* Set the LCG seed */
543 {
544     game.lcg_x = (unsigned long) seedval % game.lcg_m;
545 }
546
547 unsigned long get_next_lcg_value(void)
548 /* Return the LCG's current value, and then iterate it. */
549 {
550     unsigned long old_x = game.lcg_x;
551     game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
552     return old_x;
553 }
554
555 long randrange(long range)
556 /* Return a random integer from [0, range). */
557 {
558     return range * get_next_lcg_value() / game.lcg_m;
559 }
560
561 long rndvoc(long second, long force)
562 /*  Searches the vocabulary ATAB for a word whose second character is
563  *  char, and changes that word such that each of the other four
564  *  characters is a random letter.  If force is non-zero, it is used
565  *  as the new word.  Returns the new word. */
566 {
567     long rnd = force;
568
569     if (rnd == 0) {
570         for (int i = 1; i <= 5; i++) {
571             long j = 11 + randrange(26);
572             if (i == 2)
573                 j = second;
574             rnd = rnd * 64 + j;
575         }
576     }
577
578     long div = 64L * 64L * 64L;
579     for (int i = 1; i <= TABSIZ; i++) {
580         if (MOD(ATAB[i] / div, 64L) == second) {
581             ATAB[i] = rnd;
582             break;
583         }
584     }
585
586     return rnd;
587 }
588
589
590 /*  Machine dependent routines (MAPLIN, SAVEIO) */
591
592 bool MAPLIN(FILE *fp)
593 {
594     bool eof;
595
596     /* Read a line of input, from the specified input source.
597      * This logic is complicated partly because it has to serve
598      * several cases with different requirements and partly because
599      * of a quirk in linenoise().
600      *
601      * The quirk shows up when you paste a test log from the clipboard
602      * to the program's command prompt.  While fgets (as expected)
603      * consumes it a line at a time, linenoise() returns the first
604      * line and discards the rest.  Thus, there needs to be an
605      * editline (-s) option to fall back to fgets while still
606      * prompting.  Note that linenoise does behave properly when
607      * fed redirected stdin.
608      *
609      * The logging is a bit of a mess because there are two distinct cases
610      * in which you want to echo commands.  One is when shipping them to
611      * a log under the -l option, in which case you want to suppress
612      * prompt generation (so test logs are unadorned command sequences).
613      * On the other hand, if you redirected stdin and are feeding the program
614      * a logfile, you *do* want prompt generation - it makes checkfiles
615      * easier to read when the commands are marked by a preceding prompt.
616      */
617     do {
618         if (!editline) {
619             if (prompt)
620                 fputs("> ", stdout);
621             IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
622             eof = (feof(fp));
623         } else {
624             char *cp = linenoise("> ");
625             eof = (cp == NULL);
626             if (!eof) {
627                 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
628                 linenoiseHistoryAdd(rawbuf);
629                 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
630                 linenoiseFree(cp);
631             }
632         }
633     } while
634     (!eof && rawbuf[0] == '#');
635     if (eof) {
636         if (logfp && fp == stdin)
637             fclose(logfp);
638         return false;
639     } else {
640         FILE *efp = NULL;
641         if (logfp && fp == stdin)
642             efp = logfp;
643         else if (!isatty(0))
644             efp = stdout;
645         if (efp != NULL) {
646             if (prompt && efp == stdout)
647                 fputs("> ", efp);
648             IGNORE(fputs(rawbuf, efp));
649         }
650         strcpy(INLINE + 1, rawbuf);
651         /*  translate the chars to integers in the range 0-126 and store
652          *  them in the common array "INLINE".  Integer values are as follows:
653          *     0   = space [ASCII CODE 40 octal, 32 decimal]
654          *    1-2  = !" [ASCII 41-42 octal, 33-34 decimal]
655          *    3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
656          *   11-36 = upper-case letters
657          *   37-62 = lower-case letters
658          *    63   = percent (%) [ASCII 45 octal, 37 decimal]
659          *   64-73 = digits, 0 through 9
660          *  Remaining characters can be translated any way that is convenient;
661          *  The above mappings are required so that certain special
662          *  characters are known to fit in 6 bits and/or can be easily spotted.
663          *  Array elements beyond the end of the line should be filled with 0,
664          *  and LNLENG should be set to the index of the last character.
665          *
666          *  If the data file uses a character other than space (e.g., tab) to
667          *  separate numbers, that character should also translate to 0.
668          *
669          *  This procedure may use the map1,map2 arrays to maintain
670          *  static data for he mapping.  MAP2(1) is set to 0 when the
671          *  program starts and is not changed thereafter unless the
672          *  routines in this module choose to do so. */
673         LNLENG = 0;
674         for (long i = 1; i <= (long)sizeof(INLINE) && INLINE[i] != 0; i++) {
675             long val = INLINE[i];
676             INLINE[i] = ascii_to_advent[val];
677             if (INLINE[i] != 0)
678                 LNLENG = i;
679         }
680         LNPOSN = 1;
681         return true;
682     }
683 }
684
685 void datime(long* d, long* t)
686 {
687     struct timeval tv;
688     gettimeofday(&tv, NULL);
689     *d = (long) tv.tv_sec;
690     *t = (long) tv.tv_usec;
691 }
692
693 // LCOV_EXCL_START
694 void bug(enum bugtype num, const char *error_string)
695 {
696     fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);
697     exit(EXIT_FAILURE);
698 }
699 // LCOV_EXCL_STOP
700
701 /* end */