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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use std::collections::VecDeque;
use cairo_lang_diagnostics::Maybe;
use cairo_lang_semantic as semantic;
use cairo_lang_semantic::corelib::{get_enum_concrete_variant, get_panic_ty};
use cairo_lang_semantic::GenericArgumentId;
use itertools::{chain, zip_eq, Itertools};
use semantic::items::functions::{
ConcreteFunctionWithBody, GenericFunctionId, GenericFunctionWithBodyId,
};
use semantic::{ConcreteFunctionWithBodyId, ConcreteVariant, Mutability, Signature, TypeId};
use crate::blocks::FlatBlocksBuilder;
use crate::db::LoweringGroup;
use crate::lower::context::{LoweringContext, LoweringContextBuilder, VarRequest};
use crate::{
BlockId, FlatBlock, FlatBlockEnd, FlatLowered, MatchArm, MatchEnumInfo, MatchInfo, Statement,
StatementCall, StatementEnumConstruct, StatementStructConstruct, StatementStructDestructure,
VarRemapping, VariableId,
};
pub fn lower_panics(
db: &dyn LoweringGroup,
function_id: ConcreteFunctionWithBodyId,
lowered: &FlatLowered,
) -> Maybe<FlatLowered> {
let lowering_info = LoweringContextBuilder::new_concrete(db, function_id)?;
let mut ctx = lowering_info.ctx()?;
ctx.variables = lowered.variables.clone();
if !db.concrete_function_with_body_may_panic(function_id)? {
return Ok(FlatLowered {
diagnostics: Default::default(),
variables: ctx.variables,
blocks: lowered.blocks.clone(),
parameters: lowered.parameters.clone(),
});
}
let panic_info = PanicSignatureInfo::new(db, ctx.signature);
let mut ctx = PanicLoweringContext {
ctx,
block_queue: VecDeque::from(lowered.blocks.get().clone()),
flat_blocks: FlatBlocksBuilder::new(),
panic_info,
};
while let Some(block) = ctx.block_queue.pop_front() {
ctx = handle_block(ctx, block)?;
}
Ok(FlatLowered {
diagnostics: Default::default(),
variables: ctx.ctx.variables,
blocks: ctx.flat_blocks.build().unwrap(),
parameters: lowered.parameters.clone(),
})
}
fn handle_block(
mut ctx: PanicLoweringContext<'_>,
mut block: FlatBlock,
) -> Maybe<PanicLoweringContext<'_>> {
let mut block_ctx = PanicBlockLoweringContext { ctx, statements: Vec::new() };
for (i, stmt) in block.statements.iter().cloned().enumerate() {
if let Some((continuation_block, cur_block_end)) = block_ctx.handle_statement(&stmt)? {
ctx = block_ctx.handle_end(cur_block_end);
let block_to_edit = &mut ctx.block_queue[continuation_block.0 - ctx.flat_blocks.len()];
block_to_edit.statements.extend(block.statements.drain(i + 1..));
block_to_edit.end = block.end;
return Ok(ctx);
}
}
ctx = block_ctx.handle_end(block.end);
Ok(ctx)
}
pub struct PanicSignatureInfo {
ok_ret_tys: Vec<TypeId>,
ok_ty: TypeId,
ok_variant: ConcreteVariant,
err_variant: ConcreteVariant,
pub panic_ty: TypeId,
}
impl PanicSignatureInfo {
pub fn new(db: &dyn LoweringGroup, signature: &Signature) -> Self {
let refs = signature
.params
.iter()
.filter(|param| matches!(param.mutability, Mutability::Reference))
.map(|param| param.ty);
let original_return_ty = signature.return_type;
let ok_ret_tys = chain!(refs, [original_return_ty]).collect_vec();
let ok_ty = db.intern_type(semantic::TypeLongId::Tuple(ok_ret_tys.clone()));
let ok_variant = get_enum_concrete_variant(
db.upcast(),
"PanicResult",
vec![GenericArgumentId::Type(ok_ty)],
"Ok",
);
let err_variant = get_enum_concrete_variant(
db.upcast(),
"PanicResult",
vec![GenericArgumentId::Type(ok_ty)],
"Err",
);
let panic_ty = get_panic_ty(db.upcast(), ok_ty);
Self { ok_ret_tys, ok_ty, ok_variant, err_variant, panic_ty }
}
}
struct PanicLoweringContext<'a> {
ctx: LoweringContext<'a>,
block_queue: VecDeque<FlatBlock>,
flat_blocks: FlatBlocksBuilder,
panic_info: PanicSignatureInfo,
}
impl<'a> PanicLoweringContext<'a> {
pub fn db(&self) -> &dyn LoweringGroup {
self.ctx.db
}
fn enqueue_block(&mut self, block: FlatBlock) -> BlockId {
self.block_queue.push_back(block);
BlockId(self.flat_blocks.len() + self.block_queue.len())
}
}
struct PanicBlockLoweringContext<'a> {
ctx: PanicLoweringContext<'a>,
statements: Vec<Statement>,
}
impl<'a> PanicBlockLoweringContext<'a> {
pub fn db(&self) -> &dyn LoweringGroup {
self.ctx.db()
}
fn new_var(&mut self, req: VarRequest) -> VariableId {
self.ctx.ctx.new_var(req)
}
fn handle_statement(&mut self, stmt: &Statement) -> Maybe<Option<(BlockId, FlatBlockEnd)>> {
if let Statement::Call(call) = &stmt {
let concrete_function = self.db().lookup_intern_function(call.function).function;
if let Some(with_body) = concrete_function.get_body(self.db().upcast())? {
if self.db().concrete_function_with_body_may_panic(with_body)? {
return Ok(Some(self.handle_call_panic(call)?));
}
}
}
self.statements.push(stmt.clone());
Ok(None)
}
fn handle_call_panic(&mut self, call: &StatementCall) -> Maybe<(BlockId, FlatBlockEnd)> {
let mut original_outputs = call.outputs.clone();
let location = self.ctx.ctx.variables[original_outputs[0]].location;
let callee_signature = self.ctx.ctx.db.concrete_function_signature(call.function)?;
let callee_info = PanicSignatureInfo::new(self.ctx.ctx.db, &callee_signature);
let panic_result_var = self.new_var(VarRequest { ty: callee_info.panic_ty, location });
let n_callee_implicits = original_outputs.len() - callee_info.ok_ret_tys.len();
let mut call_outputs = original_outputs.drain(..n_callee_implicits).collect_vec();
call_outputs.push(panic_result_var);
let inner_ok_value = self.new_var(VarRequest { ty: callee_info.ok_ty, location });
let inner_ok_values = callee_info
.ok_ret_tys
.iter()
.copied()
.map(|ty| self.new_var(VarRequest { ty, location }))
.collect_vec();
self.statements.push(Statement::Call(StatementCall {
function: call.function,
inputs: call.inputs.clone(),
outputs: call_outputs,
location,
}));
let block_continuation =
self.ctx.enqueue_block(FlatBlock { statements: vec![], end: FlatBlockEnd::NotSet });
let block_ok = self.ctx.enqueue_block(FlatBlock {
statements: vec![Statement::StructDestructure(StatementStructDestructure {
input: inner_ok_value,
outputs: inner_ok_values.clone(),
})],
end: FlatBlockEnd::Goto(
block_continuation,
VarRemapping { remapping: zip_eq(original_outputs, inner_ok_values).collect() },
),
});
let data_var =
self.new_var(VarRequest { ty: self.ctx.panic_info.err_variant.ty, location });
let block_err = self
.ctx
.enqueue_block(FlatBlock { statements: vec![], end: FlatBlockEnd::Panic(data_var) });
let cur_block_end = FlatBlockEnd::Match {
info: MatchInfo::Enum(MatchEnumInfo {
concrete_enum_id: callee_info.ok_variant.concrete_enum_id,
input: panic_result_var,
arms: vec![
MatchArm {
variant_id: callee_info.ok_variant,
block_id: block_ok,
var_ids: vec![inner_ok_value],
},
MatchArm {
variant_id: callee_info.err_variant,
block_id: block_err,
var_ids: vec![data_var],
},
],
}),
};
Ok((block_continuation, cur_block_end))
}
fn handle_end(mut self, end: FlatBlockEnd) -> PanicLoweringContext<'a> {
let end = match end {
FlatBlockEnd::Goto(target, remapping) => FlatBlockEnd::Goto(target, remapping),
FlatBlockEnd::Panic(data) => {
let ty = self.ctx.panic_info.panic_ty;
let location = self.ctx.ctx.variables[data].location;
let output = self.new_var(VarRequest { ty, location });
self.statements.push(Statement::EnumConstruct(StatementEnumConstruct {
variant: self.ctx.panic_info.err_variant.clone(),
input: data,
output,
}));
FlatBlockEnd::Return(vec![output])
}
FlatBlockEnd::Return(returns) => {
let location = self.ctx.ctx.variables[returns[0]].location;
let tupled_res =
self.new_var(VarRequest { ty: self.ctx.panic_info.ok_ty, location });
self.statements.push(Statement::StructConstruct(StatementStructConstruct {
inputs: returns,
output: tupled_res,
}));
let ty = self.ctx.panic_info.panic_ty;
let output = self.new_var(VarRequest { ty, location });
self.statements.push(Statement::EnumConstruct(StatementEnumConstruct {
variant: self.ctx.panic_info.ok_variant.clone(),
input: tupled_res,
output,
}));
FlatBlockEnd::Return(vec![output])
}
FlatBlockEnd::NotSet => unreachable!(),
FlatBlockEnd::Match { info } => FlatBlockEnd::Match { info },
};
self.ctx.flat_blocks.alloc(FlatBlock { statements: self.statements, end });
self.ctx
}
}
pub fn function_may_panic(db: &dyn LoweringGroup, function: semantic::FunctionId) -> Maybe<bool> {
let concrete_function = function.get_concrete(db.upcast());
match concrete_function.generic_function {
GenericFunctionId::Free(free_function) => {
let concrete_with_body =
db.intern_concrete_function_with_body(ConcreteFunctionWithBody {
generic_function: GenericFunctionWithBodyId::Free(free_function),
generic_args: concrete_function.generic_args,
});
db.concrete_function_with_body_may_panic(concrete_with_body)
}
GenericFunctionId::Impl(impl_generic_function) => {
let Some(generic_with_body) =
impl_generic_function.to_generic_with_body(db.upcast())?
else {
unreachable!();
};
let concrete_with_body =
db.intern_concrete_function_with_body(ConcreteFunctionWithBody {
generic_function: generic_with_body,
generic_args: concrete_function.generic_args,
});
db.concrete_function_with_body_may_panic(concrete_with_body)
}
GenericFunctionId::Extern(extern_function) => {
Ok(db.extern_function_signature(extern_function)?.panicable)
}
}
}
pub fn concrete_function_with_body_may_panic(
db: &dyn LoweringGroup,
function: ConcreteFunctionWithBodyId,
) -> Maybe<bool> {
let scc_representative = db.concrete_function_with_body_scc_representative(function);
if db.has_direct_panic(function)? {
return Ok(true);
}
let direct_callees = db.concrete_function_with_body_direct_callees(function)?;
for direct_callee in direct_callees {
let generic_function = direct_callee.generic_function;
let generic_with_body = match generic_function {
GenericFunctionId::Free(free_function) => {
GenericFunctionWithBodyId::Free(free_function)
}
GenericFunctionId::Impl(impl_generic_function) => {
if let Some(generic_with_body) =
impl_generic_function.to_generic_with_body(db.upcast())?
{
generic_with_body
} else {
unreachable!()
}
}
GenericFunctionId::Extern(extern_function) => {
if db.extern_function_signature(extern_function)?.panicable {
return Ok(true);
}
continue;
}
};
let concrete_with_body = db.intern_concrete_function_with_body(ConcreteFunctionWithBody {
generic_function: generic_with_body,
generic_args: direct_callee.generic_args,
});
let direct_callee_representative =
db.concrete_function_with_body_scc_representative(concrete_with_body);
if direct_callee_representative == scc_representative {
continue;
}
if db.concrete_function_with_body_may_panic(direct_callee_representative.0)? {
return Ok(true);
}
}
Ok(false)
}
pub fn has_direct_panic(
db: &dyn LoweringGroup,
function_id: ConcreteFunctionWithBodyId,
) -> Maybe<bool> {
let lowered_function = db.priv_concrete_function_with_body_lowered_flat(function_id)?;
Ok(itertools::any(&lowered_function.blocks, |(_, block)| {
matches!(&block.end, FlatBlockEnd::Panic(..))
}))
}