1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Markdown formatting for rustdoc
13 //! This module implements markdown formatting through the pulldown-cmark
14 //! rust-library. This module exposes all of the
15 //! functionality through a unit-struct, `Markdown`, which has an implementation
16 //! of `fmt::Display`. Example usage:
19 //! #![feature(rustc_private)]
21 //! use rustdoc::html::markdown::{IdMap, Markdown, ErrorCodes};
22 //! use std::cell::RefCell;
24 //! let s = "My *markdown* _text_";
25 //! let mut id_map = IdMap::new();
26 //! let html = format!("{}", Markdown(s, &[], RefCell::new(&mut id_map), ErrorCodes::Yes));
27 //! // ... something using html
30 #![allow(non_camel_case_types)]
32 use rustc_data_structures::fx::FxHashMap;
33 use std::cell::RefCell;
34 use std::collections::VecDeque;
35 use std::default::Default;
36 use std::fmt::{self, Write};
40 use syntax::edition::Edition;
42 use html::toc::TocBuilder;
46 use pulldown_cmark::{html, Event, Tag, Parser};
47 use pulldown_cmark::{Options, OPTION_ENABLE_FOOTNOTES, OPTION_ENABLE_TABLES};
49 /// A unit struct which has the `fmt::Display` trait implemented. When
50 /// formatted, this struct will emit the HTML corresponding to the rendered
51 /// version of the contained markdown string.
52 /// The second parameter is a list of link replacements
53 pub struct Markdown<'a>(
54 pub &'a str, pub &'a [(String, String)], pub RefCell<&'a mut IdMap>, pub ErrorCodes);
55 /// A unit struct like `Markdown`, that renders the markdown with a
56 /// table of contents.
57 pub struct MarkdownWithToc<'a>(pub &'a str, pub RefCell<&'a mut IdMap>, pub ErrorCodes);
58 /// A unit struct like `Markdown`, that renders the markdown escaping HTML tags.
59 pub struct MarkdownHtml<'a>(pub &'a str, pub RefCell<&'a mut IdMap>, pub ErrorCodes);
60 /// A unit struct like `Markdown`, that renders only the first paragraph.
61 pub struct MarkdownSummaryLine<'a>(pub &'a str, pub &'a [(String, String)]);
63 #[derive(Copy, Clone, PartialEq, Debug)]
70 pub fn from(b: bool) -> Self {
72 true => ErrorCodes::Yes,
73 false => ErrorCodes::No,
77 pub fn as_bool(self) -> bool {
79 ErrorCodes::Yes => true,
80 ErrorCodes::No => false,
85 /// Controls whether a line will be hidden or shown in HTML output.
87 /// All lines are used in documentation tests.
94 fn for_html(self) -> Option<Cow<'a, str>> {
96 Line::Shown(l) => Some(l),
97 Line::Hidden(_) => None,
101 fn for_code(self) -> Cow<'a, str> {
104 Line::Hidden(l) => Cow::Borrowed(l),
109 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
110 // have no easy way of removing a potential single space after the hashes, which
111 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
112 // order to fix it we'd have to iterate to find the first non-# character, and
113 // then reallocate to remove it; which would make us return a String.
114 fn map_line(s: &str) -> Line {
115 let trimmed = s.trim();
116 if trimmed.starts_with("##") {
117 Line::Shown(Cow::Owned(s.replacen("##", "#", 1)))
118 } else if trimmed.starts_with("# ") {
120 Line::Hidden(&trimmed[2..])
121 } else if trimmed == "#" {
122 // We cannot handle '#text' because it could be #[attr].
125 Line::Shown(Cow::Borrowed(s))
129 /// Convert chars from a title for an id.
131 /// "Hello, world!" -> "hello-world"
132 fn slugify(c: char) -> Option<char> {
133 if c.is_alphanumeric() || c == '-' || c == '_' {
135 Some(c.to_ascii_lowercase())
139 } else if c.is_whitespace() && c.is_ascii() {
146 // Information about the playground if a URL has been specified, containing an
147 // optional crate name and the URL.
148 thread_local!(pub static PLAYGROUND: RefCell<Option<(Option<String>, String)>> = {
152 /// Adds syntax highlighting and playground Run buttons to rust code blocks.
153 struct CodeBlocks<'a, I: Iterator<Item = Event<'a>>> {
155 check_error_codes: ErrorCodes,
158 impl<'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'a, I> {
159 fn new(iter: I, error_codes: ErrorCodes) -> Self {
162 check_error_codes: error_codes,
167 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
168 type Item = Event<'a>;
170 fn next(&mut self) -> Option<Self::Item> {
171 let event = self.inner.next();
175 if let Some(Event::Start(Tag::CodeBlock(lang))) = event {
176 let parse_result = LangString::parse(&lang, self.check_error_codes);
177 if !parse_result.rust {
178 return Some(Event::Start(Tag::CodeBlock(lang)));
180 compile_fail = parse_result.compile_fail;
181 ignore = parse_result.ignore;
182 edition = parse_result.edition;
187 let mut origtext = String::new();
188 for event in &mut self.inner {
190 Event::End(Tag::CodeBlock(..)) => break,
191 Event::Text(ref s) => {
192 origtext.push_str(s);
197 let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
198 let text = lines.collect::<Vec<Cow<str>>>().join("\n");
199 PLAYGROUND.with(|play| {
200 // insert newline to clearly separate it from the
201 // previous block so we can shorten the html output
202 let mut s = String::from("\n");
203 let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
207 let test = origtext.lines()
208 .map(|l| map_line(l).for_code())
209 .collect::<Vec<Cow<str>>>().join("\n");
210 let krate = krate.as_ref().map(|s| &**s);
211 let (test, _) = test::make_test(&test, krate, false,
212 &Default::default());
213 let channel = if test.contains("#![feature(") {
214 "&version=nightly"
219 let edition_string = if let Some(e @ Edition::Edition2018) = edition {
220 format!("&edition={}{}", e,
221 if channel == "&version=nightly" { "" }
222 else { "&version=nightly" })
223 } else if let Some(e) = edition {
224 format!("&edition={}", e)
229 // These characters don't need to be escaped in a URI.
230 // FIXME: use a library function for percent encoding.
231 fn dont_escape(c: u8) -> bool {
232 (b'a' <= c && c <= b'z') ||
233 (b'A' <= c && c <= b'Z') ||
234 (b'0' <= c && c <= b'9') ||
235 c == b'-' || c == b'_' || c == b'.' ||
236 c == b'~' || c == b'!' || c == b'\'' ||
237 c == b'(' || c == b')' || c == b'*'
239 let mut test_escaped = String::new();
240 for b in test.bytes() {
242 test_escaped.push(char::from(b));
244 write!(test_escaped, "%{:02X}", b).unwrap();
248 r#"<a class="test-arrow" target="_blank" href="{}?code={}{}{}">Run</a>"#,
249 url, test_escaped, channel, edition_string
253 let tooltip = if ignore {
254 Some(("This example is not tested".to_owned(), "ignore"))
255 } else if compile_fail {
256 Some(("This example deliberately fails to compile".to_owned(), "compile_fail"))
257 } else if let Some(e) = edition {
258 Some((format!("This code runs with edition {}", e), "edition"))
263 if let Some((s1, s2)) = tooltip {
264 s.push_str(&highlight::render_with_highlighting(
266 Some(&format!("rust-example-rendered{}",
267 if ignore { " ignore" }
268 else if compile_fail { " compile_fail" }
269 else if edition.is_some() { " edition " }
271 playground_button.as_ref().map(String::as_str),
272 Some((s1.as_str(), s2))));
273 Some(Event::Html(s.into()))
275 s.push_str(&highlight::render_with_highlighting(
277 Some(&format!("rust-example-rendered{}",
278 if ignore { " ignore" }
279 else if compile_fail { " compile_fail" }
280 else if edition.is_some() { " edition " }
282 playground_button.as_ref().map(String::as_str),
284 Some(Event::Html(s.into()))
290 /// Make headings links with anchor ids and build up TOC.
291 struct LinkReplacer<'a, 'b, I: Iterator<Item = Event<'a>>> {
293 links: &'b [(String, String)],
296 impl<'a, 'b, I: Iterator<Item = Event<'a>>> LinkReplacer<'a, 'b, I> {
297 fn new(iter: I, links: &'b [(String, String)]) -> Self {
305 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for LinkReplacer<'a, 'b, I> {
306 type Item = Event<'a>;
308 fn next(&mut self) -> Option<Self::Item> {
309 let event = self.inner.next();
310 if let Some(Event::Start(Tag::Link(dest, text))) = event {
311 if let Some(&(_, ref replace)) = self.links.into_iter().find(|link| &*link.0 == &*dest)
313 Some(Event::Start(Tag::Link(replace.to_owned().into(), text)))
315 Some(Event::Start(Tag::Link(dest, text)))
323 /// Make headings links with anchor ids and build up TOC.
324 struct HeadingLinks<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> {
326 toc: Option<&'b mut TocBuilder>,
327 buf: VecDeque<Event<'a>>,
328 id_map: &'ids mut IdMap,
331 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, 'ids, I> {
332 fn new(iter: I, toc: Option<&'b mut TocBuilder>, ids: &'ids mut IdMap) -> Self {
336 buf: VecDeque::new(),
342 impl<'a, 'b, 'ids, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, 'ids, I> {
343 type Item = Event<'a>;
345 fn next(&mut self) -> Option<Self::Item> {
346 if let Some(e) = self.buf.pop_front() {
350 let event = self.inner.next();
351 if let Some(Event::Start(Tag::Header(level))) = event {
352 let mut id = String::new();
353 for event in &mut self.inner {
355 Event::End(Tag::Header(..)) => break,
356 Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
359 self.buf.push_back(event);
361 let id = self.id_map.derive(id);
363 if let Some(ref mut builder) = self.toc {
364 let mut html_header = String::new();
365 html::push_html(&mut html_header, self.buf.iter().cloned());
366 let sec = builder.push(level as u32, html_header, id.clone());
367 self.buf.push_front(Event::InlineHtml(format!("{} ", sec).into()));
370 self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
372 let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
376 return Some(Event::InlineHtml(start_tags.into()));
382 /// Extracts just the first paragraph.
383 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
389 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
390 fn new(iter: I) -> Self {
399 fn check_if_allowed_tag(t: &Tag) -> bool {
408 | Tag::BlockQuote => true,
413 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
414 type Item = Event<'a>;
416 fn next(&mut self) -> Option<Self::Item> {
417 if self.started && self.depth == 0 {
423 let event = self.inner.next();
424 let mut is_start = true;
425 let is_allowed_tag = match event {
426 Some(Event::Start(ref c)) => {
428 check_if_allowed_tag(c)
430 Some(Event::End(ref c)) => {
433 check_if_allowed_tag(c)
437 if is_allowed_tag == false {
439 Some(Event::Start(Tag::Paragraph))
441 Some(Event::End(Tag::Paragraph))
449 /// Moves all footnote definitions to the end and add back links to the
451 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
453 footnotes: FxHashMap<String, (Vec<Event<'a>>, u16)>,
456 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
457 fn new(iter: I) -> Self {
460 footnotes: FxHashMap::default(),
463 fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
464 let new_id = self.footnotes.keys().count() + 1;
465 let key = key.to_owned();
466 self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
470 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
471 type Item = Event<'a>;
473 fn next(&mut self) -> Option<Self::Item> {
475 match self.inner.next() {
476 Some(Event::FootnoteReference(ref reference)) => {
477 let entry = self.get_entry(&reference);
478 let reference = format!("<sup id=\"fnref{0}\"><a href=\"#fn{0}\">{0}\
481 return Some(Event::Html(reference.into()));
483 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
484 let mut content = Vec::new();
485 for event in &mut self.inner {
486 if let Event::End(Tag::FootnoteDefinition(..)) = event {
491 let entry = self.get_entry(&def);
492 (*entry).0 = content;
494 Some(e) => return Some(e),
496 if !self.footnotes.is_empty() {
497 let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
498 v.sort_by(|a, b| a.1.cmp(&b.1));
499 let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
500 for (mut content, id) in v {
501 write!(ret, "<li id=\"fn{}\">", id).unwrap();
502 let mut is_paragraph = false;
503 if let Some(&Event::End(Tag::Paragraph)) = content.last() {
507 html::push_html(&mut ret, content.into_iter());
509 " <a href=\"#fnref{}\" rev=\"footnote\">↩</a>",
512 ret.push_str("</p>");
514 ret.push_str("</li>");
516 ret.push_str("</ol></div>");
517 return Some(Event::Html(ret.into()));
527 pub struct TestableCodeError(());
529 impl fmt::Display for TestableCodeError {
530 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
531 write!(f, "invalid start of a new code block")
535 pub fn find_testable_code(
536 doc: &str, tests: &mut test::Collector, error_codes: ErrorCodes,
537 ) -> Result<(), TestableCodeError> {
538 let mut parser = Parser::new(doc);
539 let mut prev_offset = 0;
540 let mut nb_lines = 0;
541 let mut register_header = None;
542 'main: while let Some(event) = parser.next() {
544 Event::Start(Tag::CodeBlock(s)) => {
545 let block_info = if s.is_empty() {
546 LangString::all_false()
548 LangString::parse(&*s, error_codes)
550 if !block_info.rust {
553 let mut test_s = String::new();
554 let mut offset = None;
556 let event = parser.next();
557 if let Some(event) = event {
559 Event::End(Tag::CodeBlock(_)) => break,
560 Event::Text(ref s) => {
562 if offset.is_none() {
563 offset = Some(parser.get_offset());
572 if let Some(offset) = offset {
573 let lines = test_s.lines().map(|l| map_line(l).for_code());
574 let text = lines.collect::<Vec<Cow<str>>>().join("\n");
575 nb_lines += doc[prev_offset..offset].lines().count();
576 let line = tests.get_line() + (nb_lines - 1);
577 tests.add_test(text, block_info, line);
578 prev_offset = offset;
580 return Err(TestableCodeError(()));
583 Event::Start(Tag::Header(level)) => {
584 register_header = Some(level as u32);
586 Event::Text(ref s) if register_header.is_some() => {
587 let level = register_header.unwrap();
589 tests.register_header("", level);
591 tests.register_header(s, level);
593 register_header = None;
601 #[derive(Eq, PartialEq, Clone, Debug)]
602 pub struct LangString {
604 pub should_panic: bool,
608 pub test_harness: bool,
609 pub compile_fail: bool,
610 pub error_codes: Vec<String>,
611 pub allow_fail: bool,
612 pub edition: Option<Edition>
616 fn all_false() -> LangString {
618 original: String::new(),
622 rust: true, // NB This used to be `notrust = false`
625 error_codes: Vec::new(),
631 fn parse(string: &str, allow_error_code_check: ErrorCodes) -> LangString {
632 let allow_error_code_check = allow_error_code_check.as_bool();
633 let mut seen_rust_tags = false;
634 let mut seen_other_tags = false;
635 let mut data = LangString::all_false();
637 data.original = string.to_owned();
638 let tokens = string.split(|c: char|
639 !(c == '_' || c == '-' || c.is_alphanumeric())
642 for token in tokens {
646 data.should_panic = true;
647 seen_rust_tags = seen_other_tags == false;
649 "no_run" => { data.no_run = true; seen_rust_tags = !seen_other_tags; }
650 "ignore" => { data.ignore = true; seen_rust_tags = !seen_other_tags; }
651 "allow_fail" => { data.allow_fail = true; seen_rust_tags = !seen_other_tags; }
652 "rust" => { data.rust = true; seen_rust_tags = true; }
654 data.test_harness = true;
655 seen_rust_tags = !seen_other_tags || seen_rust_tags;
658 data.compile_fail = true;
659 seen_rust_tags = !seen_other_tags || seen_rust_tags;
662 x if allow_error_code_check && x.starts_with("edition") => {
663 // allow_error_code_check is true if we're on nightly, which
664 // is needed for edition support
665 data.edition = x[7..].parse::<Edition>().ok();
667 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
668 if x[1..].parse::<u32>().is_ok() {
669 data.error_codes.push(x.to_owned());
670 seen_rust_tags = !seen_other_tags || seen_rust_tags;
672 seen_other_tags = true;
675 _ => { seen_other_tags = true }
679 data.rust &= !seen_other_tags || seen_rust_tags;
685 impl<'a> fmt::Display for Markdown<'a> {
686 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
687 let Markdown(md, links, ref ids, codes) = *self;
688 let mut ids = ids.borrow_mut();
690 // This is actually common enough to special-case
691 if md.is_empty() { return Ok(()) }
692 let mut opts = Options::empty();
693 opts.insert(OPTION_ENABLE_TABLES);
694 opts.insert(OPTION_ENABLE_FOOTNOTES);
696 let replacer = |_: &str, s: &str| {
697 if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
698 Some((replace.clone(), s.to_owned()))
704 let p = Parser::new_with_broken_link_callback(md, opts, Some(&replacer));
706 let mut s = String::with_capacity(md.len() * 3 / 2);
708 let p = HeadingLinks::new(p, None, &mut ids);
709 let p = LinkReplacer::new(p, links);
710 let p = CodeBlocks::new(p, codes);
711 let p = Footnotes::new(p);
712 html::push_html(&mut s, p);
718 impl<'a> fmt::Display for MarkdownWithToc<'a> {
719 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
720 let MarkdownWithToc(md, ref ids, codes) = *self;
721 let mut ids = ids.borrow_mut();
723 let mut opts = Options::empty();
724 opts.insert(OPTION_ENABLE_TABLES);
725 opts.insert(OPTION_ENABLE_FOOTNOTES);
727 let p = Parser::new_ext(md, opts);
729 let mut s = String::with_capacity(md.len() * 3 / 2);
731 let mut toc = TocBuilder::new();
734 let p = HeadingLinks::new(p, Some(&mut toc), &mut ids);
735 let p = CodeBlocks::new(p, codes);
736 let p = Footnotes::new(p);
737 html::push_html(&mut s, p);
740 write!(fmt, "<nav id=\"TOC\">{}</nav>", toc.into_toc())?;
746 impl<'a> fmt::Display for MarkdownHtml<'a> {
747 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
748 let MarkdownHtml(md, ref ids, codes) = *self;
749 let mut ids = ids.borrow_mut();
751 // This is actually common enough to special-case
752 if md.is_empty() { return Ok(()) }
753 let mut opts = Options::empty();
754 opts.insert(OPTION_ENABLE_TABLES);
755 opts.insert(OPTION_ENABLE_FOOTNOTES);
757 let p = Parser::new_ext(md, opts);
759 // Treat inline HTML as plain text.
760 let p = p.map(|event| match event {
761 Event::Html(text) | Event::InlineHtml(text) => Event::Text(text),
765 let mut s = String::with_capacity(md.len() * 3 / 2);
767 let p = HeadingLinks::new(p, None, &mut ids);
768 let p = CodeBlocks::new(p, codes);
769 let p = Footnotes::new(p);
770 html::push_html(&mut s, p);
776 impl<'a> fmt::Display for MarkdownSummaryLine<'a> {
777 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
778 let MarkdownSummaryLine(md, links) = *self;
779 // This is actually common enough to special-case
780 if md.is_empty() { return Ok(()) }
782 let replacer = |_: &str, s: &str| {
783 if let Some(&(_, ref replace)) = links.into_iter().find(|link| &*link.0 == s) {
784 Some((replace.clone(), s.to_owned()))
790 let p = Parser::new_with_broken_link_callback(md, Options::empty(), Some(&replacer));
792 let mut s = String::new();
794 html::push_html(&mut s, LinkReplacer::new(SummaryLine::new(p), links));
800 pub fn plain_summary_line(md: &str) -> String {
801 struct ParserWrapper<'a> {
807 impl<'a> Iterator for ParserWrapper<'a> {
810 fn next(&mut self) -> Option<String> {
811 let next_event = self.inner.next();
812 if next_event.is_none() {
815 let next_event = next_event.unwrap();
816 let (ret, is_in) = match next_event {
817 Event::Start(Tag::Paragraph) => (None, 1),
818 Event::Start(Tag::Code) => (Some("`".to_owned()), 1),
819 Event::End(Tag::Code) => (Some("`".to_owned()), -1),
820 Event::Start(Tag::Header(_)) => (None, 1),
821 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
822 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
825 if is_in > 0 || (is_in < 0 && self.is_in > 0) {
829 self.is_first = false;
836 let mut s = String::with_capacity(md.len() * 3 / 2);
837 let mut p = ParserWrapper {
838 inner: Parser::new(md),
842 while let Some(t) = p.next() {
850 pub fn markdown_links(md: &str) -> Vec<(String, Option<Range<usize>>)> {
855 let mut opts = Options::empty();
856 opts.insert(OPTION_ENABLE_TABLES);
857 opts.insert(OPTION_ENABLE_FOOTNOTES);
859 let mut links = vec![];
860 let shortcut_links = RefCell::new(vec![]);
863 let locate = |s: &str| unsafe {
864 let s_start = s.as_ptr();
865 let s_end = s_start.add(s.len());
866 let md_start = md.as_ptr();
867 let md_end = md_start.add(md.len());
868 if md_start <= s_start && s_end <= md_end {
869 let start = s_start.offset_from(md_start) as usize;
870 let end = s_end.offset_from(md_start) as usize;
877 let push = |_: &str, s: &str| {
878 shortcut_links.borrow_mut().push((s.to_owned(), locate(s)));
881 let p = Parser::new_with_broken_link_callback(md, opts,
884 // There's no need to thread an IdMap through to here because
885 // the IDs generated aren't going to be emitted anywhere.
886 let mut ids = IdMap::new();
887 let iter = Footnotes::new(HeadingLinks::new(p, None, &mut ids));
890 if let Event::Start(Tag::Link(dest, _)) = ev {
891 debug!("found link: {}", dest);
892 links.push(match dest {
893 Cow::Borrowed(s) => (s.to_owned(), locate(s)),
894 Cow::Owned(s) => (s, None),
900 let mut shortcut_links = shortcut_links.into_inner();
901 links.extend(shortcut_links.drain(..));
908 map: FxHashMap<String, usize>,
912 pub fn new() -> Self {
916 pub fn populate<I: IntoIterator<Item=String>>(&mut self, ids: I) {
918 let _ = self.derive(id);
922 pub fn reset(&mut self) {
923 self.map = FxHashMap::default();
926 pub fn derive(&mut self, candidate: String) -> String {
927 let id = match self.map.get_mut(&candidate) {
930 let id = format!("{}-{}", candidate, *a);
936 self.map.insert(id.clone(), 1);
943 fn test_unique_id() {
944 let input = ["foo", "examples", "examples", "method.into_iter","examples",
945 "method.into_iter", "foo", "main", "search", "methods",
946 "examples", "method.into_iter", "assoc_type.Item", "assoc_type.Item"];
947 let expected = ["foo", "examples", "examples-1", "method.into_iter", "examples-2",
948 "method.into_iter-1", "foo-1", "main", "search", "methods",
949 "examples-3", "method.into_iter-2", "assoc_type.Item", "assoc_type.Item-1"];
951 let map = RefCell::new(IdMap::new());
953 let mut map = map.borrow_mut();
954 let actual: Vec<String> = input.iter().map(|s| map.derive(s.to_string())).collect();
955 assert_eq!(&actual[..], expected);
958 map.borrow_mut().reset();
964 use super::{ErrorCodes, LangString, Markdown, MarkdownHtml, IdMap};
965 use super::plain_summary_line;
966 use std::cell::RefCell;
967 use syntax::edition::Edition;
970 fn test_lang_string_parse() {
972 should_panic: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool,
973 compile_fail: bool, allow_fail: bool, error_codes: Vec<String>,
974 edition: Option<Edition>) {
975 assert_eq!(LangString::parse(s, ErrorCodes::Yes), LangString {
983 original: s.to_owned(),
989 fn v() -> Vec<String> {
993 // ignore-tidy-linelength
994 // marker | should_panic | no_run | ignore | rust | test_harness
995 // | compile_fail | allow_fail | error_codes | edition
996 t("", false, false, false, true, false, false, false, v(), None);
997 t("rust", false, false, false, true, false, false, false, v(), None);
998 t("sh", false, false, false, false, false, false, false, v(), None);
999 t("ignore", false, false, true, true, false, false, false, v(), None);
1000 t("should_panic", true, false, false, true, false, false, false, v(), None);
1001 t("no_run", false, true, false, true, false, false, false, v(), None);
1002 t("test_harness", false, false, false, true, true, false, false, v(), None);
1003 t("compile_fail", false, true, false, true, false, true, false, v(), None);
1004 t("allow_fail", false, false, false, true, false, false, true, v(), None);
1005 t("{.no_run .example}", false, true, false, true, false, false, false, v(), None);
1006 t("{.sh .should_panic}", true, false, false, false, false, false, false, v(), None);
1007 t("{.example .rust}", false, false, false, true, false, false, false, v(), None);
1008 t("{.test_harness .rust}", false, false, false, true, true, false, false, v(), None);
1009 t("text, no_run", false, true, false, false, false, false, false, v(), None);
1010 t("text,no_run", false, true, false, false, false, false, false, v(), None);
1011 t("edition2015", false, false, false, true, false, false, false, v(), Some(Edition::Edition2015));
1012 t("edition2018", false, false, false, true, false, false, false, v(), Some(Edition::Edition2018));
1017 fn t(input: &str, expect: &str) {
1018 let mut map = IdMap::new();
1019 let output = Markdown(input, &[], RefCell::new(&mut map), ErrorCodes::Yes).to_string();
1020 assert_eq!(output, expect, "original: {}", input);
1023 t("# Foo bar", "<h1 id=\"foo-bar\" class=\"section-header\">\
1024 <a href=\"#foo-bar\">Foo bar</a></h1>");
1025 t("## Foo-bar_baz qux", "<h2 id=\"foo-bar_baz-qux\" class=\"section-\
1026 header\"><a href=\"#foo-bar_baz-qux\">Foo-bar_baz qux</a></h2>");
1027 t("### **Foo** *bar* baz!?!& -_qux_-%",
1028 "<h3 id=\"foo-bar-baz--qux-\" class=\"section-header\">\
1029 <a href=\"#foo-bar-baz--qux-\"><strong>Foo</strong> \
1030 <em>bar</em> baz!?!& -<em>qux</em>-%</a></h3>");
1031 t("#### **Foo?** & \\*bar?!* _`baz`_ ❤ #qux",
1032 "<h4 id=\"foo--bar--baz--qux\" class=\"section-header\">\
1033 <a href=\"#foo--bar--baz--qux\"><strong>Foo?</strong> & *bar?!* \
1034 <em><code>baz</code></em> ❤ #qux</a></h4>");
1038 fn test_header_ids_multiple_blocks() {
1039 let mut map = IdMap::new();
1040 fn t(map: &mut IdMap, input: &str, expect: &str) {
1041 let output = Markdown(input, &[], RefCell::new(map), ErrorCodes::Yes).to_string();
1042 assert_eq!(output, expect, "original: {}", input);
1045 t(&mut map, "# Example", "<h1 id=\"example\" class=\"section-header\">\
1046 <a href=\"#example\">Example</a></h1>");
1047 t(&mut map, "# Panics", "<h1 id=\"panics\" class=\"section-header\">\
1048 <a href=\"#panics\">Panics</a></h1>");
1049 t(&mut map, "# Example", "<h1 id=\"example-1\" class=\"section-header\">\
1050 <a href=\"#example-1\">Example</a></h1>");
1051 t(&mut map, "# Main", "<h1 id=\"main\" class=\"section-header\">\
1052 <a href=\"#main\">Main</a></h1>");
1053 t(&mut map, "# Example", "<h1 id=\"example-2\" class=\"section-header\">\
1054 <a href=\"#example-2\">Example</a></h1>");
1055 t(&mut map, "# Panics", "<h1 id=\"panics-1\" class=\"section-header\">\
1056 <a href=\"#panics-1\">Panics</a></h1>");
1060 fn test_plain_summary_line() {
1061 fn t(input: &str, expect: &str) {
1062 let output = plain_summary_line(input);
1063 assert_eq!(output, expect, "original: {}", input);
1066 t("hello [Rust](https://www.rust-lang.org) :)", "hello Rust :)");
1067 t("hello [Rust](https://www.rust-lang.org \"Rust\") :)", "hello Rust :)");
1068 t("code `let x = i32;` ...", "code `let x = i32;` ...");
1069 t("type `Type<'static>` ...", "type `Type<'static>` ...");
1070 t("# top header", "top header");
1071 t("## header", "header");
1075 fn test_markdown_html_escape() {
1076 fn t(input: &str, expect: &str) {
1077 let mut idmap = IdMap::new();
1078 let output = MarkdownHtml(input, RefCell::new(&mut idmap), ErrorCodes::Yes).to_string();
1079 assert_eq!(output, expect, "original: {}", input);
1082 t("`Struct<'a, T>`", "<p><code>Struct<'a, T></code></p>\n");
1083 t("Struct<'a, T>", "<p>Struct<'a, T></p>\n");
1084 t("Struct<br>", "<p>Struct<br></p>\n");