TypeChecker

This commit is contained in:
2026-03-17 14:04:14 +01:00
parent 677521ca98
commit 69c254382d
3 changed files with 76 additions and 17 deletions

View File

@@ -1,4 +1,4 @@
use std::{collections::HashMap, fmt::Write}; use std::{cell::RefCell, collections::HashMap, fmt::Write, rc::Rc};
use crate::{ use crate::{
analyzer::Analyzer, analyzer::Analyzer,
@@ -77,17 +77,17 @@ pub struct CodegenX86_64 {
data_section: String, data_section: String,
label_counter: usize, label_counter: usize,
data_counter: usize, data_counter: usize,
pub analyzer: Analyzer, pub analyzer: Rc<RefCell<Analyzer>>,
} }
impl CodegenX86_64 { impl CodegenX86_64 {
pub fn new() -> CodegenX86_64 { pub fn new(analyzer: Rc<RefCell<Analyzer>>) -> CodegenX86_64 {
CodegenX86_64 { CodegenX86_64 {
output: String::new(), output: String::new(),
data_section: String::new(), data_section: String::new(),
label_counter: 0, label_counter: 0,
data_counter: 1, data_counter: 1,
analyzer: Analyzer::new(), analyzer,
} }
} }
@@ -571,11 +571,11 @@ _builtin_environ:
} }
} }
Expr::Variable(name) => { Expr::Variable(name) => {
if self.analyzer.constants.contains_key(&name.lexeme) { if self.analyzer.borrow().constants.contains_key(&name.lexeme) {
emit!( emit!(
&mut self.output, &mut self.output,
" mov rax, {}", " mov rax, {}",
self.analyzer.constants[&name.lexeme] self.analyzer.borrow().constants[&name.lexeme]
); );
} else { } else {
// TODO: move to analyzer // TODO: move to analyzer
@@ -677,7 +677,12 @@ _builtin_environ:
} }
if let Expr::Variable(callee_name) = &**callee { if let Expr::Variable(callee_name) = &**callee {
if self.analyzer.functions.contains_key(&callee_name.lexeme) { if self
.analyzer
.borrow()
.functions
.contains_key(&callee_name.lexeme)
{
// its a function (defined/builtin/extern) // its a function (defined/builtin/extern)
emit!(&mut self.output, " call {}", callee_name.lexeme); emit!(&mut self.output, " call {}", callee_name.lexeme);
} else { } else {
@@ -720,7 +725,7 @@ _builtin_environ:
} }
Expr::AddrOf { op, expr } => match *expr.clone() { Expr::AddrOf { op, expr } => match *expr.clone() {
Expr::Variable(name) => { Expr::Variable(name) => {
if self.analyzer.functions.contains_key(&name.lexeme) { if self.analyzer.borrow().functions.contains_key(&name.lexeme) {
emit!(&mut self.output, " mov rax, {}", name.lexeme); emit!(&mut self.output, " mov rax, {}", name.lexeme);
} else { } else {
let var = match env.get_var(&name.lexeme) { let var = match env.get_var(&name.lexeme) {
@@ -744,7 +749,7 @@ _builtin_environ:
} }
}, },
Expr::New(struct_name) => { Expr::New(struct_name) => {
let struct_fields = &self.analyzer.structs[&struct_name.lexeme]; let struct_fields = &self.analyzer.borrow().structs[&struct_name.lexeme];
// TODO: panic on mem.alloc error // TODO: panic on mem.alloc error
let memory_size = struct_fields.len() * 8; let memory_size = struct_fields.len() * 8;
@@ -769,7 +774,7 @@ _builtin_environ:
if BUILTIN_TYPES.contains(&name) { if BUILTIN_TYPES.contains(&name) {
return true; return true;
} }
if self.analyzer.structs.contains_key(name) { if self.analyzer.borrow().structs.contains_key(name) {
return true; return true;
} }
false false
@@ -796,7 +801,8 @@ _builtin_environ:
} }
}; };
let fields = match self.analyzer.structs.get(&struct_name) { let analyzer = self.analyzer.borrow();
let fields = match analyzer.structs.get(&struct_name) {
Some(f) => f, Some(f) => f,
None => { None => {
return error!(&field.loc, format!("unknown struct type: {}", struct_name)); return error!(&field.loc, format!("unknown struct type: {}", struct_name));

View File

@@ -2,11 +2,14 @@ mod analyzer;
mod codegen_x86_64; mod codegen_x86_64;
mod parser; mod parser;
mod tokenizer; mod tokenizer;
mod typechecker;
use std::{ use std::{
cell::RefCell,
fs, fs,
path::Path, path::Path,
process::{self, Command}, process::{self, Command},
rc::Rc,
}; };
use tokenizer::ZernError; use tokenizer::ZernError;
@@ -14,10 +17,12 @@ use tokenizer::ZernError;
use clap::Parser; use clap::Parser;
macro_rules! compile_std { macro_rules! compile_std {
($codegen:expr, $( $name:literal ),* $(,)? ) => { ($codegen:expr, $typechecker:expr, $analyzer:expr, $( $name:literal ),* $(,)? ) => {
$( $(
compile_file_to( compile_file_to(
$codegen, $codegen,
$typechecker,
$analyzer,
$name, $name,
include_str!(concat!("std/", $name)).into() include_str!(concat!("std/", $name)).into()
)?; )?;
@@ -27,6 +32,8 @@ macro_rules! compile_std {
fn compile_file_to( fn compile_file_to(
codegen: &mut codegen_x86_64::CodegenX86_64, codegen: &mut codegen_x86_64::CodegenX86_64,
typechecker: &mut typechecker::TypeChecker,
analyzer: Rc<RefCell<analyzer::Analyzer>>,
filename: &str, filename: &str,
source: String, source: String,
) -> Result<(), ZernError> { ) -> Result<(), ZernError> {
@@ -37,11 +44,15 @@ fn compile_file_to(
let statements = parser.parse()?; let statements = parser.parse()?;
for stmt in &statements { for stmt in &statements {
codegen.analyzer.register_function(stmt)?; analyzer.borrow_mut().register_function(stmt)?;
} }
for stmt in &statements { for stmt in &statements {
codegen.analyzer.analyze_stmt(stmt)?; analyzer.borrow_mut().analyze_stmt(stmt)?;
}
for stmt in &statements {
typechecker.typecheck_stmt(stmt)?;
} }
for stmt in statements { for stmt in statements {
@@ -73,10 +84,21 @@ fn compile_file(args: Args) -> Result<(), ZernError> {
let filename = Path::new(&args.path).file_name().unwrap().to_str().unwrap(); let filename = Path::new(&args.path).file_name().unwrap().to_str().unwrap();
let mut codegen = codegen_x86_64::CodegenX86_64::new(); let analyzer = Rc::new(RefCell::new(analyzer::Analyzer::new()));
let mut typechecker = typechecker::TypeChecker::new(analyzer.clone());
let mut codegen = codegen_x86_64::CodegenX86_64::new(analyzer.clone());
codegen.emit_prologue(args.use_gcc)?; codegen.emit_prologue(args.use_gcc)?;
compile_std!(&mut codegen, "syscalls.zr", "std.zr", "net.zr"); compile_std!(
compile_file_to(&mut codegen, filename, source)?; &mut codegen,
&mut typechecker,
analyzer.clone(),
"syscalls.zr",
"std.zr",
"net.zr"
);
compile_file_to(&mut codegen, &mut typechecker, analyzer, filename, source)?;
if !args.output_asm { if !args.output_asm {
let out = args.out.unwrap_or_else(|| "out".into()); let out = args.out.unwrap_or_else(|| "out".into());

31
src/typechecker.rs Normal file
View File

@@ -0,0 +1,31 @@
use std::{cell::RefCell, rc::Rc};
use crate::{
analyzer::Analyzer,
parser::{Expr, Stmt},
tokenizer::ZernError,
};
pub struct TypeChecker {
analyzer: Rc<RefCell<Analyzer>>,
}
type Type = String;
impl TypeChecker {
pub fn new(analyzer: Rc<RefCell<Analyzer>>) -> TypeChecker {
TypeChecker { analyzer }
}
pub fn typecheck_stmt(&mut self, stmt: &Stmt) -> Result<(), ZernError> {
match stmt {
_ => todo!(),
}
}
pub fn typecheck_expr(&mut self, expr: &Expr) -> Result<Type, ZernError> {
match expr {
_ => todo!(),
}
}
}