aboutsummaryrefslogtreecommitdiff
path: root/src/Lexer.zig
blob: f59737efb0cad0b2f9b4a0ad76719aca0266c56d (plain) (blame)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
const std = @import("std");

pub const Token = struct {
    loc: Location,
    type: Type,

    pub const Type = enum {
        left_paren,
        right_paren,
        left_curly,
        right_curly,
        integer_literal,
        plus,
        minus,
        equal,
        invalid,
        eof,
        identifier,

        // Keywords
        let,
        @"if",
        @"else",
    };
};

pub const Location = struct {
    start: usize,
    end: usize,

    pub fn combine(a: Location, b: Location) Location {
        std.debug.assert(a.end <= b.start);
        return .{ .start = @min(a.start, b.start), .end = @max(a.end, b.end) };
    }

    /// Assumes that the location comes directly from an `integer_literal` token.
    pub fn getInt(self: Location, file_source: []const u8) u64 {
        var value: u64 = 0;
        for (file_source[self.start..self.end]) |c| {
            std.debug.assert('0' <= c and c <= '9');
            value = value * 10 + (c - '0');
        }
        return value;
    }

    /// Assumes that the location comes directly from an `identifier` token.
    pub fn getIdent(self: Location, file_source: []const u8) []const u8 {
        return file_source[self.start..self.end];
    }
};

pub fn peek(self: *Self) Token {
    if (self.peeked == null) {
        self.peeked = self.getNext();
    }
    return self.peeked.?;
}

pub fn next(self: *Self) Token {
    const token = self.peek();
    self.peeked = null;
    return token;
}

source: []const u8,
start: usize = 0,
pos: usize = 0,
peeked: ?Token = null,

fn getNext(self: *Self) Token {
    self.start = self.pos;
    return s: switch (self.eatChar() orelse return self.create(.eof)) {
        '(' => self.create(.left_paren),
        ')' => self.create(.right_paren),
        '{' => self.create(.left_curly),
        '}' => self.create(.right_curly),
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' => self.integerLiteral(),
        '+' => self.create(.plus),
        '-' => self.create(.minus),
        '=' => self.create(.equal),
        '#' => {
            while ((self.eatChar() orelse '\n') != '\n') {}
            self.start = self.pos;
            continue :s (self.eatChar() orelse return self.create(.eof));
        },
        ' ', '\n' => {
            self.start = self.pos;
            continue :s (self.eatChar() orelse return self.create(.eof));
        },
        else => |c| if ('a' <= c and c <= 'z' or 'A' <= c and c <= 'Z')
            self.identifierOrKeyword()
        else
            self.create(.invalid),
    };
}

fn integerLiteral(self: *Self) Token {
    var value: ?u64 = self.source[self.start] - '0';
    while (digitValue(self.peekChar())) |v| {
        var nxt: ?u64 = null;
        if (value) |val|
            if (std.math.mul(u64, val, 10) catch null) |p|
                if (std.math.add(u64, p, v) catch null) |s| {
                    nxt = s;
                };

        value = nxt;
        _ = self.eatChar();
    }
    return if (value != null)
        self.create(.integer_literal)
    else
        self.create(.invalid);
}

fn identifierOrKeyword(self: *Self) Token {
    while (true) {
        const c = self.peekChar() orelse 0;
        if ('a' <= c and c <= 'z' or 'A' <= c and c <= 'Z' or c == '_') {
            _ = self.eatChar();
            continue;
        }
        const value = self.source[self.start..self.pos];
        return self.create(switch (std.meta.stringToEnum(Token.Type, value) orelse .invalid) {
            .let, .@"if", .@"else" => |t| t,
            else => .identifier,
        });
    }
}

fn create(self: *Self, ty: Token.Type) Token {
    const start = self.start;
    return .{ .loc = .{ .start = start, .end = self.pos }, .type = ty };
}

fn eatChar(self: *Self) ?u8 {
    const token = self.peekChar();
    if (token != null) self.pos += 1;
    return token;
}

fn peekChar(self: *Self) ?u8 {
    return if (self.pos < self.source.len) self.source[self.pos] else null;
}

const Self = @This();

fn digitValue(c: ?u8) ?u8 {
    return switch (c orelse return null) {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' => c.? - '0',
        else => null,
    };
}