diff options
| author | Philipp A | 2019-03-31 19:48:39 +0200 |
|---|---|---|
| committer | Philipp A | 2019-03-31 19:48:39 +0200 |
| commit | 33f1186bfb5deb0db5ae29d26daf18dbe38fd21a (patch) | |
| tree | 642197d9414ff170f5786ec61845a3f1c9e933f7 | |
| parent | 626cc2d747f198ba94bac241a872927968f50431 (diff) | |
| download | rust-rst-33f1186bfb5deb0db5ae29d26daf18dbe38fd21a.tar.bz2 | |
Implement WIP HTML rendering
| -rw-r--r-- | src/bin.rs | 19 | ||||
| -rw-r--r-- | src/parser.rs | 15 | ||||
| -rw-r--r-- | src/renderer.rs | 23 | ||||
| -rw-r--r-- | src/renderer/html.rs | 299 | ||||
| -rw-r--r-- | src/target.rs | 42 |
5 files changed, 360 insertions, 38 deletions
@@ -2,6 +2,7 @@ pub mod document_tree; pub mod parser; +pub mod renderer; pub mod target; @@ -12,22 +13,24 @@ use quicli::{ prelude::{CliResult,Verbosity}, }; -use self::parser::{ - serialize_json, - serialize_xml, +use self::parser::parse; +use self::renderer::{ + render_json, + render_xml, + render_html, }; arg_enum! { #[derive(Debug)] #[allow(non_camel_case_types)] - enum Format { json, xml } + enum Format { json, xml, html } } #[derive(Debug, StructOpt)] #[structopt(raw(setting = "structopt::clap::AppSettings::ColoredHelp"))] struct Cli { #[structopt( - long = "format", short = "f", default_value = "json", // xml is pretty defunct… + long = "format", short = "f", default_value = "html", // xml is pretty defunct… raw(possible_values = "&Format::variants()", case_insensitive = "true"), )] format: Format, @@ -41,10 +44,12 @@ fn main() -> CliResult { args.verbosity.setup_env_logger("rst")?; let content = read_file(args.file)?; + let document = parse(&content)?; let stdout = std::io::stdout(); match args.format { - Format::json => serialize_json(&content, stdout)?, - Format::xml => serialize_xml (&content, stdout)?, + Format::json => render_json(&document, stdout)?, + Format::xml => render_xml (&document, stdout)?, + Format::html => render_html(&document, stdout)?, } Ok(()) } diff --git a/src/parser.rs b/src/parser.rs index 42ca410..89e6827 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -5,8 +5,6 @@ mod pair_ext_parse; #[cfg(test)] pub mod tests; -use std::io::Write; - use failure::Error; use pest::Parser; @@ -21,16 +19,3 @@ pub fn parse(source: &str) -> Result<Document, Error> { let pairs = RstParser::parse(Rule::document, source)?; convert_document(pairs) } - - -pub fn serialize_json<W>(source: &str, stream: W) -> Result<(), Error> where W: Write { - let parsed = parse(source)?; - serde_json::to_writer(stream, &parsed)?; - Ok(()) -} - -pub fn serialize_xml<W>(source: &str, stream: W) -> Result<(), Error> where W: Write { - let parsed = parse(source)?; - serde_xml_rs::to_writer(stream, &parsed).map_err(failure::SyncFailure::new)?; - Ok(()) -} diff --git a/src/renderer.rs b/src/renderer.rs index 0b13441..9e51eb4 100644 --- a/src/renderer.rs +++ b/src/renderer.rs @@ -1 +1,22 @@ -pub static FOOTNOTE_SYMBOLS: [char; 10] = ['*', '†', '‡', '§', '¶', '#', '♠', '♥', '♦', '♣']; +mod html; + + +use std::io::Write; + +use failure::Error; + +use crate::document_tree::Document; + + +pub fn render_json<W>(document: &Document, stream: W) -> Result<(), Error> where W: Write { + serde_json::to_writer(stream, &document)?; + Ok(()) +} + +pub fn render_xml<W>(document: &Document, stream: W) -> Result<(), Error> where W: Write { + serde_xml_rs::to_writer(stream, &document).map_err(failure::SyncFailure::new)?; + Ok(()) +} + +pub use html::render_html; + diff --git a/src/renderer/html.rs b/src/renderer/html.rs new file mode 100644 index 0000000..c4080f6 --- /dev/null +++ b/src/renderer/html.rs @@ -0,0 +1,299 @@ +use std::io::Write; + +use failure::Error; + +use crate::document_tree::{ + Document, + HasChildren, + ExtraAttributes, + elements as e, + element_categories as c, +}; + + +static FOOTNOTE_SYMBOLS: [char; 10] = ['*', '†', '‡', '§', '¶', '#', '♠', '♥', '♦', '♣']; + +pub fn render_html<W>(document: &Document, stream: W) -> Result<(), Error> where W: Write { + let mut stream = stream; + document.render_html(stream.by_ref()) +} + +trait HTMLRender { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write; +} + +macro_rules! impl_html_render_cat {($cat:ident { $($member:ident),+ }) => { + impl HTMLRender for c::$cat { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + match self {$( + c::$cat::$member(elem) => (**elem).render_html(stream), + )+} + } + } +}} + +macro_rules! impl_html_render_simple {( $($type:ident => $tag:ident),+ ) => { $( + impl HTMLRender for e::$type { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + write!(stream, "<{}>", stringify!($tag))?; + for c in self.children() { + (*c).render_html(stream)?; + } + write!(stream, "</{}>", stringify!($tag))?; + Ok(()) + } + } +)+ }} + +macro_rules! impl_html_render_simple_nochildren {( $($type:ident => $tag:ident),+ ) => { $( + impl HTMLRender for e::$type { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + write!(stream, "<{0}></{0}>", stringify!($tag))?; + Ok(()) + } + } +)+ }} + +// Impl + +impl HTMLRender for Document { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + write!(stream, "<!doctype html><html>")?; + for c in self.children() { + (*c).render_html(stream)?; + } + write!(stream, "</html>")?; + Ok(()) + } +} + +impl_html_render_cat!(StructuralSubElement { Title, Subtitle, Decoration, Docinfo, SubStructure }); +impl_html_render_simple!(Title => h1, Subtitle => h2); + +impl HTMLRender for e::Docinfo { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // Like “YAML frontmatter” in Markdown + unimplemented!(); + } +} + +impl HTMLRender for e::Decoration { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // Header or footer + unimplemented!(); + } +} + +impl_html_render_cat!(SubStructure { Topic, Sidebar, Transition, Section, BodyElement }); +impl_html_render_simple!(Sidebar => aside, Section => section); +impl_html_render_simple_nochildren!(Transition => hr); + +impl HTMLRender for e::Topic { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // A mini section with title + unimplemented!(); + } +} + +impl_html_render_cat!(BodyElement { Paragraph, LiteralBlock, DoctestBlock, MathBlock, Rubric, SubstitutionDefinition, Comment, Pending, Target, Raw, Image, Compound, Container, BulletList, EnumeratedList, DefinitionList, FieldList, OptionList, LineBlock, BlockQuote, Admonition, Attention, Hint, Note, Caution, Danger, Error, Important, Tip, Warning, Footnote, Citation, SystemMessage, Figure, Table }); +impl_html_render_simple!(Paragraph => p, LiteralBlock => pre, MathBlock => math, Rubric => a, Compound => p, Container => div, BulletList => ul, EnumeratedList => ol, DefinitionList => dl, FieldList => dl, OptionList => pre, LineBlock => div, BlockQuote => blockquote, Admonition => aside, Attention => aside, Hint => aside, Note => aside, Caution => aside, Danger => aside, Error => aside, Important => aside, Tip => aside, Warning => aside, Figure => figure); +impl_html_render_simple_nochildren!(Image => img, Table => table); //TODO: after implementing the table, move it to elems with children + +impl HTMLRender for e::DoctestBlock { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // + unimplemented!(); + } +} + +impl HTMLRender for e::SubstitutionDefinition { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // TODO: Should those be removed after resolving them + Ok(()) + } +} + +impl HTMLRender for e::Comment { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + write!(stream, "<!--")?; + for c in self.children() { + (*c).render_html(stream)?; + } + write!(stream, "-->")?; + Ok(()) + } +} + +impl HTMLRender for e::Pending { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // Will those be resolved by the time we get here? + unimplemented!(); + } +} + +impl HTMLRender for e::Target { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // Should be resolved by now + unimplemented!(); + } +} + +impl HTMLRender for e::Raw { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + for c in self.children() { + write!(stream, "{}", c)?; + } + Ok(()) + } +} + +impl HTMLRender for e::Footnote { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + unimplemented!(); + } +} + +impl HTMLRender for e::Citation { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + unimplemented!(); + } +} + +impl HTMLRender for e::SystemMessage { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + write!(stream, "<figure><caption>System Message</caption>")?; + for c in self.children() { + (*c).render_html(stream)?; + } + write!(stream, "</figure>")?; + Ok(()) + } +} + +impl_html_render_cat!(TextOrInlineElement { String, Emphasis, Strong, Literal, Reference, FootnoteReference, CitationReference, SubstitutionReference, TitleReference, Abbreviation, Acronym, Superscript, Subscript, Inline, Problematic, Generated, Math, TargetInline, RawInline, ImageInline }); +impl_html_render_simple!(Emphasis => em, Strong => strong, Literal => code, FootnoteReference => a, CitationReference => a, TitleReference => a, Abbreviation => abbr, Acronym => acronym, Superscript => sup, Subscript => sub, Inline => span, Math => math, TargetInline => a); +impl_html_render_simple_nochildren!(ImageInline => img); + +impl HTMLRender for String { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + write!(stream, "{}", self)?; + Ok(()) + } +} + +impl HTMLRender for e::Reference { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + let extra = self.extra(); + write!(stream, "<a")?; + if let Some(ref target) = extra.refuri { + write!(stream, "href=\"{}\"", target)?; + } + write!(stream, ">")?; + if let Some(ref name) = extra.name { + write!(stream, "{}", name.0)?; + } + for c in self.children() { + (*c).render_html(stream)?; + } + write!(stream, "</a>")?; + Ok(()) + } +} + +impl HTMLRender for e::SubstitutionReference { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // Will those be resolved by the time we get here? + unimplemented!(); + } +} + +impl HTMLRender for e::Problematic { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // Broken inline markup leads to insertion of this in docutils + unimplemented!(); + } +} + +impl HTMLRender for e::Generated { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // Section numbers and so on + unimplemented!(); + } +} + +impl HTMLRender for e::RawInline { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + for c in self.children() { + write!(stream, "{}", c)?; + } + Ok(()) + } +} + + +//--------------\\ +//Content Models\\ +//--------------\\ + +impl_html_render_cat!(SubTopic { Title, BodyElement }); +impl_html_render_cat!(SubSidebar { Topic, Title, Subtitle, BodyElement }); +impl_html_render_simple!(ListItem => li); + +impl HTMLRender for e::DefinitionListItem { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // Term→dt, Definition→dd, Classifier→??? + unimplemented!(); + } +} + +impl HTMLRender for e::Field { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // FieldName→dt, FieldBody→dd + unimplemented!(); + } +} + +impl HTMLRender for e::OptionListItem { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + // OptionGroup→dt(s), Description→dd + unimplemented!(); + } +} + +impl_html_render_cat!(SubLineBlock { LineBlock, Line }); + +impl HTMLRender for e::Line { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + for c in self.children() { + (*c).render_html(stream)?; + } + write!(stream, "<br>")?; + Ok(()) + } +} + +impl_html_render_cat!(SubBlockQuote { Attribution, BodyElement }); +impl_html_render_simple!(Attribution => cite); //TODO: correct? + +impl_html_render_cat!(SubFigure { Caption, Legend, BodyElement }); +impl_html_render_simple!(Caption => caption); + +impl HTMLRender for e::Legend { + fn render_html<W>(&self, stream: &mut W) -> Result<(), Error> where W: Write { + unimplemented!(); + } +} + +//------------\\ +//Things to do\\ +//------------\\ + +//TODO: prettyprint option list +//TODO: render admonitions: Admonition, Attention, Hint, Note, Caution, Danger, Error, Important, Tip, Warning +//TODO: properly render tables + +//TODO: add reference target: Reference, FootnoteReference, CitationReference, TitleReference +//TODO: add title: Abbr, Acronym +//TODO: convert math, set display attr +//TODO: add id: Rubric, Target, TargetInline +//TODO: add src: Image, ImageInline diff --git a/src/target.rs b/src/target.rs index 81ff925..d36a2f5 100644 --- a/src/target.rs +++ b/src/target.rs @@ -1,4 +1,5 @@ use std::path::PathBuf; +use std::fmt; use std::str::FromStr; use std::string::ParseError; @@ -9,32 +10,43 @@ use serde_derive::Serialize; #[derive(Debug,PartialEq,Serialize)] #[serde(untagged)] pub enum Target { - #[serde(serialize_with = "serialize_url")] - Url(Url), - Path(PathBuf), + #[serde(serialize_with = "serialize_url")] + Url(Url), + Path(PathBuf), } impl From<Url> for Target { - fn from(url: Url) -> Self { - Target::Url(url) - } + fn from(url: Url) -> Self { + Target::Url(url) + } } impl From<PathBuf> for Target { - fn from(path: PathBuf) -> Self { - Target::Path(path) - } + fn from(path: PathBuf) -> Self { + Target::Path(path) + } +} + + +impl fmt::Display for Target { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use Target::*; + match *self { + Url (ref url) => write!(f, "{}", url), + Path(ref path) => write!(f, "{}", path.display()), + } + } } impl FromStr for Target { - type Err = ParseError; + type Err = ParseError; fn from_str(input: &str) -> Result<Self, Self::Err> { - Ok(match Url::parse(input) { - Ok(url) => url.into(), - Err(_) => PathBuf::from(input.trim()).into(), - }) - } + Ok(match Url::parse(input) { + Ok(url) => url.into(), + Err(_) => PathBuf::from(input.trim()).into(), + }) + } } |
