aboutsummaryrefslogtreecommitdiff
path: root/src/main.zig
blob: f687fc61d3d9d7e06dd07d7ab166c32f9f15eaee (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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
const std = @import("std");
const codegen = @import("./codegen.zig");
const target = @import("builtin").target;

pub const parse = @import("./parse.zig");
pub const Lexer = @import("./Lexer.zig");
pub const compile = @import("./compile.zig");

const blue = "\x1b[34m";
const red = "\x1b[31m";
const normal = "\x1b[0m";

pub fn main() !u8 {
    var arena: std.heap.ArenaAllocator = .init(std.heap.smp_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    var args = std.process.args();
    _ = args.next();

    const Action = enum {
        run,
        compile,
    };
    const action = (if (args.next()) |act| std.meta.stringToEnum(Action, act) else null) orelse {
        std.debug.print("Invalid action. Supply `run` or `compile`.", .{});
        return 1;
    };

    const out_dir = switch (action) {
        .run => blk: {
            const dir = try std.fmt.allocPrint(allocator, "/tmp/huginn-build-{}", .{std.crypto.random.int(u32)});
            try std.fs.makeDirAbsolute(dir);
            break :blk dir;
        },
        .compile => ".",
    };

    const in_path = args.next();
    const in_file = if (in_path) |path|
        try std.fs.cwd().openFile(path, .{})
    else
        std.io.getStdIn();

    const out_name = if (in_path) |p| blk: {
        if (!std.mem.endsWith(u8, p, ".hgn")) {
            std.debug.print("Invalid input file extension. Must be `.hgn`.", .{});
            return 1;
        }
        break :blk std.fs.path.basename(p[0 .. p.len - 4]);
    } else "a.out";
    const out_path = try std.fmt.allocPrint(allocator, "{s}/{s}", .{ out_dir, out_name });
    const out_file = try std.fs.cwd().createFile(out_path, .{ .mode = 0o777 });

    const source = try in_file.readToEndAlloc(
        allocator,
        640 * 1024, // ought to be enough for anyone
    );

    const elf = try compileSource(allocator, source);
    try out_file.writer().writeAll(elf);
    if (action == .run) {
        std.debug.print(blue ++ "running program:" ++ normal ++ "\n", .{});
        out_file.close();

        const err = std.process.execv(
            allocator,
            if (target.cpu.arch == .riscv64 and target.os.tag == .linux)
                &.{out_path}
            else
                &.{ "qemu-riscv64", out_path },
        );
        std.debug.print(red ++ "{}\n" ++ normal ++ "{any}\n", .{ err, @errorReturnTrace() });
        return 1;
    } else {
        return 0;
    }
}

fn compileSource(allocator: std.mem.Allocator, source: []const u8) ![]u8 {
    var lexer: Lexer = .{ .source = source };
    const ast = parse.file(allocator, &lexer) catch |err| {
        std.debug.print(red ++ "parsing error: {}\n" ++ normal, .{err});
        return error.ParsingError;
    };
    // std.debug.print(blue ++ "parse tree:" ++ normal ++ "\n{}\n", .{parse.fmt(ast, source, 0)});
    if (lexer.peek().type != .eof) {
        std.debug.print(red ++ "Unexpected token {}, expected end of file\n" ++ normal, .{lexer.next()});
        return error.ParsingError;
    }
    const module = compile.compile(allocator, source, ast) catch |err| {
        std.debug.print(red ++ "compilation error: {}\n" ++ normal, .{err});
        return error.CompilationError;
    };
    // std.debug.print(blue ++ "bytecode instructions: " ++ normal ++ "\n{}", .{module});
    const elf = codegen.create_elf(allocator, module) catch |err| {
        std.debug.print(red ++ "code generation error: {}\n" ++ normal, .{err});
        return error.CodeGenError;
    };
    return elf;
}

test {
    var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const test_dir = try std.fs.cwd().openDir("tests", .{ .iterate = true });
    var it = test_dir.iterateAssumeFirstIteration();
    var tmpdir = std.testing.tmpDir(.{});
    try tmpdir.dir.setAsCwd();
    defer tmpdir.cleanup();
    while (try it.next()) |entry| {
        if (!std.mem.endsWith(u8, entry.name, ".hgn")) continue;
        const file = try test_dir.readFileAlloc(allocator, entry.name, 640 * 1024);
        const basename = entry.name[0 .. entry.name.len - 4];
        const elf = try compileSource(allocator, file);
        try tmpdir.dir.writeFile(.{ .sub_path = basename, .data = elf, .flags = .{ .mode = 0o777 } });
        defer tmpdir.dir.deleteFile(basename) catch {};

        const inout_name = try std.fmt.allocPrint(allocator, "{s}.json", .{basename});
        const inoutfile = test_dir.openFile(inout_name, .{}) catch |err| switch (err) {
            error.FileNotFound => continue,
            else => return err,
        };
        var json_reader = std.json.reader(allocator, inoutfile.reader());
        const cases = try std.json.parseFromTokenSourceLeaky([]struct { stdin: []u8, stdout: []u8 }, allocator, &json_reader, .{});
        for (cases) |case| {
            var child: std.process.Child = .init(
                if (target.cpu.arch == .riscv64 and target.os.tag == .linux)
                    &.{basename}
                else
                    &.{ "qemu-riscv64", basename },
                allocator,
            );
            child.stdin_behavior = .Pipe;
            child.stdout_behavior = .Pipe;
            child.stderr_behavior = .Ignore;
            try child.spawn();
            try child.stdin.?.writeAll(case.stdin);
            const stdout = try child.stdout.?.readToEndAlloc(allocator, 640 * 1024);
            defer allocator.free(stdout);
            const term = try child.wait();
            try std.testing.expectEqualStrings(case.stdout, stdout);
            try std.testing.expectEqual(@TypeOf(term){ .Exited = 0 }, term);
        }
    }
}

fn HashMapFormatter(HashMap: type) type {
    return std.fmt.Formatter(struct {
        fn formatHashMap(
            hash_map: HashMap,
            comptime fmt: []const u8,
            options: std.fmt.FormatOptions,
            writer: anytype,
        ) !void {
            const k_fmt, const v_fmt = comptime blk: {
                var fmt_it = std.mem.splitScalar(u8, fmt, ',');
                const k_fmt = fmt_it.next() orelse "";
                const v_fmt = fmt_it.next() orelse "";
                break :blk .{ k_fmt, v_fmt };
            };
            _ = options;
            try writer.writeAll("{");
            var it = hash_map.iterator();
            var first = true;
            while (it.next()) |kv| {
                try writer.print(
                    "{s} {" ++ k_fmt ++ "}: {" ++ v_fmt ++ "}",
                    .{
                        if (first) "" else ",",
                        kv.key_ptr.*,
                        kv.value_ptr.*,
                    },
                );
                first = false;
            }
            try writer.writeAll(if (first) "}" else " }");
        }
    }.formatHashMap);
}

pub fn fmtHashMap(hash_map: anytype) HashMapFormatter(@TypeOf(hash_map)) {
    return .{ .data = hash_map };
}