charon_lib/
errors.rs

1//! Utilities to generate error reports about the external dependencies.
2use crate::ast::*;
3use crate::formatter::IntoFormatter;
4use crate::pretty::FmtWithCtx;
5pub use annotate_snippets::Level;
6use itertools::Itertools;
7use macros::VariantIndexArity;
8use petgraph::algo::dijkstra::dijkstra;
9use petgraph::prelude::DiGraphMap;
10use std::cmp::{Ord, PartialOrd};
11use std::collections::{HashMap, HashSet};
12
13#[macro_export]
14macro_rules! register_error {
15    ($ctx:expr, crate($krate:expr), $span: expr, $($fmt:tt)*) => {{
16        let msg = format!($($fmt)*);
17        $ctx.span_err($krate, $span, &msg, $crate::errors::Level::WARNING)
18    }};
19    ($ctx:expr, $span: expr, $($fmt:tt)*) => {{
20        let msg = format!($($fmt)*);
21        $ctx.span_err($span, &msg, $crate::errors::Level::WARNING)
22    }};
23}
24pub use register_error;
25
26/// Macro to either panic or return on error, depending on the CLI options
27#[macro_export]
28macro_rules! raise_error {
29    ($($tokens:tt)*) => {{
30        return Err(register_error!($($tokens)*));
31    }};
32}
33pub use raise_error;
34
35/// Custom assert to either panic or return an error
36#[macro_export]
37macro_rules! error_assert {
38    ($ctx:expr, $span: expr, $b: expr) => {
39        if !$b {
40            $crate::errors::raise_error!($ctx, $span, "assertion failure: {:?}", stringify!($b));
41        }
42    };
43    ($ctx:expr, $span: expr, $b: expr, $($fmt:tt)*) => {
44        if !$b {
45            $crate::errors::raise_error!($ctx, $span, $($fmt)*);
46        }
47    };
48}
49pub use error_assert;
50
51/// Custom assert to report an error and optionally panic
52#[macro_export]
53macro_rules! sanity_check {
54    ($ctx:expr, $span: expr, $b: expr) => {
55        if !$b {
56            $crate::errors::register_error!(
57                $ctx,
58                $span,
59                "assertion failure: {:?}",
60                stringify!($b)
61            );
62        }
63    };
64    ($ctx:expr, $span: expr, $b: expr, $($fmt:tt)*) => {
65        if !$b {
66            $crate::errors::register_error!($ctx, $span, $($fmt)*);
67        }
68    };
69}
70pub use sanity_check;
71
72/// Common error used during the translation.
73#[derive(Debug)]
74pub struct Error {
75    pub span: Span,
76    pub msg: String,
77}
78
79impl Error {
80    pub(crate) fn render(&self, krate: &TranslatedCrate, level: Level) -> String {
81        use annotate_snippets::*;
82        let span = self.span.span;
83
84        let mut group = Group::new();
85        let origin;
86        if let Some(file) = krate.files.get(span.file_id) {
87            origin = format!("{}", file.name);
88            if let Some(source) = &file.contents {
89                let snippet = Snippet::source(source)
90                    .origin(&origin)
91                    .fold(true)
92                    .annotation(AnnotationKind::Primary.span(span.to_byte_range(source)));
93                group = group.element(snippet);
94            } else {
95                // Show just the file and line/col.
96                let origin = Origin::new(&origin)
97                    .line(span.beg.line)
98                    .char_column(span.beg.col + 1)
99                    .primary(true);
100                group = group.element(origin);
101            }
102        }
103        let message = level.header(&self.msg).group(group);
104
105        Renderer::styled().render(message).to_string()
106    }
107}
108
109/// Display an error without a specific location.
110pub fn display_unspanned_error(level: Level, msg: &str) {
111    use annotate_snippets::*;
112    let message = level.header(msg);
113    let message = Renderer::styled().render(message).to_string();
114    anstream::eprintln!("{message}\n");
115}
116
117/// We use this to save the origin of an id. This is useful for the external
118/// dependencies, especially if some external dependencies don't extract:
119/// we use this information to tell the user what is the code which
120/// (transitively) lead to the extraction of those problematic dependencies.
121#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
122pub struct DepSource {
123    pub src_id: AnyTransId,
124    /// The location where the id was referred to. We store `None` for external dependencies as we
125    /// don't want to show these to the users.
126    pub span: Option<Span>,
127}
128
129/// For tracing error dependencies.
130#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, VariantIndexArity)]
131enum DepNode {
132    External(AnyTransId),
133    /// We use the span information only for local references
134    Local(AnyTransId, Span),
135}
136
137/// Graph of dependencies between erroring definitions and the definitions they came from.
138struct DepGraph {
139    dgraph: DiGraphMap<DepNode, ()>,
140}
141
142impl DepGraph {
143    fn new() -> Self {
144        DepGraph {
145            dgraph: DiGraphMap::new(),
146        }
147    }
148
149    fn insert_node(&mut self, n: DepNode) {
150        // We have to be careful about duplicate nodes
151        if !self.dgraph.contains_node(n) {
152            self.dgraph.add_node(n);
153        }
154    }
155
156    fn insert_edge(&mut self, from: DepNode, to: DepNode) {
157        self.insert_node(from);
158        self.insert_node(to);
159        if !self.dgraph.contains_edge(from, to) {
160            self.dgraph.add_edge(from, to, ());
161        }
162    }
163}
164
165impl std::fmt::Display for DepGraph {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
167        for (from, to, _) in self.dgraph.all_edges() {
168            writeln!(f, "{from:?} -> {to:?}")?
169        }
170        Ok(())
171    }
172}
173
174/// The context for tracking and reporting errors.
175pub struct ErrorCtx {
176    /// If true, do not abort on the first error and attempt to extract as much as possible.
177    pub continue_on_failure: bool,
178    /// If true, print the warnings as errors, and abort if any errors were raised.
179    pub error_on_warnings: bool,
180
181    /// The ids of the external_declarations for which extraction we encountered errors.
182    pub external_decls_with_errors: HashSet<AnyTransId>,
183    /// Graph of dependencies between items: there is an edge from item `a` to item `b` if `b`
184    /// registered the id for `a` during its translation. Because we only use this to report errors
185    /// on external items, we only record edges where `a` is an external item.
186    external_dep_graph: DepGraph,
187    /// The id of the definition we are exploring, used to track the source of errors.
188    pub def_id: Option<AnyTransId>,
189    /// Whether the definition being explored is local to the crate or not.
190    pub def_id_is_local: bool,
191    /// The number of errors encountered so far.
192    pub error_count: usize,
193}
194
195impl ErrorCtx {
196    pub fn new(continue_on_failure: bool, error_on_warnings: bool) -> Self {
197        Self {
198            continue_on_failure,
199            error_on_warnings,
200            external_decls_with_errors: HashSet::new(),
201            external_dep_graph: DepGraph::new(),
202            def_id: None,
203            def_id_is_local: false,
204            error_count: 0,
205        }
206    }
207
208    pub fn continue_on_failure(&self) -> bool {
209        self.continue_on_failure
210    }
211    pub fn has_errors(&self) -> bool {
212        self.error_count > 0
213    }
214
215    /// Report an error without registering anything.
216    pub fn display_error(
217        &self,
218        krate: &TranslatedCrate,
219        span: Span,
220        level: Level,
221        msg: String,
222    ) -> Error {
223        let error = Error { span, msg };
224        anstream::eprintln!("{}\n", error.render(krate, level));
225        error
226    }
227
228    /// Report and register an error.
229    pub fn span_err(
230        &mut self,
231        krate: &TranslatedCrate,
232        span: Span,
233        msg: &str,
234        level: Level,
235    ) -> Error {
236        let level = if level == Level::WARNING && self.error_on_warnings {
237            Level::ERROR
238        } else {
239            level
240        };
241        let err = self.display_error(krate, span, level, msg.to_string());
242        self.error_count += 1;
243        // If this item comes from an external crate, after the first error for that item we
244        // display where in the local crate that item was reached from.
245        if !self.def_id_is_local
246            && let Some(id) = self.def_id
247            && self.external_decls_with_errors.insert(id)
248        {
249            self.report_external_dep_error(krate, id);
250        }
251        if !self.continue_on_failure() {
252            panic!("{msg}");
253        }
254        err
255    }
256
257    /// Register the fact that `id` is a dependency of `src` (if `src` is not `None`).
258    pub fn register_dep_source(
259        &mut self,
260        src: &Option<DepSource>,
261        item_id: AnyTransId,
262        is_local: bool,
263    ) {
264        if let Some(src) = src
265            && src.src_id != item_id
266            && !is_local
267        {
268            let src_node = DepNode::External(item_id);
269            self.external_dep_graph.insert_node(src_node);
270
271            let tgt_node = match src.span {
272                Some(span) => DepNode::Local(src.src_id, span),
273                None => DepNode::External(src.src_id),
274            };
275            self.external_dep_graph.insert_edge(src_node, tgt_node)
276        }
277    }
278
279    /// In case errors happened when extracting the definitions coming from the external
280    /// dependencies, print a detailed report to explain to the user which dependencies were
281    /// problematic, and where they are used in the code.
282    pub fn report_external_dep_error(&self, krate: &TranslatedCrate, id: AnyTransId) {
283        use annotate_snippets::*;
284
285        // Use `Dijkstra's` algorithm to find the local items reachable from the current non-local
286        // item.
287        let graph = &self.external_dep_graph;
288        let reachable = dijkstra(&graph.dgraph, DepNode::External(id), None, |_| 1);
289        trace!("id: {:?}\nreachable:\n{:?}", id, reachable);
290
291        // Collect reachable local spans.
292        let by_file: HashMap<FileId, Vec<Span>> = reachable
293            .iter()
294            .filter_map(|(n, _)| match n {
295                DepNode::External(_) => None,
296                DepNode::Local(_, span) => Some(*span),
297            })
298            .into_group_map_by(|span| span.span.file_id);
299
300        // Collect to a `Vec` to be able to sort it and to borrow `origin` (needed by
301        // `Snippet::source`).
302        let mut by_file: Vec<(FileId, _, _, Vec<Span>)> = by_file
303            .into_iter()
304            .filter_map(|(file_id, mut spans)| {
305                spans.sort(); // Sort spans to display in file order
306                let file = krate.files.get(file_id)?;
307                let source = file.contents.as_ref()?;
308                let file_name = file.name.to_string();
309                Some((file_id, file_name, source, spans))
310            })
311            .collect();
312        // Sort by file id to avoid output instability.
313        by_file.sort_by_key(|(file_id, ..)| *file_id);
314
315        let level = Level::NOTE;
316        let snippets = by_file.iter().map(|(_, origin, source, spans)| {
317            Snippet::source(source)
318                .origin(&origin)
319                .fold(true)
320                .annotations(
321                    spans
322                        .iter()
323                        .map(|span| AnnotationKind::Context.span(span.span.to_byte_range(source))),
324                )
325        });
326
327        let msg = format!(
328            "the error occurred when translating `{}`, \
329             which is (transitively) used at the following location(s):",
330            id.with_ctx(&krate.into_fmt())
331        );
332        let message = level.header(&msg).group(Group::new().elements(snippets));
333        let out = Renderer::styled().render(message).to_string();
334        anstream::eprintln!("{}", out);
335    }
336}