#include #include "lex.h" FILE* f = stdin; char buf[TOK_MAX]; int pos; Token current; void set_input(const char* filename) { f = fopen(filename, "r"); if(!f) { fprintf(stderr, "sorry, I couldn't open the file %s for reading\n", filename); } pos = 0; current = {ERROR, 0}; } static bool whitespace(char c) { return c == ' ' || c == '\t' || c == '\n'; } static bool alpha(char c) { return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' | c == '_'; } static bool number(char c) { return '0' <= c && c <= '9'; } static void strcpy(char* dest, const char* src) { while(*dest++ = *src++); } char nextChar() { char temp; if((temp = fgetc(f)) == EOF) { current.type = END; return -1; } return temp; } void advance() { pos = 0; char temp = ' '; while(whitespace(temp)) { if((temp = nextChar()) == -1) { return; } } if(alpha(temp)) { //Name current.type = NAME; buf[pos++] = temp; while(!whitespace(temp = fgetc(f))) { buf[pos++] = temp; } if(!alpha(buf[pos - 1])) { // Error, malformed name } } else if(number(temp)) { current.type = NUMBER; buf[pos++] = temp; while(!whitespace(temp = fgetc(f))) { buf[pos++] = temp; } if(!number(buf[pos - 1])) { // Error, malformed number } } else if(temp == '/') { // Comment if((temp = nextChar()) == -1) { return; } if(temp == '/') { while(temp != '\n') { if((temp = nextChar()) == -1) { return; } } advance(); } else { // Division not comment current.type = OPERATOR; buf[pos++] = '/'; } } else if(temp == '"') { // Quoted string current.type = STRING; if((temp = nextChar()) == -1) { return; // Error, malformed string } while(temp != '"') { buf[pos++] = temp; if((temp = nextChar()) == -1) { return; } } } else { current.type = OPERATOR; do { buf[pos++] = temp; } while(!whitespace(temp = fgetc(f))); } buf[pos] = '\0'; if(pos) { strcpy(current.data, buf); } else { current.type = ERROR; } }