]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
Auto merge of #41282 - arielb1:missing-impl-item, r=petrochenkov
[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 //! ```rust,ignore
19 //! use rustdoc::html::markdown::Markdown;
20 //!
21 //! let s = "My *markdown* _text_";
22 //! let html = format!("{}", Markdown(s));
23 //! // ... something using html
24 //! ```
25
26 #![allow(non_camel_case_types)]
27
28 use libc;
29 use std::slice;
30
31 use std::ascii::AsciiExt;
32 use std::cell::RefCell;
33 use std::collections::{HashMap, VecDeque};
34 use std::default::Default;
35 use std::fmt::{self, Write};
36 use std::str;
37 use syntax::feature_gate::UnstableFeatures;
38 use syntax::codemap::Span;
39
40 use html::render::derive_id;
41 use html::toc::TocBuilder;
42 use html::highlight;
43 use test;
44
45 use pulldown_cmark::{html, Event, Tag, Parser};
46 use pulldown_cmark::{Options, OPTION_ENABLE_FOOTNOTES, OPTION_ENABLE_TABLES};
47
48 /// A unit struct which has the `fmt::Display` trait implemented. When
49 /// formatted, this struct will emit the HTML corresponding to the rendered
50 /// version of the contained markdown string.
51 // The second parameter is whether we need a shorter version or not.
52 pub struct Markdown<'a>(pub &'a str);
53 /// A unit struct like `Markdown`, that renders the markdown with a
54 /// table of contents.
55 pub struct MarkdownWithToc<'a>(pub &'a str);
56 /// A unit struct like `Markdown`, that renders the markdown escaping HTML tags.
57 pub struct MarkdownHtml<'a>(pub &'a str);
58 /// A unit struct like `Markdown`, that renders only the first paragraph.
59 pub struct MarkdownSummaryLine<'a>(pub &'a str);
60
61 /// Returns Some(code) if `s` is a line that should be stripped from
62 /// documentation but used in example code. `code` is the portion of
63 /// `s` that should be used in tests. (None for lines that should be
64 /// left as-is.)
65 fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
66     let trimmed = s.trim();
67     if trimmed == "#" {
68         Some("")
69     } else if trimmed.starts_with("# ") {
70         Some(&trimmed[2..])
71     } else {
72         None
73     }
74 }
75
76 /// Convert chars from a title for an id.
77 ///
78 /// "Hello, world!" -> "hello-world"
79 fn slugify(c: char) -> Option<char> {
80     if c.is_alphanumeric() || c == '-' || c == '_' {
81         if c.is_ascii() {
82             Some(c.to_ascii_lowercase())
83         } else {
84             Some(c)
85         }
86     } else if c.is_whitespace() && c.is_ascii() {
87         Some('-')
88     } else {
89         None
90     }
91 }
92
93 // Information about the playground if a URL has been specified, containing an
94 // optional crate name and the URL.
95 thread_local!(pub static PLAYGROUND: RefCell<Option<(Option<String>, String)>> = {
96     RefCell::new(None)
97 });
98
99 /// Adds syntax highlighting and playground Run buttons to rust code blocks.
100 struct CodeBlocks<'a, I: Iterator<Item = Event<'a>>> {
101     inner: I,
102 }
103
104 impl<'a, I: Iterator<Item = Event<'a>>> CodeBlocks<'a, I> {
105     fn new(iter: I) -> Self {
106         CodeBlocks {
107             inner: iter,
108         }
109     }
110 }
111
112 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'a, I> {
113     type Item = Event<'a>;
114
115     fn next(&mut self) -> Option<Self::Item> {
116         let event = self.inner.next();
117         if let Some(Event::Start(Tag::CodeBlock(lang))) = event {
118             if !LangString::parse(&lang).rust {
119                 return Some(Event::Start(Tag::CodeBlock(lang)));
120             }
121         } else {
122             return event;
123         }
124
125         let mut origtext = String::new();
126         for event in &mut self.inner {
127             match event {
128                 Event::End(Tag::CodeBlock(..)) => break,
129                 Event::Text(ref s) => {
130                     origtext.push_str(s);
131                 }
132                 _ => {}
133             }
134         }
135         let lines = origtext.lines().filter(|l| {
136             stripped_filtered_line(*l).is_none()
137         });
138         let text = lines.collect::<Vec<&str>>().join("\n");
139         PLAYGROUND.with(|play| {
140             // insert newline to clearly separate it from the
141             // previous block so we can shorten the html output
142             let mut s = String::from("\n");
143             let playground_button = play.borrow().as_ref().and_then(|&(ref krate, ref url)| {
144                 if url.is_empty() {
145                     return None;
146                 }
147                 let test = origtext.lines().map(|l| {
148                     stripped_filtered_line(l).unwrap_or(l)
149                 }).collect::<Vec<&str>>().join("\n");
150                 let krate = krate.as_ref().map(|s| &**s);
151                 let test = test::maketest(&test, krate, false,
152                                         &Default::default());
153                 let channel = if test.contains("#![feature(") {
154                     "&amp;version=nightly"
155                 } else {
156                     ""
157                 };
158                 // These characters don't need to be escaped in a URI.
159                 // FIXME: use a library function for percent encoding.
160                 fn dont_escape(c: u8) -> bool {
161                     (b'a' <= c && c <= b'z') ||
162                     (b'A' <= c && c <= b'Z') ||
163                     (b'0' <= c && c <= b'9') ||
164                     c == b'-' || c == b'_' || c == b'.' ||
165                     c == b'~' || c == b'!' || c == b'\'' ||
166                     c == b'(' || c == b')' || c == b'*'
167                 }
168                 let mut test_escaped = String::new();
169                 for b in test.bytes() {
170                     if dont_escape(b) {
171                         test_escaped.push(char::from(b));
172                     } else {
173                         write!(test_escaped, "%{:02X}", b).unwrap();
174                     }
175                 }
176                 Some(format!(
177                     r#"<a class="test-arrow" target="_blank" href="{}?code={}{}">Run</a>"#,
178                     url, test_escaped, channel
179                 ))
180             });
181             s.push_str(&highlight::render_with_highlighting(
182                         &text,
183                         Some("rust-example-rendered"),
184                         None,
185                         playground_button.as_ref().map(String::as_str)));
186             Some(Event::Html(s.into()))
187         })
188     }
189 }
190
191 /// Make headings links with anchor ids and build up TOC.
192 struct HeadingLinks<'a, 'b, I: Iterator<Item = Event<'a>>> {
193     inner: I,
194     toc: Option<&'b mut TocBuilder>,
195     buf: VecDeque<Event<'a>>,
196 }
197
198 impl<'a, 'b, I: Iterator<Item = Event<'a>>> HeadingLinks<'a, 'b, I> {
199     fn new(iter: I, toc: Option<&'b mut TocBuilder>) -> Self {
200         HeadingLinks {
201             inner: iter,
202             toc: toc,
203             buf: VecDeque::new(),
204         }
205     }
206 }
207
208 impl<'a, 'b, I: Iterator<Item = Event<'a>>> Iterator for HeadingLinks<'a, 'b, I> {
209     type Item = Event<'a>;
210
211     fn next(&mut self) -> Option<Self::Item> {
212         if let Some(e) = self.buf.pop_front() {
213             return Some(e);
214         }
215
216         let event = self.inner.next();
217         if let Some(Event::Start(Tag::Header(level))) = event {
218             let mut id = String::new();
219             for event in &mut self.inner {
220                 match event {
221                     Event::End(Tag::Header(..)) => break,
222                     Event::Text(ref text) => id.extend(text.chars().filter_map(slugify)),
223                     _ => {},
224                 }
225                 self.buf.push_back(event);
226             }
227             let id = derive_id(id);
228
229             if let Some(ref mut builder) = self.toc {
230                 let mut html_header = String::new();
231                 html::push_html(&mut html_header, self.buf.iter().cloned());
232                 let sec = builder.push(level as u32, html_header, id.clone());
233                 self.buf.push_front(Event::InlineHtml(format!("{} ", sec).into()));
234             }
235
236             self.buf.push_back(Event::InlineHtml(format!("</a></h{}>", level).into()));
237
238             let start_tags = format!("<h{level} id=\"{id}\" class=\"section-header\">\
239                                       <a href=\"#{id}\">",
240                                      id = id,
241                                      level = level);
242             return Some(Event::InlineHtml(start_tags.into()));
243         }
244         event
245     }
246 }
247
248 /// Extracts just the first paragraph.
249 struct SummaryLine<'a, I: Iterator<Item = Event<'a>>> {
250     inner: I,
251     started: bool,
252     depth: u32,
253 }
254
255 impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
256     fn new(iter: I) -> Self {
257         SummaryLine {
258             inner: iter,
259             started: false,
260             depth: 0,
261         }
262     }
263 }
264
265 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {
266     type Item = Event<'a>;
267
268     fn next(&mut self) -> Option<Self::Item> {
269         if self.started && self.depth == 0 {
270             return None;
271         }
272         if !self.started {
273             self.started = true;
274         }
275         let event = self.inner.next();
276         match event {
277             Some(Event::Start(..)) => self.depth += 1,
278             Some(Event::End(..)) => self.depth -= 1,
279             _ => {}
280         }
281         event
282     }
283 }
284
285 /// Moves all footnote definitions to the end and add back links to the
286 /// references.
287 struct Footnotes<'a, I: Iterator<Item = Event<'a>>> {
288     inner: I,
289     footnotes: HashMap<String, (Vec<Event<'a>>, u16)>,
290 }
291
292 impl<'a, I: Iterator<Item = Event<'a>>> Footnotes<'a, I> {
293     fn new(iter: I) -> Self {
294         Footnotes {
295             inner: iter,
296             footnotes: HashMap::new(),
297         }
298     }
299     fn get_entry(&mut self, key: &str) -> &mut (Vec<Event<'a>>, u16) {
300         let new_id = self.footnotes.keys().count() + 1;
301         let key = key.to_owned();
302         self.footnotes.entry(key).or_insert((Vec::new(), new_id as u16))
303     }
304 }
305
306 impl<'a, I: Iterator<Item = Event<'a>>> Iterator for Footnotes<'a, I> {
307     type Item = Event<'a>;
308
309     fn next(&mut self) -> Option<Self::Item> {
310         loop {
311             match self.inner.next() {
312                 Some(Event::FootnoteReference(ref reference)) => {
313                     let entry = self.get_entry(&reference);
314                     let reference = format!("<sup id=\"supref{0}\"><a href=\"#ref{0}\">{0}\
315                                              </a></sup>",
316                                             (*entry).1);
317                     return Some(Event::Html(reference.into()));
318                 }
319                 Some(Event::Start(Tag::FootnoteDefinition(def))) => {
320                     let mut content = Vec::new();
321                     for event in &mut self.inner {
322                         if let Event::End(Tag::FootnoteDefinition(..)) = event {
323                             break;
324                         }
325                         content.push(event);
326                     }
327                     let entry = self.get_entry(&def);
328                     (*entry).0 = content;
329                 }
330                 Some(e) => return Some(e),
331                 None => {
332                     if !self.footnotes.is_empty() {
333                         let mut v: Vec<_> = self.footnotes.drain().map(|(_, x)| x).collect();
334                         v.sort_by(|a, b| a.1.cmp(&b.1));
335                         let mut ret = String::from("<div class=\"footnotes\"><hr><ol>");
336                         for (mut content, id) in v {
337                             write!(ret, "<li id=\"ref{}\">", id).unwrap();
338                             let mut is_paragraph = false;
339                             if let Some(&Event::End(Tag::Paragraph)) = content.last() {
340                                 content.pop();
341                                 is_paragraph = true;
342                             }
343                             html::push_html(&mut ret, content.into_iter());
344                             write!(ret,
345                                    "&nbsp;<a href=\"#supref{}\" rev=\"footnote\">↩</a>",
346                                    id).unwrap();
347                             if is_paragraph {
348                                 ret.push_str("</p>");
349                             }
350                             ret.push_str("</li>");
351                         }
352                         ret.push_str("</ol></div>");
353                         return Some(Event::Html(ret.into()));
354                     } else {
355                         return None;
356                     }
357                 }
358             }
359         }
360     }
361 }
362
363 const DEF_OUNIT: libc::size_t = 64;
364 const HOEDOWN_EXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 11;
365 const HOEDOWN_EXT_TABLES: libc::c_uint = 1 << 0;
366 const HOEDOWN_EXT_FENCED_CODE: libc::c_uint = 1 << 1;
367 const HOEDOWN_EXT_AUTOLINK: libc::c_uint = 1 << 3;
368 const HOEDOWN_EXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
369 const HOEDOWN_EXT_SUPERSCRIPT: libc::c_uint = 1 << 8;
370 const HOEDOWN_EXT_FOOTNOTES: libc::c_uint = 1 << 2;
371
372 const HOEDOWN_EXTENSIONS: libc::c_uint =
373     HOEDOWN_EXT_NO_INTRA_EMPHASIS | HOEDOWN_EXT_TABLES |
374     HOEDOWN_EXT_FENCED_CODE | HOEDOWN_EXT_AUTOLINK |
375     HOEDOWN_EXT_STRIKETHROUGH | HOEDOWN_EXT_SUPERSCRIPT |
376     HOEDOWN_EXT_FOOTNOTES;
377
378 enum hoedown_document {}
379
380 type blockcodefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
381                                  *const hoedown_buffer, *const hoedown_renderer_data,
382                                  libc::size_t);
383
384 type blockquotefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
385                                   *const hoedown_renderer_data, libc::size_t);
386
387 type headerfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
388                               libc::c_int, *const hoedown_renderer_data,
389                               libc::size_t);
390
391 type blockhtmlfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
392                                  *const hoedown_renderer_data, libc::size_t);
393
394 type codespanfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
395                                 *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
396
397 type linkfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
398                              *const hoedown_buffer, *const hoedown_buffer,
399                              *const hoedown_renderer_data, libc::size_t) -> libc::c_int;
400
401 type entityfn = extern "C" fn (*mut hoedown_buffer, *const hoedown_buffer,
402                                *const hoedown_renderer_data, libc::size_t);
403
404 type normaltextfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
405                                   *const hoedown_renderer_data, libc::size_t);
406
407 #[repr(C)]
408 struct hoedown_renderer_data {
409     opaque: *mut libc::c_void,
410 }
411
412 #[repr(C)]
413 struct hoedown_renderer {
414     opaque: *mut libc::c_void,
415
416     blockcode: Option<blockcodefn>,
417     blockquote: Option<blockquotefn>,
418     header: Option<headerfn>,
419
420     other_block_level_callbacks: [libc::size_t; 11],
421
422     blockhtml: Option<blockhtmlfn>,
423
424     /* span level callbacks - NULL or return 0 prints the span verbatim */
425     autolink: libc::size_t, // unused
426     codespan: Option<codespanfn>,
427     other_span_level_callbacks_1: [libc::size_t; 7],
428     link: Option<linkfn>,
429     other_span_level_callbacks_2: [libc::size_t; 6],
430
431     /* low level callbacks - NULL copies input directly into the output */
432     entity: Option<entityfn>,
433     normal_text: Option<normaltextfn>,
434
435     /* header and footer */
436     other_callbacks: [libc::size_t; 2],
437 }
438
439 #[repr(C)]
440 struct hoedown_html_renderer_state {
441     opaque: *mut libc::c_void,
442     toc_data: html_toc_data,
443     flags: libc::c_uint,
444     link_attributes: Option<extern "C" fn(*mut hoedown_buffer,
445                                           *const hoedown_buffer,
446                                           *const hoedown_renderer_data)>,
447 }
448
449 #[repr(C)]
450 struct html_toc_data {
451     header_count: libc::c_int,
452     current_level: libc::c_int,
453     level_offset: libc::c_int,
454     nesting_level: libc::c_int,
455 }
456
457 #[repr(C)]
458 struct hoedown_buffer {
459     data: *const u8,
460     size: libc::size_t,
461     asize: libc::size_t,
462     unit: libc::size_t,
463 }
464
465 extern {
466     fn hoedown_html_renderer_new(render_flags: libc::c_uint,
467                                  nesting_level: libc::c_int)
468         -> *mut hoedown_renderer;
469     fn hoedown_html_renderer_free(renderer: *mut hoedown_renderer);
470
471     fn hoedown_document_new(rndr: *const hoedown_renderer,
472                             extensions: libc::c_uint,
473                             max_nesting: libc::size_t) -> *mut hoedown_document;
474     fn hoedown_document_render(doc: *mut hoedown_document,
475                                ob: *mut hoedown_buffer,
476                                document: *const u8,
477                                doc_size: libc::size_t);
478     fn hoedown_document_free(md: *mut hoedown_document);
479
480     fn hoedown_buffer_new(unit: libc::size_t) -> *mut hoedown_buffer;
481     fn hoedown_buffer_free(b: *mut hoedown_buffer);
482 }
483
484 impl hoedown_buffer {
485     fn as_bytes(&self) -> &[u8] {
486         unsafe { slice::from_raw_parts(self.data, self.size as usize) }
487     }
488 }
489
490 pub fn old_find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
491     extern fn block(_ob: *mut hoedown_buffer,
492                     text: *const hoedown_buffer,
493                     lang: *const hoedown_buffer,
494                     data: *const hoedown_renderer_data,
495                     line: libc::size_t) {
496         unsafe {
497             if text.is_null() { return }
498             let block_info = if lang.is_null() {
499                 LangString::all_false()
500             } else {
501                 let lang = (*lang).as_bytes();
502                 let s = str::from_utf8(lang).unwrap();
503                 LangString::parse(s)
504             };
505             if !block_info.rust { return }
506             let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
507             let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
508             let line = tests.get_line() + line;
509             let filename = tests.get_filename();
510             tests.add_old_test(line, filename);
511         }
512     }
513
514     extern fn header(_ob: *mut hoedown_buffer,
515                      text: *const hoedown_buffer,
516                      level: libc::c_int, data: *const hoedown_renderer_data,
517                      _: libc::size_t) {
518         unsafe {
519             let opaque = (*data).opaque as *mut hoedown_html_renderer_state;
520             let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
521             if text.is_null() {
522                 tests.register_header("", level as u32);
523             } else {
524                 let text = (*text).as_bytes();
525                 let text = str::from_utf8(text).unwrap();
526                 tests.register_header(text, level as u32);
527             }
528         }
529     }
530
531     tests.set_position(position);
532
533     unsafe {
534         let ob = hoedown_buffer_new(DEF_OUNIT);
535         let renderer = hoedown_html_renderer_new(0, 0);
536         (*renderer).blockcode = Some(block);
537         (*renderer).header = Some(header);
538         (*((*renderer).opaque as *mut hoedown_html_renderer_state)).opaque
539                 = tests as *mut _ as *mut libc::c_void;
540
541         let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
542         hoedown_document_render(document, ob, doc.as_ptr(),
543                                 doc.len() as libc::size_t);
544         hoedown_document_free(document);
545
546         hoedown_html_renderer_free(renderer);
547         hoedown_buffer_free(ob);
548     }
549 }
550
551 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector, position: Span) {
552     tests.set_position(position);
553
554     let mut parser = Parser::new(doc);
555     let mut prev_offset = 0;
556     let mut nb_lines = 0;
557     let mut register_header = None;
558     'main: while let Some(event) = parser.next() {
559         match event {
560             Event::Start(Tag::CodeBlock(s)) => {
561                 let block_info = if s.is_empty() {
562                     LangString::all_false()
563                 } else {
564                     LangString::parse(&*s)
565                 };
566                 if !block_info.rust {
567                     continue
568                 }
569                 let mut test_s = String::new();
570                 let mut offset = None;
571                 loop {
572                     let event = parser.next();
573                     if let Some(event) = event {
574                         match event {
575                             Event::End(Tag::CodeBlock(_)) => break,
576                             Event::Text(ref s) => {
577                                 test_s.push_str(s);
578                                 if offset.is_none() {
579                                     offset = Some(parser.get_offset());
580                                 }
581                             }
582                             _ => {}
583                         }
584                     } else {
585                         break 'main;
586                     }
587                 }
588                 let offset = offset.unwrap_or(0);
589                 let lines = test_s.lines().map(|l| {
590                     stripped_filtered_line(l).unwrap_or(l)
591                 });
592                 let text = lines.collect::<Vec<&str>>().join("\n");
593                 nb_lines += doc[prev_offset..offset].lines().count();
594                 let line = tests.get_line() + (nb_lines - 1);
595                 let filename = tests.get_filename();
596                 tests.add_test(text.to_owned(),
597                                block_info.should_panic, block_info.no_run,
598                                block_info.ignore, block_info.test_harness,
599                                block_info.compile_fail, block_info.error_codes,
600                                line, filename);
601                 prev_offset = offset;
602             }
603             Event::Start(Tag::Header(level)) => {
604                 register_header = Some(level as u32);
605             }
606             Event::Text(ref s) if register_header.is_some() => {
607                 let level = register_header.unwrap();
608                 if s.is_empty() {
609                     tests.register_header("", level);
610                 } else {
611                     tests.register_header(s, level);
612                 }
613                 register_header = None;
614             }
615             _ => {}
616         }
617     }
618 }
619
620 #[derive(Eq, PartialEq, Clone, Debug)]
621 struct LangString {
622     original: String,
623     should_panic: bool,
624     no_run: bool,
625     ignore: bool,
626     rust: bool,
627     test_harness: bool,
628     compile_fail: bool,
629     error_codes: Vec<String>,
630 }
631
632 impl LangString {
633     fn all_false() -> LangString {
634         LangString {
635             original: String::new(),
636             should_panic: false,
637             no_run: false,
638             ignore: false,
639             rust: true,  // NB This used to be `notrust = false`
640             test_harness: false,
641             compile_fail: false,
642             error_codes: Vec::new(),
643         }
644     }
645
646     fn parse(string: &str) -> LangString {
647         let mut seen_rust_tags = false;
648         let mut seen_other_tags = false;
649         let mut data = LangString::all_false();
650         let mut allow_compile_fail = false;
651         let mut allow_error_code_check = false;
652         if UnstableFeatures::from_environment().is_nightly_build() {
653             allow_compile_fail = true;
654             allow_error_code_check = true;
655         }
656
657         data.original = string.to_owned();
658         let tokens = string.split(|c: char|
659             !(c == '_' || c == '-' || c.is_alphanumeric())
660         );
661
662         for token in tokens {
663             match token.trim() {
664                 "" => {},
665                 "should_panic" => {
666                     data.should_panic = true;
667                     seen_rust_tags = seen_other_tags == false;
668                 }
669                 "no_run" => { data.no_run = true; seen_rust_tags = !seen_other_tags; }
670                 "ignore" => { data.ignore = true; seen_rust_tags = !seen_other_tags; }
671                 "rust" => { data.rust = true; seen_rust_tags = true; }
672                 "test_harness" => {
673                     data.test_harness = true;
674                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
675                 }
676                 "compile_fail" if allow_compile_fail => {
677                     data.compile_fail = true;
678                     seen_rust_tags = !seen_other_tags || seen_rust_tags;
679                     data.no_run = true;
680                 }
681                 x if allow_error_code_check && x.starts_with("E") && x.len() == 5 => {
682                     if let Ok(_) = x[1..].parse::<u32>() {
683                         data.error_codes.push(x.to_owned());
684                         seen_rust_tags = !seen_other_tags || seen_rust_tags;
685                     } else {
686                         seen_other_tags = true;
687                     }
688                 }
689                 _ => { seen_other_tags = true }
690             }
691         }
692
693         data.rust &= !seen_other_tags || seen_rust_tags;
694
695         data
696     }
697 }
698
699 impl<'a> fmt::Display for Markdown<'a> {
700     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
701         let Markdown(md) = *self;
702         // This is actually common enough to special-case
703         if md.is_empty() { return Ok(()) }
704
705         let mut opts = Options::empty();
706         opts.insert(OPTION_ENABLE_TABLES);
707         opts.insert(OPTION_ENABLE_FOOTNOTES);
708
709         let p = Parser::new_ext(md, opts);
710
711         let mut s = String::with_capacity(md.len() * 3 / 2);
712
713         html::push_html(&mut s,
714                         Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
715
716         fmt.write_str(&s)
717     }
718 }
719
720 impl<'a> fmt::Display for MarkdownWithToc<'a> {
721     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
722         let MarkdownWithToc(md) = *self;
723
724         let mut opts = Options::empty();
725         opts.insert(OPTION_ENABLE_TABLES);
726         opts.insert(OPTION_ENABLE_FOOTNOTES);
727
728         let p = Parser::new_ext(md, opts);
729
730         let mut s = String::with_capacity(md.len() * 3 / 2);
731
732         let mut toc = TocBuilder::new();
733
734         html::push_html(&mut s,
735                         Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, Some(&mut toc)))));
736
737         write!(fmt, "<nav id=\"TOC\">{}</nav>", toc.into_toc())?;
738
739         fmt.write_str(&s)
740     }
741 }
742
743 impl<'a> fmt::Display for MarkdownHtml<'a> {
744     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
745         let MarkdownHtml(md) = *self;
746         // This is actually common enough to special-case
747         if md.is_empty() { return Ok(()) }
748
749         let mut opts = Options::empty();
750         opts.insert(OPTION_ENABLE_TABLES);
751         opts.insert(OPTION_ENABLE_FOOTNOTES);
752
753         let p = Parser::new_ext(md, opts);
754
755         // Treat inline HTML as plain text.
756         let p = p.map(|event| match event {
757             Event::Html(text) | Event::InlineHtml(text) => Event::Text(text),
758             _ => event
759         });
760
761         let mut s = String::with_capacity(md.len() * 3 / 2);
762
763         html::push_html(&mut s,
764                         Footnotes::new(CodeBlocks::new(HeadingLinks::new(p, None))));
765
766         fmt.write_str(&s)
767     }
768 }
769
770 impl<'a> fmt::Display for MarkdownSummaryLine<'a> {
771     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
772         let MarkdownSummaryLine(md) = *self;
773         // This is actually common enough to special-case
774         if md.is_empty() { return Ok(()) }
775
776         let p = Parser::new(md);
777
778         let mut s = String::new();
779
780         html::push_html(&mut s, SummaryLine::new(p));
781
782         fmt.write_str(&s)
783     }
784 }
785
786 pub fn plain_summary_line(md: &str) -> String {
787     struct ParserWrapper<'a> {
788         inner: Parser<'a>,
789         is_in: isize,
790         is_first: bool,
791     }
792
793     impl<'a> Iterator for ParserWrapper<'a> {
794         type Item = String;
795
796         fn next(&mut self) -> Option<String> {
797             let next_event = self.inner.next();
798             if next_event.is_none() {
799                 return None
800             }
801             let next_event = next_event.unwrap();
802             let (ret, is_in) = match next_event {
803                 Event::Start(Tag::Paragraph) => (None, 1),
804                 Event::Start(Tag::Code) => (Some("`".to_owned()), 1),
805                 Event::End(Tag::Code) => (Some("`".to_owned()), -1),
806                 Event::Start(Tag::Header(_)) => (None, 1),
807                 Event::Text(ref s) if self.is_in > 0 => (Some(s.as_ref().to_owned()), 0),
808                 Event::End(Tag::Paragraph) | Event::End(Tag::Header(_)) => (None, -1),
809                 _ => (None, 0),
810             };
811             if is_in > 0 || (is_in < 0 && self.is_in > 0) {
812                 self.is_in += is_in;
813             }
814             if ret.is_some() {
815                 self.is_first = false;
816                 ret
817             } else {
818                 Some(String::new())
819             }
820         }
821     }
822     let mut s = String::with_capacity(md.len() * 3 / 2);
823     let mut p = ParserWrapper {
824         inner: Parser::new(md),
825         is_in: 0,
826         is_first: true,
827     };
828     while let Some(t) = p.next() {
829         if !t.is_empty() {
830             s.push_str(&t);
831         }
832     }
833     s
834 }
835
836 #[cfg(test)]
837 mod tests {
838     use super::{LangString, Markdown, MarkdownHtml};
839     use super::plain_summary_line;
840     use html::render::reset_ids;
841
842     #[test]
843     fn test_lang_string_parse() {
844         fn t(s: &str,
845             should_panic: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool,
846             compile_fail: bool, error_codes: Vec<String>) {
847             assert_eq!(LangString::parse(s), LangString {
848                 should_panic: should_panic,
849                 no_run: no_run,
850                 ignore: ignore,
851                 rust: rust,
852                 test_harness: test_harness,
853                 compile_fail: compile_fail,
854                 error_codes: error_codes,
855                 original: s.to_owned(),
856             })
857         }
858
859         // marker                | should_panic| no_run| ignore| rust | test_harness| compile_fail
860         //                       | error_codes
861         t("",                      false,        false,  false,  true,  false, false, Vec::new());
862         t("rust",                  false,        false,  false,  true,  false, false, Vec::new());
863         t("sh",                    false,        false,  false,  false, false, false, Vec::new());
864         t("ignore",                false,        false,  true,   true,  false, false, Vec::new());
865         t("should_panic",          true,         false,  false,  true,  false, false, Vec::new());
866         t("no_run",                false,        true,   false,  true,  false, false, Vec::new());
867         t("test_harness",          false,        false,  false,  true,  true,  false, Vec::new());
868         t("compile_fail",          false,        true,   false,  true,  false, true,  Vec::new());
869         t("{.no_run .example}",    false,        true,   false,  true,  false, false, Vec::new());
870         t("{.sh .should_panic}",   true,         false,  false,  false, false, false, Vec::new());
871         t("{.example .rust}",      false,        false,  false,  true,  false, false, Vec::new());
872         t("{.test_harness .rust}", false,        false,  false,  true,  true,  false, Vec::new());
873         t("text, no_run",          false,        true,   false,  false, false, false, Vec::new());
874         t("text,no_run",           false,        true,   false,  false, false, false, Vec::new());
875     }
876
877     #[test]
878     fn issue_17736() {
879         let markdown = "# title";
880         format!("{}", Markdown(markdown));
881         reset_ids(true);
882     }
883
884     #[test]
885     fn test_header() {
886         fn t(input: &str, expect: &str) {
887             let output = format!("{}", Markdown(input));
888             assert_eq!(output, expect, "original: {}", input);
889             reset_ids(true);
890         }
891
892         t("# Foo bar", "<h1 id=\"foo-bar\" class=\"section-header\">\
893           <a href=\"#foo-bar\">Foo bar</a></h1>");
894         t("## Foo-bar_baz qux", "<h2 id=\"foo-bar_baz-qux\" class=\"section-\
895           header\"><a href=\"#foo-bar_baz-qux\">Foo-bar_baz qux</a></h2>");
896         t("### **Foo** *bar* baz!?!& -_qux_-%",
897           "<h3 id=\"foo-bar-baz--qux-\" class=\"section-header\">\
898           <a href=\"#foo-bar-baz--qux-\"><strong>Foo</strong> \
899           <em>bar</em> baz!?!&amp; -<em>qux</em>-%</a></h3>");
900         t("#### **Foo?** & \\*bar?!*  _`baz`_ ❤ #qux",
901           "<h4 id=\"foo--bar--baz--qux\" class=\"section-header\">\
902           <a href=\"#foo--bar--baz--qux\"><strong>Foo?</strong> &amp; *bar?!*  \
903           <em><code>baz</code></em> ❤ #qux</a></h4>");
904     }
905
906     #[test]
907     fn test_header_ids_multiple_blocks() {
908         fn t(input: &str, expect: &str) {
909             let output = format!("{}", Markdown(input));
910             assert_eq!(output, expect, "original: {}", input);
911         }
912
913         let test = || {
914             t("# Example", "<h1 id=\"example\" class=\"section-header\">\
915               <a href=\"#example\">Example</a></h1>");
916             t("# Panics", "<h1 id=\"panics\" class=\"section-header\">\
917               <a href=\"#panics\">Panics</a></h1>");
918             t("# Example", "<h1 id=\"example-1\" class=\"section-header\">\
919               <a href=\"#example-1\">Example</a></h1>");
920             t("# Main", "<h1 id=\"main-1\" class=\"section-header\">\
921               <a href=\"#main-1\">Main</a></h1>");
922             t("# Example", "<h1 id=\"example-2\" class=\"section-header\">\
923               <a href=\"#example-2\">Example</a></h1>");
924             t("# Panics", "<h1 id=\"panics-1\" class=\"section-header\">\
925               <a href=\"#panics-1\">Panics</a></h1>");
926         };
927         test();
928         reset_ids(true);
929         test();
930     }
931
932     #[test]
933     fn test_plain_summary_line() {
934         fn t(input: &str, expect: &str) {
935             let output = plain_summary_line(input);
936             assert_eq!(output, expect, "original: {}", input);
937         }
938
939         t("hello [Rust](https://www.rust-lang.org) :)", "hello Rust :)");
940         t("hello [Rust](https://www.rust-lang.org \"Rust\") :)", "hello Rust :)");
941         t("code `let x = i32;` ...", "code `let x = i32;` ...");
942         t("type `Type<'static>` ...", "type `Type<'static>` ...");
943         t("# top header", "top header");
944         t("## header", "header");
945     }
946
947     #[test]
948     fn test_markdown_html_escape() {
949         fn t(input: &str, expect: &str) {
950             let output = format!("{}", MarkdownHtml(input));
951             assert_eq!(output, expect, "original: {}", input);
952         }
953
954         t("`Struct<'a, T>`", "<p><code>Struct&lt;'a, T&gt;</code></p>\n");
955         t("Struct<'a, T>", "<p>Struct&lt;'a, T&gt;</p>\n");
956         t("Struct<br>", "<p>Struct&lt;br&gt;</p>\n");
957     }
958 }