cairo_lang_lowering/borrow_check/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#[cfg(test)]
#[path = "test.rs"]
mod test;

use cairo_lang_defs::ids::TraitFunctionId;
use cairo_lang_diagnostics::{DiagnosticNote, Maybe};
use cairo_lang_semantic::corelib::{destruct_trait_fn, panic_destruct_trait_fn};
use cairo_lang_semantic::items::functions::{GenericFunctionId, ImplGenericFunctionId};
use cairo_lang_utils::unordered_hash_map::UnorderedHashMap;
use cairo_lang_utils::{Intern, LookupIntern};
use itertools::{zip_eq, Itertools};

use self::analysis::{Analyzer, StatementLocation};
pub use self::demand::Demand;
use self::demand::{AuxCombine, DemandReporter};
use crate::blocks::Blocks;
use crate::borrow_check::analysis::BackAnalysis;
use crate::db::LoweringGroup;
use crate::diagnostic::LoweringDiagnosticKind::*;
use crate::diagnostic::{LoweringDiagnostics, LoweringDiagnosticsBuilder};
use crate::ids::{FunctionId, LocationId, SemanticFunctionIdEx};
use crate::{BlockId, FlatLowered, MatchInfo, Statement, VarRemapping, VarUsage, VariableId};

pub mod analysis;
pub mod demand;

pub type BorrowCheckerDemand = Demand<VariableId, LocationId, PanicState>;
pub struct BorrowChecker<'a> {
    db: &'a dyn LoweringGroup,
    diagnostics: &'a mut LoweringDiagnostics,
    lowered: &'a FlatLowered,
    success: Maybe<()>,
    potential_destruct_calls: PotentialDestructCalls,
    destruct_fn: TraitFunctionId,
    panic_destruct_fn: TraitFunctionId,
    is_panic_destruct_fn: bool,
}

/// A state saved for each position in the back analysis.
/// Used to determine if this flow is guaranteed to end in a panic.
#[derive(Copy, Clone, Default)]
pub enum PanicState {
    EndsWithPanic,
    #[default]
    Otherwise,
}
impl AuxCombine for PanicState {
    fn merge<'a, I: Iterator<Item = &'a Self>>(mut iter: I) -> Self
    where
        Self: 'a,
    {
        if iter.all(|x| matches!(x, Self::EndsWithPanic)) {
            Self::EndsWithPanic
        } else {
            Self::Otherwise
        }
    }
}

// Represents the item that caused the triggered the need for a drop.
#[derive(Copy, Clone, Debug)]
pub enum DropPosition {
    // The trigger is a call to a panicable function.
    Panic(LocationId),
    // The trigger is a divergence in control flow.
    Diverge(LocationId),
}
impl DropPosition {
    fn as_note(self, db: &dyn LoweringGroup) -> DiagnosticNote {
        let (text, location) = match self {
            Self::Panic(location) => {
                ("the variable needs to be dropped due to the potential panic here", location)
            }
            Self::Diverge(location) => {
                ("the variable needs to be dropped due to the divergence here", location)
            }
        };
        DiagnosticNote::with_location(
            text.into(),
            location.lookup_intern(db).stable_location.diagnostic_location(db.upcast()),
        )
    }
}

impl<'a> DemandReporter<VariableId, PanicState> for BorrowChecker<'a> {
    // Note that for in BorrowChecker `IntroducePosition` is used to pass the cause of
    // the drop.
    type IntroducePosition = (Option<DropPosition>, BlockId);
    type UsePosition = LocationId;

    fn drop_aux(
        &mut self,
        (opt_drop_position, block_id): (Option<DropPosition>, BlockId),
        var_id: VariableId,
        panic_state: PanicState,
    ) {
        let var = &self.lowered.variables[var_id];
        let Err(drop_err) = var.droppable.clone() else {
            return;
        };
        let mut add_called_fn = |impl_id, function| {
            self.potential_destruct_calls.entry(block_id).or_default().push(
                cairo_lang_semantic::FunctionLongId {
                    function: cairo_lang_semantic::ConcreteFunction {
                        generic_function: GenericFunctionId::Impl(ImplGenericFunctionId {
                            impl_id,
                            function,
                        }),
                        generic_args: vec![],
                    },
                }
                .intern(self.db)
                .lowered(self.db),
            );
        };
        let destruct_err = match var.destruct_impl.clone() {
            Ok(impl_id) => {
                add_called_fn(impl_id, self.destruct_fn);
                return;
            }
            Err(err) => err,
        };
        let panic_destruct_err = if matches!(panic_state, PanicState::EndsWithPanic) {
            match var.panic_destruct_impl.clone() {
                Ok(impl_id) => {
                    add_called_fn(impl_id, self.panic_destruct_fn);
                    return;
                }
                Err(err) => Some(err),
            }
        } else {
            None
        };

        let mut location = var.location.lookup_intern(self.db);
        if let Some(drop_position) = opt_drop_position {
            location = location.with_note(drop_position.as_note(self.db));
        }
        let semantic_db = self.db.upcast();
        self.success = Err(self.diagnostics.report_by_location(
            location
                .with_note(DiagnosticNote::text_only(drop_err.format(semantic_db)))
                .with_note(DiagnosticNote::text_only(destruct_err.format(semantic_db)))
                .maybe_with_note(
                    panic_destruct_err
                        .map(|err| DiagnosticNote::text_only(err.format(semantic_db))),
                ),
            VariableNotDropped { drop_err, destruct_err },
        ));
    }

    fn dup(&mut self, position: LocationId, var_id: VariableId, next_usage_position: LocationId) {
        let var = &self.lowered.variables[var_id];
        if let Err(inference_error) = var.copyable.clone() {
            self.success = Err(self.diagnostics.report_by_location(
                next_usage_position
                    .lookup_intern(self.db)
                    .add_note_with_location(self.db, "variable was previously used here", position)
                    .with_note(DiagnosticNote::text_only(inference_error.format(self.db.upcast()))),
                VariableMoved { inference_error },
            ));
        }
    }
}

impl<'a> Analyzer<'_> for BorrowChecker<'a> {
    type Info = BorrowCheckerDemand;

    fn visit_stmt(
        &mut self,
        info: &mut Self::Info,
        (block_id, _): StatementLocation,
        stmt: &Statement,
    ) {
        info.variables_introduced(self, stmt.outputs(), (None, block_id));
        match stmt {
            Statement::Call(stmt) => {
                if let Ok(signature) = stmt.function.signature(self.db) {
                    if signature.panicable {
                        // Be prepared to panic here.
                        let panic_demand = BorrowCheckerDemand {
                            aux: PanicState::EndsWithPanic,
                            ..Default::default()
                        };
                        let location = (Some(DropPosition::Panic(stmt.location)), block_id);
                        *info = BorrowCheckerDemand::merge_demands(
                            &[(panic_demand, location), (info.clone(), location)],
                            self,
                        );
                    }
                }
            }
            Statement::Desnap(stmt) => {
                let var = &self.lowered.variables[stmt.output];
                if let Err(inference_error) = var.copyable.clone() {
                    self.success = Err(self.diagnostics.report_by_location(
                        var.location.lookup_intern(self.db).with_note(DiagnosticNote::text_only(
                            inference_error.format(self.db.upcast()),
                        )),
                        DesnappingANonCopyableType { inference_error },
                    ));
                }
            }
            _ => {}
        }
        info.variables_used(
            self,
            stmt.inputs().iter().map(|VarUsage { var_id, location }| (var_id, *location)),
        );
    }

    fn visit_goto(
        &mut self,
        info: &mut Self::Info,
        _statement_location: StatementLocation,
        _target_block_id: BlockId,
        remapping: &VarRemapping,
    ) {
        info.apply_remapping(
            self,
            remapping
                .iter()
                .map(|(dst, VarUsage { var_id: src, location })| (dst, (src, *location))),
        );
    }

    fn merge_match(
        &mut self,
        (block_id, _): StatementLocation,
        match_info: &MatchInfo,
        infos: impl Iterator<Item = Self::Info>,
    ) -> Self::Info {
        let infos: Vec<_> = infos.collect();
        let arm_demands = zip_eq(match_info.arms(), &infos)
            .map(|(arm, demand)| {
                let mut demand = demand.clone();
                demand.variables_introduced(self, &arm.var_ids, (None, block_id));
                (demand, (Some(DropPosition::Diverge(*match_info.location())), block_id))
            })
            .collect_vec();
        let mut demand = BorrowCheckerDemand::merge_demands(&arm_demands, self);
        demand.variables_used(
            self,
            match_info.inputs().iter().map(|VarUsage { var_id, location }| (var_id, *location)),
        );
        demand
    }

    fn info_from_return(
        &mut self,
        _statement_location: StatementLocation,
        vars: &[VarUsage],
    ) -> Self::Info {
        let mut info = if self.is_panic_destruct_fn {
            BorrowCheckerDemand { aux: PanicState::EndsWithPanic, ..Default::default() }
        } else {
            BorrowCheckerDemand::default()
        };

        info.variables_used(
            self,
            vars.iter().map(|VarUsage { var_id, location }| (var_id, *location)),
        );
        info
    }

    fn info_from_panic(
        &mut self,
        _statement_location: StatementLocation,
        data: &VarUsage,
    ) -> Self::Info {
        let mut info = BorrowCheckerDemand { aux: PanicState::EndsWithPanic, ..Default::default() };
        info.variables_used(self, std::iter::once((&data.var_id, data.location)));
        info
    }
}

/// The possible destruct calls per block.
pub type PotentialDestructCalls = UnorderedHashMap<BlockId, Vec<FunctionId>>;

/// Report borrow checking diagnostics.
/// Returns the potential destruct function calls per block.
pub fn borrow_check(
    db: &dyn LoweringGroup,
    is_panic_destruct_fn: bool,
    lowered: &mut FlatLowered,
) -> PotentialDestructCalls {
    if lowered.blocks.has_root().is_err() {
        return Default::default();
    }
    let mut diagnostics = LoweringDiagnostics::default();
    diagnostics.extend(std::mem::take(&mut lowered.diagnostics));
    let destruct_fn = destruct_trait_fn(db.upcast());
    let panic_destruct_fn = panic_destruct_trait_fn(db.upcast());

    let checker = BorrowChecker {
        db,
        diagnostics: &mut diagnostics,
        lowered,
        success: Ok(()),
        potential_destruct_calls: Default::default(),
        destruct_fn,
        panic_destruct_fn,
        is_panic_destruct_fn,
    };
    let mut analysis = BackAnalysis::new(lowered, checker);
    let mut root_demand = analysis.get_root_info();
    root_demand.variables_introduced(
        &mut analysis.analyzer,
        &lowered.parameters,
        (None, BlockId::root()),
    );
    let block_extra_calls = analysis.analyzer.potential_destruct_calls;
    let success = analysis.analyzer.success;
    assert!(root_demand.finalize(), "Undefined variable should not happen at this stage");

    if let Err(diag_added) = success {
        lowered.blocks = Blocks::new_errored(diag_added);
    }

    lowered.diagnostics = diagnostics.build();
    block_extra_calls
}