From 362fc7e3efbef6ba0e2e0ac20807cb35d0ac52f5 Mon Sep 17 00:00:00 2001 From: Luna Date: Fri, 27 Sep 2019 15:12:30 -0300 Subject: [PATCH] analysis: add name type resolution this only adds resolution for the types. for the actual metadata, such as e.g parameters, that isn't available, so codegen isn't helped by this. --- examples/hello.ry | 3 +-- src/analysis.zig | 6 +++++- src/comp_ctx.zig | 39 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 44 insertions(+), 4 deletions(-) diff --git a/examples/hello.ry b/examples/hello.ry index 0d93592..9be2bf2 100644 --- a/examples/hello.ry +++ b/examples/hello.ry @@ -43,8 +43,7 @@ fn multwo(num: i32, double_flag: bool) i32 { } fn multwo_with_one(b: i32) i32 { - // TODO replace by b - return multwo(2, false) + 2; + return multwo(b, false) + b; } fn add(a: i32, b: i32) i32 { diff --git a/src/analysis.zig b/src/analysis.zig index e9cbf26..f3471d8 100644 --- a/src/analysis.zig +++ b/src/analysis.zig @@ -275,7 +275,11 @@ pub const TypeSolver = struct { return func_sym.return_type; }, - // TODO analysis for .Variable + .Variable => |vari| { + // TODO maybe we can modify vari and add the current scope + // it was found for codegen purposes + return try ctx.resolveVarType(vari.lexeme); + }, .Get => |get| { var target = get.target.*; diff --git a/src/comp_ctx.zig b/src/comp_ctx.zig index 749a518..431eb92 100644 --- a/src/comp_ctx.zig +++ b/src/comp_ctx.zig @@ -1,7 +1,10 @@ const std = @import("std"); const ast = @import("ast.zig"); -pub const CompilationError = error{TypeError}; +pub const CompilationError = error{ + TypeError, + UnknownName, +}; pub const SymbolTable = std.hash_map.StringHashMap(SymbolData); pub const TypeList = std.ArrayList(SymbolUnderlyingType); @@ -289,4 +292,38 @@ pub const CompilationContext = struct { return sym_kv.?.value; } + + fn resolveVarTypeInScope( + self: *@This(), + scope_opt: ?*Scope, + name: []const u8, + ) ?SymbolUnderlyingType { + if (scope_opt == null) return null; + var scope = scope_opt.?; + + var kv_opt = scope.env.get(name); + if (kv_opt) |kv| { + // TODO maybe return the scope it was found in + return kv.value; + } else { + return self.resolveVarTypeInScope(scope.parent, name); + } + } + + fn resolveVarType(self: *@This(), name: []const u8) !SymbolUnderlyingType { + var var_type: ?SymbolUnderlyingType = null; + + if (self.current_scope) |scope| { + var_type = self.resolveVarTypeInScope(scope, name); + if (var_type) |typ| return typ; + } + + if (self.cur_function) |cur_function| { + var kv_opt = cur_function.parameters.get(name); + if (kv_opt) |kv| return kv.value; + } + + std.debug.warn("Unknown name {}\n", name); + return CompilationError.UnknownName; + } };