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