]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/scrape_examples.rs
Rollup merge of #91530 - bobrippling:suggest-1-tuple-parens, r=camelid
[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::{Decoder, FileEncoder},
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 crate struct ScrapeExamplesOptions {
35     output_path: PathBuf,
36     target_crates: Vec<String>,
37 }
38
39 impl ScrapeExamplesOptions {
40     crate fn new(
41         matches: &getopts::Matches,
42         diag: &rustc_errors::Handler,
43     ) -> Result<Option<Self>, i32> {
44         let output_path = matches.opt_str("scrape-examples-output-path");
45         let target_crates = matches.opt_strs("scrape-examples-target-crate");
46         match (output_path, !target_crates.is_empty()) {
47             (Some(output_path), true) => Ok(Some(ScrapeExamplesOptions {
48                 output_path: PathBuf::from(output_path),
49                 target_crates,
50             })),
51             (Some(_), false) | (None, true) => {
52                 diag.err("must use --scrape-examples-output-path and --scrape-examples-target-crate together");
53                 Err(1)
54             }
55             (None, false) => Ok(None),
56         }
57     }
58 }
59
60 #[derive(Encodable, Decodable, Debug, Clone)]
61 crate struct SyntaxRange {
62     crate byte_span: (u32, u32),
63     crate line_span: (usize, usize),
64 }
65
66 impl SyntaxRange {
67     fn new(span: rustc_span::Span, file: &SourceFile) -> Self {
68         let get_pos = |bytepos: BytePos| file.original_relative_byte_pos(bytepos).0;
69         let get_line = |bytepos: BytePos| file.lookup_line(bytepos).unwrap();
70
71         SyntaxRange {
72             byte_span: (get_pos(span.lo()), get_pos(span.hi())),
73             line_span: (get_line(span.lo()), get_line(span.hi())),
74         }
75     }
76 }
77
78 #[derive(Encodable, Decodable, Debug, Clone)]
79 crate struct CallLocation {
80     crate call_expr: SyntaxRange,
81     crate enclosing_item: SyntaxRange,
82 }
83
84 impl CallLocation {
85     fn new(
86         expr_span: rustc_span::Span,
87         enclosing_item_span: rustc_span::Span,
88         source_file: &SourceFile,
89     ) -> Self {
90         CallLocation {
91             call_expr: SyntaxRange::new(expr_span, source_file),
92             enclosing_item: SyntaxRange::new(enclosing_item_span, source_file),
93         }
94     }
95 }
96
97 #[derive(Encodable, Decodable, Debug, Clone)]
98 crate struct CallData {
99     crate locations: Vec<CallLocation>,
100     crate url: String,
101     crate display_name: String,
102     crate edition: Edition,
103 }
104
105 crate type FnCallLocations = FxHashMap<PathBuf, CallData>;
106 crate type AllCallLocations = FxHashMap<DefPathHash, FnCallLocations>;
107
108 /// Visitor for traversing a crate and finding instances of function calls.
109 struct FindCalls<'a, 'tcx> {
110     tcx: TyCtxt<'tcx>,
111     map: Map<'tcx>,
112     cx: Context<'tcx>,
113     target_crates: Vec<CrateNum>,
114     calls: &'a mut AllCallLocations,
115 }
116
117 impl<'a, 'tcx> Visitor<'tcx> for FindCalls<'a, 'tcx>
118 where
119     'tcx: 'a,
120 {
121     type NestedFilter = nested_filter::OnlyBodies;
122
123     fn nested_visit_map(&mut self) -> Self::Map {
124         self.map
125     }
126
127     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
128         intravisit::walk_expr(self, ex);
129
130         let tcx = self.tcx;
131
132         // If we visit an item that contains an expression outside a function body,
133         // then we need to exit before calling typeck (which will panic). See
134         // test/run-make/rustdoc-scrape-examples-invalid-expr for an example.
135         let hir = tcx.hir();
136         let owner = hir.local_def_id_to_hir_id(ex.hir_id.owner);
137         if hir.maybe_body_owned_by(owner).is_none() {
138             return;
139         }
140
141         // Get type of function if expression is a function call
142         let (ty, span) = match ex.kind {
143             hir::ExprKind::Call(f, _) => {
144                 let types = tcx.typeck(ex.hir_id.owner);
145
146                 if let Some(ty) = types.node_type_opt(f.hir_id) {
147                     (ty, ex.span)
148                 } else {
149                     trace!("node_type_opt({}) = None", f.hir_id);
150                     return;
151                 }
152             }
153             hir::ExprKind::MethodCall(_, _, span) => {
154                 let types = tcx.typeck(ex.hir_id.owner);
155                 let def_id = if let Some(def_id) = types.type_dependent_def_id(ex.hir_id) {
156                     def_id
157                 } else {
158                     trace!("type_dependent_def_id({}) = None", ex.hir_id);
159                     return;
160                 };
161                 (tcx.type_of(def_id), span)
162             }
163             _ => {
164                 return;
165             }
166         };
167
168         // If this span comes from a macro expansion, then the source code may not actually show
169         // a use of the given item, so it would be a poor example. Hence, we skip all uses in macros.
170         if span.from_expansion() {
171             trace!("Rejecting expr from macro: {:?}", span);
172             return;
173         }
174
175         // If the enclosing item has a span coming from a proc macro, then we also don't want to include
176         // the example.
177         let enclosing_item_span = tcx
178             .hir()
179             .span_with_body(tcx.hir().local_def_id_to_hir_id(tcx.hir().get_parent_item(ex.hir_id)));
180         if enclosing_item_span.from_expansion() {
181             trace!("Rejecting expr ({:?}) from macro item: {:?}", span, enclosing_item_span);
182             return;
183         }
184
185         assert!(
186             enclosing_item_span.contains(span),
187             "Attempted to scrape call at [{:?}] whose enclosing item [{:?}] doesn't contain the span of the call.",
188             span,
189             enclosing_item_span
190         );
191
192         // Save call site if the function resolves to a concrete definition
193         if let ty::FnDef(def_id, _) = ty.kind() {
194             if self.target_crates.iter().all(|krate| *krate != def_id.krate) {
195                 trace!("Rejecting expr from crate not being documented: {:?}", span);
196                 return;
197             }
198
199             let file = tcx.sess.source_map().lookup_char_pos(span.lo()).file;
200             let file_path = match file.name.clone() {
201                 FileName::Real(real_filename) => real_filename.into_local_path(),
202                 _ => None,
203             };
204
205             if let Some(file_path) = file_path {
206                 let abs_path = fs::canonicalize(file_path.clone()).unwrap();
207                 let cx = &self.cx;
208                 let mk_call_data = || {
209                     let clean_span = crate::clean::types::Span::new(span);
210                     let url = cx.href_from_span(clean_span, false).unwrap();
211                     let display_name = file_path.display().to_string();
212                     let edition = span.edition();
213                     CallData { locations: Vec::new(), url, display_name, edition }
214                 };
215
216                 let fn_key = tcx.def_path_hash(*def_id);
217                 let fn_entries = self.calls.entry(fn_key).or_default();
218
219                 trace!("Including expr: {:?}", span);
220                 let location = CallLocation::new(span, enclosing_item_span, &file);
221                 fn_entries.entry(abs_path).or_insert_with(mk_call_data).locations.push(location);
222             }
223         }
224     }
225 }
226
227 crate fn run(
228     krate: clean::Crate,
229     mut renderopts: config::RenderOptions,
230     cache: formats::cache::Cache,
231     tcx: TyCtxt<'_>,
232     options: ScrapeExamplesOptions,
233 ) -> interface::Result<()> {
234     let inner = move || -> Result<(), String> {
235         // Generates source files for examples
236         renderopts.no_emit_shared = true;
237         let (cx, _) = Context::init(krate, renderopts, cache, tcx).map_err(|e| e.to_string())?;
238
239         // Collect CrateIds corresponding to provided target crates
240         // If two different versions of the crate in the dependency tree, then examples will be collcted from both.
241         let all_crates = tcx
242             .crates(())
243             .iter()
244             .chain([&LOCAL_CRATE])
245             .map(|crate_num| (crate_num, tcx.crate_name(*crate_num)))
246             .collect::<Vec<_>>();
247         let target_crates = options
248             .target_crates
249             .into_iter()
250             .flat_map(|target| all_crates.iter().filter(move |(_, name)| name.as_str() == target))
251             .map(|(crate_num, _)| **crate_num)
252             .collect::<Vec<_>>();
253
254         debug!("All crates in TyCtxt: {:?}", all_crates);
255         debug!("Scrape examples target_crates: {:?}", target_crates);
256
257         // Run call-finder on all items
258         let mut calls = FxHashMap::default();
259         let mut finder = FindCalls { calls: &mut calls, tcx, map: tcx.hir(), cx, target_crates };
260         tcx.hir().visit_all_item_likes(&mut finder.as_deep_visitor());
261
262         // Sort call locations within a given file in document order
263         for fn_calls in calls.values_mut() {
264             for file_calls in fn_calls.values_mut() {
265                 file_calls.locations.sort_by_key(|loc| loc.call_expr.byte_span.0);
266             }
267         }
268
269         // Save output to provided path
270         let mut encoder = FileEncoder::new(options.output_path).map_err(|e| e.to_string())?;
271         calls.encode(&mut encoder).map_err(|e| e.to_string())?;
272         encoder.flush().map_err(|e| e.to_string())?;
273
274         Ok(())
275     };
276
277     if let Err(e) = inner() {
278         tcx.sess.fatal(&e);
279     }
280
281     Ok(())
282 }
283
284 // Note: the Handler must be passed in explicitly because sess isn't available while parsing options
285 crate fn load_call_locations(
286     with_examples: Vec<String>,
287     diag: &rustc_errors::Handler,
288 ) -> Result<AllCallLocations, i32> {
289     let inner = || {
290         let mut all_calls: AllCallLocations = FxHashMap::default();
291         for path in with_examples {
292             let bytes = fs::read(&path).map_err(|e| format!("{} (for path {})", e, path))?;
293             let mut decoder = Decoder::new(&bytes, 0);
294             let calls = AllCallLocations::decode(&mut decoder);
295
296             for (function, fn_calls) in calls.into_iter() {
297                 all_calls.entry(function).or_default().extend(fn_calls.into_iter());
298             }
299         }
300
301         Ok(all_calls)
302     };
303
304     inner().map_err(|e: String| {
305         diag.err(&format!("failed to load examples: {}", e));
306         1
307     })
308 }