1use std::mem;
2use std::ops::Range;
3
4use itertools::Itertools;
5use pulldown_cmark::{
6 BrokenLink, BrokenLinkCallback, CowStr, Event, LinkType, Options, Parser, Tag,
7};
8use rustc_ast as ast;
9use rustc_ast::attr::AttributeExt;
10use rustc_ast::join_path_syms;
11use rustc_ast::util::comments::beautify_doc_string;
12use rustc_data_structures::fx::FxIndexMap;
13use rustc_data_structures::unord::UnordSet;
14use rustc_middle::ty::TyCtxt;
15use rustc_span::def_id::DefId;
16use rustc_span::source_map::SourceMap;
17use rustc_span::{DUMMY_SP, InnerSpan, Span, Symbol, sym};
18use thin_vec::ThinVec;
19use tracing::{debug, trace};
20
21#[cfg(test)]
22mod tests;
23
24#[derive(Clone, Copy, PartialEq, Eq, Debug)]
25pub enum DocFragmentKind {
26 SugaredDoc,
28 RawDoc,
30}
31
32#[derive(Clone, PartialEq, Eq, Debug)]
41pub struct DocFragment {
42 pub span: Span,
43 pub item_id: Option<DefId>,
50 pub doc: Symbol,
51 pub kind: DocFragmentKind,
52 pub indent: usize,
53 pub from_expansion: bool,
56}
57
58#[derive(Clone, Copy, Debug)]
59pub enum MalformedGenerics {
60 UnbalancedAngleBrackets,
64 MissingType,
70 HasFullyQualifiedSyntax,
77 InvalidPathSeparator,
89 TooManyAngleBrackets,
93 EmptyAngleBrackets,
97}
98
99pub fn unindent_doc_fragments(docs: &mut [DocFragment]) {
113 let add = if docs.windows(2).any(|arr| arr[0].kind != arr[1].kind)
126 && docs.iter().any(|d| d.kind == DocFragmentKind::SugaredDoc)
127 {
128 1
131 } else {
132 0
133 };
134
135 let Some(min_indent) = docs
145 .iter()
146 .map(|fragment| {
147 fragment
148 .doc
149 .as_str()
150 .lines()
151 .filter(|line| line.chars().any(|c| !c.is_whitespace()))
152 .map(|line| {
153 let whitespace = line.chars().take_while(|c| *c == ' ' || *c == '\t').count();
156 whitespace
157 + (if fragment.kind == DocFragmentKind::SugaredDoc { 0 } else { add })
158 })
159 .min()
160 .unwrap_or(usize::MAX)
161 })
162 .min()
163 else {
164 return;
165 };
166
167 for fragment in docs {
168 if fragment.doc == sym::empty {
169 continue;
170 }
171
172 let indent = if fragment.kind != DocFragmentKind::SugaredDoc && min_indent > 0 {
173 min_indent - add
174 } else {
175 min_indent
176 };
177
178 fragment.indent = indent;
179 }
180}
181
182pub fn add_doc_fragment(out: &mut String, frag: &DocFragment) {
188 if frag.doc == sym::empty {
189 out.push('\n');
190 return;
191 }
192 let s = frag.doc.as_str();
193 let mut iter = s.lines();
194
195 while let Some(line) = iter.next() {
196 if line.chars().any(|c| !c.is_whitespace()) {
197 assert!(line.len() >= frag.indent);
198 out.push_str(&line[frag.indent..]);
199 } else {
200 out.push_str(line);
201 }
202 out.push('\n');
203 }
204}
205
206pub fn attrs_to_doc_fragments<'a, A: AttributeExt + Clone + 'a>(
207 attrs: impl Iterator<Item = (&'a A, Option<DefId>)>,
208 doc_only: bool,
209) -> (Vec<DocFragment>, ThinVec<A>) {
210 let mut doc_fragments = Vec::new();
211 let mut other_attrs = ThinVec::<A>::new();
212 for (attr, item_id) in attrs {
213 if let Some((doc_str, comment_kind)) = attr.doc_str_and_comment_kind() {
214 let doc = beautify_doc_string(doc_str, comment_kind);
215 let (span, kind, from_expansion) = if attr.is_doc_comment() {
216 let span = attr.span();
217 (span, DocFragmentKind::SugaredDoc, span.from_expansion())
218 } else {
219 let attr_span = attr.span();
220 let (span, from_expansion) = match attr.value_span() {
221 Some(sp) => (sp.with_ctxt(attr_span.ctxt()), sp.from_expansion()),
222 None => (attr_span, attr_span.from_expansion()),
223 };
224 (span, DocFragmentKind::RawDoc, from_expansion)
225 };
226 let fragment = DocFragment { span, doc, kind, item_id, indent: 0, from_expansion };
227 doc_fragments.push(fragment);
228 } else if !doc_only {
229 other_attrs.push(attr.clone());
230 }
231 }
232
233 unindent_doc_fragments(&mut doc_fragments);
234
235 (doc_fragments, other_attrs)
236}
237
238pub fn prepare_to_doc_link_resolution(
244 doc_fragments: &[DocFragment],
245) -> FxIndexMap<Option<DefId>, String> {
246 let mut res = FxIndexMap::default();
247 for fragment in doc_fragments {
248 let out_str = res.entry(fragment.item_id).or_default();
249 add_doc_fragment(out_str, fragment);
250 }
251 res
252}
253
254pub fn main_body_opts() -> Options {
256 Options::ENABLE_TABLES
257 | Options::ENABLE_FOOTNOTES
258 | Options::ENABLE_STRIKETHROUGH
259 | Options::ENABLE_TASKLISTS
260 | Options::ENABLE_SMART_PUNCTUATION
261}
262
263fn strip_generics_from_path_segment(segment: Vec<char>) -> Result<Symbol, MalformedGenerics> {
264 let mut stripped_segment = String::new();
265 let mut param_depth = 0;
266
267 let mut latest_generics_chunk = String::new();
268
269 for c in segment {
270 if c == '<' {
271 param_depth += 1;
272 latest_generics_chunk.clear();
273 } else if c == '>' {
274 param_depth -= 1;
275 if latest_generics_chunk.contains(" as ") {
276 return Err(MalformedGenerics::HasFullyQualifiedSyntax);
279 }
280 } else if param_depth == 0 {
281 stripped_segment.push(c);
282 } else {
283 latest_generics_chunk.push(c);
284 }
285 }
286
287 if param_depth == 0 {
288 Ok(Symbol::intern(&stripped_segment))
289 } else {
290 Err(MalformedGenerics::UnbalancedAngleBrackets)
292 }
293}
294
295pub fn strip_generics_from_path(path_str: &str) -> Result<Box<str>, MalformedGenerics> {
296 if !path_str.contains(['<', '>']) {
297 return Ok(path_str.into());
298 }
299 let mut stripped_segments = vec![];
300 let mut path = path_str.chars().peekable();
301 let mut segment = Vec::new();
302
303 while let Some(chr) = path.next() {
304 match chr {
305 ':' => {
306 if path.next_if_eq(&':').is_some() {
307 let stripped_segment =
308 strip_generics_from_path_segment(mem::take(&mut segment))?;
309 if !stripped_segment.is_empty() {
310 stripped_segments.push(stripped_segment);
311 }
312 } else {
313 return Err(MalformedGenerics::InvalidPathSeparator);
314 }
315 }
316 '<' => {
317 segment.push(chr);
318
319 match path.next() {
320 Some('<') => {
321 return Err(MalformedGenerics::TooManyAngleBrackets);
322 }
323 Some('>') => {
324 return Err(MalformedGenerics::EmptyAngleBrackets);
325 }
326 Some(chr) => {
327 segment.push(chr);
328
329 while let Some(chr) = path.next_if(|c| *c != '>') {
330 segment.push(chr);
331 }
332 }
333 None => break,
334 }
335 }
336 _ => segment.push(chr),
337 }
338 trace!("raw segment: {:?}", segment);
339 }
340
341 if !segment.is_empty() {
342 let stripped_segment = strip_generics_from_path_segment(segment)?;
343 if !stripped_segment.is_empty() {
344 stripped_segments.push(stripped_segment);
345 }
346 }
347
348 debug!("path_str: {path_str:?}\nstripped segments: {stripped_segments:?}");
349
350 if !stripped_segments.is_empty() {
351 let stripped_path = join_path_syms(stripped_segments);
352 Ok(stripped_path.into())
353 } else {
354 Err(MalformedGenerics::MissingType)
355 }
356}
357
358pub fn inner_docs(attrs: &[impl AttributeExt]) -> bool {
363 for attr in attrs {
364 if let Some(attr_style) = attr.doc_resolution_scope() {
365 return attr_style == ast::AttrStyle::Inner;
366 }
367 }
368 true
369}
370
371pub fn has_primitive_or_keyword_docs(attrs: &[impl AttributeExt]) -> bool {
373 for attr in attrs {
374 if attr.has_name(sym::rustc_doc_primitive) {
375 return true;
376 } else if attr.has_name(sym::doc)
377 && let Some(items) = attr.meta_item_list()
378 {
379 for item in items {
380 if item.has_name(sym::keyword) {
381 return true;
382 }
383 }
384 }
385 }
386 false
387}
388
389fn preprocess_link(link: &str) -> Box<str> {
393 let link = link.replace('`', "");
394 let link = link.split('#').next().unwrap();
395 let link = link.trim();
396 let link = link.rsplit('@').next().unwrap();
397 let link = link.strip_suffix("()").unwrap_or(link);
398 let link = link.strip_suffix("{}").unwrap_or(link);
399 let link = link.strip_suffix("[]").unwrap_or(link);
400 let link = if link != "!" { link.strip_suffix('!').unwrap_or(link) } else { link };
401 let link = link.trim();
402 strip_generics_from_path(link).unwrap_or_else(|_| link.into())
403}
404
405pub fn may_be_doc_link(link_type: LinkType) -> bool {
408 match link_type {
409 LinkType::Inline
410 | LinkType::Reference
411 | LinkType::ReferenceUnknown
412 | LinkType::Collapsed
413 | LinkType::CollapsedUnknown
414 | LinkType::Shortcut
415 | LinkType::ShortcutUnknown => true,
416 LinkType::Autolink | LinkType::Email => false,
417 }
418}
419
420pub(crate) fn attrs_to_preprocessed_links<A: AttributeExt + Clone>(attrs: &[A]) -> Vec<Box<str>> {
423 let (doc_fragments, _) = attrs_to_doc_fragments(attrs.iter().map(|attr| (attr, None)), true);
424 let doc = prepare_to_doc_link_resolution(&doc_fragments).into_values().next().unwrap();
425
426 parse_links(&doc)
427}
428
429fn parse_links<'md>(doc: &'md str) -> Vec<Box<str>> {
432 let mut broken_link_callback = |link: BrokenLink<'md>| Some((link.reference, "".into()));
433 let mut event_iter = Parser::new_with_broken_link_callback(
434 doc,
435 main_body_opts(),
436 Some(&mut broken_link_callback),
437 );
438 let mut links = Vec::new();
439
440 let mut refids = UnordSet::default();
441
442 while let Some(event) = event_iter.next() {
443 match event {
444 Event::Start(Tag::Link { link_type, dest_url, title: _, id })
445 if may_be_doc_link(link_type) =>
446 {
447 if matches!(
448 link_type,
449 LinkType::Inline
450 | LinkType::ReferenceUnknown
451 | LinkType::Reference
452 | LinkType::Shortcut
453 | LinkType::ShortcutUnknown
454 ) {
455 if let Some(display_text) = collect_link_data(&mut event_iter) {
456 links.push(display_text);
457 }
458 }
459 if matches!(
460 link_type,
461 LinkType::Reference | LinkType::Shortcut | LinkType::Collapsed
462 ) {
463 refids.insert(id);
464 }
465
466 links.push(preprocess_link(&dest_url));
467 }
468 _ => {}
469 }
470 }
471
472 for (label, refdef) in event_iter.reference_definitions().iter().sorted_by_key(|x| x.0) {
473 if !refids.contains(label) {
474 links.push(preprocess_link(&refdef.dest));
475 }
476 }
477
478 links
479}
480
481fn collect_link_data<'input, F: BrokenLinkCallback<'input>>(
483 event_iter: &mut Parser<'input, F>,
484) -> Option<Box<str>> {
485 let mut display_text: Option<String> = None;
486 let mut append_text = |text: CowStr<'_>| {
487 if let Some(display_text) = &mut display_text {
488 display_text.push_str(&text);
489 } else {
490 display_text = Some(text.to_string());
491 }
492 };
493
494 while let Some(event) = event_iter.next() {
495 match event {
496 Event::Text(text) => {
497 append_text(text);
498 }
499 Event::Code(code) => {
500 append_text(code);
501 }
502 Event::End(_) => {
503 break;
504 }
505 _ => {}
506 }
507 }
508
509 display_text.map(String::into_boxed_str)
510}
511
512pub fn span_of_fragments(fragments: &[DocFragment]) -> Option<Span> {
514 let (first_fragment, last_fragment) = match fragments {
515 [] => return None,
516 [first, .., last] => (first, last),
517 [first] => (first, first),
518 };
519 if first_fragment.span == DUMMY_SP {
520 return None;
521 }
522 Some(first_fragment.span.to(last_fragment.span))
523}
524
525pub fn source_span_for_markdown_range(
547 tcx: TyCtxt<'_>,
548 markdown: &str,
549 md_range: &Range<usize>,
550 fragments: &[DocFragment],
551) -> Option<(Span, bool)> {
552 let map = tcx.sess.source_map();
553 source_span_for_markdown_range_inner(map, markdown, md_range, fragments)
554}
555
556pub fn source_span_for_markdown_range_inner(
558 map: &SourceMap,
559 markdown: &str,
560 md_range: &Range<usize>,
561 fragments: &[DocFragment],
562) -> Option<(Span, bool)> {
563 use rustc_span::BytePos;
564
565 if let &[fragment] = &fragments
566 && fragment.kind == DocFragmentKind::RawDoc
567 && let Ok(snippet) = map.span_to_snippet(fragment.span)
568 && snippet.trim_end() == markdown.trim_end()
569 && let Ok(md_range_lo) = u32::try_from(md_range.start)
570 && let Ok(md_range_hi) = u32::try_from(md_range.end)
571 {
572 return Some((
574 Span::new(
575 fragment.span.lo() + rustc_span::BytePos(md_range_lo),
576 fragment.span.lo() + rustc_span::BytePos(md_range_hi),
577 fragment.span.ctxt(),
578 fragment.span.parent(),
579 ),
580 fragment.from_expansion,
581 ));
582 }
583
584 let is_all_sugared_doc = fragments.iter().all(|frag| frag.kind == DocFragmentKind::SugaredDoc);
585
586 if !is_all_sugared_doc {
587 let mut match_data = None;
592 let pat = &markdown[md_range.clone()];
593 if pat.is_empty() {
595 return None;
596 }
597 for (i, fragment) in fragments.iter().enumerate() {
598 if let Ok(snippet) = map.span_to_snippet(fragment.span)
599 && let Some(match_start) = snippet.find(pat)
600 {
601 if match_data.is_none()
606 && !snippet.as_bytes()[match_start + 1..]
607 .windows(pat.len())
608 .any(|s| s == pat.as_bytes())
609 {
610 match_data = Some((i, match_start));
611 } else {
612 return None;
614 }
615 }
616 }
617 if let Some((i, match_start)) = match_data {
618 let fragment = &fragments[i];
619 let sp = fragment.span;
620 let lo = sp.lo() + BytePos(match_start as u32);
623 return Some((
624 sp.with_lo(lo).with_hi(lo + BytePos((md_range.end - md_range.start) as u32)),
625 fragment.from_expansion,
626 ));
627 }
628 return None;
629 }
630
631 let snippet = map.span_to_snippet(span_of_fragments(fragments)?).ok()?;
632
633 let starting_line = markdown[..md_range.start].matches('\n').count();
634 let ending_line = starting_line + markdown[md_range.start..md_range.end].matches('\n').count();
635
636 let mut src_lines = snippet.split_terminator('\n');
639 let md_lines = markdown.split_terminator('\n');
640
641 let mut start_bytes = 0;
644 let mut end_bytes = 0;
645
646 'outer: for (line_no, md_line) in md_lines.enumerate() {
647 loop {
648 let source_line = src_lines.next()?;
649 match source_line.find(md_line) {
650 Some(offset) => {
651 if line_no == starting_line {
652 start_bytes += offset;
653
654 if starting_line == ending_line {
655 break 'outer;
656 }
657 } else if line_no == ending_line {
658 end_bytes += offset;
659 break 'outer;
660 } else if line_no < starting_line {
661 start_bytes += source_line.len() - md_line.len();
662 } else {
663 end_bytes += source_line.len() - md_line.len();
664 }
665 break;
666 }
667 None => {
668 if line_no <= starting_line {
671 start_bytes += source_line.len() + 1;
672 } else {
673 end_bytes += source_line.len() + 1;
674 }
675 }
676 }
677 }
678 }
679
680 let span = span_of_fragments(fragments)?;
681 let src_span = span.from_inner(InnerSpan::new(
682 md_range.start + start_bytes,
683 md_range.end + start_bytes + end_bytes,
684 ));
685 Some((
686 src_span,
687 fragments.iter().any(|frag| frag.span.overlaps(src_span) && frag.from_expansion),
688 ))
689}