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.

352 lines
12KB

  1. use pest::Parser;
  2. use pest::iterators::Pair;
  3. use tera::{Tera, Map, Context, Value, to_value};
  4. use errors::{Result, ResultExt};
  5. use config::Config;
  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>, tera: &Tera, config: &Config, body: Option<&str>) -> Result<String> {
  76. let mut context = Context::new();
  77. for (key, value) in args.iter() {
  78. 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. context.insert("body", b.trim_right());
  83. }
  84. context.insert("config", config);
  85. let tpl_name = format!("shortcodes/{}.html", name);
  86. tera.render(&tpl_name, &context).chain_err(|| format!("Failed to render {} shortcode", name))
  87. }
  88. pub fn render_shortcodes(content: &str, tera: &Tera, config: &Config) -> Result<String> {
  89. let mut res = String::with_capacity(content.len());
  90. let mut pairs = match ContentParser::parse(Rule::page, content) {
  91. Ok(p) => p,
  92. Err(e) => {
  93. let fancy_e = e.renamed_rules(|rule| {
  94. match *rule {
  95. Rule::int => "an integer".to_string(),
  96. Rule::float => "a float".to_string(),
  97. Rule::string => "a string".to_string(),
  98. Rule::literal => "a literal (int, float, string, bool)".to_string(),
  99. Rule::array => "an array".to_string(),
  100. Rule::kwarg => "a keyword argument".to_string(),
  101. Rule::ident => "an identifier".to_string(),
  102. Rule::inline_shortcode => "an inline shortcode".to_string(),
  103. Rule::ignored_inline_shortcode => "an ignored inline shortcode".to_string(),
  104. Rule::sc_body_start => "the start of a shortcode".to_string(),
  105. Rule::ignored_sc_body_start => "the start of an ignored shortcode".to_string(),
  106. Rule::text => "some text".to_string(),
  107. _ => format!("TODO error: {:?}", rule).to_string(),
  108. }
  109. });
  110. bail!("{}", fancy_e);
  111. },
  112. };
  113. // We have at least a `page` pair
  114. for p in pairs.next().unwrap().into_inner() {
  115. match p.as_rule() {
  116. Rule::text | Rule::text_in_ignored_body_sc | Rule::text_in_body_sc => res.push_str(p.into_span().as_str()),
  117. Rule::inline_shortcode => {
  118. let (name, args) = parse_shortcode_call(p);
  119. res.push_str(&render_shortcode(name, args, tera, config, None)?);
  120. },
  121. Rule::shortcode_with_body => {
  122. let mut inner = p.into_inner();
  123. // 3 items in inner: call, body, end
  124. // we don't care about the closing tag
  125. let (name, args) = parse_shortcode_call(inner.next().unwrap());
  126. let body = inner.next().unwrap().into_span().as_str();
  127. res.push_str(&render_shortcode(name, args, tera, config, Some(body))?);
  128. },
  129. Rule::ignored_inline_shortcode => {
  130. res.push_str(
  131. &p.into_span().as_str()
  132. .replacen("{{/*", "{{", 1)
  133. .replacen("*/}}", "}}", 1)
  134. );
  135. },
  136. Rule::ignored_shortcode_with_body => {
  137. for p2 in p.into_inner() {
  138. match p2.as_rule() {
  139. Rule::ignored_sc_body_start | Rule::ignored_sc_body_end => {
  140. res.push_str(
  141. &p2.into_span().as_str()
  142. .replacen("{%/*", "{%", 1)
  143. .replacen("*/%}", "%}", 1)
  144. );
  145. },
  146. Rule::text_in_ignored_body_sc => res.push_str(p2.into_span().as_str()),
  147. _ => unreachable!("Got something weird in an ignored shortcode"),
  148. }
  149. }
  150. },
  151. _ => unreachable!("unexpected page rule: {:?}", p.as_rule()),
  152. }
  153. }
  154. Ok(res)
  155. }
  156. #[cfg(test)]
  157. mod tests {
  158. use super::*;
  159. macro_rules! assert_lex_rule {
  160. ($rule: expr, $input: expr) => {
  161. let res = ContentParser::parse($rule, $input);
  162. println!("{:?}", $input);
  163. println!("{:#?}", res);
  164. if res.is_err() {
  165. println!("{}", res.unwrap_err());
  166. panic!();
  167. }
  168. assert!(res.is_ok());
  169. assert_eq!(res.unwrap().last().unwrap().into_span().end(), $input.len());
  170. };
  171. }
  172. #[test]
  173. fn lex_text() {
  174. let inputs = vec!["Hello world", "HEllo \n world", "Hello 1 2 true false 'hey'"];
  175. for i in inputs {
  176. assert_lex_rule!(Rule::text, i);
  177. }
  178. }
  179. #[test]
  180. fn lex_inline_shortcode() {
  181. let inputs = vec![
  182. "{{ youtube() }}",
  183. "{{ youtube(id=1, autoplay=true, url='hey') }}",
  184. "{{ youtube(id=1, \nautoplay=true, url='hey') }}",
  185. ];
  186. for i in inputs {
  187. assert_lex_rule!(Rule::inline_shortcode, i);
  188. }
  189. }
  190. #[test]
  191. fn lex_inline_ignored_shortcode() {
  192. let inputs = vec![
  193. "{{/* youtube() */}}",
  194. "{{/* youtube(id=1, autoplay=true, url='hey') */}}",
  195. "{{/* youtube(id=1, \nautoplay=true, \nurl='hey') */}}",
  196. ];
  197. for i in inputs {
  198. assert_lex_rule!(Rule::ignored_inline_shortcode, i);
  199. }
  200. }
  201. #[test]
  202. fn lex_shortcode_with_body() {
  203. let inputs = vec![
  204. r#"{% youtube() %}
  205. Some text
  206. {% end %}"#,
  207. r#"{% youtube(id=1,
  208. autoplay=true, url='hey') %}
  209. Some text
  210. {% end %}"#,
  211. ];
  212. for i in inputs {
  213. assert_lex_rule!(Rule::shortcode_with_body, i);
  214. }
  215. }
  216. #[test]
  217. fn lex_ignored_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::ignored_shortcode_with_body, i);
  229. }
  230. }
  231. #[test]
  232. fn lex_page() {
  233. let inputs = vec![
  234. "Some text and a shortcode `{{/* youtube() */}}`",
  235. "{{ youtube(id=1, autoplay=true, url='hey') }}",
  236. "{{ youtube(id=1, \nautoplay=true, url='hey') }} that's it",
  237. r#"
  238. This is a test
  239. {% hello() %}
  240. Body {{ var }}
  241. {% end %}
  242. "#
  243. ];
  244. for i in inputs {
  245. assert_lex_rule!(Rule::page, i);
  246. }
  247. }
  248. #[test]
  249. fn does_nothing_with_no_shortcodes() {
  250. let res = render_shortcodes("Hello World", &Tera::default(), &Config::default());
  251. assert_eq!(res.unwrap(), "Hello World");
  252. }
  253. #[test]
  254. fn can_unignore_inline_shortcode() {
  255. let res = render_shortcodes(
  256. "Hello World {{/* youtube() */}}",
  257. &Tera::default(),
  258. &Config::default(),
  259. );
  260. assert_eq!(res.unwrap(), "Hello World {{ youtube() }}");
  261. }
  262. #[test]
  263. fn can_unignore_shortcode_with_body() {
  264. let res = render_shortcodes(r#"
  265. Hello World
  266. {%/* youtube() */%}Some body {{ hello() }}{%/* end */%}"#, &Tera::default(), &Config::default());
  267. assert_eq!(res.unwrap(), "\nHello World\n{% youtube() %}Some body {{ hello() }}{% end %}");
  268. }
  269. #[test]
  270. fn can_parse_shortcode_arguments() {
  271. let inputs = vec![
  272. ("{{ youtube() }}", "youtube", Map::new()),
  273. (
  274. "{{ youtube(id=1, autoplay=true, hello='salut', float=1.2) }}",
  275. "youtube",
  276. {
  277. let mut m = Map::new();
  278. m.insert("id".to_string(), to_value(1).unwrap());
  279. m.insert("autoplay".to_string(), to_value(true).unwrap());
  280. m.insert("hello".to_string(), to_value("salut").unwrap());
  281. m.insert("float".to_string(), to_value(1.2).unwrap());
  282. m
  283. }
  284. ),
  285. (
  286. "{{ gallery(photos=['something', 'else'], fullscreen=true) }}",
  287. "gallery",
  288. {
  289. let mut m = Map::new();
  290. m.insert("photos".to_string(), to_value(["something", "else"]).unwrap());
  291. m.insert("fullscreen".to_string(), to_value(true).unwrap());
  292. m
  293. }
  294. ),
  295. ];
  296. for (i, n, a) in inputs {
  297. let mut res = ContentParser::parse(Rule::inline_shortcode, i).unwrap();
  298. let (name, args) = parse_shortcode_call(res.next().unwrap());
  299. assert_eq!(name, n);
  300. assert_eq!(args, a);
  301. }
  302. }
  303. #[test]
  304. fn can_render_inline_shortcodes() {
  305. let mut tera = Tera::default();
  306. tera.add_raw_template("shortcodes/youtube.html", "Hello {{id}}").unwrap();
  307. let res = render_shortcodes("Inline {{ youtube(id=1) }}.", &tera, &Config::default()).unwrap();
  308. assert_eq!(res, "Inline Hello 1.");
  309. }
  310. #[test]
  311. fn can_render_shortcodes_with_body() {
  312. let mut tera = Tera::default();
  313. tera.add_raw_template("shortcodes/youtube.html", "{{body}}").unwrap();
  314. let res = render_shortcodes("Body\n {% youtube() %}Hey!{% end %}", &tera, &Config::default()).unwrap();
  315. assert_eq!(res, "Body\n Hey!");
  316. }
  317. }