Debian Codegraph @

debian/rust-vendor/bindgen/diagnostics.rs

raw
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::{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)>,
17 slices: Vec<Slice<'a>>,
18 footer: Vec<(Cow<'a, str>, Level)>,
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,
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,
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 mut footer = vec![];
58 let mut slices = vec![];
59 let snippet = if let Some((msg, level)) = &self.title {
60 (*level).title(msg)
61 } else {
62 return;
63 };
64
65 for (msg, level) in &self.footer {
66 footer.push((*level).title(msg));
67 }
68
69 // add additional info that this is generated by bindgen
70 // so as to not confuse with rustc warnings
71 footer.push(
72 Level::Info.title("This diagnostic was generated by bindgen."),
73 );
74
75 for slice in &self.slices {
76 if let Some(source) = &slice.source {
77 let mut snippet = Snippet::source(source)
78 .line_start(slice.line.unwrap_or_default());
79 if let Some(origin) = &slice.filename {
80 snippet = snippet.origin(origin);
81 }
82 slices.push(snippet);
83 }
84 }
85
86 let renderer = Renderer::styled();
87 let dl = renderer.render(snippet.snippets(slices).footers(footer));
88
89 if INVOKED_BY_BUILD_SCRIPT.with(Clone::clone) {
90 // This is just a hack which hides the `warning:` added by cargo at the beginning of
91 // every line. This should be fine as our diagnostics already have a colorful title.
92 // FIXME (pvdrz): Could it be that this doesn't work in other languages?
93 let hide_warning = "\r \r";
94 let string = dl.to_string();
95 for line in string.lines() {
96 println!("cargo:warning={hide_warning}{line}");
97 }
98 } else {
99 eprintln!("{dl}\n");
100 }
101 }
102 }
103
104 /// A slice of source code.
105 #[derive(Default)]
106 pub(crate) struct Slice<'a> {
107 source: Option<Cow<'a, str>>,
108 filename: Option<String>,
109 line: Option<usize>,
110 }
111
112 impl<'a> Slice<'a> {
113 /// Set the source code.
114 pub(crate) fn with_source(
115 &mut self,
116 source: impl Into<Cow<'a, str>>,
117 ) -> &mut Self {
118 self.source = Some(source.into());
119 self
120 }
121
122 /// Set the file, line and column.
123 pub(crate) fn with_location(
124 &mut self,
125 mut name: String,
126 line: usize,
127 col: usize,
128 ) -> &mut Self {
129 write!(name, ":{line}:{col}").expect("Writing to a string cannot fail");
130 self.filename = Some(name);
131 self.line = Some(line);
132 self
133 }
134 }
135
136 pub(crate) fn get_line(
137 filename: &str,
138 line: usize,
139 ) -> io::Result<Option<String>> {
140 let file = BufReader::new(File::open(filename)?);
141 if let Some(line) = file.lines().nth(line.wrapping_sub(1)) {
142 return line.map(Some);
143 }
144
145 Ok(None)
146 }