10 #include "linenoise/linenoise.h"
13 char* xstrdup(const char* s)
15 char* ptr = strdup(s);
18 // exclude from coverage analysis because we can't simulate an out of memory error in testing
19 fprintf(stderr, "Out of memory!\n");
25 void* xmalloc(size_t size)
27 void* ptr = malloc(size);
30 // exclude from coverage analysis because we can't simulate an out of memory error in testing
31 fprintf(stderr, "Out of memory!\n");
38 void packed_to_token(long packed, char token[6])
40 // Unpack and map back to ASCII.
41 for (int i = 0; i < 5; ++i) {
42 char advent = (packed >> i * 6) & 63;
43 token[i] = new_advent_to_ascii[(int) advent];
46 // Ensure the last character is \0.
49 // Replace trailing whitespace with \0.
50 for (int i = 4; i >= 0; --i) {
51 if (token[i] == ' ' || token[i] == '\t')
58 long token_to_packed(const char token[6])
60 size_t t_len = strlen(token);
62 for (size_t i = 0; i < t_len; ++i)
64 char mapped = new_ascii_to_advent[(int) token[i]];
65 packed |= (mapped << (6 * i));
70 void tokenize(char* raw, long tokens[4])
72 // set each token to 0
73 for (int i = 0; i < 4; ++i)
76 // grab the first two words
78 words[0] = (char*) xmalloc(strlen(raw));
79 words[1] = (char*) xmalloc(strlen(raw));
80 int word_count = sscanf(raw, "%s%s", words[0], words[1]);
82 // make space for substrings and zero it out
83 char chunk_data[][6] = {
90 // break the words into up to 4 5-char substrings
91 sscanf(words[0], "%5s%5s", chunk_data[0], chunk_data[1]);
93 sscanf(words[1], "%5s%5s", chunk_data[2], chunk_data[3]);
97 // uppercase all the substrings
98 for (int i = 0; i < 4; ++i)
99 for (unsigned int j = 0; j < strlen(chunk_data[i]); ++j)
100 chunk_data[i][j] = (char) toupper(chunk_data[i][j]);
102 // pack the substrings
103 for (int i = 0; i < 4; ++i)
104 tokens[i] = token_to_packed(chunk_data[i]);
107 /* Hide the fact that wods are corrently packed longs */
109 bool wordeq(token_t a, token_t b)
114 bool wordempty(token_t a)
119 void wordclear(token_t *v)
124 /* I/O routines (speak, pspeak, rspeak, GETIN, YES) */
126 void vspeak(const char* msg, va_list ap)
128 // Do nothing if we got a null pointer.
132 // Do nothing if we got an empty string.
133 if (strlen(msg) == 0)
136 // Print a newline if the global game.blklin says to.
137 if (game.blklin == true)
140 int msglen = strlen(msg);
143 ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
144 char* rendered = xmalloc(size);
145 char* renderp = rendered;
147 // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
148 long previous_arg = 0;
149 for (int i = 0; i < msglen; i++) {
154 long arg = va_arg(ap, long);
158 // 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.
160 int ret = snprintf(renderp, size, "%ld", arg);
167 // Unmodified string specifier.
169 packed_to_token(arg, renderp); /* unpack directly to destination */
170 size_t len = strlen(renderp);
175 // Singular/plural specifier.
177 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
183 // All-lowercase specifier.
184 if (msg[i] == 'L' || msg[i] == 'C') {
185 packed_to_token(arg, renderp); /* unpack directly to destination */
186 int len = strlen(renderp);
187 for (int j = 0; j < len; ++j) {
188 renderp[j] = tolower(renderp[j]);
190 if (msg[i] == 'C') // First char uppercase, rest lowercase.
191 renderp[0] = toupper(renderp[0]);
201 // Print the message.
202 printf("%s\n", rendered);
207 void speak(const char* msg, ...)
215 void pspeak(vocab_t msg, enum speaktype mode, int skip, ...)
216 /* Find the skip+1st message from msg and print it. Modes are:
217 * feel = for inventory, what you can touch
218 * look = the long description for the state the object is in
219 * listen = the sound for the state the object is in
220 * study = text on the object. */
226 vspeak(objects[msg].inventory, ap);
229 vspeak(objects[msg].descriptions[skip], ap);
232 vspeak(objects[msg].sounds[skip], ap);
235 vspeak(objects[msg].texts[skip], ap);
238 vspeak(objects[msg].changes[skip], ap);
244 void rspeak(vocab_t i, ...)
245 /* Print the i-th "random" message (section 6 of database). */
249 vspeak(arbitrary_messages[i], ap);
253 void echo_input(FILE* destination, char* input_prompt, char* input)
255 size_t len = strlen(input_prompt) + strlen(input) + 1;
256 char* prompt_and_input = (char*) xmalloc(len);
257 strcpy(prompt_and_input, input_prompt);
258 strcat(prompt_and_input, input);
259 fprintf(destination, "%s\n", prompt_and_input);
260 free(prompt_and_input);
263 int word_count(char* s)
265 char* copy = xstrdup(s);
266 char delims[] = " \t";
270 word = strtok(copy, delims);
273 word = strtok(NULL, delims);
283 char input_prompt[] = "> ";
285 input_prompt[0] = '\0';
287 // Print a blank line if game.blklin tells us to.
288 if (game.blklin == true)
294 input = linenoise(input_prompt);
300 // Should be unreachable in tests, as they will use a non-interactive shell.
301 printf("%s", input_prompt);
303 ssize_t numread = getline(&input, &n, stdin);
304 if (numread == -1) // Got EOF; return with it.
308 if (input == NULL) // Got EOF; return with it.
310 else if (input[0] == '#') // Ignore comments.
312 else // We have a 'normal' line; leave the loop.
316 // Strip trailing newlines from the input
317 input[strcspn(input, "\n")] = 0;
319 linenoiseHistoryAdd(input);
322 echo_input(stdout, input_prompt, input);
325 echo_input(logfp, input_prompt, input);
339 // Should be unreachable. Reply should never be NULL
340 linenoiseFree(reply);
345 char* firstword = (char*) xmalloc(strlen(reply)+1);
346 sscanf(reply, "%s", firstword);
348 for (int i = 0; i < (int)strlen(firstword); ++i)
349 firstword[i] = tolower(firstword[i]);
351 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
352 int y = strncmp("y", firstword, sizeof("y") - 1);
353 int no = strncmp("no", firstword, sizeof("no") - 1);
354 int n = strncmp("n", firstword, sizeof("n") - 1);
358 if (yes == 0 || y == 0) {
361 } else if (no == 0 || n == 0) {
365 rspeak(PLEASE_ANSWER);
367 linenoiseFree(reply);
372 bool yes(const char* question, const char* yes_response, const char* no_response)
373 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
374 * if no, print Z and return false. */
385 // Should be unreachable. Reply should never be NULL
386 linenoiseFree(reply);
391 char* firstword = (char*) xmalloc(strlen(reply)+1);
392 sscanf(reply, "%s", firstword);
394 for (int i = 0; i < (int)strlen(firstword); ++i)
395 firstword[i] = tolower(firstword[i]);
397 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
398 int y = strncmp("y", firstword, sizeof("y") - 1);
399 int no = strncmp("no", firstword, sizeof("no") - 1);
400 int n = strncmp("n", firstword, sizeof("n") - 1);
404 if (yes == 0 || y == 0) {
408 } else if (no == 0 || n == 0) {
413 rspeak(PLEASE_ANSWER);
415 linenoiseFree(reply);
419 /* Data structure routines */
421 int get_motion_vocab_id(const char* word)
422 // Return the first motion number that has 'word' as one of its words.
424 for (int i = 0; i < NMOTIONS; ++i)
426 for (int j = 0; j < motions[i].words.n; ++j)
428 if (strcasecmp(word, motions[i].words.strs[j]) == 0)
432 // If execution reaches here, we didn't find the word.
433 return(WORD_NOT_FOUND);
436 int get_object_vocab_id(const char* word)
437 // Return the first object number that has 'word' as one of its words.
439 for (int i = 0; i < NOBJECTS + 1; ++i) // FIXME: the + 1 should go when 1-indexing for objects is removed
441 for (int j = 0; j < objects[i].words.n; ++j)
443 if (strcasecmp(word, objects[i].words.strs[j]) == 0)
447 // If execution reaches here, we didn't find the word.
448 return(WORD_NOT_FOUND);
451 int get_action_vocab_id(const char* word)
452 // Return the first motion number that has 'word' as one of its words.
454 for (int i = 0; i < NACTIONS; ++i)
456 for (int j = 0; j < actions[i].words.n; ++j)
458 if (strcasecmp(word, actions[i].words.strs[j]) == 0)
462 // If execution reaches here, we didn't find the word.
463 return(WORD_NOT_FOUND);
466 int get_special_vocab_id(const char* word)
467 // Return the first special number that has 'word' as one of its words.
469 for (int i = 0; i < NSPECIALS; ++i)
471 for (int j = 0; j < specials[i].words.n; ++j)
473 if (strcasecmp(word, specials[i].words.strs[j]) == 0)
477 // If execution reaches here, we didn't find the word.
478 return(WORD_NOT_FOUND);
481 long get_vocab_id(const char* word)
482 // Search the vocab categories in order for the supplied word.
486 ref_num = get_motion_vocab_id(word);
487 if (ref_num != WORD_NOT_FOUND)
488 return(ref_num + 0); // FIXME: replace with a proper hash
490 ref_num = get_object_vocab_id(word);
491 if (ref_num != WORD_NOT_FOUND)
492 return(ref_num + 1000); // FIXME: replace with a proper hash
494 ref_num = get_action_vocab_id(word);
495 if (ref_num != WORD_NOT_FOUND)
496 return(ref_num + 2000); // FIXME: replace with a proper hash
498 ref_num = get_special_vocab_id(word);
499 if (ref_num != WORD_NOT_FOUND)
500 return(ref_num + 3000); // FIXME: replace with a proper hash
502 // Check for the reservoir magic word.
503 if (strcasecmp(word, game.zzword) == 0)
504 return(PART + 2000); // FIXME: replace with a proper hash
506 return(WORD_NOT_FOUND);
509 void juggle(long object)
510 /* Juggle an object by picking it up and putting it down again, the purpose
511 * being to get the object to the front of the chain of things at its loc. */
515 i = game.place[object];
516 j = game.fixed[object];
518 move(object + NOBJECTS, j);
521 void move(long object, long where)
522 /* Place any object anywhere by picking it up and dropping it. May
523 * already be toting, in which case the carry is a no-op. Mustn't
524 * pick up objects which are not at any loc, since carry wants to
525 * remove objects from game.atloc chains. */
529 if (object > NOBJECTS)
530 from = game.fixed[object - NOBJECTS];
532 from = game.place[object];
533 if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
538 long put(long object, long where, long pval)
539 /* PUT is the same as MOVE, except it returns a value used to set up the
540 * negated game.prop values for the repository objects. */
546 void carry(long object, long where)
547 /* Start toting an object, removing it from the list of things at its former
548 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
549 * (moving "fixed" second loc), don't change game.place or game.holdng. */
553 if (object <= NOBJECTS) {
554 if (game.place[object] == CARRIED)
556 game.place[object] = CARRIED;
559 if (game.atloc[where] == object) {
560 game.atloc[where] = game.link[object];
563 temp = game.atloc[where];
564 while (game.link[temp] != object) {
565 temp = game.link[temp];
567 game.link[temp] = game.link[object];
570 void drop(long object, long where)
571 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
572 * game.holdng if the object was being toted. */
574 if (object > NOBJECTS)
575 game.fixed[object - NOBJECTS] = where;
577 if (game.place[object] == CARRIED)
579 game.place[object] = where;
583 game.link[object] = game.atloc[where];
584 game.atloc[where] = object;
587 long atdwrf(long where)
588 /* Return the index of first dwarf at the given location, zero if no dwarf is
589 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
590 * the pirate (6th dwarf). */
598 for (long i = 1; i <= NDWARVES - 1; i++) {
599 if (game.dloc[i] == where)
601 if (game.dloc[i] != 0)
607 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
608 * randrange, RNDVOC) */
610 long setbit(long bit)
611 /* Returns 2**bit for use in constructing bit-masks. */
616 bool tstbit(long mask, int bit)
617 /* Returns true if the specified bit is set in the mask. */
619 return (mask & (1 << bit)) != 0;
622 void set_seed(long seedval)
623 /* Set the LCG seed */
625 game.lcg_x = (unsigned long) seedval % game.lcg_m;
628 unsigned long get_next_lcg_value(void)
629 /* Return the LCG's current value, and then iterate it. */
631 unsigned long old_x = game.lcg_x;
632 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
636 long randrange(long range)
637 /* Return a random integer from [0, range). */
639 return range * get_next_lcg_value() / game.lcg_m;
642 void make_zzword(char zzword[6])
644 for (int i = 0; i < 5; ++i)
646 zzword[i] = 'A' + randrange(26);
648 zzword[1] = '\''; // force second char to apostrophe
652 /* Machine dependent routines (MAPLIN, SAVEIO) */
654 bool MAPLIN(FILE *fp)
658 /* Read a line of input, from the specified input source.
659 * This logic is complicated partly because it has to serve
660 * several cases with different requirements and partly because
661 * of a quirk in linenoise().
663 * The quirk shows up when you paste a test log from the clipboard
664 * to the program's command prompt. While fgets (as expected)
665 * consumes it a line at a time, linenoise() returns the first
666 * line and discards the rest. Thus, there needs to be an
667 * editline (-s) option to fall back to fgets while still
668 * prompting. Note that linenoise does behave properly when
669 * fed redirected stdin.
671 * The logging is a bit of a mess because there are two distinct cases
672 * in which you want to echo commands. One is when shipping them to
673 * a log under the -l option, in which case you want to suppress
674 * prompt generation (so test logs are unadorned command sequences).
675 * On the other hand, if you redirected stdin and are feeding the program
676 * a logfile, you *do* want prompt generation - it makes checkfiles
677 * easier to read when the commands are marked by a preceding prompt.
683 IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
686 char *cp = linenoise("> ");
689 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
690 linenoiseHistoryAdd(rawbuf);
691 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
696 (!eof && rawbuf[0] == '#');
698 if (logfp && fp == stdin)
703 if (logfp && fp == stdin)
708 if (prompt && efp == stdout)
710 IGNORE(fputs(rawbuf, efp));
712 strcpy(INLINE + 1, rawbuf);
713 /* translate the chars to integers in the range 0-126 and store
714 * them in the common array "INLINE". Integer values are as follows:
715 * 0 = space [ASCII CODE 40 octal, 32 decimal]
716 * 1-2 = !" [ASCII 41-42 octal, 33-34 decimal]
717 * 3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
718 * 11-36 = upper-case letters
719 * 37-62 = lower-case letters
720 * 63 = percent (%) [ASCII 45 octal, 37 decimal]
721 * 64-73 = digits, 0 through 9
722 * Remaining characters can be translated any way that is convenient;
723 * The above mappings are required so that certain special
724 * characters are known to fit in 6 bits and/or can be easily spotted.
725 * Array elements beyond the end of the line should be filled with 0,
726 * and LNLENG should be set to the index of the last character.
728 * If the data file uses a character other than space (e.g., tab) to
729 * separate numbers, that character should also translate to 0.
731 * This procedure may use the map1,map2 arrays to maintain
732 * static data for he mapping. MAP2(1) is set to 0 when the
733 * program starts and is not changed thereafter unless the
734 * routines in this module choose to do so. */
736 for (long i = 1; i <= (long)sizeof(INLINE) && INLINE[i] != 0; i++) {
737 long val = INLINE[i];
738 INLINE[i] = ascii_to_advent[val];
747 void datime(long* d, long* t)
750 gettimeofday(&tv, NULL);
751 *d = (long) tv.tv_sec;
752 *t = (long) tv.tv_usec;
756 void bug(enum bugtype num, const char *error_string)
758 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);