Skip to content

Commit

Permalink
Transitioned to PathStorage for paths
Browse files Browse the repository at this point in the history
  • Loading branch information
Robert-M-Lucas committed Aug 7, 2024
1 parent 3a58515 commit 7dde459
Show file tree
Hide file tree
Showing 20 changed files with 434 additions and 108 deletions.
29 changes: 25 additions & 4 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file modified build/out.out
Binary file not shown.
2 changes: 1 addition & 1 deletion main.why
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std/linked_list;
use std/linked_list.why;


fn main() -> int {
Expand Down
3 changes: 0 additions & 3 deletions parse_test.why

This file was deleted.

18 changes: 12 additions & 6 deletions src/root.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::root::compiler::compile::compile;
use crate::root::errors::WErr;
use crate::root::errors::{WErr, WErrContext};
use crate::root::name_resolver::resolve::resolve;
use crate::root::parser::parse::parse;
use crate::root::runner::{assemble, link_gcc, run};
Expand All @@ -13,6 +13,7 @@ use std::fs::File;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::time::Instant;
use crate::root::parser::path_storage::PathStorage;

#[cfg(debug_assertions)]
pub const DEBUG_ON_ERROR: bool = false;
Expand Down Expand Up @@ -53,7 +54,7 @@ pub fn main() {
}
}

pub fn main_args(args: Args) -> Result<(), WErr> {
pub fn main_args(args: Args) -> Result<(), String> {
if let Some(path) = PathBuf::from(&args.output).parent() {
if let Err(e) = fs::create_dir_all(path) {
if !matches!(e.kind(), ErrorKind::AlreadyExists) {
Expand All @@ -63,19 +64,24 @@ pub fn main_args(args: Args) -> Result<(), WErr> {
}
}

print!("Parsing... ");

print!("Parsing files... ");
time!(
let parsed = parse(PathBuf::from(&args.input))?;
let mut path_storage = PathStorage::new(&args.input).unwrap(); // TODO:
let toplevel_tokens = parse(&mut path_storage)
.map_err(|e| e.with_context(&path_storage).to_string())?;
);

print!("Resolving Names... ");
time!(
let (global_table, unprocessed_functions) = resolve(parsed)?;
let (global_table, unprocessed_functions) = resolve(toplevel_tokens)
.map_err(|e| e.with_context(&path_storage).to_string())?;
);

print!("Compiling... ");
time!(
let assembly = compile(global_table, unprocessed_functions)?;
let assembly = compile(global_table, unprocessed_functions, &path_storage)
.map_err(|e| e.with_context(&path_storage).to_string())?;
);

print!("Writing Assembly... ");
Expand Down
4 changes: 3 additions & 1 deletion src/root/compiler/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,23 @@ use crate::root::compiler::global_tracker::GlobalTracker;
use crate::root::errors::WErr;
use crate::root::name_resolver::name_resolvers::GlobalDefinitionTable;
use crate::root::parser::parse_function::FunctionToken;
use crate::root::parser::path_storage::PathStorage;
use crate::root::shared::common::FunctionID;
use crate::root::unrandom::{new_hashmap, new_hashset};

/// Compiles the entire program. Returns assembly.
pub fn compile(
mut global_table: GlobalDefinitionTable,
unprocessed_functions: HashMap<FunctionID, FunctionToken>,
path_storage: &PathStorage
) -> Result<String, WErr> {
let mut unprocessed_functions = unprocessed_functions;
let mut compiled_functions = new_hashmap();
let mut compiled_len = 0usize;

let mut open_set = new_hashset();
open_set.insert(FunctionID(0)); // Start with main
let mut global_tracker = GlobalTracker::default();
let mut global_tracker = GlobalTracker::new(path_storage);

while !open_set.is_empty() {
global_tracker.reset_functions();
Expand Down
6 changes: 5 additions & 1 deletion src/root/compiler/compile_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,11 @@ fn recursively_compile_lines(
contents.line("ret");

if line_i != lines.len() - 1 {
warn(&format!("Return isn't the last instruction in the block. Following lines in block will not be compiled/run.\n{}", rt.location().clone().into_warning()))
warn(
&format!("Return isn't the last instruction in the block. Following lines in block will not be compiled/run.\n{}",
rt.location().clone().into_warning().with_context(global_tracker.path_storage())
)
)
}
break;
}
Expand Down
18 changes: 15 additions & 3 deletions src/root/compiler/global_tracker.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
use crate::root::shared::common::FunctionID;
use derive_getters::{Dissolve, Getters};
use std::collections::HashSet;
use crate::root::parser::path_storage::PathStorage;

/// Tracks data between function compilations
#[derive(Default, Dissolve, Getters)]
pub struct GlobalTracker {
#[derive(Dissolve, Getters)]
pub struct GlobalTracker<'a> {
path_storage: &'a PathStorage,
function_calls: HashSet<FunctionID>,
readonly_contents: HashSet<String>,
readonly_data_section: String,
unique_tag_counter: usize,
}

impl GlobalTracker {
impl<'a> GlobalTracker<'a> {
pub fn new(path_storage: &'a PathStorage) -> GlobalTracker {
GlobalTracker {
path_storage,
function_calls: Default::default(),
readonly_contents: Default::default(),
readonly_data_section: "".to_string(),
unique_tag_counter: 0,
}
}

pub fn functions_mut(&mut self) -> &mut HashSet<FunctionID> {
&mut self.function_calls
}
Expand Down
33 changes: 26 additions & 7 deletions src/root/errors/mod.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
use crate::root::parser::location::Location;
use crate::root::parser::location::{ErrorL, Location, LocationTyped};
#[cfg(debug_assertions)]
use crate::root::DEBUG_ON_ERROR;
use color_print::cformat;
#[cfg(debug_assertions)]
use std::backtrace::Backtrace;
use std::fmt::{Display, Formatter};
use crate::root::parser::path_storage::PathStorage;

pub mod evaluable_errors;
pub mod name_resolver_errors;
pub mod parser_errors;


/// Universal error for Whython-8
#[derive(Debug)]
pub struct WErr {
error: String,
location: Option<Location>, // ! Important, don't do file reads unless necessary (i.e. Display)
Expand All @@ -27,8 +30,8 @@ impl WErr {
};
#[cfg(debug_assertions)]
if DEBUG_ON_ERROR {
println!("WErr created:");
println!("{}", Backtrace::capture());
println!("\n{w}");
}
w
}
Expand All @@ -43,8 +46,8 @@ impl WErr {
};
#[cfg(debug_assertions)]
if DEBUG_ON_ERROR {
println!("WErr created:");
println!("{}", Backtrace::capture());
println!("\n{w}");
}
Err(w)
}
Expand All @@ -64,15 +67,31 @@ impl WErr {
location: None,
}
}
}

impl Display for WErr {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
pub fn with_context<'a>(&'a self, path_storage: &'a PathStorage) -> WErrContext {
WErrContext {
err: self,
path_storage,
}
}

fn fmt(&self, f: &mut Formatter<'_>, path_storage: &PathStorage) -> std::fmt::Result {
let text = if let Some(location) = &self.location {
cformat!("<r,bold>Error:</>\n {}\n{}\n", self.error, location)
cformat!("<r,bold>Error:</>\n {}\n{}\n", self.error, location.with_context(path_storage))
} else {
cformat!("<r,bold>Error:</>\n {}", self.error)
};
f.write_str(&text)
}
}

pub struct WErrContext<'a> {
err: &'a WErr,
path_storage: &'a PathStorage
}

impl<'a> Display for WErrContext<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.err.fmt(f, self.path_storage)
}
}
23 changes: 12 additions & 11 deletions src/root/name_resolver/name_resolvers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use crate::root::POINTER_SIZE;
use std::collections::HashMap;
use std::path::PathBuf;
use std::rc::Rc;
use crate::root::parser::path_storage::FileID;

#[derive(Debug)]
enum NameTreeEntry {
Expand All @@ -45,16 +46,16 @@ impl NameTree {
/// Top level of tree containing all named objects/functions/types
#[derive(Default)]
struct TopLevelNameTree {
table: HashMap<Rc<PathBuf>, NameTree>,
table: HashMap<FileID, NameTree>,
}

impl TopLevelNameTree {
pub fn get_tree_mut(&mut self, path: Rc<PathBuf>) -> &mut NameTree {
if !self.table.contains_key(&path) {
self.table.insert(path.clone(), Default::default());
pub fn get_tree_mut(&mut self, file_id: FileID) -> &mut NameTree {
if !self.table.contains_key(&file_id) {
self.table.insert(file_id, Default::default());
}

self.table.get_mut(&path).unwrap()
self.table.get_mut(&file_id).unwrap()
}
}

Expand Down Expand Up @@ -161,7 +162,7 @@ impl GlobalDefinitionTable {
// TODO
let file_level_tree = self
.name_table
.get_tree_mut(st.location().path().unwrap().clone());
.get_tree_mut(st.location().file_id().unwrap());
self.id_counter += 1;
let id = TypeID(self.id_counter - 1);

Expand Down Expand Up @@ -196,7 +197,7 @@ impl GlobalDefinitionTable {
// TODO
let file_level_tree = self
.name_table
.get_tree_mut(ft.location().path().unwrap().clone());
.get_tree_mut(ft.location().file_id().unwrap());
file_level_tree.add_entry(ft.name().name().clone(), NameTreeEntry::Function(id));
}

Expand Down Expand Up @@ -275,7 +276,7 @@ impl GlobalDefinitionTable {
// TODO
if let Some(r) = process_tree(
self.name_table
.get_tree_mut(full_name.location().path().unwrap().clone()),
.get_tree_mut(full_name.location().file_id().unwrap()),
) {
return r;
}
Expand All @@ -284,7 +285,7 @@ impl GlobalDefinitionTable {
.name_table
.table
.iter()
.filter(|(p, _)| *p != full_name.location().path().unwrap())
.filter(|(p, _)| **p != full_name.location().file_id().unwrap())
{
if let Some(r) = process_tree(tree) {
return r;
Expand Down Expand Up @@ -401,7 +402,7 @@ impl GlobalDefinitionTable {
// TODO
if let Some(r) = process_tree(
self.name_table
.get_tree_mut(name.location().path().unwrap().clone()),
.get_tree_mut(name.location().file_id().unwrap()),
) {
return r;
}
Expand All @@ -411,7 +412,7 @@ impl GlobalDefinitionTable {
.name_table
.table
.iter()
.filter(|(p, _)| *p != name.location().path().unwrap())
.filter(|(p, _)| **p != name.location().file_id().unwrap())
{
if let Some(r) = process_tree(tree) {
return r;
Expand Down
Loading

0 comments on commit 7dde459

Please sign in to comment.