1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "turng.h"
#ifndef __CMIX
# define __CMIX(X)
#endif
#define LINELEN 100
char* upcase(char* s) {
char* p = s;
while (*p) { *p = toupper(*p); p++; }
return s;
}
void readTuringProgram(char* filename) {
FILE* infile;
int lineno, maxlines, jump;
char* linenoStr;
char* command;
char* symbol;
char line[LINELEN];
if (!(infile = __CMIX(spectime)fopen(filename, "r"))) {
fprintf(stderr,
"Error: cannot find turing program source file `%s'\n",
filename);
exit(-1);
}
instrs = 0;
while (__CMIX(spectime)fgets(line, LINELEN, infile)) {
lineno = atoi(strtok(line, " \t\r\n"));
fprintf(stderr, "%2d ", lineno);
if (lineno >= MAXINSTRS) {
__CMIX(spectime)fprintf(stderr, "Linenumber %d too large\n", lineno);
__CMIX(spectime)exit(-1);
};
if (instrs <= lineno) instrs = lineno + 1;
command = upcase(strtok(NULL, " \t\r\n"));
if (!strcmp(command, "IF")) {
symbol = strtok(NULL, " \t\r\n'\"");
strtok(NULL, " '\"\t\r\n"); /* "goto" */
jump = atoi(strtok(NULL, " \t\r\n"));
instruction[lineno].tag = IfGoto;
instruction[lineno].a = symbol[0];
instruction[lineno].i = jump;
fprintf(stderr, "If '%c' goto %d\n",
instruction[lineno].a, instruction[lineno].i);
} else if (!strcmp(command, "LEFT")) {
instruction[lineno].tag = Left;
fprintf(stderr, "Left\n");
} else if (!strcmp(command, "RIGHT")) {
instruction[lineno].tag = Right;
fprintf(stderr, "Right\n");
} else if (!strcmp(command, "GOTO")) {
jump = atoi(strtok(NULL, " \t\r\n"));
instruction[lineno].tag = Goto;
instruction[lineno].i = jump;
fprintf(stderr, "Goto %d\n", instruction[lineno].i);
} else if (!strcmp(command, "READGOTO")) {
instruction[lineno].tag = ReadGoto;
fprintf(stderr, "ReadGoto\n", instruction[lineno].i);
} else if (!strcmp(command, "WRITE")) {
symbol = strtok(NULL, " \t\r\n'\"");
instruction[lineno].tag = Write;
instruction[lineno].a = symbol[0];
fprintf(stderr, "Write '%c'\n", instruction[lineno].a);
} else if (!strcmp(command, "STOP")) {
instruction[lineno].tag = Stop;
fprintf(stderr, "Stop\n");
}
}
fclose(infile);
}
|