]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/scrape_examples.rs
Rollup merge of #107777 - compiler-errors:derive_const-actually-derive-const, r=fee1...
[rust.git] / src / librustdoc / scrape_examples.rs
1 //! This module analyzes crates to find call sites that can serve as examples in the documentation.
2
3 use crate::clean;
4 use crate::config;
5 use crate::formats;
6 use crate::formats::renderer::FormatRenderer;
7 use crate::html::render::Context;
8
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_hir::{
11     self as hir,
12     intravisit::{self, Visitor},
13 };
14 use rustc_interface::interface;
15 use rustc_macros::{Decodable, Encodable};
16 use rustc_middle::hir::map::Map;
17 use rustc_middle::hir::nested_filter;
18 use rustc_middle::ty::{self, TyCtxt};
19 use rustc_serialize::{
20     opaque::{FileEncoder, MemDecoder},
21     Decodable, Encodable,
22 };
23 use rustc_session::getopts;
24 use rustc_span::{
25     def_id::{CrateNum, DefPathHash, LOCAL_CRATE},
26     edition::Edition,
27     BytePos, FileName, SourceFile,
28 };
29
30 use std::fs;
31 use std::path::PathBuf;
32
33 #[derive(Debug, Clone)]
34 pub(crate) struct ScrapeExamplesOptions {
35     output_path: PathBuf,
36     target_crates: Vec<String>,
37     pub(crate) scrape_tests: bool,
38 }
39
40 impl ScrapeExamplesOptions {
41     pub(crate) fn new(
42         matches: &getopts::Matches,
43         diag: &rustc_errors::Handler,
44     ) -> Result<Option<Self>, i32> {
45         let output_path = matches.opt_str("scrape-examples-output-path");
46         let target_crates = matches.opt_strs("scrape-examples-target-crate");
47         let scrape_tests = matches.opt_present("scrape-tests");
48         match (output_path, !target_crates.is_empty(), scrape_tests) {
49             (Some(output_path), true, _) => Ok(Some(ScrapeExamplesOptions {
50                 output_path: PathBuf::from(output_path),
51                 target_crates,
52                 scrape_tests,
53             })),
54             (Some(_), false, _) | (None, true, _) => {
55                 diag.err("must use --scrape-examples-output-path and --scrape-examples-target-crate together");
56                 Err(1)
57             }
58             (None, false, true) => {
59                 diag.err("must use --scrape-examples-output-path and --scrape-examples-target-crate with --scrape-tests");
60                 Err(1)
61             }
62             (None, false, false) => Ok(None),
63         }
64     }
65 }
66
67 #[derive(Encodable, Decodable, Debug, Clone)]
68 pub(crate) struct SyntaxRange {
69     pub(crate) byte_span: (u32, u32),
70     pub(crate) line_span: (usize, usize),
71 }
72
73 impl SyntaxRange {
74     fn new(span: rustc_span::Span, file: &SourceFile) -> Option<Self> {
75         let get_pos = |bytepos: BytePos| file.original_relative_byte_pos(bytepos).0;
76         let get_line = |bytepos: BytePos| file.lookup_line(bytepos);
77
78         Some(SyntaxRange {
79             byte_span: (get_pos(span.lo()), get_pos(span.hi())),
80             line_span: (get_line(span.lo())?, get_line(span.hi())?),
81         })
82     }
83 }
84
85 #[derive(Encodable, Decodable, Debug, Clone)]
86 pub(crate) struct CallLocation {
87     pub(crate) call_expr: SyntaxRange,
88     pub(crate) call_ident: SyntaxRange,
89     pub(crate) enclosing_item: SyntaxRange,
90 }
91
92 impl CallLocation {
93     fn new(
94         expr_span: rustc_span::Span,
95         ident_span: rustc_span::Span,
96         enclosing_item_span: rustc_span::Span,
97         source_file: &SourceFile,
98     ) -> Option<Self> {
99         Some(CallLocation {
100             call_expr: SyntaxRange::new(expr_span, source_file)?,
101             call_ident: SyntaxRange::new(ident_span, source_file)?,
102             enclosing_item: SyntaxRange::new(enclosing_item_span, source_file)?,
103         })
104     }
105 }
106
107 #[derive(Encodable, Decodable, Debug, Clone)]
108 pub(crate) struct CallData {
109     pub(crate) locations: Vec<CallLocation>,
110     pub(crate) url: String,
111     pub(crate) display_name: String,
112     pub(crate) edition: Edition,
113     pub(crate) is_bin: bool,
114 }
115
116 pub(crate) type FnCallLocations = FxHashMap<PathBuf, CallData>;
117 pub(crate) type AllCallLocations = FxHashMap<DefPathHash, FnCallLocations>;
118
119 /// Visitor for traversing a crate and finding instances of function calls.
120 struct FindCalls<'a, 'tcx> {
121     tcx: TyCtxt<'tcx>,
122     map: Map<'tcx>,
123     cx: Context<'tcx>,
124     target_crates: Vec<CrateNum>,
125     calls: &'a mut AllCallLocations,
126     bin_crate: bool,
127 }
128
129 impl<'a, 'tcx> Visitor<'tcx> for FindCalls<'a, 'tcx>
130 where
131     'tcx: 'a,
132 {
133     type NestedFilter = nested_filter::OnlyBodies;
134
135     fn nested_visit_map(&mut self) -> Self::Map {
136         self.map
137     }
138
139     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
140         intravisit::walk_expr(self, ex);
141
142         let tcx = self.tcx;
143
144         // If we visit an item that contains an expression outside a function body,
145         // then we need to exit before calling typeck (which will panic). See
146         // test/run-make/rustdoc-scrape-examples-invalid-expr for an example.
147         let hir = tcx.hir();
148         if hir.maybe_body_owned_by(ex.hir_id.owner.def_id).is_none() {
149             return;
150         }
151
152         // Get type of function if expression is a function call
153         let (ty, call_span, ident_span) = match ex.kind {
154             hir::ExprKind::Call(f, _) => {
155                 let types = tcx.typeck(ex.hir_id.owner.def_id);
156
157                 if let Some(ty) = types.node_type_opt(f.hir_id) {
158                     (ty, ex.span, f.span)
159                 } else {
160                     trace!("node_type_opt({}) = None", f.hir_id);
161                     return;
162                 }
163             }
164             hir::ExprKind::MethodCall(path, _, _, call_span) => {
165                 let types = tcx.typeck(ex.hir_id.owner.def_id);
166                 let Some(def_id) = types.type_dependent_def_id(ex.hir_id) else {
167                     trace!("type_dependent_def_id({}) = None", ex.hir_id);
168                     return;
169                 };
170
171                 let ident_span = path.ident.span;
172                 (tcx.type_of(def_id), call_span, ident_span)
173             }
174             _ => {
175                 return;
176             }
177         };
178
179         // If this span comes from a macro expansion, then the source code may not actually show
180         // a use of the given item, so it would be a poor example. Hence, we skip all uses in macros.
181         if call_span.from_expansion() {
182             trace!("Rejecting expr from macro: {call_span:?}");
183             return;
184         }
185
186         // If the enclosing item has a span coming from a proc macro, then we also don't want to include
187         // the example.
188         let enclosing_item_span =
189             tcx.hir().span_with_body(tcx.hir().get_parent_item(ex.hir_id).into());
190         if enclosing_item_span.from_expansion() {
191             trace!("Rejecting expr ({call_span:?}) from macro item: {enclosing_item_span:?}");
192             return;
193         }
194
195         // If the enclosing item doesn't actually enclose the call, this means we probably have a weird
196         // macro issue even though the spans aren't tagged as being from an expansion.
197         if !enclosing_item_span.contains(call_span) {
198             warn!(
199                 "Attempted to scrape call at [{call_span:?}] whose enclosing item [{enclosing_item_span:?}] doesn't contain the span of the call."
200             );
201             return;
202         }
203
204         // Similarly for the call w/ the function ident.
205         if !call_span.contains(ident_span) {
206             warn!(
207                 "Attempted to scrape call at [{call_span:?}] whose identifier [{ident_span:?}] was not contained in the span of the call."
208             );
209             return;
210         }
211
212         // Save call site if the function resolves to a concrete definition
213         if let ty::FnDef(def_id, _) = ty.kind() {
214             if self.target_crates.iter().all(|krate| *krate != def_id.krate) {
215                 trace!("Rejecting expr from crate not being documented: {call_span:?}");
216                 return;
217             }
218
219             let source_map = tcx.sess.source_map();
220             let file = source_map.lookup_char_pos(call_span.lo()).file;
221             let file_path = match file.name.clone() {
222                 FileName::Real(real_filename) => real_filename.into_local_path(),
223                 _ => None,
224             };
225
226             if let Some(file_path) = file_path {
227                 let abs_path = match fs::canonicalize(file_path.clone()) {
228                     Ok(abs_path) => abs_path,
229                     Err(_) => {
230                         trace!("Could not canonicalize file path: {}", file_path.display());
231                         return;
232                     }
233                 };
234
235                 let cx = &self.cx;
236                 let clean_span = crate::clean::types::Span::new(call_span);
237                 let url = match cx.href_from_span(clean_span, false) {
238                     Some(url) => url,
239                     None => {
240                         trace!(
241                             "Rejecting expr ({call_span:?}) whose clean span ({clean_span:?}) cannot be turned into a link"
242                         );
243                         return;
244                     }
245                 };
246
247                 let mk_call_data = || {
248                     let display_name = file_path.display().to_string();
249                     let edition = call_span.edition();
250                     let is_bin = self.bin_crate;
251
252                     CallData { locations: Vec::new(), url, display_name, edition, is_bin }
253                 };
254
255                 let fn_key = tcx.def_path_hash(*def_id);
256                 let fn_entries = self.calls.entry(fn_key).or_default();
257
258                 trace!("Including expr: {:?}", call_span);
259                 let enclosing_item_span =
260                     source_map.span_extend_to_prev_char(enclosing_item_span, '\n', false);
261                 let location =
262                     match CallLocation::new(call_span, ident_span, enclosing_item_span, &file) {
263                         Some(location) => location,
264                         None => {
265                             trace!("Could not get serializable call location for {call_span:?}");
266                             return;
267                         }
268                     };
269                 fn_entries.entry(abs_path).or_insert_with(mk_call_data).locations.push(location);
270             }
271         }
272     }
273 }
274
275 pub(crate) fn run(
276     krate: clean::Crate,
277     mut renderopts: config::RenderOptions,
278     cache: formats::cache::Cache,
279     tcx: TyCtxt<'_>,
280     options: ScrapeExamplesOptions,
281     bin_crate: bool,
282 ) -> interface::Result<()> {
283     let inner = move || -> Result<(), String> {
284         // Generates source files for examples
285         renderopts.no_emit_shared = true;
286         let (cx, _) = Context::init(krate, renderopts, cache, tcx).map_err(|e| e.to_string())?;
287
288         // Collect CrateIds corresponding to provided target crates
289         // If two different versions of the crate in the dependency tree, then examples will be collcted from both.
290         let all_crates = tcx
291             .crates(())
292             .iter()
293             .chain([&LOCAL_CRATE])
294             .map(|crate_num| (crate_num, tcx.crate_name(*crate_num)))
295             .collect::<Vec<_>>();
296         let target_crates = options
297             .target_crates
298             .into_iter()
299             .flat_map(|target| all_crates.iter().filter(move |(_, name)| name.as_str() == target))
300             .map(|(crate_num, _)| **crate_num)
301             .collect::<Vec<_>>();
302
303         debug!("All crates in TyCtxt: {all_crates:?}");
304         debug!("Scrape examples target_crates: {target_crates:?}");
305
306         // Run call-finder on all items
307         let mut calls = FxHashMap::default();
308         let mut finder =
309             FindCalls { calls: &mut calls, tcx, map: tcx.hir(), cx, target_crates, bin_crate };
310         tcx.hir().visit_all_item_likes_in_crate(&mut finder);
311
312         // The visitor might have found a type error, which we need to
313         // promote to a fatal error
314         if tcx.sess.diagnostic().has_errors_or_lint_errors().is_some() {
315             return Err(String::from("Compilation failed, aborting rustdoc"));
316         }
317
318         // Sort call locations within a given file in document order
319         for fn_calls in calls.values_mut() {
320             for file_calls in fn_calls.values_mut() {
321                 file_calls.locations.sort_by_key(|loc| loc.call_expr.byte_span.0);
322             }
323         }
324
325         // Save output to provided path
326         let mut encoder = FileEncoder::new(options.output_path).map_err(|e| e.to_string())?;
327         calls.encode(&mut encoder);
328         encoder.finish().map_err(|e| e.to_string())?;
329
330         Ok(())
331     };
332
333     if let Err(e) = inner() {
334         tcx.sess.fatal(&e);
335     }
336
337     Ok(())
338 }
339
340 // Note: the Handler must be passed in explicitly because sess isn't available while parsing options
341 pub(crate) fn load_call_locations(
342     with_examples: Vec<String>,
343     diag: &rustc_errors::Handler,
344 ) -> Result<AllCallLocations, i32> {
345     let inner = || {
346         let mut all_calls: AllCallLocations = FxHashMap::default();
347         for path in with_examples {
348             let bytes = fs::read(&path).map_err(|e| format!("{} (for path {})", e, path))?;
349             let mut decoder = MemDecoder::new(&bytes, 0);
350             let calls = AllCallLocations::decode(&mut decoder);
351
352             for (function, fn_calls) in calls.into_iter() {
353                 all_calls.entry(function).or_default().extend(fn_calls.into_iter());
354             }
355         }
356
357         Ok(all_calls)
358     };
359
360     inner().map_err(|e: String| {
361         diag.err(&format!("failed to load examples: {}", e));
362         1
363     })
364 }