]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
Rollup merge of #44562 - eddyb:ugh-rustdoc, r=nikomatsakis
[rust.git] / src / librustdoc / html / markdown.rs
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.
4 //
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.
10
11 //! Markdown formatting for rustdoc
12 //!
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:
17 //!
18 //! ```
19 //! #![feature(rustc_private)]
20 //!
21 //! use rustdoc::html::markdown::{RenderType, Markdown};
22 //!
23 //! let s = "My *markdown* _text_";
24 //! let html = format!("{}", Markdown(s, RenderType::Pulldown));
25 //! // ... something using html
26 //! ```
27
28 #![allow(non_camel_case_types)]
29
30 use libc;
31 use std::slice;
32
33 use std::ascii::AsciiExt;
34 use std::cell::RefCell;
35 use std::collections::{HashMap, VecDeque};
36 use std::default::Default;
37 use std::fmt::{self, Write};
38 use std::str;
39 use syntax::feature_gate::UnstableFeatures;
40 use syntax::codemap::Span;
41
42 use html::render::derive_id;
43 use html::toc::TocBuilder;
44 use html::highlight;
45 use html::escape::Escape;
46 use test;
47
48 use pulldown_cmark::{html, Event, Tag, Parser};
49 use pulldown_cmark::{Options, OPTION_ENABLE_FOOTNOTES, OPTION_ENABLE_TABLES};
50
51 #[derive(PartialEq, Debug, Clone, Copy)]
52 pub enum RenderType {
53     Hoedown,
54     Pulldown,
55 }
56
57 /// A unit struct which has the `fmt::Display` trait implemented. When
58 /// formatted, this struct will emit the HTML corresponding to the rendered
59 /// version of the contained markdown string.
60 // The second parameter is whether we need a shorter version or not.
61 pub struct Markdown<'a>(pub &'a str, pub RenderType);
62 /// A unit struct like `Markdown`, that renders the markdown with a
63 /// table of contents.
64 pub struct MarkdownWithToc<'a>(pub &'a str, pub RenderType);
65 /// A unit struct like `Markdown`, that renders the markdown escaping HTML tags.
66 pub struct MarkdownHtml<'a>(pub &'a str, pub RenderType);
67 /// A unit struct like `Markdown`, that renders only the first paragraph.
68 pub struct MarkdownSummaryLine<'a>(pub &'a str);
69
70 /// Controls whether a line will be hidden or shown in HTML output.
71 ///
72 /// All lines are used in documentation tests.
73 enum Line<'a> {
74     Hidden(&'a str),
75     Shown(&'a str),
76 }
77
78 impl<'a> Line<'a> {
79     fn for_html(self) -> Option<&'a str> {
80         match self {
81             Line::Shown(l) => Some(l),
82             Line::Hidden(_) => None,
83         }
84     }
85
86     fn for_code(self) -> &'a str {
87         match self {
88             Line::Shown(l) |
89             Line::Hidden(l) => l,
90         }
91     }
92 }
93
94 // FIXME: There is a minor inconsistency here. For lines that start with ##, we
95 // have no easy way of removing a potential single space after the hashes, which
96 // is done in the single # case. This inconsistency seems okay, if non-ideal. In
97 // order to fix it we'd have to iterate to find the first non-# character, and
98 // then reallocate to remove it; which would make us return a String.
99 fn map_line(s: &str) -> Line {
100     let trimmed = s.trim();
101     if trimmed.starts_with("##") {
102         Line::Shown(&trimmed[1..])
103     } else if trimmed.starts_with("# ") {
104         // # text
105         Line::Hidden(&trimmed[2..])
106     } else if trimmed == "#" {
107         // We cannot handle '#text' because it could be #[attr].
108         Line::Hidden("")
109     } else {
110         Line::Shown(s)
111     }
112 }
113
114 /// Returns a new string with all consecutive whitespace collapsed into
115 /// single spaces.
116 ///
117 /// Any leading or trailing whitespace will be trimmed.
118 fn collapse_whitespace(s: &str) -> String {
119     s.split_whitespace().collect::<Vec<_>>().join(" ")
120 }
121
122 /// Convert chars from a title for an id.
123 ///
124 /// "Hello, world!" -> "hello-world"
125 fn slugify(c: char) -> Option<char> {
126     if c.is_alphanumeric() || c == '-' || c == '_' {
127         if c.is_ascii() {
128             Some(c.to_ascii_lowercase())
129         } else {
130             Some(c)
131         }
132     } else if c.is_whitespace() && c.is_ascii() {
133         Some('-')
134     } else {
135         None
136     }
137 }
138
139 // Information about the playground if a URL has been specified, containing an
140 // optional crate name and the URL.
141 thread_local!(pub static PLAYGROUND: RefCell<Option<(Option<String>, String)>> = {
142     RefCell::new(None)
143 });
144
145 /// Adds syntax highlighting and playground Run buttons to rust code blocks.
146 struct CodeBlocks<'a, I: Iterator<Item = Event<'a>>> {
147     inner: I,
148 }
149
150 impl<'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'a, I> {
151     fn new(iter: I) -> Self {
152         CodeBlocks {
153             inner: iter,
154         }
155     }
156 }
157
158 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
159     type Item = Event<'a>;
160
161     fn next(&mut self) -> Option<Self::Item> {
162         let event = self.inner.next();
163         let compile_fail;
164         let ignore;
165         if let Some(Event::Start(Tag::CodeBlock(lang))) = event {
166             let parse_result = LangString::parse(&lang);
167             if !parse_result.rust {
168                 return Some(Event::Start(Tag::CodeBlock(lang)));
169             }
170             compile_fail = parse_result.compile_fail;
171             ignore = parse_result.ignore;
172         } else {
173             return event;
174         }
175
176         let mut origtext = String::new();
177         for event in &mut self.inner {
178             match event {
179                 Event::End(Tag::CodeBlock(..)) => break,
180                 Event::Text(ref s) => {
181                     origtext.push_str(s);
182                 }
183                 _ => {}
184             }
185         }
186         let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
187         let text = lines.collect::<Vec<&str>>().join("\n");
188         PLAYGROUND.with(|play| {
189             // insert newline to clearly separate it from the
190             // previous block so we can shorten the html output
191             let mut s = String::from("\n");
192             let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
193                 if url.is_empty() {
194                     return None;
195                 }
196                 let test = origtext.lines()
197                     .map(|l| map_line(l).for_code())
198                     .collect::<Vec<&str>>().join("\n");
199                 let krate = krate.as_ref().map(|s| &**s);
200                 let test = test::make_test(&test, krate, false,
201                                            &Default::default());
202                 let channel = if test.contains("#![feature(") {
203                     "&amp;version=nightly"
204                 } else {
205                     ""
206                 };
207                 // These characters don't need to be escaped in a URI.
208                 // FIXME: use a library function for percent encoding.
209                 fn dont_escape(c: u8) -> bool {
210                     (b'a' <= c && c <= b'z') ||
211                     (b'A' <= c && c <= b'Z') ||
212                     (b'0' <= c && c <= b'9') ||
213                     c == b'-' || c == b'_' || c == b'.' ||
214                     c == b'~' || c == b'!' || c == b'\'' ||
215                     c == b'(' || c == b')' || c == b'*'
216                 }
217                 let mut test_escaped = String::new();
218                 for b in test.bytes() {
219                     if dont_escape(b) {
220                         test_escaped.push(char::from(b));
221                     } else {
222                         write!(test_escaped, "%{:02X}", b).unwrap();
223                     }
224                 }
225                 Some(format!(
226                     r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
227                     url, test_escaped, channel
228                 ))
229             });
230             let tooltip = if ignore {
231                 Some(("Be careful when using this code, it's not being tested!", "ignore"))
232             } else if compile_fail {
233                 Some(("This code doesn't compile so be extra careful!", "compile_fail"))
234             } else {
235                 None
236             };
237             s.push_str(&highlight::render_with_highlighting(
238                         &text,
239                         Some(&format!("rust-example-rendered{}",
240                                       if ignore { " ignore" }
241                                       else if compile_fail { " compile_fail" }
242                                       else { "" })),
243                         None,
244                         playground_button.as_ref().map(String::as_str),
245                         tooltip));
246             Some(Event::Html(s.into()))
247         })
248     }
249 }
250
251 /// Make headings links with anchor ids and build up TOC.
252 struct HeadingLinks<'a, 'b, I: Iterator<Item = Event<'a>>> {
253     inner: I,
254     toc: Option<&'b mut TocBuilder>,
255     buf: VecDeque<Event<'a>>,
256 }
257
258 impl<'a, 'b, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, I> {
259     fn new(iter: I, toc: Option<&'b mut TocBuilder>) -> Self {
260         HeadingLinks {
261             inner: iter,
262             toc,
263             buf: VecDeque::new(),
264         }
265     }
266 }
267
268 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, I> {
269     type Item = Event<'a>;
270
271     fn next(&mut self) -> Option<Self::Item> {
272         if let Some(e) = self.buf.pop_front() {
273             return Some(e);
274         }
275
276         let event = self.inner.next();
277         if let Some(Event::Start(Tag::Header(level))) = event {
278             let mut id = String::new();
279             for event in &mut self.inner {
280                 match event {
281                     Event::End(Tag::Header(..)) => break,
282                     Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
283                     _ => {},
284                 }
285                 self.buf.push_back(event);
286             }
287             let id = derive_id(id);
288
289             if let Some(ref mut builder) = self.toc {
290                 let mut html_header = String::new();
291                 html::push_html(&mut html_header, self.buf.iter().cloned());
292                 let sec = builder.push(level as u32, html_header, id.clone());
293                 self.buf.push_front(Event::InlineHtml(format!("{} ", sec).into()));
294             }
295
296             self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
297
298             let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
299                                       <a href=\"#{id}\">",
300                                      id = id,
301                                      level = level);
302             return Some(Event::InlineHtml(start_tags.into()));
303         }
304         event
305     }
306 }
307
308 /// Extracts just the first paragraph.
309 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
310     inner: I,
311     started: bool,
312     depth: u32,
313 }
314
315 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
316     fn new(iter: I) -> Self {
317         SummaryLine {
318             inner: iter,
319             started: false,
320             depth: 0,
321         }
322     }
323 }
324
325 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
326     type Item = Event<'a>;
327
328     fn next(&mut self) -> Option<Self::Item> {
329         if self.started && self.depth == 0 {
330             return None;
331         }
332         if !self.started {
333             self.started = true;
334         }
335         let event = self.inner.next();
336         match event {
337             Some(Event::Start(..)) => self.depth += 1,
338             Some(Event::End(..)) => self.depth -= 1,
339             _ => {}
340         }
341         event
342     }
343 }
344
345 /// Moves all footnote definitions to the end and add back links to the
346 /// references.
347 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
348     inner: I,
349     footnotes: HashMap<String, (Vec<Event<'a>>, u16)>,
350 }
351
352 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
353     fn new(iter: I) -> Self {
354         Footnotes {
355             inner: iter,
356             footnotes: HashMap::new(),
357         }
358     }
359     fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
360         let new_id = self.footnotes.keys().count() + 1;
361         let key = key.to_owned();
362         self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
363     }
364 }
365
366 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
367     type Item = Event<'a>;
368
369     fn next(&mut self) -> Option<Self::Item> {
370         loop {
371             match self.inner.next() {
372                 Some(Event::FootnoteReference(ref reference)) => {
373                     let entry = self.get_entry(&reference);
374                     let reference = format!("<sup id=\"supref{0}\"><a href=\"#ref{0}\">{0}\
375                                              </a></sup>",
376                                             (*entry).1);
377                     return Some(Event::Html(reference.into()));
378                 }
379                 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
380                     let mut content = Vec::new();
381                     for event in &mut self.inner {
382                         if let Event::End(Tag::FootnoteDefinition(..)) = event {
383                             break;
384                         }
385                         content.push(event);
386                     }
387                     let entry = self.get_entry(&def);
388                     (*entry).0 = content;
389                 }
390                 Some(e) => return Some(e),
391                 None => {
392                     if !self.footnotes.is_empty() {
393                         let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
394                         v.sort_by(|a, b| a.1.cmp(&b.1));
395                         let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
396                         for (mut content, id) in v {
397                             write!(ret, "<li id=\"ref{}\">", id).unwrap();
398                             let mut is_paragraph = false;
399                             if let Some(&Event::End(Tag::Paragraph)) = content.last() {
400                                 content.pop();
401                                 is_paragraph = true;
402                             }
403                             html::push_html(&mut ret, content.into_iter());
404                             write!(ret,
405                                    "&nbsp;<a href=\"#supref{}\" rev=\"footnote\">↩</a>",
406                                    id).unwrap();
407                             if is_paragraph {
408                                 ret.push_str("</p>");
409                             }
410                             ret.push_str("</li>");
411                         }
412                         ret.push_str("</ol></div>");
413                         return Some(Event::Html(ret.into()));
414                     } else {
415                         return None;
416                     }
417                 }
418             }
419         }
420     }
421 }
422
423 const DEF_OUNIT: libc::size_t = 64;
424 const HOEDOWN_EXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 11;
425 const HOEDOWN_EXT_TABLES: libc::c_uint = 1 << 0;
426 const HOEDOWN_EXT_FENCED_CODE: libc::c_uint = 1 << 1;
427 const HOEDOWN_EXT_AUTOLINK: libc::c_uint = 1 << 3;
428 const HOEDOWN_EXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
429 const HOEDOWN_EXT_SUPERSCRIPT: libc::c_uint = 1 << 8;
430 const HOEDOWN_EXT_FOOTNOTES: libc::c_uint = 1 << 2;
431 const HOEDOWN_HTML_ESCAPE: libc::c_uint = 1 << 1;
432
433 const HOEDOWN_EXTENSIONS: libc::c_uint =
434     HOEDOWN_EXT_NO_INTRA_EMPHASIS | HOEDOWN_EXT_TABLES |
435     HOEDOWN_EXT_FENCED_CODE | HOEDOWN_EXT_AUTOLINK |
436     HOEDOWN_EXT_STRIKETHROUGH | HOEDOWN_EXT_SUPERSCRIPT |
437     HOEDOWN_EXT_FOOTNOTES;
438
439 enum hoedown_document {}
440
441 type blockcodefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
442                                  *const hoedown_buffer, *const hoedown_renderer_data,
443                                  libc::size_t);
444
445 type blockquotefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
446                                   *const hoedown_renderer_data, libc::size_t);
447
448 type headerfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
449                               libc::c_int, *const hoedown_renderer_data,
450                               libc::size_t);
451
452 type blockhtmlfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
453                                  *const hoedown_renderer_data, libc::size_t);
454
455 type codespanfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
456                                 *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
457
458 type linkfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
459                              *const hoedown_buffer, *const hoedown_buffer,
460                              *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
461
462 type entityfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
463                                *const hoedown_renderer_data, libc::size_t);
464
465 type normaltextfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
466                                   *const hoedown_renderer_data, libc::size_t);
467
468 #[repr(C)]
469 struct hoedown_renderer_data {
470     opaque: *mut libc::c_void,
471 }
472
473 #[repr(C)]
474 struct hoedown_renderer {
475     opaque: *mut libc::c_void,
476
477     blockcode: Option<blockcodefn>,
478     blockquote: Option<blockquotefn>,
479     header: Option<headerfn>,
480
481     other_block_level_callbacks: [libc::size_t; 11],
482
483     blockhtml: Option<blockhtmlfn>,
484
485     /* span level callbacks - NULL or return 0 prints the span verbatim */
486     autolink: libc::size_t, // unused
487     codespan: Option<codespanfn>,
488     other_span_level_callbacks_1: [libc::size_t; 7],
489     link: Option<linkfn>,
490     other_span_level_callbacks_2: [libc::size_t; 6],
491
492     /* low level callbacks - NULL copies input directly into the output */
493     entity: Option<entityfn>,
494     normal_text: Option<normaltextfn>,
495
496     /* header and footer */
497     other_callbacks: [libc::size_t; 2],
498 }
499
500 #[repr(C)]
501 struct hoedown_html_renderer_state {
502     opaque: *mut libc::c_void,
503     toc_data: html_toc_data,
504     flags: libc::c_uint,
505     link_attributes: Option<extern "C" fn(*mut hoedown_buffer,
506                                           *const hoedown_buffer,
507                                           *const hoedown_renderer_data)>,
508 }
509
510 #[repr(C)]
511 struct html_toc_data {
512     header_count: libc::c_int,
513     current_level: libc::c_int,
514     level_offset: libc::c_int,
515     nesting_level: libc::c_int,
516 }
517
518 #[repr(C)]
519 struct hoedown_buffer {
520     data: *const u8,
521     size: libc::size_t,
522     asize: libc::size_t,
523     unit: libc::size_t,
524 }
525
526 struct MyOpaque {
527     dfltblk: extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
528                            *const hoedown_buffer, *const hoedown_renderer_data,
529                            libc::size_t),
530     toc_builder: Option<TocBuilder>,
531 }
532
533 extern {
534     fn hoedown_html_renderer_new(render_flags: libc::c_uint,
535                                  nesting_level: libc::c_int)
536         -> *mut hoedown_renderer;
537     fn hoedown_html_renderer_free(renderer: *mut hoedown_renderer);
538
539     fn hoedown_document_new(rndr: *const hoedown_renderer,
540                             extensions: libc::c_uint,
541                             max_nesting: libc::size_t) -> *mut hoedown_document;
542     fn hoedown_document_render(doc: *mut hoedown_document,
543                                ob: *mut hoedown_buffer,
544                                document: *const u8,
545                                doc_size: libc::size_t);
546     fn hoedown_document_free(md: *mut hoedown_document);
547
548     fn hoedown_buffer_new(unit: libc::size_t) -> *mut hoedown_buffer;
549     fn hoedown_buffer_free(b: *mut hoedown_buffer);
550     fn hoedown_buffer_put(b: *mut hoedown_buffer, c: *const u8, len: libc::size_t);
551 }
552
553 impl hoedown_buffer {
554     fn as_bytes(&self) -> &[u8] {
555         unsafe { slice::from_raw_parts(self.data, self.size as usize) }
556     }
557 }
558
559 pub fn render(w: &mut fmt::Formatter,
560               s: &str,
561               print_toc: bool,
562               html_flags: libc::c_uint) -> fmt::Result {
563     extern fn block(ob: *mut hoedown_buffer, orig_text: *const hoedown_buffer,
564                     lang: *const hoedown_buffer, data: *const hoedown_renderer_data,
565                     line: libc::size_t) {
566         unsafe {
567             if orig_text.is_null() { return }
568
569             let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
570             let my_opaque: &MyOpaque = &*((*opaque).opaque as *const MyOpaque);
571             let text = (*orig_text).as_bytes();
572             let origtext = str::from_utf8(text).unwrap();
573             let origtext = origtext.trim_left();
574             debug!("docblock: ==============\n{:?}\n=======", text);
575             let mut compile_fail = false;
576             let mut ignore = false;
577
578             let rendered = if lang.is_null() || origtext.is_empty() {
579                 false
580             } else {
581                 let rlang = (*lang).as_bytes();
582                 let rlang = str::from_utf8(rlang).unwrap();
583                 let parse_result = LangString::parse(rlang);
584                 compile_fail = parse_result.compile_fail;
585                 ignore = parse_result.ignore;
586                 if !parse_result.rust {
587                     (my_opaque.dfltblk)(ob, orig_text, lang,
588                                         opaque as *const hoedown_renderer_data,
589                                         line);
590                     true
591                 } else {
592                     false
593                 }
594             };
595
596             let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
597             let text = lines.collect::<Vec<&str>>().join("\n");
598             if rendered { return }
599             PLAYGROUND.with(|play| {
600                 // insert newline to clearly separate it from the
601                 // previous block so we can shorten the html output
602                 let mut s = String::from("\n");
603                 let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
604                     if url.is_empty() {
605                         return None;
606                     }
607                     let test = origtext.lines()
608                         .map(|l| map_line(l).for_code())
609                         .collect::<Vec<&str>>().join("\n");
610                     let krate = krate.as_ref().map(|s| &**s);
611                     let test = test::make_test(&test, krate, false,
612                                                &Default::default());
613                     let channel = if test.contains("#![feature(") {
614                         "&amp;version=nightly"
615                     } else {
616                         ""
617                     };
618                     // These characters don't need to be escaped in a URI.
619                     // FIXME: use a library function for percent encoding.
620                     fn dont_escape(c: u8) -> bool {
621                         (b'a' <= c && c <= b'z') ||
622                         (b'A' <= c && c <= b'Z') ||
623                         (b'0' <= c && c <= b'9') ||
624                         c == b'-' || c == b'_' || c == b'.' ||
625                         c == b'~' || c == b'!' || c == b'\'' ||
626                         c == b'(' || c == b')' || c == b'*'
627                     }
628                     let mut test_escaped = String::new();
629                     for b in test.bytes() {
630                         if dont_escape(b) {
631                             test_escaped.push(char::from(b));
632                         } else {
633                             write!(test_escaped, "%{:02X}", b).unwrap();
634                         }
635                     }
636                     Some(format!(
637                         r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
638                         url, test_escaped, channel
639                     ))
640                 });
641                 let tooltip = if ignore {
642                     Some(("Be careful when using this code, it's not being tested!", "ignore"))
643                 } else if compile_fail {
644                     Some(("This code doesn't compile so be extra careful!", "compile_fail"))
645                 } else {
646                     None
647                 };
648                 s.push_str(&highlight::render_with_highlighting(
649                                &text,
650                                Some(&format!("rust-example-rendered{}",
651                                              if ignore { " ignore" }
652                                              else if compile_fail { " compile_fail" }
653                                              else { "" })),
654                                None,
655                                playground_button.as_ref().map(String::as_str),
656                                tooltip));
657                 hoedown_buffer_put(ob, s.as_ptr(), s.len());
658             })
659         }
660     }
661
662     extern fn header(ob: *mut hoedown_buffer, text: *const hoedown_buffer,
663                      level: libc::c_int, data: *const hoedown_renderer_data,
664                      _: libc::size_t) {
665         // hoedown does this, we may as well too
666         unsafe { hoedown_buffer_put(ob, "\n".as_ptr(), 1); }
667
668         // Extract the text provided
669         let s = if text.is_null() {
670             "".to_owned()
671         } else {
672             let s = unsafe { (*text).as_bytes() };
673             str::from_utf8(&s).unwrap().to_owned()
674         };
675
676         // Discard '<em>', '<code>' tags and some escaped characters,
677         // transform the contents of the header into a hyphenated string
678         // without non-alphanumeric characters other than '-' and '_'.
679         //
680         // This is a terrible hack working around how hoedown gives us rendered
681         // html for text rather than the raw text.
682         let mut id = s.clone();
683         let repl_sub = vec!["<em>", "</em>", "<code>", "</code>",
684                             "<strong>", "</strong>",
685                             "&lt;", "&gt;", "&amp;", "&#39;", "&quot;"];
686         for sub in repl_sub {
687             id = id.replace(sub, "");
688         }
689         let id = id.chars().filter_map(|c| {
690             if c.is_alphanumeric() || c == '-' || c == '_' {
691                 if c.is_ascii() {
692                     Some(c.to_ascii_lowercase())
693                 } else {
694                     Some(c)
695                 }
696             } else if c.is_whitespace() && c.is_ascii() {
697                 Some('-')
698             } else {
699                 None
700             }
701         }).collect::<String>();
702
703         let opaque = unsafe { (*data).opaque as *mut hoedown_html_renderer_state };
704         let opaque = unsafe { &mut *((*opaque).opaque as *mut MyOpaque) };
705
706         let id = derive_id(id);
707
708         let sec = opaque.toc_builder.as_mut().map_or("".to_owned(), |builder| {
709             format!("{} ", builder.push(level as u32, s.clone(), id.clone()))
710         });
711
712         // Render the HTML
713         let text = format!("<h{lvl} id='{id}' class='section-header'>\
714                            <a href='#{id}'>{sec}{}</a></h{lvl}>",
715                            s, lvl = level, id = id, sec = sec);
716
717         unsafe { hoedown_buffer_put(ob, text.as_ptr(), text.len()); }
718     }
719
720     extern fn codespan(
721         ob: *mut hoedown_buffer,
722         text: *const hoedown_buffer,
723         _: *const hoedown_renderer_data,
724         _: libc::size_t
725     ) -> libc::c_int {
726         let content = if text.is_null() {
727             "".to_owned()
728         } else {
729             let bytes = unsafe { (*text).as_bytes() };
730             let s = str::from_utf8(bytes).unwrap();
731             collapse_whitespace(s)
732         };
733
734         let content = format!("<code>{}</code>", Escape(&content));
735         unsafe {
736             hoedown_buffer_put(ob, content.as_ptr(), content.len());
737         }
738         // Return anything except 0, which would mean "also print the code span verbatim".
739         1
740     }
741
742     unsafe {
743         let ob = hoedown_buffer_new(DEF_OUNIT);
744         let renderer = hoedown_html_renderer_new(html_flags, 0);
745         let mut opaque = MyOpaque {
746             dfltblk: (*renderer).blockcode.unwrap(),
747             toc_builder: if print_toc {Some(TocBuilder::new())} else {None}
748         };
749         (*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
750                 = &mut opaque as *mut _ as *mut libc::c_void;
751         (*renderer).blockcode = Some(block);
752         (*renderer).header = Some(header);
753         (*renderer).codespan = Some(codespan);
754
755         let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
756         hoedown_document_render(document, ob, s.as_ptr(),
757                                 s.len() as libc::size_t);
758         hoedown_document_free(document);
759
760         hoedown_html_renderer_free(renderer);
761
762         let mut ret = opaque.toc_builder.map_or(Ok(()), |builder| {
763             write!(w, "<nav id=\"TOC\">{}</nav>", builder.into_toc())
764         });
765
766         if ret.is_ok() {
767             let buf = (*ob).as_bytes();
768             ret = w.write_str(str::from_utf8(buf).unwrap());
769         }
770         hoedown_buffer_free(ob);
771         ret
772     }
773 }
774
775 pub fn old_find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
776     extern fn block(_ob: *mut hoedown_buffer,
777                     text: *const hoedown_buffer,
778                     lang: *const hoedown_buffer,
779                     data: *const hoedown_renderer_data,
780                     line: libc::size_t) {
781         unsafe {
782             if text.is_null() { return }
783             let block_info = if lang.is_null() {
784                 LangString::all_false()
785             } else {
786                 let lang = (*lang).as_bytes();
787                 let s = str::from_utf8(lang).unwrap();
788                 LangString::parse(s)
789             };
790             if !block_info.rust { return }
791             let text = (*text).as_bytes();
792             let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
793             let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
794             let text = str::from_utf8(text).unwrap();
795             let lines = text.lines().map(|l| map_line(l).for_code());
796             let text = lines.collect::<Vec<&str>>().join("\n");
797             let filename = tests.get_filename();
798
799             if tests.render_type == RenderType::Hoedown {
800                 let line = tests.get_line() + line;
801                 tests.add_test(text.to_owned(),
802                                block_info.should_panic, block_info.no_run,
803                                block_info.ignore, block_info.test_harness,
804                                block_info.compile_fail, block_info.error_codes,
805                                line, filename, block_info.allow_fail);
806             } else {
807                 tests.add_old_test(text, filename);
808             }
809         }
810     }
811
812     extern fn header(_ob: *mut hoedown_buffer,
813                      text: *const hoedown_buffer,
814                      level: libc::c_int, data: *const hoedown_renderer_data,
815                      _: libc::size_t) {
816         unsafe {
817             let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
818             let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
819             if text.is_null() {
820                 tests.register_header("", level as u32);
821             } else {
822                 let text = (*text).as_bytes();
823                 let text = str::from_utf8(text).unwrap();
824                 tests.register_header(text, level as u32);
825             }
826         }
827     }
828
829     tests.set_position(position);
830     unsafe {
831         let ob = hoedown_buffer_new(DEF_OUNIT);
832         let renderer = hoedown_html_renderer_new(0, 0);
833         (*renderer).blockcode = Some(block);
834         (*renderer).header = Some(header);
835         (*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
836                 = tests as *mut _ as *mut libc::c_void;
837
838         let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
839         hoedown_document_render(document, ob, doc.as_ptr(),
840                                 doc.len() as libc::size_t);
841         hoedown_document_free(document);
842
843         hoedown_html_renderer_free(renderer);
844         hoedown_buffer_free(ob);
845     }
846 }
847
848 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
849     tests.set_position(position);
850
851     let mut parser = Parser::new(doc);
852     let mut prev_offset = 0;
853     let mut nb_lines = 0;
854     let mut register_header = None;
855     'main: while let Some(event) = parser.next() {
856         match event {
857             Event::Start(Tag::CodeBlock(s)) => {
858                 let block_info = if s.is_empty() {
859                     LangString::all_false()
860                 } else {
861                     LangString::parse(&*s)
862                 };
863                 if !block_info.rust {
864                     continue
865                 }
866                 let mut test_s = String::new();
867                 let mut offset = None;
868                 loop {
869                     let event = parser.next();
870                     if let Some(event) = event {
871                         match event {
872                             Event::End(Tag::CodeBlock(_)) => break,
873                             Event::Text(ref s) => {
874                                 test_s.push_str(s);
875                                 if offset.is_none() {
876                                     offset = Some(parser.get_offset());
877                                 }
878                             }
879                             _ => {}
880                         }
881                     } else {
882                         break 'main;
883                     }
884                 }
885                 let offset = offset.unwrap_or(0);
886                 let lines = test_s.lines().map(|l| map_line(l).for_code());
887                 let text = lines.collect::<Vec<&str>>().join("\n");
888                 nb_lines += doc[prev_offset..offset].lines().count();
889                 let line = tests.get_line() + (nb_lines - 1);
890                 let filename = tests.get_filename();
891                 tests.add_test(text.to_owned(),
892                                block_info.should_panic, block_info.no_run,
893                                block_info.ignore, block_info.test_harness,
894                                block_info.compile_fail, block_info.error_codes,
895                                line, filename, block_info.allow_fail);
896                 prev_offset = offset;
897             }
898             Event::Start(Tag::Header(level)) => {
899                 register_header = Some(level as u32);
900             }
901             Event::Text(ref s) if register_header.is_some() => {
902                 let level = register_header.unwrap();
903                 if s.is_empty() {
904                     tests.register_header("", level);
905                 } else {
906                     tests.register_header(s, level);
907                 }
908                 register_header = None;
909             }
910             _ => {}
911         }
912     }
913 }
914
915 #[derive(Eq, PartialEq, Clone, Debug)]
916 struct LangString {
917     original: String,
918     should_panic: bool,
919     no_run: bool,
920     ignore: bool,
921     rust: bool,
922     test_harness: bool,
923     compile_fail: bool,
924     error_codes: Vec<String>,
925     allow_fail: bool,
926 }
927
928 impl LangString {
929     fn all_false() -> LangString {
930         LangString {
931             original: String::new(),
932             should_panic: false,
933             no_run: false,
934             ignore: false,
935             rust: true,  // NB This used to be `notrust = false`
936             test_harness: false,
937             compile_fail: false,
938             error_codes: Vec::new(),
939             allow_fail: false,
940         }
941     }
942
943     fn parse(string: &str) -> LangString {
944         let mut seen_rust_tags = false;
945         let mut seen_other_tags = false;
946         let mut data = LangString::all_false();
947         let mut allow_error_code_check = false;
948         if UnstableFeatures::from_environment().is_nightly_build() {
949             allow_error_code_check = true;
950         }
951
952         data.original = string.to_owned();
953         let tokens = string.split(|c: char|
954             !(c == '_' || c == '-' || c.is_alphanumeric())
955         );
956
957         for token in tokens {
958             match token.trim() {
959                 "" => {},
960                 "should_panic" => {
961                     data.should_panic = true;
962                     seen_rust_tags = seen_other_tags == false;
963                 }
964                 "no_run" => { data.no_run = true; seen_rust_tags = !seen_other_tags; }
965                 "ignore" => { data.ignore = true; seen_rust_tags = !seen_other_tags; }
966                 "allow_fail" => { data.allow_fail = true; seen_rust_tags = !seen_other_tags; }
967                 "rust" => { data.rust = true; seen_rust_tags = true; }
968                 "test_harness" => {
969                     data.test_harness = true;
970                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
971                 }
972                 "compile_fail" => {
973                     data.compile_fail = true;
974                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
975                     data.no_run = true;
976                 }
977                 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
978                     if let Ok(_) = x[1..].parse::<u32>() {
979                         data.error_codes.push(x.to_owned());
980                         seen_rust_tags = !seen_other_tags || seen_rust_tags;
981                     } else {
982                         seen_other_tags = true;
983                     }
984                 }
985                 _ => { seen_other_tags = true }
986             }
987         }
988
989         data.rust &= !seen_other_tags || seen_rust_tags;
990
991         data
992     }
993 }
994
995 impl<'a> fmt::Display for Markdown<'a> {
996     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
997         let Markdown(md, render_type) = *self;
998
999         // This is actually common enough to special-case
1000         if md.is_empty() { return Ok(()) }
1001         if render_type == RenderType::Hoedown {
1002             render(fmt, md, false, 0)
1003         } else {
1004             let mut opts = Options::empty();
1005             opts.insert(OPTION_ENABLE_TABLES);
1006             opts.insert(OPTION_ENABLE_FOOTNOTES);
1007
1008             let p = Parser::new_ext(md, opts);
1009
1010             let mut s = String::with_capacity(md.len() * 3 / 2);
1011
1012             html::push_html(&mut s,
1013                             Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
1014
1015             fmt.write_str(&s)
1016         }
1017     }
1018 }
1019
1020 impl<'a> fmt::Display for MarkdownWithToc<'a> {
1021     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1022         let MarkdownWithToc(md, render_type) = *self;
1023
1024         if render_type == RenderType::Hoedown {
1025             render(fmt, md, true, 0)
1026         } else {
1027             let mut opts = Options::empty();
1028             opts.insert(OPTION_ENABLE_TABLES);
1029             opts.insert(OPTION_ENABLE_FOOTNOTES);
1030
1031             let p = Parser::new_ext(md, opts);
1032
1033             let mut s = String::with_capacity(md.len() * 3 / 2);
1034
1035             let mut toc = TocBuilder::new();
1036
1037             html::push_html(&mut s,
1038                             Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, Some(&mut toc)))));
1039
1040             write!(fmt, "<nav id=\"TOC\">{}</nav>", toc.into_toc())?;
1041
1042             fmt.write_str(&s)
1043         }
1044     }
1045 }
1046
1047 impl<'a> fmt::Display for MarkdownHtml<'a> {
1048     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1049         let MarkdownHtml(md, render_type) = *self;
1050
1051         // This is actually common enough to special-case
1052         if md.is_empty() { return Ok(()) }
1053         if render_type == RenderType::Hoedown {
1054             render(fmt, md, false, HOEDOWN_HTML_ESCAPE)
1055         } else {
1056             let mut opts = Options::empty();
1057             opts.insert(OPTION_ENABLE_TABLES);
1058             opts.insert(OPTION_ENABLE_FOOTNOTES);
1059
1060             let p = Parser::new_ext(md, opts);
1061
1062             // Treat inline HTML as plain text.
1063             let p = p.map(|event| match event {
1064                 Event::Html(text) | Event::InlineHtml(text) => Event::Text(text),
1065                 _ => event
1066             });
1067
1068             let mut s = String::with_capacity(md.len() * 3 / 2);
1069
1070             html::push_html(&mut s,
1071                             Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
1072
1073             fmt.write_str(&s)
1074         }
1075     }
1076 }
1077
1078 impl<'a> fmt::Display for MarkdownSummaryLine<'a> {
1079     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
1080         let MarkdownSummaryLine(md) = *self;
1081         // This is actually common enough to special-case
1082         if md.is_empty() { return Ok(()) }
1083
1084         let p = Parser::new(md);
1085
1086         let mut s = String::new();
1087
1088         html::push_html(&mut s, SummaryLine::new(p));
1089
1090         fmt.write_str(&s)
1091     }
1092 }
1093
1094 pub fn plain_summary_line(md: &str) -> String {
1095     struct ParserWrapper<'a> {
1096         inner: Parser<'a>,
1097         is_in: isize,
1098         is_first: bool,
1099     }
1100
1101     impl<'a> Iterator for ParserWrapper<'a> {
1102         type Item = String;
1103
1104         fn next(&mut self) -> Option<String> {
1105             let next_event = self.inner.next();
1106             if next_event.is_none() {
1107                 return None
1108             }
1109             let next_event = next_event.unwrap();
1110             let (ret, is_in) = match next_event {
1111                 Event::Start(Tag::Paragraph) => (None, 1),
1112                 Event::Start(Tag::Code) => (Some("`".to_owned()), 1),
1113                 Event::End(Tag::Code) => (Some("`".to_owned()), -1),
1114                 Event::Start(Tag::Header(_)) => (None, 1),
1115                 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
1116                 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
1117                 _ => (None, 0),
1118             };
1119             if is_in > 0 || (is_in < 0 && self.is_in > 0) {
1120                 self.is_in += is_in;
1121             }
1122             if ret.is_some() {
1123                 self.is_first = false;
1124                 ret
1125             } else {
1126                 Some(String::new())
1127             }
1128         }
1129     }
1130     let mut s = String::with_capacity(md.len() * 3 / 2);
1131     let mut p = ParserWrapper {
1132         inner: Parser::new(md),
1133         is_in: 0,
1134         is_first: true,
1135     };
1136     while let Some(t) = p.next() {
1137         if !t.is_empty() {
1138             s.push_str(&t);
1139         }
1140     }
1141     s
1142 }
1143
1144 #[cfg(test)]
1145 mod tests {
1146     use super::{LangString, Markdown, MarkdownHtml};
1147     use super::plain_summary_line;
1148     use super::RenderType;
1149     use html::render::reset_ids;
1150
1151     #[test]
1152     fn test_lang_string_parse() {
1153         fn t(s: &str,
1154             should_panic: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool,
1155             compile_fail: bool, allow_fail: bool, error_codes: Vec<String>) {
1156             assert_eq!(LangString::parse(s), LangString {
1157                 should_panic,
1158                 no_run,
1159                 ignore,
1160                 rust,
1161                 test_harness,
1162                 compile_fail,
1163                 error_codes,
1164                 original: s.to_owned(),
1165                 allow_fail,
1166             })
1167         }
1168
1169         fn v() -> Vec<String> {
1170             Vec::new()
1171         }
1172
1173         // marker                | should_panic| no_run| ignore| rust | test_harness| compile_fail
1174         //                       | allow_fail | error_codes
1175         t("",                      false,        false,  false,  true,  false, false, false, v());
1176         t("rust",                  false,        false,  false,  true,  false, false, false, v());
1177         t("sh",                    false,        false,  false,  false, false, false, false, v());
1178         t("ignore",                false,        false,  true,   true,  false, false, false, v());
1179         t("should_panic",          true,         false,  false,  true,  false, false, false, v());
1180         t("no_run",                false,        true,   false,  true,  false, false, false, v());
1181         t("test_harness",          false,        false,  false,  true,  true,  false, false, v());
1182         t("compile_fail",          false,        true,   false,  true,  false, true,  false, v());
1183         t("allow_fail",            false,        false,  false,  true,  false, false, true,  v());
1184         t("{.no_run .example}",    false,        true,   false,  true,  false, false, false, v());
1185         t("{.sh .should_panic}",   true,         false,  false,  false, false, false, false, v());
1186         t("{.example .rust}",      false,        false,  false,  true,  false, false, false, v());
1187         t("{.test_harness .rust}", false,        false,  false,  true,  true,  false, false, v());
1188         t("text, no_run",          false,        true,   false,  false, false, false, false, v());
1189         t("text,no_run",           false,        true,   false,  false, false, false, false, v());
1190     }
1191
1192     #[test]
1193     fn issue_17736() {
1194         let markdown = "# title";
1195         format!("{}", Markdown(markdown, RenderType::Pulldown));
1196         reset_ids(true);
1197     }
1198
1199     #[test]
1200     fn test_header() {
1201         fn t(input: &str, expect: &str) {
1202             let output = format!("{}", Markdown(input, RenderType::Pulldown));
1203             assert_eq!(output, expect, "original: {}", input);
1204             reset_ids(true);
1205         }
1206
1207         t("# Foo bar", "<h1 id=\"foo-bar\" class=\"section-header\">\
1208           <a href=\"#foo-bar\">Foo bar</a></h1>");
1209         t("## Foo-bar_baz qux", "<h2 id=\"foo-bar_baz-qux\" class=\"section-\
1210           header\"><a href=\"#foo-bar_baz-qux\">Foo-bar_baz qux</a></h2>");
1211         t("### **Foo** *bar* baz!?!& -_qux_-%",
1212           "<h3 id=\"foo-bar-baz--qux-\" class=\"section-header\">\
1213           <a href=\"#foo-bar-baz--qux-\"><strong>Foo</strong> \
1214           <em>bar</em> baz!?!&amp; -<em>qux</em>-%</a></h3>");
1215         t("#### **Foo?** & \\*bar?!*  _`baz`_ ❤ #qux",
1216           "<h4 id=\"foo--bar--baz--qux\" class=\"section-header\">\
1217           <a href=\"#foo--bar--baz--qux\"><strong>Foo?</strong> &amp; *bar?!*  \
1218           <em><code>baz</code></em> ❤ #qux</a></h4>");
1219     }
1220
1221     #[test]
1222     fn test_header_ids_multiple_blocks() {
1223         fn t(input: &str, expect: &str) {
1224             let output = format!("{}", Markdown(input, RenderType::Pulldown));
1225             assert_eq!(output, expect, "original: {}", input);
1226         }
1227
1228         let test = || {
1229             t("# Example", "<h1 id=\"example\" class=\"section-header\">\
1230               <a href=\"#example\">Example</a></h1>");
1231             t("# Panics", "<h1 id=\"panics\" class=\"section-header\">\
1232               <a href=\"#panics\">Panics</a></h1>");
1233             t("# Example", "<h1 id=\"example-1\" class=\"section-header\">\
1234               <a href=\"#example-1\">Example</a></h1>");
1235             t("# Main", "<h1 id=\"main-1\" class=\"section-header\">\
1236               <a href=\"#main-1\">Main</a></h1>");
1237             t("# Example", "<h1 id=\"example-2\" class=\"section-header\">\
1238               <a href=\"#example-2\">Example</a></h1>");
1239             t("# Panics", "<h1 id=\"panics-1\" class=\"section-header\">\
1240               <a href=\"#panics-1\">Panics</a></h1>");
1241         };
1242         test();
1243         reset_ids(true);
1244         test();
1245     }
1246
1247     #[test]
1248     fn test_plain_summary_line() {
1249         fn t(input: &str, expect: &str) {
1250             let output = plain_summary_line(input);
1251             assert_eq!(output, expect, "original: {}", input);
1252         }
1253
1254         t("hello [Rust](https://www.rust-lang.org) :)", "hello Rust :)");
1255         t("hello [Rust](https://www.rust-lang.org \"Rust\") :)", "hello Rust :)");
1256         t("code `let x = i32;` ...", "code `let x = i32;` ...");
1257         t("type `Type<'static>` ...", "type `Type<'static>` ...");
1258         t("# top header", "top header");
1259         t("## header", "header");
1260     }
1261
1262     #[test]
1263     fn test_markdown_html_escape() {
1264         fn t(input: &str, expect: &str) {
1265             let output = format!("{}", MarkdownHtml(input, RenderType::Pulldown));
1266             assert_eq!(output, expect, "original: {}", input);
1267         }
1268
1269         t("`Struct<'a, T>`", "<p><code>Struct&lt;'a, T&gt;</code></p>\n");
1270         t("Struct<'a, T>", "<p>Struct&lt;'a, T&gt;</p>\n");
1271         t("Struct<br>", "<p>Struct&lt;br&gt;</p>\n");
1272     }
1273 }