aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_cfg/src/lib.rs
blob: 697a0458147d76fb376fc73f99f242f7d0a474a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//! ra_cfg defines conditional compiling options, `cfg` attibute parser and evaluator

mod cfg_expr;

use std::iter::IntoIterator;

use ra_syntax::SmolStr;
use rustc_hash::FxHashSet;

pub use cfg_expr::{parse_cfg, CfgExpr};

/// Configuration options used for conditional compilition on items with `cfg` attributes.
/// We have two kind of options in different namespaces: atomic options like `unix`, and
/// key-value options like `target_arch="x86"`.
///
/// Note that for key-value options, one key can have multiple values (but not none).
/// `feature` is an example. We have both `feature="foo"` and `feature="bar"` if features
/// `foo` and `bar` are both enabled. And here, we store key-value options as a set of tuple
/// of key and value in `key_values`.
///
/// See: https://doc.rust-lang.org/reference/conditional-compilation.html#set-configuration-options
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CfgOptions {
    atoms: FxHashSet<SmolStr>,
    key_values: FxHashSet<(SmolStr, SmolStr)>,
}

impl CfgOptions {
    pub fn check(&self, cfg: &CfgExpr) -> Option<bool> {
        cfg.fold(&|key, value| match value {
            None => self.atoms.contains(key),
            Some(value) => self.key_values.contains(&(key.clone(), value.clone())),
        })
    }

    pub fn is_cfg_enabled(&self, attr: &tt::Subtree) -> Option<bool> {
        self.check(&parse_cfg(attr))
    }

    pub fn insert_atom(&mut self, key: SmolStr) {
        self.atoms.insert(key);
    }

    pub fn remove_atom(&mut self, name: &str) {
        self.atoms.remove(name);
    }

    pub fn insert_key_value(&mut self, key: SmolStr, value: SmolStr) {
        self.key_values.insert((key, value));
    }

    /// Shortcut to set features
    pub fn insert_features(&mut self, iter: impl IntoIterator<Item = SmolStr>) {
        iter.into_iter().for_each(|feat| self.insert_key_value("feature".into(), feat));
    }

    /// Shortcut to set cfgs
    pub fn insert_cfgs(&mut self, iter: impl IntoIterator<Item = SmolStr>) {
        iter.into_iter().for_each(|cfg| match cfg.find('=') {
            Some(split) => self
                .insert_key_value(cfg[0..split].into(), cfg[split + 1..].trim_matches('"').into()),
            None => self.insert_atom(cfg),
        });
    }
}