10 #include "linenoise/linenoise.h"
13 void* xmalloc(size_t size)
15 void* ptr = malloc(size);
17 fprintf(stderr, "Out of memory!\n");
23 char* xstrdup(const char* s)
25 char* ptr = strdup(s);
27 fprintf(stderr, "Out of memory!\n");
33 void packed_to_token(long packed, char token[6])
35 // Unpack and map back to ASCII.
36 for (int i = 0; i < 5; ++i) {
37 char advent = (packed >> i * 6) & 63;
38 token[4 - i] = advent_to_ascii[(int) advent];
41 // Ensure the last character is \0.
44 // Replace trailing whitespace with \0.
45 for (int i = 4; i >= 0; --i) {
46 if (token[i] == ' ' || token[i] == '\t')
53 /* Hide the fact that wods are corrently packed longs */
55 bool wordeq(token_t a, token_t b)
60 bool wordempty(token_t a)
65 void wordclear(token_t *v)
70 /* I/O routines (SPEAK, PSPEAK, RSPEAK, SETPRM, GETIN, YES) */
72 void speak(const char* msg)
74 // Do nothing if we got a null pointer.
78 // Do nothing if we got an empty string.
82 // Print a newline if the global game.blklin says to.
83 if (game.blklin == true)
86 // Create a copy of our string, so we can edit it.
87 char* copy = xstrdup(msg);
89 // Staging area for stringified parameters.
90 char parameters[5][100]; // FIXME: to be replaced with dynamic allocation
92 // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
93 int pi = 0; // parameter index
94 for (int i = 0; i < (int)strlen(msg); ++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 + 1] == 'd') {
101 sprintf(parameters[pi], "%ld", PARMS[pi]);
104 // Unmodified string specifier.
105 if (msg[i + 1] == 's') {
106 packed_to_token(PARMS[pi], parameters[pi]);
109 // Singular/plural specifier.
110 if (msg[i + 1] == 'S') {
112 if (PARMS[pi - 1] > 1) { // look at the *previous* parameter (which by necessity must be numeric)
113 sprintf(parameters[pi], "%s", "s");
115 sprintf(parameters[pi], "%s", "");
119 // All-lowercase specifier.
120 if (msg[i + 1] == 'L') {
122 packed_to_token(PARMS[pi], parameters[pi]);
123 for (int j = 0; j < (int)strlen(parameters[pi]); ++j) {
124 parameters[pi][j] = tolower(parameters[pi][j]);
128 // First char uppercase, rest lowercase.
129 if (msg[i + 1] == 'C') {
131 packed_to_token(PARMS[pi], parameters[pi]);
132 for (int j = 0; j < (int)strlen(parameters[pi]); ++j) {
133 parameters[pi][j] = tolower(parameters[pi][j]);
135 parameters[pi][0] = toupper(parameters[pi][0]);
140 // Render the final string.
141 char rendered[2000]; // FIXME: to be replaced with dynamic allocation
142 sprintf(rendered, copy, parameters[1], parameters[2], parameters[3], parameters[4]); // FIXME: to be replaced with vsprintf()
144 // Print the message.
145 printf("%s\n", rendered);
150 void PSPEAK(vocab_t msg, int skip)
151 /* Find the skip+1st message from msg and print it. msg should be
152 * the index of the inventory message for object. (INVEN+N+1 message
153 * is game.prop=N message). */
156 speak(object_descriptions[msg].longs[skip]);
158 speak(object_descriptions[msg].inventory);
161 void RSPEAK(vocab_t i)
162 /* Print the i-th "random" message (section 6 of database). */
164 speak(arbitrary_messages[i]);
167 void SETPRM(long first, long p1, long p2)
168 /* Stores parameters into the PRMCOM parms array for use by speak. P1 and P2
169 * are stored into PARMS(first) and PARMS(first+1). */
171 if (first >= MAXPARMS)
172 BUG(TOO_MANY_PARAMETERS_GIVEN_TO_SETPRM);
175 PARMS[first + 1] = p2;
179 bool GETIN(FILE *input,
180 long *pword1, long *pword1x,
181 long *pword2, long *pword2x)
182 /* Get a command from the adventurer. Snarf out the first word, pad it with
183 * blanks, and return it in WORD1. Chars 6 thru 10 are returned in WORD1X, in
184 * case we need to print out the whole word in an error message. Any number of
185 * blanks may follow the word. If a second word appears, it is returned in
186 * WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
192 fputc('\n', stdout);;
195 *pword1 = GETTXT(true, true, true);
196 if (game.blklin && *pword1 < 0)
198 *pword1x = GETTXT(false, true, true);
200 junk = GETTXT(false, true, true);
203 *pword2 = GETTXT(true, true, true);
204 *pword2x = GETTXT(false, true, true);
206 junk = GETTXT(false, true, true);
209 if (GETTXT(true, true, true) <= 0)
215 void echo_input(FILE* destination, char* input_prompt, char* input)
217 size_t len = strlen(input_prompt) + strlen(input) + 1;
218 char* prompt_and_input = (char*) xmalloc(len);
219 strcpy(prompt_and_input, input_prompt);
220 strcat(prompt_and_input, input);
221 fprintf(destination, "%s\n", prompt_and_input);
222 free(prompt_and_input);
228 char input_prompt[] = "> ";
230 input_prompt[0] = '\0';
232 // Print a blank line if game.blklin tells us to.
233 if (game.blklin == true)
239 input = linenoise(input_prompt);
244 printf("%s", input_prompt);
245 IGNORE(getline(&input, &n, stdin));
248 if (input == NULL) // Got EOF; quit.
250 else if (input[0] == '#') // Ignore comments.
252 else // We have a 'normal' line; leave the loop.
256 // Strip trailing newlines from the input
257 input[strcspn(input, "\n")] = 0;
259 linenoiseHistoryAdd(input);
262 echo_input(stdout, input_prompt, input);
265 echo_input(logfp, input_prompt, input);
270 bool YES(const char* question, const char* yes_response, const char* no_response)
271 /* Print message X, wait for yes/no answer. If yes, print Y and return true;
272 * if no, print Z and return false. */
282 char* firstword = (char*) xmalloc(strlen(reply));
283 sscanf(reply, "%s", firstword);
285 for (int i = 0; i < (int)strlen(firstword); ++i)
286 firstword[i] = tolower(firstword[i]);
288 int yes = strncmp("yes", firstword, sizeof("yes") - 1);
289 int y = strncmp("y", firstword, sizeof("y") - 1);
290 int no = strncmp("no", firstword, sizeof("no") - 1);
291 int n = strncmp("n", firstword, sizeof("n") - 1);
295 if (yes == 0 || y == 0) {
299 } else if (no == 0 || n == 0) {
304 RSPEAK(PLEASE_ANSWER);
306 linenoiseFree(reply);
310 /* Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT) */
312 long GETTXT(bool skip, bool onewrd, bool upper)
313 /* Take characters from an input line and pack them into 30-bit words.
314 * Skip says to skip leading blanks. ONEWRD says stop if we come to a
315 * blank. UPPER says to map all letters to uppercase. If we reach the
316 * end of the line, the word is filled up with blanks (which encode as 0's).
317 * If we're already at end of line when TEXT is called, we return -1. */
320 static long splitting = -1;
322 if (LNPOSN != splitting)
328 if ((!skip) || INLINE[LNPOSN] != 0)
334 for (int I = 1; I <= TOKLEN; I++) {
336 if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
338 char current = INLINE[LNPOSN];
339 if (current < ascii_to_advent['%']) {
341 if (upper && current >= ascii_to_advent['a'])
342 current = current - 26;
343 text = text + current;
347 if (splitting != LNPOSN) {
348 text = text + ascii_to_advent['%'];
353 text = text + current - ascii_to_advent['%'];
361 token_t MAKEWD(long letters)
362 /* Combine TOKLEN (currently 5) uppercase letters (represented by
363 * pairs of decimal digits in lettrs) to form a 30-bit value matching
364 * the one that GETTXT would return given those characters plus
365 * trailing blanks. Caution: lettrs will overflow 31 bits if
366 * 5-letter word starts with V-Z. As a kludgey workaround, you can
367 * increment a letter by 5 by adding 50 to the next pair of
370 long i = 1, word = 0;
372 for (long k = letters; k != 0; k = k / 100) {
373 word = word + i * (MOD(k, 50) + 10);
375 if (MOD(k, 100) > 50)word = word + i * 5;
377 i = 64L * 64L * 64L * 64L * 64L / i;
382 /* Data structure routines */
384 long VOCAB(long id, long init)
385 /* Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
386 * -1 if not found. If INIT is positive, this is an initialisation call setting
387 * up a keyword variable, and not finding it constitutes a bug. It also means
388 * that only KTAB values which taken over 1000 equal INIT may be considered.
389 * (Thus "STEPS", which is a motion verb as well as an object, may be located
390 * as an object.) And it also means the KTAB value is taken modulo 1000. */
394 for (long i = 1; i <= TABSIZ; i++) {
399 BUG(REQUIRED_VOCABULARY_WORD_NOT_FOUND);
401 if (init >= 0 && KTAB[i] / 1000 != init)
406 lexeme = MOD(lexeme, 1000);
410 BUG(RAN_OFF_END_OF_VOCABULARY_TABLE);
413 void JUGGLE(long object)
414 /* Juggle an object by picking it up and putting it down again, the purpose
415 * being to get the object to the front of the chain of things at its loc. */
419 i = game.place[object];
420 j = game.fixed[object];
422 MOVE(object + NOBJECTS, j);
425 void MOVE(long object, long where)
426 /* Place any object anywhere by picking it up and dropping it. May
427 * already be toting, in which case the carry is a no-op. Mustn't
428 * pick up objects which are not at any loc, since carry wants to
429 * remove objects from game.atloc chains. */
433 if (object > NOBJECTS)
434 from = game.fixed[object - NOBJECTS];
436 from = game.place[object];
437 if (from != LOC_NOWHERE && from != CARRIED && !SPECIAL(from))
442 long PUT(long object, long where, long pval)
443 /* PUT is the same as MOVE, except it returns a value used to set up the
444 * negated game.prop values for the repository objects. */
450 void CARRY(long object, long where)
451 /* Start toting an object, removing it from the list of things at its former
452 * location. Incr holdng unless it was already being toted. If object>NOBJECTS
453 * (moving "fixed" second loc), don't change game.place or game.holdng. */
457 if (object <= NOBJECTS) {
458 if (game.place[object] == CARRIED)
460 game.place[object] = CARRIED;
463 if (game.atloc[where] == object) {
464 game.atloc[where] = game.link[object];
467 temp = game.atloc[where];
468 while (game.link[temp] != object) {
469 temp = game.link[temp];
471 game.link[temp] = game.link[object];
474 void DROP(long object, long where)
475 /* Place an object at a given loc, prefixing it onto the game.atloc list. Decr
476 * game.holdng if the object was being toted. */
478 if (object > NOBJECTS)
479 game.fixed[object - NOBJECTS] = where;
481 if (game.place[object] == CARRIED)
483 game.place[object] = where;
487 game.link[object] = game.atloc[where];
488 game.atloc[where] = object;
491 long ATDWRF(long where)
492 /* Return the index of first dwarf at the given location, zero if no dwarf is
493 * there (or if dwarves not active yet), -1 if all dwarves are dead. Ignore
494 * the pirate (6th dwarf). */
502 for (long i = 1; i <= NDWARVES - 1; i++) {
503 if (game.dloc[i] == where)
505 if (game.dloc[i] != 0)
511 /* Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
512 * randrange, RNDVOC) */
514 long SETBIT(long bit)
515 /* Returns 2**bit for use in constructing bit-masks. */
520 bool TSTBIT(long mask, int bit)
521 /* Returns true if the specified bit is set in the mask. */
523 return (mask & (1 << bit)) != 0;
526 void set_seed(long seedval)
527 /* Set the LCG seed */
529 game.lcg_x = (unsigned long) seedval % game.lcg_m;
532 unsigned long get_next_lcg_value(void)
533 /* Return the LCG's current value, and then iterate it. */
535 unsigned long old_x = game.lcg_x;
536 game.lcg_x = (game.lcg_a * game.lcg_x + game.lcg_c) % game.lcg_m;
540 long randrange(long range)
541 /* Return a random integer from [0, range). */
543 return range * get_next_lcg_value() / game.lcg_m;
546 long RNDVOC(long second, long force)
547 /* Searches the vocabulary ATAB for a word whose second character is
548 * char, and changes that word such that each of the other four
549 * characters is a random letter. If force is non-zero, it is used
550 * as the new word. Returns the new word. */
555 for (int i = 1; i <= 5; i++) {
556 long j = 11 + randrange(26);
563 long div = 64L * 64L * 64L;
564 for (int i = 1; i <= TABSIZ; i++) {
565 if (MOD(ATAB[i] / div, 64L) == second) {
575 /* Machine dependent routines (MAPLIN, SAVEIO) */
577 bool MAPLIN(FILE *fp)
581 /* Read a line of input, from the specified input source.
582 * This logic is complicated partly because it has to serve
583 * several cases with different requirements and partly because
584 * of a quirk in linenoise().
586 * The quirk shows up when you paste a test log from the clipboard
587 * to the program's command prompt. While fgets (as expected)
588 * consumes it a line at a time, linenoise() returns the first
589 * line and discards the rest. Thus, there needs to be an
590 * editline (-s) option to fall back to fgets while still
591 * prompting. Note that linenoise does behave properly when
592 * fed redirected stdin.
594 * The logging is a bit of a mess because there are two distinct cases
595 * in which you want to echo commands. One is when shipping them to
596 * a log under the -l option, in which case you want to suppress
597 * prompt generation (so test logs are unadorned command sequences).
598 * On the other hand, if you redirected stdin and are feeding the program
599 * a logfile, you *do* want prompt generation - it makes checkfiles
600 * easier to read when the commands are marked by a preceding prompt.
606 IGNORE(fgets(rawbuf, sizeof(rawbuf) - 1, fp));
609 char *cp = linenoise("> ");
612 strncpy(rawbuf, cp, sizeof(rawbuf) - 1);
613 linenoiseHistoryAdd(rawbuf);
614 strncat(rawbuf, "\n", sizeof(rawbuf) - strlen(rawbuf) - 1);
619 (!eof && rawbuf[0] == '#');
621 if (logfp && fp == stdin)
626 if (logfp && fp == stdin)
631 if (prompt && efp == stdout)
633 IGNORE(fputs(rawbuf, efp));
635 strcpy(INLINE + 1, rawbuf);
636 /* translate the chars to integers in the range 0-126 and store
637 * them in the common array "INLINE". Integer values are as follows:
638 * 0 = space [ASCII CODE 40 octal, 32 decimal]
639 * 1-2 = !" [ASCII 41-42 octal, 33-34 decimal]
640 * 3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
641 * 11-36 = upper-case letters
642 * 37-62 = lower-case letters
643 * 63 = percent (%) [ASCII 45 octal, 37 decimal]
644 * 64-73 = digits, 0 through 9
645 * Remaining characters can be translated any way that is convenient;
646 * The above mappings are required so that certain special
647 * characters are known to fit in 6 bits and/or can be easily spotted.
648 * Array elements beyond the end of the line should be filled with 0,
649 * and LNLENG should be set to the index of the last character.
651 * If the data file uses a character other than space (e.g., tab) to
652 * separate numbers, that character should also translate to 0.
654 * This procedure may use the map1,map2 arrays to maintain static data for
655 * the mapping. MAP2(1) is set to 0 when the program starts
656 * and is not changed thereafter unless the routines on this page choose
659 for (long i = 1; i <= (long)sizeof(INLINE) && INLINE[i] != 0; i++) {
660 long val = INLINE[i];
661 INLINE[i] = ascii_to_advent[val];
670 void DATIME(long* d, long* t)
673 gettimeofday(&tv, NULL);
674 *d = (long) tv.tv_sec;
675 *t = (long) tv.tv_usec;
678 void bug(enum bugtype num, const char *error_string)
680 fprintf(stderr, "Fatal error %d, %s.\n", num, error_string);