Skip to content

Commit d58c9df

Browse files
committed
Only highlight identifier in scraped examples, not arguments
1 parent 7e81b0a commit d58c9df

File tree

3 files changed

+44
-49
lines changed

3 files changed

+44
-49
lines changed

src/librustdoc/html/render/mod.rs

Lines changed: 4 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2717,45 +2717,20 @@ fn render_call_locations(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item) {
27172717
// The output code is limited to that byte range.
27182718
let contents_subset = &contents[(byte_min as usize)..(byte_max as usize)];
27192719

2720-
// Given a call-site range, return the set of sub-ranges that exclude leading whitespace
2721-
// when the range spans multiple lines.
2722-
let strip_leading_whitespace = |(lo, hi): (u32, u32)| -> Vec<(u32, u32)> {
2723-
let contents_range = &contents_subset[(lo as usize)..(hi as usize)];
2724-
let mut ignoring_whitespace = false;
2725-
let mut ranges = Vec::new();
2726-
let mut cur_lo = 0;
2727-
for (idx, chr) in contents_range.char_indices() {
2728-
let idx = idx as u32;
2729-
if ignoring_whitespace {
2730-
if !chr.is_whitespace() {
2731-
ignoring_whitespace = false;
2732-
cur_lo = idx;
2733-
}
2734-
} else if chr == '\n' {
2735-
ranges.push((lo + cur_lo, lo + idx));
2736-
cur_lo = idx;
2737-
ignoring_whitespace = true;
2738-
}
2739-
}
2740-
ranges.push((lo + cur_lo, hi));
2741-
ranges
2742-
};
2743-
27442720
// The call locations need to be updated to reflect that the size of the program has changed.
27452721
// Specifically, the ranges are all subtracted by `byte_min` since that's the new zero point.
27462722
let (mut byte_ranges, line_ranges): (Vec<_>, Vec<_>) = call_data
27472723
.locations
27482724
.iter()
27492725
.map(|loc| {
2750-
let (byte_lo, byte_hi) = loc.call_expr.byte_span;
2726+
let (byte_lo, byte_hi) = loc.call_ident.byte_span;
27512727
let (line_lo, line_hi) = loc.call_expr.line_span;
27522728
let byte_range = (byte_lo - byte_min, byte_hi - byte_min);
2753-
let byte_ranges = strip_leading_whitespace(byte_range);
27542729

27552730
let line_range = (line_lo - line_min, line_hi - line_min);
27562731
let (line_url, line_title) = link_to_loc(call_data, loc);
27572732

2758-
(byte_ranges, (line_range, line_url, line_title))
2733+
(byte_range, (line_range, line_url, line_title))
27592734
})
27602735
.unzip();
27612736

@@ -2810,8 +2785,8 @@ fn render_call_locations(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item) {
28102785
let root_path = vec!["../"; cx.current.len() - 1].join("");
28112786

28122787
let mut decoration_info = FxHashMap::default();
2813-
decoration_info.insert("highlight focus", byte_ranges.remove(0));
2814-
decoration_info.insert("highlight", byte_ranges.into_iter().flatten().collect());
2788+
decoration_info.insert("highlight focus", vec![byte_ranges.remove(0)]);
2789+
decoration_info.insert("highlight", byte_ranges);
28152790

28162791
sources::print_src(
28172792
w,

src/librustdoc/scrape_examples.rs

Lines changed: 38 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -85,17 +85,20 @@ impl SyntaxRange {
8585
#[derive(Encodable, Decodable, Debug, Clone)]
8686
crate struct CallLocation {
8787
crate call_expr: SyntaxRange,
88+
crate call_ident: SyntaxRange,
8889
crate enclosing_item: SyntaxRange,
8990
}
9091

9192
impl CallLocation {
9293
fn new(
9394
expr_span: rustc_span::Span,
95+
ident_span: rustc_span::Span,
9496
enclosing_item_span: rustc_span::Span,
9597
source_file: &SourceFile,
9698
) -> Self {
9799
CallLocation {
98100
call_expr: SyntaxRange::new(expr_span, source_file),
101+
call_ident: SyntaxRange::new(ident_span, source_file),
99102
enclosing_item: SyntaxRange::new(enclosing_item_span, source_file),
100103
}
101104
}
@@ -146,24 +149,39 @@ where
146149
}
147150

148151
// Get type of function if expression is a function call
149-
let (ty, span) = match ex.kind {
152+
let (ty, call_span, ident_span) = match ex.kind {
150153
hir::ExprKind::Call(f, _) => {
151154
let types = tcx.typeck(ex.hir_id.owner);
152155

153156
if let Some(ty) = types.node_type_opt(f.hir_id) {
154-
(ty, ex.span)
157+
(ty, ex.span, f.span)
155158
} else {
156159
trace!("node_type_opt({}) = None", f.hir_id);
157160
return;
158161
}
159162
}
160-
hir::ExprKind::MethodCall(_, _, span) => {
163+
hir::ExprKind::MethodCall(_, args, call_span) => {
161164
let types = tcx.typeck(ex.hir_id.owner);
162165
let Some(def_id) = types.type_dependent_def_id(ex.hir_id) else {
163166
trace!("type_dependent_def_id({}) = None", ex.hir_id);
164167
return;
165168
};
166-
(tcx.type_of(def_id), span)
169+
170+
// The MethodCall node doesn't directly contain a span for the
171+
// method identifier, so we have to compute it by trimming the full
172+
// span based on the arguments.
173+
let ident_span = match args.get(1) {
174+
// If there is an argument, e.g. "f(x)", then
175+
// get the span "f(" and delete the lparen.
176+
Some(arg) => {
177+
let with_paren = call_span.until(arg.span);
178+
with_paren.with_hi(with_paren.hi() - BytePos(1))
179+
}
180+
// Otherwise, just delete both parens directly.
181+
None => call_span.with_hi(call_span.hi() - BytePos(2)),
182+
};
183+
184+
(tcx.type_of(def_id), call_span, ident_span)
167185
}
168186
_ => {
169187
return;
@@ -172,8 +190,8 @@ where
172190

173191
// If this span comes from a macro expansion, then the source code may not actually show
174192
// a use of the given item, so it would be a poor example. Hence, we skip all uses in macros.
175-
if span.from_expansion() {
176-
trace!("Rejecting expr from macro: {:?}", span);
193+
if call_span.from_expansion() {
194+
trace!("Rejecting expr from macro: {:?}", call_span);
177195
return;
178196
}
179197

@@ -183,26 +201,29 @@ where
183201
.hir()
184202
.span_with_body(tcx.hir().local_def_id_to_hir_id(tcx.hir().get_parent_item(ex.hir_id)));
185203
if enclosing_item_span.from_expansion() {
186-
trace!("Rejecting expr ({:?}) from macro item: {:?}", span, enclosing_item_span);
204+
trace!("Rejecting expr ({:?}) from macro item: {:?}", call_span, enclosing_item_span);
187205
return;
188206
}
189207

190208
assert!(
191-
enclosing_item_span.contains(span),
192-
"Attempted to scrape call at [{:?}] whose enclosing item [{:?}] doesn't contain the span of the call.",
193-
span,
194-
enclosing_item_span
209+
enclosing_item_span.contains(call_span),
210+
"Attempted to scrape call at [{call_span:?}] whose enclosing item [{enclosing_item_span:?}] doesn't contain the span of the call.",
211+
);
212+
213+
assert!(
214+
call_span.contains(ident_span),
215+
"Attempted to scrape call at [{call_span:?}] whose identifier [{ident_span:?}] was not contained in the span of the call."
195216
);
196217

197218
// Save call site if the function resolves to a concrete definition
198219
if let ty::FnDef(def_id, _) = ty.kind() {
199220
if self.target_crates.iter().all(|krate| *krate != def_id.krate) {
200-
trace!("Rejecting expr from crate not being documented: {:?}", span);
221+
trace!("Rejecting expr from crate not being documented: {call_span:?}");
201222
return;
202223
}
203224

204225
let source_map = tcx.sess.source_map();
205-
let file = source_map.lookup_char_pos(span.lo()).file;
226+
let file = source_map.lookup_char_pos(call_span.lo()).file;
206227
let file_path = match file.name.clone() {
207228
FileName::Real(real_filename) => real_filename.into_local_path(),
208229
_ => None,
@@ -212,20 +233,20 @@ where
212233
let abs_path = fs::canonicalize(file_path.clone()).unwrap();
213234
let cx = &self.cx;
214235
let mk_call_data = || {
215-
let clean_span = crate::clean::types::Span::new(span);
236+
let clean_span = crate::clean::types::Span::new(call_span);
216237
let url = cx.href_from_span(clean_span, false).unwrap();
217238
let display_name = file_path.display().to_string();
218-
let edition = span.edition();
239+
let edition = call_span.edition();
219240
CallData { locations: Vec::new(), url, display_name, edition }
220241
};
221242

222243
let fn_key = tcx.def_path_hash(*def_id);
223244
let fn_entries = self.calls.entry(fn_key).or_default();
224245

225-
trace!("Including expr: {:?}", span);
246+
trace!("Including expr: {:?}", call_span);
226247
let enclosing_item_span =
227248
source_map.span_extend_to_prev_char(enclosing_item_span, '\n', false);
228-
let location = CallLocation::new(span, enclosing_item_span, &file);
249+
let location = CallLocation::new(call_span, ident_span, enclosing_item_span, &file);
229250
fn_entries.entry(abs_path).or_insert_with(mk_call_data).locations.push(location);
230251
}
231252
}
Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
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'
3+
// @has foobar/fn.ok.html '//*[@class="highlight focus"]' ''
4+
// @has foobar/fn.ok.html '//*[@class="highlight"]' ''
65

76
pub fn ok(_x: i32) {}

0 commit comments

Comments
 (0)