cairo_lang_semantic/
types.rs

1use std::fmt::Write;
2
3use cairo_lang_debug::DebugWithDb;
4use cairo_lang_defs::db::DefsGroup;
5use cairo_lang_defs::diagnostic_utils::StableLocation;
6use cairo_lang_defs::ids::{
7    EnumId, ExternTypeId, GenericParamId, GenericTypeId, LanguageElementId, ModuleId,
8    NamedLanguageElementId, StructId, TraitTypeId, UnstableSalsaId,
9};
10use cairo_lang_diagnostics::{DiagnosticAdded, Maybe};
11use cairo_lang_filesystem::db::FilesGroup;
12use cairo_lang_proc_macros::SemanticObject;
13use cairo_lang_syntax::attribute::consts::MUST_USE_ATTR;
14use cairo_lang_syntax::node::ast::PathSegment;
15use cairo_lang_syntax::node::ids::SyntaxStablePtrId;
16use cairo_lang_syntax::node::{TypedStablePtr, TypedSyntaxNode, ast};
17use cairo_lang_utils::{Intern, OptionFrom, define_short_id, extract_matches, try_extract_matches};
18use itertools::{Itertools, chain};
19use num_bigint::BigInt;
20use num_traits::Zero;
21use salsa::Database;
22use sha3::{Digest, Keccak256};
23
24use crate::corelib::{
25    CorelibSemantic, concrete_copy_trait, concrete_destruct_trait, concrete_drop_trait,
26    concrete_panic_destruct_trait, get_usize_ty, unit_ty,
27};
28use crate::diagnostic::SemanticDiagnosticKind::*;
29use crate::diagnostic::{NotFoundItemType, SemanticDiagnostics, SemanticDiagnosticsBuilder};
30use crate::expr::compute::{ComputationContext, compute_expr_semantic};
31use crate::expr::fmt::CountingWriter;
32use crate::expr::inference::canonic::{CanonicalTrait, ResultNoErrEx};
33use crate::expr::inference::solver::{SemanticSolver, SolutionSet, enrich_lookup_context};
34use crate::expr::inference::{InferenceData, InferenceError, InferenceId, TypeVar};
35use crate::items::attribute::SemanticQueryAttrs;
36use crate::items::constant::{ConstValue, ConstValueId, resolve_const_expr_and_evaluate};
37use crate::items::enm::{EnumSemantic, SemanticEnumEx};
38use crate::items::extern_type::ExternTypeSemantic;
39use crate::items::generics::{GenericParamSemantic, fmt_generic_args};
40use crate::items::imp::{ImplId, ImplLookupContext, ImplLookupContextId, ImplSemantic};
41use crate::items::structure::StructSemantic;
42use crate::resolve::{ResolutionContext, ResolvedConcreteItem, ResolvedGenericItem, Resolver};
43use crate::substitution::SemanticRewriter;
44use crate::{ConcreteTraitId, FunctionId, GenericArgumentId, semantic, semantic_object_for_id};
45
46#[derive(Clone, Debug, Hash, PartialEq, Eq, SemanticObject)]
47pub enum TypeLongId<'db> {
48    Concrete(ConcreteTypeId<'db>),
49    /// Some expressions might have invalid types during processing, either due to errors or
50    /// during inference.
51    Tuple(Vec<TypeId<'db>>),
52    Snapshot(TypeId<'db>),
53    GenericParameter(GenericParamId<'db>),
54    Var(TypeVar<'db>),
55    Coupon(FunctionId<'db>),
56    FixedSizeArray {
57        type_id: TypeId<'db>,
58        size: ConstValueId<'db>,
59    },
60    ImplType(ImplTypeId<'db>),
61    Closure(ClosureTypeLongId<'db>),
62    Missing(#[dont_rewrite] DiagnosticAdded),
63}
64impl<'db> OptionFrom<TypeLongId<'db>> for ConcreteTypeId<'db> {
65    fn option_from(other: TypeLongId<'db>) -> Option<Self> {
66        try_extract_matches!(other, TypeLongId::Concrete)
67    }
68}
69
70define_short_id!(TypeId, TypeLongId<'db>);
71semantic_object_for_id!(TypeId, TypeLongId<'a>);
72impl<'db> TypeId<'db> {
73    pub fn missing(db: &'db dyn Database, diag_added: DiagnosticAdded) -> Self {
74        TypeLongId::Missing(diag_added).intern(db)
75    }
76
77    pub fn format(&self, db: &dyn Database) -> String {
78        self.long(db).format(db)
79    }
80
81    /// Returns [Maybe::Err] if the type is [TypeLongId::Missing].
82    pub fn check_not_missing(&self, db: &dyn Database) -> Maybe<()> {
83        if let TypeLongId::Missing(diag_added) = self.long(db) { Err(*diag_added) } else { Ok(()) }
84    }
85
86    /// Returns `true` if the type is [TypeLongId::Missing].
87    pub fn is_missing(&self, db: &dyn Database) -> bool {
88        self.check_not_missing(db).is_err()
89    }
90
91    /// Returns `true` if the type is `()`.
92    pub fn is_unit(&self, db: &dyn Database) -> bool {
93        matches!(self.long(db), TypeLongId::Tuple(types) if types.is_empty())
94    }
95
96    /// Returns the [TypeHead] for a type if available.
97    pub fn head(&self, db: &'db dyn Database) -> Option<TypeHead<'db>> {
98        self.long(db).head(db)
99    }
100
101    /// Returns true if the type does not depend on any generics.
102    pub fn is_fully_concrete(&self, db: &dyn Database) -> bool {
103        db.priv_type_is_fully_concrete(*self)
104    }
105
106    /// Returns true if the type does not contain any inference variables.
107    pub fn is_var_free(&self, db: &dyn Database) -> bool {
108        db.priv_type_is_var_free(*self)
109    }
110
111    /// Returns whether the type is phantom.
112    /// Type is considered phantom if it has the `#[phantom]` attribute, or is a tuple or fixed
113    /// sized array containing it.
114    pub fn is_phantom(&self, db: &dyn Database) -> bool {
115        self.long(db).is_phantom(db)
116    }
117
118    /// Short name of the type argument.
119    pub fn short_name(&self, db: &dyn Database) -> String {
120        db.priv_type_short_name(*self)
121    }
122}
123impl<'db> TypeLongId<'db> {
124    pub fn format(&self, db: &dyn Database) -> String {
125        format!("{:?}", self.debug(db))
126    }
127
128    /// Returns the [TypeHead] for a type if available.
129    pub fn head(&self, db: &'db dyn Database) -> Option<TypeHead<'db>> {
130        Some(match self {
131            TypeLongId::Concrete(concrete) => TypeHead::Concrete(concrete.generic_type(db)),
132            TypeLongId::Tuple(_) => TypeHead::Tuple,
133            TypeLongId::Snapshot(inner) => TypeHead::Snapshot(Box::new(inner.head(db)?)),
134            TypeLongId::Coupon(_) => TypeHead::Coupon,
135            TypeLongId::FixedSizeArray { .. } => TypeHead::FixedSizeArray,
136            TypeLongId::GenericParameter(generic_param_id) => TypeHead::Generic(*generic_param_id),
137            TypeLongId::Var(_)
138            | TypeLongId::Missing(_)
139            | TypeLongId::ImplType(_)
140            | TypeLongId::Closure(_) => {
141                return None;
142            }
143        })
144    }
145
146    /// Returns whether the type is phantom.
147    /// Type is considered phantom if it has the `#[phantom]` attribute, (or an other attribute
148    /// declared by a plugin as defining a phantom type), or is a tuple or fixed sized array
149    /// containing it.
150    pub fn is_phantom(&self, db: &dyn Database) -> bool {
151        match self {
152            TypeLongId::Concrete(id) => match id {
153                ConcreteTypeId::Struct(id) => {
154                    let crate_id = id.struct_id(db).long(db).0.owning_crate(db);
155
156                    db.declared_phantom_type_attributes(crate_id)
157                        .iter()
158                        .any(|attr| id.has_attr(db, attr.long(db)).unwrap_or_default())
159                }
160                ConcreteTypeId::Enum(id) => {
161                    let crate_id = id.enum_id(db).long(db).0.owning_crate(db);
162
163                    db.declared_phantom_type_attributes(crate_id)
164                        .iter()
165                        .any(|attr| id.has_attr(db, attr.long(db)).unwrap_or_default())
166                }
167                ConcreteTypeId::Extern(id) => {
168                    let crate_id = id.extern_type_id(db).long(db).0.owning_crate(db);
169
170                    db.declared_phantom_type_attributes(crate_id)
171                        .iter()
172                        .any(|attr| id.has_attr(db, attr.long(db)).unwrap_or_default())
173                }
174            },
175            TypeLongId::Tuple(inner) => inner.iter().any(|ty| ty.is_phantom(db)),
176            TypeLongId::FixedSizeArray { type_id, .. } => type_id.is_phantom(db),
177            TypeLongId::Snapshot(_)
178            | TypeLongId::GenericParameter(_)
179            | TypeLongId::Var(_)
180            | TypeLongId::Coupon(_)
181            | TypeLongId::ImplType(_)
182            | TypeLongId::Missing(_)
183            | TypeLongId::Closure(_) => false,
184        }
185    }
186
187    /// Returns the module id of the given type if applicable.
188    pub fn module_id(&self, db: &'db dyn Database) -> Option<ModuleId<'db>> {
189        match self {
190            TypeLongId::Concrete(concrete) => Some(concrete.generic_type(db).parent_module(db)),
191            TypeLongId::Snapshot(ty) => {
192                let (_n_snapshots, inner_ty) = peel_snapshots(db, *ty);
193                inner_ty.module_id(db)
194            }
195            TypeLongId::GenericParameter(_) => None,
196            TypeLongId::Var(_) => None,
197            TypeLongId::Coupon(function_id) => {
198                function_id.get_concrete(db).generic_function.module_id(db)
199            }
200            TypeLongId::Missing(_) => None,
201            TypeLongId::Tuple(_) => Some(db.core_info().tuple_submodule),
202            TypeLongId::ImplType(_) => None,
203            TypeLongId::FixedSizeArray { .. } => Some(db.core_info().fixed_size_array_submodule),
204            TypeLongId::Closure(closure) => {
205                if let Ok(function_id) = closure.parent_function {
206                    function_id.get_concrete(db).generic_function.module_id(db)
207                } else {
208                    None
209                }
210            }
211        }
212    }
213}
214impl<'db> DebugWithDb<'db> for TypeLongId<'db> {
215    type Db = dyn Database;
216
217    fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &'db dyn Database) -> std::fmt::Result {
218        match self {
219            TypeLongId::Concrete(concrete) => write!(f, "{}", concrete.format(db)),
220            TypeLongId::Tuple(inner_types) => {
221                if inner_types.len() == 1 {
222                    write!(f, "({},)", inner_types[0].format(db))
223                } else {
224                    write!(f, "({})", inner_types.iter().map(|ty| ty.format(db)).join(", "))
225                }
226            }
227            TypeLongId::Snapshot(ty) => write!(f, "@{}", ty.format(db)),
228            TypeLongId::GenericParameter(generic_param) => {
229                write!(f, "{}", generic_param.name(db).map_or("_", |name| name.long(db)))
230            }
231            TypeLongId::ImplType(impl_type_id) => {
232                write!(
233                    f,
234                    "{:?}::{}",
235                    impl_type_id.impl_id.debug(db),
236                    impl_type_id.ty.name(db).long(db)
237                )
238            }
239            TypeLongId::Var(var) => write!(f, "?{}", var.id.0),
240            TypeLongId::Coupon(function_id) => write!(f, "{}::Coupon", function_id.full_path(db)),
241            TypeLongId::Missing(_) => write!(f, "<missing>"),
242            TypeLongId::FixedSizeArray { type_id, size } => {
243                write!(f, "[{}; {:?}]", type_id.format(db), size.debug(db))
244            }
245            TypeLongId::Closure(closure) => {
246                write!(f, "{:?}", closure.debug(db))
247            }
248        }
249    }
250}
251
252/// Head of a type.
253///
254/// A type that is not one of {generic param, type variable, impl type} has a head, which represents
255/// the kind of the root node in its type tree. This is used for caching queries for fast lookups
256/// when the type is not completely inferred yet.
257#[derive(Clone, Debug, Hash, PartialEq, Eq, salsa::Update)]
258pub enum TypeHead<'db> {
259    Concrete(GenericTypeId<'db>),
260    Snapshot(Box<TypeHead<'db>>),
261    Generic(GenericParamId<'db>),
262    Tuple,
263    Coupon,
264    FixedSizeArray,
265}
266
267#[derive(Clone, Debug, Hash, PartialEq, Eq, SemanticObject)]
268pub enum ConcreteTypeId<'db> {
269    Struct(ConcreteStructId<'db>),
270    Enum(ConcreteEnumId<'db>),
271    Extern(ConcreteExternTypeId<'db>),
272}
273impl<'db> ConcreteTypeId<'db> {
274    pub fn new(
275        db: &'db dyn Database,
276        generic_ty: GenericTypeId<'db>,
277        generic_args: Vec<semantic::GenericArgumentId<'db>>,
278    ) -> Self {
279        match generic_ty {
280            GenericTypeId::Struct(id) => ConcreteTypeId::Struct(
281                ConcreteStructLongId { struct_id: id, generic_args }.intern(db),
282            ),
283            GenericTypeId::Enum(id) => {
284                ConcreteTypeId::Enum(ConcreteEnumLongId { enum_id: id, generic_args }.intern(db))
285            }
286            GenericTypeId::Extern(id) => ConcreteTypeId::Extern(
287                ConcreteExternTypeLongId { extern_type_id: id, generic_args }.intern(db),
288            ),
289        }
290    }
291    pub fn generic_type(&self, db: &'db dyn Database) -> GenericTypeId<'db> {
292        match self {
293            ConcreteTypeId::Struct(id) => GenericTypeId::Struct(id.long(db).struct_id),
294            ConcreteTypeId::Enum(id) => GenericTypeId::Enum(id.long(db).enum_id),
295            ConcreteTypeId::Extern(id) => GenericTypeId::Extern(id.long(db).extern_type_id),
296        }
297    }
298    pub fn generic_args(&self, db: &'db dyn Database) -> Vec<semantic::GenericArgumentId<'db>> {
299        match self {
300            ConcreteTypeId::Struct(id) => id.long(db).generic_args.clone(),
301            ConcreteTypeId::Enum(id) => id.long(db).generic_args.clone(),
302            ConcreteTypeId::Extern(id) => id.long(db).generic_args.clone(),
303        }
304    }
305    pub fn format(&self, db: &dyn Database) -> String {
306        format!("{:?}", self.debug(db))
307    }
308
309    /// Returns whether the type has the `#[must_use]` attribute.
310    pub fn is_must_use(&self, db: &dyn Database) -> Maybe<bool> {
311        match self {
312            ConcreteTypeId::Struct(id) => id.has_attr(db, MUST_USE_ATTR),
313            ConcreteTypeId::Enum(id) => id.has_attr(db, MUST_USE_ATTR),
314            ConcreteTypeId::Extern(id) => id.has_attr(db, MUST_USE_ATTR),
315        }
316    }
317    /// Returns true if the type does not depend on any generics.
318    pub fn is_fully_concrete(&self, db: &dyn Database) -> bool {
319        self.generic_args(db)
320            .iter()
321            .all(|generic_argument_id| generic_argument_id.is_fully_concrete(db))
322    }
323    /// Returns true if the type does not contain any inference variables.
324    pub fn is_var_free(&self, db: &dyn Database) -> bool {
325        self.generic_args(db).iter().all(|generic_argument_id| generic_argument_id.is_var_free(db))
326    }
327}
328impl<'db> DebugWithDb<'db> for ConcreteTypeId<'db> {
329    type Db = dyn Database;
330
331    fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &'db dyn Database) -> std::fmt::Result {
332        let f = &mut CountingWriter::new(f);
333        write!(f, "{}", self.generic_type(db).format(db))?;
334        fmt_generic_args(&self.generic_args(db), f, db)
335    }
336}
337
338#[derive(Clone, Debug, Hash, PartialEq, Eq, SemanticObject)]
339pub struct ConcreteStructLongId<'db> {
340    pub struct_id: StructId<'db>,
341    pub generic_args: Vec<semantic::GenericArgumentId<'db>>,
342}
343define_short_id!(ConcreteStructId, ConcreteStructLongId<'db>);
344semantic_object_for_id!(ConcreteStructId, ConcreteStructLongId<'a>);
345impl<'db> ConcreteStructId<'db> {
346    pub fn struct_id(&self, db: &'db dyn Database) -> StructId<'db> {
347        self.long(db).struct_id
348    }
349}
350impl<'db> DebugWithDb<'db> for ConcreteStructLongId<'db> {
351    type Db = dyn Database;
352
353    fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &'db dyn Database) -> std::fmt::Result {
354        write!(f, "{:?}", ConcreteTypeId::Struct(self.clone().intern(db)).debug(db))
355    }
356}
357
358#[derive(Clone, Debug, Hash, PartialEq, Eq, SemanticObject)]
359pub struct ConcreteEnumLongId<'db> {
360    pub enum_id: EnumId<'db>,
361    pub generic_args: Vec<semantic::GenericArgumentId<'db>>,
362}
363impl<'db> DebugWithDb<'db> for ConcreteEnumLongId<'db> {
364    type Db = dyn Database;
365
366    fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &'db dyn Database) -> std::fmt::Result {
367        write!(f, "{:?}", ConcreteTypeId::Enum(self.clone().intern(db)).debug(db))
368    }
369}
370
371define_short_id!(ConcreteEnumId, ConcreteEnumLongId<'db>);
372semantic_object_for_id!(ConcreteEnumId, ConcreteEnumLongId<'a>);
373impl<'db> ConcreteEnumId<'db> {
374    pub fn enum_id(&self, db: &'db dyn Database) -> EnumId<'db> {
375        self.long(db).enum_id
376    }
377}
378
379#[derive(Clone, Debug, Hash, PartialEq, Eq, SemanticObject)]
380pub struct ConcreteExternTypeLongId<'db> {
381    pub extern_type_id: ExternTypeId<'db>,
382    pub generic_args: Vec<semantic::GenericArgumentId<'db>>,
383}
384define_short_id!(ConcreteExternTypeId, ConcreteExternTypeLongId<'db>);
385semantic_object_for_id!(ConcreteExternTypeId, ConcreteExternTypeLongId<'a>);
386impl<'db> ConcreteExternTypeId<'db> {
387    pub fn extern_type_id(&self, db: &'db dyn Database) -> ExternTypeId<'db> {
388        self.long(db).extern_type_id
389    }
390}
391
392/// A type id of a closure function.
393#[derive(Clone, Debug, Hash, PartialEq, Eq, SemanticObject)]
394pub struct ClosureTypeLongId<'db> {
395    pub param_tys: Vec<TypeId<'db>>,
396    pub ret_ty: TypeId<'db>,
397    /// The set of types captured by the closure, this field is used to determined if the
398    /// closure has Drop, Destruct or PanicDestruct.
399    /// A vector as the fields needs to be hashable.
400    pub captured_types: Vec<TypeId<'db>>,
401    /// The parent function of the closure or an error.
402    pub parent_function: Maybe<FunctionId<'db>>,
403    /// Every closure has a unique type that is based on the stable location of its wrapper.
404    #[dont_rewrite]
405    pub wrapper_location: StableLocation<'db>,
406}
407
408impl<'db> DebugWithDb<'db> for ClosureTypeLongId<'db> {
409    type Db = dyn Database;
410
411    fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &'db dyn Database) -> std::fmt::Result {
412        write!(f, "{{closure@{:?}}}", self.wrapper_location.debug(db))
413    }
414}
415
416/// An impl item of kind type.
417#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, SemanticObject, salsa::Update)]
418pub struct ImplTypeId<'db> {
419    /// The impl the item type is in.
420    impl_id: ImplId<'db>,
421    /// The trait type this impl type "implements".
422    ty: TraitTypeId<'db>,
423}
424impl<'db> ImplTypeId<'db> {
425    /// Creates a new impl type id. For an impl type of a concrete impl, asserts that the trait
426    /// type belongs to the same trait that the impl implements (panics if not).
427    pub fn new(impl_id: ImplId<'db>, ty: TraitTypeId<'db>, db: &'db dyn Database) -> Self {
428        if let crate::items::imp::ImplLongId::Concrete(concrete_impl) = impl_id.long(db) {
429            let impl_def_id = concrete_impl.impl_def_id(db);
430            assert_eq!(Ok(ty.trait_id(db)), db.impl_def_trait(impl_def_id));
431        }
432
433        ImplTypeId { impl_id, ty }
434    }
435    pub fn impl_id(&self) -> ImplId<'db> {
436        self.impl_id
437    }
438    pub fn ty(&self) -> TraitTypeId<'db> {
439        self.ty
440    }
441    pub fn format(&self, db: &dyn Database) -> String {
442        format!("{}::{}", self.impl_id.name(db), self.ty.name(db).long(db))
443    }
444}
445impl<'db> DebugWithDb<'db> for ImplTypeId<'db> {
446    type Db = dyn Database;
447
448    fn fmt(&self, f: &mut std::fmt::Formatter<'_>, db: &'db dyn Database) -> std::fmt::Result {
449        write!(f, "{}", self.format(db))
450    }
451}
452
453/// A wrapper around ImplTypeById that implements Ord for saving in an ordered collection.
454#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, salsa::Update)]
455pub struct ImplTypeById<'db>(ImplTypeId<'db>);
456
457impl<'db> From<ImplTypeId<'db>> for ImplTypeById<'db> {
458    fn from(impl_type_id: ImplTypeId<'db>) -> Self {
459        Self(impl_type_id)
460    }
461}
462impl<'db> Ord for ImplTypeById<'db> {
463    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
464        self.0
465            .impl_id
466            .get_internal_id()
467            .cmp(&other.0.impl_id.get_internal_id())
468            .then_with(|| self.0.ty.get_internal_id().cmp(&other.0.ty.get_internal_id()))
469    }
470}
471impl<'db> PartialOrd for ImplTypeById<'db> {
472    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
473        Some(self.cmp(other))
474    }
475}
476
477// TODO(spapini): add a query wrapper.
478/// Resolves a type given a module and a path. Used for resolving from non-statement context.
479pub fn resolve_type<'db>(
480    db: &'db dyn Database,
481    diagnostics: &mut SemanticDiagnostics<'db>,
482    resolver: &mut Resolver<'db>,
483    ty_syntax: &ast::Expr<'db>,
484) -> TypeId<'db> {
485    resolve_type_ex(db, diagnostics, resolver, ty_syntax, ResolutionContext::Default)
486}
487/// Resolves a type given a module and a path. Allows defining a resolution context.
488pub fn resolve_type_ex<'db>(
489    db: &'db dyn Database,
490    diagnostics: &mut SemanticDiagnostics<'db>,
491    resolver: &mut Resolver<'db>,
492    ty_syntax: &ast::Expr<'db>,
493    ctx: ResolutionContext<'db, '_>,
494) -> TypeId<'db> {
495    maybe_resolve_type(db, diagnostics, resolver, ty_syntax, ctx)
496        .unwrap_or_else(|diag_added| TypeId::missing(db, diag_added))
497}
498fn maybe_resolve_type<'db>(
499    db: &'db dyn Database,
500    diagnostics: &mut SemanticDiagnostics<'db>,
501    resolver: &mut Resolver<'db>,
502    ty_syntax: &ast::Expr<'db>,
503    mut ctx: ResolutionContext<'db, '_>,
504) -> Maybe<TypeId<'db>> {
505    Ok(match ty_syntax {
506        ast::Expr::Path(path) => {
507            match resolver.resolve_concrete_path_ex(
508                diagnostics,
509                path,
510                NotFoundItemType::Type,
511                ctx,
512            )? {
513                ResolvedConcreteItem::Type(ty) => ty,
514                _ => {
515                    return Err(diagnostics.report(path.stable_ptr(db), NotAType));
516                }
517            }
518        }
519        ast::Expr::Parenthesized(expr_syntax) => {
520            resolve_type_ex(db, diagnostics, resolver, &expr_syntax.expr(db), ctx)
521        }
522        ast::Expr::Tuple(tuple_syntax) => {
523            let sub_tys = tuple_syntax
524                .expressions(db)
525                .elements(db)
526                .map(|subexpr_syntax| {
527                    resolve_type_ex(
528                        db,
529                        diagnostics,
530                        resolver,
531                        &subexpr_syntax,
532                        match ctx {
533                            ResolutionContext::Default => ResolutionContext::Default,
534                            ResolutionContext::ModuleItem(id) => ResolutionContext::ModuleItem(id),
535                            ResolutionContext::Statement(ref mut env) => {
536                                ResolutionContext::Statement(env)
537                            }
538                        },
539                    )
540                })
541                .collect();
542            TypeLongId::Tuple(sub_tys).intern(db)
543        }
544        ast::Expr::Unary(unary_syntax)
545            if matches!(unary_syntax.op(db), ast::UnaryOperator::At(_)) =>
546        {
547            let ty = resolve_type_ex(db, diagnostics, resolver, &unary_syntax.expr(db), ctx);
548            TypeLongId::Snapshot(ty).intern(db)
549        }
550        // TODO(TomerStarkware): make sure this is unreachable.
551        ast::Expr::Unary(unary_syntax)
552            if matches!(unary_syntax.op(db), ast::UnaryOperator::Desnap(_)) =>
553        {
554            let ty = resolve_type_ex(db, diagnostics, resolver, &unary_syntax.expr(db), ctx);
555            if let Some(desnapped_ty) = try_extract_matches!(ty.long(db), TypeLongId::Snapshot) {
556                *desnapped_ty
557            } else {
558                return Err(diagnostics.report(ty_syntax.stable_ptr(db), DerefNonRef { ty }));
559            }
560        }
561        ast::Expr::FixedSizeArray(array_syntax) => {
562            let Some([ty]) = &array_syntax.exprs(db).elements(db).collect_array() else {
563                return Err(
564                    diagnostics.report(ty_syntax.stable_ptr(db), FixedSizeArrayTypeNonSingleType)
565                );
566            };
567            let ty = resolve_type_ex(db, diagnostics, resolver, ty, ctx);
568            let size =
569                match extract_fixed_size_array_size(db, diagnostics, array_syntax, resolver)? {
570                    Some(size) => size,
571                    None => {
572                        return Err(diagnostics
573                            .report(ty_syntax.stable_ptr(db), FixedSizeArrayTypeEmptySize));
574                    }
575                };
576            TypeLongId::FixedSizeArray { type_id: ty, size }.intern(db)
577        }
578        _ => {
579            return Err(diagnostics.report(ty_syntax.stable_ptr(db), UnknownType));
580        }
581    })
582}
583
584/// A generic argument which is not fully inferred. Used to avoid cycles in the inference.
585#[derive(Clone, Debug, PartialEq, Eq, salsa::Update)]
586pub enum ShallowGenericArg<'db> {
587    /// The generic argument is a generic parameter.
588    GenericParameter(GenericParamId<'db>),
589    /// The generic argument is a generic type.
590    GenericType(GenericTypeId<'db>),
591    Snapshot(Box<ShallowGenericArg<'db>>),
592    Tuple,
593    FixedSizeArray,
594}
595
596impl<'db> ShallowGenericArg<'db> {
597    /// Returns the module id of the shallow generic argument.
598    pub fn module_id(&self, db: &'db dyn Database) -> Option<ModuleId<'db>> {
599        match self {
600            ShallowGenericArg::GenericParameter(_) => None,
601            ShallowGenericArg::GenericType(ty) => Some(ty.module_id(db)),
602            ShallowGenericArg::Snapshot(inner) => inner.module_id(db),
603            ShallowGenericArg::Tuple => TypeLongId::Tuple(vec![]).module_id(db),
604            ShallowGenericArg::FixedSizeArray => TypeLongId::FixedSizeArray {
605                type_id: unit_ty(db),
606                size: ConstValue::Struct(vec![], unit_ty(db)).intern(db),
607            }
608            .module_id(db),
609        }
610    }
611    pub fn head(&self) -> TypeHead<'db> {
612        match self {
613            ShallowGenericArg::GenericParameter(param) => TypeHead::Generic(*param),
614            ShallowGenericArg::GenericType(ty) => TypeHead::Concrete(*ty),
615            ShallowGenericArg::Snapshot(inner) => TypeHead::Snapshot(Box::new(inner.head())),
616            ShallowGenericArg::Tuple => TypeHead::Tuple,
617            ShallowGenericArg::FixedSizeArray => TypeHead::FixedSizeArray,
618        }
619    }
620}
621/// Resolves a shallow generic argument from a syntax node.
622pub fn maybe_resolve_shallow_generic_arg_type<'db>(
623    db: &'db dyn Database,
624    diagnostics: &mut SemanticDiagnostics<'db>,
625    resolver: &mut Resolver<'db>,
626    ty_syntax: &ast::Expr<'db>,
627) -> Option<ShallowGenericArg<'db>> {
628    Some(match ty_syntax {
629        ast::Expr::Path(path) => {
630            if let [PathSegment::Simple(path)] =
631                path.segments(db).elements(db).collect_vec().as_slice()
632                && let Some(ResolvedConcreteItem::Type(ty)) =
633                    resolver.determine_base_item_in_local_scope(&path.ident(db))
634            {
635                let param = extract_matches!(ty.long(db), TypeLongId::GenericParameter);
636                return Some(ShallowGenericArg::GenericParameter(*param));
637            }
638
639            match resolver
640                .resolve_generic_path_with_args(
641                    diagnostics,
642                    path,
643                    NotFoundItemType::Type,
644                    ResolutionContext::Default,
645                )
646                .ok()?
647            {
648                ResolvedGenericItem::GenericType(ty) => ShallowGenericArg::GenericType(ty),
649                _ => {
650                    return None;
651                }
652            }
653        }
654        ast::Expr::Parenthesized(expr_syntax) => maybe_resolve_shallow_generic_arg_type(
655            db,
656            diagnostics,
657            resolver,
658            &expr_syntax.expr(db),
659        )?,
660        ast::Expr::Tuple(_) => ShallowGenericArg::Tuple,
661        ast::Expr::Unary(unary_syntax)
662            if matches!(unary_syntax.op(db), ast::UnaryOperator::At(_)) =>
663        {
664            ShallowGenericArg::Snapshot(Box::new(maybe_resolve_shallow_generic_arg_type(
665                db,
666                diagnostics,
667                resolver,
668                &unary_syntax.expr(db),
669            )?))
670        }
671        ast::Expr::Unary(unary_syntax)
672            if matches!(unary_syntax.op(db), ast::UnaryOperator::Desnap(_)) =>
673        {
674            maybe_resolve_shallow_generic_arg_type(
675                db,
676                diagnostics,
677                resolver,
678                &unary_syntax.expr(db),
679            )?
680        }
681        ast::Expr::FixedSizeArray(_) => ShallowGenericArg::FixedSizeArray,
682        _ => {
683            return None;
684        }
685    })
686}
687
688/// Extracts the size of a fixed size array, or none if the size is missing. Reports an error if the
689/// size is not a numeric literal.
690pub fn extract_fixed_size_array_size<'db>(
691    db: &'db dyn Database,
692    diagnostics: &mut SemanticDiagnostics<'db>,
693    syntax: &ast::ExprFixedSizeArray<'db>,
694    resolver: &mut Resolver<'db>,
695) -> Maybe<Option<ConstValueId<'db>>> {
696    match syntax.size(db) {
697        ast::OptionFixedSizeArraySize::FixedSizeArraySize(size_clause) => {
698            let mut ctx = ComputationContext::new_global(db, diagnostics, resolver);
699            let size_expr_syntax = size_clause.size(db);
700            let size = compute_expr_semantic(&mut ctx, &size_expr_syntax);
701            let const_value = resolve_const_expr_and_evaluate(
702                db,
703                &mut ctx,
704                &size,
705                size_expr_syntax.stable_ptr(db).untyped(),
706                get_usize_ty(db),
707                false,
708            );
709            if matches!(const_value.long(db), ConstValue::Int(_, _) | ConstValue::Generic(_)) {
710                Ok(Some(const_value))
711            } else {
712                Err(diagnostics.report(syntax.stable_ptr(db), FixedSizeArrayNonNumericSize))
713            }
714        }
715        ast::OptionFixedSizeArraySize::Empty(_) => Ok(None),
716    }
717}
718
719/// Verifies that a given fixed size array size is within limits, and adds a diagnostic if not.
720pub fn verify_fixed_size_array_size<'db>(
721    db: &'db dyn Database,
722    diagnostics: &mut SemanticDiagnostics<'db>,
723    size: &BigInt,
724    syntax: &ast::ExprFixedSizeArray<'db>,
725) -> Maybe<()> {
726    if size > &BigInt::from(i16::MAX) {
727        return Err(diagnostics.report(syntax.stable_ptr(db), FixedSizeArraySizeTooBig));
728    }
729    Ok(())
730}
731
732#[derive(Clone, Debug, PartialEq, Eq, salsa::Update)]
733pub struct TypeInfo<'db> {
734    pub droppable: Result<ImplId<'db>, InferenceError<'db>>,
735    pub copyable: Result<ImplId<'db>, InferenceError<'db>>,
736    pub destruct_impl: Result<ImplId<'db>, InferenceError<'db>>,
737    pub panic_destruct_impl: Result<ImplId<'db>, InferenceError<'db>>,
738}
739
740/// Checks if there is at least one impl that can be inferred for a specific concrete trait.
741pub fn get_impl_at_context<'db>(
742    db: &'db dyn Database,
743    lookup_context: ImplLookupContextId<'db>,
744    concrete_trait_id: ConcreteTraitId<'db>,
745    stable_ptr: Option<SyntaxStablePtrId<'db>>,
746) -> Result<ImplId<'db>, InferenceError<'db>> {
747    let constrains =
748        db.generic_params_type_constraints(lookup_context.long(db).generic_params.clone());
749    if constrains.is_empty() && concrete_trait_id.is_var_free(db) {
750        return solve_concrete_trait_no_constraints(db, lookup_context, concrete_trait_id);
751    }
752    let mut inference_data = InferenceData::new(InferenceId::NoContext);
753    let mut inference = inference_data.inference(db);
754    inference.conform_generic_params_type_constraints(constrains);
755    // It's ok to consume the errors without reporting as this is a helper function meant to find an
756    // impl and return it, but it's ok if the impl can't be found.
757    let impl_id = inference.new_impl_var(concrete_trait_id, stable_ptr, lookup_context);
758    if let Err((err_set, _)) = inference.finalize_without_reporting() {
759        return Err(inference
760            .consume_error_without_reporting(err_set)
761            .expect("Error couldn't be already consumed"));
762    };
763    Ok(inference.rewrite(impl_id).no_err())
764}
765
766/// Implementation of [TypesSemantic::single_value_type].
767fn single_value_type(db: &dyn Database, ty: TypeId<'_>) -> Maybe<bool> {
768    Ok(match ty.long(db) {
769        TypeLongId::Concrete(concrete_type_id) => match concrete_type_id {
770            ConcreteTypeId::Struct(id) => {
771                for member in db.struct_members(id.struct_id(db))?.values() {
772                    if !db.single_value_type(member.ty)? {
773                        return Ok(false);
774                    }
775                }
776                true
777            }
778            ConcreteTypeId::Enum(id) => {
779                let variants = db.enum_variants(id.enum_id(db))?;
780                if variants.len() != 1 {
781                    return Ok(false);
782                }
783
784                db.single_value_type(
785                    db.variant_semantic(id.enum_id(db), *variants.values().next().unwrap())?.ty,
786                )?
787            }
788            ConcreteTypeId::Extern(_) => false,
789        },
790        TypeLongId::Tuple(types) => {
791            for ty in types {
792                if !db.single_value_type(*ty)? {
793                    return Ok(false);
794                }
795            }
796            true
797        }
798        TypeLongId::Snapshot(ty) => db.single_value_type(*ty)?,
799        TypeLongId::GenericParameter(_)
800        | TypeLongId::Var(_)
801        | TypeLongId::Missing(_)
802        | TypeLongId::Coupon(_)
803        | TypeLongId::ImplType(_)
804        | TypeLongId::Closure(_) => false,
805        TypeLongId::FixedSizeArray { type_id, size } => {
806            db.single_value_type(*type_id)?
807                || matches!(size.long(db),
808                            ConstValue::Int(value, _) if value.is_zero())
809        }
810    })
811}
812
813/// Query implementation of [TypesSemantic::single_value_type].
814#[salsa::tracked]
815fn single_value_type_tracked<'db>(db: &'db dyn Database, ty: TypeId<'db>) -> Maybe<bool> {
816    single_value_type(db, ty)
817}
818
819/// Adds diagnostics for a type, post semantic analysis of types.
820pub fn add_type_based_diagnostics<'db>(
821    db: &'db dyn Database,
822    diagnostics: &mut SemanticDiagnostics<'db>,
823    ty: TypeId<'db>,
824    stable_ptr: impl Into<SyntaxStablePtrId<'db>> + Copy,
825) {
826    if db.type_size_info(ty) == Ok(TypeSizeInformation::Infinite) {
827        diagnostics.report(stable_ptr, InfiniteSizeType(ty));
828    }
829    if let TypeLongId::Concrete(ConcreteTypeId::Extern(extrn)) = ty.long(db) {
830        let long_id = extrn.long(db);
831        if long_id.extern_type_id.name(db).long(db) == "Array"
832            && let [GenericArgumentId::Type(arg_ty)] = &long_id.generic_args[..]
833            && db.type_size_info(*arg_ty) == Ok(TypeSizeInformation::ZeroSized)
834        {
835            diagnostics.report(stable_ptr, ArrayOfZeroSizedElements(*arg_ty));
836        }
837    }
838}
839
840#[derive(Clone, Debug, PartialEq, Eq)]
841pub enum TypeSizeInformation {
842    /// The type has an infinite size - caused by a recursion in it.
843    /// If the type simply holds an infinite type, it would be considered `Other`, for diagnostics
844    /// reasons.
845    Infinite,
846    /// The type is zero size.
847    ZeroSized,
848    /// The typed has some none zero size.
849    Other,
850}
851
852/// Implementation of [TypesSemantic::type_size_info].
853fn type_size_info(db: &dyn Database, ty: TypeId<'_>) -> Maybe<TypeSizeInformation> {
854    match ty.long(db) {
855        TypeLongId::Concrete(concrete_type_id) => match concrete_type_id {
856            ConcreteTypeId::Struct(id) => {
857                if check_all_type_are_zero_sized(
858                    db,
859                    db.concrete_struct_members(*id)?.iter().map(|(_, member)| &member.ty),
860                )? {
861                    return Ok(TypeSizeInformation::ZeroSized);
862                }
863            }
864            ConcreteTypeId::Enum(id) => {
865                for variant in &db.concrete_enum_variants(*id)? {
866                    // Recursive calling in order to find infinite sized types.
867                    db.type_size_info(variant.ty)?;
868                }
869            }
870            ConcreteTypeId::Extern(_) => {}
871        },
872        TypeLongId::Tuple(types) => {
873            if check_all_type_are_zero_sized(db, types.iter())? {
874                return Ok(TypeSizeInformation::ZeroSized);
875            }
876        }
877        TypeLongId::Snapshot(ty) => {
878            if db.type_size_info(*ty)? == TypeSizeInformation::ZeroSized {
879                return Ok(TypeSizeInformation::ZeroSized);
880            }
881        }
882        TypeLongId::Closure(closure_ty) => {
883            if check_all_type_are_zero_sized(db, closure_ty.captured_types.iter())? {
884                return Ok(TypeSizeInformation::ZeroSized);
885            }
886        }
887        TypeLongId::Coupon(_) => return Ok(TypeSizeInformation::ZeroSized),
888        TypeLongId::GenericParameter(_)
889        | TypeLongId::Var(_)
890        | TypeLongId::Missing(_)
891        | TypeLongId::ImplType(_) => {}
892        TypeLongId::FixedSizeArray { type_id, size } => {
893            if matches!(size.long(db), ConstValue::Int(value,_) if value.is_zero())
894                || db.type_size_info(*type_id)? == TypeSizeInformation::ZeroSized
895            {
896                return Ok(TypeSizeInformation::ZeroSized);
897            }
898        }
899    }
900    Ok(TypeSizeInformation::Other)
901}
902
903/// Query implementation of [TypesSemantic::type_size_info].
904#[salsa::tracked(cycle_result=type_size_info_cycle)]
905fn type_size_info_tracked<'db>(
906    db: &'db dyn Database,
907    ty: TypeId<'db>,
908) -> Maybe<TypeSizeInformation> {
909    type_size_info(db, ty)
910}
911
912/// Checks if all types in the iterator are zero sized.
913fn check_all_type_are_zero_sized<'a>(
914    db: &dyn Database,
915    types: impl Iterator<Item = &'a TypeId<'a>>,
916) -> Maybe<bool> {
917    let mut zero_sized = true;
918    for ty in types {
919        if db.type_size_info(*ty)? != TypeSizeInformation::ZeroSized {
920            zero_sized = false;
921        }
922    }
923    Ok(zero_sized)
924}
925
926/// Cycle handling of [TypesSemantic::type_size_info].
927fn type_size_info_cycle<'db>(
928    _db: &'db dyn Database,
929    _ty: TypeId<'db>,
930) -> Maybe<TypeSizeInformation> {
931    Ok(TypeSizeInformation::Infinite)
932}
933
934// TODO(spapini): type info lookup for non generic types needs to not depend on lookup_context.
935// This is to ensure that sierra generator will see a consistent type info of types.
936/// Implementation of [TypesSemantic::type_info].
937fn type_info<'db>(
938    db: &'db dyn Database,
939    lookup_context: ImplLookupContextId<'db>,
940    ty: TypeId<'db>,
941) -> TypeInfo<'db> {
942    // Dummy stable pointer for type inference variables, since inference is disabled.
943    let droppable = get_impl_at_context(db, lookup_context, concrete_drop_trait(db, ty), None);
944    let copyable = get_impl_at_context(db, lookup_context, concrete_copy_trait(db, ty), None);
945    let destruct_impl =
946        get_impl_at_context(db, lookup_context, concrete_destruct_trait(db, ty), None);
947    let panic_destruct_impl =
948        get_impl_at_context(db, lookup_context, concrete_panic_destruct_trait(db, ty), None);
949    TypeInfo { droppable, copyable, destruct_impl, panic_destruct_impl }
950}
951
952/// Query implementation of [TypesSemantic::type_info].
953#[salsa::tracked]
954fn type_info_tracked<'db>(
955    db: &'db dyn Database,
956    lookup_context: ImplLookupContextId<'db>,
957    ty: TypeId<'db>,
958) -> TypeInfo<'db> {
959    type_info(db, lookup_context, ty)
960}
961
962/// Solves a concrete trait without any constraints.
963/// Only works when the given trait is var free.
964fn solve_concrete_trait_no_constraints<'db>(
965    db: &'db dyn Database,
966    lookup_context: ImplLookupContextId<'db>,
967    id: ConcreteTraitId<'db>,
968) -> Result<ImplId<'db>, InferenceError<'db>> {
969    let mut lookup_context = lookup_context.long(db).clone();
970    enrich_lookup_context(db, id, &mut lookup_context);
971    let lookup_context = lookup_context.intern(db);
972    match db.canonic_trait_solutions(
973        CanonicalTrait { id, mappings: Default::default() },
974        lookup_context,
975        Default::default(),
976    )? {
977        SolutionSet::None => Err(InferenceError::NoImplsFound(id)),
978        SolutionSet::Unique(solution) => Ok(solution.0),
979        SolutionSet::Ambiguous(ambiguity) => Err(InferenceError::Ambiguity(ambiguity)),
980    }
981}
982
983/// Implementation of [TypesSemantic::copyable].
984fn copyable<'db>(
985    db: &'db dyn Database,
986    ty: TypeId<'db>,
987) -> Result<ImplId<'db>, InferenceError<'db>> {
988    solve_concrete_trait_no_constraints(
989        db,
990        ImplLookupContext::new_from_type(ty, db).intern(db),
991        concrete_copy_trait(db, ty),
992    )
993}
994
995/// Query implementation of [TypesSemantic::copyable].
996#[salsa::tracked]
997fn copyable_tracked<'db>(
998    db: &'db dyn Database,
999    ty: TypeId<'db>,
1000) -> Result<ImplId<'db>, InferenceError<'db>> {
1001    copyable(db, ty)
1002}
1003
1004/// Implementation of [TypesSemantic::droppable].
1005fn droppable<'db>(
1006    db: &'db dyn Database,
1007    ty: TypeId<'db>,
1008) -> Result<ImplId<'db>, InferenceError<'db>> {
1009    solve_concrete_trait_no_constraints(
1010        db,
1011        ImplLookupContext::new_from_type(ty, db).intern(db),
1012        concrete_drop_trait(db, ty),
1013    )
1014}
1015
1016/// Query implementation of [TypesSemantic::droppable].
1017#[salsa::tracked]
1018fn droppable_tracked<'db>(
1019    db: &'db dyn Database,
1020    ty: TypeId<'db>,
1021) -> Result<ImplId<'db>, InferenceError<'db>> {
1022    droppable(db, ty)
1023}
1024
1025/// Implementation of [PrivTypesSemantic::priv_type_is_fully_concrete].
1026fn priv_type_is_fully_concrete(db: &dyn Database, ty: TypeId<'_>) -> bool {
1027    match ty.long(db) {
1028        TypeLongId::Concrete(concrete_type_id) => concrete_type_id.is_fully_concrete(db),
1029        TypeLongId::Tuple(types) => types.iter().all(|ty| ty.is_fully_concrete(db)),
1030        TypeLongId::Snapshot(ty) => ty.is_fully_concrete(db),
1031        TypeLongId::GenericParameter(_)
1032        | TypeLongId::Var(_)
1033        | TypeLongId::Missing(_)
1034        | TypeLongId::ImplType(_) => false,
1035        TypeLongId::Coupon(function_id) => function_id.is_fully_concrete(db),
1036        TypeLongId::FixedSizeArray { type_id, size } => {
1037            type_id.is_fully_concrete(db) && size.is_fully_concrete(db)
1038        }
1039        TypeLongId::Closure(closure) => {
1040            closure.parent_function.map(|id| id.is_fully_concrete(db)).unwrap_or(true)
1041                && closure.param_tys.iter().all(|param| param.is_fully_concrete(db))
1042                && closure.ret_ty.is_fully_concrete(db)
1043        }
1044    }
1045}
1046
1047/// Query implementation of [PrivTypesSemantic::priv_type_is_fully_concrete].
1048#[salsa::tracked]
1049pub fn priv_type_is_fully_concrete_tracked<'db>(db: &'db dyn Database, ty: TypeId<'db>) -> bool {
1050    priv_type_is_fully_concrete(db, ty)
1051}
1052
1053pub fn priv_type_is_var_free<'db>(db: &'db dyn Database, ty: TypeId<'db>) -> bool {
1054    match ty.long(db) {
1055        TypeLongId::Concrete(concrete_type_id) => concrete_type_id.is_var_free(db),
1056        TypeLongId::Tuple(types) => types.iter().all(|ty| ty.is_var_free(db)),
1057        TypeLongId::Snapshot(ty) => ty.is_var_free(db),
1058        TypeLongId::Var(_) => false,
1059        TypeLongId::GenericParameter(_) | TypeLongId::Missing(_) => true,
1060        TypeLongId::Coupon(function_id) => function_id.is_var_free(db),
1061        TypeLongId::FixedSizeArray { type_id, size } => {
1062            type_id.is_var_free(db) && size.is_var_free(db)
1063        }
1064        // TODO(TomerStarkware): consider rename the function to `priv_type_might_need_rewrite`.
1065        // a var free ImplType needs to be rewritten if has impl bounds constraints.
1066        TypeLongId::ImplType(_) => false,
1067        TypeLongId::Closure(closure) => {
1068            chain!(&closure.captured_types, &closure.param_tys).all(|param| param.is_var_free(db))
1069                && closure.ret_ty.is_var_free(db)
1070        }
1071    }
1072}
1073
1074/// Query implementation of [PrivTypesSemantic::priv_type_is_var_free].
1075#[salsa::tracked]
1076pub fn priv_type_is_var_free_tracked<'db>(db: &'db dyn Database, ty: TypeId<'db>) -> bool {
1077    priv_type_is_var_free(db, ty)
1078}
1079
1080pub fn priv_type_short_name(db: &dyn Database, ty: TypeId<'_>) -> String {
1081    match ty.long(db) {
1082        TypeLongId::Concrete(concrete_type_id) => {
1083            let mut result = concrete_type_id.generic_type(db).format(db);
1084            let mut generic_args = concrete_type_id.generic_args(db).into_iter().peekable();
1085            if generic_args.peek().is_some() {
1086                result.push_str("::<h0x");
1087                let mut hasher = Keccak256::new();
1088                for arg in generic_args {
1089                    hasher.update(arg.short_name(db).as_bytes());
1090                }
1091                for c in hasher.finalize() {
1092                    result.push_str(&format!("{c:x}"));
1093                }
1094                result.push('>');
1095            }
1096            result
1097        }
1098        TypeLongId::Tuple(types) => {
1099            let mut result = String::from("(h0x");
1100            let mut hasher = Keccak256::new();
1101            for ty in types {
1102                hasher.update(ty.short_name(db).as_bytes());
1103            }
1104            for c in hasher.finalize() {
1105                result.push_str(&format!("{c:x}"));
1106            }
1107            result.push(')');
1108            result
1109        }
1110        TypeLongId::Snapshot(ty) => {
1111            format!("@{}", ty.short_name(db))
1112        }
1113        TypeLongId::FixedSizeArray { type_id, size } => {
1114            format!("[{}; {:?}", type_id.short_name(db), size.debug(db))
1115        }
1116        other => other.format(db),
1117    }
1118}
1119
1120#[salsa::tracked]
1121pub fn priv_type_short_name_tracked<'db>(db: &'db dyn Database, ty: TypeId<'db>) -> String {
1122    priv_type_short_name(db, ty)
1123}
1124
1125/// Peels all wrapping Snapshot (`@`) from the type.
1126/// Returns the number of peeled snapshots and the inner type.
1127pub fn peel_snapshots<'db>(db: &'db dyn Database, ty: TypeId<'db>) -> (usize, TypeLongId<'db>) {
1128    peel_snapshots_ex(db, ty.long(db).clone())
1129}
1130
1131/// Same as `peel_snapshots`, but takes a `TypeLongId` instead of a `TypeId`.
1132pub fn peel_snapshots_ex<'db>(
1133    db: &'db dyn Database,
1134    mut long_ty: TypeLongId<'db>,
1135) -> (usize, TypeLongId<'db>) {
1136    let mut n_snapshots = 0;
1137    while let TypeLongId::Snapshot(ty) = long_ty {
1138        long_ty = ty.long(db).clone();
1139        n_snapshots += 1;
1140    }
1141    (n_snapshots, long_ty)
1142}
1143
1144/// Wraps a type with Snapshot (`@`) `n_snapshots` times.
1145pub fn wrap_in_snapshots<'db>(
1146    db: &'db dyn Database,
1147    mut ty: TypeId<'db>,
1148    n_snapshots: usize,
1149) -> TypeId<'db> {
1150    for _ in 0..n_snapshots {
1151        ty = TypeLongId::Snapshot(ty).intern(db);
1152    }
1153    ty
1154}
1155
1156/// Returns `true` if coupons are enabled in the module.
1157pub(crate) fn are_coupons_enabled(db: &dyn Database, module_id: ModuleId<'_>) -> bool {
1158    let owning_crate = module_id.owning_crate(db);
1159    let Some(config) = db.crate_config(owning_crate) else { return false };
1160    config.settings.experimental_features.coupons
1161}
1162
1163/// Trait for types-related semantic queries.
1164pub trait TypesSemantic<'db>: Database {
1165    /// Returns the generic params of a generic type.
1166    fn generic_type_generic_params(
1167        &'db self,
1168        generic_type: GenericTypeId<'db>,
1169    ) -> Maybe<&'db [semantic::GenericParam<'db>]> {
1170        match generic_type {
1171            GenericTypeId::Struct(id) => self.struct_generic_params(id),
1172            GenericTypeId::Enum(id) => self.enum_generic_params(id),
1173            GenericTypeId::Extern(id) => self.extern_type_declaration_generic_params(id),
1174        }
1175    }
1176    /// Returns true if there is only one value for the given type and hence the values of the given
1177    /// type are all interchangeable.
1178    /// Examples include the unit type tuple of a unit type and empty structs.
1179    /// Always returns false for extern types.
1180    fn single_value_type(&'db self, ty: TypeId<'db>) -> Maybe<bool> {
1181        single_value_type_tracked(self.as_dyn_database(), ty)
1182    }
1183    /// Returns the type size information for the given type.
1184    fn type_size_info(&'db self, ty: TypeId<'db>) -> Maybe<TypeSizeInformation> {
1185        type_size_info_tracked(self.as_dyn_database(), ty)
1186    }
1187    /// Returns the type info for a type in a context.
1188    fn type_info(
1189        &'db self,
1190        lookup_context: ImplLookupContextId<'db>,
1191        ty: TypeId<'db>,
1192    ) -> TypeInfo<'db> {
1193        type_info_tracked(self.as_dyn_database(), lookup_context, ty)
1194    }
1195    /// Returns the `Copy` impl for a type in general context.
1196    fn copyable(&'db self, ty: TypeId<'db>) -> Result<ImplId<'db>, InferenceError<'db>> {
1197        copyable_tracked(self.as_dyn_database(), ty)
1198    }
1199    /// Returns the `Drop` impl for a type in general context.
1200    fn droppable(&'db self, ty: TypeId<'db>) -> Result<ImplId<'db>, InferenceError<'db>> {
1201        droppable_tracked(self.as_dyn_database(), ty)
1202    }
1203}
1204impl<'db, T: Database + ?Sized> TypesSemantic<'db> for T {}
1205
1206/// Private trait for types-related semantic queries.
1207pub trait PrivTypesSemantic<'db>: Database {
1208    /// Private query to check if a type is fully concrete.
1209    fn priv_type_is_fully_concrete(&self, ty: TypeId<'db>) -> bool {
1210        priv_type_is_fully_concrete_tracked(self.as_dyn_database(), ty)
1211    }
1212    /// Private query to check if a type contains no variables.
1213    fn priv_type_is_var_free(&self, ty: TypeId<'db>) -> bool {
1214        priv_type_is_var_free_tracked(self.as_dyn_database(), ty)
1215    }
1216    /// Private query for a shorter unique name for types.
1217    fn priv_type_short_name(&self, ty: TypeId<'db>) -> String {
1218        priv_type_short_name_tracked(self.as_dyn_database(), ty)
1219    }
1220}
1221impl<'db, T: Database + ?Sized> PrivTypesSemantic<'db> for T {}