Skip to main content

waveless_compiler/
compiler_cx.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4use crate::*;
5
6#[derive(Constructor, Getters, Debug)]
7#[getset(get = "pub")]
8pub struct CompilerCx {
9    project: project::Project,
10    workspace_root: PathBuf,
11}
12
13impl CompilerCx {
14    pub fn acquire() -> &'static Self {
15        COMPILER_CX
16            .get()
17            .ok_or(eyre!("Compiler context should have been initialized."))
18            .unwrap()
19    }
20
21    /// Sets the [`COMPILER_CX`]'s `OnceLock`.
22    /// NOTE: If compiler's context is set this method will panic.
23    pub fn set_cx(self) {
24        if !COMPILER_CX.initialized() {
25            COMPILER_CX.set(self).unwrap();
26        } else {
27            panic!("Compiler context has already been initialized.");
28        }
29    }
30
31    /// Builds the compiler's context by loading the project
32    /// from the workspace's root.
33    pub async fn from_workspace() -> Result<Self> {
34        let workspace_root = get_workspace_root("project.toml")?;
35
36        match read(workspace_root.join("project.toml")) {
37            Ok(file_buffer) => match toml::from_slice::<project::Project>(&file_buffer) {
38                Ok(project) => Ok(Self::new(project, workspace_root)),
39                Err(err) => Err(err).wrap_err("Cannot deserialize the `project.toml` file."),
40            },
41            Err(err) => Err(err)
42                .wrap_err("Cannot open the `project.toml` file.")
43                .suggestion("Are you sure that you are in the project's folder?"),
44        }
45    }
46}