Skip to main content

ftml/parsing/rule/impls/block/blocks/
iftags.rs

1/*
2 * parsing/rule/impls/block/blocks/iftags.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
21use super::prelude::*;
22use crate::data::PageInfo;
23use crate::parsing::ElementCondition;
24
25pub const BLOCK_IFTAGS: BlockRule = BlockRule {
26    name: "block-iftags",
27    accepts_names: &["iftags"],
28    accepts_star: false,
29    accepts_score: false,
30    accepts_newlines: true,
31    parse_fn,
32};
33
34fn parse_fn<'r, 't>(
35    parser: &mut Parser<'r, 't>,
36    name: &'t str,
37    flag_star: bool,
38    flag_score: bool,
39    in_head: bool,
40) -> ParseResult<'r, 't, Elements<'t>> {
41    debug!("Parsing iftags block (name '{name}', in-head {in_head})");
42    assert!(!flag_star, "IfTags doesn't allow star flag");
43    assert!(!flag_score, "IfTags doesn't allow score flag");
44    assert_block_name(&BLOCK_IFTAGS, name);
45
46    // Parse out tag conditions
47    let conditions =
48        parser.get_head_value(&BLOCK_IFTAGS, in_head, |parser, spec| match spec {
49            Some(spec) => Ok(ElementCondition::parse(spec)),
50            None => Err(parser.make_err(ParseErrorKind::BlockMissingArguments)),
51        })?;
52
53    // Get body content, never with paragraphs
54    let (elements, errors, paragraph_safe) =
55        parser.get_body_elements(&BLOCK_IFTAGS, false)?.into();
56
57    trace!(
58        "IfTags conditions parsed (conditions length {}, elements length {})",
59        conditions.len(),
60        elements.len(),
61    );
62
63    // Return elements based on condition
64    let elements = if check_iftags(parser.page_info(), &conditions) {
65        trace!("Conditions passed, including elements");
66
67        Elements::Multiple(elements)
68    } else {
69        trace!("Conditions failed, excluding elements");
70
71        Elements::None
72    };
73
74    ok!(paragraph_safe; elements, errors)
75}
76
77pub fn check_iftags(info: &PageInfo, conditions: &[ElementCondition]) -> bool {
78    trace!("Checking iftags");
79    ElementCondition::check(conditions, &info.tags)
80}