1use std::borrow::Cow;
30use std::collections::VecDeque;
31use std::fmt::{self, Write};
32use std::iter::Peekable;
33use std::ops::{ControlFlow, Range};
34use std::path::PathBuf;
35use std::str::{self, CharIndices};
36use std::sync::atomic::AtomicUsize;
37use std::sync::{Arc, Weak};
38
39use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
40use rustc_errors::{Diag, DiagMessage};
41use rustc_hir::def_id::LocalDefId;
42use rustc_middle::ty::TyCtxt;
43pub(crate) use rustc_resolve::rustdoc::main_body_opts;
44use rustc_resolve::rustdoc::pulldown_cmark::{
45 self, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag, TagEnd, html,
46};
47use rustc_resolve::rustdoc::{DocFragment, may_be_doc_link, source_span_for_markdown_range};
48use rustc_span::edition::Edition;
49use rustc_span::{Span, Symbol};
50use tracing::{debug, trace};
51
52use crate::clean::RenderedLink;
53use crate::doctest;
54use crate::doctest::GlobalTestOptions;
55use crate::html::escape::{Escape, EscapeBodyText};
56use crate::html::highlight;
57use crate::html::length_limit::HtmlWithLimit;
58use crate::html::render::small_url_encode;
59use crate::html::toc::{Toc, TocBuilder};
60
61mod footnotes;
62#[cfg(test)]
63mod tests;
64
65const MAX_HEADER_LEVEL: u32 = 6;
66
67pub(crate) fn summary_opts() -> Options {
69 Options::ENABLE_TABLES
70 | Options::ENABLE_FOOTNOTES
71 | Options::ENABLE_STRIKETHROUGH
72 | Options::ENABLE_TASKLISTS
73 | Options::ENABLE_SMART_PUNCTUATION
74}
75
76#[derive(Debug, Clone, Copy)]
77pub enum HeadingOffset {
78 H1 = 0,
79 H2,
80 H3,
81 H4,
82 H5,
83 H6,
84}
85
86pub struct Markdown<'a> {
89 pub content: &'a str,
90 pub links: &'a [RenderedLink],
92 pub ids: &'a mut IdMap,
94 pub error_codes: ErrorCodes,
96 pub edition: Edition,
98 pub playground: &'a Option<Playground>,
99 pub heading_offset: HeadingOffset,
102}
103pub(crate) struct MarkdownWithToc<'a> {
105 pub(crate) content: &'a str,
106 pub(crate) links: &'a [RenderedLink],
107 pub(crate) ids: &'a mut IdMap,
108 pub(crate) error_codes: ErrorCodes,
109 pub(crate) edition: Edition,
110 pub(crate) playground: &'a Option<Playground>,
111}
112
113pub(crate) struct MarkdownItemInfo<'a> {
116 pub(crate) content: &'a str,
117 pub(crate) links: &'a [RenderedLink],
118 pub(crate) ids: &'a mut IdMap,
119}
120
121pub(crate) struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [RenderedLink]);
123
124#[derive(Copy, Clone, PartialEq, Debug)]
125pub enum ErrorCodes {
126 Yes,
127 No,
128}
129
130impl ErrorCodes {
131 pub(crate) fn from(b: bool) -> Self {
132 match b {
133 true => ErrorCodes::Yes,
134 false => ErrorCodes::No,
135 }
136 }
137
138 pub(crate) fn as_bool(self) -> bool {
139 match self {
140 ErrorCodes::Yes => true,
141 ErrorCodes::No => false,
142 }
143 }
144}
145
146pub(crate) enum Line<'a> {
150 Hidden(&'a str),
151 Shown(Cow<'a, str>),
152}
153
154impl<'a> Line<'a> {
155 fn for_html(self) -> Option<Cow<'a, str>> {
156 match self {
157 Line::Shown(l) => Some(l),
158 Line::Hidden(_) => None,
159 }
160 }
161
162 pub(crate) fn for_code(self) -> Cow<'a, str> {
163 match self {
164 Line::Shown(l) => l,
165 Line::Hidden(l) => Cow::Borrowed(l),
166 }
167 }
168}
169
170pub(crate) fn map_line(s: &str) -> Line<'_> {
178 let trimmed = s.trim();
179 if trimmed.starts_with("##") {
180 Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
181 } else if let Some(stripped) = trimmed.strip_prefix("# ") {
182 Line::Hidden(stripped)
184 } else if trimmed == "#" {
185 Line::Hidden("")
187 } else {
188 Line::Shown(Cow::Borrowed(s))
189 }
190}
191
192fn slugify(c: char) -> Option<char> {
196 if c.is_alphanumeric() || c == '-' || c == '_' {
197 if c.is_ascii() { Some(c.to_ascii_lowercase()) } else { Some(c) }
198 } else if c.is_whitespace() && c.is_ascii() {
199 Some('-')
200 } else {
201 None
202 }
203}
204
205#[derive(Debug)]
206pub struct Playground {
207 pub crate_name: Option<Symbol>,
208 pub url: String,
209}
210
211struct CodeBlocks<'p, 'a, I: Iterator<Item = Event<'a>>> {
213 inner: I,
214 check_error_codes: ErrorCodes,
215 edition: Edition,
216 playground: &'p Option<Playground>,
219}
220
221impl<'p, 'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'p, 'a, I> {
222 fn new(
223 iter: I,
224 error_codes: ErrorCodes,
225 edition: Edition,
226 playground: &'p Option<Playground>,
227 ) -> Self {
228 CodeBlocks { inner: iter, check_error_codes: error_codes, edition, playground }
229 }
230}
231
232impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
233 type Item = Event<'a>;
234
235 fn next(&mut self) -> Option<Self::Item> {
236 let event = self.inner.next();
237 let Some(Event::Start(Tag::CodeBlock(kind))) = event else {
238 return event;
239 };
240
241 let mut original_text = String::new();
242 for event in &mut self.inner {
243 match event {
244 Event::End(TagEnd::CodeBlock) => break,
245 Event::Text(ref s) => {
246 original_text.push_str(s);
247 }
248 _ => {}
249 }
250 }
251
252 let LangString { added_classes, compile_fail, should_panic, ignore, edition, .. } =
253 match kind {
254 CodeBlockKind::Fenced(ref lang) => {
255 let parse_result =
256 LangString::parse_without_check(lang, self.check_error_codes);
257 if !parse_result.rust {
258 let added_classes = parse_result.added_classes;
259 let lang_string = if let Some(lang) = parse_result.unknown.first() {
260 format!("language-{lang}")
261 } else {
262 String::new()
263 };
264 let whitespace = if added_classes.is_empty() { "" } else { " " };
265 return Some(Event::Html(
266 format!(
267 "<div class=\"example-wrap\">\
268 <pre class=\"{lang_string}{whitespace}{added_classes}\">\
269 <code>{text}</code>\
270 </pre>\
271 </div>",
272 added_classes = added_classes.join(" "),
273 text = Escape(original_text.trim_suffix('\n')),
274 )
275 .into(),
276 ));
277 }
278 parse_result
279 }
280 CodeBlockKind::Indented => Default::default(),
281 };
282
283 let lines = original_text.lines().filter_map(|l| map_line(l).for_html());
284 let text = lines.intersperse("\n".into()).collect::<String>();
285
286 let explicit_edition = edition.is_some();
287 let edition = edition.unwrap_or(self.edition);
288
289 let playground_button = self.playground.as_ref().and_then(|playground| {
290 let krate = &playground.crate_name;
291 let url = &playground.url;
292 if url.is_empty() {
293 return None;
294 }
295 let test = original_text
296 .lines()
297 .map(|l| map_line(l).for_code())
298 .intersperse("\n".into())
299 .collect::<String>();
300 let krate = krate.as_ref().map(|s| s.as_str());
301
302 let opts = GlobalTestOptions {
305 crate_name: krate.map(String::from).unwrap_or_default(),
306 no_crate_inject: false,
307 insert_indent_space: true,
308 args_file: PathBuf::new(),
309 };
310 let mut builder = doctest::BuildDocTestBuilder::new(&test).edition(edition);
311 if let Some(krate) = krate {
312 builder = builder.crate_name(krate);
313 }
314 let doctest = builder.build(None);
315 let (wrapped, _) = doctest.generate_unique_doctest(&test, false, &opts, krate);
316 let test = wrapped.to_string();
317 let channel = if test.contains("#![feature(") { "&version=nightly" } else { "" };
318
319 let test_escaped = small_url_encode(test);
320 Some(format!(
321 "<a class=\"test-arrow\" \
322 target=\"_blank\" \
323 title=\"Run code\" \
324 href=\"{url}?code={test_escaped}{channel}&edition={edition}\"></a>",
325 ))
326 });
327
328 let tooltip = {
329 use highlight::Tooltip::*;
330
331 if ignore == Ignore::All {
332 Some(IgnoreAll)
333 } else if let Ignore::Some(platforms) = ignore {
334 Some(IgnoreSome(platforms))
335 } else if compile_fail {
336 Some(CompileFail)
337 } else if should_panic {
338 Some(ShouldPanic)
339 } else if explicit_edition {
340 Some(Edition(edition))
341 } else {
342 None
343 }
344 };
345
346 let s = format!(
349 "\n{}",
350 highlight::render_example_with_highlighting(
351 &text,
352 tooltip.as_ref(),
353 playground_button.as_deref(),
354 &added_classes,
355 edition,
356 )
357 );
358 Some(Event::Html(s.into()))
359 }
360}
361
362struct LinkReplacerInner<'a> {
364 links: &'a [RenderedLink],
365 shortcut_link: Option<&'a RenderedLink>,
366}
367
368struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
369 iter: I,
370 inner: LinkReplacerInner<'a>,
371}
372
373impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
374 fn new(iter: I, links: &'a [RenderedLink]) -> Self {
375 LinkReplacer { iter, inner: { LinkReplacerInner { links, shortcut_link: None } } }
376 }
377}
378
379struct SpannedLinkReplacer<'a, I: Iterator<Item = SpannedEvent<'a>>> {
382 iter: I,
383 inner: LinkReplacerInner<'a>,
384}
385
386impl<'a, I: Iterator<Item = SpannedEvent<'a>>> SpannedLinkReplacer<'a, I> {
387 fn new(iter: I, links: &'a [RenderedLink]) -> Self {
388 SpannedLinkReplacer { iter, inner: { LinkReplacerInner { links, shortcut_link: None } } }
389 }
390}
391
392impl<'a> LinkReplacerInner<'a> {
393 fn handle_event(&mut self, event: &mut Event<'a>) {
394 match event {
396 Event::Start(Tag::Link {
399 link_type: LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
401 dest_url,
402 title,
403 ..
404 }) => {
405 debug!("saw start of shortcut link to {dest_url} with title {title}");
406 let link = self.links.iter().find(|&link| *link.href == **dest_url);
409 if let Some(link) = link {
412 trace!("it matched");
413 assert!(self.shortcut_link.is_none(), "shortcut links cannot be nested");
414 self.shortcut_link = Some(link);
415 if title.is_empty() && !link.tooltip.is_empty() {
416 *title = CowStr::Borrowed(link.tooltip.as_ref());
417 }
418 }
419 }
420 Event::End(TagEnd::Link) if self.shortcut_link.is_some() => {
422 debug!("saw end of shortcut link");
423 self.shortcut_link = None;
424 }
425 Event::Code(text) => {
428 trace!("saw code {text}");
429 if let Some(link) = self.shortcut_link {
430 if let Some(link) = self.links.iter().find(|l| {
440 l.href == link.href
441 && Some(&**text) == l.original_text.get(1..l.original_text.len() - 1)
442 }) {
443 debug!("replacing {text} with {new_text}", new_text = link.new_text);
444 *text = CowStr::Borrowed(&link.new_text);
445 }
446 }
447 }
448 Event::Text(text) => {
451 trace!("saw text {text}");
452 if let Some(link) = self.shortcut_link {
453 if let Some(link) = self
455 .links
456 .iter()
457 .find(|l| l.href == link.href && **text == *l.original_text)
458 {
459 debug!("replacing {text} with {new_text}", new_text = link.new_text);
460 *text = CowStr::Borrowed(&link.new_text);
461 }
462 }
463 }
464 Event::Start(Tag::Link { dest_url, title, .. }) => {
467 if let Some(link) =
468 self.links.iter().find(|&link| *link.original_text == **dest_url)
469 {
470 *dest_url = CowStr::Borrowed(link.href.as_ref());
471 if title.is_empty() && !link.tooltip.is_empty() {
472 *title = CowStr::Borrowed(link.tooltip.as_ref());
473 }
474 }
475 }
476 _ => {}
478 }
479 }
480}
481
482impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
483 type Item = Event<'a>;
484
485 fn next(&mut self) -> Option<Self::Item> {
486 let mut event = self.iter.next();
487 if let Some(ref mut event) = event {
488 self.inner.handle_event(event);
489 }
490 event
492 }
493}
494
495impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for SpannedLinkReplacer<'a, I> {
496 type Item = SpannedEvent<'a>;
497
498 fn next(&mut self) -> Option<Self::Item> {
499 let (mut event, range) = self.iter.next()?;
500 self.inner.handle_event(&mut event);
501 Some((event, range))
503 }
504}
505
506struct TableWrapper<'a, I: Iterator<Item = Event<'a>>> {
508 inner: I,
509 stored_events: VecDeque<Event<'a>>,
510}
511
512impl<'a, I: Iterator<Item = Event<'a>>> TableWrapper<'a, I> {
513 fn new(iter: I) -> Self {
514 Self { inner: iter, stored_events: VecDeque::new() }
515 }
516}
517
518impl<'a, I: Iterator<Item = Event<'a>>> Iterator for TableWrapper<'a, I> {
519 type Item = Event<'a>;
520
521 fn next(&mut self) -> Option<Self::Item> {
522 if let Some(first) = self.stored_events.pop_front() {
523 return Some(first);
524 }
525
526 let event = self.inner.next()?;
527
528 Some(match event {
529 Event::Start(Tag::Table(t)) => {
530 self.stored_events.push_back(Event::Start(Tag::Table(t)));
531 Event::Html(CowStr::Borrowed(r#"<div class="table">"#))
532 }
533 Event::End(TagEnd::Table) => {
534 self.stored_events.push_back(Event::Html(CowStr::Borrowed("</div>")));
535 Event::End(TagEnd::Table)
536 }
537 e => e,
538 })
539 }
540}
541
542type SpannedEvent<'a> = (Event<'a>, Range<usize>);
543
544struct HeadingLinks<'a, 'b, 'ids, I> {
546 inner: I,
547 toc: Option<&'b mut TocBuilder>,
548 buf: VecDeque<SpannedEvent<'a>>,
549 id_map: &'ids mut IdMap,
550 heading_offset: HeadingOffset,
551}
552
553impl<'b, 'ids, I> HeadingLinks<'_, 'b, 'ids, I> {
554 fn new(
555 iter: I,
556 toc: Option<&'b mut TocBuilder>,
557 ids: &'ids mut IdMap,
558 heading_offset: HeadingOffset,
559 ) -> Self {
560 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids, heading_offset }
561 }
562}
563
564impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for HeadingLinks<'a, '_, '_, I> {
565 type Item = SpannedEvent<'a>;
566
567 fn next(&mut self) -> Option<Self::Item> {
568 if let Some(e) = self.buf.pop_front() {
569 return Some(e);
570 }
571
572 let event = self.inner.next();
573 if let Some((Event::Start(Tag::Heading { level, .. }), _)) = event {
574 let mut id = String::new();
575 for event in &mut self.inner {
576 match &event.0 {
577 Event::End(TagEnd::Heading(_)) => break,
578 Event::Text(text) | Event::Code(text) => {
579 id.extend(text.chars().filter_map(slugify));
580 self.buf.push_back(event);
581 }
582 _ => self.buf.push_back(event),
583 }
584 }
585 let id = self.id_map.derive(id);
586 let percent_encoded_id = small_url_encode(id.clone());
587
588 if let Some(ref mut builder) = self.toc {
589 let mut text_header = String::new();
590 plain_text_from_events(self.buf.iter().map(|(ev, _)| ev.clone()), &mut text_header);
591 let mut html_header = String::new();
592 html_text_from_events(self.buf.iter().map(|(ev, _)| ev.clone()), &mut html_header);
593 let sec = builder.push(level as u32, text_header, html_header, id.clone());
594 self.buf.push_front((Event::Html(format!("{sec} ").into()), 0..0));
595 }
596
597 let level =
598 std::cmp::min(level as u32 + (self.heading_offset as u32), MAX_HEADER_LEVEL);
599 self.buf.push_back((Event::Html(format!("</h{level}>").into()), 0..0));
600
601 let start_tags = format!(
602 "<h{level} id=\"{id}\"><a class=\"doc-anchor\" href=\"#{percent_encoded_id}\">§</a>"
603 );
604 return Some((Event::Html(start_tags.into()), 0..0));
605 }
606 event
607 }
608}
609
610struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
612 inner: I,
613 started: bool,
614 depth: u32,
615 skipped_tags: u32,
616}
617
618impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
619 fn new(iter: I) -> Self {
620 SummaryLine { inner: iter, started: false, depth: 0, skipped_tags: 0 }
621 }
622}
623
624fn check_if_allowed_tag(t: &TagEnd) -> bool {
625 matches!(
626 t,
627 TagEnd::Paragraph
628 | TagEnd::Emphasis
629 | TagEnd::Strong
630 | TagEnd::Strikethrough
631 | TagEnd::Link
632 | TagEnd::BlockQuote
633 )
634}
635
636fn is_forbidden_tag(t: &TagEnd) -> bool {
637 matches!(
638 t,
639 TagEnd::CodeBlock
640 | TagEnd::Table
641 | TagEnd::TableHead
642 | TagEnd::TableRow
643 | TagEnd::TableCell
644 | TagEnd::FootnoteDefinition
645 )
646}
647
648impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
649 type Item = Event<'a>;
650
651 fn next(&mut self) -> Option<Self::Item> {
652 if self.started && self.depth == 0 {
653 return None;
654 }
655 if !self.started {
656 self.started = true;
657 }
658 if let Some(event) = self.inner.next() {
659 let mut is_start = true;
660 let is_allowed_tag = match event {
661 Event::Start(ref c) => {
662 if is_forbidden_tag(&c.to_end()) {
663 self.skipped_tags += 1;
664 return None;
665 }
666 self.depth += 1;
667 check_if_allowed_tag(&c.to_end())
668 }
669 Event::End(ref c) => {
670 if is_forbidden_tag(c) {
671 self.skipped_tags += 1;
672 return None;
673 }
674 self.depth -= 1;
675 is_start = false;
676 check_if_allowed_tag(c)
677 }
678 Event::FootnoteReference(_) => {
679 self.skipped_tags += 1;
680 false
681 }
682 _ => true,
683 };
684 if !is_allowed_tag {
685 self.skipped_tags += 1;
686 }
687 return if !is_allowed_tag {
688 if is_start {
689 Some(Event::Start(Tag::Paragraph))
690 } else {
691 Some(Event::End(TagEnd::Paragraph))
692 }
693 } else {
694 Some(event)
695 };
696 }
697 None
698 }
699}
700
701pub(crate) struct MdRelLine {
708 offset: usize,
709}
710
711impl MdRelLine {
712 pub(crate) const fn new(offset: usize) -> Self {
714 Self { offset }
715 }
716
717 pub(crate) const fn offset(self) -> usize {
719 self.offset
720 }
721}
722
723#[derive(Clone, Debug)]
724pub(crate) struct CodeLineMapping {
725 pub(crate) generated: Range<usize>,
726 pub(crate) original: Span,
727}
728
729pub(crate) fn find_testable_code<T: doctest::DocTestVisitor>(
730 doc: &str,
731 tests: &mut T,
732 error_codes: ErrorCodes,
733 extra_info: Option<&ExtraInfo<'_, '_>>,
734) {
735 find_codes(doc, tests, error_codes, extra_info, false)
736}
737
738pub(crate) fn find_codes<T: doctest::DocTestVisitor>(
739 doc: &str,
740 tests: &mut T,
741 error_codes: ErrorCodes,
742 extra_info: Option<&ExtraInfo<'_, '_>>,
743 include_non_rust: bool,
744) {
745 let mut parser = Parser::new_ext(doc, main_body_opts()).into_offset_iter();
746 let mut prev_offset = 0;
747 let mut nb_lines = 0;
748 let mut register_header = None;
749 while let Some((event, offset)) = parser.next() {
750 match event {
751 Event::Start(Tag::CodeBlock(kind)) => {
752 let block_info = match kind {
753 CodeBlockKind::Fenced(ref lang) => {
754 if lang.is_empty() {
755 Default::default()
756 } else {
757 LangString::parse(lang, error_codes, extra_info)
758 }
759 }
760 CodeBlockKind::Indented => Default::default(),
761 };
762 if !include_non_rust && !block_info.rust {
763 continue;
764 }
765
766 let mut test_s = String::new();
767 let mut text_events = Vec::new();
768
769 while let Some((Event::Text(s), offset)) = parser.next() {
770 let start = test_s.len();
771 test_s.push_str(&s);
772 text_events.push((start..test_s.len(), offset));
773 }
774 let (text, code_mappings) = map_code_block(doc, &test_s, &text_events, extra_info);
775
776 nb_lines += doc[prev_offset..offset.start].lines().count();
777 if nb_lines != 0 && !&doc[prev_offset..offset.start].ends_with('\n') {
781 nb_lines -= 1;
782 }
783 let line = MdRelLine::new(nb_lines);
784 tests.visit_test(text, block_info, line, code_mappings);
785 prev_offset = offset.start;
786 }
787 Event::Start(Tag::Heading { level, .. }) => {
788 register_header = Some(level as u32);
789 }
790 Event::Text(ref s) if register_header.is_some() => {
791 let level = register_header.unwrap();
792 tests.visit_header(s, level);
793 register_header = None;
794 }
795 _ => {}
796 }
797 }
798}
799
800fn map_code_block(
801 doc: &str,
802 code: &str,
803 text_events: &[(Range<usize>, Range<usize>)],
804 extra_info: Option<&ExtraInfo<'_, '_>>,
805) -> (String, Vec<CodeLineMapping>) {
806 let mut text = String::new();
807 let mut code_mappings = Vec::new();
808 let mut code_line_start = 0;
809
810 for (line_index, line) in code.lines().enumerate() {
811 if line_index != 0 {
812 text.push('\n');
813 }
814
815 let generated_start = text.len();
816 let mapped_line = map_line(line).for_code();
817 text.push_str(&mapped_line);
818 let generated = generated_start..text.len();
819
820 if mapped_line.as_ref() == line
821 && let Some(extra_info) = extra_info
822 && let Some(fragments) = extra_info.fragments
823 {
824 let code_line = code_line_start..code_line_start + line.len();
825 if let Some(md_range) = markdown_range_for_code_range(text_events, code_line)
826 && let Some((original, _)) =
827 source_span_for_markdown_range(extra_info.tcx, doc, &md_range, fragments)
828 {
829 code_mappings.push(CodeLineMapping { generated, original });
830 }
831 }
832
833 code_line_start += line.len() + 1;
834 }
835
836 (text, code_mappings)
837}
838
839fn markdown_range_for_code_range(
840 text_events: &[(Range<usize>, Range<usize>)],
841 code_range: Range<usize>,
842) -> Option<Range<usize>> {
843 text_events.iter().find_map(|(event_code_range, event_md_range)| {
844 if event_code_range.start <= code_range.start && code_range.end <= event_code_range.end {
845 let start = event_md_range.start + code_range.start - event_code_range.start;
846 let end = event_md_range.start + code_range.end - event_code_range.start;
847 Some(start..end)
848 } else {
849 None
850 }
851 })
852}
853
854pub(crate) struct ExtraInfo<'doc, 'tcx> {
855 def_id: LocalDefId,
856 sp: Span,
857 tcx: TyCtxt<'tcx>,
858 fragments: Option<&'doc [DocFragment]>,
859}
860
861impl<'doc, 'tcx> ExtraInfo<'doc, 'tcx> {
862 pub(crate) fn new(
863 tcx: TyCtxt<'tcx>,
864 def_id: LocalDefId,
865 sp: Span,
866 fragments: Option<&'doc [DocFragment]>,
867 ) -> ExtraInfo<'doc, 'tcx> {
868 ExtraInfo { def_id, sp, tcx, fragments }
869 }
870
871 fn error_invalid_codeblock_attr(&self, msg: impl Into<DiagMessage>) {
872 self.error_invalid_codeblock_attr_with_help(msg, |_| {});
873 }
874
875 fn error_invalid_codeblock_attr_with_help(
876 &self,
877 msg: impl Into<DiagMessage>,
878 f: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
879 ) {
880 self.tcx.emit_node_span_lint(
881 crate::lint::INVALID_CODEBLOCK_ATTRIBUTES,
882 self.tcx.local_def_id_to_hir_id(self.def_id),
883 self.sp,
884 rustc_errors::DiagDecorator(|lint| {
885 lint.primary_message(msg);
886 f(lint);
887 }),
888 );
889 }
890}
891
892#[derive(Eq, PartialEq, Clone, Debug)]
893pub(crate) struct LangString {
894 pub(crate) original: String,
895 pub(crate) should_panic: bool,
896 pub(crate) no_run: bool,
897 pub(crate) ignore: Ignore,
898 pub(crate) rust: bool,
899 pub(crate) test_harness: bool,
900 pub(crate) compile_fail: bool,
901 pub(crate) standalone_crate: bool,
902 pub(crate) error_codes: Vec<String>,
903 pub(crate) edition: Option<Edition>,
904 pub(crate) added_classes: Vec<String>,
905 pub(crate) unknown: Vec<String>,
906}
907
908#[derive(Eq, PartialEq, Clone, Debug)]
909pub(crate) enum Ignore {
910 All,
911 None,
912 Some(Vec<String>),
913}
914
915pub(crate) struct TagIterator<'a, 'tcx> {
956 inner: Peekable<CharIndices<'a>>,
957 data: &'a str,
958 is_in_attribute_block: bool,
959 extra: Option<&'a ExtraInfo<'a, 'tcx>>,
960 is_error: bool,
961}
962
963#[derive(Clone, Debug, Eq, PartialEq)]
964pub(crate) enum LangStringToken<'a> {
965 LangToken(&'a str),
966 ClassAttribute(&'a str),
967 KeyValueAttribute(&'a str, &'a str),
968}
969
970fn is_leading_char(c: char) -> bool {
971 c == '_' || c == '-' || c == ':' || c.is_ascii_alphabetic() || c.is_ascii_digit()
972}
973fn is_bareword_char(c: char) -> bool {
974 is_leading_char(c) || ".!#$%&*+/;<>?@^|~".contains(c)
975}
976fn is_separator(c: char) -> bool {
977 c == ' ' || c == ',' || c == '\t'
978}
979
980struct Indices {
981 start: usize,
982 end: usize,
983}
984
985impl<'a, 'tcx> TagIterator<'a, 'tcx> {
986 pub(crate) fn new(data: &'a str, extra: Option<&'a ExtraInfo<'a, 'tcx>>) -> Self {
987 Self {
988 inner: data.char_indices().peekable(),
989 data,
990 is_in_attribute_block: false,
991 extra,
992 is_error: false,
993 }
994 }
995
996 fn emit_error(&mut self, err: impl Into<DiagMessage>) {
997 if let Some(extra) = self.extra {
998 extra.error_invalid_codeblock_attr(err);
999 }
1000 self.is_error = true;
1001 }
1002
1003 fn skip_separators(&mut self) -> Option<usize> {
1004 while let Some((pos, c)) = self.inner.peek() {
1005 if !is_separator(*c) {
1006 return Some(*pos);
1007 }
1008 self.inner.next();
1009 }
1010 None
1011 }
1012
1013 fn parse_string(&mut self, start: usize) -> Option<Indices> {
1014 for (pos, c) in self.inner.by_ref() {
1015 if c == '"' {
1016 return Some(Indices { start: start + 1, end: pos });
1017 }
1018 }
1019 self.emit_error("unclosed quote string `\"`");
1020 None
1021 }
1022
1023 fn parse_class(&mut self, start: usize) -> Option<LangStringToken<'a>> {
1024 while let Some((pos, c)) = self.inner.peek().copied() {
1025 if is_bareword_char(c) {
1026 self.inner.next();
1027 } else {
1028 let class = &self.data[start + 1..pos];
1029 if class.is_empty() {
1030 self.emit_error(format!("unexpected `{c}` character after `.`"));
1031 return None;
1032 } else if self.check_after_token() {
1033 return Some(LangStringToken::ClassAttribute(class));
1034 } else {
1035 return None;
1036 }
1037 }
1038 }
1039 let class = &self.data[start + 1..];
1040 if class.is_empty() {
1041 self.emit_error("missing character after `.`");
1042 None
1043 } else if self.check_after_token() {
1044 Some(LangStringToken::ClassAttribute(class))
1045 } else {
1046 None
1047 }
1048 }
1049
1050 fn parse_token(&mut self, start: usize) -> Option<Indices> {
1051 while let Some((pos, c)) = self.inner.peek() {
1052 if !is_bareword_char(*c) {
1053 return Some(Indices { start, end: *pos });
1054 }
1055 self.inner.next();
1056 }
1057 self.emit_error("unexpected end");
1058 None
1059 }
1060
1061 fn parse_key_value(&mut self, c: char, start: usize) -> Option<LangStringToken<'a>> {
1062 let key_indices =
1063 if c == '"' { self.parse_string(start)? } else { self.parse_token(start)? };
1064 if key_indices.start == key_indices.end {
1065 self.emit_error("unexpected empty string as key");
1066 return None;
1067 }
1068
1069 if let Some((_, c)) = self.inner.next() {
1070 if c != '=' {
1071 self.emit_error(format!("expected `=`, found `{c}`"));
1072 return None;
1073 }
1074 } else {
1075 self.emit_error("unexpected end");
1076 return None;
1077 }
1078 let value_indices = match self.inner.next() {
1079 Some((pos, '"')) => self.parse_string(pos)?,
1080 Some((pos, c)) if is_bareword_char(c) => self.parse_token(pos)?,
1081 Some((_, c)) => {
1082 self.emit_error(format!("unexpected `{c}` character after `=`"));
1083 return None;
1084 }
1085 None => {
1086 self.emit_error("expected value after `=`");
1087 return None;
1088 }
1089 };
1090 if value_indices.start == value_indices.end {
1091 self.emit_error("unexpected empty string as value");
1092 None
1093 } else if self.check_after_token() {
1094 Some(LangStringToken::KeyValueAttribute(
1095 &self.data[key_indices.start..key_indices.end],
1096 &self.data[value_indices.start..value_indices.end],
1097 ))
1098 } else {
1099 None
1100 }
1101 }
1102
1103 fn check_after_token(&mut self) -> bool {
1105 if let Some((_, c)) = self.inner.peek().copied() {
1106 if c == '}' || is_separator(c) || c == '(' {
1107 true
1108 } else {
1109 self.emit_error(format!("unexpected `{c}` character"));
1110 false
1111 }
1112 } else {
1113 true
1115 }
1116 }
1117
1118 fn parse_in_attribute_block(&mut self) -> Option<LangStringToken<'a>> {
1119 if let Some((pos, c)) = self.inner.next() {
1120 if c == '}' {
1121 self.is_in_attribute_block = false;
1122 return self.next();
1123 } else if c == '.' {
1124 return self.parse_class(pos);
1125 } else if c == '"' || is_leading_char(c) {
1126 return self.parse_key_value(c, pos);
1127 } else {
1128 self.emit_error(format!("unexpected character `{c}`"));
1129 return None;
1130 }
1131 }
1132 self.emit_error("unclosed attribute block (`{}`): missing `}` at the end");
1133 None
1134 }
1135
1136 fn skip_paren_block(&mut self) -> bool {
1138 for (_, c) in self.inner.by_ref() {
1139 if c == ')' {
1140 return true;
1141 }
1142 }
1143 self.emit_error("unclosed comment: missing `)` at the end");
1144 false
1145 }
1146
1147 fn parse_outside_attribute_block(&mut self, start: usize) -> Option<LangStringToken<'a>> {
1148 while let Some((pos, c)) = self.inner.next() {
1149 if c == '"' {
1150 if pos != start {
1151 self.emit_error("expected ` `, `{` or `,` found `\"`");
1152 return None;
1153 }
1154 let indices = self.parse_string(pos)?;
1155 if let Some((_, c)) = self.inner.peek().copied()
1156 && c != '{'
1157 && !is_separator(c)
1158 && c != '('
1159 {
1160 self.emit_error(format!("expected ` `, `{{` or `,` after `\"`, found `{c}`"));
1161 return None;
1162 }
1163 return Some(LangStringToken::LangToken(&self.data[indices.start..indices.end]));
1164 } else if c == '{' {
1165 self.is_in_attribute_block = true;
1166 return self.next();
1167 } else if is_separator(c) {
1168 if pos != start {
1169 return Some(LangStringToken::LangToken(&self.data[start..pos]));
1170 }
1171 return self.next();
1172 } else if c == '(' {
1173 if !self.skip_paren_block() {
1174 return None;
1175 }
1176 if pos != start {
1177 return Some(LangStringToken::LangToken(&self.data[start..pos]));
1178 }
1179 return self.next();
1180 } else if (pos == start && is_leading_char(c)) || (pos != start && is_bareword_char(c))
1181 {
1182 continue;
1183 } else {
1184 self.emit_error(format!("unexpected character `{c}`"));
1185 return None;
1186 }
1187 }
1188 let token = &self.data[start..];
1189 if token.is_empty() { None } else { Some(LangStringToken::LangToken(&self.data[start..])) }
1190 }
1191}
1192
1193impl<'a> Iterator for TagIterator<'a, '_> {
1194 type Item = LangStringToken<'a>;
1195
1196 fn next(&mut self) -> Option<Self::Item> {
1197 if self.is_error {
1198 return None;
1199 }
1200 let Some(start) = self.skip_separators() else {
1201 if self.is_in_attribute_block {
1202 self.emit_error("unclosed attribute block (`{}`): missing `}` at the end");
1203 }
1204 return None;
1205 };
1206 if self.is_in_attribute_block {
1207 self.parse_in_attribute_block()
1208 } else {
1209 self.parse_outside_attribute_block(start)
1210 }
1211 }
1212}
1213
1214impl Default for LangString {
1215 fn default() -> Self {
1216 Self {
1217 original: String::new(),
1218 should_panic: false,
1219 no_run: false,
1220 ignore: Ignore::None,
1221 rust: true,
1222 test_harness: false,
1223 compile_fail: false,
1224 standalone_crate: false,
1225 error_codes: Vec::new(),
1226 edition: None,
1227 added_classes: Vec::new(),
1228 unknown: Vec::new(),
1229 }
1230 }
1231}
1232
1233impl LangString {
1234 fn parse_without_check(string: &str, allow_error_code_check: ErrorCodes) -> Self {
1235 Self::parse(string, allow_error_code_check, None)
1236 }
1237
1238 fn parse(
1239 string: &str,
1240 allow_error_code_check: ErrorCodes,
1241 extra: Option<&ExtraInfo<'_, '_>>,
1242 ) -> Self {
1243 let allow_error_code_check = allow_error_code_check.as_bool();
1244 let mut seen_rust_tags = false;
1245 let mut seen_other_tags = false;
1246 let mut seen_custom_tag = false;
1247 let mut data = LangString::default();
1248 let mut ignores = vec![];
1249
1250 data.original = string.to_owned();
1251
1252 let mut call = |tokens: &mut dyn Iterator<Item = LangStringToken<'_>>| {
1253 for token in tokens {
1254 match token {
1255 LangStringToken::LangToken("should_panic") => {
1256 data.should_panic = true;
1257 seen_rust_tags = !seen_other_tags;
1258 }
1259 LangStringToken::LangToken("no_run") => {
1260 data.no_run = true;
1261 seen_rust_tags = !seen_other_tags;
1262 }
1263 LangStringToken::LangToken("ignore") => {
1264 data.ignore = Ignore::All;
1265 seen_rust_tags = !seen_other_tags;
1266 }
1267 LangStringToken::LangToken(x)
1268 if let Some(ignore) = x.strip_prefix("ignore-") =>
1269 {
1270 ignores.push(ignore.to_owned());
1271 seen_rust_tags = !seen_other_tags;
1272 }
1273 LangStringToken::LangToken("rust") => {
1274 data.rust = true;
1275 seen_rust_tags = true;
1276 }
1277 LangStringToken::LangToken("custom") => {
1278 seen_custom_tag = true;
1279 }
1280 LangStringToken::LangToken("test_harness") => {
1281 data.test_harness = true;
1282 seen_rust_tags = !seen_other_tags || seen_rust_tags;
1283 }
1284 LangStringToken::LangToken("compile_fail") => {
1285 data.compile_fail = true;
1286 seen_rust_tags = !seen_other_tags || seen_rust_tags;
1287 data.no_run = true;
1288 }
1289 LangStringToken::LangToken("standalone_crate") => {
1290 data.standalone_crate = true;
1291 seen_rust_tags = !seen_other_tags || seen_rust_tags;
1292 }
1293 LangStringToken::LangToken(x)
1294 if let Some(edition) = x.strip_prefix("edition") =>
1295 {
1296 data.edition = edition.parse::<Edition>().ok();
1297 }
1298 LangStringToken::LangToken(x)
1299 if let Some(edition) = x.strip_prefix("rust")
1300 && edition.parse::<Edition>().is_ok()
1301 && let Some(extra) = extra =>
1302 {
1303 extra.error_invalid_codeblock_attr_with_help(
1304 format!("unknown attribute `{x}`"),
1305 |lint| {
1306 lint.help(format!(
1307 "there is an attribute with a similar name: `edition{edition}`"
1308 ));
1309 },
1310 );
1311 }
1312 LangStringToken::LangToken(x)
1313 if allow_error_code_check
1314 && let Some(error_code) = x.strip_prefix('E')
1315 && error_code.len() == 4 =>
1316 {
1317 if error_code.parse::<u32>().is_ok() {
1318 data.error_codes.push(x.to_owned());
1319 seen_rust_tags = !seen_other_tags || seen_rust_tags;
1320 } else {
1321 seen_other_tags = true;
1322 }
1323 }
1324 LangStringToken::LangToken(x) if let Some(extra) = extra => {
1325 if let Some(help) = match x.to_lowercase().as_str() {
1326 "compile-fail" | "compile_fail" | "compilefail" => Some(
1327 "use `compile_fail` to invert the results of this test, so that it \
1328 passes if it cannot be compiled and fails if it can",
1329 ),
1330 "should-panic" | "should_panic" | "shouldpanic" => Some(
1331 "use `should_panic` to invert the results of this test, so that if \
1332 passes if it panics and fails if it does not",
1333 ),
1334 "no-run" | "no_run" | "norun" => Some(
1335 "use `no_run` to compile, but not run, the code sample during \
1336 testing",
1337 ),
1338 "test-harness" | "test_harness" | "testharness" => Some(
1339 "use `test_harness` to run functions marked `#[test]` instead of a \
1340 potentially-implicit `main` function",
1341 ),
1342 "standalone" | "standalone_crate" | "standalone-crate"
1343 if extra.sp.at_least_rust_2024() =>
1344 {
1345 Some(
1346 "use `standalone_crate` to compile this code block \
1347 separately",
1348 )
1349 }
1350 _ => None,
1351 } {
1352 extra.error_invalid_codeblock_attr_with_help(
1353 format!("unknown attribute `{x}`"),
1354 |lint| {
1355 lint.help(help).help(
1356 "this code block may be skipped during testing, \
1357 because unknown attributes are treated as markers for \
1358 code samples written in other programming languages, \
1359 unless it is also explicitly marked as `rust`",
1360 );
1361 },
1362 );
1363 }
1364 seen_other_tags = true;
1365 data.unknown.push(x.to_owned());
1366 }
1367 LangStringToken::LangToken(x) => {
1368 seen_other_tags = true;
1369 data.unknown.push(x.to_owned());
1370 }
1371 LangStringToken::KeyValueAttribute("class", value) => {
1372 data.added_classes.push(value.to_owned());
1373 }
1374 LangStringToken::KeyValueAttribute(key, ..) if let Some(extra) = extra => {
1375 extra
1376 .error_invalid_codeblock_attr(format!("unsupported attribute `{key}`"));
1377 }
1378 LangStringToken::ClassAttribute(class) => {
1379 data.added_classes.push(class.to_owned());
1380 }
1381 _ => {}
1382 }
1383 }
1384 };
1385
1386 let mut tag_iter = TagIterator::new(string, extra);
1387 call(&mut tag_iter);
1388
1389 if !ignores.is_empty() {
1391 data.ignore = Ignore::Some(ignores);
1392 }
1393
1394 data.rust &= !seen_custom_tag && (!seen_other_tags || seen_rust_tags) && !tag_iter.is_error;
1395
1396 data
1397 }
1398}
1399
1400impl<'a> Markdown<'a> {
1401 pub fn write_into(self, f: impl fmt::Write) -> fmt::Result {
1402 if self.content.is_empty() {
1404 return Ok(());
1405 }
1406
1407 html::write_html_fmt(f, self.into_iter())
1408 }
1409
1410 fn into_iter(self) -> CodeBlocks<'a, 'a, impl Iterator<Item = Event<'a>>> {
1411 let Markdown {
1412 content: md,
1413 links,
1414 ids,
1415 error_codes: codes,
1416 edition,
1417 playground,
1418 heading_offset,
1419 } = self;
1420
1421 let replacer = move |broken_link: BrokenLink<'_>| {
1422 links
1423 .iter()
1424 .find(|link| *link.original_text == *broken_link.reference)
1425 .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1426 };
1427
1428 let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(replacer));
1429 let p = p.into_offset_iter();
1430
1431 ids.handle_footnotes(|ids, existing_footnotes| {
1432 let p = HeadingLinks::new(p, None, ids, heading_offset);
1433 let p = SpannedLinkReplacer::new(p, links);
1434 let p = footnotes::Footnotes::new(p, existing_footnotes);
1435 let p = TableWrapper::new(p.map(|(ev, _)| ev));
1436 CodeBlocks::new(p, codes, edition, playground)
1437 })
1438 }
1439
1440 pub(crate) fn split_summary_and_content(self) -> (Option<String>, Option<String>) {
1446 if self.content.is_empty() {
1447 return (None, None);
1448 }
1449 let mut p = self.into_iter();
1450
1451 let mut event_level = 0;
1452 let mut summary_events = Vec::new();
1453 let mut get_next_tag = false;
1454
1455 let mut end_of_summary = false;
1456 while let Some(event) = p.next() {
1457 match event {
1458 Event::Start(_) => event_level += 1,
1459 Event::End(kind) => {
1460 event_level -= 1;
1461 if event_level == 0 {
1462 end_of_summary = true;
1464 get_next_tag = kind == TagEnd::Table;
1466 }
1467 }
1468 _ => {}
1469 }
1470 summary_events.push(event);
1471 if end_of_summary {
1472 if get_next_tag && let Some(event) = p.next() {
1473 summary_events.push(event);
1474 }
1475 break;
1476 }
1477 }
1478 let mut summary = String::new();
1479 html::push_html(&mut summary, summary_events.into_iter());
1480 if summary.is_empty() {
1481 return (None, None);
1482 }
1483 let mut content = String::new();
1484 html::push_html(&mut content, p);
1485
1486 if content.is_empty() { (Some(summary), None) } else { (Some(summary), Some(content)) }
1487 }
1488}
1489
1490impl MarkdownWithToc<'_> {
1491 pub(crate) fn into_parts(self) -> (Toc, String) {
1492 let MarkdownWithToc { content: md, links, ids, error_codes: codes, edition, playground } =
1493 self;
1494
1495 if md.is_empty() {
1497 return (Toc { entries: Vec::new() }, String::new());
1498 }
1499 let mut replacer = |broken_link: BrokenLink<'_>| {
1500 links
1501 .iter()
1502 .find(|link| *link.original_text == *broken_link.reference)
1503 .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1504 };
1505
1506 let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(&mut replacer));
1507 let p = p.into_offset_iter();
1508
1509 let mut s = String::with_capacity(md.len() * 3 / 2);
1510
1511 let mut toc = TocBuilder::new();
1512
1513 ids.handle_footnotes(|ids, existing_footnotes| {
1514 let p = HeadingLinks::new(p, Some(&mut toc), ids, HeadingOffset::H1);
1515 let p = footnotes::Footnotes::new(p, existing_footnotes);
1516 let p = TableWrapper::new(p.map(|(ev, _)| ev));
1517 let p = CodeBlocks::new(p, codes, edition, playground);
1518 html::push_html(&mut s, p);
1519 });
1520
1521 (toc.into_toc(), s)
1522 }
1523
1524 pub(crate) fn write_into(self, mut f: impl fmt::Write) -> fmt::Result {
1525 let (toc, s) = self.into_parts();
1526 write!(f, "<nav id=\"rustdoc\">{toc}</nav>{s}", toc = toc.print())
1527 }
1528}
1529
1530impl<'a> MarkdownItemInfo<'a> {
1531 pub(crate) fn new(content: &'a str, links: &'a [RenderedLink], ids: &'a mut IdMap) -> Self {
1532 Self { content, links, ids }
1533 }
1534
1535 pub(crate) fn write_into(self, mut f: impl fmt::Write) -> fmt::Result {
1536 let MarkdownItemInfo { content: md, links, ids } = self;
1537
1538 if md.is_empty() {
1540 return Ok(());
1541 }
1542
1543 let replacer = move |broken_link: BrokenLink<'_>| {
1544 links
1545 .iter()
1546 .find(|link| *link.original_text == *broken_link.reference)
1547 .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1548 };
1549
1550 let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(replacer));
1551 let p = p.into_offset_iter();
1552
1553 let p = p.map(|event| match event.0 {
1555 Event::Html(text) | Event::InlineHtml(text) => (Event::Text(text), event.1),
1556 _ => event,
1557 });
1558
1559 ids.handle_footnotes(|ids, existing_footnotes| {
1560 let p = HeadingLinks::new(p, None, ids, HeadingOffset::H1);
1561 let p = SpannedLinkReplacer::new(p, links);
1562 let p = footnotes::Footnotes::new(p, existing_footnotes);
1563 let p = TableWrapper::new(p.map(|(ev, _)| ev));
1564 html::write_html_fmt(&mut f, p)?;
1566
1567 Ok(())
1568 })
1569 }
1570}
1571
1572impl MarkdownSummaryLine<'_> {
1573 pub(crate) fn into_string_with_has_more_content(self) -> (String, bool) {
1574 let MarkdownSummaryLine(md, links) = self;
1575 if md.is_empty() {
1577 return (String::new(), false);
1578 }
1579
1580 let mut replacer = |broken_link: BrokenLink<'_>| {
1581 links
1582 .iter()
1583 .find(|link| *link.original_text == *broken_link.reference)
1584 .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1585 };
1586
1587 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer))
1588 .peekable();
1589 let mut summary = SummaryLine::new(p);
1590
1591 let mut s = String::new();
1592
1593 let without_paragraphs = LinkReplacer::new(&mut summary, links).filter(|event| {
1594 !matches!(event, Event::Start(Tag::Paragraph) | Event::End(TagEnd::Paragraph))
1595 });
1596
1597 html::push_html(&mut s, without_paragraphs);
1598
1599 let has_more_content = matches!(summary.inner.peek(), Some(Event::Start(_) | Event::Rule))
1600 || summary.skipped_tags > 0;
1601
1602 (s, has_more_content)
1603 }
1604
1605 pub(crate) fn into_string(self) -> String {
1606 self.into_string_with_has_more_content().0
1607 }
1608}
1609
1610fn markdown_summary_with_limit(
1619 md: &str,
1620 link_names: &[RenderedLink],
1621 length_limit: usize,
1622) -> (String, bool) {
1623 if md.is_empty() {
1624 return (String::new(), false);
1625 }
1626
1627 let mut replacer = |broken_link: BrokenLink<'_>| {
1628 link_names
1629 .iter()
1630 .find(|link| *link.original_text == *broken_link.reference)
1631 .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1632 };
1633
1634 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1635 let mut p = LinkReplacer::new(p, link_names);
1636
1637 let mut buf = HtmlWithLimit::new(length_limit);
1638 let mut stopped_early = false;
1639 let _ = p.try_for_each(|event| {
1640 match &event {
1641 Event::Text(text) => {
1642 let r =
1643 text.split_inclusive(char::is_whitespace).try_for_each(|word| buf.push(word));
1644 if r.is_break() {
1645 stopped_early = true;
1646 }
1647 return r;
1648 }
1649 Event::Code(code) => {
1650 buf.open_tag("code");
1651 let r = buf.push(code);
1652 if r.is_break() {
1653 stopped_early = true;
1654 } else {
1655 buf.close_tag();
1656 }
1657 return r;
1658 }
1659 Event::Start(tag) => match tag {
1660 Tag::Emphasis => buf.open_tag("em"),
1661 Tag::Strong => buf.open_tag("strong"),
1662 Tag::CodeBlock(..) => return ControlFlow::Break(()),
1663 _ => {}
1664 },
1665 Event::End(tag) => match tag {
1666 TagEnd::Emphasis | TagEnd::Strong => buf.close_tag(),
1667 TagEnd::Paragraph | TagEnd::Heading(_) => return ControlFlow::Break(()),
1668 _ => {}
1669 },
1670 Event::HardBreak | Event::SoftBreak => buf.push(" ")?,
1671 _ => {}
1672 };
1673 ControlFlow::Continue(())
1674 });
1675
1676 (buf.finish(), stopped_early)
1677}
1678
1679pub(crate) fn short_markdown_summary(markdown: &str, link_names: &[RenderedLink]) -> String {
1686 let (mut s, was_shortened) = markdown_summary_with_limit(markdown, link_names, 59);
1687
1688 if was_shortened {
1689 s.push('…');
1690 }
1691
1692 s
1693}
1694
1695pub(crate) fn plain_text_summary(md: &str, link_names: &[RenderedLink]) -> String {
1702 if md.is_empty() {
1703 return String::new();
1704 }
1705
1706 let mut s = String::with_capacity(md.len() * 3 / 2);
1707
1708 let mut replacer = |broken_link: BrokenLink<'_>| {
1709 link_names
1710 .iter()
1711 .find(|link| *link.original_text == *broken_link.reference)
1712 .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1713 };
1714
1715 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1716
1717 plain_text_from_events(p, &mut s);
1718
1719 s
1720}
1721
1722pub(crate) fn plain_text_from_events<'a>(
1723 events: impl Iterator<Item = pulldown_cmark::Event<'a>>,
1724 s: &mut String,
1725) {
1726 for event in events {
1727 match &event {
1728 Event::Text(text) => s.push_str(text),
1729 Event::Code(code) => {
1730 s.push('`');
1731 s.push_str(code);
1732 s.push('`');
1733 }
1734 Event::HardBreak | Event::SoftBreak => s.push(' '),
1735 Event::Start(Tag::CodeBlock(..)) => break,
1736 Event::End(TagEnd::Paragraph) => break,
1737 Event::End(TagEnd::Heading(..)) => break,
1738 _ => (),
1739 }
1740 }
1741}
1742
1743pub(crate) fn html_text_from_events<'a>(
1744 events: impl Iterator<Item = pulldown_cmark::Event<'a>>,
1745 s: &mut String,
1746) {
1747 for event in events {
1748 match &event {
1749 Event::Text(text) => {
1750 write!(s, "{}", EscapeBodyText(text)).expect("string alloc infallible")
1751 }
1752 Event::Code(code) => {
1753 s.push_str("<code>");
1754 write!(s, "{}", EscapeBodyText(code)).expect("string alloc infallible");
1755 s.push_str("</code>");
1756 }
1757 Event::HardBreak | Event::SoftBreak => s.push(' '),
1758 Event::Start(Tag::CodeBlock(..)) => break,
1759 Event::End(TagEnd::Paragraph) => break,
1760 Event::End(TagEnd::Heading(..)) => break,
1761 _ => (),
1762 }
1763 }
1764}
1765
1766#[derive(Debug)]
1767pub(crate) struct MarkdownLink {
1768 pub kind: LinkType,
1769 pub link: String,
1770 pub range: MarkdownLinkRange,
1771}
1772
1773#[derive(Clone, Debug)]
1774pub(crate) enum MarkdownLinkRange {
1775 Destination(Range<usize>),
1777 WholeLink(Range<usize>),
1781}
1782
1783impl MarkdownLinkRange {
1784 pub fn inner_range(&self) -> &Range<usize> {
1786 match self {
1787 MarkdownLinkRange::Destination(range) => range,
1788 MarkdownLinkRange::WholeLink(range) => range,
1789 }
1790 }
1791}
1792
1793pub(crate) fn markdown_links<'md, R>(
1794 md: &'md str,
1795 preprocess_link: impl Fn(MarkdownLink) -> Option<R>,
1796) -> Vec<R> {
1797 use itertools::Itertools;
1798 if md.is_empty() {
1799 return vec![];
1800 }
1801
1802 let locate = |s: &str, fallback: Range<usize>| unsafe {
1804 let s_start = s.as_ptr();
1805 let s_end = s_start.add(s.len());
1806 let md_start = md.as_ptr();
1807 let md_end = md_start.add(md.len());
1808 if md_start <= s_start && s_end <= md_end {
1809 let start = s_start.offset_from(md_start) as usize;
1810 let end = s_end.offset_from(md_start) as usize;
1811 MarkdownLinkRange::Destination(start..end)
1812 } else {
1813 MarkdownLinkRange::WholeLink(fallback)
1814 }
1815 };
1816
1817 let span_for_link = |link: &CowStr<'_>, span: Range<usize>| {
1818 match link {
1823 CowStr::Borrowed(s) => locate(s, span),
1828
1829 CowStr::Boxed(_) | CowStr::Inlined(_) => MarkdownLinkRange::WholeLink(span),
1831 }
1832 };
1833
1834 let span_for_refdef = |link: &CowStr<'_>, span: Range<usize>| {
1835 let mut square_brace_count = 0;
1838 let mut iter = md.as_bytes()[span.start..span.end].iter().copied().enumerate();
1839 for (_i, c) in &mut iter {
1840 match c {
1841 b':' if square_brace_count == 0 => break,
1842 b'[' => square_brace_count += 1,
1843 b']' => square_brace_count -= 1,
1844 _ => {}
1845 }
1846 }
1847 while let Some((i, c)) = iter.next() {
1848 if c == b'<' {
1849 while let Some((j, c)) = iter.next() {
1850 match c {
1851 b'\\' => {
1852 let _ = iter.next();
1853 }
1854 b'>' => {
1855 return MarkdownLinkRange::Destination(
1856 i + 1 + span.start..j + span.start,
1857 );
1858 }
1859 _ => {}
1860 }
1861 }
1862 } else if !c.is_ascii_whitespace() {
1863 for (j, c) in iter.by_ref() {
1864 if c.is_ascii_whitespace() {
1865 return MarkdownLinkRange::Destination(i + span.start..j + span.start);
1866 }
1867 }
1868 return MarkdownLinkRange::Destination(i + span.start..span.end);
1869 }
1870 }
1871 span_for_link(link, span)
1872 };
1873
1874 let span_for_offset_backward = |span: Range<usize>, open: u8, close: u8| {
1875 let mut open_brace = !0;
1876 let mut close_brace = !0;
1877 for (i, b) in md.as_bytes()[span.clone()].iter().copied().enumerate().rev() {
1878 let i = i + span.start;
1879 if b == close {
1880 close_brace = i;
1881 break;
1882 }
1883 }
1884 if close_brace < span.start || close_brace >= span.end {
1885 return MarkdownLinkRange::WholeLink(span);
1886 }
1887 let mut nesting = 1;
1888 for (i, b) in md.as_bytes()[span.start..close_brace].iter().copied().enumerate().rev() {
1889 let i = i + span.start;
1890 if b == close {
1891 nesting += 1;
1892 }
1893 if b == open {
1894 nesting -= 1;
1895 }
1896 if nesting == 0 {
1897 open_brace = i;
1898 break;
1899 }
1900 }
1901 assert!(open_brace != close_brace);
1902 if open_brace < span.start || open_brace >= span.end {
1903 return MarkdownLinkRange::WholeLink(span);
1904 }
1905 let range = (open_brace + 1)..close_brace;
1907 MarkdownLinkRange::Destination(range)
1908 };
1909
1910 let span_for_offset_forward = |span: Range<usize>, open: u8, close: u8| {
1911 let mut open_brace = !0;
1912 let mut close_brace = !0;
1913 for (i, b) in md.as_bytes()[span.clone()].iter().copied().enumerate() {
1914 let i = i + span.start;
1915 if b == open {
1916 open_brace = i;
1917 break;
1918 }
1919 }
1920 if open_brace < span.start || open_brace >= span.end {
1921 return MarkdownLinkRange::WholeLink(span);
1922 }
1923 let mut nesting = 0;
1924 for (i, b) in md.as_bytes()[open_brace..span.end].iter().copied().enumerate() {
1925 let i = i + open_brace;
1926 if b == close {
1927 nesting -= 1;
1928 }
1929 if b == open {
1930 nesting += 1;
1931 }
1932 if nesting == 0 {
1933 close_brace = i;
1934 break;
1935 }
1936 }
1937 assert!(open_brace != close_brace);
1938 if open_brace < span.start || open_brace >= span.end {
1939 return MarkdownLinkRange::WholeLink(span);
1940 }
1941 let range = (open_brace + 1)..close_brace;
1943 MarkdownLinkRange::Destination(range)
1944 };
1945
1946 let mut broken_link_callback = |link: BrokenLink<'md>| Some((link.reference, "".into()));
1947 let event_iter = Parser::new_with_broken_link_callback(
1948 md,
1949 main_body_opts(),
1950 Some(&mut broken_link_callback),
1951 )
1952 .into_offset_iter();
1953 let mut links = Vec::new();
1954
1955 let mut refdefs = FxIndexMap::default();
1956 for (label, refdef) in event_iter.reference_definitions().iter().sorted_by_key(|x| x.0) {
1957 refdefs.insert(label.to_string(), (false, refdef.dest.to_string(), refdef.span.clone()));
1958 }
1959
1960 for (event, span) in event_iter {
1961 match event {
1962 Event::Start(Tag::Link { link_type, dest_url, id, .. })
1963 if may_be_doc_link(link_type) =>
1964 {
1965 let range = match link_type {
1966 LinkType::ReferenceUnknown | LinkType::ShortcutUnknown => {
1968 span_for_offset_backward(span, b'[', b']')
1969 }
1970 LinkType::CollapsedUnknown => span_for_offset_forward(span, b'[', b']'),
1971 LinkType::Inline => span_for_offset_backward(span, b'(', b')'),
1972 LinkType::Reference | LinkType::Collapsed | LinkType::Shortcut => {
1974 if let Some((is_used, dest_url, span)) = refdefs.get_mut(&id[..]) {
1975 *is_used = true;
1976 span_for_refdef(&CowStr::from(&dest_url[..]), span.clone())
1977 } else {
1978 span_for_link(&dest_url, span)
1979 }
1980 }
1981 LinkType::Autolink | LinkType::Email => unreachable!(),
1982 };
1983
1984 if let Some(link) = preprocess_link(MarkdownLink {
1985 kind: link_type,
1986 link: dest_url.into_string(),
1987 range,
1988 }) {
1989 links.push(link);
1990 }
1991 }
1992 _ => {}
1993 }
1994 }
1995
1996 for (_label, (is_used, dest_url, span)) in refdefs.into_iter() {
1997 if !is_used
1998 && let Some(link) = preprocess_link(MarkdownLink {
1999 kind: LinkType::Reference,
2000 range: span_for_refdef(&CowStr::from(&dest_url[..]), span),
2001 link: dest_url,
2002 })
2003 {
2004 links.push(link);
2005 }
2006 }
2007
2008 links
2009}
2010
2011#[derive(Debug)]
2012pub(crate) struct RustCodeBlock {
2013 pub(crate) range: Range<usize>,
2016 pub(crate) code: Range<usize>,
2018 pub(crate) is_fenced: bool,
2019 pub(crate) lang_string: LangString,
2020}
2021
2022pub(crate) fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_, '_>) -> Vec<RustCodeBlock> {
2025 let mut code_blocks = vec![];
2026
2027 if md.is_empty() {
2028 return code_blocks;
2029 }
2030
2031 let mut p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
2032
2033 while let Some((event, offset)) = p.next() {
2034 if let Event::Start(Tag::CodeBlock(syntax)) = event {
2035 let (lang_string, code_start, code_end, range, is_fenced) = match syntax {
2036 CodeBlockKind::Fenced(syntax) => {
2037 let syntax = syntax.as_ref();
2038 let lang_string = if syntax.is_empty() {
2039 Default::default()
2040 } else {
2041 LangString::parse(syntax, ErrorCodes::Yes, Some(extra_info))
2042 };
2043 if !lang_string.rust {
2044 continue;
2045 }
2046 let (code_start, mut code_end) = match p.next() {
2047 Some((Event::Text(_), offset)) => (offset.start, offset.end),
2048 Some((_, sub_offset)) => {
2049 let code = Range { start: sub_offset.start, end: sub_offset.start };
2050 code_blocks.push(RustCodeBlock {
2051 is_fenced: true,
2052 range: offset,
2053 code,
2054 lang_string,
2055 });
2056 continue;
2057 }
2058 None => {
2059 let code = Range { start: offset.end, end: offset.end };
2060 code_blocks.push(RustCodeBlock {
2061 is_fenced: true,
2062 range: offset,
2063 code,
2064 lang_string,
2065 });
2066 continue;
2067 }
2068 };
2069 while let Some((Event::Text(_), offset)) = p.next() {
2070 code_end = offset.end;
2071 }
2072 (lang_string, code_start, code_end, offset, true)
2073 }
2074 CodeBlockKind::Indented => {
2075 if offset.end > offset.start && md.get(offset.end..=offset.end) == Some("\n") {
2078 (
2079 LangString::default(),
2080 offset.start,
2081 offset.end,
2082 Range { start: offset.start, end: offset.end - 1 },
2083 false,
2084 )
2085 } else {
2086 (LangString::default(), offset.start, offset.end, offset, false)
2087 }
2088 }
2089 };
2090
2091 code_blocks.push(RustCodeBlock {
2092 is_fenced,
2093 range,
2094 code: Range { start: code_start, end: code_end },
2095 lang_string,
2096 });
2097 }
2098 }
2099
2100 code_blocks
2101}
2102
2103#[derive(Clone, Default, Debug)]
2104pub struct IdMap {
2105 map: FxHashMap<String, usize>,
2106 existing_footnotes: Arc<AtomicUsize>,
2107}
2108
2109fn is_default_id(id: &str) -> bool {
2110 matches!(
2111 id,
2112 "help"
2114 | "settings"
2115 | "not-displayed"
2116 | "alternative-display"
2117 | "search"
2118 | "crate-search"
2119 | "crate-search-div"
2120 | "themeStyle"
2123 | "settings-menu"
2124 | "help-button"
2125 | "sidebar-button"
2126 | "main-content"
2127 | "toggle-all-docs"
2128 | "all-types"
2129 | "default-settings"
2130 | "sidebar-vars"
2131 | "copy-path"
2132 | "rustdoc-toc"
2133 | "rustdoc-modnav"
2134 | "fields"
2137 | "variants"
2138 | "implementors-list"
2139 | "synthetic-implementors-list"
2140 | "foreign-impls"
2141 | "implementations"
2142 | "trait-implementations"
2143 | "synthetic-implementations"
2144 | "blanket-implementations"
2145 | "required-associated-types"
2146 | "provided-associated-types"
2147 | "provided-associated-consts"
2148 | "required-associated-consts"
2149 | "required-methods"
2150 | "provided-methods"
2151 | "dyn-compatibility"
2152 | "implementors"
2153 | "synthetic-implementors"
2154 | "implementations-list"
2155 | "trait-implementations-list"
2156 | "synthetic-implementations-list"
2157 | "blanket-implementations-list"
2158 | "deref-methods"
2159 | "layout"
2160 | "aliased-type",
2161 )
2162}
2163
2164impl IdMap {
2165 pub fn new() -> Self {
2166 IdMap { map: FxHashMap::default(), existing_footnotes: Arc::new(AtomicUsize::new(0)) }
2167 }
2168
2169 pub(crate) fn derive<S: AsRef<str> + ToString>(&mut self, candidate: S) -> String {
2170 let id = match self.map.get_mut(candidate.as_ref()) {
2171 None => {
2172 let candidate = candidate.to_string();
2173 if is_default_id(&candidate) {
2174 let id = format!("{}-{}", candidate, 1);
2175 self.map.insert(candidate, 2);
2176 id
2177 } else {
2178 candidate
2179 }
2180 }
2181 Some(a) => {
2182 let id = format!("{}-{}", candidate.as_ref(), *a);
2183 *a += 1;
2184 id
2185 }
2186 };
2187
2188 self.map.insert(id.clone(), 1);
2189 id
2190 }
2191
2192 pub(crate) fn handle_footnotes<'a, T, F: FnOnce(&'a mut Self, Weak<AtomicUsize>) -> T>(
2195 &'a mut self,
2196 closure: F,
2197 ) -> T {
2198 let existing_footnotes = Arc::downgrade(&self.existing_footnotes);
2199
2200 closure(self, existing_footnotes)
2201 }
2202
2203 pub(crate) fn clear(&mut self) {
2204 self.map.clear();
2205 self.existing_footnotes = Arc::new(AtomicUsize::new(0));
2206 }
2207}