+/EE312

software design

git clone https://git.julia.blue/+/EE312

Joseph RyanFix error messages and add command line args88398ce

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