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
use sway_types::Span;
use crate::{error::*, semantic_analysis::*, type_system::*, types::DeterministicallyAborts};
use super::TypedExpression;
pub(crate) fn instantiate_if_expression(
condition: TypedExpression,
then: TypedExpression,
r#else: Option<TypedExpression>,
span: Span,
type_annotation: TypeId,
self_type: TypeId,
) -> CompileResult<TypedExpression> {
let mut warnings = vec![];
let mut errors = vec![];
let then_deterministically_aborts = then.deterministically_aborts();
if !then_deterministically_aborts {
let ty_to_check = if r#else.is_some() {
type_annotation
} else {
insert_type(TypeInfo::Tuple(vec![]))
};
let (mut new_warnings, new_errors) = unify_with_self(
then.return_type,
ty_to_check,
self_type,
&then.span,
"`then` branch must return expected type.",
);
warnings.append(&mut new_warnings);
errors.append(&mut new_errors.into_iter().map(|x| x.into()).collect());
}
let mut else_deterministically_aborts = false;
let r#else = r#else.map(|r#else| {
else_deterministically_aborts = r#else.deterministically_aborts();
let ty_to_check = if then_deterministically_aborts {
type_annotation
} else {
then.return_type
};
if !else_deterministically_aborts {
let (mut new_warnings, new_errors) = unify_with_self(
r#else.return_type,
ty_to_check,
self_type,
&r#else.span,
"`else` branch must return expected type.",
);
warnings.append(&mut new_warnings);
errors.append(&mut new_errors.into_iter().map(|x| x.into()).collect());
}
Box::new(r#else)
});
let r#else_ret_ty = r#else
.as_ref()
.map(|x| x.return_type)
.unwrap_or_else(|| insert_type(TypeInfo::Tuple(Vec::new())));
if !else_deterministically_aborts && !then_deterministically_aborts {
let (mut new_warnings, new_errors) = unify_with_self(
then.return_type,
r#else_ret_ty,
self_type,
&span,
"The two branches of an if expression must return the same type.",
);
warnings.append(&mut new_warnings);
if new_errors.is_empty() {
if !look_up_type_id(r#else_ret_ty).is_unit() && r#else.is_none() {
errors.push(CompileError::NoElseBranch {
span: span.clone(),
r#type: look_up_type_id(type_annotation).to_string(),
});
}
} else {
errors.append(&mut new_errors.into_iter().map(|x| x.into()).collect());
}
}
let return_type = if !then_deterministically_aborts {
then.return_type
} else {
r#else_ret_ty
};
let exp = TypedExpression {
expression: TypedExpressionVariant::IfExp {
condition: Box::new(condition),
then: Box::new(then),
r#else,
},
is_constant: IsConstant::No,
return_type,
span,
};
ok(exp, warnings, errors)
}