Skip to main content

sway_core/
build_config.rs

1use itertools::Itertools;
2use serde::{Deserialize, Deserializer, Serialize};
3use std::{
4    collections::{BTreeMap, HashSet},
5    path::PathBuf,
6    sync::Arc,
7};
8use strum::{Display, EnumString};
9use sway_ir::{Options, PassManager};
10
11#[derive(
12    Clone,
13    Copy,
14    Debug,
15    Display,
16    Default,
17    Eq,
18    PartialEq,
19    Hash,
20    Serialize,
21    Deserialize,
22    clap::ValueEnum,
23    EnumString,
24)]
25pub enum BuildTarget {
26    #[default]
27    #[serde(rename = "fuel")]
28    #[clap(name = "fuel")]
29    #[strum(serialize = "fuel")]
30    Fuel,
31    #[serde(rename = "evm")]
32    #[clap(name = "evm")]
33    #[strum(serialize = "evm")]
34    EVM,
35}
36
37impl BuildTarget {
38    pub const CFG: &'static [&'static str] = &["evm", "fuel"];
39}
40
41#[derive(Default, Clone, Copy)]
42pub enum DbgGeneration {
43    Full,
44    #[default]
45    None,
46}
47
48#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Default)]
49pub enum OptLevel {
50    #[default]
51    Opt0 = 0,
52    Opt1 = 1,
53}
54
55impl<'de> serde::Deserialize<'de> for OptLevel {
56    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
57        let num = u8::deserialize(d)?;
58        match num {
59            0 => Ok(OptLevel::Opt0),
60            1 => Ok(OptLevel::Opt1),
61            _ => Err(serde::de::Error::custom(format!("invalid opt level {num}"))),
62        }
63    }
64}
65
66/// Which ASM to print.
67#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
68pub struct PrintAsm {
69    #[serde(rename = "virtual")]
70    pub virtual_abstract: bool,
71    #[serde(rename = "allocated")]
72    pub allocated_abstract: bool,
73    pub r#final: bool,
74}
75
76impl PrintAsm {
77    pub fn all() -> Self {
78        Self {
79            virtual_abstract: true,
80            allocated_abstract: true,
81            r#final: true,
82        }
83    }
84
85    pub fn none() -> Self {
86        Self::default()
87    }
88
89    pub fn abstract_virtual() -> Self {
90        Self {
91            virtual_abstract: true,
92            ..Self::default()
93        }
94    }
95
96    pub fn abstract_allocated() -> Self {
97        Self {
98            allocated_abstract: true,
99            ..Self::default()
100        }
101    }
102
103    pub fn r#final() -> Self {
104        Self {
105            r#final: true,
106            ..Self::default()
107        }
108    }
109}
110
111impl std::ops::BitOrAssign for PrintAsm {
112    fn bitor_assign(&mut self, rhs: Self) {
113        self.virtual_abstract |= rhs.virtual_abstract;
114        self.allocated_abstract |= rhs.allocated_abstract;
115        self.r#final |= rhs.r#final;
116    }
117}
118
119/// Which IR states to print.
120#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
121pub struct IrCli {
122    pub initial: bool,
123    pub r#final: bool,
124    #[serde(rename = "modified")]
125    pub modified_only: bool,
126    /// Whether to print the IR metadata (`!N = ...`) definitions block.
127    /// Opt in, as metadata is mostly not needed in the IR analysis and
128    /// produces a lot of clutter.
129    #[serde(rename = "print-md", default)]
130    pub print_metadata: bool,
131    pub passes: Vec<String>,
132}
133
134impl Default for IrCli {
135    fn default() -> Self {
136        Self {
137            initial: false,
138            r#final: false,
139            modified_only: true,   // Default option is more restrictive.
140            print_metadata: false, // Metadata is opt in.
141            passes: vec![],
142        }
143    }
144}
145
146impl IrCli {
147    pub fn all(modified_only: bool, print_metadata: bool) -> Self {
148        Self {
149            initial: true,
150            r#final: true,
151            modified_only,
152            print_metadata,
153            passes: PassManager::OPTIMIZATION_PASSES
154                .iter()
155                .map(|pass| pass.to_string())
156                .collect_vec(),
157        }
158    }
159
160    pub fn none() -> Self {
161        Self::default()
162    }
163
164    pub fn r#final() -> Self {
165        Self {
166            r#final: true,
167            ..Self::default()
168        }
169    }
170}
171
172impl std::ops::BitOrAssign for IrCli {
173    fn bitor_assign(&mut self, rhs: Self) {
174        self.initial |= rhs.initial;
175        self.r#final |= rhs.r#final;
176        // Both sides must request only passes that modify IR
177        // in order for `modified_only` to be true.
178        // Otherwise, displaying passes regardless if they
179        // are modified or not wins.
180        self.modified_only &= rhs.modified_only;
181        self.print_metadata |= rhs.print_metadata;
182        for pass in rhs.passes {
183            if !self.passes.contains(&pass) {
184                self.passes.push(pass);
185            }
186        }
187    }
188}
189
190impl From<&IrCli> for Options {
191    fn from(value: &IrCli) -> Self {
192        Self {
193            print_initial: value.initial,
194            print_final: value.r#final,
195            print_modified_only: value.modified_only,
196            print_metadata: value.print_metadata,
197            print_passes: HashSet::from_iter(value.passes.iter().cloned()),
198            ..Default::default()
199        }
200    }
201}
202
203#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Default)]
204#[serde(rename_all = "snake_case")]
205pub enum Backtrace {
206    All,
207    #[default]
208    AllExceptNever,
209    OnlyAlways,
210    None,
211}
212
213impl From<Backtrace> for sway_ir::Backtrace {
214    fn from(value: Backtrace) -> Self {
215        match value {
216            Backtrace::All => sway_ir::Backtrace::All,
217            Backtrace::AllExceptNever => sway_ir::Backtrace::AllExceptNever,
218            Backtrace::OnlyAlways => sway_ir::Backtrace::OnlyAlways,
219            Backtrace::None => sway_ir::Backtrace::None,
220        }
221    }
222}
223
224/// Configuration for the overall build and compilation process.
225#[derive(Clone)]
226pub struct BuildConfig {
227    // Build target for code generation.
228    pub(crate) build_target: BuildTarget,
229    pub(crate) dbg_generation: DbgGeneration,
230    // The canonical file path to the root module.
231    // E.g. `/home/user/project/src/main.sw`.
232    pub(crate) canonical_root_module: Arc<PathBuf>,
233    pub(crate) print_dca_graph: Option<String>,
234    pub(crate) print_dca_graph_url_format: Option<String>,
235    pub(crate) print_asm: PrintAsm,
236    pub(crate) print_bytecode: bool,
237    pub(crate) print_bytecode_spans: bool,
238    pub(crate) print_ir: IrCli,
239    pub(crate) include_tests: bool,
240    pub(crate) optimization_level: OptLevel,
241    pub(crate) backtrace: Backtrace,
242    pub time_phases: bool,
243    pub profile: bool,
244    pub metrics_outfile: Option<String>,
245    pub lsp_mode: Option<LspConfig>,
246}
247
248impl BuildConfig {
249    /// Construct a `BuildConfig` from a relative path to the root module and the canonical path to
250    /// the manifest directory.
251    ///
252    /// The `root_module` path must be either canonical, or relative to the directory containing
253    /// the manifest. E.g. `project/src/main.sw` or `project/src/lib.sw`.
254    ///
255    /// The `canonical_manifest_dir` must be the canonical (aka absolute) path to the directory
256    /// containing the `Forc.toml` file for the project. E.g. `/home/user/project`.
257    pub fn root_from_file_name_and_manifest_path(
258        root_module: PathBuf,
259        canonical_manifest_dir: PathBuf,
260        build_target: BuildTarget,
261        dbg_generation: DbgGeneration,
262    ) -> Self {
263        assert!(
264            canonical_manifest_dir.has_root(),
265            "manifest dir must be a canonical path",
266        );
267        let canonical_root_module = match root_module.has_root() {
268            true => root_module,
269            false => {
270                assert!(
271                    root_module.starts_with(canonical_manifest_dir.file_name().unwrap()),
272                    "file_name must be either absolute or relative to manifest directory",
273                );
274                canonical_manifest_dir
275                    .parent()
276                    .expect("unable to retrieve manifest directory parent")
277                    .join(&root_module)
278            }
279        };
280        Self {
281            build_target,
282            dbg_generation,
283            canonical_root_module: Arc::new(canonical_root_module),
284            print_dca_graph: None,
285            print_dca_graph_url_format: None,
286            print_asm: PrintAsm::default(),
287            print_bytecode: false,
288            print_bytecode_spans: false,
289            print_ir: IrCli::default(),
290            include_tests: false,
291            time_phases: false,
292            profile: false,
293            metrics_outfile: None,
294            optimization_level: OptLevel::default(),
295            backtrace: Backtrace::default(),
296            lsp_mode: None,
297        }
298    }
299
300    /// Dummy build config that can be used for testing.
301    /// This is not valid generally, but asm generation will accept it.
302    pub fn dummy_for_asm_generation() -> Self {
303        Self::root_from_file_name_and_manifest_path(
304            PathBuf::from("/"),
305            PathBuf::from("/"),
306            BuildTarget::default(),
307            DbgGeneration::None,
308        )
309    }
310
311    pub fn with_print_dca_graph(self, a: Option<String>) -> Self {
312        Self {
313            print_dca_graph: a,
314            ..self
315        }
316    }
317
318    pub fn with_print_dca_graph_url_format(self, a: Option<String>) -> Self {
319        Self {
320            print_dca_graph_url_format: a,
321            ..self
322        }
323    }
324
325    pub fn with_print_asm(self, print_asm: PrintAsm) -> Self {
326        Self { print_asm, ..self }
327    }
328
329    pub fn with_print_bytecode(self, bytecode: bool, bytecode_spans: bool) -> Self {
330        Self {
331            print_bytecode: bytecode,
332            print_bytecode_spans: bytecode_spans,
333            ..self
334        }
335    }
336
337    pub fn with_print_ir(self, a: IrCli) -> Self {
338        Self {
339            print_ir: a,
340            ..self
341        }
342    }
343
344    pub fn with_time_phases(self, a: bool) -> Self {
345        Self {
346            time_phases: a,
347            ..self
348        }
349    }
350
351    pub fn with_profile(self, a: bool) -> Self {
352        Self { profile: a, ..self }
353    }
354
355    pub fn with_metrics(self, a: Option<String>) -> Self {
356        Self {
357            metrics_outfile: a,
358            ..self
359        }
360    }
361
362    pub fn with_optimization_level(self, optimization_level: OptLevel) -> Self {
363        Self {
364            optimization_level,
365            ..self
366        }
367    }
368
369    pub fn with_backtrace(self, backtrace: Backtrace) -> Self {
370        Self { backtrace, ..self }
371    }
372
373    /// Whether or not to include test functions in parsing, type-checking and codegen.
374    ///
375    /// This should be set to `true` by invocations like `forc test` or `forc check --tests`.
376    ///
377    /// Default: `false`
378    pub fn with_include_tests(self, include_tests: bool) -> Self {
379        Self {
380            include_tests,
381            ..self
382        }
383    }
384
385    pub fn with_lsp_mode(self, lsp_mode: Option<LspConfig>) -> Self {
386        Self { lsp_mode, ..self }
387    }
388
389    pub fn canonical_root_module(&self) -> Arc<PathBuf> {
390        self.canonical_root_module.clone()
391    }
392}
393
394#[derive(Clone, Debug, Default)]
395pub struct LspConfig {
396    // This is set to true if compilation was triggered by a didChange LSP event. In this case, we
397    // bypass collecting type metadata and skip DCA.
398    //
399    // This is set to false if compilation was triggered by a didSave or didOpen LSP event.
400    pub optimized_build: bool,
401    // The value of the `version` field in the `DidChangeTextDocumentParams` struct.
402    // This is used to determine if the file has been modified since the last compilation.
403    pub file_versions: BTreeMap<PathBuf, Option<u64>>,
404}
405
406#[cfg(test)]
407mod test {
408    use super::*;
409    #[test]
410    fn test_root_from_file_name_and_manifest_path() {
411        let root_module = PathBuf::from("mock_path/src/main.sw");
412        let canonical_manifest_dir = PathBuf::from("/tmp/sway_project/mock_path");
413        BuildConfig::root_from_file_name_and_manifest_path(
414            root_module,
415            canonical_manifest_dir,
416            BuildTarget::default(),
417            DbgGeneration::Full,
418        );
419    }
420
421    #[test]
422    fn test_root_from_file_name_and_manifest_path_contains_dot() {
423        let root_module = PathBuf::from("mock_path_contains_._dot/src/main.sw");
424        let canonical_manifest_dir = PathBuf::from("/tmp/sway_project/mock_path_contains_._dot");
425        BuildConfig::root_from_file_name_and_manifest_path(
426            root_module,
427            canonical_manifest_dir,
428            BuildTarget::default(),
429            DbgGeneration::Full,
430        );
431    }
432}