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