1use std::cell::Cell;
4use std::str::FromStr;
5use std::sync::Arc;
6
7use proc_macro2::{TokenStream, TokenTree};
8use rustc_attr_parsing::eval_config_entry;
9use rustc_hir::attrs::{AttributeKind, CfgEntry};
10use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
11use rustc_hir::{self as hir, CRATE_HIR_ID, intravisit};
12use rustc_middle::hir::nested_filter;
13use rustc_middle::ty::TyCtxt;
14use rustc_resolve::rustdoc::span_of_fragments;
15use rustc_span::source_map::SourceMap;
16use rustc_span::{BytePos, DUMMY_SP, FileName, Pos, Span, sym};
17
18use super::{DocTestVisitor, ScrapedDocTest};
19use crate::clean::cfg::Cfg;
20use crate::clean::{Attributes, CfgInfo};
21use crate::html::markdown::{self, CodeLineMapping, ErrorCodes, LangString, MdRelLine};
22
23struct RustCollector {
24 source_map: Arc<SourceMap>,
25 tests: Vec<ScrapedDocTest>,
26 cur_path: Vec<String>,
27 position: Span,
28 global_crate_attrs: Vec<String>,
29}
30
31impl RustCollector {
32 fn get_filename(&self) -> FileName {
33 let filename = self.source_map.span_to_filename(self.position);
34 filename
35 }
36
37 fn get_base_line(&self) -> usize {
38 let sp_lo = self.position.lo().to_usize();
39 let loc = self.source_map.lookup_char_pos(BytePos(sp_lo as u32));
40 loc.line
41 }
42}
43
44impl DocTestVisitor for RustCollector {
45 fn visit_test(
46 &mut self,
47 test: String,
48 config: LangString,
49 rel_line: MdRelLine,
50 code_mappings: Vec<CodeLineMapping>,
51 ) {
52 let base_line = self.get_base_line();
53 let line = base_line + rel_line.offset();
54 let count = Cell::new(base_line);
55 let span = if line > base_line {
56 match self.source_map.span_extend_while(self.position, |c| {
57 if c == '\n' {
58 let count_v = count.get();
59 count.set(count_v + 1);
60 if count_v >= line {
61 return false;
62 }
63 }
64 true
65 }) {
66 Ok(sp) => self.source_map.span_extend_to_line(sp.shrink_to_hi()),
67 _ => self.position,
68 }
69 } else {
70 self.position
71 };
72 self.tests.push(ScrapedDocTest::new(
73 self.get_filename(),
74 line,
75 self.cur_path.clone(),
76 config,
77 test,
78 span,
79 code_mappings,
80 self.global_crate_attrs.clone(),
81 ));
82 }
83
84 fn visit_header(&mut self, _name: &str, _level: u32) {}
85}
86
87pub(super) struct HirCollector<'tcx> {
88 codes: ErrorCodes,
89 tcx: TyCtxt<'tcx>,
90 collector: RustCollector,
91}
92
93impl<'tcx> HirCollector<'tcx> {
94 pub fn new(codes: ErrorCodes, tcx: TyCtxt<'tcx>) -> Self {
95 let collector = RustCollector {
96 source_map: tcx.sess.psess.clone_source_map(),
97 cur_path: vec![],
98 position: DUMMY_SP,
99 tests: vec![],
100 global_crate_attrs: Vec::new(),
101 };
102 Self { codes, tcx, collector }
103 }
104
105 pub fn collect_crate(mut self) -> Vec<ScrapedDocTest> {
106 let tcx = self.tcx;
107 self.visit_testable(None, CRATE_DEF_ID, tcx.hir_span(CRATE_HIR_ID), |this| {
108 tcx.hir_walk_toplevel_module(this)
109 });
110 self.collector.tests
111 }
112}
113
114impl HirCollector<'_> {
115 fn visit_testable<F: FnOnce(&mut Self)>(
116 &mut self,
117 name: Option<String>,
118 def_id: LocalDefId,
119 sp: Span,
120 nested: F,
121 ) {
122 let hir_attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id));
123
124 let mut cfg_info = CfgInfo::default();
125 let mut found_features = 0;
126
127 let source_map = self.tcx.sess.source_map();
128 let old_global_crate_attrs_len = self.collector.global_crate_attrs.len();
129 for attr in hir_attrs.iter() {
134 let hir::Attribute::Parsed(attr) = attr else { continue };
135 if let AttributeKind::TargetFeature { features, .. } = attr {
136 for (feature, _) in features {
137 found_features += 1;
138 cfg_info.current_cfg &= Cfg(CfgEntry::NameValue {
139 name: sym::target_feature,
140 value: Some(*feature),
141 span: DUMMY_SP,
142 });
143 }
144 } else if let AttributeKind::Doc(d) = attr {
145 for attr_span in &d.test_attrs {
146 if let Ok(snippet) = source_map.span_to_snippet(*attr_span)
149 && let Ok(stream) = TokenStream::from_str(&snippet)
150 {
151 let mut iter = stream.into_iter().peekable();
152 while let Some(token) = iter.next() {
153 if let TokenTree::Ident(i) = token {
154 let i = i.to_string();
155 let peek = iter.peek();
156 match peek {
164 Some(TokenTree::Group(g)) => {
165 let g = g.to_string();
166 iter.next();
167 self.collector.global_crate_attrs.push(format!("{i}{g}"));
170 }
171 Some(TokenTree::Punct(p)) if p.as_char() == '=' => {
174 let p = p.to_string();
175 iter.next();
176 if let Some(last) = iter.next() {
177 self.collector
180 .global_crate_attrs
181 .push(format!("{i}{p}{last}"));
182 }
183 }
184 _ => {
185 self.collector.global_crate_attrs.push(i.to_string());
188 }
189 }
190 }
191 }
192 }
193 }
194 }
195 }
196
197 if found_features != 0
200 && !eval_config_entry(&self.tcx.sess, &cfg_info.current_cfg.inner()).as_bool()
201 {
202 return;
203 }
204
205 let mut has_name = false;
206 if let Some(name) = name {
207 self.collector.cur_path.push(name);
208 has_name = true;
209 }
210
211 let attrs = Attributes::from_hir(hir_attrs);
214 if let Some(doc) = attrs.opt_doc_value() {
215 let span = span_of_fragments(&attrs.doc_strings).unwrap_or(sp);
216 self.collector.position = if span.edition().at_least_rust_2024() {
217 span
218 } else {
219 hir_attrs
222 .iter()
223 .find(|attr| attr.doc_str().is_some())
224 .map(|attr| {
225 attr.span().ctxt().outer_expn().expansion_cause().unwrap_or(attr.span())
226 })
227 .unwrap_or(DUMMY_SP)
228 };
229 markdown::find_testable_code(
230 &doc,
231 &mut self.collector,
232 self.codes,
233 Some(&crate::html::markdown::ExtraInfo::new(
234 self.tcx,
235 def_id,
236 span,
237 Some(&attrs.doc_strings),
238 )),
239 );
240 }
241
242 nested(self);
243
244 self.collector.global_crate_attrs.truncate(old_global_crate_attrs_len);
246
247 if has_name {
248 self.collector.cur_path.pop();
249 }
250 }
251}
252
253impl<'tcx> intravisit::Visitor<'tcx> for HirCollector<'tcx> {
254 type NestedFilter = nested_filter::All;
255
256 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
257 self.tcx
258 }
259
260 fn visit_item(&mut self, item: &'tcx hir::Item<'_>) {
261 let name = match &item.kind {
262 hir::ItemKind::Impl(impl_) => {
263 Some(rustc_hir_pretty::id_to_string(&self.tcx, impl_.self_ty.hir_id))
264 }
265 _ => item.kind.ident().map(|ident| ident.to_string()),
266 };
267
268 self.visit_testable(name, item.owner_id.def_id, item.span, |this| {
269 intravisit::walk_item(this, item);
270 });
271 }
272
273 fn visit_trait_item(&mut self, item: &'tcx hir::TraitItem<'_>) {
274 self.visit_testable(
275 Some(item.ident.to_string()),
276 item.owner_id.def_id,
277 item.span,
278 |this| {
279 intravisit::walk_trait_item(this, item);
280 },
281 );
282 }
283
284 fn visit_impl_item(&mut self, item: &'tcx hir::ImplItem<'_>) {
285 self.visit_testable(
286 Some(item.ident.to_string()),
287 item.owner_id.def_id,
288 item.span,
289 |this| {
290 intravisit::walk_impl_item(this, item);
291 },
292 );
293 }
294
295 fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'_>) {
296 self.visit_testable(
297 Some(item.ident.to_string()),
298 item.owner_id.def_id,
299 item.span,
300 |this| {
301 intravisit::walk_foreign_item(this, item);
302 },
303 );
304 }
305
306 fn visit_variant(&mut self, v: &'tcx hir::Variant<'_>) {
307 self.visit_testable(Some(v.ident.to_string()), v.def_id, v.span, |this| {
308 intravisit::walk_variant(this, v);
309 });
310 }
311
312 fn visit_field_def(&mut self, f: &'tcx hir::FieldDef<'_>) {
313 self.visit_testable(Some(f.ident.to_string()), f.def_id, f.span, |this| {
314 intravisit::walk_field_def(this, f);
315 });
316 }
317}