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