1 //! This module analyzes crates to find call sites that can serve as examples in the documentation.
6 use crate::formats::renderer::FormatRenderer;
7 use crate::html::render::Context;
9 use rustc_data_structures::fx::FxHashMap;
12 intravisit::{self, Visitor},
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},
23 use rustc_session::getopts;
25 def_id::{CrateNum, DefPathHash, LOCAL_CRATE},
27 BytePos, FileName, SourceFile,
31 use std::path::PathBuf;
33 #[derive(Debug, Clone)]
34 crate struct ScrapeExamplesOptions {
36 target_crates: Vec<String>,
39 impl ScrapeExamplesOptions {
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),
51 (Some(_), false) | (None, true) => {
52 diag.err("must use --scrape-examples-output-path and --scrape-examples-target-crate together");
55 (None, false) => Ok(None),
60 #[derive(Encodable, Decodable, Debug, Clone)]
61 crate struct SyntaxRange {
62 crate byte_span: (u32, u32),
63 crate line_span: (usize, usize),
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();
72 byte_span: (get_pos(span.lo()), get_pos(span.hi())),
73 line_span: (get_line(span.lo()), get_line(span.hi())),
78 #[derive(Encodable, Decodable, Debug, Clone)]
79 crate struct CallLocation {
80 crate call_expr: SyntaxRange,
81 crate enclosing_item: SyntaxRange,
87 expr_span: rustc_span::Span,
89 source_file: &SourceFile,
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));
96 call_expr: SyntaxRange::new(expr_span, source_file),
97 enclosing_item: SyntaxRange::new(enclosing_item_span, source_file),
102 #[derive(Encodable, Decodable, Debug, Clone)]
103 crate struct CallData {
104 crate locations: Vec<CallLocation>,
106 crate display_name: String,
107 crate edition: Edition,
110 crate type FnCallLocations = FxHashMap<PathBuf, CallData>;
111 crate type AllCallLocations = FxHashMap<DefPathHash, FnCallLocations>;
113 /// Visitor for traversing a crate and finding instances of function calls.
114 struct FindCalls<'a, 'tcx> {
118 target_crates: Vec<CrateNum>,
119 calls: &'a mut AllCallLocations,
122 impl<'a, 'tcx> Visitor<'tcx> for FindCalls<'a, 'tcx>
126 type Map = Map<'tcx>;
128 fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
129 intravisit::NestedVisitorMap::OnlyBodies(self.map)
132 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
133 intravisit::walk_expr(self, ex);
137 // If we visit an item that contains an expression outside a function body,
138 // then we need to exit before calling typeck (which will panic). See
139 // test/run-make/rustdoc-scrape-examples-invalid-expr for an example.
141 let owner = hir.local_def_id_to_hir_id(ex.hir_id.owner);
142 if hir.maybe_body_owned_by(owner).is_none() {
146 // Get type of function if expression is a function call
147 let (ty, span) = match ex.kind {
148 hir::ExprKind::Call(f, _) => {
149 let types = tcx.typeck(ex.hir_id.owner);
151 match types.node_type_opt(f.hir_id) {
152 Some(ty) => (ty, ex.span),
158 hir::ExprKind::MethodCall(_, _, _, span) => {
159 let types = tcx.typeck(ex.hir_id.owner);
160 let def_id = types.type_dependent_def_id(ex.hir_id).unwrap();
161 (tcx.type_of(def_id), span)
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() {
174 // Save call site if the function resolves to a concrete definition
175 if let ty::FnDef(def_id, _) = ty.kind() {
176 // Ignore functions not from the crate being documented
177 if self.target_crates.iter().all(|krate| *krate != def_id.krate) {
181 let file = tcx.sess.source_map().lookup_char_pos(span.lo()).file;
182 let file_path = match file.name.clone() {
183 FileName::Real(real_filename) => real_filename.into_local_path(),
187 if let Some(file_path) = file_path {
188 let abs_path = fs::canonicalize(file_path.clone()).unwrap();
190 let mk_call_data = || {
191 let clean_span = crate::clean::types::Span::new(span);
192 let url = cx.href_from_span(clean_span, false).unwrap();
193 let display_name = file_path.display().to_string();
194 let edition = span.edition();
195 CallData { locations: Vec::new(), url, display_name, edition }
198 let fn_key = tcx.def_path_hash(*def_id);
199 let fn_entries = self.calls.entry(fn_key).or_default();
201 let location = CallLocation::new(tcx, span, ex.hir_id, &file);
202 fn_entries.entry(abs_path).or_insert_with(mk_call_data).locations.push(location);
210 renderopts: config::RenderOptions,
211 cache: formats::cache::Cache,
213 options: ScrapeExamplesOptions,
214 ) -> interface::Result<()> {
215 let inner = move || -> Result<(), String> {
216 // Generates source files for examples
217 let (cx, _) = Context::init(krate, renderopts, cache, tcx).map_err(|e| e.to_string())?;
219 // Collect CrateIds corresponding to provided target crates
220 // If two different versions of the crate in the dependency tree, then examples will be collcted from both.
224 .chain([&LOCAL_CRATE])
225 .map(|crate_num| (crate_num, tcx.crate_name(*crate_num)))
226 .collect::<Vec<_>>();
227 let target_crates = options
230 .map(|target| all_crates.iter().filter(move |(_, name)| name.as_str() == target))
232 .map(|(crate_num, _)| **crate_num)
233 .collect::<Vec<_>>();
235 debug!("All crates in TyCtxt: {:?}", all_crates);
236 debug!("Scrape examples target_crates: {:?}", target_crates);
238 // Run call-finder on all items
239 let mut calls = FxHashMap::default();
240 let mut finder = FindCalls { calls: &mut calls, tcx, map: tcx.hir(), cx, target_crates };
241 tcx.hir().visit_all_item_likes(&mut finder.as_deep_visitor());
243 // Save output to provided path
244 let mut encoder = FileEncoder::new(options.output_path).map_err(|e| e.to_string())?;
245 calls.encode(&mut encoder).map_err(|e| e.to_string())?;
246 encoder.flush().map_err(|e| e.to_string())?;
251 if let Err(e) = inner() {
258 // Note: the Handler must be passed in explicitly because sess isn't available while parsing options
259 crate fn load_call_locations(
260 with_examples: Vec<String>,
261 diag: &rustc_errors::Handler,
262 ) -> Result<AllCallLocations, i32> {
264 let mut all_calls: AllCallLocations = FxHashMap::default();
265 for path in with_examples {
266 let bytes = fs::read(&path).map_err(|e| format!("{} (for path {})", e, path))?;
267 let mut decoder = Decoder::new(&bytes, 0);
268 let calls = AllCallLocations::decode(&mut decoder)?;
270 for (function, fn_calls) in calls.into_iter() {
271 all_calls.entry(function).or_default().extend(fn_calls.into_iter());
278 inner().map_err(|e: String| {
279 diag.err(&format!("failed to load examples: {}", e));