+/EE312
software design
git clone https://git.julia.blue/+/EE312
88398ce
master
1#include <stdio.h> 2#include "lex.h" 3 4FILE * f = stdin ; 5char buf [TOK_MAX ]; 6int pos ; 7Token current ; 8 9void set_input (const char * filename ) { 10f = fopen (filename ,"r" ); 11if (!f ) { 12fprintf (stderr ,"sorry, I couldn't open the file %s for reading\n" ,filename ); 13 } 14pos = 0 ; 15current = {ERROR ,0 }; 16} 17 18static bool whitespace (char c ) { 19return c == ' ' || c == '\t' || c == '\n' ; 20} 21 22static bool alpha (char c ) { 23return 'a' <=c && c <='z' || 'A' <=c && c <='Z' |c == '_' ; 24} 25 26static bool number (char c ) { 27return '0' <=c && c <='9' ; 28} 29 30static void strcpy (char * dest ,const char * src ) { 31while (* dest ++ = * src ++ ); 32} 33 34char nextChar () { 35char temp ; 36if ((temp = fgetc (f ))== EOF ) { 37current .type = END ; 38return -1 ; 39 } 40return temp ; 41} 42 43void advance () { 44pos = 0 ; 45char temp = ' ' ; 46while (whitespace (temp )) { 47if ((temp = nextChar ())== -1 ) { 48return ; 49 } 50 } 51if (alpha (temp )) {//Name 52current .type = NAME ; 53buf [pos ++ ]= temp ; 54while (!whitespace (temp = fgetc (f ))) { 55buf [pos ++ ]= temp ; 56 } 57if (!alpha (buf [pos - 1 ])) { 58// Error, malformed name 59 } 60 }else if (number (temp )) { 61current .type = NUMBER ; 62buf [pos ++ ]= temp ; 63while (!whitespace (temp = fgetc (f ))) { 64buf [pos ++ ]= temp ; 65 } 66if (!number (buf [pos - 1 ])) { 67// Error, malformed number 68 } 69 70 }else if (temp == '/' ) {// Comment 71if ((temp = nextChar ())== -1 ) { 72return ; 73 } 74if (temp == '/' ) { 75while (temp != '\n' ) { 76if ((temp = nextChar ())== -1 ) { 77return ; 78 } 79 } 80advance (); 81 }else { 82// Division not comment 83current .type = OPERATOR ; 84buf [pos ++ ]= '/' ; 85 } 86 }else if (temp == '"' ) {// Quoted string 87current .type = STRING ; 88if ((temp = nextChar ())== -1 ) { 89return ;// Error, malformed string 90 } 91while (temp != '"' ) { 92buf [pos ++ ]= temp ; 93if ((temp = nextChar ())== -1 ) { 94return ; 95 } 96 } 97 }else { 98current .type = OPERATOR ; 99do { 100buf [pos ++ ]= temp ; 101 }while (!whitespace (temp = fgetc (f ))); 102 } 103buf [pos ]= '\0' ; 104if (pos ) { 105strcpy (current .data ,buf ); 106 }else { 107current .type = ERROR ; 108 } 109}