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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
//! Utilities to generate error reports about the external dependencies.
use crate::ast::*;
use macros::VariantIndexArity;
use petgraph::prelude::DiGraphMap;
use std::cmp::{Ord, PartialOrd};
use std::collections::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);
        }
    }};
    ($ctx:expr, $krate:expr, $span: expr, $msg: expr) => {{
        $ctx.span_err($krate, $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);
    }};
    ($ctx:expr, $krate:expr, $span:expr, $msg:expr) => {{
        $crate::errors::register_error_or_panic!($ctx, $krate, $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>,
}

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

/// Graph of dependencies between erroring definitions and the definitions they came from.
struct DepGraph {
    dgraph: DiGraphMap<DepNode, ()>,
}

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

    fn insert_node(&mut self, n: DepNode) {
        // 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: DepNode, to: DepNode) {
        self.insert_node(from);
        self.insert_node(to);
        if !self.dgraph.contains_edge(from, to) {
            self.dgraph.add_edge(from, to, ());
        }
    }
}

impl std::fmt::Display for DepGraph {
    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(())
    }
}

/// 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>,
    /// Graph of dependencies between items: there is an edge from item `a` to item `b` if `b`
    /// registered the id for `a` during its translation. Because we only use this to report errors
    /// on external items, we only record edges where `a` is an external item.
    external_dep_graph: DepGraph,
    /// 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<'ctx> ErrorCtx<'ctx> {
    pub fn new(
        continue_on_failure: bool,
        error_on_warnings: bool,
        #[cfg(feature = "rustc")] dcx: rustc_errors::DiagCtxtHandle<'ctx>,
        #[cfg(not(feature = "rustc"))] dcx: &'ctx (),
    ) -> Self {
        Self {
            continue_on_failure,
            error_on_warnings,
            dcx,
            external_decls_with_errors: HashSet::new(),
            ignored_failed_decls: HashSet::new(),
            external_dep_graph: DepGraph::new(),
            def_id: None,
            def_id_is_local: false,
            error_count: 0,
        }
    }

    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,
        _krate: &TranslatedCrate,
        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, _krate: &TranslatedCrate, _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, krate: &TranslatedCrate, span: Span, msg: &str) {
        self.span_err_no_register(krate, span, msg);
        self.error_count += 1;
        // If this item comes from an external crate, after the first error for that item we
        // display where in the local crate that item was reached from.
        #[cfg(feature = "rustc")]
        if !self.def_id_is_local
            && let Some(id) = self.def_id
            && self.external_decls_with_errors.insert(id)
        {
            use crate::formatter::IntoFormatter;
            self.report_external_dep_error(&krate.into_fmt(), id);
        }
    }

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

    /// Register the fact that `id` is a dependency of `src` (if `src` is not `None`).
    pub fn register_dep_source(
        &mut self,
        src: &Option<DepSource>,
        item_id: AnyTransId,
        is_local: bool,
    ) {
        if let Some(src) = src
            && src.src_id != item_id
            && !is_local
        {
            let src_node = DepNode::External(item_id);
            self.external_dep_graph.insert_node(src_node);

            let tgt_node = match src.span {
                Some(span) => DepNode::Local(src.src_id, span),
                None => DepNode::External(src.src_id),
            };
            self.external_dep_graph.insert_edge(src_node, tgt_node)
        }
    }

    /// 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_dep_error(&self, f: &crate::formatter::FmtCtx<'_>, id: AnyTransId) {
        use crate::formatter::Formatter;
        use petgraph::algo::dijkstra::dijkstra;
        use rustc_error_messages::MultiSpan;

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

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

        // Display the error message
        let spans = MultiSpan::from_spans(reachable);
        let msg = format!(
            "the error occurred when translating `{}`, \
             which is (transitively) used at the following location(s):",
            f.format_object(id)
        );

        self.dcx.span_note(spans, msg);
    }
}