cairo_annotations/annotations/
profiler.rsuse crate::annotations::impl_helpers::impl_namespace;
use cairo_lang_sierra::program::{Program, StatementIdx};
use derive_more::Display;
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
use std::sync::LazyLock;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum VersionedProfilerAnnotations {
V1(ProfilerAnnotationsV1),
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ProfilerAnnotationsV1 {
pub statements_functions: HashMap<StatementIdx, Vec<FunctionName>>,
}
static RE_LOOP_FUNC: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"\[expr\d*\]").expect("Failed to create regex for normalizing loop function names")
});
static RE_MONOMORPHIZATION: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"<.*>")
.expect("Failed to create regex for normalizing monomorphized generic function names")
});
#[derive(
Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize, Deserialize, Display, Default,
)]
pub struct FunctionName(pub String);
impl FunctionName {
#[must_use]
pub fn from_sierra_statement_idx(
statement_idx: StatementIdx,
sierra_program: &Program,
split_generics: bool,
) -> Self {
let function_idx = sierra_program
.funcs
.partition_point(|f| f.entry_point.0 <= statement_idx.0)
- 1;
let function_name = sierra_program.funcs[function_idx].id.to_string();
let function_name = RE_LOOP_FUNC.replace(&function_name, "");
let function_name = if split_generics {
function_name
} else {
RE_MONOMORPHIZATION.replace(&function_name, "")
};
Self(function_name.to_string())
}
}
impl Serialize for VersionedProfilerAnnotations {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
VersionedProfilerAnnotations::V1(v1) => v1.serialize(serializer),
}
}
}
impl<'de> Deserialize<'de> for VersionedProfilerAnnotations {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
ProfilerAnnotationsV1::deserialize(deserializer).map(VersionedProfilerAnnotations::V1)
}
}
impl_namespace!(
"github.com/software-mansion/cairo-profiler",
ProfilerAnnotationsV1,
VersionedProfilerAnnotations
);