]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/markdown.rs
doc: remove incomplete sentence
[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 hoedown C-library
14 //! (bundled into the rust runtime). This module self-contains the C bindings
15 //! and necessary legwork to render markdown, and exposes all of the
16 //! functionality through a unit-struct, `Markdown`, which has an implementation
17 //! of `fmt::Show`. Example usage:
18 //!
19 //! ```rust,ignore
20 //! use rustdoc::html::markdown::Markdown;
21 //!
22 //! let s = "My *markdown* _text_";
23 //! let html = format!("{}", Markdown(s));
24 //! // ... something using html
25 //! ```
26
27 #![allow(dead_code)]
28 #![allow(non_camel_case_types)]
29
30 use libc;
31 use std::ascii::AsciiExt;
32 use std::c_str::ToCStr;
33 use std::cell::{RefCell, Cell};
34 use std::collections::HashMap;
35 use std::fmt;
36 use std::slice;
37 use std::str;
38
39 use html::toc::TocBuilder;
40 use html::highlight;
41 use html::escape::Escape;
42 use test;
43
44 /// A unit struct which has the `fmt::Show` trait implemented. When
45 /// formatted, this struct will emit the HTML corresponding to the rendered
46 /// version of the contained markdown string.
47 pub struct Markdown<'a>(pub &'a str);
48 /// A unit struct like `Markdown`, that renders the markdown with a
49 /// table of contents.
50 pub struct MarkdownWithToc<'a>(pub &'a str);
51
52 const DEF_OUNIT: libc::size_t = 64;
53 const HOEDOWN_EXT_NO_INTRA_EMPHASIS: libc::c_uint = 1 << 10;
54 const HOEDOWN_EXT_TABLES: libc::c_uint = 1 << 0;
55 const HOEDOWN_EXT_FENCED_CODE: libc::c_uint = 1 << 1;
56 const HOEDOWN_EXT_AUTOLINK: libc::c_uint = 1 << 3;
57 const HOEDOWN_EXT_STRIKETHROUGH: libc::c_uint = 1 << 4;
58 const HOEDOWN_EXT_SUPERSCRIPT: libc::c_uint = 1 << 8;
59 const HOEDOWN_EXT_FOOTNOTES: libc::c_uint = 1 << 2;
60
61 const HOEDOWN_EXTENSIONS: libc::c_uint =
62     HOEDOWN_EXT_NO_INTRA_EMPHASIS | HOEDOWN_EXT_TABLES |
63     HOEDOWN_EXT_FENCED_CODE | HOEDOWN_EXT_AUTOLINK |
64     HOEDOWN_EXT_STRIKETHROUGH | HOEDOWN_EXT_SUPERSCRIPT |
65     HOEDOWN_EXT_FOOTNOTES;
66
67 type hoedown_document = libc::c_void;  // this is opaque to us
68
69 type blockcodefn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
70                                  *const hoedown_buffer, *mut libc::c_void);
71
72 type headerfn = extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
73                               libc::c_int, *mut libc::c_void);
74
75 #[repr(C)]
76 struct hoedown_renderer {
77     opaque: *mut hoedown_html_renderer_state,
78     blockcode: Option<blockcodefn>,
79     blockquote: Option<extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
80                                      *mut libc::c_void)>,
81     blockhtml: Option<extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
82                                     *mut libc::c_void)>,
83     header: Option<headerfn>,
84     other: [libc::size_t; 28],
85 }
86
87 #[repr(C)]
88 struct hoedown_html_renderer_state {
89     opaque: *mut libc::c_void,
90     toc_data: html_toc_data,
91     flags: libc::c_uint,
92     link_attributes: Option<extern "C" fn(*mut hoedown_buffer,
93                                           *const hoedown_buffer,
94                                           *mut libc::c_void)>,
95 }
96
97 #[repr(C)]
98 struct html_toc_data {
99     header_count: libc::c_int,
100     current_level: libc::c_int,
101     level_offset: libc::c_int,
102     nesting_level: libc::c_int,
103 }
104
105 struct MyOpaque {
106     dfltblk: extern "C" fn(*mut hoedown_buffer, *const hoedown_buffer,
107                            *const hoedown_buffer, *mut libc::c_void),
108     toc_builder: Option<TocBuilder>,
109 }
110
111 #[repr(C)]
112 struct hoedown_buffer {
113     data: *const u8,
114     size: libc::size_t,
115     asize: libc::size_t,
116     unit: libc::size_t,
117 }
118
119 // hoedown FFI
120 #[link(name = "hoedown", kind = "static")]
121 extern {
122     fn hoedown_html_renderer_new(render_flags: libc::c_uint,
123                                  nesting_level: libc::c_int)
124         -> *mut hoedown_renderer;
125     fn hoedown_html_renderer_free(renderer: *mut hoedown_renderer);
126
127     fn hoedown_document_new(rndr: *mut hoedown_renderer,
128                             extensions: libc::c_uint,
129                             max_nesting: libc::size_t) -> *mut hoedown_document;
130     fn hoedown_document_render(doc: *mut hoedown_document,
131                                ob: *mut hoedown_buffer,
132                                document: *const u8,
133                                doc_size: libc::size_t);
134     fn hoedown_document_free(md: *mut hoedown_document);
135
136     fn hoedown_buffer_new(unit: libc::size_t) -> *mut hoedown_buffer;
137     fn hoedown_buffer_puts(b: *mut hoedown_buffer, c: *const libc::c_char);
138     fn hoedown_buffer_free(b: *mut hoedown_buffer);
139
140 }
141
142 /// Returns Some(code) if `s` is a line that should be stripped from
143 /// documentation but used in example code. `code` is the portion of
144 /// `s` that should be used in tests. (None for lines that should be
145 /// left as-is.)
146 fn stripped_filtered_line<'a>(s: &'a str) -> Option<&'a str> {
147     let trimmed = s.trim();
148     if trimmed.starts_with("# ") {
149         Some(trimmed.slice_from(2))
150     } else {
151         None
152     }
153 }
154
155 thread_local!(static USED_HEADER_MAP: RefCell<HashMap<String, uint>> = {
156     RefCell::new(HashMap::new())
157 });
158 thread_local!(static TEST_IDX: Cell<uint> = Cell::new(0));
159
160 thread_local!(pub static PLAYGROUND_KRATE: RefCell<Option<Option<String>>> = {
161     RefCell::new(None)
162 });
163
164 pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result {
165     extern fn block(ob: *mut hoedown_buffer, orig_text: *const hoedown_buffer,
166                     lang: *const hoedown_buffer, opaque: *mut libc::c_void) {
167         unsafe {
168             if orig_text.is_null() { return }
169
170             let opaque = opaque as *mut hoedown_html_renderer_state;
171             let my_opaque: &MyOpaque = &*((*opaque).opaque as *const MyOpaque);
172             let text = slice::from_raw_buf(&(*orig_text).data,
173                                            (*orig_text).size as uint);
174             let origtext = str::from_utf8(text).unwrap();
175             debug!("docblock: ==============\n{}\n=======", text);
176             let rendered = if lang.is_null() {
177                 false
178             } else {
179                 let rlang = slice::from_raw_buf(&(*lang).data,
180                                                 (*lang).size as uint);
181                 let rlang = str::from_utf8(rlang).unwrap();
182                 if !LangString::parse(rlang).rust {
183                     (my_opaque.dfltblk)(ob, orig_text, lang,
184                                         opaque as *mut libc::c_void);
185                     true
186                 } else {
187                     false
188                 }
189             };
190
191             let lines = origtext.lines().filter(|l| {
192                 stripped_filtered_line(*l).is_none()
193             });
194             let text = lines.collect::<Vec<&str>>().connect("\n");
195             if rendered { return }
196             PLAYGROUND_KRATE.with(|krate| {
197                 let mut s = String::new();
198                 let id = krate.borrow().as_ref().map(|krate| {
199                     let idx = TEST_IDX.with(|slot| {
200                         let i = slot.get();
201                         slot.set(i + 1);
202                         i
203                     });
204
205                     let test = origtext.lines().map(|l| {
206                         stripped_filtered_line(l).unwrap_or(l)
207                     }).collect::<Vec<&str>>().connect("\n");
208                     let krate = krate.as_ref().map(|s| s.as_slice());
209                     let test = test::maketest(test.as_slice(), krate, false, false);
210                     s.push_str(format!("<span id='rust-example-raw-{}' \
211                                          class='rusttest'>{}</span>",
212                                        idx, Escape(test.as_slice())).as_slice());
213                     format!("rust-example-rendered-{}", idx)
214                 });
215                 let id = id.as_ref().map(|a| a.as_slice());
216                 s.push_str(highlight::highlight(text.as_slice(), None, id)
217                                      .as_slice());
218                 let output = s.to_c_str();
219                 hoedown_buffer_puts(ob, output.as_ptr());
220             })
221         }
222     }
223
224     extern fn header(ob: *mut hoedown_buffer, text: *const hoedown_buffer,
225                      level: libc::c_int, opaque: *mut libc::c_void) {
226         // hoedown does this, we may as well too
227         "\n".with_c_str(|p| unsafe { hoedown_buffer_puts(ob, p) });
228
229         // Extract the text provided
230         let s = if text.is_null() {
231             "".to_string()
232         } else {
233             unsafe {
234                 String::from_raw_buf_len((*text).data, (*text).size as uint)
235             }
236         };
237
238         // Transform the contents of the header into a hyphenated string
239         let id = s.words().map(|s| s.to_ascii_lowercase())
240             .collect::<Vec<String>>().connect("-");
241
242         // This is a terrible hack working around how hoedown gives us rendered
243         // html for text rather than the raw text.
244
245         let opaque = opaque as *mut hoedown_html_renderer_state;
246         let opaque = unsafe { &mut *((*opaque).opaque as *mut MyOpaque) };
247
248         // Make sure our hyphenated ID is unique for this page
249         let id = USED_HEADER_MAP.with(|map| {
250             let id = id.replace("<code>", "").replace("</code>", "").to_string();
251             let id = match map.borrow_mut().get_mut(&id) {
252                 None => id,
253                 Some(a) => { *a += 1; format!("{}-{}", id, *a - 1) }
254             };
255             map.borrow_mut().insert(id.clone(), 1);
256             id
257         });
258
259         let sec = match opaque.toc_builder {
260             Some(ref mut builder) => {
261                 builder.push(level as u32, s.clone(), id.clone())
262             }
263             None => {""}
264         };
265
266         // Render the HTML
267         let text = format!(r##"<h{lvl} id="{id}" class='section-header'><a
268                            href="#{id}">{sec}{}</a></h{lvl}>"##,
269                            s, lvl = level, id = id,
270                            sec = if sec.len() == 0 {
271                                sec.to_string()
272                            } else {
273                                format!("{} ", sec)
274                            });
275
276         text.with_c_str(|p| unsafe { hoedown_buffer_puts(ob, p) });
277     }
278
279     reset_headers();
280
281     unsafe {
282         let ob = hoedown_buffer_new(DEF_OUNIT);
283         let renderer = hoedown_html_renderer_new(0, 0);
284         let mut opaque = MyOpaque {
285             dfltblk: (*renderer).blockcode.unwrap(),
286             toc_builder: if print_toc {Some(TocBuilder::new())} else {None}
287         };
288         (*(*renderer).opaque).opaque = &mut opaque as *mut _ as *mut libc::c_void;
289         (*renderer).blockcode = Some(block as blockcodefn);
290         (*renderer).header = Some(header as headerfn);
291
292         let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
293         hoedown_document_render(document, ob, s.as_ptr(),
294                                 s.len() as libc::size_t);
295         hoedown_document_free(document);
296
297         hoedown_html_renderer_free(renderer);
298
299         let mut ret = match opaque.toc_builder {
300             Some(b) => write!(w, "<nav id=\"TOC\">{}</nav>", b.into_toc()),
301             None => Ok(())
302         };
303
304         if ret.is_ok() {
305             let buf = slice::from_raw_buf(&(*ob).data, (*ob).size as uint);
306             ret = w.write_str(str::from_utf8(buf).unwrap());
307         }
308         hoedown_buffer_free(ob);
309         ret
310     }
311 }
312
313 pub fn find_testable_code(doc: &str, tests: &mut ::test::Collector) {
314     extern fn block(_ob: *mut hoedown_buffer,
315                     text: *const hoedown_buffer,
316                     lang: *const hoedown_buffer,
317                     opaque: *mut libc::c_void) {
318         unsafe {
319             if text.is_null() { return }
320             let block_info = if lang.is_null() {
321                 LangString::all_false()
322             } else {
323                 let lang = slice::from_raw_buf(&(*lang).data,
324                                                (*lang).size as uint);
325                 let s = str::from_utf8(lang).unwrap();
326                 LangString::parse(s)
327             };
328             if !block_info.rust { return }
329             let text = slice::from_raw_buf(&(*text).data, (*text).size as uint);
330             let opaque = opaque as *mut hoedown_html_renderer_state;
331             let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
332             let text = str::from_utf8(text).unwrap();
333             let lines = text.lines().map(|l| {
334                 stripped_filtered_line(l).unwrap_or(l)
335             });
336             let text = lines.collect::<Vec<&str>>().connect("\n");
337             tests.add_test(text.to_string(),
338                            block_info.should_fail, block_info.no_run,
339                            block_info.ignore, block_info.test_harness);
340         }
341     }
342
343     extern fn header(_ob: *mut hoedown_buffer,
344                      text: *const hoedown_buffer,
345                      level: libc::c_int, opaque: *mut libc::c_void) {
346         unsafe {
347             let opaque = opaque as *mut hoedown_html_renderer_state;
348             let tests = &mut *((*opaque).opaque as *mut ::test::Collector);
349             if text.is_null() {
350                 tests.register_header("", level as u32);
351             } else {
352                 let text = slice::from_raw_buf(&(*text).data, (*text).size as uint);
353                 let text = str::from_utf8(text).unwrap();
354                 tests.register_header(text, level as u32);
355             }
356         }
357     }
358
359     unsafe {
360         let ob = hoedown_buffer_new(DEF_OUNIT);
361         let renderer = hoedown_html_renderer_new(0, 0);
362         (*renderer).blockcode = Some(block as blockcodefn);
363         (*renderer).header = Some(header as headerfn);
364         (*(*renderer).opaque).opaque = tests as *mut _ as *mut libc::c_void;
365
366         let document = hoedown_document_new(renderer, HOEDOWN_EXTENSIONS, 16);
367         hoedown_document_render(document, ob, doc.as_ptr(),
368                                 doc.len() as libc::size_t);
369         hoedown_document_free(document);
370
371         hoedown_html_renderer_free(renderer);
372         hoedown_buffer_free(ob);
373     }
374 }
375
376 #[deriving(Eq, PartialEq, Clone, Show)]
377 struct LangString {
378     should_fail: bool,
379     no_run: bool,
380     ignore: bool,
381     rust: bool,
382     test_harness: bool,
383 }
384
385 impl LangString {
386     fn all_false() -> LangString {
387         LangString {
388             should_fail: false,
389             no_run: false,
390             ignore: false,
391             rust: true,  // NB This used to be `notrust = false`
392             test_harness: false,
393         }
394     }
395
396     fn parse(string: &str) -> LangString {
397         let mut seen_rust_tags = false;
398         let mut seen_other_tags = false;
399         let mut data = LangString::all_false();
400
401         let mut tokens = string.split(|&: c: char|
402             !(c == '_' || c == '-' || c.is_alphanumeric())
403         );
404
405         for token in tokens {
406             match token {
407                 "" => {},
408                 "should_fail" => { data.should_fail = true; seen_rust_tags = true; },
409                 "no_run" => { data.no_run = true; seen_rust_tags = true; },
410                 "ignore" => { data.ignore = true; seen_rust_tags = true; },
411                 "rust" => { data.rust = true; seen_rust_tags = true; },
412                 "test_harness" => { data.test_harness = true; seen_rust_tags = true; }
413                 _ => { seen_other_tags = true }
414             }
415         }
416
417         data.rust &= !seen_other_tags || seen_rust_tags;
418
419         data
420     }
421 }
422
423 /// By default this markdown renderer generates anchors for each header in the
424 /// rendered document. The anchor name is the contents of the header separated
425 /// by hyphens, and a task-local map is used to disambiguate among duplicate
426 /// headers (numbers are appended).
427 ///
428 /// This method will reset the local table for these headers. This is typically
429 /// used at the beginning of rendering an entire HTML page to reset from the
430 /// previous state (if any).
431 pub fn reset_headers() {
432     USED_HEADER_MAP.with(|s| s.borrow_mut().clear());
433     TEST_IDX.with(|s| s.set(0));
434 }
435
436 impl<'a> fmt::Show for Markdown<'a> {
437     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
438         let Markdown(md) = *self;
439         // This is actually common enough to special-case
440         if md.len() == 0 { return Ok(()) }
441         render(fmt, md.as_slice(), false)
442     }
443 }
444
445 impl<'a> fmt::Show for MarkdownWithToc<'a> {
446     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
447         let MarkdownWithToc(md) = *self;
448         render(fmt, md.as_slice(), true)
449     }
450 }
451
452 #[cfg(test)]
453 mod tests {
454     use super::{LangString, Markdown};
455
456     #[test]
457     fn test_lang_string_parse() {
458         fn t(s: &str,
459             should_fail: bool, no_run: bool, ignore: bool, rust: bool, test_harness: bool) {
460             assert_eq!(LangString::parse(s), LangString {
461                 should_fail: should_fail,
462                 no_run: no_run,
463                 ignore: ignore,
464                 rust: rust,
465                 test_harness: test_harness,
466             })
467         }
468
469         // marker                | should_fail | no_run | ignore | rust | test_harness
470         t("",                      false,        false,   false,   true,  false);
471         t("rust",                  false,        false,   false,   true,  false);
472         t("sh",                    false,        false,   false,   false, false);
473         t("ignore",                false,        false,   true,    true,  false);
474         t("should_fail",           true,         false,   false,   true,  false);
475         t("no_run",                false,        true,    false,   true,  false);
476         t("test_harness",          false,        false,   false,   true,  true);
477         t("{.no_run .example}",    false,        true,    false,   true,  false);
478         t("{.sh .should_fail}",    true,         false,   false,   true,  false);
479         t("{.example .rust}",      false,        false,   false,   true,  false);
480         t("{.test_harness .rust}", false,        false,   false,   true,  true);
481     }
482
483     #[test]
484     fn issue_17736() {
485         let markdown = "# title";
486         format!("{}", Markdown(markdown.as_slice()));
487     }
488 }