1use std::iter;
2
3use cairo_lang_casm::ap_change::{ApChangeError, ApplyApChange};
4use cairo_lang_sierra::edit_state::{put_results, take_args};
5use cairo_lang_sierra::ids::{ConcreteTypeId, FunctionId, VarId};
6use cairo_lang_sierra::program::{BranchInfo, Function, StatementIdx};
7use cairo_lang_sierra_type_size::TypeSizeMap;
8use cairo_lang_utils::unordered_hash_set::UnorderedHashSet;
9use itertools::{chain, zip_eq};
10use thiserror::Error;
11
12use crate::environment::ap_tracking::update_ap_tracking;
13use crate::environment::frame_state::FrameStateError;
14use crate::environment::gas_wallet::{GasWallet, GasWalletError};
15use crate::environment::{
16 ApTracking, ApTrackingBase, Environment, EnvironmentError, validate_environment_equality,
17 validate_final_environment,
18};
19use crate::invocations::{ApTrackingChange, BranchChanges};
20use crate::metadata::Metadata;
21use crate::references::{
22 IntroductionPoint, OutputReferenceValueIntroductionPoint, ReferenceExpression, ReferenceValue,
23 ReferencesError, StatementRefs, build_function_parameters_refs, check_types_match,
24};
25
26#[derive(Error, Debug, Eq, PartialEq)]
27pub enum AnnotationError {
28 #[error("#{statement_idx}: Inconsistent references annotations: {error}")]
29 InconsistentReferencesAnnotation {
30 statement_idx: StatementIdx,
31 error: InconsistentReferenceError,
32 },
33 #[error("#{source_statement_idx}->#{destination_statement_idx}: Annotation was already set.")]
34 AnnotationAlreadySet {
35 source_statement_idx: StatementIdx,
36 destination_statement_idx: StatementIdx,
37 },
38 #[error("#{statement_idx}: {error}")]
39 InconsistentEnvironments { statement_idx: StatementIdx, error: EnvironmentError },
40 #[error("#{statement_idx}: Belongs to two different functions.")]
41 InconsistentFunctionId { statement_idx: StatementIdx },
42 #[error("#{statement_idx}: Invalid convergence.")]
43 InvalidConvergence { statement_idx: StatementIdx },
44 #[error("InvalidStatementIdx")]
45 InvalidStatementIdx,
46 #[error("MissingAnnotationsForStatement")]
47 MissingAnnotationsForStatement(StatementIdx),
48 #[error("#{statement_idx}: {var_id} is undefined.")]
49 MissingReferenceError { statement_idx: StatementIdx, var_id: VarId },
50 #[error("#{source_statement_idx}->#{destination_statement_idx}: {var_id} was overridden.")]
51 OverrideReferenceError {
52 source_statement_idx: StatementIdx,
53 destination_statement_idx: StatementIdx,
54 var_id: VarId,
55 },
56 #[error(transparent)]
57 FrameStateError(#[from] FrameStateError),
58 #[error("#{source_statement_idx}->#{destination_statement_idx}: {error}")]
59 GasWalletError {
60 source_statement_idx: StatementIdx,
61 destination_statement_idx: StatementIdx,
62 error: GasWalletError,
63 },
64 #[error("#{statement_idx}: {error}")]
65 ReferencesError { statement_idx: StatementIdx, error: ReferencesError },
66 #[error("#{statement_idx}: Attempting to enable ap tracking when already enabled.")]
67 ApTrackingAlreadyEnabled { statement_idx: StatementIdx },
68 #[error(
69 "#{source_statement_idx}->#{destination_statement_idx}: Got '{error}' error while moving \
70 {var_id} introduced at {} .", {introduction_point}
71 )]
72 ApChangeError {
73 var_id: VarId,
74 source_statement_idx: StatementIdx,
75 destination_statement_idx: StatementIdx,
76 introduction_point: IntroductionPoint,
77 error: ApChangeError,
78 },
79 #[error("#{source_statement_idx} -> #{destination_statement_idx}: Ap tracking error")]
80 ApTrackingError {
81 source_statement_idx: StatementIdx,
82 destination_statement_idx: StatementIdx,
83 error: ApChangeError,
84 },
85 #[error(
86 "#{statement_idx}: Invalid function ap change annotation. Expected ap tracking: \
87 {expected:?}, got: {actual:?}."
88 )]
89 InvalidFunctionApChange {
90 statement_idx: StatementIdx,
91 expected: ApTracking,
92 actual: ApTracking,
93 },
94}
95
96impl AnnotationError {
97 pub fn stmt_indices(&self) -> Vec<StatementIdx> {
98 match self {
99 AnnotationError::ApChangeError {
100 source_statement_idx,
101 destination_statement_idx,
102 introduction_point,
103 ..
104 } => chain!(
105 [source_statement_idx, destination_statement_idx],
106 &introduction_point.source_statement_idx,
107 [&introduction_point.destination_statement_idx]
108 )
109 .cloned()
110 .collect(),
111 _ => vec![],
112 }
113 }
114}
115
116#[derive(Error, Debug, Eq, PartialEq)]
118pub enum InconsistentReferenceError {
119 #[error("Variable {var} type mismatch. Expected `{expected}`, got `{actual}`.")]
120 TypeMismatch { var: VarId, expected: ConcreteTypeId, actual: ConcreteTypeId },
121 #[error("Variable {var} expression mismatch. Expected `{expected}`, got `{actual}`.")]
122 ExpressionMismatch { var: VarId, expected: ReferenceExpression, actual: ReferenceExpression },
123 #[error("Variable {var} stack index mismatch. Expected `{expected:?}`, got `{actual:?}`.")]
124 StackIndexMismatch { var: VarId, expected: Option<usize>, actual: Option<usize> },
125 #[error("Variable {var} introduction point mismatch. Expected `{expected}`, got `{actual}`.")]
126 IntroductionPointMismatch { var: VarId, expected: IntroductionPoint, actual: IntroductionPoint },
127 #[error("Variable count mismatch.")]
128 VariableCountMismatch,
129 #[error("Missing expected variable {0}.")]
130 VariableMissing(VarId),
131 #[error("Ap tracking is disabled while trying to merge {0}.")]
132 ApTrackingDisabled(VarId),
133}
134
135#[derive(Clone, Debug)]
137pub struct StatementAnnotations {
138 pub refs: StatementRefs,
139 pub function_id: FunctionId,
141 pub convergence_allowed: bool,
143 pub environment: Environment,
144}
145
146pub struct ProgramAnnotations {
149 per_statement_annotations: Vec<Option<StatementAnnotations>>,
151 backwards_jump_indices: UnorderedHashSet<StatementIdx>,
153}
154impl ProgramAnnotations {
155 fn new(n_statements: usize, backwards_jump_indices: UnorderedHashSet<StatementIdx>) -> Self {
156 ProgramAnnotations {
157 per_statement_annotations: iter::repeat_with(|| None).take(n_statements).collect(),
158 backwards_jump_indices,
159 }
160 }
161
162 pub fn create(
165 n_statements: usize,
166 backwards_jump_indices: UnorderedHashSet<StatementIdx>,
167 functions: &[Function],
168 metadata: &Metadata,
169 gas_usage_check: bool,
170 type_sizes: &TypeSizeMap,
171 ) -> Result<Self, AnnotationError> {
172 let mut annotations = ProgramAnnotations::new(n_statements, backwards_jump_indices);
173 for func in functions {
174 annotations.set_or_assert(func.entry_point, StatementAnnotations {
175 refs: build_function_parameters_refs(func, type_sizes).map_err(|error| {
176 AnnotationError::ReferencesError { statement_idx: func.entry_point, error }
177 })?,
178 function_id: func.id.clone(),
179 convergence_allowed: false,
180 environment: Environment::new(if gas_usage_check {
181 GasWallet::Value(metadata.gas_info.function_costs[&func.id].clone())
182 } else {
183 GasWallet::Disabled
184 }),
185 })?
186 }
187
188 Ok(annotations)
189 }
190
191 pub fn set_or_assert(
196 &mut self,
197 statement_idx: StatementIdx,
198 annotations: StatementAnnotations,
199 ) -> Result<(), AnnotationError> {
200 let idx = statement_idx.0;
201 match self.per_statement_annotations.get(idx).ok_or(AnnotationError::InvalidStatementIdx)? {
202 None => self.per_statement_annotations[idx] = Some(annotations),
203 Some(expected_annotations) => {
204 if expected_annotations.function_id != annotations.function_id {
205 return Err(AnnotationError::InconsistentFunctionId { statement_idx });
206 }
207 validate_environment_equality(
208 &expected_annotations.environment,
209 &annotations.environment,
210 )
211 .map_err(|error| AnnotationError::InconsistentEnvironments {
212 statement_idx,
213 error,
214 })?;
215 self.test_references_consistency(&annotations, expected_annotations).map_err(
216 |error| AnnotationError::InconsistentReferencesAnnotation {
217 statement_idx,
218 error,
219 },
220 )?;
221
222 if !expected_annotations.convergence_allowed {
225 return Err(AnnotationError::InvalidConvergence { statement_idx });
226 }
227 }
228 };
229 Ok(())
230 }
231
232 fn test_references_consistency(
235 &self,
236 actual: &StatementAnnotations,
237 expected: &StatementAnnotations,
238 ) -> Result<(), InconsistentReferenceError> {
239 if actual.refs.len() != expected.refs.len() {
241 return Err(InconsistentReferenceError::VariableCountMismatch);
242 }
243 let ap_tracking_enabled =
244 matches!(actual.environment.ap_tracking, ApTracking::Enabled { .. });
245 for (var_id, actual_ref) in actual.refs.iter() {
246 let Some(expected_ref) = expected.refs.get(var_id) else {
248 return Err(InconsistentReferenceError::VariableMissing(var_id.clone()));
249 };
250 if actual_ref.ty != expected_ref.ty {
252 return Err(InconsistentReferenceError::TypeMismatch {
253 var: var_id.clone(),
254 expected: expected_ref.ty.clone(),
255 actual: actual_ref.ty.clone(),
256 });
257 }
258 if actual_ref.expression != expected_ref.expression {
259 return Err(InconsistentReferenceError::ExpressionMismatch {
260 var: var_id.clone(),
261 expected: expected_ref.expression.clone(),
262 actual: actual_ref.expression.clone(),
263 });
264 }
265 if actual_ref.stack_idx != expected_ref.stack_idx {
266 return Err(InconsistentReferenceError::StackIndexMismatch {
267 var: var_id.clone(),
268 expected: expected_ref.stack_idx,
269 actual: actual_ref.stack_idx,
270 });
271 }
272 test_var_consistency(var_id, actual_ref, expected_ref, ap_tracking_enabled)?;
273 }
274 Ok(())
275 }
276
277 pub fn get_annotations_after_take_args<'a>(
281 &mut self,
282 statement_idx: StatementIdx,
283 ref_ids: impl Iterator<Item = &'a VarId>,
284 ) -> Result<(StatementAnnotations, Vec<ReferenceValue>), AnnotationError> {
285 let existing = self.per_statement_annotations[statement_idx.0]
286 .as_mut()
287 .ok_or(AnnotationError::MissingAnnotationsForStatement(statement_idx))?;
288 let mut updated = if self.backwards_jump_indices.contains(&statement_idx) {
289 existing.clone()
290 } else {
291 std::mem::replace(existing, StatementAnnotations {
292 refs: Default::default(),
293 function_id: existing.function_id.clone(),
294 convergence_allowed: false,
296 environment: existing.environment.clone(),
297 })
298 };
299 let refs = std::mem::take(&mut updated.refs);
300 let (statement_refs, taken_refs) = take_args(refs, ref_ids).map_err(|error| {
301 AnnotationError::MissingReferenceError { statement_idx, var_id: error.var_id() }
302 })?;
303 updated.refs = statement_refs;
304 Ok((updated, taken_refs))
305 }
306
307 pub fn propagate_annotations(
313 &mut self,
314 source_statement_idx: StatementIdx,
315 destination_statement_idx: StatementIdx,
316 mut annotations: StatementAnnotations,
317 branch_info: &BranchInfo,
318 branch_changes: BranchChanges,
319 must_set: bool,
320 ) -> Result<(), AnnotationError> {
321 if must_set && self.per_statement_annotations[destination_statement_idx.0].is_some() {
322 return Err(AnnotationError::AnnotationAlreadySet {
323 source_statement_idx,
324 destination_statement_idx,
325 });
326 }
327
328 for (var_id, ref_value) in annotations.refs.iter_mut() {
329 if branch_changes.clear_old_stack {
330 ref_value.stack_idx = None;
331 }
332 ref_value.expression =
333 std::mem::replace(&mut ref_value.expression, ReferenceExpression::zero_sized())
334 .apply_ap_change(branch_changes.ap_change)
335 .map_err(|error| AnnotationError::ApChangeError {
336 var_id: var_id.clone(),
337 source_statement_idx,
338 destination_statement_idx,
339 introduction_point: ref_value.introduction_point.clone(),
340 error,
341 })?;
342 }
343 let mut refs = put_results(
344 annotations.refs,
345 zip_eq(
346 &branch_info.results,
347 branch_changes.refs.into_iter().map(|value| ReferenceValue {
348 expression: value.expression,
349 ty: value.ty,
350 stack_idx: value.stack_idx,
351 introduction_point: match value.introduction_point {
352 OutputReferenceValueIntroductionPoint::New(output_idx) => {
353 IntroductionPoint {
354 source_statement_idx: Some(source_statement_idx),
355 destination_statement_idx,
356 output_idx,
357 }
358 }
359 OutputReferenceValueIntroductionPoint::Existing(introduction_point) => {
360 introduction_point
361 }
362 },
363 }),
364 ),
365 )
366 .map_err(|error| AnnotationError::OverrideReferenceError {
367 source_statement_idx,
368 destination_statement_idx,
369 var_id: error.var_id(),
370 })?;
371
372 let available_stack_indices: UnorderedHashSet<_> =
376 refs.values().flat_map(|r| r.stack_idx).collect();
377 let new_stack_size_opt = (0..branch_changes.new_stack_size)
378 .find(|i| !available_stack_indices.contains(&(branch_changes.new_stack_size - 1 - i)));
379 let stack_size = if let Some(new_stack_size) = new_stack_size_opt {
380 let stack_removal = branch_changes.new_stack_size - new_stack_size;
382 for (_, r) in refs.iter_mut() {
383 r.stack_idx =
386 r.stack_idx.and_then(|stack_idx| stack_idx.checked_sub(stack_removal));
387 }
388 new_stack_size
389 } else {
390 branch_changes.new_stack_size
391 };
392
393 let ap_tracking = match branch_changes.ap_tracking_change {
394 ApTrackingChange::Disable => ApTracking::Disabled,
395 ApTrackingChange::Enable => {
396 if !matches!(annotations.environment.ap_tracking, ApTracking::Disabled) {
397 return Err(AnnotationError::ApTrackingAlreadyEnabled {
398 statement_idx: source_statement_idx,
399 });
400 }
401 ApTracking::Enabled {
402 ap_change: 0,
403 base: ApTrackingBase::Statement(destination_statement_idx),
404 }
405 }
406 ApTrackingChange::None => {
407 update_ap_tracking(annotations.environment.ap_tracking, branch_changes.ap_change)
408 .map_err(|error| AnnotationError::ApTrackingError {
409 source_statement_idx,
410 destination_statement_idx,
411 error,
412 })?
413 }
414 };
415
416 self.set_or_assert(destination_statement_idx, StatementAnnotations {
417 refs,
418 function_id: annotations.function_id,
419 convergence_allowed: !must_set,
420 environment: Environment {
421 ap_tracking,
422 stack_size,
423 frame_state: annotations.environment.frame_state,
424 gas_wallet: annotations
425 .environment
426 .gas_wallet
427 .update(branch_changes.gas_change)
428 .map_err(|error| AnnotationError::GasWalletError {
429 source_statement_idx,
430 destination_statement_idx,
431 error,
432 })?,
433 },
434 })
435 }
436
437 pub fn validate_return_properties(
439 &self,
440 statement_idx: StatementIdx,
441 annotations: &StatementAnnotations,
442 functions: &[Function],
443 metadata: &Metadata,
444 return_refs: &[ReferenceValue],
445 ) -> Result<(), AnnotationError> {
446 let func = &functions.iter().find(|func| func.id == annotations.function_id).unwrap();
448
449 let expected_ap_tracking = match metadata.ap_change_info.function_ap_change.get(&func.id) {
450 Some(x) => ApTracking::Enabled { ap_change: *x, base: ApTrackingBase::FunctionStart },
451 None => ApTracking::Disabled,
452 };
453 if annotations.environment.ap_tracking != expected_ap_tracking {
454 return Err(AnnotationError::InvalidFunctionApChange {
455 statement_idx,
456 expected: expected_ap_tracking,
457 actual: annotations.environment.ap_tracking,
458 });
459 }
460
461 check_types_match(return_refs, &func.signature.ret_types)
463 .map_err(|error| AnnotationError::ReferencesError { statement_idx, error })?;
464 Ok(())
465 }
466
467 pub fn validate_final_annotations(
469 &self,
470 statement_idx: StatementIdx,
471 annotations: &StatementAnnotations,
472 functions: &[Function],
473 metadata: &Metadata,
474 return_refs: &[ReferenceValue],
475 ) -> Result<(), AnnotationError> {
476 self.validate_return_properties(
477 statement_idx,
478 annotations,
479 functions,
480 metadata,
481 return_refs,
482 )?;
483 validate_final_environment(&annotations.environment)
484 .map_err(|error| AnnotationError::InconsistentEnvironments { statement_idx, error })
485 }
486}
487
488fn test_var_consistency(
492 var_id: &VarId,
493 actual: &ReferenceValue,
494 expected: &ReferenceValue,
495 ap_tracking_enabled: bool,
496) -> Result<(), InconsistentReferenceError> {
497 if actual.stack_idx.is_some() {
499 return Ok(());
500 }
501 if actual.expression.can_apply_unknown() {
504 return Ok(());
505 }
506 if !ap_tracking_enabled {
508 return Err(InconsistentReferenceError::ApTrackingDisabled(var_id.clone()));
509 }
510 if actual.introduction_point == expected.introduction_point {
512 Ok(())
513 } else {
514 Err(InconsistentReferenceError::IntroductionPointMismatch {
515 var: var_id.clone(),
516 expected: expected.introduction_point.clone(),
517 actual: actual.introduction_point.clone(),
518 })
519 }
520}