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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
use cairo_lang_defs::ids::{EnumId, GenericTypeId, ImplDefId, ModuleId, ModuleItemId, TraitId};
use cairo_lang_diagnostics::{Maybe, ToOption};
use cairo_lang_filesystem::ids::{CrateId, CrateLongId};
use cairo_lang_syntax::node::ast::{self, BinaryOperator, UnaryOperator};
use cairo_lang_syntax::node::ids::SyntaxStablePtrId;
use cairo_lang_utils::{extract_matches, try_extract_matches, OptionFrom};
use num_bigint::BigInt;
use num_traits::{Num, Signed};
use smol_str::SmolStr;
use crate::db::SemanticGroup;
use crate::diagnostic::SemanticDiagnosticKind;
use crate::expr::compute::ComputationContext;
use crate::expr::inference::Inference;
use crate::items::enm::SemanticEnumEx;
use crate::items::functions::{GenericFunctionId, ImplGenericFunctionId};
use crate::items::imp::ImplId;
use crate::items::trt::{
ConcreteTraitGenericFunctionId, ConcreteTraitGenericFunctionLongId, ConcreteTraitId,
};
use crate::items::us::SemanticUseEx;
use crate::resolve_path::ResolvedGenericItem;
use crate::types::ConcreteEnumLongId;
use crate::{
semantic, ConcreteEnumId, ConcreteFunction, ConcreteImplLongId, ConcreteVariant, Expr, ExprId,
ExprTuple, FunctionId, FunctionLongId, GenericArgumentId, TypeId, TypeLongId,
};
pub fn core_module(db: &dyn SemanticGroup) -> ModuleId {
let core_crate = db.core_crate();
ModuleId::CrateRoot(core_crate)
}
pub fn core_crate(db: &dyn SemanticGroup) -> CrateId {
db.intern_crate(CrateLongId("core".into()))
}
pub fn core_felt252_ty(db: &dyn SemanticGroup) -> TypeId {
get_core_ty_by_name(db, "felt252".into(), vec![])
}
pub fn core_nonzero_ty(db: &dyn SemanticGroup, inner_type: TypeId) -> TypeId {
get_core_ty_by_name(db, "NonZero".into(), vec![GenericArgumentId::Type(inner_type)])
}
pub fn try_get_core_ty_by_name(
db: &dyn SemanticGroup,
name: SmolStr,
generic_args: Vec<GenericArgumentId>,
) -> Result<TypeId, SemanticDiagnosticKind> {
let core_module = db.core_module();
let module_item_id = db
.module_item_by_name(core_module, name.clone())
.map_err(|_| SemanticDiagnosticKind::UnknownType)?
.ok_or(SemanticDiagnosticKind::UnknownType)?;
let generic_type = match module_item_id {
ModuleItemId::Use(use_id) => {
db.use_resolved_item(use_id).to_option().and_then(|resolved_generic_item| {
try_extract_matches!(resolved_generic_item, ResolvedGenericItem::GenericType)
})
}
ModuleItemId::TypeAlias(type_alias_id) => {
let ty =
db.type_alias_resolved_type(type_alias_id).expect("Could not find type alias.");
assert!(
db.type_alias_generic_params(type_alias_id).unwrap().is_empty(),
"Cannot get type aliases with params from corelib."
);
return Ok(ty);
}
_ => GenericTypeId::option_from(module_item_id),
}
.unwrap_or_else(|| panic!("{name} is not a type."));
Ok(db.intern_type(semantic::TypeLongId::Concrete(semantic::ConcreteTypeId::new(
db,
generic_type,
generic_args,
))))
}
pub fn get_core_ty_by_name(
db: &dyn SemanticGroup,
name: SmolStr,
generic_args: Vec<GenericArgumentId>,
) -> TypeId {
try_get_core_ty_by_name(db, name, generic_args).unwrap()
}
pub fn core_bool_ty(db: &dyn SemanticGroup) -> TypeId {
let core_module = db.core_module();
let generic_type = db
.module_item_by_name(core_module, "bool".into())
.expect("Failed to load core lib.")
.and_then(GenericTypeId::option_from)
.expect("Type bool was not found in core lib.");
db.intern_type(semantic::TypeLongId::Concrete(semantic::ConcreteTypeId::new(
db,
generic_type,
vec![],
)))
}
pub fn core_bool_enum(db: &dyn SemanticGroup) -> ConcreteEnumId {
let core_module = db.core_module();
let enum_id = db
.module_item_by_name(core_module, "bool".into())
.expect("Failed to load core lib.")
.and_then(EnumId::option_from)
.expect("Type bool was not found in core lib.");
db.intern_concrete_enum(ConcreteEnumLongId { enum_id, generic_args: vec![] })
}
pub fn false_variant(db: &dyn SemanticGroup) -> ConcreteVariant {
get_enum_concrete_variant(db, "bool", vec![], "False")
}
pub fn true_variant(db: &dyn SemanticGroup) -> ConcreteVariant {
get_enum_concrete_variant(db, "bool", vec![], "True")
}
pub fn jump_nz_zero_variant(db: &dyn SemanticGroup) -> ConcreteVariant {
get_enum_concrete_variant(
db,
"IsZeroResult",
vec![GenericArgumentId::Type(core_felt252_ty(db))],
"Zero",
)
}
pub fn jump_nz_nonzero_variant(db: &dyn SemanticGroup) -> ConcreteVariant {
get_enum_concrete_variant(
db,
"IsZeroResult",
vec![GenericArgumentId::Type(core_felt252_ty(db))],
"NonZero",
)
}
pub fn false_literal_expr(
ctx: &mut ComputationContext<'_>,
stable_ptr: ast::ExprPtr,
) -> semantic::Expr {
get_bool_variant_expr(ctx, "bool", "False", stable_ptr)
}
pub fn true_literal_expr(
ctx: &mut ComputationContext<'_>,
stable_ptr: ast::ExprPtr,
) -> semantic::Expr {
get_bool_variant_expr(ctx, "bool", "True", stable_ptr)
}
fn get_bool_variant_expr(
ctx: &mut ComputationContext<'_>,
enum_name: &str,
variant_name: &str,
stable_ptr: ast::ExprPtr,
) -> semantic::Expr {
let concrete_variant = get_enum_concrete_variant(ctx.db, enum_name, vec![], variant_name);
semantic::Expr::EnumVariantCtor(semantic::ExprEnumVariantCtor {
variant: concrete_variant,
value_expr: unit_expr(ctx, stable_ptr),
ty: core_bool_ty(ctx.db),
stable_ptr,
})
}
pub fn get_enum_concrete_variant(
db: &dyn SemanticGroup,
enum_name: &str,
generic_args: Vec<GenericArgumentId>,
variant_name: &str,
) -> ConcreteVariant {
let module_id = core_module(db);
let enum_item = db.module_item_by_name(module_id, enum_name.into()).unwrap().unwrap();
let enum_id = extract_matches!(enum_item, ModuleItemId::Enum);
let concrete_enum_id = db.intern_concrete_enum(ConcreteEnumLongId { enum_id, generic_args });
let variant_id = db.enum_variants(enum_id).unwrap()[variant_name];
let variant = db.variant_semantic(enum_id, variant_id).unwrap();
db.concrete_enum_variant(concrete_enum_id, &variant).unwrap()
}
pub fn unit_ty(db: &dyn SemanticGroup) -> TypeId {
db.intern_type(semantic::TypeLongId::Tuple(vec![]))
}
pub fn never_ty(db: &dyn SemanticGroup) -> TypeId {
let core_module = db.core_module();
let generic_type = db
.module_item_by_name(core_module, "never".into())
.expect("Failed to load core lib.")
.and_then(GenericTypeId::option_from)
.expect("Type bool was not found in core lib.");
db.intern_type(semantic::TypeLongId::Concrete(semantic::ConcreteTypeId::new(
db,
generic_type,
vec![],
)))
}
pub fn unwrap_error_propagation_type(
db: &dyn SemanticGroup,
ty: TypeId,
) -> Option<(ConcreteVariant, ConcreteVariant)> {
match db.lookup_intern_type(ty) {
TypeLongId::Concrete(semantic::ConcreteTypeId::Enum(enm)) => {
let name = enm.enum_id(db.upcast()).name(db.upcast());
if name == "Option" || name == "Result" {
if let [ok_variant, err_variant] =
db.concrete_enum_variants(enm).to_option()?.as_slice()
{
Some((ok_variant.clone(), err_variant.clone()))
} else {
None
}
} else {
None
}
}
TypeLongId::GenericParameter(_) => todo!(
"When generic types are supported, if type is of matching type, allow unwrapping it \
to type."
),
TypeLongId::Concrete(
semantic::ConcreteTypeId::Struct(_) | semantic::ConcreteTypeId::Extern(_),
)
| TypeLongId::Tuple(_)
| TypeLongId::Snapshot(_)
| TypeLongId::Var(_)
| TypeLongId::Missing(_) => None,
}
}
pub fn unit_expr(ctx: &mut ComputationContext<'_>, stable_ptr: ast::ExprPtr) -> ExprId {
ctx.exprs.alloc(Expr::Tuple(ExprTuple {
items: Vec::new(),
ty: ctx.db.intern_type(TypeLongId::Tuple(Vec::new())),
stable_ptr,
}))
}
pub fn core_unary_operator(
db: &dyn SemanticGroup,
inference: &mut Inference<'_>,
unary_op: &UnaryOperator,
stable_ptr: SyntaxStablePtrId,
) -> Maybe<Result<ConcreteTraitGenericFunctionId, SemanticDiagnosticKind>> {
let (trait_name, function_name) = match unary_op {
UnaryOperator::Minus(_) => ("Neg", "neg"),
UnaryOperator::Not(_) => ("Not", "not"),
UnaryOperator::At(_) => unreachable!("@ is not an unary operator."),
UnaryOperator::Desnap(_) => unreachable!("* is not an unary operator."),
};
Ok(Ok(get_core_trait_function_infer(
db,
inference,
trait_name.into(),
function_name.into(),
stable_ptr,
)))
}
pub fn core_binary_operator(
db: &dyn SemanticGroup,
inference: &mut Inference<'_>,
binary_op: &BinaryOperator,
stable_ptr: SyntaxStablePtrId,
) -> Maybe<Result<ConcreteTraitGenericFunctionId, SemanticDiagnosticKind>> {
let (trait_name, function_name) = match binary_op {
BinaryOperator::Plus(_) => ("Add", "add"),
BinaryOperator::PlusEq(_) => ("AddEq", "add_eq"),
BinaryOperator::Minus(_) => ("Sub", "sub"),
BinaryOperator::MinusEq(_) => ("SubEq", "sub_eq"),
BinaryOperator::Mul(_) => ("Mul", "mul"),
BinaryOperator::MulEq(_) => ("MulEq", "mul_eq"),
BinaryOperator::Div(_) => ("Div", "div"),
BinaryOperator::DivEq(_) => ("DivEq", "div_eq"),
BinaryOperator::Mod(_) => ("Rem", "rem"),
BinaryOperator::ModEq(_) => ("RemEq", "rem_eq"),
BinaryOperator::EqEq(_) => ("PartialEq", "eq"),
BinaryOperator::Neq(_) => ("PartialEq", "ne"),
BinaryOperator::LE(_) => ("PartialOrd", "le"),
BinaryOperator::GE(_) => ("PartialOrd", "ge"),
BinaryOperator::LT(_) => ("PartialOrd", "lt"),
BinaryOperator::GT(_) => ("PartialOrd", "gt"),
BinaryOperator::And(_) => ("BitAnd", "bitand"),
BinaryOperator::Or(_) => ("BitOr", "bitor"),
BinaryOperator::Xor(_) => ("BitXor", "bitxor"),
_ => return Ok(Err(SemanticDiagnosticKind::UnknownBinaryOperator)),
};
Ok(Ok(get_core_trait_function_infer(
db,
inference,
trait_name.into(),
function_name.into(),
stable_ptr,
)))
}
pub fn felt252_eq(db: &dyn SemanticGroup) -> FunctionId {
get_core_function_impl_method(db, "Felt252PartialEq".into(), "eq".into())
}
pub fn felt252_sub(db: &dyn SemanticGroup) -> FunctionId {
get_core_function_impl_method(db, "Felt252Sub".into(), "sub".into())
}
fn get_core_function_impl_method(
db: &dyn SemanticGroup,
impl_name: SmolStr,
method_name: SmolStr,
) -> FunctionId {
let core_module = db.core_module();
let module_item_id = db
.module_item_by_name(core_module, impl_name.clone())
.expect("Failed to load core lib.")
.unwrap_or_else(|| panic!("Impl '{impl_name}' was not found in core lib."));
let impl_def_id = match module_item_id {
ModuleItemId::Use(use_id) => {
db.use_resolved_item(use_id).to_option().and_then(|resolved_generic_item| {
try_extract_matches!(resolved_generic_item, ResolvedGenericItem::Impl)
})
}
_ => ImplDefId::option_from(module_item_id),
}
.unwrap_or_else(|| panic!("{impl_name} is not an impl."));
let impl_id = ImplId::Concrete(
db.intern_concrete_impl(ConcreteImplLongId { impl_def_id, generic_args: vec![] }),
);
let concrete_trait_id = db.impl_concrete_trait(impl_id).unwrap();
let function = db
.trait_functions(concrete_trait_id.trait_id(db))
.ok()
.and_then(|functions| functions.get(&method_name).cloned())
.unwrap_or_else(|| {
panic!("no {method_name} in {}.", concrete_trait_id.trait_id(db).name(db.upcast()))
});
db.intern_function(FunctionLongId {
function: ConcreteFunction {
generic_function: GenericFunctionId::Impl(ImplGenericFunctionId { impl_id, function }),
generic_args: vec![],
},
})
}
pub fn core_felt252_is_zero(db: &dyn SemanticGroup) -> FunctionId {
get_core_function_id(db, "felt252_is_zero".into(), vec![])
}
pub fn get_core_function_id(
db: &dyn SemanticGroup,
name: SmolStr,
generic_args: Vec<GenericArgumentId>,
) -> FunctionId {
let generic_function = get_core_generic_function_id(db, name);
db.intern_function(FunctionLongId {
function: ConcreteFunction { generic_function, generic_args },
})
}
pub fn get_core_generic_function_id(db: &dyn SemanticGroup, name: SmolStr) -> GenericFunctionId {
let core_module = db.core_module();
let module_item_id = db
.module_item_by_name(core_module, name.clone())
.expect("Failed to load core lib.")
.unwrap_or_else(|| panic!("Function '{name}' was not found in core lib."));
match module_item_id {
ModuleItemId::Use(use_id) => {
db.use_resolved_item(use_id).to_option().and_then(|resolved_generic_item| {
try_extract_matches!(resolved_generic_item, ResolvedGenericItem::GenericFunction)
})
}
_ => GenericFunctionId::option_from(module_item_id),
}
.unwrap_or_else(|| panic!("{name} is not a function."))
}
pub fn concrete_copy_trait(db: &dyn SemanticGroup, ty: TypeId) -> ConcreteTraitId {
get_core_concrete_trait(db, "Copy".into(), vec![GenericArgumentId::Type(ty)])
}
pub fn concrete_drop_trait(db: &dyn SemanticGroup, ty: TypeId) -> ConcreteTraitId {
get_core_concrete_trait(db, "Drop".into(), vec![GenericArgumentId::Type(ty)])
}
pub fn copy_trait(db: &dyn SemanticGroup) -> TraitId {
get_core_trait(db, "Copy".into())
}
pub fn drop_trait(db: &dyn SemanticGroup) -> TraitId {
get_core_trait(db, "Drop".into())
}
fn get_core_concrete_trait(
db: &dyn SemanticGroup,
name: SmolStr,
generic_args: Vec<GenericArgumentId>,
) -> ConcreteTraitId {
let trait_id = get_core_trait(db, name);
db.intern_concrete_trait(semantic::ConcreteTraitLongId { trait_id, generic_args })
}
fn get_core_trait(db: &dyn SemanticGroup, name: SmolStr) -> TraitId {
let core_module = db.core_module();
let use_id = extract_matches!(
db.module_item_by_name(core_module, name).unwrap().unwrap(),
ModuleItemId::Use
);
let trait_id =
extract_matches!(db.use_resolved_item(use_id).unwrap(), ResolvedGenericItem::Trait);
trait_id
}
fn get_core_trait_function_infer(
db: &dyn SemanticGroup,
inference: &mut Inference<'_>,
trait_name: SmolStr,
function_name: SmolStr,
stable_ptr: SyntaxStablePtrId,
) -> ConcreteTraitGenericFunctionId {
let trait_id = get_core_trait(db, trait_name);
let generic_params = db.trait_generic_params(trait_id);
let generic_args = generic_params
.iter()
.map(|_| GenericArgumentId::Type(inference.new_type_var(stable_ptr)))
.collect();
let concrete_trait_id =
db.intern_concrete_trait(semantic::ConcreteTraitLongId { trait_id, generic_args });
let trait_function = db.trait_function_by_name(trait_id, function_name).unwrap().unwrap();
db.intern_concrete_trait_function(ConcreteTraitGenericFunctionLongId::new(
db,
concrete_trait_id,
trait_function,
))
}
pub fn get_panic_ty(db: &dyn SemanticGroup, inner_ty: TypeId) -> TypeId {
get_core_ty_by_name(db.upcast(), "PanicResult".into(), vec![GenericArgumentId::Type(inner_ty)])
}
pub fn get_const_libfunc_name_by_type(db: &dyn SemanticGroup, ty: TypeId) -> String {
if ty == core_felt252_ty(db) {
"felt252_const".into()
} else if ty == get_core_ty_by_name(db, "u8".into(), vec![]) {
"u8_const".into()
} else if ty == get_core_ty_by_name(db, "u16".into(), vec![]) {
"u16_const".into()
} else if ty == get_core_ty_by_name(db, "u32".into(), vec![]) {
"u32_const".into()
} else if ty == get_core_ty_by_name(db, "u64".into(), vec![]) {
"u64_const".into()
} else if ty == get_core_ty_by_name(db, "u128".into(), vec![]) {
"u128_const".into()
} else {
panic!("No const libfunc for type {}.", ty.format(db))
}
}
pub fn validate_literal(
db: &dyn SemanticGroup,
ty: TypeId,
value: BigInt,
) -> Result<(), SemanticDiagnosticKind> {
let is_out_of_range = if ty == core_felt252_ty(db) {
value.is_negative()
|| value
> BigInt::from_str_radix(
"800000000000011000000000000000000000000000000000000000000000000",
16,
)
.unwrap()
} else if ty == get_core_ty_by_name(db, "u8".into(), vec![]) {
value.is_negative() || value.bits() > 8
} else if ty == get_core_ty_by_name(db, "u16".into(), vec![]) {
value.is_negative() || value.bits() > 16
} else if ty == get_core_ty_by_name(db, "u32".into(), vec![]) {
value.is_negative() || value.bits() > 32
} else if ty == get_core_ty_by_name(db, "u64".into(), vec![]) {
value.is_negative() || value.bits() > 64
} else if ty == get_core_ty_by_name(db, "u128".into(), vec![]) {
value.is_negative() || value.bits() > 128
} else {
return Err(SemanticDiagnosticKind::NoLiteralFunctionFound);
};
if is_out_of_range { Err(SemanticDiagnosticKind::LiteralOutOfRange { ty }) } else { Ok(()) }
}