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::may_be_doc_link;
45use rustc_resolve::rustdoc::pulldown_cmark::{
46 self, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag, TagEnd, html,
47};
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 )
356 );
357 Some(Event::Html(s.into()))
358 }
359}
360
361struct LinkReplacerInner<'a> {
363 links: &'a [RenderedLink],
364 shortcut_link: Option<&'a RenderedLink>,
365}
366
367struct LinkReplacer<'a, I: Iterator<Item = Event<'a>>> {
368 iter: I,
369 inner: LinkReplacerInner<'a>,
370}
371
372impl<'a, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, I> {
373 fn new(iter: I, links: &'a [RenderedLink]) -> Self {
374 LinkReplacer { iter, inner: { LinkReplacerInner { links, shortcut_link: None } } }
375 }
376}
377
378struct SpannedLinkReplacer<'a, I: Iterator<Item = SpannedEvent<'a>>> {
381 iter: I,
382 inner: LinkReplacerInner<'a>,
383}
384
385impl<'a, I: Iterator<Item = SpannedEvent<'a>>> SpannedLinkReplacer<'a, I> {
386 fn new(iter: I, links: &'a [RenderedLink]) -> Self {
387 SpannedLinkReplacer { iter, inner: { LinkReplacerInner { links, shortcut_link: None } } }
388 }
389}
390
391impl<'a> LinkReplacerInner<'a> {
392 fn handle_event(&mut self, event: &mut Event<'a>) {
393 match event {
395 Event::Start(Tag::Link {
398 link_type: LinkType::ShortcutUnknown | LinkType::CollapsedUnknown,
400 dest_url,
401 title,
402 ..
403 }) => {
404 debug!("saw start of shortcut link to {dest_url} with title {title}");
405 let link = self.links.iter().find(|&link| *link.href == **dest_url);
408 if let Some(link) = link {
411 trace!("it matched");
412 assert!(self.shortcut_link.is_none(), "shortcut links cannot be nested");
413 self.shortcut_link = Some(link);
414 if title.is_empty() && !link.tooltip.is_empty() {
415 *title = CowStr::Borrowed(link.tooltip.as_ref());
416 }
417 }
418 }
419 Event::End(TagEnd::Link) if self.shortcut_link.is_some() => {
421 debug!("saw end of shortcut link");
422 self.shortcut_link = None;
423 }
424 Event::Code(text) => {
427 trace!("saw code {text}");
428 if let Some(link) = self.shortcut_link {
429 if let Some(link) = self.links.iter().find(|l| {
439 l.href == link.href
440 && Some(&**text) == l.original_text.get(1..l.original_text.len() - 1)
441 }) {
442 debug!("replacing {text} with {new_text}", new_text = link.new_text);
443 *text = CowStr::Borrowed(&link.new_text);
444 }
445 }
446 }
447 Event::Text(text) => {
450 trace!("saw text {text}");
451 if let Some(link) = self.shortcut_link {
452 if let Some(link) = self
454 .links
455 .iter()
456 .find(|l| l.href == link.href && **text == *l.original_text)
457 {
458 debug!("replacing {text} with {new_text}", new_text = link.new_text);
459 *text = CowStr::Borrowed(&link.new_text);
460 }
461 }
462 }
463 Event::Start(Tag::Link { dest_url, title, .. }) => {
466 if let Some(link) =
467 self.links.iter().find(|&link| *link.original_text == **dest_url)
468 {
469 *dest_url = CowStr::Borrowed(link.href.as_ref());
470 if title.is_empty() && !link.tooltip.is_empty() {
471 *title = CowStr::Borrowed(link.tooltip.as_ref());
472 }
473 }
474 }
475 _ => {}
477 }
478 }
479}
480
481impl<'a, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, I> {
482 type Item = Event<'a>;
483
484 fn next(&mut self) -> Option<Self::Item> {
485 let mut event = self.iter.next();
486 if let Some(ref mut event) = event {
487 self.inner.handle_event(event);
488 }
489 event
491 }
492}
493
494impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for SpannedLinkReplacer<'a, I> {
495 type Item = SpannedEvent<'a>;
496
497 fn next(&mut self) -> Option<Self::Item> {
498 let (mut event, range) = self.iter.next()?;
499 self.inner.handle_event(&mut event);
500 Some((event, range))
502 }
503}
504
505struct TableWrapper<'a, I: Iterator<Item = Event<'a>>> {
507 inner: I,
508 stored_events: VecDeque<Event<'a>>,
509}
510
511impl<'a, I: Iterator<Item = Event<'a>>> TableWrapper<'a, I> {
512 fn new(iter: I) -> Self {
513 Self { inner: iter, stored_events: VecDeque::new() }
514 }
515}
516
517impl<'a, I: Iterator<Item = Event<'a>>> Iterator for TableWrapper<'a, I> {
518 type Item = Event<'a>;
519
520 fn next(&mut self) -> Option<Self::Item> {
521 if let Some(first) = self.stored_events.pop_front() {
522 return Some(first);
523 }
524
525 let event = self.inner.next()?;
526
527 Some(match event {
528 Event::Start(Tag::Table(t)) => {
529 self.stored_events.push_back(Event::Start(Tag::Table(t)));
530 Event::Html(CowStr::Borrowed("<div>"))
531 }
532 Event::End(TagEnd::Table) => {
533 self.stored_events.push_back(Event::Html(CowStr::Borrowed("</div>")));
534 Event::End(TagEnd::Table)
535 }
536 e => e,
537 })
538 }
539}
540
541type SpannedEvent<'a> = (Event<'a>, Range<usize>);
542
543struct HeadingLinks<'a, 'b, 'ids, I> {
545 inner: I,
546 toc: Option<&'b mut TocBuilder>,
547 buf: VecDeque<SpannedEvent<'a>>,
548 id_map: &'ids mut IdMap,
549 heading_offset: HeadingOffset,
550}
551
552impl<'b, 'ids, I> HeadingLinks<'_, 'b, 'ids, I> {
553 fn new(
554 iter: I,
555 toc: Option<&'b mut TocBuilder>,
556 ids: &'ids mut IdMap,
557 heading_offset: HeadingOffset,
558 ) -> Self {
559 HeadingLinks { inner: iter, toc, buf: VecDeque::new(), id_map: ids, heading_offset }
560 }
561}
562
563impl<'a, I: Iterator<Item = SpannedEvent<'a>>> Iterator for HeadingLinks<'a, '_, '_, I> {
564 type Item = SpannedEvent<'a>;
565
566 fn next(&mut self) -> Option<Self::Item> {
567 if let Some(e) = self.buf.pop_front() {
568 return Some(e);
569 }
570
571 let event = self.inner.next();
572 if let Some((Event::Start(Tag::Heading { level, .. }), _)) = event {
573 let mut id = String::new();
574 for event in &mut self.inner {
575 match &event.0 {
576 Event::End(TagEnd::Heading(_)) => break,
577 Event::Text(text) | Event::Code(text) => {
578 id.extend(text.chars().filter_map(slugify));
579 self.buf.push_back(event);
580 }
581 _ => self.buf.push_back(event),
582 }
583 }
584 let id = self.id_map.derive(id);
585
586 if let Some(ref mut builder) = self.toc {
587 let mut text_header = String::new();
588 plain_text_from_events(self.buf.iter().map(|(ev, _)| ev.clone()), &mut text_header);
589 let mut html_header = String::new();
590 html_text_from_events(self.buf.iter().map(|(ev, _)| ev.clone()), &mut html_header);
591 let sec = builder.push(level as u32, text_header, html_header, id.clone());
592 self.buf.push_front((Event::Html(format!("{sec} ").into()), 0..0));
593 }
594
595 let level =
596 std::cmp::min(level as u32 + (self.heading_offset as u32), MAX_HEADER_LEVEL);
597 self.buf.push_back((Event::Html(format!("</h{level}>").into()), 0..0));
598
599 let start_tags =
600 format!("<h{level} id=\"{id}\"><a class=\"doc-anchor\" href=\"#{id}\">§</a>");
601 return Some((Event::Html(start_tags.into()), 0..0));
602 }
603 event
604 }
605}
606
607struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
609 inner: I,
610 started: bool,
611 depth: u32,
612 skipped_tags: u32,
613}
614
615impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
616 fn new(iter: I) -> Self {
617 SummaryLine { inner: iter, started: false, depth: 0, skipped_tags: 0 }
618 }
619}
620
621fn check_if_allowed_tag(t: &TagEnd) -> bool {
622 matches!(
623 t,
624 TagEnd::Paragraph
625 | TagEnd::Emphasis
626 | TagEnd::Strong
627 | TagEnd::Strikethrough
628 | TagEnd::Link
629 | TagEnd::BlockQuote
630 )
631}
632
633fn is_forbidden_tag(t: &TagEnd) -> bool {
634 matches!(
635 t,
636 TagEnd::CodeBlock
637 | TagEnd::Table
638 | TagEnd::TableHead
639 | TagEnd::TableRow
640 | TagEnd::TableCell
641 | TagEnd::FootnoteDefinition
642 )
643}
644
645impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
646 type Item = Event<'a>;
647
648 fn next(&mut self) -> Option<Self::Item> {
649 if self.started && self.depth == 0 {
650 return None;
651 }
652 if !self.started {
653 self.started = true;
654 }
655 if let Some(event) = self.inner.next() {
656 let mut is_start = true;
657 let is_allowed_tag = match event {
658 Event::Start(ref c) => {
659 if is_forbidden_tag(&c.to_end()) {
660 self.skipped_tags += 1;
661 return None;
662 }
663 self.depth += 1;
664 check_if_allowed_tag(&c.to_end())
665 }
666 Event::End(ref c) => {
667 if is_forbidden_tag(c) {
668 self.skipped_tags += 1;
669 return None;
670 }
671 self.depth -= 1;
672 is_start = false;
673 check_if_allowed_tag(c)
674 }
675 Event::FootnoteReference(_) => {
676 self.skipped_tags += 1;
677 false
678 }
679 _ => true,
680 };
681 if !is_allowed_tag {
682 self.skipped_tags += 1;
683 }
684 return if !is_allowed_tag {
685 if is_start {
686 Some(Event::Start(Tag::Paragraph))
687 } else {
688 Some(Event::End(TagEnd::Paragraph))
689 }
690 } else {
691 Some(event)
692 };
693 }
694 None
695 }
696}
697
698pub(crate) struct MdRelLine {
705 offset: usize,
706}
707
708impl MdRelLine {
709 pub(crate) const fn new(offset: usize) -> Self {
711 Self { offset }
712 }
713
714 pub(crate) const fn offset(self) -> usize {
716 self.offset
717 }
718}
719
720pub(crate) fn find_testable_code<T: doctest::DocTestVisitor>(
721 doc: &str,
722 tests: &mut T,
723 error_codes: ErrorCodes,
724 extra_info: Option<&ExtraInfo<'_>>,
725) {
726 find_codes(doc, tests, error_codes, extra_info, false)
727}
728
729pub(crate) fn find_codes<T: doctest::DocTestVisitor>(
730 doc: &str,
731 tests: &mut T,
732 error_codes: ErrorCodes,
733 extra_info: Option<&ExtraInfo<'_>>,
734 include_non_rust: bool,
735) {
736 let mut parser = Parser::new_ext(doc, main_body_opts()).into_offset_iter();
737 let mut prev_offset = 0;
738 let mut nb_lines = 0;
739 let mut register_header = None;
740 while let Some((event, offset)) = parser.next() {
741 match event {
742 Event::Start(Tag::CodeBlock(kind)) => {
743 let block_info = match kind {
744 CodeBlockKind::Fenced(ref lang) => {
745 if lang.is_empty() {
746 Default::default()
747 } else {
748 LangString::parse(lang, error_codes, extra_info)
749 }
750 }
751 CodeBlockKind::Indented => Default::default(),
752 };
753 if !include_non_rust && !block_info.rust {
754 continue;
755 }
756
757 let mut test_s = String::new();
758
759 while let Some((Event::Text(s), _)) = parser.next() {
760 test_s.push_str(&s);
761 }
762 let text = test_s
763 .lines()
764 .map(|l| map_line(l).for_code())
765 .collect::<Vec<Cow<'_, str>>>()
766 .join("\n");
767
768 nb_lines += doc[prev_offset..offset.start].lines().count();
769 if nb_lines != 0 && !&doc[prev_offset..offset.start].ends_with('\n') {
773 nb_lines -= 1;
774 }
775 let line = MdRelLine::new(nb_lines);
776 tests.visit_test(text, block_info, line);
777 prev_offset = offset.start;
778 }
779 Event::Start(Tag::Heading { level, .. }) => {
780 register_header = Some(level as u32);
781 }
782 Event::Text(ref s) if register_header.is_some() => {
783 let level = register_header.unwrap();
784 tests.visit_header(s, level);
785 register_header = None;
786 }
787 _ => {}
788 }
789 }
790}
791
792pub(crate) struct ExtraInfo<'tcx> {
793 def_id: LocalDefId,
794 sp: Span,
795 tcx: TyCtxt<'tcx>,
796}
797
798impl<'tcx> ExtraInfo<'tcx> {
799 pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId, sp: Span) -> ExtraInfo<'tcx> {
800 ExtraInfo { def_id, sp, tcx }
801 }
802
803 fn error_invalid_codeblock_attr(&self, msg: impl Into<DiagMessage>) {
804 self.error_invalid_codeblock_attr_with_help(msg, |_| {});
805 }
806
807 fn error_invalid_codeblock_attr_with_help(
808 &self,
809 msg: impl Into<DiagMessage>,
810 f: impl for<'a, 'b> FnOnce(&'b mut Diag<'a, ()>),
811 ) {
812 self.tcx.emit_node_span_lint(
813 crate::lint::INVALID_CODEBLOCK_ATTRIBUTES,
814 self.tcx.local_def_id_to_hir_id(self.def_id),
815 self.sp,
816 rustc_errors::DiagDecorator(|lint| {
817 lint.primary_message(msg);
818 f(lint);
819 }),
820 );
821 }
822}
823
824#[derive(Eq, PartialEq, Clone, Debug)]
825pub(crate) struct LangString {
826 pub(crate) original: String,
827 pub(crate) should_panic: bool,
828 pub(crate) no_run: bool,
829 pub(crate) ignore: Ignore,
830 pub(crate) rust: bool,
831 pub(crate) test_harness: bool,
832 pub(crate) compile_fail: bool,
833 pub(crate) standalone_crate: bool,
834 pub(crate) error_codes: Vec<String>,
835 pub(crate) edition: Option<Edition>,
836 pub(crate) added_classes: Vec<String>,
837 pub(crate) unknown: Vec<String>,
838}
839
840#[derive(Eq, PartialEq, Clone, Debug)]
841pub(crate) enum Ignore {
842 All,
843 None,
844 Some(Vec<String>),
845}
846
847pub(crate) struct TagIterator<'a, 'tcx> {
887 inner: Peekable<CharIndices<'a>>,
888 data: &'a str,
889 is_in_attribute_block: bool,
890 extra: Option<&'a ExtraInfo<'tcx>>,
891 is_error: bool,
892}
893
894#[derive(Clone, Debug, Eq, PartialEq)]
895pub(crate) enum LangStringToken<'a> {
896 LangToken(&'a str),
897 ClassAttribute(&'a str),
898 KeyValueAttribute(&'a str, &'a str),
899}
900
901fn is_leading_char(c: char) -> bool {
902 c == '_' || c == '-' || c == ':' || c.is_ascii_alphabetic() || c.is_ascii_digit()
903}
904fn is_bareword_char(c: char) -> bool {
905 is_leading_char(c) || ".!#$%&*+/;<>?@^|~".contains(c)
906}
907fn is_separator(c: char) -> bool {
908 c == ' ' || c == ',' || c == '\t'
909}
910
911struct Indices {
912 start: usize,
913 end: usize,
914}
915
916impl<'a, 'tcx> TagIterator<'a, 'tcx> {
917 pub(crate) fn new(data: &'a str, extra: Option<&'a ExtraInfo<'tcx>>) -> Self {
918 Self {
919 inner: data.char_indices().peekable(),
920 data,
921 is_in_attribute_block: false,
922 extra,
923 is_error: false,
924 }
925 }
926
927 fn emit_error(&mut self, err: impl Into<DiagMessage>) {
928 if let Some(extra) = self.extra {
929 extra.error_invalid_codeblock_attr(err);
930 }
931 self.is_error = true;
932 }
933
934 fn skip_separators(&mut self) -> Option<usize> {
935 while let Some((pos, c)) = self.inner.peek() {
936 if !is_separator(*c) {
937 return Some(*pos);
938 }
939 self.inner.next();
940 }
941 None
942 }
943
944 fn parse_string(&mut self, start: usize) -> Option<Indices> {
945 for (pos, c) in self.inner.by_ref() {
946 if c == '"' {
947 return Some(Indices { start: start + 1, end: pos });
948 }
949 }
950 self.emit_error("unclosed quote string `\"`");
951 None
952 }
953
954 fn parse_class(&mut self, start: usize) -> Option<LangStringToken<'a>> {
955 while let Some((pos, c)) = self.inner.peek().copied() {
956 if is_bareword_char(c) {
957 self.inner.next();
958 } else {
959 let class = &self.data[start + 1..pos];
960 if class.is_empty() {
961 self.emit_error(format!("unexpected `{c}` character after `.`"));
962 return None;
963 } else if self.check_after_token() {
964 return Some(LangStringToken::ClassAttribute(class));
965 } else {
966 return None;
967 }
968 }
969 }
970 let class = &self.data[start + 1..];
971 if class.is_empty() {
972 self.emit_error("missing character after `.`");
973 None
974 } else if self.check_after_token() {
975 Some(LangStringToken::ClassAttribute(class))
976 } else {
977 None
978 }
979 }
980
981 fn parse_token(&mut self, start: usize) -> Option<Indices> {
982 while let Some((pos, c)) = self.inner.peek() {
983 if !is_bareword_char(*c) {
984 return Some(Indices { start, end: *pos });
985 }
986 self.inner.next();
987 }
988 self.emit_error("unexpected end");
989 None
990 }
991
992 fn parse_key_value(&mut self, c: char, start: usize) -> Option<LangStringToken<'a>> {
993 let key_indices =
994 if c == '"' { self.parse_string(start)? } else { self.parse_token(start)? };
995 if key_indices.start == key_indices.end {
996 self.emit_error("unexpected empty string as key");
997 return None;
998 }
999
1000 if let Some((_, c)) = self.inner.next() {
1001 if c != '=' {
1002 self.emit_error(format!("expected `=`, found `{c}`"));
1003 return None;
1004 }
1005 } else {
1006 self.emit_error("unexpected end");
1007 return None;
1008 }
1009 let value_indices = match self.inner.next() {
1010 Some((pos, '"')) => self.parse_string(pos)?,
1011 Some((pos, c)) if is_bareword_char(c) => self.parse_token(pos)?,
1012 Some((_, c)) => {
1013 self.emit_error(format!("unexpected `{c}` character after `=`"));
1014 return None;
1015 }
1016 None => {
1017 self.emit_error("expected value after `=`");
1018 return None;
1019 }
1020 };
1021 if value_indices.start == value_indices.end {
1022 self.emit_error("unexpected empty string as value");
1023 None
1024 } else if self.check_after_token() {
1025 Some(LangStringToken::KeyValueAttribute(
1026 &self.data[key_indices.start..key_indices.end],
1027 &self.data[value_indices.start..value_indices.end],
1028 ))
1029 } else {
1030 None
1031 }
1032 }
1033
1034 fn check_after_token(&mut self) -> bool {
1036 if let Some((_, c)) = self.inner.peek().copied() {
1037 if c == '}' || is_separator(c) || c == '(' {
1038 true
1039 } else {
1040 self.emit_error(format!("unexpected `{c}` character"));
1041 false
1042 }
1043 } else {
1044 true
1046 }
1047 }
1048
1049 fn parse_in_attribute_block(&mut self) -> Option<LangStringToken<'a>> {
1050 if let Some((pos, c)) = self.inner.next() {
1051 if c == '}' {
1052 self.is_in_attribute_block = false;
1053 return self.next();
1054 } else if c == '.' {
1055 return self.parse_class(pos);
1056 } else if c == '"' || is_leading_char(c) {
1057 return self.parse_key_value(c, pos);
1058 } else {
1059 self.emit_error(format!("unexpected character `{c}`"));
1060 return None;
1061 }
1062 }
1063 self.emit_error("unclosed attribute block (`{}`): missing `}` at the end");
1064 None
1065 }
1066
1067 fn skip_paren_block(&mut self) -> bool {
1069 for (_, c) in self.inner.by_ref() {
1070 if c == ')' {
1071 return true;
1072 }
1073 }
1074 self.emit_error("unclosed comment: missing `)` at the end");
1075 false
1076 }
1077
1078 fn parse_outside_attribute_block(&mut self, start: usize) -> Option<LangStringToken<'a>> {
1079 while let Some((pos, c)) = self.inner.next() {
1080 if c == '"' {
1081 if pos != start {
1082 self.emit_error("expected ` `, `{` or `,` found `\"`");
1083 return None;
1084 }
1085 let indices = self.parse_string(pos)?;
1086 if let Some((_, c)) = self.inner.peek().copied()
1087 && c != '{'
1088 && !is_separator(c)
1089 && c != '('
1090 {
1091 self.emit_error(format!("expected ` `, `{{` or `,` after `\"`, found `{c}`"));
1092 return None;
1093 }
1094 return Some(LangStringToken::LangToken(&self.data[indices.start..indices.end]));
1095 } else if c == '{' {
1096 self.is_in_attribute_block = true;
1097 return self.next();
1098 } else if is_separator(c) {
1099 if pos != start {
1100 return Some(LangStringToken::LangToken(&self.data[start..pos]));
1101 }
1102 return self.next();
1103 } else if c == '(' {
1104 if !self.skip_paren_block() {
1105 return None;
1106 }
1107 if pos != start {
1108 return Some(LangStringToken::LangToken(&self.data[start..pos]));
1109 }
1110 return self.next();
1111 } else if (pos == start && is_leading_char(c)) || (pos != start && is_bareword_char(c))
1112 {
1113 continue;
1114 } else {
1115 self.emit_error(format!("unexpected character `{c}`"));
1116 return None;
1117 }
1118 }
1119 let token = &self.data[start..];
1120 if token.is_empty() { None } else { Some(LangStringToken::LangToken(&self.data[start..])) }
1121 }
1122}
1123
1124impl<'a> Iterator for TagIterator<'a, '_> {
1125 type Item = LangStringToken<'a>;
1126
1127 fn next(&mut self) -> Option<Self::Item> {
1128 if self.is_error {
1129 return None;
1130 }
1131 let Some(start) = self.skip_separators() else {
1132 if self.is_in_attribute_block {
1133 self.emit_error("unclosed attribute block (`{}`): missing `}` at the end");
1134 }
1135 return None;
1136 };
1137 if self.is_in_attribute_block {
1138 self.parse_in_attribute_block()
1139 } else {
1140 self.parse_outside_attribute_block(start)
1141 }
1142 }
1143}
1144
1145impl Default for LangString {
1146 fn default() -> Self {
1147 Self {
1148 original: String::new(),
1149 should_panic: false,
1150 no_run: false,
1151 ignore: Ignore::None,
1152 rust: true,
1153 test_harness: false,
1154 compile_fail: false,
1155 standalone_crate: false,
1156 error_codes: Vec::new(),
1157 edition: None,
1158 added_classes: Vec::new(),
1159 unknown: Vec::new(),
1160 }
1161 }
1162}
1163
1164impl LangString {
1165 fn parse_without_check(string: &str, allow_error_code_check: ErrorCodes) -> Self {
1166 Self::parse(string, allow_error_code_check, None)
1167 }
1168
1169 fn parse(
1170 string: &str,
1171 allow_error_code_check: ErrorCodes,
1172 extra: Option<&ExtraInfo<'_>>,
1173 ) -> Self {
1174 let allow_error_code_check = allow_error_code_check.as_bool();
1175 let mut seen_rust_tags = false;
1176 let mut seen_other_tags = false;
1177 let mut seen_custom_tag = false;
1178 let mut data = LangString::default();
1179 let mut ignores = vec![];
1180
1181 data.original = string.to_owned();
1182
1183 let mut call = |tokens: &mut dyn Iterator<Item = LangStringToken<'_>>| {
1184 for token in tokens {
1185 match token {
1186 LangStringToken::LangToken("should_panic") => {
1187 data.should_panic = true;
1188 seen_rust_tags = !seen_other_tags;
1189 }
1190 LangStringToken::LangToken("no_run") => {
1191 data.no_run = true;
1192 seen_rust_tags = !seen_other_tags;
1193 }
1194 LangStringToken::LangToken("ignore") => {
1195 data.ignore = Ignore::All;
1196 seen_rust_tags = !seen_other_tags;
1197 }
1198 LangStringToken::LangToken(x)
1199 if let Some(ignore) = x.strip_prefix("ignore-") =>
1200 {
1201 ignores.push(ignore.to_owned());
1202 seen_rust_tags = !seen_other_tags;
1203 }
1204 LangStringToken::LangToken("rust") => {
1205 data.rust = true;
1206 seen_rust_tags = true;
1207 }
1208 LangStringToken::LangToken("custom") => {
1209 seen_custom_tag = true;
1210 }
1211 LangStringToken::LangToken("test_harness") => {
1212 data.test_harness = true;
1213 seen_rust_tags = !seen_other_tags || seen_rust_tags;
1214 }
1215 LangStringToken::LangToken("compile_fail") => {
1216 data.compile_fail = true;
1217 seen_rust_tags = !seen_other_tags || seen_rust_tags;
1218 data.no_run = true;
1219 }
1220 LangStringToken::LangToken("standalone_crate") => {
1221 data.standalone_crate = true;
1222 seen_rust_tags = !seen_other_tags || seen_rust_tags;
1223 }
1224 LangStringToken::LangToken(x)
1225 if let Some(edition) = x.strip_prefix("edition") =>
1226 {
1227 data.edition = edition.parse::<Edition>().ok();
1228 }
1229 LangStringToken::LangToken(x)
1230 if let Some(edition) = x.strip_prefix("rust")
1231 && edition.parse::<Edition>().is_ok()
1232 && let Some(extra) = extra =>
1233 {
1234 extra.error_invalid_codeblock_attr_with_help(
1235 format!("unknown attribute `{x}`"),
1236 |lint| {
1237 lint.help(format!(
1238 "there is an attribute with a similar name: `edition{edition}`"
1239 ));
1240 },
1241 );
1242 }
1243 LangStringToken::LangToken(x)
1244 if allow_error_code_check
1245 && let Some(error_code) = x.strip_prefix('E')
1246 && error_code.len() == 4 =>
1247 {
1248 if error_code.parse::<u32>().is_ok() {
1249 data.error_codes.push(x.to_owned());
1250 seen_rust_tags = !seen_other_tags || seen_rust_tags;
1251 } else {
1252 seen_other_tags = true;
1253 }
1254 }
1255 LangStringToken::LangToken(x) if let Some(extra) = extra => {
1256 if let Some(help) = match x.to_lowercase().as_str() {
1257 "compile-fail" | "compile_fail" | "compilefail" => Some(
1258 "use `compile_fail` to invert the results of this test, so that it \
1259 passes if it cannot be compiled and fails if it can",
1260 ),
1261 "should-panic" | "should_panic" | "shouldpanic" => Some(
1262 "use `should_panic` to invert the results of this test, so that if \
1263 passes if it panics and fails if it does not",
1264 ),
1265 "no-run" | "no_run" | "norun" => Some(
1266 "use `no_run` to compile, but not run, the code sample during \
1267 testing",
1268 ),
1269 "test-harness" | "test_harness" | "testharness" => Some(
1270 "use `test_harness` to run functions marked `#[test]` instead of a \
1271 potentially-implicit `main` function",
1272 ),
1273 "standalone" | "standalone_crate" | "standalone-crate"
1274 if extra.sp.at_least_rust_2024() =>
1275 {
1276 Some(
1277 "use `standalone_crate` to compile this code block \
1278 separately",
1279 )
1280 }
1281 _ => None,
1282 } {
1283 extra.error_invalid_codeblock_attr_with_help(
1284 format!("unknown attribute `{x}`"),
1285 |lint| {
1286 lint.help(help).help(
1287 "this code block may be skipped during testing, \
1288 because unknown attributes are treated as markers for \
1289 code samples written in other programming languages, \
1290 unless it is also explicitly marked as `rust`",
1291 );
1292 },
1293 );
1294 }
1295 seen_other_tags = true;
1296 data.unknown.push(x.to_owned());
1297 }
1298 LangStringToken::LangToken(x) => {
1299 seen_other_tags = true;
1300 data.unknown.push(x.to_owned());
1301 }
1302 LangStringToken::KeyValueAttribute("class", value) => {
1303 data.added_classes.push(value.to_owned());
1304 }
1305 LangStringToken::KeyValueAttribute(key, ..) if let Some(extra) = extra => {
1306 extra
1307 .error_invalid_codeblock_attr(format!("unsupported attribute `{key}`"));
1308 }
1309 LangStringToken::ClassAttribute(class) => {
1310 data.added_classes.push(class.to_owned());
1311 }
1312 _ => {}
1313 }
1314 }
1315 };
1316
1317 let mut tag_iter = TagIterator::new(string, extra);
1318 call(&mut tag_iter);
1319
1320 if !ignores.is_empty() {
1322 data.ignore = Ignore::Some(ignores);
1323 }
1324
1325 data.rust &= !seen_custom_tag && (!seen_other_tags || seen_rust_tags) && !tag_iter.is_error;
1326
1327 data
1328 }
1329}
1330
1331impl<'a> Markdown<'a> {
1332 pub fn write_into(self, f: impl fmt::Write) -> fmt::Result {
1333 if self.content.is_empty() {
1335 return Ok(());
1336 }
1337
1338 html::write_html_fmt(f, self.into_iter())
1339 }
1340
1341 fn into_iter(self) -> CodeBlocks<'a, 'a, impl Iterator<Item = Event<'a>>> {
1342 let Markdown {
1343 content: md,
1344 links,
1345 ids,
1346 error_codes: codes,
1347 edition,
1348 playground,
1349 heading_offset,
1350 } = self;
1351
1352 let replacer = move |broken_link: BrokenLink<'_>| {
1353 links
1354 .iter()
1355 .find(|link| *link.original_text == *broken_link.reference)
1356 .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1357 };
1358
1359 let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(replacer));
1360 let p = p.into_offset_iter();
1361
1362 ids.handle_footnotes(|ids, existing_footnotes| {
1363 let p = HeadingLinks::new(p, None, ids, heading_offset);
1364 let p = SpannedLinkReplacer::new(p, links);
1365 let p = footnotes::Footnotes::new(p, existing_footnotes);
1366 let p = TableWrapper::new(p.map(|(ev, _)| ev));
1367 CodeBlocks::new(p, codes, edition, playground)
1368 })
1369 }
1370
1371 pub(crate) fn split_summary_and_content(self) -> (Option<String>, Option<String>) {
1377 if self.content.is_empty() {
1378 return (None, None);
1379 }
1380 let mut p = self.into_iter();
1381
1382 let mut event_level = 0;
1383 let mut summary_events = Vec::new();
1384 let mut get_next_tag = false;
1385
1386 let mut end_of_summary = false;
1387 while let Some(event) = p.next() {
1388 match event {
1389 Event::Start(_) => event_level += 1,
1390 Event::End(kind) => {
1391 event_level -= 1;
1392 if event_level == 0 {
1393 end_of_summary = true;
1395 get_next_tag = kind == TagEnd::Table;
1397 }
1398 }
1399 _ => {}
1400 }
1401 summary_events.push(event);
1402 if end_of_summary {
1403 if get_next_tag && let Some(event) = p.next() {
1404 summary_events.push(event);
1405 }
1406 break;
1407 }
1408 }
1409 let mut summary = String::new();
1410 html::push_html(&mut summary, summary_events.into_iter());
1411 if summary.is_empty() {
1412 return (None, None);
1413 }
1414 let mut content = String::new();
1415 html::push_html(&mut content, p);
1416
1417 if content.is_empty() { (Some(summary), None) } else { (Some(summary), Some(content)) }
1418 }
1419}
1420
1421impl MarkdownWithToc<'_> {
1422 pub(crate) fn into_parts(self) -> (Toc, String) {
1423 let MarkdownWithToc { content: md, links, ids, error_codes: codes, edition, playground } =
1424 self;
1425
1426 if md.is_empty() {
1428 return (Toc { entries: Vec::new() }, String::new());
1429 }
1430 let mut replacer = |broken_link: BrokenLink<'_>| {
1431 links
1432 .iter()
1433 .find(|link| *link.original_text == *broken_link.reference)
1434 .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1435 };
1436
1437 let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(&mut replacer));
1438 let p = p.into_offset_iter();
1439
1440 let mut s = String::with_capacity(md.len() * 3 / 2);
1441
1442 let mut toc = TocBuilder::new();
1443
1444 ids.handle_footnotes(|ids, existing_footnotes| {
1445 let p = HeadingLinks::new(p, Some(&mut toc), ids, HeadingOffset::H1);
1446 let p = footnotes::Footnotes::new(p, existing_footnotes);
1447 let p = TableWrapper::new(p.map(|(ev, _)| ev));
1448 let p = CodeBlocks::new(p, codes, edition, playground);
1449 html::push_html(&mut s, p);
1450 });
1451
1452 (toc.into_toc(), s)
1453 }
1454
1455 pub(crate) fn write_into(self, mut f: impl fmt::Write) -> fmt::Result {
1456 let (toc, s) = self.into_parts();
1457 write!(f, "<nav id=\"rustdoc\">{toc}</nav>{s}", toc = toc.print())
1458 }
1459}
1460
1461impl<'a> MarkdownItemInfo<'a> {
1462 pub(crate) fn new(content: &'a str, links: &'a [RenderedLink], ids: &'a mut IdMap) -> Self {
1463 Self { content, links, ids }
1464 }
1465
1466 pub(crate) fn write_into(self, mut f: impl fmt::Write) -> fmt::Result {
1467 let MarkdownItemInfo { content: md, links, ids } = self;
1468
1469 if md.is_empty() {
1471 return Ok(());
1472 }
1473
1474 let replacer = move |broken_link: BrokenLink<'_>| {
1475 links
1476 .iter()
1477 .find(|link| *link.original_text == *broken_link.reference)
1478 .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1479 };
1480
1481 let p = Parser::new_with_broken_link_callback(md, main_body_opts(), Some(replacer));
1482 let p = p.into_offset_iter();
1483
1484 let p = p.map(|event| match event.0 {
1486 Event::Html(text) | Event::InlineHtml(text) => (Event::Text(text), event.1),
1487 _ => event,
1488 });
1489
1490 ids.handle_footnotes(|ids, existing_footnotes| {
1491 let p = HeadingLinks::new(p, None, ids, HeadingOffset::H1);
1492 let p = SpannedLinkReplacer::new(p, links);
1493 let p = footnotes::Footnotes::new(p, existing_footnotes);
1494 let p = TableWrapper::new(p.map(|(ev, _)| ev));
1495 html::write_html_fmt(&mut f, p)?;
1497
1498 Ok(())
1499 })
1500 }
1501}
1502
1503impl MarkdownSummaryLine<'_> {
1504 pub(crate) fn into_string_with_has_more_content(self) -> (String, bool) {
1505 let MarkdownSummaryLine(md, links) = self;
1506 if md.is_empty() {
1508 return (String::new(), false);
1509 }
1510
1511 let mut replacer = |broken_link: BrokenLink<'_>| {
1512 links
1513 .iter()
1514 .find(|link| *link.original_text == *broken_link.reference)
1515 .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1516 };
1517
1518 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer))
1519 .peekable();
1520 let mut summary = SummaryLine::new(p);
1521
1522 let mut s = String::new();
1523
1524 let without_paragraphs = LinkReplacer::new(&mut summary, links).filter(|event| {
1525 !matches!(event, Event::Start(Tag::Paragraph) | Event::End(TagEnd::Paragraph))
1526 });
1527
1528 html::push_html(&mut s, without_paragraphs);
1529
1530 let has_more_content =
1531 matches!(summary.inner.peek(), Some(Event::Start(_))) || summary.skipped_tags > 0;
1532
1533 (s, has_more_content)
1534 }
1535
1536 pub(crate) fn into_string(self) -> String {
1537 self.into_string_with_has_more_content().0
1538 }
1539}
1540
1541fn markdown_summary_with_limit(
1550 md: &str,
1551 link_names: &[RenderedLink],
1552 length_limit: usize,
1553) -> (String, bool) {
1554 if md.is_empty() {
1555 return (String::new(), false);
1556 }
1557
1558 let mut replacer = |broken_link: BrokenLink<'_>| {
1559 link_names
1560 .iter()
1561 .find(|link| *link.original_text == *broken_link.reference)
1562 .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1563 };
1564
1565 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1566 let mut p = LinkReplacer::new(p, link_names);
1567
1568 let mut buf = HtmlWithLimit::new(length_limit);
1569 let mut stopped_early = false;
1570 let _ = p.try_for_each(|event| {
1571 match &event {
1572 Event::Text(text) => {
1573 let r =
1574 text.split_inclusive(char::is_whitespace).try_for_each(|word| buf.push(word));
1575 if r.is_break() {
1576 stopped_early = true;
1577 }
1578 return r;
1579 }
1580 Event::Code(code) => {
1581 buf.open_tag("code");
1582 let r = buf.push(code);
1583 if r.is_break() {
1584 stopped_early = true;
1585 } else {
1586 buf.close_tag();
1587 }
1588 return r;
1589 }
1590 Event::Start(tag) => match tag {
1591 Tag::Emphasis => buf.open_tag("em"),
1592 Tag::Strong => buf.open_tag("strong"),
1593 Tag::CodeBlock(..) => return ControlFlow::Break(()),
1594 _ => {}
1595 },
1596 Event::End(tag) => match tag {
1597 TagEnd::Emphasis | TagEnd::Strong => buf.close_tag(),
1598 TagEnd::Paragraph | TagEnd::Heading(_) => return ControlFlow::Break(()),
1599 _ => {}
1600 },
1601 Event::HardBreak | Event::SoftBreak => buf.push(" ")?,
1602 _ => {}
1603 };
1604 ControlFlow::Continue(())
1605 });
1606
1607 (buf.finish(), stopped_early)
1608}
1609
1610pub(crate) fn short_markdown_summary(markdown: &str, link_names: &[RenderedLink]) -> String {
1617 let (mut s, was_shortened) = markdown_summary_with_limit(markdown, link_names, 59);
1618
1619 if was_shortened {
1620 s.push('…');
1621 }
1622
1623 s
1624}
1625
1626pub(crate) fn plain_text_summary(md: &str, link_names: &[RenderedLink]) -> String {
1633 if md.is_empty() {
1634 return String::new();
1635 }
1636
1637 let mut s = String::with_capacity(md.len() * 3 / 2);
1638
1639 let mut replacer = |broken_link: BrokenLink<'_>| {
1640 link_names
1641 .iter()
1642 .find(|link| *link.original_text == *broken_link.reference)
1643 .map(|link| (link.href.as_str().into(), link.tooltip.as_str().into()))
1644 };
1645
1646 let p = Parser::new_with_broken_link_callback(md, summary_opts(), Some(&mut replacer));
1647
1648 plain_text_from_events(p, &mut s);
1649
1650 s
1651}
1652
1653pub(crate) fn plain_text_from_events<'a>(
1654 events: impl Iterator<Item = pulldown_cmark::Event<'a>>,
1655 s: &mut String,
1656) {
1657 for event in events {
1658 match &event {
1659 Event::Text(text) => s.push_str(text),
1660 Event::Code(code) => {
1661 s.push('`');
1662 s.push_str(code);
1663 s.push('`');
1664 }
1665 Event::HardBreak | Event::SoftBreak => s.push(' '),
1666 Event::Start(Tag::CodeBlock(..)) => break,
1667 Event::End(TagEnd::Paragraph) => break,
1668 Event::End(TagEnd::Heading(..)) => break,
1669 _ => (),
1670 }
1671 }
1672}
1673
1674pub(crate) fn html_text_from_events<'a>(
1675 events: impl Iterator<Item = pulldown_cmark::Event<'a>>,
1676 s: &mut String,
1677) {
1678 for event in events {
1679 match &event {
1680 Event::Text(text) => {
1681 write!(s, "{}", EscapeBodyText(text)).expect("string alloc infallible")
1682 }
1683 Event::Code(code) => {
1684 s.push_str("<code>");
1685 write!(s, "{}", EscapeBodyText(code)).expect("string alloc infallible");
1686 s.push_str("</code>");
1687 }
1688 Event::HardBreak | Event::SoftBreak => s.push(' '),
1689 Event::Start(Tag::CodeBlock(..)) => break,
1690 Event::End(TagEnd::Paragraph) => break,
1691 Event::End(TagEnd::Heading(..)) => break,
1692 _ => (),
1693 }
1694 }
1695}
1696
1697#[derive(Debug)]
1698pub(crate) struct MarkdownLink {
1699 pub kind: LinkType,
1700 pub link: String,
1701 pub range: MarkdownLinkRange,
1702}
1703
1704#[derive(Clone, Debug)]
1705pub(crate) enum MarkdownLinkRange {
1706 Destination(Range<usize>),
1708 WholeLink(Range<usize>),
1712}
1713
1714impl MarkdownLinkRange {
1715 pub fn inner_range(&self) -> &Range<usize> {
1717 match self {
1718 MarkdownLinkRange::Destination(range) => range,
1719 MarkdownLinkRange::WholeLink(range) => range,
1720 }
1721 }
1722}
1723
1724pub(crate) fn markdown_links<'md, R>(
1725 md: &'md str,
1726 preprocess_link: impl Fn(MarkdownLink) -> Option<R>,
1727) -> Vec<R> {
1728 use itertools::Itertools;
1729 if md.is_empty() {
1730 return vec![];
1731 }
1732
1733 let locate = |s: &str, fallback: Range<usize>| unsafe {
1735 let s_start = s.as_ptr();
1736 let s_end = s_start.add(s.len());
1737 let md_start = md.as_ptr();
1738 let md_end = md_start.add(md.len());
1739 if md_start <= s_start && s_end <= md_end {
1740 let start = s_start.offset_from(md_start) as usize;
1741 let end = s_end.offset_from(md_start) as usize;
1742 MarkdownLinkRange::Destination(start..end)
1743 } else {
1744 MarkdownLinkRange::WholeLink(fallback)
1745 }
1746 };
1747
1748 let span_for_link = |link: &CowStr<'_>, span: Range<usize>| {
1749 match link {
1754 CowStr::Borrowed(s) => locate(s, span),
1759
1760 CowStr::Boxed(_) | CowStr::Inlined(_) => MarkdownLinkRange::WholeLink(span),
1762 }
1763 };
1764
1765 let span_for_refdef = |link: &CowStr<'_>, span: Range<usize>| {
1766 let mut square_brace_count = 0;
1769 let mut iter = md.as_bytes()[span.start..span.end].iter().copied().enumerate();
1770 for (_i, c) in &mut iter {
1771 match c {
1772 b':' if square_brace_count == 0 => break,
1773 b'[' => square_brace_count += 1,
1774 b']' => square_brace_count -= 1,
1775 _ => {}
1776 }
1777 }
1778 while let Some((i, c)) = iter.next() {
1779 if c == b'<' {
1780 while let Some((j, c)) = iter.next() {
1781 match c {
1782 b'\\' => {
1783 let _ = iter.next();
1784 }
1785 b'>' => {
1786 return MarkdownLinkRange::Destination(
1787 i + 1 + span.start..j + span.start,
1788 );
1789 }
1790 _ => {}
1791 }
1792 }
1793 } else if !c.is_ascii_whitespace() {
1794 for (j, c) in iter.by_ref() {
1795 if c.is_ascii_whitespace() {
1796 return MarkdownLinkRange::Destination(i + span.start..j + span.start);
1797 }
1798 }
1799 return MarkdownLinkRange::Destination(i + span.start..span.end);
1800 }
1801 }
1802 span_for_link(link, span)
1803 };
1804
1805 let span_for_offset_backward = |span: Range<usize>, open: u8, close: u8| {
1806 let mut open_brace = !0;
1807 let mut close_brace = !0;
1808 for (i, b) in md.as_bytes()[span.clone()].iter().copied().enumerate().rev() {
1809 let i = i + span.start;
1810 if b == close {
1811 close_brace = i;
1812 break;
1813 }
1814 }
1815 if close_brace < span.start || close_brace >= span.end {
1816 return MarkdownLinkRange::WholeLink(span);
1817 }
1818 let mut nesting = 1;
1819 for (i, b) in md.as_bytes()[span.start..close_brace].iter().copied().enumerate().rev() {
1820 let i = i + span.start;
1821 if b == close {
1822 nesting += 1;
1823 }
1824 if b == open {
1825 nesting -= 1;
1826 }
1827 if nesting == 0 {
1828 open_brace = i;
1829 break;
1830 }
1831 }
1832 assert!(open_brace != close_brace);
1833 if open_brace < span.start || open_brace >= span.end {
1834 return MarkdownLinkRange::WholeLink(span);
1835 }
1836 let range = (open_brace + 1)..close_brace;
1838 MarkdownLinkRange::Destination(range)
1839 };
1840
1841 let span_for_offset_forward = |span: Range<usize>, open: u8, close: u8| {
1842 let mut open_brace = !0;
1843 let mut close_brace = !0;
1844 for (i, b) in md.as_bytes()[span.clone()].iter().copied().enumerate() {
1845 let i = i + span.start;
1846 if b == open {
1847 open_brace = i;
1848 break;
1849 }
1850 }
1851 if open_brace < span.start || open_brace >= span.end {
1852 return MarkdownLinkRange::WholeLink(span);
1853 }
1854 let mut nesting = 0;
1855 for (i, b) in md.as_bytes()[open_brace..span.end].iter().copied().enumerate() {
1856 let i = i + open_brace;
1857 if b == close {
1858 nesting -= 1;
1859 }
1860 if b == open {
1861 nesting += 1;
1862 }
1863 if nesting == 0 {
1864 close_brace = i;
1865 break;
1866 }
1867 }
1868 assert!(open_brace != close_brace);
1869 if open_brace < span.start || open_brace >= span.end {
1870 return MarkdownLinkRange::WholeLink(span);
1871 }
1872 let range = (open_brace + 1)..close_brace;
1874 MarkdownLinkRange::Destination(range)
1875 };
1876
1877 let mut broken_link_callback = |link: BrokenLink<'md>| Some((link.reference, "".into()));
1878 let event_iter = Parser::new_with_broken_link_callback(
1879 md,
1880 main_body_opts(),
1881 Some(&mut broken_link_callback),
1882 )
1883 .into_offset_iter();
1884 let mut links = Vec::new();
1885
1886 let mut refdefs = FxIndexMap::default();
1887 for (label, refdef) in event_iter.reference_definitions().iter().sorted_by_key(|x| x.0) {
1888 refdefs.insert(label.to_string(), (false, refdef.dest.to_string(), refdef.span.clone()));
1889 }
1890
1891 for (event, span) in event_iter {
1892 match event {
1893 Event::Start(Tag::Link { link_type, dest_url, id, .. })
1894 if may_be_doc_link(link_type) =>
1895 {
1896 let range = match link_type {
1897 LinkType::ReferenceUnknown | LinkType::ShortcutUnknown => {
1899 span_for_offset_backward(span, b'[', b']')
1900 }
1901 LinkType::CollapsedUnknown => span_for_offset_forward(span, b'[', b']'),
1902 LinkType::Inline => span_for_offset_backward(span, b'(', b')'),
1903 LinkType::Reference | LinkType::Collapsed | LinkType::Shortcut => {
1905 if let Some((is_used, dest_url, span)) = refdefs.get_mut(&id[..]) {
1906 *is_used = true;
1907 span_for_refdef(&CowStr::from(&dest_url[..]), span.clone())
1908 } else {
1909 span_for_link(&dest_url, span)
1910 }
1911 }
1912 LinkType::Autolink | LinkType::Email => unreachable!(),
1913 };
1914
1915 if let Some(link) = preprocess_link(MarkdownLink {
1916 kind: link_type,
1917 link: dest_url.into_string(),
1918 range,
1919 }) {
1920 links.push(link);
1921 }
1922 }
1923 _ => {}
1924 }
1925 }
1926
1927 for (_label, (is_used, dest_url, span)) in refdefs.into_iter() {
1928 if !is_used
1929 && let Some(link) = preprocess_link(MarkdownLink {
1930 kind: LinkType::Reference,
1931 range: span_for_refdef(&CowStr::from(&dest_url[..]), span),
1932 link: dest_url,
1933 })
1934 {
1935 links.push(link);
1936 }
1937 }
1938
1939 links
1940}
1941
1942#[derive(Debug)]
1943pub(crate) struct RustCodeBlock {
1944 pub(crate) range: Range<usize>,
1947 pub(crate) code: Range<usize>,
1949 pub(crate) is_fenced: bool,
1950 pub(crate) lang_string: LangString,
1951}
1952
1953pub(crate) fn rust_code_blocks(md: &str, extra_info: &ExtraInfo<'_>) -> Vec<RustCodeBlock> {
1956 let mut code_blocks = vec![];
1957
1958 if md.is_empty() {
1959 return code_blocks;
1960 }
1961
1962 let mut p = Parser::new_ext(md, main_body_opts()).into_offset_iter();
1963
1964 while let Some((event, offset)) = p.next() {
1965 if let Event::Start(Tag::CodeBlock(syntax)) = event {
1966 let (lang_string, code_start, code_end, range, is_fenced) = match syntax {
1967 CodeBlockKind::Fenced(syntax) => {
1968 let syntax = syntax.as_ref();
1969 let lang_string = if syntax.is_empty() {
1970 Default::default()
1971 } else {
1972 LangString::parse(syntax, ErrorCodes::Yes, Some(extra_info))
1973 };
1974 if !lang_string.rust {
1975 continue;
1976 }
1977 let (code_start, mut code_end) = match p.next() {
1978 Some((Event::Text(_), offset)) => (offset.start, offset.end),
1979 Some((_, sub_offset)) => {
1980 let code = Range { start: sub_offset.start, end: sub_offset.start };
1981 code_blocks.push(RustCodeBlock {
1982 is_fenced: true,
1983 range: offset,
1984 code,
1985 lang_string,
1986 });
1987 continue;
1988 }
1989 None => {
1990 let code = Range { start: offset.end, end: offset.end };
1991 code_blocks.push(RustCodeBlock {
1992 is_fenced: true,
1993 range: offset,
1994 code,
1995 lang_string,
1996 });
1997 continue;
1998 }
1999 };
2000 while let Some((Event::Text(_), offset)) = p.next() {
2001 code_end = offset.end;
2002 }
2003 (lang_string, code_start, code_end, offset, true)
2004 }
2005 CodeBlockKind::Indented => {
2006 if offset.end > offset.start && md.get(offset.end..=offset.end) == Some("\n") {
2009 (
2010 LangString::default(),
2011 offset.start,
2012 offset.end,
2013 Range { start: offset.start, end: offset.end - 1 },
2014 false,
2015 )
2016 } else {
2017 (LangString::default(), offset.start, offset.end, offset, false)
2018 }
2019 }
2020 };
2021
2022 code_blocks.push(RustCodeBlock {
2023 is_fenced,
2024 range,
2025 code: Range { start: code_start, end: code_end },
2026 lang_string,
2027 });
2028 }
2029 }
2030
2031 code_blocks
2032}
2033
2034#[derive(Clone, Default, Debug)]
2035pub struct IdMap {
2036 map: FxHashMap<String, usize>,
2037 existing_footnotes: Arc<AtomicUsize>,
2038}
2039
2040fn is_default_id(id: &str) -> bool {
2041 matches!(
2042 id,
2043 "help"
2045 | "settings"
2046 | "not-displayed"
2047 | "alternative-display"
2048 | "search"
2049 | "crate-search"
2050 | "crate-search-div"
2051 | "themeStyle"
2054 | "settings-menu"
2055 | "help-button"
2056 | "sidebar-button"
2057 | "main-content"
2058 | "toggle-all-docs"
2059 | "all-types"
2060 | "default-settings"
2061 | "sidebar-vars"
2062 | "copy-path"
2063 | "rustdoc-toc"
2064 | "rustdoc-modnav"
2065 | "fields"
2068 | "variants"
2069 | "implementors-list"
2070 | "synthetic-implementors-list"
2071 | "foreign-impls"
2072 | "implementations"
2073 | "trait-implementations"
2074 | "synthetic-implementations"
2075 | "blanket-implementations"
2076 | "required-associated-types"
2077 | "provided-associated-types"
2078 | "provided-associated-consts"
2079 | "required-associated-consts"
2080 | "required-methods"
2081 | "provided-methods"
2082 | "dyn-compatibility"
2083 | "implementors"
2084 | "synthetic-implementors"
2085 | "implementations-list"
2086 | "trait-implementations-list"
2087 | "synthetic-implementations-list"
2088 | "blanket-implementations-list"
2089 | "deref-methods"
2090 | "layout"
2091 | "aliased-type"
2092 )
2093}
2094
2095impl IdMap {
2096 pub fn new() -> Self {
2097 IdMap { map: FxHashMap::default(), existing_footnotes: Arc::new(AtomicUsize::new(0)) }
2098 }
2099
2100 pub(crate) fn derive<S: AsRef<str> + ToString>(&mut self, candidate: S) -> String {
2101 let id = match self.map.get_mut(candidate.as_ref()) {
2102 None => {
2103 let candidate = candidate.to_string();
2104 if is_default_id(&candidate) {
2105 let id = format!("{}-{}", candidate, 1);
2106 self.map.insert(candidate, 2);
2107 id
2108 } else {
2109 candidate
2110 }
2111 }
2112 Some(a) => {
2113 let id = format!("{}-{}", candidate.as_ref(), *a);
2114 *a += 1;
2115 id
2116 }
2117 };
2118
2119 self.map.insert(id.clone(), 1);
2120 id
2121 }
2122
2123 pub(crate) fn handle_footnotes<'a, T, F: FnOnce(&'a mut Self, Weak<AtomicUsize>) -> T>(
2126 &'a mut self,
2127 closure: F,
2128 ) -> T {
2129 let existing_footnotes = Arc::downgrade(&self.existing_footnotes);
2130
2131 closure(self, existing_footnotes)
2132 }
2133
2134 pub(crate) fn clear(&mut self) {
2135 self.map.clear();
2136 self.existing_footnotes = Arc::new(AtomicUsize::new(0));
2137 }
2138}