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