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
/*
 * SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
 * SPDX-License-Identifier: BSD-2-Clause
 */
//! Common definitions for the feature-check crate's modules.

use std::collections::HashMap;
use std::fmt::Debug;

use anyhow::Error as AnyError;
use thiserror::Error;

use crate::version::Version;

/// The default option to pass to a program to obtain the list of features.
pub const DEFAULT_OPTION_NAME: &str = "--features";

/// The default prefix to look for in the lines output by the program.
pub const DEFAULT_PREFIX: &str = "Features: ";

/// The result of evaluating either a single term or the whole expression.
#[derive(Debug)]
#[non_exhaustive]
pub enum CalcResult {
    /// No value, e.g. the queried feature is not present.
    Null,
    /// A boolean value, usually for the whole expression.
    Bool(bool),
    /// A feature's obtained version.
    Version(Version),
}

/// An object that may be evaluated and provide a result.
pub trait Calculable: Debug {
    /// Get the value of the evaluated term or expression as applied to
    /// the list of features obtained for the program.
    ///
    /// # Errors
    ///
    /// Will propagate errors from parsing strings as [`crate::version::Version`] objects.
    /// Will also return an error if the expression contains comparisons of
    /// objects of incompatible types (e.g. a version string and a comparison result).
    fn get_value(&self, features: &HashMap<String, Version>) -> Result<CalcResult, ParseError>;
}

/// The feature-check operating mode, usually "List".
#[derive(Debug)]
#[non_exhaustive]
pub enum Mode {
    /// Obtain the list of the program's features.
    List,
    /// Obtain the value of a single feature.
    Single(Box<dyn Calculable + 'static>),
    /// Evaluate a "feature op version" expression.
    Simple(Box<dyn Calculable + 'static>),
}

/// Runtime configuration settings for
/// the [`obtain_features`][crate::obtain::obtain_features] function.
#[derive(Debug)]
#[non_exhaustive]
pub struct Config {
    /// The option to pass to the program to query for supported features.
    pub option_name: String,
    /// The prefix to look for in the lines output by the program.
    pub prefix: String,
    /// The name or full path of the program to execute.
    pub program: String,
    /// The feature-check tool's operating mode.
    pub mode: Mode,
}

impl Default for Config {
    #[inline]
    fn default() -> Self {
        Self {
            option_name: DEFAULT_OPTION_NAME.to_owned(),
            prefix: DEFAULT_PREFIX.to_owned(),
            program: String::new(),
            mode: Mode::List,
        }
    }
}

// https://github.com/rust-lang/rust-clippy/issues/4979
#[allow(clippy::missing_const_for_fn)]
impl Config {
    /// Replace the option name to query.
    #[inline]
    #[must_use]
    pub fn with_option_name(self, option_name: String) -> Self {
        Self {
            option_name,
            ..self
        }
    }
    /// Replace the prefix to look for in the program output.
    #[inline]
    #[must_use]
    pub fn with_prefix(self, prefix: String) -> Self {
        Self { prefix, ..self }
    }
    /// Replace the name of the program to execute.
    #[inline]
    #[must_use]
    pub fn with_program(self, program: String) -> Self {
        Self { program, ..self }
    }
    /// Replace the query mode.
    #[inline]
    #[must_use]
    pub fn with_mode(self, mode: Mode) -> Self {
        Self { mode, ..self }
    }
}

/// Errors that can occur during parsing a test expression or the features line.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ParseError {
    /// The arguments to a comparison operator are of incompatible types.
    #[error("Cannot compare {0} to {1}")]
    CannotCompare(String, String),

    /// An unrecognized comparison operator was specified.
    #[error("Invalid comparison operator '{0}'")]
    InvalidComparisonOperator(String),

    /// The arguments to a comparison operator are of unexpected types.
    #[error("Don't know how to compare {0} to anything, including {1}")]
    Uncomparable(String, String),

    /// A parser failed.
    #[error("Could not parse '{0}' as a valid expression")]
    ParseFailure(String, #[source] AnyError),

    /// A parser left some bytes out.
    #[error("Could not parse '{0}' as a valid expression: {1} bytes left over")]
    ParseLeftovers(String, usize),
}

/// Errors that can occur during querying a program's features.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ObtainError {
    /// The program's output was not a valid UTF-8 string.
    #[error("Could not decode the {0} program's output as valid UTF-8")]
    DecodeOutput(String, #[source] AnyError),

    /// The program could not be executed.
    #[error("Could not execute the {0} program")]
    RunProgram(String, #[source] AnyError),

    /// A user-supplied expression could not be parsed.
    #[error("Parse error")]
    Parse(#[source] ParseError),
}

/// The result of querying a program for its supported features.
#[derive(Debug)]
#[non_exhaustive]
pub enum Obtained {
    /// The program could not be executed at all, or its output could
    /// not be parsed as a reasonable string.
    Failed(ObtainError),
    /// The program does not support being queried for features.
    NotSupported,
    /// The program's supported features were successfully parsed.
    Features(HashMap<String, Version>),
}