Skip to main content

cairo_lang_semantic/items/
macro_call.rs

1use std::sync::Arc;
2
3use cairo_lang_defs::db::DefsGroup;
4use cairo_lang_defs::ids::{LanguageElementId, MacroCallId, ModuleId};
5use cairo_lang_diagnostics::{Diagnostics, Maybe, skip_diagnostic};
6use cairo_lang_filesystem::ids::{
7    CodeMapping, CodeOrigin, FileKind, FileLongId, SmolStrId, VirtualFile,
8};
9use cairo_lang_filesystem::span::{TextOffset, TextSpan};
10use cairo_lang_syntax::node::{TypedStablePtr, TypedSyntaxNode, ast};
11use cairo_lang_utils::Intern;
12use salsa::Database;
13
14use crate::SemanticDiagnostic;
15use crate::diagnostic::{
16    NotFoundItemType, SemanticDiagnosticKind, SemanticDiagnostics, SemanticDiagnosticsBuilder,
17};
18use crate::expr::inference::InferenceId;
19use crate::items::macro_declaration::{
20    MacroDeclarationSemantic, MatcherContext, expand_macro_rule, is_macro_rule_match,
21};
22use crate::items::module::ModuleSemantic;
23use crate::resolve::{ResolutionContext, ResolvedGenericItem, Resolver, ResolverMacroData};
24
25/// The data associated with a macro call in item context.
26#[derive(Debug, Clone, PartialEq, Eq, salsa::Update)]
27pub struct MacroCallData<'db> {
28    /// The module to which the macro call was expanded to.
29    pub macro_call_module: Maybe<ModuleId<'db>>,
30    pub diagnostics: Diagnostics<'db, SemanticDiagnostic<'db>>,
31    pub defsite_module_id: ModuleId<'db>,
32    pub callsite_module_id: ModuleId<'db>,
33    pub expansion_mappings: Arc<[CodeMapping]>,
34    pub parent_macro_call_data: Option<Arc<ResolverMacroData<'db>>>,
35}
36
37/// Implementation of [MacroCallSemantic::priv_macro_call_data].
38fn priv_macro_call_data<'db>(
39    db: &'db dyn Database,
40    macro_call_id: MacroCallId<'db>,
41) -> Maybe<MacroCallData<'db>> {
42    let inference_id = InferenceId::MacroCall(macro_call_id);
43    let module_id = macro_call_id.parent_module(db);
44    let mut resolver = Resolver::new(db, module_id, inference_id);
45    let macro_call_syntax = db.module_macro_call_by_id(macro_call_id)?;
46    // Resolve the macro call path, and report diagnostics if it finds no match or
47    // the resolved item is not a macro declaration.
48    let macro_call_path = macro_call_syntax.path(db);
49    let macro_name = macro_call_path.as_syntax_node().get_text_without_trivia(db);
50    let callsite_module_id = macro_call_id.parent_module(db);
51    // If the call is to `expose!` and no other `expose` item is locally declared - using expose.
52    if macro_name.long(db) == EXPOSE_MACRO_NAME
53        && let Ok(None) = db.module_item_by_name(callsite_module_id, macro_name)
54    {
55        let (content, mapping) = expose_content_and_mapping(db, macro_call_syntax.arguments(db))?;
56        let code_mappings: Arc<[CodeMapping]> = [mapping].into();
57        let parent_macro_call_data = resolver.macro_call_data;
58        let generated_file_id = FileLongId::Virtual(VirtualFile {
59            parent: Some(macro_call_syntax.stable_ptr(db).untyped().span_in_file(db)),
60            name: macro_name,
61            content: SmolStrId::from(db, content),
62            code_mappings: code_mappings.clone(),
63            kind: FileKind::Module,
64            original_item_removed: false,
65        })
66        .intern(db);
67        let macro_call_module =
68            ModuleId::MacroCall { id: macro_call_id, generated_file_id, is_expose: true };
69        return Ok(MacroCallData {
70            macro_call_module: Ok(macro_call_module),
71            diagnostics: Default::default(),
72            // Defsite and callsite aren't actually used, as it defines nothing in its code.
73            defsite_module_id: callsite_module_id,
74            callsite_module_id,
75            expansion_mappings: code_mappings,
76            parent_macro_call_data,
77        });
78    }
79    let mut diagnostics = SemanticDiagnostics::new(callsite_module_id);
80    let macro_declaration_id = match resolver.resolve_generic_path(
81        &mut diagnostics,
82        &macro_call_path,
83        NotFoundItemType::Macro,
84        ResolutionContext::Default,
85    ) {
86        Ok(ResolvedGenericItem::Macro(macro_declaration_id)) => macro_declaration_id,
87        Ok(_) => {
88            let diag_added = diagnostics.report(
89                macro_call_syntax.stable_ptr(db),
90                SemanticDiagnosticKind::InlineMacroNotFound(macro_name),
91            );
92            return Ok(MacroCallData {
93                macro_call_module: Err(diag_added),
94                diagnostics: diagnostics.build(),
95                defsite_module_id: callsite_module_id,
96                callsite_module_id,
97                expansion_mappings: Arc::new([]),
98                parent_macro_call_data: None,
99            });
100        }
101        Err(diag_added) => {
102            return Ok(MacroCallData {
103                macro_call_module: Err(diag_added),
104                diagnostics: diagnostics.build(),
105                defsite_module_id: callsite_module_id,
106                callsite_module_id,
107                expansion_mappings: Arc::new([]),
108                parent_macro_call_data: None,
109            });
110        }
111    };
112    let defsite_module_id = macro_declaration_id.parent_module(db);
113    let macro_rules = match db.macro_declaration_rules(macro_declaration_id) {
114        Ok(rules) => rules,
115        Err(diag_added) => {
116            return Ok(MacroCallData {
117                macro_call_module: Err(diag_added),
118                diagnostics: diagnostics.build(),
119                defsite_module_id,
120                callsite_module_id,
121                expansion_mappings: Arc::new([]),
122                parent_macro_call_data: None,
123            });
124        }
125    };
126    let Some((rule, (captures, placeholder_to_rep_id))) = macro_rules.iter().find_map(|rule| {
127        is_macro_rule_match(db, rule, &macro_call_syntax.arguments(db)).map(|res| (rule, res))
128    }) else {
129        let diag_added = diagnostics.report(
130            macro_call_syntax.stable_ptr(db),
131            SemanticDiagnosticKind::InlineMacroNoMatchingRule(macro_name),
132        );
133        return Ok(MacroCallData {
134            macro_call_module: Err(diag_added),
135            diagnostics: diagnostics.build(),
136            defsite_module_id,
137            callsite_module_id,
138            expansion_mappings: Arc::new([]),
139            parent_macro_call_data: None,
140        });
141    };
142    let mut matcher_ctx = MatcherContext { captures, placeholder_to_rep_id, ..Default::default() };
143    let expanded_code = expand_macro_rule(db, rule, &mut matcher_ctx).unwrap();
144    let parent_macro_call_data = resolver.macro_call_data;
145    let generated_file_id = FileLongId::Virtual(VirtualFile {
146        parent: Some(macro_call_syntax.stable_ptr(db).untyped().span_in_file(db)),
147        name: macro_name,
148        content: SmolStrId::from_arcstr(db, &expanded_code.text),
149        code_mappings: expanded_code.code_mappings.clone(),
150        kind: FileKind::Module,
151        original_item_removed: false,
152    })
153    .intern(db);
154    let macro_call_module =
155        ModuleId::MacroCall { id: macro_call_id, generated_file_id, is_expose: false };
156    Ok(MacroCallData {
157        macro_call_module: Ok(macro_call_module),
158        diagnostics: diagnostics.build(),
159        defsite_module_id,
160        callsite_module_id,
161        expansion_mappings: expanded_code.code_mappings,
162        parent_macro_call_data,
163    })
164}
165
166/// Query implementation of [MacroCallSemantic::priv_macro_call_data].
167#[salsa::tracked(cycle_fn=priv_macro_call_data_cycle, cycle_initial=priv_macro_call_data_initial)]
168fn priv_macro_call_data_tracked<'db>(
169    db: &'db dyn Database,
170    macro_call_id: MacroCallId<'db>,
171) -> Maybe<MacroCallData<'db>> {
172    priv_macro_call_data(db, macro_call_id)
173}
174
175/// The name of the `expose!` macro.
176pub const EXPOSE_MACRO_NAME: &str = "expose";
177
178// TODO(eytan-starkware): Return SmolStrId
179/// Gets the content and mappings for the `expose!` macro call.
180pub fn expose_content_and_mapping<'db>(
181    db: &'db dyn Database,
182    args: ast::TokenTreeNode<'db>,
183) -> Maybe<(String, CodeMapping)> {
184    let tokens = match args.subtree(db) {
185        ast::WrappedTokenTree::Parenthesized(tree) => tree.tokens(db),
186        ast::WrappedTokenTree::Braced(tree) => tree.tokens(db),
187        ast::WrappedTokenTree::Bracketed(tree) => tree.tokens(db),
188        ast::WrappedTokenTree::Missing(_) => return Err(skip_diagnostic()),
189    };
190    let tokens_node = tokens.as_syntax_node();
191    let tokens_span = tokens_node.span(db);
192    Ok((
193        tokens_node.get_text(db).to_string(),
194        CodeMapping {
195            span: TextSpan::new_with_width(TextOffset::START, tokens_span.width()),
196            origin: CodeOrigin::Start(tokens_span.start),
197        },
198    ))
199}
200
201/// Cycle handling for [MacroCallSemantic::priv_macro_call_data].
202fn priv_macro_call_data_cycle<'db>(
203    _db: &'db dyn Database,
204    _cycle: &salsa::Cycle<'_>,
205    _last_provisional_value: &Maybe<MacroCallData<'db>>,
206    value: Maybe<MacroCallData<'db>>,
207    _macro_call_id: MacroCallId<'db>,
208) -> Maybe<MacroCallData<'db>> {
209    value
210}
211
212/// Cycle handling for [MacroCallSemantic::priv_macro_call_data].
213fn priv_macro_call_data_initial<'db>(
214    db: &'db dyn Database,
215    _id: salsa::Id,
216    macro_call_id: MacroCallId<'db>,
217) -> Maybe<MacroCallData<'db>> {
218    // If we are in a cycle, we return an empty MacroCallData with no diagnostics.
219    // This is to prevent infinite recursion in case of cyclic macro calls.
220    let module_id = macro_call_id.parent_module(db);
221    let mut diagnostics = SemanticDiagnostics::new(module_id);
222    let macro_call_syntax = db.module_macro_call_by_id(macro_call_id)?;
223    let macro_call_path = macro_call_syntax.path(db);
224    let macro_name = macro_call_path.as_syntax_node().get_text_without_trivia(db);
225
226    let diag_added = diagnostics.report(
227        macro_call_id.stable_ptr(db).untyped(),
228        SemanticDiagnosticKind::InlineMacroNotFound(macro_name),
229    );
230
231    Ok(MacroCallData {
232        macro_call_module: Err(diag_added),
233        diagnostics: diagnostics.build(),
234        defsite_module_id: module_id,
235        callsite_module_id: module_id,
236        expansion_mappings: Arc::new([]),
237        parent_macro_call_data: None,
238    })
239}
240
241/// Implementation of [MacroCallSemantic::macro_call_diagnostics].
242fn macro_call_diagnostics<'db>(
243    db: &'db dyn Database,
244    macro_call_id: MacroCallId<'db>,
245) -> Diagnostics<'db, SemanticDiagnostic<'db>> {
246    db.priv_macro_call_data(macro_call_id).map(|data| data.diagnostics).unwrap_or_default()
247}
248
249/// Query implementation of [MacroCallSemantic::macro_call_diagnostics].
250#[salsa::tracked]
251fn macro_call_diagnostics_tracked<'db>(
252    db: &'db dyn Database,
253    macro_call_id: MacroCallId<'db>,
254) -> Diagnostics<'db, SemanticDiagnostic<'db>> {
255    macro_call_diagnostics(db, macro_call_id)
256}
257
258/// Implementation of [MacroCallSemantic::macro_call_module_id].
259fn macro_call_module_id<'db>(
260    db: &'db dyn Database,
261    macro_call_id: MacroCallId<'db>,
262) -> Maybe<ModuleId<'db>> {
263    db.priv_macro_call_data(macro_call_id)?.macro_call_module
264}
265
266/// Query implementation of [MacroCallSemantic::macro_call_module_id].
267#[salsa::tracked(cycle_fn=macro_call_module_id_cycle, cycle_initial=macro_call_module_id_initial)]
268fn macro_call_module_id_tracked<'db>(
269    db: &'db dyn Database,
270    macro_call_id: MacroCallId<'db>,
271) -> Maybe<ModuleId<'db>> {
272    macro_call_module_id(db, macro_call_id)
273}
274
275/// Cycle handling for [MacroCallSemantic::macro_call_module_id].
276fn macro_call_module_id_cycle<'db>(
277    _db: &'db dyn Database,
278    _cycle: &salsa::Cycle<'_>,
279    _last_provisional_value: &Maybe<ModuleId<'db>>,
280    value: Maybe<ModuleId<'db>>,
281    _macro_call_id: MacroCallId<'db>,
282) -> Maybe<ModuleId<'db>> {
283    value
284}
285/// Cycle handling for [MacroCallSemantic::macro_call_module_id].
286fn macro_call_module_id_initial<'db>(
287    _db: &'db dyn Database,
288    _id: salsa::Id,
289    _macro_call_id: MacroCallId<'db>,
290) -> Maybe<ModuleId<'db>> {
291    Err(skip_diagnostic())
292}
293
294/// Returns the modules that are considered a part of this module.
295///
296/// If `include_all` is true, all modules are returned, regardless if exposed, or are the main
297/// module.
298#[salsa::tracked(returns(ref))]
299pub fn module_macro_modules<'db>(
300    db: &'db dyn Database,
301    include_all: bool,
302    module_id: ModuleId<'db>,
303) -> Vec<ModuleId<'db>> {
304    let mut modules = vec![];
305    let mut stack = vec![(module_id, include_all)];
306    while let Some((module_id, expose)) = stack.pop() {
307        if expose {
308            modules.push(module_id);
309        }
310        if let Ok(macro_calls) = db.module_macro_calls_ids(module_id) {
311            for macro_call in macro_calls.iter().rev() {
312                let Ok(macro_module_id) = db.macro_call_module_id(*macro_call) else {
313                    continue;
314                };
315                let expose = expose
316                    || matches!(macro_module_id, ModuleId::MacroCall { is_expose: true, .. });
317                stack.push((macro_module_id, expose));
318            }
319        }
320    }
321    modules
322}
323
324/// Trait for macro call-related semantic queries.
325pub trait MacroCallSemantic<'db>: Database {
326    /// Returns the semantic data of a macro call.
327    fn priv_macro_call_data(
328        &'db self,
329        macro_call_id: MacroCallId<'db>,
330    ) -> Maybe<MacroCallData<'db>> {
331        priv_macro_call_data_tracked(self.as_dyn_database(), macro_call_id)
332    }
333    /// Returns the expansion result of a macro call.
334    fn macro_call_module_id(&'db self, macro_call_id: MacroCallId<'db>) -> Maybe<ModuleId<'db>> {
335        macro_call_module_id_tracked(self.as_dyn_database(), macro_call_id)
336    }
337    /// Returns the semantic diagnostics of a macro call.
338    fn macro_call_diagnostics(
339        &'db self,
340        macro_call_id: MacroCallId<'db>,
341    ) -> Diagnostics<'db, SemanticDiagnostic<'db>> {
342        macro_call_diagnostics_tracked(self.as_dyn_database(), macro_call_id)
343    }
344}
345impl<'db, T: Database + ?Sized> MacroCallSemantic<'db> for T {}