cairo_lang_semantic/
helper.rs

1use cairo_lang_defs::ids::{ExternFunctionId, ModuleId, ModuleItemId, TraitId};
2use smol_str::SmolStr;
3
4use crate::db::SemanticGroup;
5use crate::{FunctionId, GenericArgumentId, TypeId, corelib};
6
7/// Helper for getting functions in the corelib.
8pub struct ModuleHelper<'a> {
9    /// The db.
10    pub db: &'a dyn SemanticGroup,
11    /// The current module id.
12    pub id: ModuleId,
13}
14impl<'a> ModuleHelper<'a> {
15    /// Returns a helper for the core module.
16    pub fn core(db: &'a dyn SemanticGroup) -> Self {
17        Self { db, id: db.core_module() }
18    }
19    /// Returns a helper for a submodule named `name` of the current module.
20    pub fn submodule(&self, name: &str) -> Self {
21        let id = corelib::get_submodule(self.db, self.id, name).unwrap_or_else(|| {
22            panic!("`{name}` missing in `{}`.", self.id.full_path(self.db.upcast()))
23        });
24        Self { db: self.db, id }
25    }
26    /// Returns the id of an extern function named `name` in the current module.
27    pub fn extern_function_id(&self, name: impl Into<SmolStr>) -> ExternFunctionId {
28        let name = name.into();
29        let Ok(Some(ModuleItemId::ExternFunction(id))) =
30            self.db.module_item_by_name(self.id, name.clone())
31        else {
32            panic!("`{}` not found in `{}`.", name, self.id.full_path(self.db.upcast()));
33        };
34        id
35    }
36    /// Returns the id of a trait named `name` in the current module.
37    pub fn trait_id(&self, name: impl Into<SmolStr>) -> TraitId {
38        let name = name.into();
39        let Ok(Some(ModuleItemId::Trait(id))) = self.db.module_item_by_name(self.id, name.clone())
40        else {
41            panic!("`{}` not found in `{}`.", name, self.id.full_path(self.db.upcast()));
42        };
43        id
44    }
45    /// Returns the id of a function named `name` in the current module, with the given
46    /// `generic_args`.
47    pub fn function_id(
48        &self,
49        name: impl Into<SmolStr>,
50        generic_args: Vec<GenericArgumentId>,
51    ) -> FunctionId {
52        corelib::get_function_id(self.db, self.id, name.into(), generic_args)
53    }
54    /// Returns the id of a type named `name` in the current module, with the given
55    /// `generic_args`.
56    pub fn ty(&self, name: impl Into<SmolStr>, generic_args: Vec<GenericArgumentId>) -> TypeId {
57        corelib::get_ty_by_name(self.db, self.id, name.into(), generic_args)
58    }
59}