+/EE312

software design

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

Joseph RyanAdd functions to blip5dbb718

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