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