cairo_lang_sierra/extensions/modules/
consts.rs

1use num_bigint::BigInt;
2use num_traits::Signed;
3
4use crate::extensions::lib_func::{
5    DeferredOutputKind, LibfuncSignature, OutputVarInfo, SierraApChange,
6    SignatureSpecializationContext, SpecializationContext,
7};
8use crate::extensions::{
9    NamedLibfunc, OutputVarReferenceInfo, SignatureBasedConcreteLibfunc, SpecializationError,
10    args_as_single_value,
11};
12use crate::ids::GenericTypeId;
13use crate::program::GenericArg;
14
15/// Trait for implementing a library function that returns a const of a given type.
16pub trait ConstGenLibfunc: Default {
17    /// The library function id.
18    const STR_ID: &'static str;
19    /// The id of the generic type to implement the library functions for.
20    const GENERIC_TYPE_ID: GenericTypeId;
21    /// The bound on the value of the type.
22    fn bound() -> BigInt;
23}
24
25/// Wrapper to prevent implementation collisions for `NamedLibfunc`.
26#[derive(Default)]
27pub struct WrapConstGenLibfunc<T: ConstGenLibfunc>(T);
28
29impl<T: ConstGenLibfunc> NamedLibfunc for WrapConstGenLibfunc<T> {
30    const STR_ID: &'static str = <T as ConstGenLibfunc>::STR_ID;
31    type Concrete = SignatureAndConstConcreteLibfunc;
32
33    fn specialize_signature(
34        &self,
35        context: &dyn SignatureSpecializationContext,
36        _args: &[GenericArg],
37    ) -> Result<LibfuncSignature, SpecializationError> {
38        Ok(LibfuncSignature::new_non_branch(
39            vec![],
40            vec![OutputVarInfo {
41                ty: context.get_concrete_type(<T as ConstGenLibfunc>::GENERIC_TYPE_ID, &[])?,
42                ref_info: OutputVarReferenceInfo::Deferred(DeferredOutputKind::Const),
43            }],
44            SierraApChange::Known { new_vars_only: true },
45        ))
46    }
47
48    fn specialize(
49        &self,
50        context: &dyn SpecializationContext,
51        args: &[GenericArg],
52    ) -> Result<Self::Concrete, SpecializationError> {
53        let c = args_as_single_value(args)?;
54        if c.is_negative() || c > (<T as ConstGenLibfunc>::bound()) {
55            return Err(SpecializationError::UnsupportedGenericArg);
56        }
57        Ok(SignatureAndConstConcreteLibfunc {
58            c: c.clone(),
59            signature: <Self as NamedLibfunc>::specialize_signature(self, context.upcast(), args)?,
60        })
61    }
62}
63
64/// Struct providing a ConcreteLibfunc signature and a const.
65pub struct SignatureAndConstConcreteLibfunc {
66    pub c: BigInt,
67    pub signature: LibfuncSignature,
68}
69impl SignatureBasedConcreteLibfunc for SignatureAndConstConcreteLibfunc {
70    fn signature(&self) -> &LibfuncSignature {
71        &self.signature
72    }
73}