2021-08-26 21:43:12 +00:00
|
|
|
//! This module analyzes crates to find call sites that can serve as examples in the documentation.
|
2021-05-09 23:22:22 +00:00
|
|
|
|
2021-06-03 00:21:48 +00:00
|
|
|
use crate::clean;
|
|
|
|
use crate::config;
|
|
|
|
use crate::formats;
|
|
|
|
use crate::formats::renderer::FormatRenderer;
|
|
|
|
use crate::html::render::Context;
|
|
|
|
|
2021-05-09 23:22:22 +00:00
|
|
|
use rustc_data_structures::fx::FxHashMap;
|
|
|
|
use rustc_hir::{
|
|
|
|
self as hir,
|
|
|
|
intravisit::{self, Visitor},
|
2021-08-26 21:43:12 +00:00
|
|
|
HirId,
|
2021-05-09 23:22:22 +00:00
|
|
|
};
|
|
|
|
use rustc_interface::interface;
|
2021-09-17 01:12:45 +00:00
|
|
|
use rustc_macros::{Decodable, Encodable};
|
2021-05-09 23:22:22 +00:00
|
|
|
use rustc_middle::hir::map::Map;
|
2021-05-30 17:00:44 +00:00
|
|
|
use rustc_middle::ty::{self, TyCtxt};
|
2021-09-17 01:12:45 +00:00
|
|
|
use rustc_serialize::{
|
|
|
|
opaque::{Decoder, FileEncoder},
|
|
|
|
Decodable, Encodable,
|
|
|
|
};
|
2021-09-20 21:08:33 +00:00
|
|
|
use rustc_session::getopts;
|
|
|
|
use rustc_span::{
|
2021-10-13 01:26:39 +00:00
|
|
|
def_id::{CrateNum, DefPathHash, LOCAL_CRATE},
|
2021-09-20 21:08:33 +00:00
|
|
|
edition::Edition,
|
|
|
|
BytePos, FileName, SourceFile,
|
|
|
|
};
|
2021-09-17 01:12:45 +00:00
|
|
|
|
2021-06-01 21:02:09 +00:00
|
|
|
use std::fs;
|
2021-06-03 00:21:48 +00:00
|
|
|
use std::path::PathBuf;
|
|
|
|
|
2021-09-20 21:08:33 +00:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
crate struct ScrapeExamplesOptions {
|
|
|
|
output_path: PathBuf,
|
|
|
|
target_crates: Vec<String>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ScrapeExamplesOptions {
|
|
|
|
crate fn new(
|
|
|
|
matches: &getopts::Matches,
|
|
|
|
diag: &rustc_errors::Handler,
|
|
|
|
) -> Result<Option<Self>, i32> {
|
|
|
|
let output_path = matches.opt_str("scrape-examples-output-path");
|
|
|
|
let target_crates = matches.opt_strs("scrape-examples-target-crate");
|
|
|
|
match (output_path, !target_crates.is_empty()) {
|
|
|
|
(Some(output_path), true) => Ok(Some(ScrapeExamplesOptions {
|
|
|
|
output_path: PathBuf::from(output_path),
|
|
|
|
target_crates,
|
|
|
|
})),
|
|
|
|
(Some(_), false) | (None, true) => {
|
|
|
|
diag.err(&format!("must use --scrape-examples-output-path and --scrape-examples-target-crate together"));
|
|
|
|
Err(1)
|
|
|
|
}
|
|
|
|
(None, false) => Ok(None),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-17 01:12:45 +00:00
|
|
|
#[derive(Encodable, Decodable, Debug, Clone)]
|
2021-08-26 21:43:12 +00:00
|
|
|
crate struct SyntaxRange {
|
|
|
|
crate byte_span: (u32, u32),
|
|
|
|
crate line_span: (usize, usize),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl SyntaxRange {
|
|
|
|
fn new(span: rustc_span::Span, file: &SourceFile) -> Self {
|
|
|
|
let get_pos = |bytepos: BytePos| file.original_relative_byte_pos(bytepos).0;
|
|
|
|
let get_line = |bytepos: BytePos| file.lookup_line(bytepos).unwrap();
|
|
|
|
|
|
|
|
SyntaxRange {
|
|
|
|
byte_span: (get_pos(span.lo()), get_pos(span.hi())),
|
|
|
|
line_span: (get_line(span.lo()), get_line(span.hi())),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-17 01:12:45 +00:00
|
|
|
#[derive(Encodable, Decodable, Debug, Clone)]
|
2021-06-03 00:21:48 +00:00
|
|
|
crate struct CallLocation {
|
2021-08-26 21:43:12 +00:00
|
|
|
crate call_expr: SyntaxRange,
|
|
|
|
crate enclosing_item: SyntaxRange,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl CallLocation {
|
|
|
|
fn new(
|
|
|
|
tcx: TyCtxt<'_>,
|
|
|
|
expr_span: rustc_span::Span,
|
|
|
|
expr_id: HirId,
|
2021-09-17 01:12:45 +00:00
|
|
|
source_file: &SourceFile,
|
2021-08-26 21:43:12 +00:00
|
|
|
) -> Self {
|
2021-09-17 01:12:45 +00:00
|
|
|
let enclosing_item_span =
|
|
|
|
tcx.hir().span_with_body(tcx.hir().get_parent_item(expr_id)).source_callsite();
|
2021-08-26 21:43:12 +00:00
|
|
|
assert!(enclosing_item_span.contains(expr_span));
|
|
|
|
|
|
|
|
CallLocation {
|
|
|
|
call_expr: SyntaxRange::new(expr_span, source_file),
|
|
|
|
enclosing_item: SyntaxRange::new(enclosing_item_span, source_file),
|
|
|
|
}
|
|
|
|
}
|
2021-06-03 00:21:48 +00:00
|
|
|
}
|
2021-05-09 23:22:22 +00:00
|
|
|
|
2021-09-17 01:12:45 +00:00
|
|
|
#[derive(Encodable, Decodable, Debug, Clone)]
|
2021-06-03 00:21:48 +00:00
|
|
|
crate struct CallData {
|
|
|
|
crate locations: Vec<CallLocation>,
|
|
|
|
crate url: String,
|
|
|
|
crate display_name: String,
|
2021-09-17 01:12:45 +00:00
|
|
|
crate edition: Edition,
|
2021-06-03 00:21:48 +00:00
|
|
|
}
|
2021-09-17 01:12:45 +00:00
|
|
|
|
2021-06-03 00:21:48 +00:00
|
|
|
crate type FnCallLocations = FxHashMap<PathBuf, CallData>;
|
2021-09-21 22:49:36 +00:00
|
|
|
crate type AllCallLocations = FxHashMap<DefPathHash, FnCallLocations>;
|
2021-05-09 23:22:22 +00:00
|
|
|
|
|
|
|
/// Visitor for traversing a crate and finding instances of function calls.
|
|
|
|
struct FindCalls<'a, 'tcx> {
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
map: Map<'tcx>,
|
2021-06-03 00:21:48 +00:00
|
|
|
cx: Context<'tcx>,
|
2021-09-20 21:08:33 +00:00
|
|
|
target_crates: Vec<CrateNum>,
|
2021-05-09 23:22:22 +00:00
|
|
|
calls: &'a mut AllCallLocations,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for FindCalls<'a, 'tcx>
|
|
|
|
where
|
|
|
|
'tcx: 'a,
|
|
|
|
{
|
|
|
|
type Map = Map<'tcx>;
|
|
|
|
|
|
|
|
fn nested_visit_map(&mut self) -> intravisit::NestedVisitorMap<Self::Map> {
|
|
|
|
intravisit::NestedVisitorMap::OnlyBodies(self.map)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
|
|
|
|
intravisit::walk_expr(self, ex);
|
|
|
|
|
2021-09-17 01:12:45 +00:00
|
|
|
let tcx = self.tcx;
|
2021-10-29 20:21:50 +00:00
|
|
|
|
|
|
|
// If we visit an item that contains an expression outside a function body,
|
|
|
|
// then we need to exit before calling typeck (which will panic). See
|
|
|
|
// test/run-make/rustdoc-scrape-examples-invalid-expr for an example.
|
|
|
|
let hir = tcx.hir();
|
|
|
|
let owner = hir.local_def_id_to_hir_id(ex.hir_id.owner);
|
|
|
|
if hir.maybe_body_owned_by(owner).is_none() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get type of function if expression is a function call
|
2021-05-09 23:22:22 +00:00
|
|
|
let (ty, span) = match ex.kind {
|
2021-06-01 21:02:09 +00:00
|
|
|
hir::ExprKind::Call(f, _) => {
|
2021-09-17 01:12:45 +00:00
|
|
|
let types = tcx.typeck(ex.hir_id.owner);
|
2021-10-29 20:21:50 +00:00
|
|
|
|
|
|
|
match types.node_type_opt(f.hir_id) {
|
|
|
|
Some(ty) => (ty, ex.span),
|
|
|
|
None => {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
2021-06-01 21:02:09 +00:00
|
|
|
}
|
2021-05-09 23:22:22 +00:00
|
|
|
hir::ExprKind::MethodCall(_, _, _, span) => {
|
2021-09-17 01:12:45 +00:00
|
|
|
let types = tcx.typeck(ex.hir_id.owner);
|
2021-05-09 23:22:22 +00:00
|
|
|
let def_id = types.type_dependent_def_id(ex.hir_id).unwrap();
|
2021-09-17 01:12:45 +00:00
|
|
|
(tcx.type_of(def_id), span)
|
2021-05-09 23:22:22 +00:00
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-10-08 22:32:22 +00:00
|
|
|
// If this span comes from a macro expansion, then the source code may not actually show
|
|
|
|
// a use of the given item, so it would be a poor example. Hence, we skip all uses in macros.
|
|
|
|
if span.from_expansion() {
|
|
|
|
return;
|
|
|
|
}
|
2021-06-03 00:21:48 +00:00
|
|
|
|
2021-06-01 21:02:09 +00:00
|
|
|
// Save call site if the function resolves to a concrete definition
|
2021-05-30 17:00:44 +00:00
|
|
|
if let ty::FnDef(def_id, _) = ty.kind() {
|
2021-09-20 21:08:33 +00:00
|
|
|
// Ignore functions not from the crate being documented
|
|
|
|
if self.target_crates.iter().all(|krate| *krate != def_id.krate) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-09-17 01:12:45 +00:00
|
|
|
let file = tcx.sess.source_map().lookup_char_pos(span.lo()).file;
|
2021-06-03 00:21:48 +00:00
|
|
|
let file_path = match file.name.clone() {
|
|
|
|
FileName::Real(real_filename) => real_filename.into_local_path(),
|
|
|
|
_ => None,
|
|
|
|
};
|
|
|
|
|
|
|
|
if let Some(file_path) = file_path {
|
|
|
|
let abs_path = fs::canonicalize(file_path.clone()).unwrap();
|
|
|
|
let cx = &self.cx;
|
2021-09-17 01:12:45 +00:00
|
|
|
let mk_call_data = || {
|
|
|
|
let clean_span = crate::clean::types::Span::new(span);
|
2021-10-07 17:27:09 +00:00
|
|
|
let url = cx.href_from_span(clean_span, false).unwrap();
|
2021-09-17 01:12:45 +00:00
|
|
|
let display_name = file_path.display().to_string();
|
2021-09-20 21:08:33 +00:00
|
|
|
let edition = span.edition();
|
2021-09-17 01:12:45 +00:00
|
|
|
CallData { locations: Vec::new(), url, display_name, edition }
|
|
|
|
};
|
|
|
|
|
2021-09-21 22:49:36 +00:00
|
|
|
let fn_key = tcx.def_path_hash(*def_id);
|
2021-09-17 01:12:45 +00:00
|
|
|
let fn_entries = self.calls.entry(fn_key).or_default();
|
|
|
|
|
|
|
|
let location = CallLocation::new(tcx, span, ex.hir_id, &file);
|
|
|
|
fn_entries.entry(abs_path).or_insert_with(mk_call_data).locations.push(location);
|
2021-06-03 00:21:48 +00:00
|
|
|
}
|
2021-05-09 23:22:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-03 00:21:48 +00:00
|
|
|
crate fn run(
|
|
|
|
krate: clean::Crate,
|
|
|
|
renderopts: config::RenderOptions,
|
|
|
|
cache: formats::cache::Cache,
|
2021-09-17 01:12:45 +00:00
|
|
|
tcx: TyCtxt<'_>,
|
2021-09-20 21:08:33 +00:00
|
|
|
options: ScrapeExamplesOptions,
|
2021-06-03 00:21:48 +00:00
|
|
|
) -> interface::Result<()> {
|
2021-09-17 01:12:45 +00:00
|
|
|
let inner = move || -> Result<(), String> {
|
2021-06-03 00:21:48 +00:00
|
|
|
// Generates source files for examples
|
2021-09-17 01:12:45 +00:00
|
|
|
let (cx, _) = Context::init(krate, renderopts, cache, tcx).map_err(|e| e.to_string())?;
|
2021-06-03 00:21:48 +00:00
|
|
|
|
2021-09-20 21:08:33 +00:00
|
|
|
// Collect CrateIds corresponding to provided target crates
|
|
|
|
// If two different versions of the crate in the dependency tree, then examples will be collcted from both.
|
2021-10-13 01:26:39 +00:00
|
|
|
let all_crates = tcx
|
|
|
|
.crates(())
|
|
|
|
.iter()
|
|
|
|
.chain([&LOCAL_CRATE])
|
|
|
|
.map(|crate_num| (crate_num, tcx.crate_name(*crate_num)))
|
|
|
|
.collect::<Vec<_>>();
|
2021-09-20 21:08:33 +00:00
|
|
|
let target_crates = options
|
|
|
|
.target_crates
|
|
|
|
.into_iter()
|
2021-10-13 01:26:39 +00:00
|
|
|
.map(|target| all_crates.iter().filter(move |(_, name)| name.as_str() == target))
|
2021-09-20 21:08:33 +00:00
|
|
|
.flatten()
|
2021-10-13 01:26:39 +00:00
|
|
|
.map(|(crate_num, _)| **crate_num)
|
2021-09-20 21:08:33 +00:00
|
|
|
.collect::<Vec<_>>();
|
|
|
|
|
2021-10-13 01:26:39 +00:00
|
|
|
debug!("All crates in TyCtxt: {:?}", all_crates);
|
|
|
|
debug!("Scrape examples target_crates: {:?}", target_crates);
|
|
|
|
|
2021-06-03 00:21:48 +00:00
|
|
|
// Run call-finder on all items
|
|
|
|
let mut calls = FxHashMap::default();
|
2021-09-20 21:08:33 +00:00
|
|
|
let mut finder = FindCalls { calls: &mut calls, tcx, map: tcx.hir(), cx, target_crates };
|
2021-10-07 04:43:40 +00:00
|
|
|
tcx.hir().visit_all_item_likes(&mut finder.as_deep_visitor());
|
2021-06-03 00:21:48 +00:00
|
|
|
|
2021-11-04 20:57:09 +00:00
|
|
|
// Sort call locations within a given file in document order
|
|
|
|
for fn_calls in calls.values_mut() {
|
|
|
|
for file_calls in fn_calls.values_mut() {
|
|
|
|
file_calls.locations.sort_by_key(|loc| loc.call_expr.byte_span.0);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-17 01:12:45 +00:00
|
|
|
// Save output to provided path
|
2021-09-20 21:08:33 +00:00
|
|
|
let mut encoder = FileEncoder::new(options.output_path).map_err(|e| e.to_string())?;
|
2021-09-17 01:12:45 +00:00
|
|
|
calls.encode(&mut encoder).map_err(|e| e.to_string())?;
|
|
|
|
encoder.flush().map_err(|e| e.to_string())?;
|
2021-06-03 00:21:48 +00:00
|
|
|
|
|
|
|
Ok(())
|
2021-06-01 21:02:09 +00:00
|
|
|
};
|
2021-05-09 23:22:22 +00:00
|
|
|
|
2021-09-17 01:12:45 +00:00
|
|
|
if let Err(e) = inner() {
|
|
|
|
tcx.sess.fatal(&e);
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
2021-05-09 23:22:22 +00:00
|
|
|
}
|
2021-08-26 03:15:46 +00:00
|
|
|
|
2021-10-07 17:27:09 +00:00
|
|
|
// Note: the Handler must be passed in explicitly because sess isn't available while parsing options
|
2021-08-26 03:15:46 +00:00
|
|
|
crate fn load_call_locations(
|
|
|
|
with_examples: Vec<String>,
|
|
|
|
diag: &rustc_errors::Handler,
|
2021-09-17 01:12:45 +00:00
|
|
|
) -> Result<AllCallLocations, i32> {
|
|
|
|
let inner = || {
|
|
|
|
let mut all_calls: AllCallLocations = FxHashMap::default();
|
|
|
|
for path in with_examples {
|
2021-08-26 03:15:46 +00:00
|
|
|
let bytes = fs::read(&path).map_err(|e| format!("{} (for path {})", e, path))?;
|
2021-09-17 01:12:45 +00:00
|
|
|
let mut decoder = Decoder::new(&bytes, 0);
|
|
|
|
let calls = AllCallLocations::decode(&mut decoder)?;
|
|
|
|
|
|
|
|
for (function, fn_calls) in calls.into_iter() {
|
|
|
|
all_calls.entry(function).or_default().extend(fn_calls.into_iter());
|
2021-08-26 03:15:46 +00:00
|
|
|
}
|
2021-09-17 01:12:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(all_calls)
|
|
|
|
};
|
|
|
|
|
|
|
|
inner().map_err(|e: String| {
|
|
|
|
diag.err(&format!("failed to load examples: {}", e));
|
|
|
|
1
|
|
|
|
})
|
2021-08-26 03:15:46 +00:00
|
|
|
}
|