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