charon_lib/
errors.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
//! Utilities to generate error reports about the external dependencies.
use crate::ast::{AnyTransId, Span};
use std::cmp::{Ord, PartialOrd};
use std::collections::{HashMap, HashSet};

/// Common error used during the translation.
#[derive(Debug)]
pub struct Error {
    pub span: Span,
    pub msg: String,
}

#[macro_export]
macro_rules! register_error_or_panic {
    ($ctx:expr, $span: expr, $msg: expr) => {{
        $ctx.span_err($span, &$msg);
        if !$ctx.continue_on_failure() {
            panic!("{}", $msg);
        }
    }};
}
pub use register_error_or_panic;

/// Macro to either panic or return on error, depending on the CLI options
#[macro_export]
macro_rules! error_or_panic {
    ($ctx:expr, $span:expr, $msg:expr) => {{
        $crate::errors::register_error_or_panic!($ctx, $span, $msg);
        let e = $crate::errors::Error {
            span: $span,
            msg: $msg.to_string(),
        };
        return Err(e);
    }};
}
pub use error_or_panic;

/// Custom assert to either panic or return an error
#[macro_export]
macro_rules! error_assert {
    ($ctx:expr, $span: expr, $b: expr) => {
        if !$b {
            let msg = format!("assertion failure: {:?}", stringify!($b));
            $crate::errors::error_or_panic!($ctx, $span, msg);
        }
    };
    ($ctx:expr, $span: expr, $b: expr, $msg: expr) => {
        if !$b {
            $crate::errors::error_or_panic!($ctx, $span, $msg);
        }
    };
}
pub use error_assert;

/// We use this to save the origin of an id. This is useful for the external
/// dependencies, especially if some external dependencies don't extract:
/// we use this information to tell the user what is the code which
/// (transitively) lead to the extraction of those problematic dependencies.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct DepSource {
    pub src_id: AnyTransId,
    /// The location where the id was referred to. We store `None` for external dependencies as we
    /// don't want to show these to the users.
    pub span: Option<Span>,
}

/// The context for tracking and reporting errors.
pub struct ErrorCtx<'ctx> {
    /// If true, do not abort on the first error and attempt to extract as much as possible.
    pub continue_on_failure: bool,
    /// If true, print the warnings as errors, and abort if any errors were raised.
    pub error_on_warnings: bool,

    /// The compiler session, used for displaying errors.
    #[cfg(feature = "rustc")]
    pub dcx: rustc_errors::DiagCtxtHandle<'ctx>,
    #[cfg(not(feature = "rustc"))]
    pub dcx: &'ctx (),
    /// The ids of the external_declarations for which extraction we encountered errors.
    pub external_decls_with_errors: HashSet<AnyTransId>,
    /// The ids of the declarations we completely failed to extract and had to ignore.
    pub ignored_failed_decls: HashSet<AnyTransId>,
    /// For each external item, a list of locations that point to it. See [DepSource].
    pub external_dep_sources: HashMap<AnyTransId, HashSet<DepSource>>,
    /// The id of the definition we are exploring, used to track the source of errors.
    pub def_id: Option<AnyTransId>,
    /// Whether the definition being explored is local to the crate or not.
    pub def_id_is_local: bool,
    /// The number of errors encountered so far.
    pub error_count: usize,
}

impl ErrorCtx<'_> {
    pub fn continue_on_failure(&self) -> bool {
        self.continue_on_failure
    }
    pub(crate) fn has_errors(&self) -> bool {
        self.error_count > 0
    }

    /// Report an error without registering anything.
    #[cfg(feature = "rustc")]
    pub fn span_err_no_register(
        &self,
        span: impl Into<rustc_error_messages::MultiSpan>,
        msg: &str,
    ) {
        let msg = msg.to_string();
        if self.error_on_warnings {
            self.dcx.span_err(span, msg);
        } else {
            self.dcx.span_warn(span, msg);
        }
    }
    #[cfg(not(feature = "rustc"))]
    pub(crate) fn span_err_no_register(&self, _span: Span, msg: &str) {
        let msg = msg.to_string();
        if self.error_on_warnings {
            error!("{}", msg);
        } else {
            warn!("{}", msg);
        }
    }

    /// Report and register an error.
    pub fn span_err(&mut self, span: Span, msg: &str) {
        self.span_err_no_register(span, msg);
        self.error_count += 1;
        if let Some(id) = self.def_id
            && !self.def_id_is_local
        {
            let _ = self.external_decls_with_errors.insert(id);
        }
    }

    pub fn ignore_failed_decl(&mut self, id: AnyTransId) {
        self.ignored_failed_decls.insert(id);
    }
}

impl ErrorCtx<'_> {
    /// In case errors happened when extracting the definitions coming from
    /// the external dependencies, print a detailed report to explain
    /// to the user which dependencies were problematic, and where they
    /// are used in the code.
    #[cfg(feature = "rustc")]
    pub fn report_external_deps_errors(&self, f: crate::formatter::FmtCtx<'_>) {
        use crate::formatter::Formatter;
        use macros::VariantIndexArity;
        use petgraph::algo::dijkstra::dijkstra;
        use petgraph::graphmap::DiGraphMap;
        use rustc_error_messages::MultiSpan;

        if !self.has_errors() {
            return;
        }

        /// For tracing error dependencies.
        #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, VariantIndexArity)]
        enum Node {
            External(AnyTransId),
            /// We use the span information only for local references
            Local(AnyTransId, Span),
        }

        struct Graph {
            dgraph: DiGraphMap<Node, ()>,
        }

        impl std::fmt::Display for Graph {
            fn fmt(
                &self,
                f: &mut std::fmt::Formatter<'_>,
            ) -> std::result::Result<(), std::fmt::Error> {
                for (from, to, _) in self.dgraph.all_edges() {
                    writeln!(f, "{from:?} -> {to:?}")?
                }
                Ok(())
            }
        }

        impl Graph {
            fn new() -> Self {
                Graph {
                    dgraph: DiGraphMap::new(),
                }
            }

            fn insert_node(&mut self, n: Node) {
                // We have to be careful about duplicate nodes
                if !self.dgraph.contains_node(n) {
                    self.dgraph.add_node(n);
                }
            }

            fn insert_edge(&mut self, from: Node, to: Node) {
                self.insert_node(from);
                self.insert_node(to);
                if !self.dgraph.contains_edge(from, to) {
                    self.dgraph.add_edge(from, to, ());
                }
            }
        }

        // Create a dependency graph, with spans.
        // We want to know what are the usages in the source code which
        // lead to the extraction of the problematic definitions. For this
        // reason, we only include edges:
        // - from external def to external def
        // - from local def to external def
        let mut graph = Graph::new();

        trace!("dep_sources:\n{:?}", self.external_dep_sources);
        for (id, srcs) in &self.external_dep_sources {
            let src_node = Node::External(*id);
            graph.insert_node(src_node);

            for src in srcs {
                let tgt_node = match src.span {
                    Some(span) => Node::Local(src.src_id, span),
                    None => Node::External(src.src_id),
                };
                graph.insert_edge(src_node, tgt_node)
            }
        }
        trace!("Graph:\n{}", graph);

        // We need to compute the reachability graph. An easy way is simply
        // to use Dijkstra on every external definition which triggered an
        // error.
        for id in &self.external_decls_with_errors {
            let reachable = dijkstra(&graph.dgraph, Node::External(*id), None, &mut |_| 1);
            trace!("id: {:?}\nreachable:\n{:?}", id, reachable);

            let reachable: Vec<rustc_span::Span> = reachable
                .iter()
                .filter_map(|(n, _)| match n {
                    Node::External(_) => None,
                    Node::Local(_, span) => Some(span.rust_span()),
                })
                .collect();

            // Display the error message
            let span = MultiSpan::from_spans(reachable);
            let msg = format!(
                "The external definition `{}` triggered errors. \
                It is (transitively) used at the following location(s):",
                f.format_object(*id)
            );
            self.span_err_no_register(span, &msg);
        }
    }
}