]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/scrape_examples.rs
Move more scrape-examples logic from JS to rust
[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     HirId,
14 };
15 use rustc_interface::interface;
16 use rustc_macros::{Decodable, Encodable};
17 use rustc_middle::hir::map::Map;
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},
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(&format!("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         tcx: TyCtxt<'_>,
87         expr_span: rustc_span::Span,
88         expr_id: HirId,
89         source_file: &SourceFile,
90     ) -> Self {
91         let enclosing_item_span =
92             tcx.hir().span_with_body(tcx.hir().get_parent_item(expr_id)).source_callsite();
93         assert!(enclosing_item_span.contains(expr_span));
94
95         CallLocation {
96             call_expr: SyntaxRange::new(expr_span, source_file),
97             enclosing_item: SyntaxRange::new(enclosing_item_span, source_file),
98         }
99     }
100 }
101
102 #[derive(Encodable, Decodable, Debug, Clone)]
103 crate struct CallData {
104     crate locations: Vec<CallLocation>,
105     crate url: String,
106     crate display_name: String,
107     crate edition: Edition,
108 }
109
110 crate type FnCallLocations = FxHashMap<PathBuf, CallData>;
111 crate type AllCallLocations = FxHashMap<DefPathHash, FnCallLocations>;
112
113 /// Visitor for traversing a crate and finding instances of function calls.
114 struct FindCalls<'a, 'tcx> {
115     tcx: TyCtxt<'tcx>,
116     map: Map<'tcx>,
117     cx: Context<'tcx>,
118     target_crates: Vec<CrateNum>,
119     calls: &'a mut AllCallLocations,
120 }
121
122 impl<'a, 'tcx> Visitor<'tcx> for FindCalls<'a, 'tcx>
123 where
124     'tcx: 'a,
125 {
126     type Map = Map<'tcx>;
127
128     fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
129         intravisit::NestedVisitorMap::OnlyBodies(self.map)
130     }
131
132     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
133         intravisit::walk_expr(self, ex);
134
135         // Get type of function if expression is a function call
136         let tcx = self.tcx;
137         let (ty, span) = match ex.kind {
138             hir::ExprKind::Call(f, _) => {
139                 let types = tcx.typeck(ex.hir_id.owner);
140                 (types.node_type(f.hir_id), ex.span)
141             }
142             hir::ExprKind::MethodCall(_, _, _, span) => {
143                 let types = tcx.typeck(ex.hir_id.owner);
144                 let def_id = types.type_dependent_def_id(ex.hir_id).unwrap();
145                 (tcx.type_of(def_id), span)
146             }
147             _ => {
148                 return;
149             }
150         };
151
152         // We need to get the file the example originates in. If the call is contained
153         // in a macro, then trace the span back to the macro source (rather than macro definition).
154         let span = span.source_callsite();
155
156         // Save call site if the function resolves to a concrete definition
157         if let ty::FnDef(def_id, _) = ty.kind() {
158             // Ignore functions not from the crate being documented
159             if self.target_crates.iter().all(|krate| *krate != def_id.krate) {
160                 return;
161             }
162
163             let file = tcx.sess.source_map().lookup_char_pos(span.lo()).file;
164             let file_path = match file.name.clone() {
165                 FileName::Real(real_filename) => real_filename.into_local_path(),
166                 _ => None,
167             };
168
169             if let Some(file_path) = file_path {
170                 let abs_path = fs::canonicalize(file_path.clone()).unwrap();
171                 let cx = &self.cx;
172                 let mk_call_data = || {
173                     let clean_span = crate::clean::types::Span::new(span);
174                     let url = cx.href_from_span(clean_span, false).unwrap();
175                     let display_name = file_path.display().to_string();
176                     let edition = span.edition();
177                     CallData { locations: Vec::new(), url, display_name, edition }
178                 };
179
180                 let fn_key = tcx.def_path_hash(*def_id);
181                 let fn_entries = self.calls.entry(fn_key).or_default();
182
183                 let location = CallLocation::new(tcx, span, ex.hir_id, &file);
184                 fn_entries.entry(abs_path).or_insert_with(mk_call_data).locations.push(location);
185             }
186         }
187     }
188 }
189
190 crate fn run(
191     krate: clean::Crate,
192     renderopts: config::RenderOptions,
193     cache: formats::cache::Cache,
194     tcx: TyCtxt<'_>,
195     options: ScrapeExamplesOptions,
196 ) -> interface::Result<()> {
197     let inner = move || -> Result<(), String> {
198         // Generates source files for examples
199         let (cx, _) = Context::init(krate, renderopts, cache, tcx).map_err(|e| e.to_string())?;
200
201         // Collect CrateIds corresponding to provided target crates
202         // If two different versions of the crate in the dependency tree, then examples will be collcted from both.
203         let find_crates_with_name = |target_crate: String| {
204             tcx.crates(())
205                 .iter()
206                 .filter(move |crate_num| tcx.crate_name(**crate_num).as_str() == target_crate)
207                 .copied()
208         };
209         let target_crates = options
210             .target_crates
211             .into_iter()
212             .map(find_crates_with_name)
213             .flatten()
214             .collect::<Vec<_>>();
215
216         // Run call-finder on all items
217         let mut calls = FxHashMap::default();
218         let mut finder = FindCalls { calls: &mut calls, tcx, map: tcx.hir(), cx, target_crates };
219         tcx.hir().visit_all_item_likes(&mut finder.as_deep_visitor());
220
221         // Save output to provided path
222         let mut encoder = FileEncoder::new(options.output_path).map_err(|e| e.to_string())?;
223         calls.encode(&mut encoder).map_err(|e| e.to_string())?;
224         encoder.flush().map_err(|e| e.to_string())?;
225
226         Ok(())
227     };
228
229     if let Err(e) = inner() {
230         tcx.sess.fatal(&e);
231     }
232
233     Ok(())
234 }
235
236 // Note: the Handler must be passed in explicitly because sess isn't available while parsing options
237 crate fn load_call_locations(
238     with_examples: Vec<String>,
239     diag: &rustc_errors::Handler,
240 ) -> Result<AllCallLocations, i32> {
241     let inner = || {
242         let mut all_calls: AllCallLocations = FxHashMap::default();
243         for path in with_examples {
244             let bytes = fs::read(&path).map_err(|e| format!("{} (for path {})", e, path))?;
245             let mut decoder = Decoder::new(&bytes, 0);
246             let calls = AllCallLocations::decode(&mut decoder)?;
247
248             for (function, fn_calls) in calls.into_iter() {
249                 all_calls.entry(function).or_default().extend(fn_calls.into_iter());
250             }
251         }
252
253         Ok(all_calls)
254     };
255
256     inner().map_err(|e: String| {
257         diag.err(&format!("failed to load examples: {}", e));
258         1
259     })
260 }