1use std::fmt::Display;
2
3use cairo_lang_casm::assembler::AssembledCairoProgram;
4use cairo_lang_casm::instructions::{Instruction, InstructionBody, RetInstruction};
5use cairo_lang_sierra::extensions::ConcreteLibfunc;
6use cairo_lang_sierra::extensions::circuit::{CircuitConcreteLibfunc, CircuitInfo, VALUE_SIZE};
7use cairo_lang_sierra::extensions::const_type::ConstConcreteLibfunc;
8use cairo_lang_sierra::extensions::core::{
9 CoreConcreteLibfunc, CoreLibfunc, CoreType, CoreTypeConcrete,
10};
11use cairo_lang_sierra::extensions::coupon::CouponConcreteLibfunc;
12use cairo_lang_sierra::extensions::gas::GasConcreteLibfunc;
13use cairo_lang_sierra::extensions::lib_func::SierraApChange;
14use cairo_lang_sierra::ids::{ConcreteLibfuncId, ConcreteTypeId, VarId};
15use cairo_lang_sierra::program::{
16 BranchTarget, GenericArg, Invocation, Program, Statement, StatementIdx,
17};
18use cairo_lang_sierra::program_registry::{ProgramRegistry, ProgramRegistryError};
19use cairo_lang_sierra_type_size::ProgramRegistryInfo;
20use cairo_lang_utils::casts::IntoOrPanic;
21use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
22use cairo_lang_utils::unordered_hash_map::UnorderedHashMap;
23use cairo_lang_utils::unordered_hash_set::UnorderedHashSet;
24use itertools::{chain, zip_eq};
25use num_bigint::BigInt;
26use num_traits::{ToPrimitive, Zero};
27use thiserror::Error;
28
29use crate::annotations::{AnnotationError, ProgramAnnotations, StatementAnnotations};
30use crate::circuit::CircuitsInfo;
31use crate::invocations::enm::get_variant_selector;
32use crate::invocations::{
33 BranchChanges, InvocationError, ProgramInfo, check_references_on_stack, compile_invocation,
34};
35use crate::metadata::Metadata;
36use crate::references::{ReferenceValue, ReferencesError, check_types_match};
37use crate::relocations::{RelocationEntry, relocate_instructions};
38
39#[cfg(test)]
40#[path = "compiler_test.rs"]
41mod test;
42
43#[derive(Error, Debug, Eq, PartialEq)]
44pub enum CompilationError {
45 #[error("Error from program registry: {0}")]
46 ProgramRegistryError(Box<ProgramRegistryError>),
47 #[error(transparent)]
48 AnnotationError(#[from] AnnotationError),
49 #[error("#{statement_idx}: {error}")]
50 InvocationError { statement_idx: StatementIdx, error: InvocationError },
51 #[error("#{statement_idx}: Return arguments are not on the stack.")]
52 ReturnArgumentsNotOnStack { statement_idx: StatementIdx },
53 #[error("#{statement_idx}: {error}")]
54 ReferencesError { statement_idx: StatementIdx, error: ReferencesError },
55 #[error("#{statement_idx}: Invocation mismatched to libfunc")]
56 LibfuncInvocationMismatch { statement_idx: StatementIdx },
57 #[error("{var_id} is dangling at #{statement_idx}.")]
58 DanglingReferences { statement_idx: StatementIdx, var_id: VarId },
59 #[error("#{source_statement_idx}->#{destination_statement_idx}: Expected branch align")]
60 ExpectedBranchAlign {
61 source_statement_idx: StatementIdx,
62 destination_statement_idx: StatementIdx,
63 },
64 #[error("Const data does not match the declared const type.")]
65 ConstDataMismatch,
66 #[error("Unsupported const type.")]
67 UnsupportedConstType,
68 #[error("Unsupported circuit type.")]
69 UnsupportedCircuitType,
70 #[error("Const segments must appear in ascending order without holes.")]
71 ConstSegmentsOutOfOrder,
72 #[error("Code size limit exceeded.")]
73 CodeSizeLimitExceeded,
74 #[error("Unknown function id in metadata.")]
75 MetadataUnknownFunctionId,
76 #[error("Statement #{0} out of bounds in metadata.")]
77 MetadataStatementOutOfBound(StatementIdx),
78 #[error("Statement #{0} should not have gas variables.")]
79 StatementNotSupportingGasVariables(StatementIdx),
80 #[error("Statement #{0} should not have ap-change variables.")]
81 StatementNotSupportingApChangeVariables(StatementIdx),
82 #[error("Expected all gas variables to be positive.")]
83 MetadataNegativeGasVariable,
84}
85
86impl CompilationError {
87 pub fn stmt_indices(&self) -> Vec<StatementIdx> {
88 match self {
89 CompilationError::AnnotationError(err) => err.stmt_indices(),
90 _ => vec![],
91 }
92 }
93}
94
95#[derive(Debug, Eq, PartialEq, Clone, Copy)]
97pub struct SierraToCasmConfig {
98 pub gas_usage_check: bool,
100 pub max_bytecode_size: usize,
102}
103
104#[derive(Debug, Eq, PartialEq, Clone)]
106pub struct CairoProgram {
107 pub instructions: Vec<Instruction>,
108 pub debug_info: CairoProgramDebugInfo,
109 pub consts_info: ConstsInfo,
110}
111impl Display for CairoProgram {
112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113 if std::env::var("PRINT_CASM_BYTECODE_OFFSETS").is_ok() {
114 let mut bytecode_offset = 0;
115 for instruction in &self.instructions {
116 writeln!(f, "{instruction}; // {bytecode_offset}")?;
117 bytecode_offset += instruction.body.op_size();
118 }
119 for segment in self.consts_info.segments.values() {
120 writeln!(f, "ret; // {bytecode_offset}")?;
121 bytecode_offset += 1;
122 for value in &segment.values {
123 writeln!(f, "dw {value}; // {bytecode_offset}")?;
124 bytecode_offset += 1;
125 }
126 }
127 } else {
128 for instruction in &self.instructions {
129 writeln!(f, "{instruction};")?;
130 }
131 for segment in self.consts_info.segments.values() {
132 writeln!(f, "ret;")?;
133 for value in &segment.values {
134 writeln!(f, "dw {value};")?;
135 }
136 }
137 }
138 Ok(())
139 }
140}
141
142impl CairoProgram {
143 pub fn assemble(&self) -> AssembledCairoProgram {
145 self.assemble_ex(&[], &[])
146 }
147
148 pub fn assemble_ex<'a>(
151 &'a self,
152 header: impl IntoIterator<Item = &'a Instruction>,
153 footer: &[Instruction],
154 ) -> AssembledCairoProgram {
155 let mut bytecode = vec![];
156 let mut hints = vec![];
157 for instruction in chain!(header, &self.instructions) {
158 if !instruction.hints.is_empty() {
159 hints.push((bytecode.len(), instruction.hints.clone()))
160 }
161 bytecode.extend(instruction.assemble().encode().into_iter())
162 }
163 let [ref ret_bytecode] = Instruction::new(InstructionBody::Ret(RetInstruction {}), false)
164 .assemble()
165 .encode()[..]
166 else {
167 panic!("`ret` instruction should be a single word.")
168 };
169 for segment in self.consts_info.segments.values() {
170 bytecode.push(ret_bytecode.clone());
171 bytecode.extend(segment.values.clone());
172 }
173 for instruction in footer {
174 assert!(
175 instruction.hints.is_empty(),
176 "All footer instructions must have no hints since these cannot be added to the \
177 hints dict."
178 );
179 bytecode.extend(instruction.assemble().encode().into_iter())
180 }
181 AssembledCairoProgram { bytecode, hints }
182 }
183
184 pub fn sierra_statement_index_by_pc(&self, pc: usize) -> StatementIdx {
186 StatementIdx(
190 self.debug_info.sierra_statement_info.partition_point(|x| x.start_offset <= pc) - 1,
191 )
192 }
193}
194
195#[derive(Debug, Eq, PartialEq, Clone)]
197pub struct SierraStatementDebugInfo {
198 pub start_offset: usize,
200 pub end_offset: usize,
202 pub instruction_idx: usize,
204 pub additional_kind_info: StatementKindDebugInfo,
206}
207
208#[derive(Debug, Eq, PartialEq, Clone)]
211pub enum StatementKindDebugInfo {
212 Return(ReturnStatementDebugInfo),
213 Invoke(InvokeStatementDebugInfo),
214}
215
216#[derive(Debug, Eq, PartialEq, Clone)]
218pub struct ReturnStatementDebugInfo {
219 pub ref_values: Vec<ReferenceValue>,
221}
222
223#[derive(Debug, Eq, PartialEq, Clone)]
225pub struct InvokeStatementDebugInfo {
226 pub result_branch_changes: Vec<BranchChanges>,
228 pub ref_values: Vec<ReferenceValue>,
230}
231
232#[derive(Debug, Eq, PartialEq, Clone)]
234pub struct CairoProgramDebugInfo {
235 pub sierra_statement_info: Vec<SierraStatementDebugInfo>,
237}
238
239#[derive(Debug, Eq, PartialEq, Default, Clone)]
241pub struct ConstsInfo {
242 pub segments: OrderedHashMap<u32, ConstSegment>,
243 pub total_segments_size: usize,
244
245 pub circuit_segments: OrderedHashMap<ConcreteTypeId, u32>,
247}
248impl ConstsInfo {
249 pub fn new<'a>(
251 program_info: &ProgramRegistryInfo,
252 libfunc_ids: impl Iterator<Item = &'a ConcreteLibfuncId> + Clone,
253 circuit_infos: &OrderedHashMap<ConcreteTypeId, CircuitInfo>,
254 const_segments_max_size: usize,
255 ) -> Result<Self, CompilationError> {
256 let mut segments_data_size = 0;
257
258 let mut add_const = |segments: &mut OrderedHashMap<u32, ConstSegment>,
261 segment_id,
262 ty,
263 const_data: Vec<BigInt>| {
264 let segment: &mut ConstSegment = segments.entry(segment_id).or_default();
265
266 segments_data_size += const_data.len();
267 segment.const_offset.insert(ty, segment.values.len());
268 segment.values.extend(const_data);
269 if segments_data_size + segments.len() > const_segments_max_size {
270 return Err(CompilationError::CodeSizeLimitExceeded);
271 }
272 Ok(())
273 };
274
275 let mut segments = OrderedHashMap::default();
276
277 for id in libfunc_ids.clone() {
278 if let CoreConcreteLibfunc::Const(ConstConcreteLibfunc::AsBox(as_box)) =
279 program_info.registry.get_libfunc(id).unwrap()
280 {
281 add_const(
282 &mut segments,
283 as_box.segment_id,
284 as_box.const_type.clone(),
285 extract_const_value(program_info, &as_box.const_type).unwrap(),
286 )?;
287 }
288 }
289
290 if segments
292 .keys()
293 .enumerate()
294 .any(|(i, segment_id)| i != segment_id.into_or_panic::<usize>())
295 {
296 return Err(CompilationError::ConstSegmentsOutOfOrder);
297 }
298
299 let mut next_segment = segments.len() as u32;
300 let mut circuit_segments = OrderedHashMap::default();
301
302 for id in libfunc_ids {
303 if let CoreConcreteLibfunc::Circuit(CircuitConcreteLibfunc::GetDescriptor(libfunc)) =
304 program_info.registry.get_libfunc(id).unwrap()
305 {
306 let circ_ty = &libfunc.ty;
307 let info = circuit_infos.get(circ_ty).unwrap();
308 let mut const_value: Vec<BigInt> = vec![];
309 let mut push_offset =
310 |offset: usize| const_value.push((offset * VALUE_SIZE).into());
311 for gate_offsets in chain!(info.add_offsets.iter(), info.mul_offsets.iter()) {
312 push_offset(gate_offsets.lhs);
313 push_offset(gate_offsets.rhs);
314 push_offset(gate_offsets.output);
315 }
316
317 add_const(&mut segments, next_segment, circ_ty.clone(), const_value)?;
318 circuit_segments.insert(circ_ty.clone(), next_segment);
319 next_segment += 1;
320 }
321 }
322
323 let mut total_segments_size = 0;
324 for (_, segment) in segments.iter_mut() {
325 segment.segment_offset = total_segments_size;
326 total_segments_size += 1 + segment.values.len();
328 }
329 Ok(Self { segments, total_segments_size, circuit_segments })
330 }
331}
332
333#[derive(Debug, Eq, PartialEq, Default, Clone)]
335pub struct ConstSegment {
336 pub values: Vec<BigInt>,
338 pub const_offset: UnorderedHashMap<ConcreteTypeId, usize>,
340 pub segment_offset: usize,
342}
343
344fn extract_const_value(
347 program_info: &ProgramRegistryInfo,
348 ty: &ConcreteTypeId,
349) -> Result<Vec<BigInt>, CompilationError> {
350 let mut values = Vec::new();
351 let mut types_stack = vec![ty.clone()];
352 while let Some(ty) = types_stack.pop() {
353 let CoreTypeConcrete::Const(const_type) = program_info.registry.get_type(&ty).unwrap()
354 else {
355 return Err(CompilationError::UnsupportedConstType);
356 };
357 let inner_type = program_info.registry.get_type(&const_type.inner_ty).unwrap();
358 match inner_type {
359 CoreTypeConcrete::Struct(_) => {
360 for arg in const_type.inner_data.iter().rev() {
362 match arg {
363 GenericArg::Type(arg_ty) => types_stack.push(arg_ty.clone()),
364 _ => return Err(CompilationError::ConstDataMismatch),
365 }
366 }
367 }
368 CoreTypeConcrete::Enum(enm) => {
369 match &const_type.inner_data[..] {
371 [GenericArg::Value(variant_index), GenericArg::Type(ty)] => {
372 let variant_index = variant_index.to_usize().unwrap();
373 values.push(
374 get_variant_selector(enm.variants.len(), variant_index).unwrap().into(),
375 );
376 let full_enum_size: usize =
377 program_info.type_sizes[&const_type.inner_ty].into_or_panic();
378 let variant_size: usize =
379 program_info.type_sizes[&enm.variants[variant_index]].into_or_panic();
380 values.extend(itertools::repeat_n(
382 BigInt::zero(),
383 full_enum_size - variant_size - 1,
385 ));
386 types_stack.push(ty.clone());
387 }
388 _ => return Err(CompilationError::ConstDataMismatch),
389 }
390 }
391 CoreTypeConcrete::NonZero(_) => match &const_type.inner_data[..] {
392 [GenericArg::Type(inner)] => {
393 types_stack.push(inner.clone());
394 }
395 _ => return Err(CompilationError::ConstDataMismatch),
396 },
397 _ => match &const_type.inner_data[..] {
398 [GenericArg::Value(value)] => {
399 values.push(value.clone());
400 }
401 _ => return Err(CompilationError::ConstDataMismatch),
402 },
403 };
404 }
405 Ok(values)
406}
407
408pub fn check_basic_structure(
410 statement_idx: StatementIdx,
411 invocation: &Invocation,
412 libfunc: &CoreConcreteLibfunc,
413) -> Result<(), CompilationError> {
414 if invocation.args.len() != libfunc.param_signatures().len()
415 || !itertools::equal(
416 invocation.branches.iter().map(|branch| branch.results.len()),
417 libfunc.output_types().iter().map(|types| types.len()),
418 )
419 || match libfunc.fallthrough() {
420 Some(expected_fallthrough) => {
421 invocation.branches[expected_fallthrough].target != BranchTarget::Fallthrough
422 }
423 None => false,
424 }
425 {
426 Err(CompilationError::LibfuncInvocationMismatch { statement_idx })
427 } else {
428 Ok(())
429 }
430}
431
432pub fn compile(
435 program: &Program,
436 program_info: &ProgramRegistryInfo,
437 metadata: &Metadata,
438 config: SierraToCasmConfig,
439) -> Result<CairoProgram, Box<CompilationError>> {
440 let mut instructions = Vec::new();
441 let mut relocations: Vec<RelocationEntry> = Vec::new();
442
443 let mut sierra_statement_info: Vec<SierraStatementDebugInfo> =
447 Vec::with_capacity(program.statements.len());
448
449 validate_metadata(program, &program_info.registry, metadata)?;
450 let mut backwards_jump_indices = UnorderedHashSet::<_>::default();
451 for (statement_id, statement) in program.statements.iter().enumerate() {
452 if let Statement::Invocation(invocation) = statement {
453 for branch in &invocation.branches {
454 if let BranchTarget::Statement(target) = branch.target
455 && target.0 < statement_id
456 {
457 backwards_jump_indices.insert(target);
458 }
459 }
460 }
461 }
462 let mut program_annotations = ProgramAnnotations::create(
463 program.statements.len(),
464 backwards_jump_indices,
465 &program.funcs,
466 metadata,
467 config.gas_usage_check,
468 &program_info.type_sizes,
469 )
470 .map_err(|err| Box::new(err.into()))?;
471
472 let circuits_info = CircuitsInfo::new(
473 &program_info.registry,
474 program.type_declarations.iter().map(|td| &td.id),
475 )?;
476
477 let mut program_offset: usize = 0;
478 for (statement_id, statement) in program.statements.iter().enumerate() {
479 let statement_idx = StatementIdx(statement_id);
480
481 if program_offset > config.max_bytecode_size {
482 return Err(Box::new(CompilationError::CodeSizeLimitExceeded));
483 }
484 match statement {
485 Statement::Return(ref_ids) => {
486 let (annotations, return_refs) = program_annotations
487 .get_annotations_after_take_args(statement_idx, ref_ids.iter())
488 .map_err(|err| Box::new(err.into()))?;
489 return_refs.iter().for_each(|r| r.validate(&program_info.type_sizes));
490
491 if let Some(var_id) = annotations.refs.keys().next() {
492 return Err(Box::new(CompilationError::DanglingReferences {
493 statement_idx,
494 var_id: var_id.clone(),
495 }));
496 };
497
498 program_annotations
499 .validate_final_annotations(
500 statement_idx,
501 &annotations,
502 &program.funcs,
503 metadata,
504 &return_refs,
505 )
506 .map_err(|err| Box::new(err.into()))?;
507 check_references_on_stack(&return_refs).map_err(|error| match error {
508 InvocationError::InvalidReferenceExpressionForArgument => {
509 CompilationError::ReturnArgumentsNotOnStack { statement_idx }
510 }
511 _ => CompilationError::InvocationError { statement_idx, error },
512 })?;
513
514 let start_offset = program_offset;
515
516 let ret_instruction = RetInstruction {};
517 program_offset += ret_instruction.op_size();
518
519 sierra_statement_info.push(SierraStatementDebugInfo {
520 start_offset,
521 end_offset: program_offset,
522 instruction_idx: instructions.len(),
523 additional_kind_info: StatementKindDebugInfo::Return(
524 ReturnStatementDebugInfo { ref_values: return_refs },
525 ),
526 });
527
528 instructions.push(Instruction::new(InstructionBody::Ret(ret_instruction), false));
529 }
530 Statement::Invocation(invocation) => {
531 let (annotations, invoke_refs) = program_annotations
532 .get_annotations_after_take_args(statement_idx, invocation.args.iter())
533 .map_err(|err| Box::new(err.into()))?;
534
535 let libfunc = program_info
536 .registry
537 .get_libfunc(&invocation.libfunc_id)
538 .map_err(CompilationError::ProgramRegistryError)?;
539 check_basic_structure(statement_idx, invocation, libfunc)?;
540
541 let param_types: Vec<_> = libfunc
542 .param_signatures()
543 .iter()
544 .map(|param_signature| param_signature.ty.clone())
545 .collect();
546 check_types_match(&invoke_refs, ¶m_types).map_err(|error| {
547 Box::new(AnnotationError::ReferencesError { statement_idx, error }.into())
548 })?;
549 invoke_refs.iter().for_each(|r| r.validate(&program_info.type_sizes));
550 let compiled_invocation = compile_invocation(
551 ProgramInfo {
552 metadata,
553 type_sizes: &program_info.type_sizes,
554 circuits_info: &circuits_info,
555 const_data_values: &|ty| extract_const_value(program_info, ty).unwrap(),
556 },
557 invocation,
558 libfunc,
559 statement_idx,
560 &invoke_refs,
561 annotations.environment,
562 )
563 .map_err(|error| CompilationError::InvocationError { statement_idx, error })?;
564
565 let start_offset = program_offset;
566
567 for instruction in &compiled_invocation.instructions {
568 program_offset += instruction.body.op_size();
569 }
570
571 sierra_statement_info.push(SierraStatementDebugInfo {
572 start_offset,
573 end_offset: program_offset,
574 instruction_idx: instructions.len(),
575 additional_kind_info: StatementKindDebugInfo::Invoke(
576 InvokeStatementDebugInfo {
577 result_branch_changes: compiled_invocation.results.clone(),
578 ref_values: invoke_refs,
579 },
580 ),
581 });
582
583 for entry in compiled_invocation.relocations {
584 relocations.push(RelocationEntry {
585 instruction_idx: instructions.len() + entry.instruction_idx,
586 relocation: entry.relocation,
587 });
588 }
589 instructions.extend(compiled_invocation.instructions);
590
591 let branching_libfunc = compiled_invocation.results.len() > 1;
592 let mut all_updated_annotations = vec![StatementAnnotations {
595 environment: compiled_invocation.environment,
596 ..annotations
597 }];
598 while all_updated_annotations.len() < compiled_invocation.results.len() {
599 all_updated_annotations.push(all_updated_annotations[0].clone());
600 }
601
602 for ((branch_info, branch_changes), updated_annotations) in
603 zip_eq(&invocation.branches, compiled_invocation.results)
604 .zip(all_updated_annotations)
605 {
606 let destination_statement_idx = statement_idx.next(&branch_info.target);
607 if branching_libfunc
608 && !is_branch_align(
609 &program_info.registry,
610 &program.statements[destination_statement_idx.0],
611 )?
612 {
613 return Err(Box::new(CompilationError::ExpectedBranchAlign {
614 source_statement_idx: statement_idx,
615 destination_statement_idx,
616 }));
617 }
618
619 program_annotations
620 .propagate_annotations(
621 statement_idx,
622 destination_statement_idx,
623 updated_annotations,
624 branch_info,
625 branch_changes,
626 branching_libfunc,
627 )
628 .map_err(|err| Box::new(err.into()))?;
629 }
630 }
631 }
632 }
633
634 let statement_offsets: Vec<usize> = std::iter::once(0)
635 .chain(sierra_statement_info.iter().map(|s: &SierraStatementDebugInfo| s.end_offset))
636 .collect();
637
638 let const_segments_max_size = config
639 .max_bytecode_size
640 .checked_sub(program_offset)
641 .ok_or_else(|| Box::new(CompilationError::CodeSizeLimitExceeded))?;
642 let consts_info = ConstsInfo::new(
643 program_info,
644 program.libfunc_declarations.iter().map(|ld| &ld.id),
645 &circuits_info.circuits,
646 const_segments_max_size,
647 )?;
648 relocate_instructions(&relocations, &statement_offsets, &consts_info, &mut instructions);
649
650 Ok(CairoProgram {
651 instructions,
652 consts_info,
653 debug_info: CairoProgramDebugInfo { sierra_statement_info },
654 })
655}
656
657pub fn validate_metadata(
659 program: &Program,
660 registry: &ProgramRegistry<CoreType, CoreLibfunc>,
661 metadata: &Metadata,
662) -> Result<(), CompilationError> {
663 for function_id in metadata.ap_change_info.function_ap_change.keys() {
665 registry
666 .get_function(function_id)
667 .map_err(|_| CompilationError::MetadataUnknownFunctionId)?;
668 }
669 for (function_id, costs) in metadata.gas_info.function_costs.iter() {
670 registry
671 .get_function(function_id)
672 .map_err(|_| CompilationError::MetadataUnknownFunctionId)?;
673 for (_token_type, value) in costs.iter() {
674 if *value < 0 {
675 return Err(CompilationError::MetadataNegativeGasVariable);
676 }
677 }
678 }
679
680 let get_libfunc = |idx: &StatementIdx| -> Result<&CoreConcreteLibfunc, CompilationError> {
682 if let Statement::Invocation(invocation) =
683 program.get_statement(idx).ok_or(CompilationError::MetadataStatementOutOfBound(*idx))?
684 {
685 registry
686 .get_libfunc(&invocation.libfunc_id)
687 .map_err(CompilationError::ProgramRegistryError)
688 } else {
689 Err(CompilationError::StatementNotSupportingApChangeVariables(*idx))
690 }
691 };
692
693 for idx in metadata.ap_change_info.variable_values.keys() {
695 if !matches!(get_libfunc(idx)?, CoreConcreteLibfunc::BranchAlign(_)) {
696 return Err(CompilationError::StatementNotSupportingApChangeVariables(*idx));
697 }
698 }
699 for ((idx, _token), value) in metadata.gas_info.variable_values.iter() {
700 if *value < 0 {
701 return Err(CompilationError::MetadataNegativeGasVariable);
702 }
703 if !matches!(
704 get_libfunc(idx)?,
705 CoreConcreteLibfunc::BranchAlign(_)
706 | CoreConcreteLibfunc::Coupon(CouponConcreteLibfunc::Refund(_))
707 | CoreConcreteLibfunc::Gas(
708 GasConcreteLibfunc::WithdrawGas(_)
709 | GasConcreteLibfunc::BuiltinWithdrawGas(_)
710 | GasConcreteLibfunc::RedepositGas(_)
711 )
712 ) {
713 return Err(CompilationError::StatementNotSupportingGasVariables(*idx));
714 }
715 }
716 Ok(())
717}
718
719fn is_branch_align(
721 registry: &ProgramRegistry<CoreType, CoreLibfunc>,
722 statement: &Statement,
723) -> Result<bool, CompilationError> {
724 if let Statement::Invocation(invocation) = statement {
725 let libfunc = registry
726 .get_libfunc(&invocation.libfunc_id)
727 .map_err(CompilationError::ProgramRegistryError)?;
728 if let [branch_signature] = libfunc.branch_signatures()
729 && branch_signature.ap_change == SierraApChange::BranchAlign
730 {
731 return Ok(true);
732 }
733 }
734
735 Ok(false)
736}