ftml/includes/parse.rs
1/*
2 * includes/parse.rs
3 *
4 * ftml - Library to parse Wikidot text
5 * Copyright (C) 2019-2026 Wikijump Team
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16 *
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21//! This module provides functions to parse strings into [`IncludeRef`]s
22
23mod parser {
24 // Since pest generates some code that clippy doesn't like
25 #![allow(clippy::empty_docs)]
26
27 #[derive(Parser, Debug)]
28 #[grammar = "includes/grammar.pest"]
29 pub struct IncludeParser;
30}
31
32use self::parser::*;
33use super::IncludeRef;
34use crate::data::{PageRef, PageRefParseError};
35use pest::Parser;
36use pest::iterators::Pairs;
37use std::borrow::Cow;
38use std::collections::HashMap;
39
40/// Parses a single include block in the text.
41///
42/// # Arguments
43/// The "start" argument is the index at which the include block starts.
44/// It does not necessarily relate to the index of the include within the text str.
45///
46/// # Return values
47/// Returns a tuple of an [`IncludeRef`] that represents the included text and a usize that
48/// represents the end index of the include block, such that start..end covers the full include
49/// block (before the include goes through).
50pub fn parse_include_block<'t>(
51 text: &'t str,
52 start: usize,
53) -> Result<(IncludeRef<'t>, usize), IncludeParseError> {
54 match IncludeParser::parse(Rule::include, &text[start..]) {
55 Ok(mut pairs) => {
56 // Extract inner pairs
57 // These actually make up the include block's tokens
58 let first = pairs.next().expect("No pairs returned on successful parse");
59 let span = first.as_span();
60
61 debug!("Parsed include block");
62
63 // Convert into an IncludeRef
64 let include = process_pairs(first.into_inner())?;
65
66 // Adjust offset and return
67 Ok((include, start + span.end()))
68 }
69 Err(error) => {
70 warn!("Include block was invalid: {error}");
71 Err(IncludeParseError)
72 }
73 }
74}
75
76/// Creates an [`IncludeRef`] out of pest [`Pairs`].
77fn process_pairs(mut pairs: Pairs<Rule>) -> Result<IncludeRef, IncludeParseError> {
78 let page_raw = pairs.next().ok_or(IncludeParseError)?.as_str();
79 let page_ref = PageRef::parse(page_raw)?;
80
81 trace!("Got page for include {page_ref:?}");
82 let mut arguments = HashMap::new();
83 let mut var_reference = String::new();
84
85 for pair in pairs {
86 debug_assert_eq!(pair.as_rule(), Rule::argument);
87
88 let (key, value) = {
89 let mut argument_pairs = pair.into_inner();
90
91 let key = argument_pairs
92 .next()
93 .expect("Argument pairs terminated early")
94 .as_str();
95
96 let value = argument_pairs
97 .next()
98 .expect("Argument pairs terminated early")
99 .as_str();
100
101 (key, value)
102 };
103
104 trace!("Adding argument for include (key '{key}', value '{value}')");
105
106 // In Wikidot, the first argument takes precedence.
107 //
108 // However, with nested includes, you can set a fallback
109 // by making the first argument its corresponding value.
110 //
111 // For instance, if we're in `component:test`:
112 // ```
113 // [[include component:test-backend
114 // width={$width} |
115 // width=300px
116 // ]]
117 // ```
118
119 var_reference.clear();
120 str_write!(var_reference, "{{${key}}}");
121
122 if !arguments.contains_key(key) && value != var_reference {
123 let key = Cow::Borrowed(key);
124 let value = Cow::Borrowed(value);
125
126 arguments.insert(key, value);
127 }
128 }
129
130 Ok(IncludeRef::new(page_ref, arguments))
131}
132
133#[derive(Debug, PartialEq, Eq)]
134pub struct IncludeParseError;
135
136impl From<PageRefParseError> for IncludeParseError {
137 #[inline]
138 fn from(_: PageRefParseError) -> Self {
139 IncludeParseError
140 }
141}