/**************************************************************************** * fsm2num.c * David Boozer * (v1.0) March 30, 1999 * (v1.1) April 28, 2000 * 07 November 2007 (modified) ***************************************************************************** * Translate finite state machine representation of a Turing machine into * Turing number representation of Turing machine. ****************************************************************************/ #include #define NUM 1 #define ARW 2 #define RL 3 FILE *input_file; int line_num = 1; int token_val; int lookahead; void syntax_error () { fprintf (stderr, "Error: syntax error in line %d\n", line_num); exit (0); } int next_token () { char t; while (1) { t = getc (input_file); if (t == ' ' || t == '\t') ; else if (t == '\n') line_num++; else if (t == ';') { do t = getc (input_file); while (t != '\n' && t != EOF); line_num++; } else if (isdigit(t)) { ungetc (t, input_file); fscanf (input_file, "%d", &token_val); return NUM; } else if (t == '-') { if (getc (input_file) != '-') syntax_error (); if (getc (input_file) != '>') syntax_error (); return ARW; } else if (t == 'R' || t == 'L') { token_val = t; return RL; } else if (t == EOF) return EOF; else syntax_error (); } } void match (int token) { if (lookahead == token) lookahead = next_token (); else syntax_error (); } int match_bit () { int bit; bit = token_val; match (NUM); if (bit != 0 && bit != 1) syntax_error (); return bit; } void parse () { static int next_index = 2; int n, index, bit; int i, num_bits; n = token_val; match (NUM); bit = match_bit (); index = n<<1 | bit; if (index != next_index++) { fprintf (stderr, "Error: fsm entry skipped in line %d\n", line_num); exit (0); } match (ARW); n = token_val; match (NUM); for (i = n, num_bits = 0; i > 0; i >>= 1, num_bits++); for (i = num_bits-1; i >= 0; i--) printf ("%s", (n>>i & 1) ? "100" : "10"); bit = match_bit (); if (bit == 0 && token_val == 'R') printf ("1100"); if (bit == 1 && token_val == 'R') printf ("11000"); if (bit == 0 && token_val == 'L') printf ("110000"); if (bit == 1 && token_val == 'L') printf ("1100000"); match (RL); } int main (int argc, char *argv[]) { if (argc != 2) { fprintf (stderr, "Syntax: fsm2num \n"); exit (0); } input_file = fopen (argv[1], "r"); if (input_file == NULL) { fprintf (stderr, "Error reading from file: %s\n", argv[1]); exit (0); } lookahead = next_token (); while (lookahead != EOF) parse (); printf ("111\n"); return 0; }