You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

365 lines
13KB

  1. use pest::Parser;
  2. use pest::iterators::Pair;
  3. use tera::{Map, Context, Value, to_value};
  4. use errors::{Result, ResultExt};
  5. use ::context::RenderContext;
  6. // This include forces recompiling this source file if the grammar file changes.
  7. // Uncomment it when doing changes to the .pest file
  8. const _GRAMMAR: &str = include_str!("content.pest");
  9. #[derive(Parser)]
  10. #[grammar = "content.pest"]
  11. pub struct ContentParser;
  12. fn replace_string_markers(input: &str) -> String {
  13. match input.chars().next().unwrap() {
  14. '"' => input.replace('"', "").to_string(),
  15. '\'' => input.replace('\'', "").to_string(),
  16. '`' => input.replace('`', "").to_string(),
  17. _ => unreachable!("How did you even get there"),
  18. }
  19. }
  20. fn parse_literal(pair: Pair<Rule>) -> Value {
  21. let mut val = None;
  22. for p in pair.into_inner() {
  23. match p.as_rule() {
  24. Rule::boolean => match p.as_str() {
  25. "true" => val = Some(Value::Bool(true)),
  26. "false" => val = Some(Value::Bool(false)),
  27. _ => unreachable!(),
  28. },
  29. Rule::string => val = Some(Value::String(replace_string_markers(p.as_str()))),
  30. Rule::float => {
  31. val = Some(to_value(p.as_str().parse::<f64>().unwrap()).unwrap());
  32. },
  33. Rule::int => {
  34. val = Some(to_value(p.as_str().parse::<i64>().unwrap()).unwrap());
  35. },
  36. _ => unreachable!("Unknown literal: {:?}", p)
  37. };
  38. }
  39. val.unwrap()
  40. }
  41. /// Returns (shortcode_name, kwargs)
  42. fn parse_shortcode_call(pair: Pair<Rule>) -> (String, Map<String, Value>) {
  43. let mut name = None;
  44. let mut args = Map::new();
  45. for p in pair.into_inner() {
  46. match p.as_rule() {
  47. Rule::ident => { name = Some(p.into_span().as_str().to_string()); },
  48. Rule::kwarg => {
  49. let mut arg_name = None;
  50. let mut arg_val = None;
  51. for p2 in p.into_inner() {
  52. match p2.as_rule() {
  53. Rule::ident => { arg_name = Some(p2.into_span().as_str().to_string()); },
  54. Rule::literal => { arg_val = Some(parse_literal(p2)); },
  55. Rule::array => {
  56. let mut vals = vec![];
  57. for p3 in p2.into_inner() {
  58. match p3.as_rule() {
  59. Rule::literal => vals.push(parse_literal(p3)),
  60. _ => unreachable!("Got something other than literal in an array: {:?}", p3),
  61. }
  62. }
  63. arg_val = Some(Value::Array(vals));
  64. },
  65. _ => unreachable!("Got something unexpected in a kwarg: {:?}", p2),
  66. }
  67. }
  68. args.insert(arg_name.unwrap(), arg_val.unwrap());
  69. },
  70. _ => unreachable!("Got something unexpected in a shortcode: {:?}", p)
  71. }
  72. }
  73. (name.unwrap(), args)
  74. }
  75. fn render_shortcode(name: String, args: Map<String, Value>, context: &RenderContext, body: Option<&str>) -> Result<String> {
  76. let mut tera_context = Context::new();
  77. for (key, value) in args.iter() {
  78. tera_context.insert(key, value);
  79. }
  80. if let Some(ref b) = body {
  81. // Trimming right to avoid most shortcodes with bodies ending up with a HTML new line
  82. tera_context.insert("body", b.trim_right());
  83. }
  84. tera_context.extend(context.tera_context.clone());
  85. let tpl_name = format!("shortcodes/{}.html", name);
  86. let res = context.tera
  87. .render(&tpl_name, &tera_context)
  88. .chain_err(|| format!("Failed to render {} shortcode", name))?;
  89. // We trim left every single line of a shortcode to avoid the accidental
  90. // shortcode counted as code block because of 4 spaces left padding
  91. Ok(res.lines().map(|s| s.trim_left()).collect())
  92. }
  93. pub fn render_shortcodes(content: &str, context: &RenderContext) -> Result<String> {
  94. let mut res = String::with_capacity(content.len());
  95. let mut pairs = match ContentParser::parse(Rule::page, content) {
  96. Ok(p) => p,
  97. Err(e) => {
  98. let fancy_e = e.renamed_rules(|rule| {
  99. match *rule {
  100. Rule::int => "an integer".to_string(),
  101. Rule::float => "a float".to_string(),
  102. Rule::string => "a string".to_string(),
  103. Rule::literal => "a literal (int, float, string, bool)".to_string(),
  104. Rule::array => "an array".to_string(),
  105. Rule::kwarg => "a keyword argument".to_string(),
  106. Rule::ident => "an identifier".to_string(),
  107. Rule::inline_shortcode => "an inline shortcode".to_string(),
  108. Rule::ignored_inline_shortcode => "an ignored inline shortcode".to_string(),
  109. Rule::sc_body_start => "the start of a shortcode".to_string(),
  110. Rule::ignored_sc_body_start => "the start of an ignored shortcode".to_string(),
  111. Rule::text => "some text".to_string(),
  112. _ => format!("TODO error: {:?}", rule).to_string(),
  113. }
  114. });
  115. bail!("{}", fancy_e);
  116. },
  117. };
  118. // We have at least a `page` pair
  119. for p in pairs.next().unwrap().into_inner() {
  120. match p.as_rule() {
  121. Rule::text | Rule::text_in_ignored_body_sc | Rule::text_in_body_sc => res.push_str(p.into_span().as_str()),
  122. Rule::inline_shortcode => {
  123. let (name, args) = parse_shortcode_call(p);
  124. res.push_str(&render_shortcode(name, args, context, None)?);
  125. },
  126. Rule::shortcode_with_body => {
  127. let mut inner = p.into_inner();
  128. // 3 items in inner: call, body, end
  129. // we don't care about the closing tag
  130. let (name, args) = parse_shortcode_call(inner.next().unwrap());
  131. let body = inner.next().unwrap().into_span().as_str();
  132. res.push_str(&render_shortcode(name, args, context, Some(body))?);
  133. },
  134. Rule::ignored_inline_shortcode => {
  135. res.push_str(
  136. &p.into_span().as_str()
  137. .replacen("{{/*", "{{", 1)
  138. .replacen("*/}}", "}}", 1)
  139. );
  140. },
  141. Rule::ignored_shortcode_with_body => {
  142. for p2 in p.into_inner() {
  143. match p2.as_rule() {
  144. Rule::ignored_sc_body_start | Rule::ignored_sc_body_end => {
  145. res.push_str(
  146. &p2.into_span().as_str()
  147. .replacen("{%/*", "{%", 1)
  148. .replacen("*/%}", "%}", 1)
  149. );
  150. },
  151. Rule::text_in_ignored_body_sc => res.push_str(p2.into_span().as_str()),
  152. _ => unreachable!("Got something weird in an ignored shortcode: {:?}", p2),
  153. }
  154. }
  155. },
  156. _ => unreachable!("unexpected page rule: {:?}", p.as_rule()),
  157. }
  158. }
  159. Ok(res)
  160. }
  161. #[cfg(test)]
  162. mod tests {
  163. use std::collections::HashMap;
  164. use tera::Tera;
  165. use config::Config;
  166. use front_matter::InsertAnchor;
  167. use super::*;
  168. macro_rules! assert_lex_rule {
  169. ($rule: expr, $input: expr) => {
  170. let res = ContentParser::parse($rule, $input);
  171. println!("{:?}", $input);
  172. println!("{:#?}", res);
  173. if res.is_err() {
  174. println!("{}", res.unwrap_err());
  175. panic!();
  176. }
  177. assert!(res.is_ok());
  178. assert_eq!(res.unwrap().last().unwrap().into_span().end(), $input.len());
  179. };
  180. }
  181. fn render_shortcodes(code: &str, tera: &Tera) -> String {
  182. let config = Config::default();
  183. let permalinks = HashMap::new();
  184. let context = RenderContext::new(&tera, &config, "", &permalinks, InsertAnchor::None);
  185. super::render_shortcodes(code, &context).unwrap()
  186. }
  187. #[test]
  188. fn lex_text() {
  189. let inputs = vec!["Hello world", "HEllo \n world", "Hello 1 2 true false 'hey'"];
  190. for i in inputs {
  191. assert_lex_rule!(Rule::text, i);
  192. }
  193. }
  194. #[test]
  195. fn lex_inline_shortcode() {
  196. let inputs = vec![
  197. "{{ youtube() }}",
  198. "{{ youtube(id=1, autoplay=true, url='hey') }}",
  199. "{{ youtube(id=1, \nautoplay=true, url='hey') }}",
  200. ];
  201. for i in inputs {
  202. assert_lex_rule!(Rule::inline_shortcode, i);
  203. }
  204. }
  205. #[test]
  206. fn lex_inline_ignored_shortcode() {
  207. let inputs = vec![
  208. "{{/* youtube() */}}",
  209. "{{/* youtube(id=1, autoplay=true, url='hey') */}}",
  210. "{{/* youtube(id=1, \nautoplay=true, \nurl='hey') */}}",
  211. ];
  212. for i in inputs {
  213. assert_lex_rule!(Rule::ignored_inline_shortcode, i);
  214. }
  215. }
  216. #[test]
  217. fn lex_shortcode_with_body() {
  218. let inputs = vec![
  219. r#"{% youtube() %}
  220. Some text
  221. {% end %}"#,
  222. r#"{% youtube(id=1,
  223. autoplay=true, url='hey') %}
  224. Some text
  225. {% end %}"#,
  226. ];
  227. for i in inputs {
  228. assert_lex_rule!(Rule::shortcode_with_body, i);
  229. }
  230. }
  231. #[test]
  232. fn lex_ignored_shortcode_with_body() {
  233. let inputs = vec![
  234. r#"{%/* youtube() */%}
  235. Some text
  236. {%/* end */%}"#,
  237. r#"{%/* youtube(id=1,
  238. autoplay=true, url='hey') */%}
  239. Some text
  240. {%/* end */%}"#,
  241. ];
  242. for i in inputs {
  243. assert_lex_rule!(Rule::ignored_shortcode_with_body, i);
  244. }
  245. }
  246. #[test]
  247. fn lex_page() {
  248. let inputs = vec![
  249. "Some text and a shortcode `{{/* youtube() */}}`",
  250. "{{ youtube(id=1, autoplay=true, url='hey') }}",
  251. "{{ youtube(id=1, \nautoplay=true, url='hey') }} that's it",
  252. r#"
  253. This is a test
  254. {% hello() %}
  255. Body {{ var }}
  256. {% end %}
  257. "#
  258. ];
  259. for i in inputs {
  260. assert_lex_rule!(Rule::page, i);
  261. }
  262. }
  263. #[test]
  264. fn does_nothing_with_no_shortcodes() {
  265. let res = render_shortcodes("Hello World", &Tera::default());
  266. assert_eq!(res, "Hello World");
  267. }
  268. #[test]
  269. fn can_unignore_inline_shortcode() {
  270. let res = render_shortcodes("Hello World {{/* youtube() */}}", &Tera::default());
  271. assert_eq!(res, "Hello World {{ youtube() }}");
  272. }
  273. #[test]
  274. fn can_unignore_shortcode_with_body() {
  275. let res = render_shortcodes(r#"
  276. Hello World
  277. {%/* youtube() */%}Some body {{ hello() }}{%/* end */%}"#, &Tera::default());
  278. assert_eq!(res, "\nHello World\n{% youtube() %}Some body {{ hello() }}{% end %}");
  279. }
  280. #[test]
  281. fn can_parse_shortcode_arguments() {
  282. let inputs = vec![
  283. ("{{ youtube() }}", "youtube", Map::new()),
  284. (
  285. "{{ youtube(id=1, autoplay=true, hello='salut', float=1.2) }}",
  286. "youtube",
  287. {
  288. let mut m = Map::new();
  289. m.insert("id".to_string(), to_value(1).unwrap());
  290. m.insert("autoplay".to_string(), to_value(true).unwrap());
  291. m.insert("hello".to_string(), to_value("salut").unwrap());
  292. m.insert("float".to_string(), to_value(1.2).unwrap());
  293. m
  294. }
  295. ),
  296. (
  297. "{{ gallery(photos=['something', 'else'], fullscreen=true) }}",
  298. "gallery",
  299. {
  300. let mut m = Map::new();
  301. m.insert("photos".to_string(), to_value(["something", "else"]).unwrap());
  302. m.insert("fullscreen".to_string(), to_value(true).unwrap());
  303. m
  304. }
  305. ),
  306. ];
  307. for (i, n, a) in inputs {
  308. let mut res = ContentParser::parse(Rule::inline_shortcode, i).unwrap();
  309. let (name, args) = parse_shortcode_call(res.next().unwrap());
  310. assert_eq!(name, n);
  311. assert_eq!(args, a);
  312. }
  313. }
  314. #[test]
  315. fn can_render_inline_shortcodes() {
  316. let mut tera = Tera::default();
  317. tera.add_raw_template("shortcodes/youtube.html", "Hello {{id}}").unwrap();
  318. let res = render_shortcodes("Inline {{ youtube(id=1) }}.", &tera);
  319. assert_eq!(res, "Inline Hello 1.");
  320. }
  321. #[test]
  322. fn can_render_shortcodes_with_body() {
  323. let mut tera = Tera::default();
  324. tera.add_raw_template("shortcodes/youtube.html", "{{body}}").unwrap();
  325. let res = render_shortcodes("Body\n {% youtube() %}Hey!{% end %}", &tera);
  326. assert_eq!(res, "Body\n Hey!");
  327. }
  328. }