feature_check/expr/parser/
p_nom.rs

1//! Parse query expressions using a Nom parser combinator.
2// SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
3// SPDX-License-Identifier: BSD-2-Clause
4
5use std::collections::HashMap;
6use std::iter;
7
8use anyhow::Context as _;
9use nom::{
10    Err as NErr, IResult, branch as nbranch,
11    bytes::complete as nbytesc,
12    character::complete as ncharc,
13    combinator as ncomb,
14    error::{Error as NError, ErrorKind as NErrorKind},
15    multi as nmulti, sequence as nseq,
16};
17
18use crate::defs::{Mode, ParseError};
19use crate::expr::{BoolOp, BoolOpKind, FeatureOp, VersionOp};
20use crate::version::{ParseError as VParseError, Version, VersionComponent};
21
22/// Utility function for building up a Nom failure error.
23#[inline]
24fn err_fail(input: &str) -> NErr<NError<&str>> {
25    NErr::Failure(NError::new(input, NErrorKind::Fail))
26}
27
28/// Make a `nom` error suitable for using as an `anyhow` error.
29fn clone_err_input(err: NErr<NError<&str>>) -> NErr<NError<String>> {
30    err.map_input(ToOwned::to_owned)
31}
32
33/// Parse the numerical part of a version component into an unsigned integer.
34///
35/// # Errors
36///
37/// Standard Nom parser errors; also, [`nom::Err::Failure`] on (hopefully impossible)
38/// failure to convert the already-validated characters to a number.
39#[inline]
40fn v_num(input: &str) -> IResult<&str, u32> {
41    let (r_input, digits) = nbytesc::take_while1(|chr: char| chr.is_ascii_digit())(input)?;
42    #[expect(clippy::map_err_ignore, reason = "it really does not matter")]
43    Ok((r_input, digits.parse::<u32>().map_err(|_| err_fail(input))?))
44}
45
46/// Parse the freeform string part of a version component into a string.
47///
48/// # Errors
49///
50/// Standard Nom parser errors; also, [`nom::Err::Failure`] on (hopefully impossible)
51/// failure to split the already-validated characters up.
52#[inline]
53fn v_rest(input: &str) -> IResult<&str, &str> {
54    let (f_input, _) = ncharc::one_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrwxyz~+")(input)?;
55    let (r_input, _) = nbytesc::take_while(|chr| {
56        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~+".contains(chr)
57    })(f_input)?;
58    Ok((
59        r_input,
60        input.strip_suffix(r_input).ok_or_else(|| err_fail(input))?,
61    ))
62}
63
64/// Parse a version component that contains a numerical part and
65/// an optional freeform one.
66///
67/// # Errors
68///
69/// Standard Nom parser errors.
70#[inline]
71fn v_comp_with_num(input: &str) -> IResult<&str, VersionComponent> {
72    let (r_input, (num, rest)) = nseq::pair(v_num, ncomb::opt(v_rest))(input)?;
73    Ok((
74        r_input,
75        VersionComponent {
76            num: Some(num),
77            rest: rest.map_or_else(String::new, str::to_owned),
78        },
79    ))
80}
81
82/// Parse a version component that only contains the freeform string part.
83///
84/// # Errors
85///
86/// Standard Nom parser errors.
87#[inline]
88fn v_comp_rest_only(input: &str) -> IResult<&str, VersionComponent> {
89    let (r_input, rest) = v_rest(input)?;
90    Ok((
91        r_input,
92        VersionComponent {
93            num: None,
94            rest: rest.to_owned(),
95        },
96    ))
97}
98
99/// Parse a dot-separated list of version components into a vector.
100///
101/// # Errors
102///
103/// Standard Nom parser errors.
104#[inline]
105fn v_components(input: &str) -> IResult<&str, Vec<VersionComponent>> {
106    let (r_input, (first, arr)) = nseq::pair(
107        nbranch::alt((v_comp_with_num, v_comp_rest_only)),
108        ncomb::opt(nmulti::many0(nseq::pair(
109            nbytesc::tag("."),
110            nbranch::alt((v_comp_with_num, v_comp_rest_only)),
111        ))),
112    )(input)?;
113    if let Some(comps) = arr {
114        Ok((
115            r_input,
116            iter::once(first)
117                .chain(comps.into_iter().map(|(_dot, comp)| comp))
118                .collect(),
119        ))
120    } else {
121        Ok((r_input, vec![first]))
122    }
123}
124
125/// Parse a version string into a [`Version`] struct.
126///
127/// # Errors
128///
129/// Standard Nom parser errors; also, [`nom::Err::Failure`] on (hopefully impossible)
130/// failure to split the already-validated characters up.
131#[inline]
132fn p_version(input: &str) -> IResult<&str, Version> {
133    let (r_input, comps) = v_components(input)?;
134    let v_chars = input.strip_suffix(r_input).ok_or_else(|| err_fail(input))?;
135    Ok((r_input, Version::new(String::from(v_chars), comps)))
136}
137
138/// Parse a version string.
139///
140/// # Errors
141///
142/// Returns an error if the version string is invalid.
143#[inline]
144pub fn parse_version(value: &str) -> Result<Version, VParseError> {
145    let (left, res) = p_version(value)
146        .map_err(clone_err_input)
147        .context("Could not parse a version string")
148        .map_err(|err| VParseError::ParseFailure(value.to_owned(), err))?;
149    if left.is_empty() {
150        Ok(res)
151    } else {
152        Err(VParseError::ParseLeftovers(value.to_owned(), left.len()))
153    }
154}
155
156/// Parse a feature name to a string slice.
157///
158/// Errors:
159///
160/// Standard Nom parser errors.
161#[inline]
162fn p_feature(input: &str) -> IResult<&str, &str> {
163    let (r_input, name) =
164        nbytesc::is_a("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-")(input)?;
165    Ok((r_input, name))
166}
167
168/// Parse a comparison operator sign ("<", ">=", etc).
169///
170/// Errors:
171///
172/// Standard Nom parser errors; also, [`nom::Err::Failure`] on (hopefully impossible)
173/// failure to convert the already-validated characters to a [`BoolOpKind`] value.
174#[inline]
175fn p_op_sign(input: &str) -> IResult<&str, BoolOpKind> {
176    let (r_input, res) = nbranch::alt((
177        nbytesc::tag(BoolOpKind::LE),
178        nbytesc::tag(BoolOpKind::LT),
179        nbytesc::tag(BoolOpKind::EQ),
180        nbytesc::tag(BoolOpKind::GE),
181        nbytesc::tag(BoolOpKind::GT),
182    ))(input)?;
183    #[expect(clippy::map_err_ignore, reason = "it really does not matter")]
184    Ok((r_input, res.parse().map_err(|_| err_fail(input))?))
185}
186
187/// Parse a comparison operator word ("lt", "ge", etc).
188///
189/// Errors:
190///
191/// Standard Nom parser errors; also, [`nom::Err::Failure`] on (hopefully impossible)
192/// failure to convert the already-validated characters to a [`BoolOpKind`] value.
193#[inline]
194fn p_op_word(input: &str) -> IResult<&str, BoolOpKind> {
195    let (r_input, res) = nbranch::alt((
196        nbytesc::tag(BoolOpKind::LT_S),
197        nbytesc::tag(BoolOpKind::LE_S),
198        nbytesc::tag(BoolOpKind::EQ_S),
199        nbytesc::tag(BoolOpKind::GE_S),
200        nbytesc::tag(BoolOpKind::GT_S),
201    ))(input)?;
202    #[expect(clippy::map_err_ignore, reason = "it really does not matter")]
203    Ok((r_input, res.parse().map_err(|_| err_fail(input))?))
204}
205
206/// Parse a comparison operator sign ("<", ">=", etc) and a version string.
207///
208/// Errors:
209///
210/// Standard Nom parser errors.
211#[inline]
212fn p_op_sign_and_version(input: &str) -> IResult<&str, (BoolOpKind, Version)> {
213    let (r_input, res) = nseq::tuple((
214        ncharc::multispace0,
215        p_op_sign,
216        ncharc::multispace0,
217        p_version,
218        ncharc::multispace0,
219    ))(input)?;
220    Ok((r_input, (res.1, res.3)))
221}
222
223/// Parse a comparison operator word ("lt", "ge", etc) and a version string.
224///
225/// Errors:
226///
227/// Standard Nom parser errors.
228#[inline]
229fn p_op_word_and_version(input: &str) -> IResult<&str, (BoolOpKind, Version)> {
230    let (r_input, res) = nseq::tuple((
231        ncharc::multispace1,
232        p_op_word,
233        ncharc::multispace1,
234        p_version,
235        ncharc::multispace0,
236    ))(input)?;
237    Ok((r_input, (res.1, res.3)))
238}
239
240/// Parse a comparison operator ("<", "ge", etc) and a version string.
241///
242/// # Errors
243///
244/// Standard Nom parser errors.
245#[inline]
246fn p_op_and_version(input: &str) -> IResult<&str, (BoolOpKind, Version)> {
247    nbranch::alt((p_op_sign_and_version, p_op_word_and_version))(input)
248}
249
250/// Parse a single feature name or a simple expression.
251///
252/// Errors:
253///
254/// Standard Nom parser errors.
255#[inline]
256fn p_expr(input: &str) -> IResult<&str, Mode> {
257    let (r_input, (feature, op_ver)) = nseq::pair(p_feature, ncomb::opt(p_op_and_version))(input)?;
258    if let Some((op, ver)) = op_ver {
259        Ok((
260            r_input,
261            Mode::Simple(Box::new(BoolOp::new(
262                op,
263                Box::new(FeatureOp::new(feature)),
264                Box::new(VersionOp::from_version(ver)),
265            ))),
266        ))
267    } else {
268        Ok((r_input, Mode::Single(Box::new(FeatureOp::new(feature)))))
269    }
270}
271
272/// Parse a single `feature[=version]` pair with a "1.0" version default.
273///
274/// # Errors
275///
276/// Standard Nom parser errors; also, [`nom::Err::Failure`] on (hopefully impossible)
277/// failure to convert a "1.0" string to a [`Version`] struct.
278#[inline]
279fn p_feature_version(input: &str) -> IResult<&str, (String, Version)> {
280    let (r_input, (feature, version)) = nseq::pair(
281        p_feature,
282        ncomb::opt(nseq::pair(nbytesc::tag("="), p_version)),
283    )(input)?;
284    #[expect(clippy::map_err_ignore, reason = "it really does not matter")]
285    Ok((
286        r_input,
287        (
288            feature.to_owned(),
289            version.map_or_else(
290                || parse_version("1.0").map_err(|_| err_fail(input)),
291                |(_, ver)| Ok(ver),
292            )?,
293        ),
294    ))
295}
296
297/// Parse a `feature=[version] feature[=version]...` line into a map.
298///
299/// # Errors
300///
301/// Standard Nom parser errors.
302#[inline]
303fn p_features_line(input: &str) -> IResult<&str, HashMap<String, Version>> {
304    let (r_input, (_, first, rest, _)) = nseq::tuple((
305        ncharc::multispace0,
306        p_feature_version,
307        nmulti::many0(nseq::pair(ncharc::multispace1, p_feature_version)),
308        ncharc::multispace0,
309    ))(input)?;
310    Ok((
311        r_input,
312        iter::once(first)
313            .chain(rest.into_iter().map(|(_, pair)| pair))
314            .collect(),
315    ))
316}
317
318/// Parse a feature name or a "feature op version" expression.
319///
320/// # Errors
321///
322/// Returns an error if the expression is invalid.
323#[inline]
324pub fn parse_expr(expr: &str) -> Result<Mode, ParseError> {
325    let (left, mode) = p_expr(expr)
326        .map_err(clone_err_input)
327        .context("Could not parse a test expression")
328        .map_err(|err| ParseError::ParseFailure(expr.to_owned(), err))?;
329    if left.is_empty() {
330        Ok(mode)
331    } else {
332        Err(ParseError::ParseLeftovers(expr.to_owned(), left.len()))
333    }
334}
335
336/// Parse a line of `feature[=version]` pairs.
337///
338/// # Errors
339///
340/// Returns an error if the feature names or version strings are invalid.
341#[inline]
342pub fn parse_features_line(line: &str) -> Result<HashMap<String, Version>, ParseError> {
343    let (left, res) = p_features_line(line)
344        .map_err(clone_err_input)
345        .context("Could not parse the program's features line")
346        .map_err(|err| ParseError::ParseFailure(line.to_owned(), err))?;
347    if left.is_empty() {
348        Ok(res)
349    } else {
350        Err(ParseError::ParseLeftovers(line.to_owned(), left.len()))
351    }
352}