Skip to content

Commit ad03584

Browse files
authored
Rollup merge of #90583 - willcrichton:example-analyzer, r=jyn514
Fix ICE when rustdoc is scraping examples inside of a proc macro This PR provides a clearer semantics for how --scrape-examples interacts with macros. If an expression's span AND it's enclosing item's span both are not `from_expansion`, then the example will be scraped. The added test case `rustdoc-scrape-examples-macros` shows a variety of situations. * A macro-rules macro that takes a function call as input: good * A macro-rules macro that generates a function call as output: bad * A proc-macro that generates a function call as output: bad * An attribute macro that generates a function call as output: bad * An attribute macro that takes a function call as input: good, if the proc macro is designed to propagate the input spans I ran this updated rustdoc on pyo3 and confirmed that it successfully scrapes examples from inside a proc macro, eg <img width="1013" alt="Screen Shot 2021-11-04 at 1 11 28 PM" src="https://user-images.githubusercontent.com/663326/140412691-81a3bb6b-a448-4a1b-a293-f7a795553634.png"> (cc `@mejrs)` Additionally, this PR fixes an ordering bug in the highlighting logic. Fixes #90567. r? `@jyn514`
2 parents 7dc54bf + 4846d10 commit ad03584

File tree

9 files changed

+141
-13
lines changed

9 files changed

+141
-13
lines changed

Diff for: src/librustdoc/html/highlight.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -270,12 +270,18 @@ struct Decorations {
270270

271271
impl Decorations {
272272
fn new(info: DecorationInfo) -> Self {
273-
let (starts, ends) = info
273+
// Extract tuples (start, end, kind) into separate sequences of (start, kind) and (end).
274+
let (mut starts, mut ends): (Vec<_>, Vec<_>) = info
274275
.0
275276
.into_iter()
276277
.map(|(kind, ranges)| ranges.into_iter().map(move |(lo, hi)| ((lo, kind), hi)))
277278
.flatten()
278279
.unzip();
280+
281+
// Sort the sequences in document order.
282+
starts.sort_by_key(|(lo, _)| *lo);
283+
ends.sort();
284+
279285
Decorations { starts, ends }
280286
}
281287
}

Diff for: src/librustdoc/scrape_examples.rs

+27-9
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ use rustc_data_structures::fx::FxHashMap;
1010
use rustc_hir::{
1111
self as hir,
1212
intravisit::{self, Visitor},
13-
HirId,
1413
};
1514
use rustc_interface::interface;
1615
use rustc_macros::{Decodable, Encodable};
@@ -83,15 +82,10 @@ crate struct CallLocation {
8382

8483
impl CallLocation {
8584
fn new(
86-
tcx: TyCtxt<'_>,
8785
expr_span: rustc_span::Span,
88-
expr_id: HirId,
86+
enclosing_item_span: rustc_span::Span,
8987
source_file: &SourceFile,
9088
) -> 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-
9589
CallLocation {
9690
call_expr: SyntaxRange::new(expr_span, source_file),
9791
enclosing_item: SyntaxRange::new(enclosing_item_span, source_file),
@@ -168,13 +162,29 @@ where
168162
// If this span comes from a macro expansion, then the source code may not actually show
169163
// a use of the given item, so it would be a poor example. Hence, we skip all uses in macros.
170164
if span.from_expansion() {
165+
trace!("Rejecting expr from macro: {:?}", span);
166+
return;
167+
}
168+
169+
// If the enclosing item has a span coming from a proc macro, then we also don't want to include
170+
// the example.
171+
let enclosing_item_span = tcx.hir().span_with_body(tcx.hir().get_parent_item(ex.hir_id));
172+
if enclosing_item_span.from_expansion() {
173+
trace!("Rejecting expr ({:?}) from macro item: {:?}", span, enclosing_item_span);
171174
return;
172175
}
173176

177+
assert!(
178+
enclosing_item_span.contains(span),
179+
"Attempted to scrape call at [{:?}] whose enclosing item [{:?}] doesn't contain the span of the call.",
180+
span,
181+
enclosing_item_span
182+
);
183+
174184
// Save call site if the function resolves to a concrete definition
175185
if let ty::FnDef(def_id, _) = ty.kind() {
176-
// Ignore functions not from the crate being documented
177186
if self.target_crates.iter().all(|krate| *krate != def_id.krate) {
187+
trace!("Rejecting expr from crate not being documented: {:?}", span);
178188
return;
179189
}
180190

@@ -198,7 +208,8 @@ where
198208
let fn_key = tcx.def_path_hash(*def_id);
199209
let fn_entries = self.calls.entry(fn_key).or_default();
200210

201-
let location = CallLocation::new(tcx, span, ex.hir_id, &file);
211+
trace!("Including expr: {:?}", span);
212+
let location = CallLocation::new(span, enclosing_item_span, &file);
202213
fn_entries.entry(abs_path).or_insert_with(mk_call_data).locations.push(location);
203214
}
204215
}
@@ -240,6 +251,13 @@ crate fn run(
240251
let mut finder = FindCalls { calls: &mut calls, tcx, map: tcx.hir(), cx, target_crates };
241252
tcx.hir().visit_all_item_likes(&mut finder.as_deep_visitor());
242253

254+
// Sort call locations within a given file in document order
255+
for fn_calls in calls.values_mut() {
256+
for file_calls in fn_calls.values_mut() {
257+
file_calls.locations.sort_by_key(|loc| loc.call_expr.byte_span.0);
258+
}
259+
}
260+
243261
// Save output to provided path
244262
let mut encoder = FileEncoder::new(options.output_path).map_err(|e| e.to_string())?;
245263
calls.encode(&mut encoder).map_err(|e| e.to_string())?;
+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
-include ../../run-make-fulldeps/tools.mk
2+
3+
OUTPUT_DIR := "$(TMPDIR)/rustdoc"
4+
5+
all:
6+
$(RUSTC) src/proc.rs --crate-name foobar_macro --edition=2021 --crate-type proc-macro --emit=dep-info,link
7+
8+
$(RUSTC) src/lib.rs --crate-name foobar --edition=2021 --crate-type lib --emit=dep-info,link
9+
10+
$(RUSTDOC) examples/ex.rs --crate-name ex --crate-type bin --output $(OUTPUT_DIR) \
11+
--extern foobar=$(TMPDIR)/libfoobar.rlib --extern foobar_macro=$(TMPDIR)/libfoobar_macro.so \
12+
-Z unstable-options --scrape-examples-output-path $(TMPDIR)/ex.calls --scrape-examples-target-crate foobar
13+
14+
$(RUSTDOC) src/lib.rs --crate-name foobar --crate-type lib --output $(OUTPUT_DIR) \
15+
-Z unstable-options --with-examples $(TMPDIR)/ex.calls
16+
17+
$(HTMLDOCCK) $(OUTPUT_DIR) src/lib.rs
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
extern crate foobar;
2+
extern crate foobar_macro;
3+
4+
use foobar::*;
5+
use foobar_macro::*;
6+
7+
a_proc_macro!(); // no
8+
9+
#[an_attr_macro]
10+
fn a() {
11+
f(); // no
12+
}
13+
14+
#[an_attr_macro(with_span)]
15+
fn b() {
16+
f(); // yes
17+
}
18+
19+
fn c() {
20+
a_rules_macro!(f()); // yes
21+
}
22+
23+
fn d() {
24+
a_rules_macro!(()); // no
25+
}
26+
27+
fn main(){}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// Scraped example should only include line numbers for items b and c in ex.rs
2+
// @!has foobar/fn.f.html '//*[@class="line-numbers"]' '14'
3+
// @has foobar/fn.f.html '//*[@class="line-numbers"]' '15'
4+
// @has foobar/fn.f.html '//*[@class="line-numbers"]' '21'
5+
// @!has foobar/fn.f.html '//*[@class="line-numbers"]' '22'
6+
7+
pub fn f() {}
8+
9+
#[macro_export]
10+
macro_rules! a_rules_macro {
11+
($e:expr) => { ($e, foobar::f()); }
12+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
extern crate proc_macro;
2+
use proc_macro::*;
3+
4+
#[proc_macro]
5+
pub fn a_proc_macro(_item: TokenStream) -> TokenStream {
6+
"fn ex() { foobar::f(); }".parse().unwrap()
7+
}
8+
9+
// inserts foobar::f() to the end of the function
10+
#[proc_macro_attribute]
11+
pub fn an_attr_macro(attr: TokenStream, item: TokenStream) -> TokenStream {
12+
let new_call: TokenStream = "foobar::f();".parse().unwrap();
13+
14+
let mut tokens = item.into_iter();
15+
16+
let fn_tok = tokens.next().unwrap();
17+
let ident_tok = tokens.next().unwrap();
18+
let args_tok = tokens.next().unwrap();
19+
let body = match tokens.next().unwrap() {
20+
TokenTree::Group(g) => {
21+
let new_g = Group::new(g.delimiter(), new_call);
22+
let mut outer_g = Group::new(
23+
g.delimiter(),
24+
[TokenTree::Group(g.clone()), TokenTree::Group(new_g)].into_iter().collect(),
25+
);
26+
27+
if attr.to_string() == "with_span" {
28+
outer_g.set_span(g.span());
29+
}
30+
31+
TokenTree::Group(outer_g)
32+
}
33+
_ => unreachable!(),
34+
};
35+
36+
let tokens = vec![fn_tok, ident_tok, args_tok, body].into_iter().collect::<TokenStream>();
37+
38+
tokens
39+
}

Diff for: src/test/run-make/rustdoc-scrape-examples-ordering/examples/ex1.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
fn main() {
2-
foobar::ok();
2+
foobar::ok(0);
33

44
// this is a
55

6+
// ..
7+
68
// BIG
79

810
// item
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
fn main() {
2-
foobar::ok();
2+
foobar::ok(1);
33
// small item
44
}
5+
6+
fn f() {
7+
foobar::ok(2);
8+
}
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
// @has foobar/fn.ok.html '//*[@class="docblock scraped-example-list"]' 'ex2'
22
// @has foobar/fn.ok.html '//*[@class="more-scraped-examples"]' 'ex1'
3+
// @has foobar/fn.ok.html '//*[@class="highlight focus"]' '1'
4+
// @has foobar/fn.ok.html '//*[@class="highlight"]' '2'
5+
// @has foobar/fn.ok.html '//*[@class="highlight focus"]' '0'
36

4-
pub fn ok() {}
7+
pub fn ok(_x: i32) {}

0 commit comments

Comments
 (0)