Skip to main content

cfg_expr/
expr.rs

1pub mod lexer;
2mod parser;
3
4use smallvec::SmallVec;
5use std::ops::Range;
6
7/// A predicate function, used to combine 1 or more predicates
8/// into a single value
9#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
10pub enum Func {
11    /// `not()` with a configuration predicate. It is true if its predicate
12    /// is false and false if its predicate is true.
13    Not,
14    /// `all()` with a comma separated list of configuration predicates. It
15    /// is false if at least one predicate is false. If there are no predicates,
16    /// it is true.
17    ///
18    /// The associated `usize` is the number of predicates inside the `all()`.
19    All(usize),
20    /// `any()` with a comma separated list of configuration predicates. It
21    /// is true if at least one predicate is true. If there are no predicates,
22    /// it is false.
23    ///
24    /// The associated `usize` is the number of predicates inside the `any()`.
25    Any(usize),
26}
27
28use crate::targets as targ;
29
30/// All predicates that pertains to a target, except for `target_feature`
31#[derive(Clone, PartialEq, Eq, Debug)]
32pub enum TargetPredicate {
33    /// [target_abi](https://github.com/rust-lang/rust/issues/80970)
34    Abi(targ::Abi),
35    /// [target_arch](https://doc.rust-lang.org/reference/conditional-compilation.html#target_arch)
36    Arch(targ::Arch),
37    /// [target_endian](https://doc.rust-lang.org/reference/conditional-compilation.html#target_endian)
38    Endian(targ::Endian),
39    /// [target_env](https://doc.rust-lang.org/reference/conditional-compilation.html#target_env)
40    Env(targ::Env),
41    /// [target_family](https://doc.rust-lang.org/reference/conditional-compilation.html#target_family)
42    /// This also applies to the bare [`unix` and `windows`](https://doc.rust-lang.org/reference/conditional-compilation.html#unix-and-windows)
43    /// predicates.
44    Family(targ::Family),
45    /// [target_has_atomic](https://doc.rust-lang.org/reference/conditional-compilation.html#target_has_atomic).
46    HasAtomic(targ::HasAtomic),
47    /// [target_os](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os)
48    Os(targ::Os),
49    /// [panic](https://doc.rust-lang.org/reference/conditional-compilation.html#panic)
50    Panic(targ::Panic),
51    /// [target_pointer_width](https://doc.rust-lang.org/reference/conditional-compilation.html#target_pointer_width)
52    PointerWidth(u8),
53    /// [target_vendor](https://doc.rust-lang.org/reference/conditional-compilation.html#target_vendor)
54    Vendor(targ::Vendor),
55}
56
57pub trait TargetMatcher {
58    fn matches(&self, tp: &TargetPredicate) -> bool;
59}
60
61impl TargetMatcher for targ::TargetInfo {
62    fn matches(&self, tp: &TargetPredicate) -> bool {
63        use TargetPredicate::{
64            Abi, Arch, Endian, Env, Family, HasAtomic, Os, Panic, PointerWidth, Vendor,
65        };
66
67        match tp {
68            // The ABI is allowed to be an empty string
69            Abi(abi) => match &self.abi {
70                Some(a) => abi == a,
71                None => abi.0.is_empty(),
72            },
73            Arch(a) => a == &self.arch,
74            Endian(end) => *end == self.endian,
75            // The environment is allowed to be an empty string
76            Env(env) => match &self.env {
77                Some(e) => env == e,
78                None => env.0.is_empty(),
79            },
80            Family(fam) => self.families.contains(fam),
81            HasAtomic(has_atomic) => self.has_atomics.contains(*has_atomic),
82            Os(os) => match &self.os {
83                Some(self_os) => os == self_os,
84                // os = "none" means it should be matched against None. Note that this is different
85                // from "env" above.
86                None => os.as_str() == "none",
87            },
88            PointerWidth(w) => *w == self.pointer_width,
89            Vendor(ven) => match &self.vendor {
90                Some(v) => ven == v,
91                None => ven == &targ::Vendor::unknown,
92            },
93            Panic(panic) => &self.panic == panic,
94        }
95    }
96}
97
98#[cfg(feature = "targets")]
99impl TargetMatcher for target_lexicon::Triple {
100    #[allow(clippy::cognitive_complexity)]
101    #[allow(clippy::match_same_arms)]
102    fn matches(&self, tp: &TargetPredicate) -> bool {
103        use TargetPredicate::{
104            Abi, Arch, Endian, Env, Family, HasAtomic, Os, Panic, PointerWidth, Vendor,
105        };
106        use target_lexicon::{
107            self as tl, Architecture as arch, ArmArchitecture, Endianness as endian,
108            Environment as env, Mips32Architecture as mips32, Mips64Architecture as mips64,
109            OperatingSystem as os,
110        };
111
112        const NUTTX: tl::Vendor = tl::Vendor::Custom(tl::CustomVendor::Static("nuttx"));
113        const RTEMS: tl::Vendor = tl::Vendor::Custom(tl::CustomVendor::Static("rtems"));
114        const WALI: tl::Vendor = tl::Vendor::Custom(tl::CustomVendor::Static("wali"));
115        const WASIP3: tl::Vendor = tl::Vendor::Custom(tl::CustomVendor::Static("wasip3"));
116        const OE: tl::Vendor = tl::Vendor::Custom(tl::CustomVendor::Static("oe"));
117
118        match tp {
119            Abi(_) => {
120                // `target_abi` is unstable. Assume false for this.
121                false
122            }
123            Arch(arch) => {
124                if arch == &targ::Arch::x86 {
125                    matches!(self.architecture, arch::X86_32(_))
126                } else if arch == &targ::Arch::wasm32 {
127                    self.architecture == arch::Wasm32 || self.architecture == arch::Asmjs
128                } else if arch == &targ::Arch::arm {
129                    matches!(self.architecture, arch::Arm(_))
130                } else if arch == &targ::Arch::bpf {
131                    self.architecture == arch::Bpfeb || self.architecture == arch::Bpfel
132                } else if arch == &targ::Arch::x86_64 {
133                    self.architecture == arch::X86_64 || self.architecture == arch::X86_64h
134                } else if arch == &targ::Arch::mips32r6 {
135                    matches!(
136                        self.architecture,
137                        arch::Mips32(mips32::Mipsisa32r6 | mips32::Mipsisa32r6el)
138                    )
139                } else if arch == &targ::Arch::mips64r6 {
140                    matches!(
141                        self.architecture,
142                        arch::Mips64(mips64::Mipsisa64r6 | mips64::Mipsisa64r6el)
143                    )
144                } else if arch == &targ::Arch::amdgpu {
145                    self.architecture == arch::AmdGcn
146                } else {
147                    match arch.0.parse::<arch>() {
148                        Ok(a) => match (self.architecture, a) {
149                            (arch::Aarch64(_), arch::Aarch64(_))
150                            | (arch::Mips32(_), arch::Mips32(_))
151                            | (arch::Mips64(_), arch::Mips64(_))
152                            | (arch::Powerpc64le, arch::Powerpc64)
153                            | (arch::Riscv32(_), arch::Riscv32(_))
154                            | (arch::Riscv64(_), arch::Riscv64(_))
155                            | (arch::Sparcv9, arch::Sparc64) => true,
156                            (a, b) => a == b,
157                        },
158                        Err(_) => false,
159                    }
160                }
161            }
162            Endian(end) => match self.architecture.endianness() {
163                Ok(endian) => matches!(
164                    (end, endian),
165                    (crate::targets::Endian::little, endian::Little)
166                        | (crate::targets::Endian::big, endian::Big)
167                ),
168
169                Err(_) => false,
170            },
171            Env(env) => {
172                // The environment is implied by some operating systems
173                match self.operating_system {
174                    os::Redox => env == &targ::Env::relibc,
175                    os::VxWorks => env == &targ::Env::gnu,
176                    os::Freebsd => env.0.is_empty(),
177                    os::Netbsd => match self.architecture {
178                        arch::Arm(ArmArchitecture::Armv6 | ArmArchitecture::Armv7) => {
179                            env.0.is_empty()
180                        }
181                        _ => env.0.is_empty(),
182                    },
183                    os::None_ | os::Cloudabi | os::Hermit => match self.environment {
184                        env::LinuxKernel => env == &targ::Env::gnu,
185                        _ => env.0.is_empty(),
186                    },
187                    os::IOS(_) | os::TvOS(_) => match self.environment {
188                        env::LinuxKernel => env == &targ::Env::gnu,
189                        env::Macabi => env == &targ::Env::macabi,
190                        env::Sim => env == &targ::Env::sim,
191                        env::Unknown => env.0.is_empty() || env == &targ::Env::sim,
192                        _ => env.0.is_empty(),
193                    },
194                    os::WasiP1 => env == &targ::Env::p1,
195                    os::WasiP2 => env == &targ::Env::p2,
196                    os::Wasi => env.0.is_empty() || env == &targ::Env::p1,
197                    _ => {
198                        if env.0.is_empty() {
199                            matches!(
200                                self.environment,
201                                env::Unknown
202                                    | env::Android
203                                    | env::Softfloat
204                                    | env::Androideabi
205                                    | env::Eabi
206                                    | env::Eabihf
207                                    | env::Sim
208                                    | env::None
209                            )
210                        } else if env == &targ::Env::p3 {
211                            self.vendor == WASIP3
212                        } else {
213                            match env.0.parse::<env>() {
214                                Ok(e) => {
215                                    // Rustc shortens multiple "gnu*" environments to just "gnu"
216                                    if env == &targ::Env::gnu {
217                                        match self.environment {
218                                            env::Gnu
219                                            | env::Gnuabi64
220                                            | env::Gnueabi
221                                            | env::Gnuspe
222                                            | env::Gnux32
223                                            | env::GnuIlp32
224                                            | env::Gnueabihf
225                                            | env::GnuLlvm => true,
226                                            // Rust 1.49.0 changed all android targets to have the
227                                            // gnu environment
228                                            env::Android | env::Androideabi
229                                                if self.operating_system == os::Linux =>
230                                            {
231                                                true
232                                            }
233                                            env::Kernel => self.operating_system == os::Linux,
234                                            _ => self.architecture == arch::Avr,
235                                        }
236                                    } else if env == &targ::Env::musl {
237                                        matches!(
238                                            self.environment,
239                                            env::Musl
240                                                | env::Musleabi
241                                                | env::Musleabihf
242                                                | env::Muslabi64
243                                        )
244                                    } else if env == &targ::Env::uclibc {
245                                        matches!(
246                                            self.environment,
247                                            env::Uclibc | env::Uclibceabi | env::Uclibceabihf
248                                        )
249                                    } else if env == &targ::Env::newlib {
250                                        matches!(self.operating_system, os::Horizon | os::Espidf)
251                                            || self.vendor == RTEMS
252                                    } else {
253                                        self.environment == e
254                                    }
255                                }
256                                Err(_) => false,
257                            }
258                        }
259                    }
260                }
261            }
262            Family(fam) => {
263                match self.operating_system {
264                    os::AmdHsa
265                    | os::Bitrig
266                    | os::Cloudabi
267                    | os::Cuda
268                    | os::Hermit
269                    | os::Nebulet
270                    | os::None_
271                    | os::Uefi => false,
272                    os::Aix
273                    | os::Darwin(_)
274                    | os::Dragonfly
275                    | os::Espidf
276                    | os::Freebsd
277                    | os::Fuchsia
278                    | os::Haiku
279                    | os::Hurd
280                    | os::Illumos
281                    | os::IOS(_)
282                    | os::L4re
283                    | os::MacOSX { .. }
284                    | os::Horizon
285                    | os::Netbsd
286                    | os::Openbsd
287                    | os::Redox
288                    | os::Solaris
289                    | os::TvOS(_)
290                    | os::VisionOS(_)
291                    | os::VxWorks
292                    | os::WatchOS(_) => fam == &crate::targets::Family::unix,
293                    os::Emscripten => {
294                        match self.architecture {
295                            // asmjs, wasm32 and wasm64 are part of both the wasm and unix families
296                            arch::Asmjs | arch::Wasm32 => {
297                                fam == &crate::targets::Family::wasm
298                                    || fam == &crate::targets::Family::unix
299                            }
300                            _ => false,
301                        }
302                    }
303                    os::Unknown if self.vendor == NUTTX || self.vendor == RTEMS => {
304                        fam == &crate::targets::Family::unix
305                    }
306                    os::Unknown => {
307                        // asmjs, wasm32 and wasm64 are part of the wasm family.
308                        match self.architecture {
309                            arch::Asmjs | arch::Wasm32 | arch::Wasm64 => {
310                                fam == &crate::targets::Family::wasm
311                            }
312                            _ => false,
313                        }
314                    }
315                    os::Linux if self.vendor == WALI => {
316                        fam == &crate::targets::Family::wasm || fam == &crate::targets::Family::unix
317                    }
318                    os::Linux => {
319                        // The 'kernel' environment is treated specially as not-unix
320                        if self.environment != env::Kernel {
321                            fam == &crate::targets::Family::unix
322                        } else {
323                            false
324                        }
325                    }
326                    os::Wasi | os::WasiP1 | os::WasiP2 => fam == &crate::targets::Family::wasm,
327                    os::Windows => fam == &crate::targets::Family::windows,
328                    os::Cygwin => fam == &crate::targets::Family::unix,
329                    // I really dislike non-exhaustive :(
330                    _ => false,
331                }
332            }
333            HasAtomic(_) => {
334                // atomic support depends on both the architecture and the OS. Assume false for
335                // this.
336                false
337            }
338            Os(os) => {
339                if os == &targ::Os::wasi
340                    && (matches!(self.operating_system, os::WasiP1 | os::WasiP2)
341                        || self.vendor == WASIP3)
342                    || (os == &targ::Os::nuttx && self.vendor == NUTTX)
343                    || (os == &targ::Os::rtems && self.vendor == RTEMS)
344                {
345                    return true;
346                }
347
348                match os.0.parse::<os>() {
349                    Ok(o) => match self.environment {
350                        env::HermitKernel => os == &targ::Os::hermit,
351                        _ => self.operating_system == o,
352                    },
353                    Err(_) => {
354                        // Handle special case for darwin/macos, where the triple is
355                        // "darwin", but rustc identifies the OS as "macos"
356                        if os == &targ::Os::macos && matches!(self.operating_system, os::Darwin(_))
357                        {
358                            true
359                        } else {
360                            // For android, the os is still linux, but the environment is android
361                            os == &targ::Os::android
362                                && self.operating_system == os::Linux
363                                && (self.environment == env::Android
364                                    || self.environment == env::Androideabi)
365                        }
366                    }
367                }
368            }
369            Panic(_) => {
370                // panic support depends on the OS. Assume false for this.
371                false
372            }
373            Vendor(ven) => {
374                // Unsure why the OpenEmbedded (oe) targets don't have it as the vendor, but for now the official
375                // rust targets don't
376                if self.vendor == OE && ven == &targ::Vendor::unknown {
377                    true
378                } else {
379                    match ven.0.parse::<target_lexicon::Vendor>() {
380                        Ok(v) => {
381                            if self.vendor == v
382                                || ((self.vendor == NUTTX
383                                    || self.vendor == RTEMS
384                                    || self.vendor == WALI
385                                    || self.vendor == WASIP3)
386                                    && ven == &targ::Vendor::unknown)
387                            {
388                                true
389                            } else if let tl::Vendor::Custom(custom) = &self.vendor {
390                                matches!(custom.as_str(), "esp" | "esp32" | "esp32s2" | "esp32s3")
391                                    && (v == tl::Vendor::Espressif || v == tl::Vendor::Unknown)
392                            } else {
393                                false
394                            }
395                        }
396                        Err(_) => false,
397                    }
398                }
399            }
400            PointerWidth(pw) => {
401                // The gnux32 environment is a special case, where it has an
402                // x86_64 architecture, but a 32-bit pointer width
403                if !matches!(self.environment, env::Gnux32 | env::GnuIlp32) {
404                    *pw == match self.pointer_width() {
405                        Ok(pw) => pw.bits(),
406                        Err(_) => return false,
407                    }
408                } else {
409                    *pw == 32
410                }
411            }
412        }
413    }
414}
415
416impl TargetPredicate {
417    /// Returns true of the predicate matches the specified target
418    ///
419    /// Note that when matching against a [`target_lexicon::Triple`], the
420    /// `has_target_atomic` and `panic` predicates will _always_ return `false`.
421    ///
422    /// ```
423    /// use cfg_expr::{targets::*, expr::TargetPredicate as tp};
424    /// let win = get_builtin_target_by_triple("x86_64-pc-windows-msvc").unwrap();
425    ///
426    /// assert!(
427    ///     tp::Arch(Arch::x86_64).matches(win) &&
428    ///     tp::Endian(Endian::little).matches(win) &&
429    ///     tp::Env(Env::msvc).matches(win) &&
430    ///     tp::Family(Family::windows).matches(win) &&
431    ///     tp::Os(Os::windows).matches(win) &&
432    ///     tp::PointerWidth(64).matches(win) &&
433    ///     tp::Vendor(Vendor::pc).matches(win)
434    /// );
435    /// ```
436    pub fn matches<T>(&self, target: &T) -> bool
437    where
438        T: TargetMatcher,
439    {
440        target.matches(self)
441    }
442}
443
444#[derive(Clone, Debug)]
445pub(crate) enum Which {
446    Abi,
447    Arch,
448    Endian(targ::Endian),
449    Env,
450    Family,
451    Os,
452    HasAtomic(targ::HasAtomic),
453    Panic,
454    PointerWidth(u8),
455    Vendor,
456}
457
458#[derive(Clone, Debug)]
459pub(crate) struct InnerTarget {
460    which: Which,
461    span: Option<Range<usize>>,
462}
463
464/// A single predicate in a `cfg()` expression
465#[derive(Debug, PartialEq, Eq)]
466pub enum Predicate<'a> {
467    /// A target predicate, with the `target_` prefix
468    Target(TargetPredicate),
469    /// Whether rustc's test harness is [enabled](https://doc.rust-lang.org/reference/conditional-compilation.html#test)
470    Test,
471    /// [Enabled](https://doc.rust-lang.org/reference/conditional-compilation.html#debug_assertions)
472    /// when compiling without optimizations.
473    DebugAssertions,
474    /// [Enabled](https://doc.rust-lang.org/reference/conditional-compilation.html#proc_macro) for
475    /// crates of the `proc_macro` type.
476    ProcMacro,
477    /// A [`feature = "<name>"`](https://doc.rust-lang.org/nightly/cargo/reference/features.html)
478    Feature(&'a str),
479    /// [target_feature](https://doc.rust-lang.org/reference/conditional-compilation.html#target_feature)
480    TargetFeature(&'a str),
481    /// A generic bare predicate key that doesn't match one of the known options, eg `cfg(bare)`
482    Flag(&'a str),
483    /// A generic key = "value" predicate that doesn't match one of the known options, eg `cfg(foo = "bar")`
484    KeyValue { key: &'a str, val: &'a str },
485}
486
487#[derive(Clone, Debug)]
488pub(crate) enum InnerPredicate {
489    Target(InnerTarget),
490    Test,
491    DebugAssertions,
492    ProcMacro,
493    Feature(Range<usize>),
494    TargetFeature(Range<usize>),
495    Other {
496        identifier: Range<usize>,
497        value: Option<Range<usize>>,
498    },
499}
500
501impl InnerPredicate {
502    fn to_pred<'a>(&self, s: &'a str) -> Predicate<'a> {
503        use InnerPredicate as IP;
504        use Predicate::{
505            DebugAssertions, Feature, Flag, KeyValue, ProcMacro, Target, TargetFeature, Test,
506        };
507
508        match self {
509            IP::Target(it) => match &it.which {
510                Which::Abi => Target(TargetPredicate::Abi(targ::Abi::new(
511                    s[it.span.clone().unwrap()].to_owned(),
512                ))),
513                Which::Arch => Target(TargetPredicate::Arch(targ::Arch::new(
514                    s[it.span.clone().unwrap()].to_owned(),
515                ))),
516                Which::Os => Target(TargetPredicate::Os(targ::Os::new(
517                    s[it.span.clone().unwrap()].to_owned(),
518                ))),
519                Which::Vendor => Target(TargetPredicate::Vendor(targ::Vendor::new(
520                    s[it.span.clone().unwrap()].to_owned(),
521                ))),
522                Which::Env => Target(TargetPredicate::Env(targ::Env::new(
523                    s[it.span.clone().unwrap()].to_owned(),
524                ))),
525                Which::Family => Target(TargetPredicate::Family(targ::Family::new(
526                    s[it.span.clone().unwrap()].to_owned(),
527                ))),
528                Which::Endian(end) => Target(TargetPredicate::Endian(*end)),
529                Which::HasAtomic(has_atomic) => Target(TargetPredicate::HasAtomic(*has_atomic)),
530                Which::Panic => Target(TargetPredicate::Panic(targ::Panic::new(
531                    s[it.span.clone().unwrap()].to_owned(),
532                ))),
533                Which::PointerWidth(pw) => Target(TargetPredicate::PointerWidth(*pw)),
534            },
535            IP::Test => Test,
536            IP::DebugAssertions => DebugAssertions,
537            IP::ProcMacro => ProcMacro,
538            IP::Feature(rng) => Feature(&s[rng.clone()]),
539            IP::TargetFeature(rng) => TargetFeature(&s[rng.clone()]),
540            IP::Other { identifier, value } => match value {
541                Some(vs) => KeyValue {
542                    key: &s[identifier.clone()],
543                    val: &s[vs.clone()],
544                },
545                None => Flag(&s[identifier.clone()]),
546            },
547        }
548    }
549}
550
551#[derive(Clone, Debug)]
552pub(crate) enum ExprNode {
553    Fn(Func),
554    Predicate(InnerPredicate),
555}
556
557/// A parsed `cfg()` expression that can evaluated
558#[derive(Clone, Debug)]
559pub struct Expression {
560    pub(crate) expr: SmallVec<[ExprNode; 5]>,
561    // We keep the original string around for providing the arbitrary
562    // strings that can make up an expression
563    pub(crate) original: String,
564}
565
566impl Expression {
567    /// An iterator over each predicate in the expression
568    pub fn predicates(&self) -> impl Iterator<Item = Predicate<'_>> {
569        self.expr.iter().filter_map(move |item| match item {
570            ExprNode::Predicate(pred) => {
571                let pred = pred.clone().to_pred(&self.original);
572                Some(pred)
573            }
574            ExprNode::Fn(_) => None,
575        })
576    }
577
578    /// Evaluates the expression, using the provided closure to determine the value of
579    /// each predicate, which are then combined into a final result depending on the
580    /// functions `not()`, `all()`, or `any()` in the expression.
581    ///
582    /// `eval_predicate` typically returns `bool`, but may return any type that implements
583    /// the `Logic` trait.
584    ///
585    /// ## Examples
586    ///
587    /// ```
588    /// use cfg_expr::{targets::*, Expression, Predicate};
589    ///
590    /// let linux_musl = get_builtin_target_by_triple("x86_64-unknown-linux-musl").unwrap();
591    ///
592    /// let expr = Expression::parse(r#"all(not(windows), target_env = "musl", any(target_arch = "x86", target_arch = "x86_64"))"#).unwrap();
593    ///
594    /// assert!(expr.eval(|pred| {
595    ///     match pred {
596    ///         Predicate::Target(tp) => tp.matches(linux_musl),
597    ///         _ => false,
598    ///     }
599    /// }));
600    /// ```
601    ///
602    /// Returning `Option<bool>`, where `None` indicates the result is unknown:
603    ///
604    /// ```
605    /// use cfg_expr::{targets::*, Expression, Predicate};
606    ///
607    /// let expr = Expression::parse(r#"any(target_feature = "sse2", target_env = "musl")"#).unwrap();
608    ///
609    /// let linux_gnu = get_builtin_target_by_triple("x86_64-unknown-linux-gnu").unwrap();
610    /// let linux_musl = get_builtin_target_by_triple("x86_64-unknown-linux-musl").unwrap();
611    ///
612    /// fn eval(expr: &Expression, target: &TargetInfo) -> Option<bool> {
613    ///     expr.eval(|pred| {
614    ///         match pred {
615    ///             Predicate::Target(tp) => Some(tp.matches(target)),
616    ///             Predicate::TargetFeature(_) => None,
617    ///             _ => panic!("unexpected predicate"),
618    ///         }
619    ///     })
620    /// }
621    ///
622    /// // Whether the target feature is present is unknown, so the whole expression evaluates to
623    /// // None (unknown).
624    /// assert_eq!(eval(&expr, linux_gnu), None);
625    ///
626    /// // Whether the target feature is present is irrelevant for musl, since the any() always
627    /// // evaluates to true.
628    /// assert_eq!(eval(&expr, linux_musl), Some(true));
629    /// ```
630    pub fn eval<EP, T>(&self, mut eval_predicate: EP) -> T
631    where
632        EP: FnMut(&Predicate<'_>) -> T,
633        T: Logic + std::fmt::Debug,
634    {
635        let mut result_stack = SmallVec::<[T; 8]>::new();
636
637        // We store the expression as postfix, so just evaluate each component
638        // requirement in the order it comes, and then combining the previous
639        // results according to each operator as it comes
640        for node in self.expr.iter() {
641            match node {
642                ExprNode::Predicate(pred) => {
643                    let pred = pred.to_pred(&self.original);
644
645                    result_stack.push(eval_predicate(&pred));
646                }
647                ExprNode::Fn(Func::All(count)) => {
648                    // all() with a comma separated list of configuration predicates.
649                    let mut result = T::top();
650
651                    for _ in 0..*count {
652                        let r = result_stack.pop().unwrap();
653                        result = result.and(r);
654                    }
655
656                    result_stack.push(result);
657                }
658                ExprNode::Fn(Func::Any(count)) => {
659                    // any() with a comma separated list of configuration predicates.
660                    let mut result = T::bottom();
661
662                    for _ in 0..*count {
663                        let r = result_stack.pop().unwrap();
664                        result = result.or(r);
665                    }
666
667                    result_stack.push(result);
668                }
669                ExprNode::Fn(Func::Not) => {
670                    // not() with a configuration predicate.
671                    // It is true if its predicate is false
672                    // and false if its predicate is true.
673                    let r = result_stack.pop().unwrap();
674                    result_stack.push(r.not());
675                }
676            }
677        }
678
679        result_stack.pop().unwrap()
680    }
681
682    /// The original string which has been parsed to produce this [`Expression`].
683    ///
684    /// ```
685    /// use cfg_expr::Expression;
686    ///
687    /// assert_eq!(
688    ///     Expression::parse("any()").unwrap().original(),
689    ///     "any()"
690    /// );
691    /// ```
692    #[inline]
693    pub fn original(&self) -> &str {
694        &self.original
695    }
696}
697
698/// [`PartialEq`] will do a **syntactical** comparison, so will just check if both
699/// expressions have been parsed from the same string, **not** if they are semantically
700/// equivalent.
701///
702/// ```
703/// use cfg_expr::Expression;
704///
705/// assert_eq!(
706///     Expression::parse("any()").unwrap(),
707///     Expression::parse("any()").unwrap()
708/// );
709/// assert_ne!(
710///     Expression::parse("any()").unwrap(),
711///     Expression::parse("unix").unwrap()
712/// );
713/// ```
714impl PartialEq for Expression {
715    fn eq(&self, other: &Self) -> bool {
716        self.original.eq(&other.original)
717    }
718}
719
720impl std::str::FromStr for Expression {
721    type Err = crate::error::ParseError;
722
723    fn from_str(s: &str) -> Result<Self, Self::Err> {
724        Expression::parse(s)
725    }
726}
727
728impl std::fmt::Display for Expression {
729    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
730        f.write_str(&self.original)
731    }
732}
733
734/// A propositional logic used to evaluate `Expression` instances.
735///
736/// An `Expression` consists of some predicates and the `any`, `all` and `not` operators. An
737/// implementation of `Logic` defines how the `any`, `all` and `not` operators should be evaluated.
738pub trait Logic {
739    /// The result of an `all` operation with no operands, akin to Boolean `true`.
740    fn top() -> Self;
741
742    /// The result of an `any` operation with no operands, akin to Boolean `false`.
743    fn bottom() -> Self;
744
745    /// `AND`, which corresponds to the `all` operator.
746    fn and(self, other: Self) -> Self;
747
748    /// `OR`, which corresponds to the `any` operator.
749    fn or(self, other: Self) -> Self;
750
751    /// `NOT`, which corresponds to the `not` operator.
752    fn not(self) -> Self;
753}
754
755/// A boolean logic.
756impl Logic for bool {
757    #[inline]
758    fn top() -> Self {
759        true
760    }
761
762    #[inline]
763    fn bottom() -> Self {
764        false
765    }
766
767    #[inline]
768    fn and(self, other: Self) -> Self {
769        self && other
770    }
771
772    #[inline]
773    fn or(self, other: Self) -> Self {
774        self || other
775    }
776
777    #[inline]
778    fn not(self) -> Self {
779        !self
780    }
781}
782
783/// A three-valued logic -- `None` stands for the value being unknown.
784///
785/// The truth tables for this logic are described on
786/// [Wikipedia](https://en.wikipedia.org/wiki/Three-valued_logic#Kleene_and_Priest_logics).
787impl Logic for Option<bool> {
788    #[inline]
789    fn top() -> Self {
790        Some(true)
791    }
792
793    #[inline]
794    fn bottom() -> Self {
795        Some(false)
796    }
797
798    #[inline]
799    fn and(self, other: Self) -> Self {
800        match (self, other) {
801            // If either is false, the expression is false.
802            (Some(false), _) | (_, Some(false)) => Some(false),
803            // If both are true, the expression is true.
804            (Some(true), Some(true)) => Some(true),
805            // One or both are unknown -- the result is unknown.
806            _ => None,
807        }
808    }
809
810    #[inline]
811    fn or(self, other: Self) -> Self {
812        match (self, other) {
813            // If either is true, the expression is true.
814            (Some(true), _) | (_, Some(true)) => Some(true),
815            // If both are false, the expression is false.
816            (Some(false), Some(false)) => Some(false),
817            // One or both are unknown -- the result is unknown.
818            _ => None,
819        }
820    }
821
822    #[inline]
823    fn not(self) -> Self {
824        self.map(|v| !v)
825    }
826}