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