11 #include "linenoise/linenoise.h"
14 void* xmalloc(size_t size)
16 void* ptr = malloc(size);
19 // exclude from coverage analysis because we can't simulate an out of memory error in testing
20 fprintf(stderr, "Out of memory!\n");
27 void packed_to_token(long packed, char token[6])
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];
35 // Ensure the last character is \0.
38 // Replace trailing whitespace with \0.
39 for (int i = 4; i >= 0; --i) {
40 if (token[i] == ' ' || token[i] == '\t')
47 /* Hide the fact that wods are corrently packed longs */
49 bool wordeq(token_t a, token_t b)
54 bool wordempty(token_t a)
59 void wordclear(token_t *v)
64 /* I/O routines (speak, pspeak, rspeak, GETIN, YES) */
66 void vspeak(const char* msg, va_list ap)
68 // Do nothing if we got a null pointer.
72 // Do nothing if we got an empty string.
76 // Print a newline if the global game.blklin says to.
77 if (game.blklin == true)
80 int msglen = strlen(msg);
83 ssize_t size = 2000; /* msglen > 50 ? msglen*2 : 100; */
84 char* rendered = xmalloc(size);
85 char* renderp = rendered;
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++) {
94 long arg = va_arg(ap, long);
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.
100 int ret = snprintf(renderp, size, "%ld", arg);
107 // Unmodified string specifier.
109 packed_to_token(arg, renderp); /* unpack directly to destination */
110 size_t len = strlen(renderp);
115 // Singular/plural specifier.
117 if (previous_arg > 1) { // look at the *previous* parameter (which by necessity must be numeric)
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]);
130 if (msg[i] == 'C') // First char uppercase, rest lowercase.
131 renderp[0] = toupper(renderp[0]);
141 // Print the message.
142 printf("%s\n", rendered);
147 void speak(const char* msg, ...)
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. */
166 vspeak(objects[msg].inventory, ap);
169 vspeak(objects[msg].longs[skip], ap);
172 vspeak(objects[msg].sounds[skip], ap);
175 vspeak(objects[msg].texts[skip], ap);
181 void rspeak(vocab_t i, ...)
182 /* Print the i-th "random" message (section 6 of database). */
186 vspeak(arbitrary_messages[i], ap);
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. */
203 fputc('\n', stdout);;
206 *pword1 = GETTXT(true, true, true);
207 if (game.blklin && *pword1 < 0)
209 *pword1x = GETTXT(false, true, true);
211 junk = GETTXT(false, true, true);
214 *pword2 = GETTXT(true, true, true);
215 *pword2x = GETTXT(false, true, true);
217 junk = GETTXT(false, true, true);
220 if (GETTXT(true, true, true) <= 0)
226 void echo_input(FILE* destination, char* input_prompt, char* input)
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);
239 char input_prompt[] = "> ";
241 input_prompt[0] = '\0';
243 // Print a blank line if game.blklin tells us to.
244 if (game.blklin == true)
250 input = linenoise(input_prompt);
256 // Should be unreachable in tests, as they will use a non-interactive shell.
257 printf("%s", input_prompt);
259 IGNORE(getline(&input, &n, stdin));
262 if (input == NULL) // Got EOF; return with it.
264 else if (input[0] == '#') // Ignore comments.
266 else // We have a 'normal' line; leave the loop.
270 // Strip trailing newlines from the input
271 input[strcspn(input, "\n")] = 0;
273 linenoiseHistoryAdd(input);
276 echo_input(stdout, input_prompt, input);
279 echo_input(logfp, input_prompt, input);
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. */
297 // Should be unreachable. Reply should never be NULL
298 linenoiseFree(reply);
303 char* firstword = (char*) xmalloc(strlen(reply)+1);
304 sscanf(reply, "%s", firstword);
306 for (int i = 0; i < (int)strlen(firstword); ++i)
307 firstword[i] = tolower(firstword[i]);
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);
316 if (yes == 0 || y == 0) {
320 } else if (no == 0 || n == 0) {
325 rspeak(PLEASE_ANSWER);
327 linenoiseFree(reply);
331 /* Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT) */
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. */
341 static long splitting = -1;
343 if (LNPOSN != splitting)
349 if ((!skip) || INLINE[LNPOSN] != 0)
355 for (int I = 1; I <= TOKLEN; I++) {
357 if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
359 char current = INLINE[LNPOSN];
360 if (current < ascii_to_advent['%']) {
362 if (upper && current >= ascii_to_advent['a'])
363 current = current - 26;
364 text = text + current;
368 if (splitting != LNPOSN) {
369 text = text + ascii_to_advent['%'];
374 text = text + current - ascii_to_advent['%'];
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
391 long i = 1, word = 0;
393 for (long k = letters; k != 0; k = k / 100) {
394 word = word + i * (MOD(k, 50) + 10);
396 if (MOD(k, 100) > 50)word = word + i * 5;
398 i = 64L * 64L * 64L * 64L * 64L / i;
403 /* Data structure routines */
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. */
415 for (long i = 1; i <= TABSIZ; i++) {
420 BUG(REQUIRED_VOCABULARY_WORD_NOT_FOUND); // LCOV_EXCL_LINE
422 if (init >= 0 && KTAB[i] / 1000 != init)
427 lexeme = MOD(lexeme, 1000);
431 BUG(RAN_OFF_END_OF_VOCABULARY_TABLE); // LCOV_EXCL_LINE
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. */
440 i = game.place[object];
441 j = game.fixed[object];
443 move(object + NOBJECTS, j);
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. */
454 if (object > NOBJECTS)
455 from = game.fixed[object - NOBJECTS];
457 from = game.place[object];
458 if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
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. */
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. */
478 if (object <= NOBJECTS) {
479 if (game.place[object] == CARRIED)
481 game.place[object] = CARRIED;
484 if (game.atloc[where] == object) {
485 game.atloc[where] = game.link[object];
488 temp = game.atloc[where];
489 while (game.link[temp] != object) {
490 temp = game.link[temp];
492 game.link[temp] = game.link[object];
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. */
499 if (object > NOBJECTS)
500 game.fixed[object - NOBJECTS] = where;
502 if (game.place[object] == CARRIED)
504 game.place[object] = where;
508 game.link[object] = game.atloc[where];
509 game.atloc[where] = object;
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). */
523 for (long i = 1; i <= NDWARVES - 1; i++) {
524 if (game.dloc[i] == where)
526 if (game.dloc[i] != 0)
532 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
533 * randrange, RNDVOC) */
535 long setbit(long bit)
536 /* Returns 2**bit for use in constructing bit-masks. */
541 bool tstbit(long mask, int bit)
542 /* Returns true if the specified bit is set in the mask. */
544 return (mask & (1 << bit)) != 0;
547 void set_seed(long seedval)
548 /* Set the LCG seed */
550 game.lcg_x = (unsigned long) seedval % game.lcg_m;
553 unsigned long get_next_lcg_value(void)
554 /* Return the LCG's current value, and then iterate it. */
556 unsigned long old_x = game.lcg_x;
557 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
561 long randrange(long range)
562 /* Return a random integer from [0, range). */
564 return range * get_next_lcg_value() / game.lcg_m;
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. */
576 for (int i = 1; i <= 5; i++) {
577 long j = 11 + randrange(26);
584 long div = 64L * 64L * 64L;
585 for (int i = 1; i <= TABSIZ; i++) {
586 if (MOD(ATAB[i] / div, 64L) == second) {
596 /* Machine dependent routines (MAPLIN, SAVEIO) */
598 bool MAPLIN(FILE *fp)
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().
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.
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.
627 IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
630 char *cp = linenoise("> ");
633 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
634 linenoiseHistoryAdd(rawbuf);
635 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
640 (!eof && rawbuf[0] == '#');
642 if (logfp && fp == stdin)
647 if (logfp && fp == stdin)
652 if (prompt && efp == stdout)
654 IGNORE(fputs(rawbuf, efp));
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.
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.
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. */
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];
691 void datime(long* d, long* t)
694 gettimeofday(&tv, NULL);
695 *d = (long) tv.tv_sec;
696 *t = (long) tv.tv_usec;
700 void bug(enum bugtype num, const char *error_string)
702 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);