/*scanner.c - lexical scanner for arithmetic expressions*/ #include "scanner.h" /*WHICH STANDARD HEADER FILES DO YOU NEED TO INCLUDE HERE?*/ static char current_char; /*next character to be scanned*/ Token token; /*the token most recently scanned*/ int number; /*if token==NumberToken, here's the #*/ static char next_char() /*all input comes through here*/ { current_char = getchar(); } /*sets the token type and gets the next character*/ static void make_token(t) Token t; { next_char(); token = t; } /*On entry, 'current_char' is a digit. Set the global variable 'number' to the integer represented by the string of digits, and set the global variable 'token' to NumberToken.*/ static void string_to_number() { token = NumberToken; number = 0; /*invariant: The portion of the digit string that is to the left of the position of 'current_char' is the base-ten representation of 'number'. (For ease of specification, define the null string as a valid base-ten representation of the integer 0.)*/ /*In other, less declarative words, 'number' is accumulating the digits by place value.*/ /*bound: the number of digits that remain to be processed*/ do { /*FILL IN THE GUARD AND THE BODY OF THIS LOOP*/ } while( ); } /*initialise the scanner by loading the first character*/ void init_scanner() { next_char(); } /*top-level scanner function*/ void next_token() { /*THERE ARE FOUR THINGS TO DO HERE: * FIRST, SKIP WHITE SPACE -USE THE isspace() FUNCTION FROM -THEN... * IF THE CURRENT CHARACTER IS A DIGIT (USE isdigit()), CALL string_to_number() * IF THE CURRENT CHARACTER IS ONE OF +,-,*,/, or ., CALL make_token() WITH * THE APPROPRIATE TOKEN (LISTED IN scanner.h) * IF THE CURRENT CHARACTER IS NONE OF THE ABOVE, PRINT AN ERROR MESSAGE AND * END THE PROGRAM *YOU'LL NEED TO USE A COMBINATION OF if...else AND switch*/ } /*print the type and value of the token - useful in debugging*/ void print_token(t) Token t; { switch(t) { case NumberToken: printf("%d", number); break; case PlusToken: putchar('+'); break; case MinusToken: putchar('-'); break; case TimesToken: putchar('*'); break; case DivideToken: putchar('/'); break; case LeftParenToken: putchar('('); break; case RightParenToken: putchar(')'); break; case PeriodToken: putchar('.'); break; default: printf("undefined token %d", (int)t); } } /*ONCE YOU'RE DONE WITH THIS PROGRAM, GET scanner.h AND testscan.c, AND COMPILE THEM AND LINK THEM ALL TOGETHER LIKE THIS: cc -g -o testscan testscan.c scanner.c */