summaryrefslogtreecommitdiff
path: root/core/lexer.c
blob: 163e2f58003be40f3f8fa22cbc20de5e1dcdc531 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
 * Copyright (c) 2026, Apollo Telephone Laboratories.
 * Provided under the BSD-3 clause.
 */

#include <atas/lexer.h>
#include <atas/trace.h>
#include <stdio.h>
#include <stdbool.h>

/*
 * Returns true if the given char is a whitespace
 *
 * @c:  Character to compare against a set of whitespace
 */
static inline bool
lexer_is_ws(char c)
{
    switch (c) {
    case '\n':
    case '\f':
    case '\t':
    case '\r':
    case ' ':
        return true;
    }

    return false;
}

/*
 * Scan a single byte from the input source file
 *
 * @state:   Assembler state
 * @skip_ws: If true, skip whitespaces
 *
 * Returns the scanned byte on success, returns '\0'
 * on failure.
 */
static char
lexer_scan_byte(struct atas_state *state, bool skip_ws)
{
    char c;

    if (state == NULL) {
        return '\0';
    }

    if ((c = fgetc(state->in_file)) == EOF) {
        return '\0';
    }

    while (lexer_is_ws(c) && skip_ws) {
        if ((c = fgetc(state->in_file)) == EOF) {
            return '\0';
        }
    }

    return c;
}

int
atas_lexer_scan(struct atas_state *state, struct atas_token *token)
{
    char c;

    if (state == NULL || token == NULL) {
        return -1;
    }

    c = lexer_scan_byte(state, true);
    if (c == '\0') {
        return -1;
    }

    switch (c) {
    case ',':
        token->type = TT_COMMA;
        token->c = c;
        return 0;
    }

    trace_fatal("unexpected token '%c' while scanning\n", c);
    atas_fatal(state);
    return -1;
}