repos / lc3vm.zig.git


commit
2fd0f08
parent
2fd0f08
author
Evgenii Akentev
date
2025-11-01 20:17:50 +0400 +04
Little Computer 3 in Zig
5 files changed,  +501, -0
A .gitignore
+23, -0
 1@@ -0,0 +1,23 @@
 2+# This file is for zig-specific build artifacts.
 3+# If you have OS-specific or editor-specific files to ignore,
 4+# such as *.swp or .DS_Store, put those in your global
 5+# ~/.gitignore and put this in your ~/.gitconfig:
 6+#
 7+# [core]
 8+#     excludesfile = ~/.gitignore
 9+#
10+# Cheers!
11+# -andrewrk
12+
13+.zig-cache/
14+zig-out/
15+/release/
16+/debug/
17+/build/
18+/build-*/
19+/docgen_tmp/
20+
21+# Although this was renamed to .zig-cache, let's leave it here for a few
22+# releases to make it less annoying to work with multiple branches.
23+zig-cache/
24+
A build.zig
+156, -0
  1@@ -0,0 +1,156 @@
  2+const std = @import("std");
  3+
  4+// Although this function looks imperative, it does not perform the build
  5+// directly and instead it mutates the build graph (`b`) that will be then
  6+// executed by an external runner. The functions in `std.Build` implement a DSL
  7+// for defining build steps and express dependencies between them, allowing the
  8+// build runner to parallelize the build automatically (and the cache system to
  9+// know when a step doesn't need to be re-run).
 10+pub fn build(b: *std.Build) void {
 11+    // Standard target options allow the person running `zig build` to choose
 12+    // what target to build for. Here we do not override the defaults, which
 13+    // means any target is allowed, and the default is native. Other options
 14+    // for restricting supported target set are available.
 15+    const target = b.standardTargetOptions(.{});
 16+    // Standard optimization options allow the person running `zig build` to select
 17+    // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
 18+    // set a preferred release mode, allowing the user to decide how to optimize.
 19+    const optimize = b.standardOptimizeOption(.{});
 20+    // It's also possible to define more custom flags to toggle optional features
 21+    // of this build script using `b.option()`. All defined flags (including
 22+    // target and optimize options) will be listed when running `zig build --help`
 23+    // in this directory.
 24+
 25+    // This creates a module, which represents a collection of source files alongside
 26+    // some compilation options, such as optimization mode and linked system libraries.
 27+    // Zig modules are the preferred way of making Zig code available to consumers.
 28+    // addModule defines a module that we intend to make available for importing
 29+    // to our consumers. We must give it a name because a Zig package can expose
 30+    // multiple modules and consumers will need to be able to specify which
 31+    // module they want to access.
 32+    const mod = b.addModule("lc3-vm_zig", .{
 33+        // The root source file is the "entry point" of this module. Users of
 34+        // this module will only be able to access public declarations contained
 35+        // in this file, which means that if you have declarations that you
 36+        // intend to expose to consumers that were defined in other files part
 37+        // of this module, you will have to make sure to re-export them from
 38+        // the root file.
 39+        .root_source_file = b.path("src/root.zig"),
 40+        // Later on we'll use this module as the root module of a test executable
 41+        // which requires us to specify a target.
 42+        .target = target,
 43+    });
 44+
 45+    // Here we define an executable. An executable needs to have a root module
 46+    // which needs to expose a `main` function. While we could add a main function
 47+    // to the module defined above, it's sometimes preferable to split business
 48+    // business logic and the CLI into two separate modules.
 49+    //
 50+    // If your goal is to create a Zig library for others to use, consider if
 51+    // it might benefit from also exposing a CLI tool. A parser library for a
 52+    // data serialization format could also bundle a CLI syntax checker, for example.
 53+    //
 54+    // If instead your goal is to create an executable, consider if users might
 55+    // be interested in also being able to embed the core functionality of your
 56+    // program in their own executable in order to avoid the overhead involved in
 57+    // subprocessing your CLI tool.
 58+    //
 59+    // If neither case applies to you, feel free to delete the declaration you
 60+    // don't need and to put everything under a single module.
 61+    const exe = b.addExecutable(.{
 62+        .name = "lc3-vm_zig",
 63+        .root_module = b.createModule(.{
 64+            // b.createModule defines a new module just like b.addModule but,
 65+            // unlike b.addModule, it does not expose the module to consumers of
 66+            // this package, which is why in this case we don't have to give it a name.
 67+            .root_source_file = b.path("src/main.zig"),
 68+            // Target and optimization levels must be explicitly wired in when
 69+            // defining an executable or library (in the root module), and you
 70+            // can also hardcode a specific target for an executable or library
 71+            // definition if desireable (e.g. firmware for embedded devices).
 72+            .target = target,
 73+            .optimize = optimize,
 74+            // List of modules available for import in source files part of the
 75+            // root module.
 76+            .imports = &.{
 77+                // Here "lc3-vm_zig" is the name you will use in your source code to
 78+                // import this module (e.g. `@import("lc3-vm_zig")`). The name is
 79+                // repeated because you are allowed to rename your imports, which
 80+                // can be extremely useful in case of collisions (which can happen
 81+                // importing modules from different packages).
 82+                .{ .name = "lc3-vm_zig", .module = mod },
 83+            },
 84+        }),
 85+    });
 86+
 87+    // This declares intent for the executable to be installed into the
 88+    // install prefix when running `zig build` (i.e. when executing the default
 89+    // step). By default the install prefix is `zig-out/` but can be overridden
 90+    // by passing `--prefix` or `-p`.
 91+    b.installArtifact(exe);
 92+
 93+    // This creates a top level step. Top level steps have a name and can be
 94+    // invoked by name when running `zig build` (e.g. `zig build run`).
 95+    // This will evaluate the `run` step rather than the default step.
 96+    // For a top level step to actually do something, it must depend on other
 97+    // steps (e.g. a Run step, as we will see in a moment).
 98+    const run_step = b.step("run", "Run the app");
 99+
100+    // This creates a RunArtifact step in the build graph. A RunArtifact step
101+    // invokes an executable compiled by Zig. Steps will only be executed by the
102+    // runner if invoked directly by the user (in the case of top level steps)
103+    // or if another step depends on it, so it's up to you to define when and
104+    // how this Run step will be executed. In our case we want to run it when
105+    // the user runs `zig build run`, so we create a dependency link.
106+    const run_cmd = b.addRunArtifact(exe);
107+    run_step.dependOn(&run_cmd.step);
108+
109+    // By making the run step depend on the default step, it will be run from the
110+    // installation directory rather than directly from within the cache directory.
111+    run_cmd.step.dependOn(b.getInstallStep());
112+
113+    // This allows the user to pass arguments to the application in the build
114+    // command itself, like this: `zig build run -- arg1 arg2 etc`
115+    if (b.args) |args| {
116+        run_cmd.addArgs(args);
117+    }
118+
119+    // Creates an executable that will run `test` blocks from the provided module.
120+    // Here `mod` needs to define a target, which is why earlier we made sure to
121+    // set the releative field.
122+    const mod_tests = b.addTest(.{
123+        .root_module = mod,
124+    });
125+
126+    // A run step that will run the test executable.
127+    const run_mod_tests = b.addRunArtifact(mod_tests);
128+
129+    // Creates an executable that will run `test` blocks from the executable's
130+    // root module. Note that test executables only test one module at a time,
131+    // hence why we have to create two separate ones.
132+    const exe_tests = b.addTest(.{
133+        .root_module = exe.root_module,
134+    });
135+
136+    // A run step that will run the second test executable.
137+    const run_exe_tests = b.addRunArtifact(exe_tests);
138+
139+    // A top level step for running all tests. dependOn can be called multiple
140+    // times and since the two run steps do not depend on one another, this will
141+    // make the two of them run in parallel.
142+    const test_step = b.step("test", "Run tests");
143+    test_step.dependOn(&run_mod_tests.step);
144+    test_step.dependOn(&run_exe_tests.step);
145+
146+    // Just like flags, top level steps are also listed in the `--help` menu.
147+    //
148+    // The Zig build system is entirely implemented in userland, which means
149+    // that it cannot hook into private compiler APIs. All compilation work
150+    // orchestrated by the build system will result in other Zig compiler
151+    // subcommands being invoked with the right flags defined. You can observe
152+    // these invocations when one fails (or you pass a flag to increase
153+    // verbosity) to validate assumptions and diagnose problems.
154+    //
155+    // Lastly, the Zig build system is relatively simple and self-contained,
156+    // and reading its source code will allow you to master it.
157+}
A build.zig.zon
+81, -0
 1@@ -0,0 +1,81 @@
 2+.{
 3+    // This is the default name used by packages depending on this one. For
 4+    // example, when a user runs `zig fetch --save <url>`, this field is used
 5+    // as the key in the `dependencies` table. Although the user can choose a
 6+    // different name, most users will stick with this provided value.
 7+    //
 8+    // It is redundant to include "zig" in this name because it is already
 9+    // within the Zig package namespace.
10+    .name = .arithvm_zig,
11+    // This is a [Semantic Version](https://semver.org/).
12+    // In a future version of Zig it will be used for package deduplication.
13+    .version = "0.0.0",
14+    // Together with name, this represents a globally unique package
15+    // identifier. This field is generated by the Zig toolchain when the
16+    // package is first created, and then *never changes*. This allows
17+    // unambiguous detection of one package being an updated version of
18+    // another.
19+    //
20+    // When forking a Zig project, this id should be regenerated (delete the
21+    // field and run `zig build`) if the upstream project is still maintained.
22+    // Otherwise, the fork is *hostile*, attempting to take control over the
23+    // original project's identity. Thus it is recommended to leave the comment
24+    // on the following line intact, so that it shows up in code reviews that
25+    // modify the field.
26+    .fingerprint = 0x79da8ce1ed863de0, // Changing this has security and trust implications.
27+    // Tracks the earliest Zig version that the package considers to be a
28+    // supported use case.
29+    .minimum_zig_version = "0.15.1",
30+    // This field is optional.
31+    // Each dependency must either provide a `url` and `hash`, or a `path`.
32+    // `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
33+    // Once all dependencies are fetched, `zig build` no longer requires
34+    // internet connectivity.
35+    .dependencies = .{
36+        // See `zig fetch --save <url>` for a command-line interface for adding dependencies.
37+        //.example = .{
38+        //    // When updating this field to a new URL, be sure to delete the corresponding
39+        //    // `hash`, otherwise you are communicating that you expect to find the old hash at
40+        //    // the new URL. If the contents of a URL change this will result in a hash mismatch
41+        //    // which will prevent zig from using it.
42+        //    .url = "https://example.com/foo.tar.gz",
43+        //
44+        //    // This is computed from the file contents of the directory of files that is
45+        //    // obtained after fetching `url` and applying the inclusion rules given by
46+        //    // `paths`.
47+        //    //
48+        //    // This field is the source of truth; packages do not come from a `url`; they
49+        //    // come from a `hash`. `url` is just one of many possible mirrors for how to
50+        //    // obtain a package matching this `hash`.
51+        //    //
52+        //    // Uses the [multihash](https://multiformats.io/multihash/) format.
53+        //    .hash = "...",
54+        //
55+        //    // When this is provided, the package is found in a directory relative to the
56+        //    // build root. In this case the package's hash is irrelevant and therefore not
57+        //    // computed. This field and `url` are mutually exclusive.
58+        //    .path = "foo",
59+        //
60+        //    // When this is set to `true`, a package is declared to be lazily
61+        //    // fetched. This makes the dependency only get fetched if it is
62+        //    // actually used.
63+        //    .lazy = false,
64+        //},
65+    },
66+    // Specifies the set of files and directories that are included in this package.
67+    // Only files and directories listed here are included in the `hash` that
68+    // is computed for this package. Only files listed here will remain on disk
69+    // when using the zig package manager. As a rule of thumb, one should list
70+    // files required for compilation plus any license(s).
71+    // Paths are relative to the build root. Use the empty string (`""`) to refer to
72+    // the build root itself.
73+    // A directory listed here means that all files within, recursively, are included.
74+    .paths = .{
75+        "build.zig",
76+        "build.zig.zon",
77+        "src",
78+        // For example...
79+        //"LICENSE",
80+        //"README.md",
81+    },
82+}
A src/main.zig
+20, -0
 1@@ -0,0 +1,20 @@
 2+const std = @import("std");
 3+const lc3vm_zig = @import("lc3-vm_zig");
 4+
 5+pub fn main() !void {
 6+    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); 
 7+    defer arena.deinit();
 8+
 9+    var memory = &lc3vm_zig.memory;
10+
11+    memory[0x3000] = 0xF026;    //  1111 0000 0010 0110             TRAP trp_in_u16  ;read an uint16_t from stdin and put it in R0
12+    memory[0x3002] = 0x1220;    //  0001 0010 0010 0000             ADD R1,R0,x0     ;add contents of R0 to R1
13+    memory[0x3003] = 0xF026;    //  1111 0000 0010 0110             TRAP trp_in_u16  ;read an uint16_t from stdin and put it in R0
14+    memory[0x3004] = 0x1240;    //  0001 0010 0010 0000             ADD R1,R1,R0     ;add contents of R0 to R1
15+    memory[0x3006] = 0x1060;    //  0001 0000 0110 0000             ADD R0,R1,x0     ;add contents of R1 to R0
16+    memory[0x3007] = 0xF027;    //  1111 0000 0010 0111             TRAP trp_out_u16;show the contents of R0 to stdout
17+    memory[0x3008] = 0xF025;    //  1111 0000 0010 0101             HALT             ;halt
18+
19+    try lc3vm_zig.start(arena.allocator(), 0);
20+}
21+
A src/root.zig
+221, -0
  1@@ -0,0 +1,221 @@
  2+//! By convention, root.zig is the root source file when making a library.
  3+const std = @import("std");
  4+
  5+// Implementation of the Little Computer 3 following
  6+// https://www.andreinc.net/2021/12/01/writing-a-simple-vm-in-less-than-125-lines-of-c
  7+
  8+const pcStart: u16 = 0x3000;
  9+const u16Max: u32 = 65535;
 10+pub var memory: [u16Max + 1]u16 = .{0} ** (u16Max + 1);
 11+var running: bool = true;
 12+
 13+inline fn mr(address: u16) u16 { return memory[address]; }
 14+
 15+inline fn mw(address: u16, value: u16) void {
 16+    memory[address] = value;
 17+}
 18+
 19+const Register = enum(u16) {
 20+    R0 = 0,
 21+    R1 = 1,
 22+    R2 = 2,
 23+    R3 = 3,
 24+    R4 = 4,
 25+    R5 = 5,
 26+    R6 = 6,
 27+    R7 = 7,
 28+    RPC = 8,
 29+    RCND = 9,
 30+    RCNT = 10
 31+};
 32+
 33+var registers: [11]u16 = .{0} ** 11;
 34+
 35+// The instruction fits into u16:
 36+//
 37+// [ OP CODE ][ PARAM1 ][ PARAM2 ][ ][ PARAM3 ]
 38+// [ 4 bits  ][          12 bits              ]
 39+
 40+const Opcode = enum {
 41+    br, // conditional
 42+    add, // addition
 43+    ld, // load RPC + offset
 44+    st, // store
 45+    jsr, // jump to subroutine
 46+    andop, // bitwise and
 47+    ldr, // load base + offset
 48+    str, // store base + offset
 49+    rti, // return from interrupt
 50+    not, // bitwise complement
 51+    ldi, // load indirect
 52+    sti, // store indirect
 53+    jmp, // jump/return to subroutine
 54+    unused, // unused opcode
 55+    lea, // load effective address
 56+    trap, // system trap/call
 57+
 58+    pub fn parse(instruction: u16) Opcode {
 59+        // shift 12 bits to the right to get first 4 bits
 60+        return @enumFromInt(instruction >> 12);
 61+    }
 62+};
 63+
 64+const TrapFunc = enum {
 65+    tgetc, tout, tputs, tin, tputsp, thalt, tinu16, toutu16,
 66+
 67+    pub fn parse(n: u16) TrapFunc {
 68+        return @enumFromInt(n);
 69+    }
 70+};
 71+
 72+const Flag = enum(u16) {
 73+    FP = (1 << 0),
 74+    FZ = (1 << 1),
 75+    FN = (1 << 2),
 76+};
 77+
 78+inline fn uf(r: u16) void {
 79+    if (registers[r] == 0) { registers[@intFromEnum(Register.RCND)] = @intFromEnum(Flag.FZ); }
 80+    else if ((registers[r] >> 15) == 1) { registers[@intFromEnum(Register.RCND)] = @intFromEnum(Flag.FN); }
 81+    else registers[@intFromEnum(Register.RCND)] = @intFromEnum(Flag.FP);
 82+}
 83+
 84+inline fn fcnd(instruction: u16) u16 { return (instruction >> 9) & 0x7; }
 85+inline fn dr(instruction: u16) u16 { return (instruction >> 9) & 0x7; }
 86+inline fn sr1(instruction: u16) u16 { return(instruction >> 6) & 0x7; }
 87+inline fn sr2(instruction: u16) u16 { return (instruction) & 0x7; }
 88+inline fn imm(instruction: u16) u16 { return (instruction) & 0x1F; }
 89+inline fn fimm(instruction: u16) u16 { return (instruction >> 5) & 1; }
 90+
 91+inline fn sext(n: u16, b: u32) u16 {
 92+    return if ((n >> (b - 1)) & 1 == 1) @truncate(@as(u32, n) | (0xFFFF << b)) else n;
 93+}
 94+
 95+//  0000 0000 0001 0110 <--- a in binary
 96+//  1111 1111 1111 0110 <--- sextimm(a) in binary
 97+inline fn sextimm(instruction: u16) u16 { return sext(imm(instruction), 5); }
 98+
 99+inline fn poff(instruction: u16) u16 { return sext(instruction & 0x3F, 6); }
100+inline fn poff9(instruction: u16) u16 { return sext(instruction & 0x1FF, 9); }
101+inline fn poff11(instruction: u16) u16 { return sext(instruction & 0x7FF, 11); }
102+inline fn fl(instruction: u16) u16 { return (instruction >> 11) & 1; }
103+inline fn br(instruction: u16) u16 { return (instruction >> 6) & 0x7; }
104+inline fn trp(instruction: u16) u16 { return instruction & 0xFF; }
105+
106+pub fn evaluate(allocator: std.mem.Allocator, i: u16) !void {
107+    switch (Opcode.parse(i)) {
108+        inline .add => {
109+            registers[dr(i)] = registers[sr1(i)] +
110+                if (fimm(i) == 1)
111+                    sextimm(i)
112+                else registers[sr2(i)];
113+            uf(dr(i));
114+        },
115+        inline .andop => {
116+            registers[dr(i)] = registers[sr1(i)] & (if (fimm(i) == 1) (sextimm(i)) else registers[sr2(i)]);
117+            uf(dr(i));
118+        },
119+        inline .ld => {
120+            registers[dr(i)] = mr(registers[@intFromEnum(Register.RPC)] + poff9(i));
121+            uf(dr(i));
122+        },
123+        inline .ldi => {
124+            registers[dr(i)] = mr(mr(registers[@intFromEnum(Register.RPC)] + poff9(i)));
125+            uf(dr(i));
126+        },
127+        inline .ldr => {
128+            registers[dr(i)] = mr(registers[sr1(i)] + poff(i));
129+            uf(dr(i));
130+        },
131+        inline .lea => {
132+            registers[dr(i)] = registers[@intFromEnum(Register.RPC)] + poff9(i);
133+            uf(dr(i));
134+        },
135+        inline .not => {
136+            registers[dr(i)] = ~ registers[sr1(i)];
137+            uf(dr(i));
138+        },
139+        inline .st => {
140+            mw(registers[@intFromEnum(Register.RPC)] + poff9(i), registers[dr(i)]);
141+        },
142+        inline .sti => {
143+            mw(mr(registers[@intFromEnum(Register.RPC)] + poff9(i)), registers[dr(i)]);
144+        },
145+        inline .str => {
146+            mw(registers[sr1(i)] + poff(i), registers[dr(i)]);
147+        },
148+        inline .jmp => {
149+            registers[@intFromEnum(Register.RPC)] = registers[br(i)];
150+        },
151+        inline .jsr => {
152+            registers[@intFromEnum(Register.R7)] = registers[@intFromEnum(Register.RPC)];
153+            registers[@intFromEnum(Register.RPC)] = if (fl(i) == 1) (registers[@intFromEnum(Register.RPC)] + poff11(i)) else registers[br(i)];
154+        },
155+        inline .br => {
156+            if (registers[@intFromEnum(Register.RCND)] & fcnd(i) == 1) {
157+                registers[@intFromEnum(Register.RPC)] += poff9(i);
158+            }
159+        },
160+        inline .unused, .rti => {
161+        },
162+        inline .trap => {
163+            switch (TrapFunc.parse(trp(i) - 0x20)) {
164+                inline .tgetc => {
165+                    const dest: []u8 = try allocator.alloc(u8, 1); 
166+                    _ = try std.fs.File.stdin().read(dest);
167+                    registers[@intFromEnum(Register.R0)] = dest[0];
168+                },
169+                inline .tout => {
170+                    std.debug.print("{}", .{ registers[@intFromEnum(Register.R0)] });
171+                },
172+                inline .tputs => {
173+                },
174+                inline .tin => {
175+                    const buffer: []u8 = try allocator.alloc(u8, 1024); 
176+                    defer allocator.free(buffer);
177+
178+                    var stdin = std.fs.File.stdin().reader(buffer).interface;
179+                    const m = try stdin.takeInt(u8, .little);
180+                    registers[@intFromEnum(Register.R0)] = m;
181+                },
182+                inline .thalt => {
183+                    running = false;
184+                },
185+                inline .tinu16 => {
186+                    const buffer: []u8 = try allocator.alloc(u8, 1024); 
187+                    defer allocator.free(buffer);
188+
189+                    var line_buffer: []u8 = try allocator.alloc(u8, 1024); 
190+                    defer allocator.free(line_buffer);
191+                    var writer: std.io.Writer = .fixed(line_buffer);
192+                    
193+                    var stdin = std.fs.File.stdin().reader(buffer).interface;
194+
195+                    const line_length = try stdin.streamDelimiterLimit(&writer, '\n', .unlimited);
196+                    const v: u16 = try std.fmt.parseInt(u16, line_buffer[0..line_length], 10);
197+                    registers[@intFromEnum(Register.R0)] = v;
198+                },
199+                inline .tputsp => {
200+                },
201+                inline .toutu16 => {
202+                    const buffer: []u8 = try allocator.alloc(u8, 1024); 
203+                    defer allocator.free(buffer);
204+
205+                    const v: u16 = registers[@intFromEnum(Register.R0)]; 
206+                    std.debug.print("{}\n", .{ v });
207+                },
208+            }
209+        }
210+    }
211+}
212+
213+pub fn start(allocator: std.mem.Allocator, offset: u16) !void {
214+    registers[@intFromEnum(Register.RPC)] = pcStart + offset;
215+    while (running) {
216+        const instruction = mr(registers[@intFromEnum(Register.RPC)]);
217+        registers[@intFromEnum(Register.RPC)] += 1;
218+
219+        try evaluate(allocator, instruction);
220+    }
221+}
222+