use core::cell::Ref;
use url::Url;
use crate::{
collections::HashMap,
compiler::{
CompileOptions,
error::{
DetailedCompilerErrors, DetailedCompilerErrorsWithMaybeRichAst,
},
parse_datex_script_to_rich_ast_detailed_errors,
precompiler::precompiled_ast::RichAst,
},
runtime::{Runtime, cache::shared_references_cache::SharedReferencesCache},
types::r#type::Type,
};
pub struct WorkspaceFile {
pub url: Url,
pub content: String,
pub rich_ast: Option<RichAst>,
pub return_type: Option<Type>,
pub errors: Option<DetailedCompilerErrors>,
}
pub struct CompilerWorkspace {
files: HashMap<Url, WorkspaceFile>,
runtime: Runtime,
}
impl CompilerWorkspace {
pub fn new(runtime: Runtime) -> Self {
Self {
files: HashMap::new(),
runtime,
}
}
pub fn files(&self) -> &HashMap<Url, WorkspaceFile> {
&self.files
}
pub fn load_file(&mut self, url: Url, content: String) -> &WorkspaceFile {
let result = self.get_rich_ast_for_file(&url, content.clone());
let workspace_file = match result {
Ok(rich_ast) => WorkspaceFile {
url: url.clone(),
content,
rich_ast: Some(rich_ast),
return_type: None,
errors: None,
},
Err(error) => WorkspaceFile {
url: url.clone(),
content,
rich_ast: error.ast,
return_type: None,
errors: Some(error.errors),
},
};
self.files.insert(url.clone(), workspace_file);
self.files.get(&url).unwrap()
}
pub fn get_file(&self, url: &Url) -> Option<&WorkspaceFile> {
self.files.get(url)
}
pub fn get_file_mut(&mut self, url: &Url) -> Option<&mut WorkspaceFile> {
self.files.get_mut(url)
}
fn get_rich_ast_for_file(
&self,
_url: &Url,
content: String,
) -> Result<RichAst, DetailedCompilerErrorsWithMaybeRichAst> {
let mut options = CompileOptions::default();
let rich_ast = parse_datex_script_to_rich_ast_detailed_errors(
&content,
&mut options,
self.runtime.clone(),
)?;
Ok(rich_ast)
}
pub fn runtime(&self) -> &Runtime {
&self.runtime
}
pub fn memory(&self) -> Ref<'_, SharedReferencesCache> {
self.runtime.shared_references_cache_refcell().borrow()
}
}