Skip to content

Commit

Permalink
Add MIT License and improve memory for imports
Browse files Browse the repository at this point in the history
  • Loading branch information
Luukdegram committed Aug 23, 2020
1 parent 71a974a commit 3bba48e
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 21 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Luuk de Gram

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
27 changes: 14 additions & 13 deletions src/compiler.zig
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub fn compile(

var root_scope = Compiler.Scope{
.symbols = Compiler.SymbolTable.init(allocator),
.id = .root,
.id = .global,
.allocator = &arena.allocator,
};
defer root_scope.symbols.deinit();
Expand Down Expand Up @@ -83,26 +83,26 @@ pub const Compiler = struct {
/// Hashmap of `Symbol` where the key is the Symbol's name
const SymbolTable = std.StringHashMap(Symbol);

/// Scope of the current state (function, root, etc)
/// Scope of the current state (function, global, etc)
const Scope = struct {
/// Symbols that exist within the current scope
symbols: SymbolTable,
/// Type of the Scope. i.e. Root, function, etc
id: Tag,
/// If not a root scope, the scope will own a parent
/// If not a global scope, the scope will own a parent
parent: ?*Scope = null,
allocator: *Allocator,

/// The type of the scope
const Id = enum {
root,
global,
function,
loop,
};

/// Some `Scope` types can have a payload
const Tag = union(Id) {
root,
global,
function: void,
loop: struct {
start: u16,
Expand All @@ -117,7 +117,7 @@ pub const Compiler = struct {
new_scope.* = .{
.symbols = SymbolTable.init(self.allocator),
.id = switch (id) {
.root => .{ .root = {} },
.global => .{ .global = {} },
.function => .{ .function = {} },
.loop => .{ .loop = .{ .start = 0, .breaks = std.ArrayList(*bytecode.Instruction).init(self.allocator) } },
},
Expand All @@ -128,8 +128,9 @@ pub const Compiler = struct {
}

/// Defines a new symbol and saves it in the symbol table
/// Returns an error if Symbol already exists
fn define(self: *Scope, name: []const u8, mutable: bool) Error!Symbol {
if (self.resolve(name)) |s| return s;
if (self.resolve(name)) |_| return Error.CompilerError;
const index = self.symbols.items().len;

const symbol = Symbol{
Expand Down Expand Up @@ -230,7 +231,7 @@ pub const Compiler = struct {

/// Sets the current `Scope` to its parent's scope and cleans up the closing scope's memory
fn exitScope(self: *Compiler) void {
if (self.scope.id == .root) return; // can't escape the root scope
if (self.scope.id == .global) return; // can't escape the global scope
if (self.scope.parent) |parent| {
const old = self.scope;
self.scope = parent;
Expand All @@ -248,7 +249,7 @@ pub const Compiler = struct {
fn resolveSymbol(self: *Compiler, scope: *const Scope, name: []const u8) ?Symbol {
return if (scope.resolve(name)) |symbol|
symbol
else if (scope.id != .root and scope.parent != null)
else if (scope.id != .global and scope.parent != null)
self.resolveSymbol(scope.parent.?, name)
else
null;
Expand Down Expand Up @@ -347,7 +348,7 @@ pub const Compiler = struct {

try self.compile(decl.value);

const opcode: bytecode.Opcode = if (symbol.scope == .root)
const opcode: bytecode.Opcode = if (symbol.scope == .global)
.bind_global
else
.bind_local;
Expand All @@ -356,7 +357,7 @@ pub const Compiler = struct {
},
.identifier => |id| if (self.resolveSymbol(self.scope, id.value)) |symbol| {
const opcode: bytecode.Opcode = switch (symbol.scope) {
.root => .load_global,
.global => .load_global,
.function, .loop => .load_local,
};
_ = try self.emitOp(opcode, symbol.index);
Expand Down Expand Up @@ -500,7 +501,7 @@ pub const Compiler = struct {

// point the end jump to last op
self.instructions.items[end_jump].ptr = @intCast(u16, end);

self.exitScope();
},
.assignment => |asg| {
Expand All @@ -511,7 +512,7 @@ pub const Compiler = struct {

try self.compile(asg.right);

if (symbol.scope == .root)
if (symbol.scope == .global)
_ = try self.emitOp(.assign_global, symbol.index)
else
_ = try self.emitOp(.assign_local, symbol.index);
Expand Down
33 changes: 25 additions & 8 deletions src/vm.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const Allocator = std.mem.Allocator;
//! The Virtual Machine of Luf is stack-based.
//! Currently the stack has a size of 2048 (pre-allocated)

/// Creates a new Virtual Machine on the stack, runs the given `ByteCode`
/// Creates a new Virtual Machine on the heap, runs the given `ByteCode`
/// and finally returns the `Vm`. Use deinit() to free its memory.
pub fn run(code: ByteCode, allocator: *Allocator) Vm.Error!*Vm {
//TODO cleanup this mess once we have implemented a garbage collector
Expand All @@ -24,10 +24,11 @@ pub fn run(code: ByteCode, allocator: *Allocator) Vm.Error!*Vm {
.allocator = allocator,
.arena = arena,
.call_stack = Vm.CallStack.init(allocator),
.imports = std.StringHashMap(*Value).init(allocator),
};

try vm.call_stack.append(.{
.fp = undefined,
.fp = null,
.sp = 0,
.ip = 0,
.instructions = code.instructions,
Expand All @@ -51,16 +52,20 @@ pub const Vm = struct {
/// Globals that live inside the VM
/// Currently allows 65536 Values
globals: Value.List,
/// Call stack that contains the instruction and stack pointer, as well as the instructions
/// to run the stack
call_stack: CallStack,
/// Modules that were imported
imports: std.StringHashMap(*Value),
allocator: *Allocator,
arena: std.heap.ArenaAllocator,
call_stack: CallStack,

pub const Error = error{ OutOfMemory, OutOfBounds, MissingValue, InvalidOperator } || BuiltinError;
const CallStack = std.ArrayList(Frame);
/// Function `Frame` on the callstack
const Frame = struct {
/// Frame pointer which contains the actual function `Value`
fp: *const Value,
fp: ?*const Value,
/// `Instruction` pointer to the position of the function in the bytecode's instruction set
ip: usize,
/// Stack pointer. Mostly used to reset the stack pointer between scope changes
Expand All @@ -75,6 +80,7 @@ pub const Vm = struct {
self.globals.deinit();
self.arena.deinit();
self.call_stack.deinit();
self.imports.deinit();
self.allocator.destroy(self);
}

Expand Down Expand Up @@ -682,15 +688,16 @@ pub const Vm = struct {
defer self.allocator.free(source);

// we should probably save this bytecode so we can free it at a later point
var code = compiler.compile(&self.arena.allocator, source) catch {
var code = compiler.compile(self.allocator, source) catch {
return Error.InvalidOperator;
};
defer code.deinit();

const last_ip = self.ip;
const last_sp = self.sp;

try self.call_stack.append(.{
.fp = undefined, //TODO make this optional for safety
.fp = null,
.sp = 0,
.ip = 0,
.instructions = code.instructions,
Expand All @@ -703,12 +710,18 @@ pub const Vm = struct {
try attributes.ensureCapacity(code.symbols.items().len);
for (code.symbols.items()) |entry, i| {
const symbol: compiler.Compiler.Symbol = entry.value;
std.debug.assert(symbol.scope == .root);
std.debug.assert(symbol.scope == .global);

const name = try self.newValue();
name.* = .{ .string = try self.arena.allocator.dupe(u8, symbol.name) };
const value = try self.newValue();
value.* = code.constants[symbol.index];

// Create a copy of the function instructions as we're free'ing all compiler memory on scope exit
if (value.isType(.function)) {
value.function.instructions = try self.arena.allocator.dupe(byte_code.Instruction, value.function.instructions);
}

attributes.putAssumeCapacityNoClobber(name, value);
}

Expand All @@ -723,7 +736,11 @@ pub const Vm = struct {
const name = self.pop().?;
if (!name.isType(.string)) return Error.InvalidOperator;

const mod = try self.importModule(name.string);
const mod = self.imports.get(name.string) orelse blk: {
const imp = try self.importModule(name.string);
try self.imports.put(name.string, imp);
break :blk imp;
};

const ret = try self.newValue();
ret.* = .{
Expand Down

0 comments on commit 3bba48e

Please sign in to comment.