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