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.

375 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 std::path::Path;
  165. use tera::Tera;
  166. use config::Config;
  167. use front_matter::InsertAnchor;
  168. use super::*;
  169. macro_rules! assert_lex_rule {
  170. ($rule: expr, $input: expr) => {
  171. let res = ContentParser::parse($rule, $input);
  172. println!("{:?}", $input);
  173. println!("{:#?}", res);
  174. if res.is_err() {
  175. println!("{}", res.unwrap_err());
  176. panic!();
  177. }
  178. assert!(res.is_ok());
  179. assert_eq!(res.unwrap().last().unwrap().into_span().end(), $input.len());
  180. };
  181. }
  182. fn render_shortcodes(code: &str, tera: &Tera) -> String {
  183. let config = Config::default();
  184. let permalinks = HashMap::new();
  185. let context = RenderContext::new(&tera, &config, "", &permalinks, Path::new("something"), InsertAnchor::None);
  186. super::render_shortcodes(code, &context).unwrap()
  187. }
  188. #[test]
  189. fn lex_text() {
  190. let inputs = vec!["Hello world", "HEllo \n world", "Hello 1 2 true false 'hey'"];
  191. for i in inputs {
  192. assert_lex_rule!(Rule::text, i);
  193. }
  194. }
  195. #[test]
  196. fn lex_inline_shortcode() {
  197. let inputs = vec![
  198. "{{ youtube() }}",
  199. "{{ youtube(id=1, autoplay=true, url='hey') }}",
  200. "{{ youtube(id=1, \nautoplay=true, url='hey') }}",
  201. ];
  202. for i in inputs {
  203. assert_lex_rule!(Rule::inline_shortcode, i);
  204. }
  205. }
  206. #[test]
  207. fn lex_inline_ignored_shortcode() {
  208. let inputs = vec![
  209. "{{/* youtube() */}}",
  210. "{{/* youtube(id=1, autoplay=true, url='hey') */}}",
  211. "{{/* youtube(id=1, \nautoplay=true, \nurl='hey') */}}",
  212. ];
  213. for i in inputs {
  214. assert_lex_rule!(Rule::ignored_inline_shortcode, i);
  215. }
  216. }
  217. #[test]
  218. fn lex_shortcode_with_body() {
  219. let inputs = vec![
  220. r#"{% youtube() %}
  221. Some text
  222. {% end %}"#,
  223. r#"{% youtube(id=1,
  224. autoplay=true, url='hey') %}
  225. Some text
  226. {% end %}"#,
  227. ];
  228. for i in inputs {
  229. assert_lex_rule!(Rule::shortcode_with_body, i);
  230. }
  231. }
  232. #[test]
  233. fn lex_ignored_shortcode_with_body() {
  234. let inputs = vec![
  235. r#"{%/* youtube() */%}
  236. Some text
  237. {%/* end */%}"#,
  238. r#"{%/* youtube(id=1,
  239. autoplay=true, url='hey') */%}
  240. Some text
  241. {%/* end */%}"#,
  242. ];
  243. for i in inputs {
  244. assert_lex_rule!(Rule::ignored_shortcode_with_body, i);
  245. }
  246. }
  247. #[test]
  248. fn lex_page() {
  249. let inputs = vec![
  250. "Some text and a shortcode `{{/* youtube() */}}`",
  251. "{{ youtube(id=1, autoplay=true, url='hey') }}",
  252. "{{ youtube(id=1, \nautoplay=true, url='hey') }} that's it",
  253. r#"
  254. This is a test
  255. {% hello() %}
  256. Body {{ var }}
  257. {% end %}
  258. "#
  259. ];
  260. for i in inputs {
  261. assert_lex_rule!(Rule::page, i);
  262. }
  263. }
  264. #[test]
  265. fn does_nothing_with_no_shortcodes() {
  266. let res = render_shortcodes("Hello World", &Tera::default());
  267. assert_eq!(res, "Hello World");
  268. }
  269. #[test]
  270. fn can_unignore_inline_shortcode() {
  271. let res = render_shortcodes("Hello World {{/* youtube() */}}", &Tera::default());
  272. assert_eq!(res, "Hello World {{ youtube() }}");
  273. }
  274. #[test]
  275. fn can_unignore_shortcode_with_body() {
  276. let res = render_shortcodes(r#"
  277. Hello World
  278. {%/* youtube() */%}Some body {{ hello() }}{%/* end */%}"#, &Tera::default());
  279. assert_eq!(res, "\nHello World\n{% youtube() %}Some body {{ hello() }}{% end %}");
  280. }
  281. // https://github.com/Keats/gutenberg/issues/383
  282. #[test]
  283. fn unignore_shortcode_with_body_does_not_swallow_initial_whitespace() {
  284. let res = render_shortcodes(r#"
  285. Hello World
  286. {%/* youtube() */%}
  287. Some body {{ hello() }}{%/* end */%}"#, &Tera::default());
  288. assert_eq!(res, "\nHello World\n{% youtube() %}\nSome body {{ hello() }}{% end %}");
  289. }
  290. #[test]
  291. fn can_parse_shortcode_arguments() {
  292. let inputs = vec![
  293. ("{{ youtube() }}", "youtube", Map::new()),
  294. (
  295. "{{ youtube(id=1, autoplay=true, hello='salut', float=1.2) }}",
  296. "youtube",
  297. {
  298. let mut m = Map::new();
  299. m.insert("id".to_string(), to_value(1).unwrap());
  300. m.insert("autoplay".to_string(), to_value(true).unwrap());
  301. m.insert("hello".to_string(), to_value("salut").unwrap());
  302. m.insert("float".to_string(), to_value(1.2).unwrap());
  303. m
  304. }
  305. ),
  306. (
  307. "{{ gallery(photos=['something', 'else'], fullscreen=true) }}",
  308. "gallery",
  309. {
  310. let mut m = Map::new();
  311. m.insert("photos".to_string(), to_value(["something", "else"]).unwrap());
  312. m.insert("fullscreen".to_string(), to_value(true).unwrap());
  313. m
  314. }
  315. ),
  316. ];
  317. for (i, n, a) in inputs {
  318. let mut res = ContentParser::parse(Rule::inline_shortcode, i).unwrap();
  319. let (name, args) = parse_shortcode_call(res.next().unwrap());
  320. assert_eq!(name, n);
  321. assert_eq!(args, a);
  322. }
  323. }
  324. #[test]
  325. fn can_render_inline_shortcodes() {
  326. let mut tera = Tera::default();
  327. tera.add_raw_template("shortcodes/youtube.html", "Hello {{id}}").unwrap();
  328. let res = render_shortcodes("Inline {{ youtube(id=1) }}.", &tera);
  329. assert_eq!(res, "Inline Hello 1.");
  330. }
  331. #[test]
  332. fn can_render_shortcodes_with_body() {
  333. let mut tera = Tera::default();
  334. tera.add_raw_template("shortcodes/youtube.html", "{{body}}").unwrap();
  335. let res = render_shortcodes("Body\n {% youtube() %}Hey!{% end %}", &tera);
  336. assert_eq!(res, "Body\n Hey!");
  337. }
  338. }