Skip to main content

antlr_rust_codegen/
artifact.rs

1use std::collections::{BTreeMap, BTreeSet, btree_map::Entry};
2use std::fs;
3use std::io;
4use std::path::{Component, Path, PathBuf};
5
6/// Inventory returned by a completed generation.
7#[derive(Clone, Debug, Eq, PartialEq)]
8pub struct Generation {
9    inputs: Vec<PathBuf>,
10    outputs: Vec<PathBuf>,
11    warnings: Vec<String>,
12}
13
14impl Generation {
15    pub(crate) const fn new(
16        inputs: Vec<PathBuf>,
17        outputs: Vec<PathBuf>,
18        warnings: Vec<String>,
19    ) -> Self {
20        Self {
21            inputs,
22            outputs,
23            warnings,
24        }
25    }
26
27    /// Canonical paths of every grammar, token vocabulary, and semantic-pattern file read.
28    pub fn inputs(&self) -> &[PathBuf] {
29        &self.inputs
30    }
31
32    /// Paths written or confirmed current by this generation.
33    pub fn outputs(&self) -> &[PathBuf] {
34        &self.outputs
35    }
36
37    /// Non-fatal compiler and transform diagnostics in CLI display form.
38    pub fn warnings(&self) -> &[String] {
39        &self.warnings
40    }
41
42    /// Emits Cargo rebuild directives for the complete resolved input graph.
43    #[allow(clippy::print_stdout)]
44    pub fn emit_rerun_if_changed(&self) {
45        for input in &self.inputs {
46            println!("cargo::rerun-if-changed={}", input.display());
47        }
48    }
49}
50
51#[derive(Debug, Default)]
52pub(crate) struct GeneratedArtifacts {
53    files: BTreeMap<PathBuf, Vec<u8>>,
54    remove_if_present: BTreeSet<PathBuf>,
55}
56
57impl GeneratedArtifacts {
58    pub(crate) fn insert(
59        &mut self,
60        path: impl Into<PathBuf>,
61        contents: impl Into<Vec<u8>>,
62    ) -> io::Result<()> {
63        let path = path.into();
64        validate_relative_path(&path)?;
65        match self.files.entry(path.clone()) {
66            Entry::Vacant(entry) => {
67                entry.insert(contents.into());
68                self.remove_if_present.remove(&path);
69                Ok(())
70            }
71            Entry::Occupied(_) => Err(io::Error::new(
72                io::ErrorKind::InvalidInput,
73                format!("generated artifact collision: {}", path.display()),
74            )),
75        }
76    }
77
78    pub(crate) fn remove_if_present(&mut self, path: impl Into<PathBuf>) -> io::Result<()> {
79        let path = path.into();
80        validate_relative_path(&path)?;
81        if !self.files.contains_key(&path) {
82            self.remove_if_present.insert(path);
83        }
84        Ok(())
85    }
86
87    pub(crate) fn write_to(self, output_directory: &Path) -> io::Result<Vec<PathBuf>> {
88        fs::create_dir_all(output_directory)?;
89        let mut outputs = Vec::with_capacity(self.files.len());
90        for (relative, contents) in self.files {
91            let path = output_directory.join(&relative);
92            if let Some(parent) = path.parent() {
93                fs::create_dir_all(parent)?;
94            }
95            let unchanged = fs::read(&path).is_ok_and(|existing| existing == contents);
96            if !unchanged {
97                fs::write(&path, contents)?;
98            }
99            outputs.push(path);
100        }
101        for relative in self.remove_if_present {
102            let path = output_directory.join(relative);
103            match fs::remove_file(path) {
104                Ok(()) => {}
105                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
106                Err(error) => return Err(error),
107            }
108        }
109        Ok(outputs)
110    }
111}
112
113fn validate_relative_path(path: &Path) -> io::Result<()> {
114    if path.as_os_str().is_empty()
115        || path
116            .components()
117            .any(|component| !matches!(component, Component::Normal(_)))
118    {
119        return Err(io::Error::new(
120            io::ErrorKind::InvalidInput,
121            format!(
122                "generated artifact path must stay below the output directory: {}",
123                path.display()
124            ),
125        ));
126    }
127    Ok(())
128}