Debian Codegraph @

diagnostics.rs

raw ◀ ▶
1 Debian patch touch this file
1 //! Types and function used to emit pretty diagnostics for `bindgen`.
2 //!
3 //! The entry point of this module is the [`Diagnostic`] type.
4
5 use std::fmt::Write;
6 use std::io::{self, BufRead, BufReader};
7 use std::{borrow::Cow, fs::File};
8
•9 use annotate_snippets::{Annotation, Group, Renderer, Snippet};
10
11 pub(crate) use annotate_snippets::Level;
12
13 /// A `bindgen` diagnostic.
14 #[derive(Default)]
15 pub(crate) struct Diagnostic<'a> {
•16 title: Option<(Cow<'a, str>, Level<'static>)>,
17 slices: Vec<Slice<'a>>,
•18 footer: Vec<(Cow<'a, str>, Level<'static>)>,
19 }
20
21 impl<'a> Diagnostic<'a> {
22 /// Add a title to the diagnostic and set its type.
23 pub(crate) fn with_title(
24 &mut self,
25 title: impl Into<Cow<'a, str>>,
•26 level: Level<'static>,
27 ) -> &mut Self {
28 self.title = Some((title.into(), level));
29 self
30 }
31
32 /// Add a slice of source code to the diagnostic.
33 pub(crate) fn add_slice(&mut self, slice: Slice<'a>) -> &mut Self {
34 self.slices.push(slice);
35 self
36 }
37
38 /// Add a footer annotation to the diagnostic. This annotation will have its own type.
39 pub(crate) fn add_annotation(
40 &mut self,
41 msg: impl Into<Cow<'a, str>>,
•42 level: Level<'static>,
43 ) -> &mut Self {
44 self.footer.push((msg.into(), level));
45 self
46 }
47
48 /// Print this diagnostic.
49 ///
50 /// The diagnostic is printed using `cargo:warning` if `bindgen` is being invoked by a build
51 /// script or using `eprintln` otherwise.
52 pub(crate) fn display(&self) {
53 std::thread_local! {
54 static INVOKED_BY_BUILD_SCRIPT: bool = std::env::var_os("CARGO_CFG_TARGET_ARCH").is_some();
55 }
56
•57 let Some((msg, level)) = &self.title else {
58 return;
59 };
60
•61 let mut group = Group::with_title(level.clone().primary_title(msg.as_ref()));
62
63 for slice in &self.slices {
64 if let Some(source) = &slice.source {
•65 let mut snippet = Snippet::<Annotation>::source(source.as_ref())
66 .line_start(slice.line.unwrap_or_default());
67 if let Some(origin) = &slice.filename {
•68 snippet = snippet.path(origin.as_str());
69 }
•70 group = group.element(snippet);
71 }
72 }
73
•74 for (msg, level) in &self.footer {
75 group = group.element(level.clone().message(msg.as_ref()));
76 }
77 // add additional info that this is generated by bindgen
78 // so as to not confuse with rustc warnings
79 group = group.element(Level::INFO.message("This diagnostic was generated by bindgen."));
80
81 let renderer = Renderer::styled();
•82 let dl = renderer.render(std::slice::from_ref(&group));
83
84 if INVOKED_BY_BUILD_SCRIPT.with(Clone::clone) {
85 // This is just a hack which hides the `warning:` added by cargo at the beginning of
86 // every line. This should be fine as our diagnostics already have a colorful title.
87 // FIXME (pvdrz): Could it be that this doesn't work in other languages?
88 let hide_warning = "\r \r";
89 let string = dl.to_string();
90 for line in string.lines() {
91 println!("cargo:warning={hide_warning}{line}");
92 }
93 } else {
94 eprintln!("{dl}\n");
95 }
96 }
97 }
98
99 /// A slice of source code.
100 #[derive(Default)]
101 pub(crate) struct Slice<'a> {
102 source: Option<Cow<'a, str>>,
103 filename: Option<String>,
104 line: Option<usize>,
105 }
106
107 impl<'a> Slice<'a> {
108 /// Set the source code.
109 pub(crate) fn with_source(
110 &mut self,
111 source: impl Into<Cow<'a, str>>,
112 ) -> &mut Self {
113 self.source = Some(source.into());
114 self
115 }
116
117 /// Set the file, line and column.
118 pub(crate) fn with_location(
119 &mut self,
120 mut name: String,
121 line: usize,
122 col: usize,
123 ) -> &mut Self {
124 write!(name, ":{line}:{col}").expect("Writing to a string cannot fail");
125 self.filename = Some(name);
126 self.line = Some(line);
127 self
128 }
129 }
130
131 pub(crate) fn get_line(
132 filename: &str,
133 line: usize,
134 ) -> io::Result<Option<String>> {
135 let file = BufReader::new(File::open(filename)?);
136 if let Some(line) = file.lines().nth(line.wrapping_sub(1)) {
137 return line.map(Some);
138 }
139
140 Ok(None)
141 }