Skip to main content

antlr_rust_codegen/
artifact.rs

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