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