summaryrefslogtreecommitdiffstats
path: root/build/syntax_mapping.rs
blob: a8c79948cee7ca62718f8498710fe9f3b8857221 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
use std::{convert::Infallible, env, fs, path::Path, str::FromStr};

use anyhow::{anyhow, bail};
use indexmap::IndexMap;
use itertools::Itertools;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::Deserialize;
use serde_with::DeserializeFromStr;
use walkdir::WalkDir;

/// Known mapping targets.
///
/// Corresponds to `syntax_mapping::MappingTarget`.
#[allow(clippy::enum_variant_names)]
#[derive(Clone, Debug, Eq, PartialEq, Hash, DeserializeFromStr)]
pub enum MappingTarget {
    MapTo(String),
    MapToUnknown,
    MapExtensionToUnknown,
}
impl FromStr for MappingTarget {
    type Err = Infallible;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "MappingTarget::MapToUnknown" => Ok(Self::MapToUnknown),
            "MappingTarget::MapExtensionToUnknown" => Ok(Self::MapExtensionToUnknown),
            syntax => Ok(Self::MapTo(syntax.into())),
        }
    }
}
impl MappingTarget {
    fn codegen(&self) -> String {
        match self {
            Self::MapTo(syntax) => format!(r###"MappingTarget::MapTo(r#"{syntax}"#)"###),
            Self::MapToUnknown => "MappingTarget::MapToUnknown".into(),
            Self::MapExtensionToUnknown => "MappingTarget::MapExtensionToUnknown".into(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, DeserializeFromStr)]
/// A single matcher.
///
/// Codegen converts this into a `Lazy<Option<GlobMatcher>>`.
struct Matcher(Vec<MatcherSegment>);
/// Parse a matcher.
///
/// Note that this implementation is rather strict: it will greedily interpret
/// every valid environment variable replacement as such, then immediately
/// hard-error if it finds a '$', '{', or '}' anywhere in the remaining text
/// segments.
///
/// The reason for this strictness is I currently cannot think of a valid reason
/// why you would ever need '$', '{', or '}' as plaintext in a glob pattern.
/// Therefore any such occurrences are likely human errors.
///
/// If we later discover some edge cases, it's okay to make it more permissive.
impl FromStr for Matcher {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use MatcherSegment as Seg;
        static VAR_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"\$\{([\w\d_\-]+)\}").unwrap());

        let mut segments = vec![];
        let mut text_start = 0;
        for capture in VAR_REGEX.captures_iter(s) {
            let match_0 = capture.get(0).unwrap();

            // text before this var
            let text_end = match_0.start();
            segments.push(Seg::Text(s[text_start..text_end].into()));
            text_start = match_0.end();

            // this var
            segments.push(Seg::Env(capture.get(1).unwrap().as_str().into()));
        }
        // possible trailing text
        segments.push(Seg::Text(s[text_start..].into()));

        // cleanup empty text segments
        let non_empty_segments = segments
            .into_iter()
            .filter(|seg| match seg {
                Seg::Text(t) => !t.is_empty(),
                Seg::Env(_) => true,
            })
            .collect_vec();

        if non_empty_segments.is_empty() {
            bail!(r#"Parsed an empty matcher: "{s}""#);
        }

        if non_empty_segments.iter().any(|seg| match seg {
            Seg::Text(t) => t.contains(['$', '{', '}']),
            Seg::Env(_) => false,
        }) {
            bail!(r#"Invalid matcher: "{s}""#);
        }

        Ok(Self(non_empty_segments))
    }
}
impl Matcher {
    fn codegen(&self) -> String {
        match self.0.len() {
            0 => unreachable!("0-length matcher should never be created"),
            // if-let guard would be ideal here
            // see: https://github.com/rust-lang/rust/issues/51114
            1 if matches!(self.0[0], MatcherSegment::Text(_)) => {
                let MatcherSegment::Text(ref s) = self.0[0] else {
                    unreachable!()
                };
                format!(r###"Lazy::new(|| Some(build_matcher_fixed(r#"{s}"#)))"###)
            }
            // parser logic ensures that this case can only happen when there are dynamic segments
            _ => {
                let segs = self.0.iter().map(MatcherSegment::codegen).join(", ");
                format!(r###"Lazy::new(|| build_matcher_dynamic(&[{segs}]))"###)
            }
        }
    }
}

/// A segment in a matcher.
///
/// Corresponds to `syntax_mapping::MatcherSegment`.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum MatcherSegment {
    Text(String),
    Env(String),
}
impl MatcherSegment {
    fn codegen(&self) -> String {
        match self {
            Self::Text(s) => format!(r###"MatcherSegment::Text(r#"{s}"#)"###),
            Self::Env(s) => format!(r###"MatcherSegment::Env(r#"{s}"#)"###),
        }
    }
}

/// A struct that models a single .toml file in /src/syntax_mapping/builtins/.
#[derive(Clone, Debug, Deserialize)]
struct MappingDefModel {
    mappings: IndexMap<MappingTarget, Vec<Matcher>>,
}
impl MappingDefModel {
    fn into_mapping_list(self) -> MappingList {
        let list = self
            .mappings
            .into_iter()
            .flat_map(|(target, matchers)| {
                matchers
                    .into_iter()
                    .map(|matcher| (matcher, target.clone()))
                    .collect::<Vec<_>>()
            })
            .collect();
        MappingList(list)
    }
}

#[derive(Clone, Debug)]
struct MappingList(Vec<(Matcher, MappingTarget)>);
impl MappingList {
    fn codegen(&self) -> String {
        let array_items: Vec<_> = self
            .0
            .iter()
            .map(|(matcher, target)| {
                format!("({m}, {t})", m = matcher.codegen(), t = target.codegen())
            })
            .collect();
        let len = array_items.len();

        format!(
            "pub(crate) static BUILTIN_MAPPINGS: [(Lazy<Option<GlobMatcher>>, MappingTarget); {len}] = [\n{items}\n];",
            items = array_items.join(",\n")
        )
    }
}

fn read_all_mappings() -> anyhow::Result<MappingList> {
    let mut all_mappings = vec![];

    for entry in WalkDir::new("src/syntax_mapping/builtins")
        .sort_by_file_name()
        .into_iter()
        .map(|entry| entry.unwrap_or_else(|err| panic!("failed to visit a file: {err}")))
        .filter(|entry| {
            let path = entry.path();
            path.is_file() && path.extension().map(|ext| ext == "toml").unwrap_or(false)
        })
    {
        let toml_string = fs::read_to_string(entry.path())?;
        let mappings = toml::from_str::<MappingDefModel>(&toml_string)?.into_mapping_list();
        all_mappings.extend(mappings.0);
    }

    let duplicates = all_mappings
        .iter()
        .duplicates_by(|(matcher, _)| matcher)
        .collect_vec();
    if !duplicates.is_empty() {
        bail!("Rules with duplicate matchers found: {duplicates:?}");
    }

    Ok(MappingList(all_mappings))
}

/// Build the static syntax mappings defined in /src/syntax_mapping/builtins/
/// into a .rs source file, which is to be inserted with `include!`.
pub fn build_static_mappings() -> anyhow::Result<()> {
    println!("cargo:rerun-if-changed=src/syntax_mapping/builtins/");

    let mappings = read_all_mappings()?;

    let codegen_path = Path::new(&env::var_os("OUT_DIR").ok_or(anyhow!("OUT_DIR is unset"))?)
        .join("codegen_static_syntax_mappings.rs");

    fs::write(codegen_path, mappings.codegen())?;

    Ok(())
}