cairo_lang_plugins/plugins/
config.rs

1use std::vec;
2
3use cairo_lang_defs::patcher::PatchBuilder;
4use cairo_lang_defs::plugin::{
5    MacroPlugin, MacroPluginMetadata, PluginDiagnostic, PluginGeneratedFile, PluginResult,
6};
7use cairo_lang_filesystem::cfg::{Cfg, CfgSet};
8use cairo_lang_filesystem::ids::SmolStrId;
9use cairo_lang_syntax::attribute::structured::{
10    Attribute, AttributeArg, AttributeArgVariant, AttributeStructurize,
11};
12use cairo_lang_syntax::node::helpers::{BodyItems, GetIdentifier, QueryAttrs};
13use cairo_lang_syntax::node::{TypedStablePtr, TypedSyntaxNode, ast};
14use cairo_lang_utils::try_extract_matches;
15use itertools::Itertools;
16use salsa::Database;
17
18/// Represents a predicate tree used to evaluate configuration attributes to handle nested
19/// predicates, such as logical `not` operations, and evaluate them based on a given set of
20/// configuration flags (`CfgSet`).
21#[derive(Debug, Clone)]
22enum PredicateTree {
23    Cfg(Cfg),
24    Not(Box<PredicateTree>),
25    And(Vec<PredicateTree>),
26    Or(Vec<PredicateTree>),
27}
28
29impl PredicateTree {
30    /// Evaluates the predicate tree against the provided configuration set (`CfgSet`) by traversing
31    /// the `PredicateTree` and determines whether the predicate is satisfied by the given
32    /// `cfg_set`.
33    fn evaluate(&self, cfg_set: &CfgSet) -> bool {
34        match self {
35            PredicateTree::Cfg(cfg) => cfg_set.contains(cfg),
36            PredicateTree::Not(inner) => !inner.evaluate(cfg_set),
37            PredicateTree::And(predicates) => predicates.iter().all(|p| p.evaluate(cfg_set)),
38            PredicateTree::Or(predicates) => predicates.iter().any(|p| p.evaluate(cfg_set)),
39        }
40    }
41}
42
43/// Represents a part of a configuration predicate.
44pub enum ConfigPredicatePart<'db> {
45    /// A configuration item, either a key-value pair or a simple name.
46    Cfg(Cfg),
47    /// A function call in the predicate (`not`, `and`, `or`).
48    Call(ast::ExprFunctionCall<'db>),
49}
50
51/// Plugin that enables ignoring modules not involved in the current config.
52///
53/// Mostly useful for marking test modules to prevent usage of their functionality out of tests,
54/// and reduce compilation time when the tests data isn't required.
55#[derive(Debug, Default)]
56#[non_exhaustive]
57pub struct ConfigPlugin;
58
59const CFG_ATTR: &str = "cfg";
60
61impl MacroPlugin for ConfigPlugin {
62    fn generate_code<'db>(
63        &self,
64        db: &'db dyn Database,
65        item_ast: ast::ModuleItem<'db>,
66        metadata: &MacroPluginMetadata<'_>,
67    ) -> PluginResult<'db> {
68        let mut diagnostics = vec![];
69
70        if should_drop(db, metadata.cfg_set, &item_ast, &mut diagnostics) {
71            PluginResult { code: None, diagnostics, remove_original_item: true }
72        } else if let Some(builder) =
73            handle_undropped_item(db, metadata.cfg_set, item_ast, &mut diagnostics)
74        {
75            let (content, code_mappings) = builder.build();
76            PluginResult {
77                code: Some(PluginGeneratedFile {
78                    name: "config".into(),
79                    content,
80                    code_mappings,
81                    aux_data: None,
82                    diagnostics_note: Default::default(),
83                    is_unhygienic: false,
84                }),
85                diagnostics,
86                remove_original_item: true,
87            }
88        } else {
89            PluginResult { code: None, diagnostics, remove_original_item: false }
90        }
91    }
92
93    fn declared_attributes<'db>(&self, db: &'db dyn Database) -> Vec<SmolStrId<'db>> {
94        vec![SmolStrId::from(db, CFG_ATTR)]
95    }
96}
97
98/// Extension trait for `BodyItems` filtering out items that are not included in the cfg.
99pub trait HasItemsInCfgEx<'a, Item: QueryAttrs<'a>>: BodyItems<'a, Item = Item> {
100    fn iter_items_in_cfg(
101        &self,
102        db: &'a dyn Database,
103        cfg_set: &CfgSet,
104    ) -> impl Iterator<Item = Item>;
105}
106
107impl<'a, Item: QueryAttrs<'a>, Body: BodyItems<'a, Item = Item>> HasItemsInCfgEx<'a, Item>
108    for Body
109{
110    fn iter_items_in_cfg(
111        &self,
112        db: &'a dyn Database,
113        cfg_set: &CfgSet,
114    ) -> impl Iterator<Item = Item> {
115        self.iter_items(db).filter(move |item| !should_drop(db, cfg_set, item, &mut vec![]))
116    }
117}
118
119/// Handles an item that is not dropped from the AST completely due to not matching the config.
120/// In case it includes dropped elements and needs to be rewritten, it returns the appropriate
121/// PatchBuilder. Otherwise returns `None`, and it won't be rewritten or dropped.
122fn handle_undropped_item<'a>(
123    db: &'a dyn Database,
124    cfg_set: &CfgSet,
125    item_ast: ast::ModuleItem<'a>,
126    diagnostics: &mut Vec<PluginDiagnostic<'a>>,
127) -> Option<PatchBuilder<'a>> {
128    match item_ast {
129        ast::ModuleItem::Trait(trait_item) => {
130            let body = try_extract_matches!(trait_item.body(db), ast::MaybeTraitBody::Some)?;
131            let items = get_kept_items_nodes(db, cfg_set, body.iter_items(db), diagnostics)?;
132            let mut builder = PatchBuilder::new(db, &trait_item);
133            builder.add_node(trait_item.attributes(db).as_syntax_node());
134            builder.add_node(trait_item.trait_kw(db).as_syntax_node());
135            builder.add_node(trait_item.name(db).as_syntax_node());
136            builder.add_node(trait_item.generic_params(db).as_syntax_node());
137            builder.add_node(body.lbrace(db).as_syntax_node());
138            for item in items {
139                builder.add_node(item);
140            }
141            builder.add_node(body.rbrace(db).as_syntax_node());
142            Some(builder)
143        }
144        ast::ModuleItem::Impl(impl_item) => {
145            let body = try_extract_matches!(impl_item.body(db), ast::MaybeImplBody::Some)?;
146            let items = get_kept_items_nodes(db, cfg_set, body.iter_items(db), diagnostics)?;
147            let mut builder = PatchBuilder::new(db, &impl_item);
148            builder.add_node(impl_item.attributes(db).as_syntax_node());
149            builder.add_node(impl_item.impl_kw(db).as_syntax_node());
150            builder.add_node(impl_item.name(db).as_syntax_node());
151            builder.add_node(impl_item.generic_params(db).as_syntax_node());
152            builder.add_node(impl_item.of_kw(db).as_syntax_node());
153            builder.add_node(impl_item.trait_path(db).as_syntax_node());
154            builder.add_node(body.lbrace(db).as_syntax_node());
155            for item in items {
156                builder.add_node(item);
157            }
158            builder.add_node(body.rbrace(db).as_syntax_node());
159            Some(builder)
160        }
161        _ => None,
162    }
163}
164
165/// Gets the list of items that should be kept in the AST.
166/// Returns `None` if all items should be kept.
167fn get_kept_items_nodes<'a, Item: QueryAttrs<'a> + TypedSyntaxNode<'a>>(
168    db: &'a dyn Database,
169    cfg_set: &CfgSet,
170    all_items: impl Iterator<Item = Item>,
171    diagnostics: &mut Vec<PluginDiagnostic<'a>>,
172) -> Option<Vec<cairo_lang_syntax::node::SyntaxNode<'a>>> {
173    let mut any_dropped = false;
174    let mut kept_items_nodes = vec![];
175    for item in all_items {
176        if should_drop(db, cfg_set, &item, diagnostics) {
177            any_dropped = true;
178        } else {
179            kept_items_nodes.push(item.as_syntax_node());
180        }
181    }
182    if any_dropped { Some(kept_items_nodes) } else { None }
183}
184
185/// Check if the given item should be dropped from the AST.
186fn should_drop<'a, Item: QueryAttrs<'a>>(
187    db: &'a dyn Database,
188    cfg_set: &CfgSet,
189    item: &Item,
190    diagnostics: &mut Vec<PluginDiagnostic<'a>>,
191) -> bool {
192    item.query_attr(db, CFG_ATTR).any(|attr| {
193        match parse_predicate(db, attr.structurize(db), diagnostics) {
194            Some(predicate_tree) => !predicate_tree.evaluate(cfg_set),
195            None => false,
196        }
197    })
198}
199
200/// Parse `#[cfg(not(ghf)...)]` attribute arguments as a predicate matching [`Cfg`] items.
201fn parse_predicate<'a>(
202    db: &'a dyn Database,
203    attr: Attribute<'a>,
204    diagnostics: &mut Vec<PluginDiagnostic<'a>>,
205) -> Option<PredicateTree> {
206    Some(PredicateTree::And(
207        attr.args
208            .into_iter()
209            .filter_map(|arg| parse_predicate_item(db, arg, diagnostics))
210            .collect(),
211    ))
212}
213
214/// Parse single `#[cfg(...)]` attribute argument as a [`Cfg`] item.
215fn parse_predicate_item<'a>(
216    db: &'a dyn Database,
217    item: AttributeArg<'a>,
218    diagnostics: &mut Vec<PluginDiagnostic<'a>>,
219) -> Option<PredicateTree> {
220    match extract_config_predicate_part(db, &item) {
221        Some(ConfigPredicatePart::Cfg(cfg)) => Some(PredicateTree::Cfg(cfg)),
222        Some(ConfigPredicatePart::Call(call)) => {
223            let operator = call.path(db).as_syntax_node().get_text(db);
224            let args = call
225                .arguments(db)
226                .arguments(db)
227                .elements(db)
228                .map(|arg| AttributeArg::from_ast(arg, db))
229                .collect_vec();
230
231            match operator {
232                "not" => {
233                    if args.len() != 1 {
234                        diagnostics.push(PluginDiagnostic::error(
235                            call.stable_ptr(db),
236                            "`not` operator expects exactly one argument.".into(),
237                        ));
238                        None
239                    } else {
240                        Some(PredicateTree::Not(Box::new(parse_predicate_item(
241                            db,
242                            args[0].clone(),
243                            diagnostics,
244                        )?)))
245                    }
246                }
247                "and" => {
248                    if args.len() < 2 {
249                        diagnostics.push(PluginDiagnostic::error(
250                            call.stable_ptr(db),
251                            "`and` operator expects at least two arguments.".into(),
252                        ));
253                        None
254                    } else {
255                        Some(PredicateTree::And(
256                            args.into_iter()
257                                .filter_map(|arg| parse_predicate_item(db, arg, diagnostics))
258                                .collect(),
259                        ))
260                    }
261                }
262                "or" => {
263                    if args.len() < 2 {
264                        diagnostics.push(PluginDiagnostic::error(
265                            call.stable_ptr(db),
266                            "`or` operator expects at least two arguments.".into(),
267                        ));
268                        None
269                    } else {
270                        Some(PredicateTree::Or(
271                            args.into_iter()
272                                .filter_map(|arg| parse_predicate_item(db, arg, diagnostics))
273                                .collect(),
274                        ))
275                    }
276                }
277                _ => {
278                    diagnostics.push(PluginDiagnostic::error(
279                        call.stable_ptr(db),
280                        format!("Unsupported operator: `{operator}`."),
281                    ));
282                    None
283                }
284            }
285        }
286        None => {
287            diagnostics.push(PluginDiagnostic::error(
288                item.arg.stable_ptr(db).untyped(),
289                "Invalid configuration argument.".into(),
290            ));
291            None
292        }
293    }
294}
295
296/// Extracts a configuration predicate part from an attribute argument.
297fn extract_config_predicate_part<'a>(
298    db: &dyn Database,
299    arg: &AttributeArg<'a>,
300) -> Option<ConfigPredicatePart<'a>> {
301    match &arg.variant {
302        AttributeArgVariant::Unnamed(ast::Expr::Path(path)) => {
303            if let Some([ast::PathSegment::Simple(segment)]) =
304                path.segments(db).elements(db).collect_array()
305            {
306                Some(ConfigPredicatePart::Cfg(Cfg::name(segment.identifier(db).to_string(db))))
307            } else {
308                None
309            }
310        }
311        AttributeArgVariant::Unnamed(ast::Expr::FunctionCall(call)) => {
312            Some(ConfigPredicatePart::Call(call.clone()))
313        }
314        AttributeArgVariant::Named { name, value } => {
315            let value_text = match value {
316                ast::Expr::String(terminal) => terminal.string_value(db).unwrap_or_default(),
317                ast::Expr::ShortString(terminal) => terminal.string_value(db).unwrap_or_default(),
318                _ => return None,
319            };
320
321            Some(ConfigPredicatePart::Cfg(Cfg::kv(name.text.to_string(db), value_text)))
322        }
323        _ => None,
324    }
325}