-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
operations.rs
504 lines (474 loc) · 13.4 KB
/
operations.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
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
use std::marker::PhantomData;
use derive_enum_from_into::EnumFrom;
use source_map::{Span, SpanWithSource};
use crate::{
diagnostics::TypeCheckError,
types::{
cast_as_number, cast_as_string, is_type_truthy_falsy, new_logical_or_type,
StructureGenerics, TypeStore,
},
ASTImplementation, CheckingData, Constant, Decidable, Environment, Type, TypeId,
};
#[derive(Clone, Debug, binary_serialize_derive::BinarySerializable)]
pub enum MathematicalAndBitwise {
Add,
Subtract,
Multiply,
Divide,
Modulo,
Exponent,
BitwiseShiftLeft,
BitwiseShiftRight,
BitwiseShiftRightUnsigned,
BitwiseAnd,
BitwiseXOr,
BitwiseOr,
}
#[derive(Clone, Debug, EnumFrom)]
pub enum PureBinaryOperation {
MathematicalAndBitwise(MathematicalAndBitwise),
// Some of these can be reduced
EqualityAndInequality(EqualityAndInequality),
}
/// TODO report errors better here
pub fn evaluate_pure_binary_operation_handle_errors<T: crate::ReadFromFS, M: ASTImplementation>(
(lhs, lhs_pos): (TypeId, SpanWithSource),
operator: PureBinaryOperation,
(rhs, rhs_pos): (TypeId, SpanWithSource),
checking_data: &mut CheckingData<T, M>,
environment: &mut Environment,
) -> TypeId {
match operator {
PureBinaryOperation::MathematicalAndBitwise(operator) => {
let result = evaluate_mathematical_operation(
lhs,
operator,
rhs,
&mut checking_data.types,
checking_data.options.strict_casts,
);
match result {
Ok(result) => result,
Err(err) => {
// checking_data.diagnostics_container.add_error(TypeCheckError::)
TypeId::ERROR_TYPE
}
}
}
PureBinaryOperation::EqualityAndInequality(operator) => {
evaluate_equality_inequality_operation(
lhs,
operator,
rhs,
&mut checking_data.types,
checking_data.options.strict_casts,
)
.unwrap_or(TypeId::ERROR_TYPE)
}
}
}
pub fn evaluate_mathematical_operation(
lhs: TypeId,
operator: MathematicalAndBitwise,
rhs: TypeId,
types: &mut TypeStore,
strict_casts: bool,
) -> Result<TypeId, ()> {
fn attempt_constant_math_operator(
lhs: TypeId,
operator: MathematicalAndBitwise,
rhs: TypeId,
types: &mut TypeStore,
strict_casts: bool,
) -> Result<TypeId, ()> {
if let MathematicalAndBitwise::Add = operator {
let constant = match (types.get_type_by_id(lhs), types.get_type_by_id(rhs)) {
(Type::Constant(Constant::Number(lhs)), Type::Constant(Constant::Number(rhs))) => {
Constant::Number(lhs + rhs)
}
(Type::Constant(lhs), Type::Constant(rhs)) => {
let mut first = cast_as_string(lhs, strict_casts)?;
let second = cast_as_string(rhs, strict_casts)?;
// Concatenate strings
first.push_str(&second);
Constant::String(first)
}
_ => return Err(()),
};
Ok(types.new_constant_type(constant))
} else {
match (types.get_type_by_id(lhs), types.get_type_by_id(rhs)) {
(Type::Constant(c1), Type::Constant(c2)) => {
let lhs = cast_as_number(c1, strict_casts).unwrap_or(f64::NAN);
let rhs = cast_as_number(c2, strict_casts).unwrap_or(f64::NAN);
// TODO hopefully Rust implementation is the same as JS
let value = match operator {
MathematicalAndBitwise::Add => unreachable!(),
MathematicalAndBitwise::Subtract => lhs - rhs,
MathematicalAndBitwise::Multiply => lhs * rhs,
MathematicalAndBitwise::Divide => lhs / rhs,
MathematicalAndBitwise::Modulo => lhs % rhs,
MathematicalAndBitwise::Exponent => lhs.powf(rhs),
MathematicalAndBitwise::BitwiseShiftLeft => {
f64::from((lhs as i32) << (rhs as i32))
}
MathematicalAndBitwise::BitwiseShiftRight => {
f64::from((lhs as i32) >> (rhs as i32))
}
MathematicalAndBitwise::BitwiseShiftRightUnsigned => {
(lhs as i32).wrapping_shr(rhs as u32).into()
}
MathematicalAndBitwise::BitwiseAnd => {
f64::from((lhs as i32) & (rhs as i32))
}
MathematicalAndBitwise::BitwiseXOr => {
f64::from((lhs as i32) ^ (rhs as i32))
}
MathematicalAndBitwise::BitwiseOr => f64::from((lhs as i32) | (rhs as i32)),
};
let value = ordered_float::NotNan::try_from(value);
let ty = match value {
Ok(value) => types.new_constant_type(Constant::Number(value)),
Err(_) => TypeId::NAN_TYPE,
};
Ok(ty)
}
_ => Err(()),
}
}
}
let is_dependent =
types.get_type_by_id(lhs).is_dependent() || types.get_type_by_id(rhs).is_dependent();
// TODO check sides
if is_dependent {
let constructor = crate::types::Constructor::BinaryOperator { lhs, operator, rhs };
return Ok(types.register_type(crate::Type::Constructor(constructor)));
}
attempt_constant_math_operator(lhs, operator, rhs, types, strict_casts)
}
/// Not canonical / reducible
#[derive(Clone, Debug)]
pub enum EqualityAndInequality {
StrictEqual,
StrictNotEqual,
Equal,
NotEqual,
GreaterThan,
LessThan,
LessThanEqual,
GreaterThanEqual,
}
/// Canonical / irreducible
#[derive(Clone, Debug, binary_serialize_derive::BinarySerializable)]
pub enum CanonicalEqualityAndInequality {
StrictEqual,
LessThan,
}
pub fn evaluate_equality_inequality_operation(
lhs: TypeId,
operator: EqualityAndInequality,
rhs: TypeId,
types: &mut TypeStore,
strict_casts: bool,
) -> Result<TypeId, ()> {
match operator {
EqualityAndInequality::StrictEqual => {
// crate::utils::notify!("{:?} === {:?}", lhs, rhs);
let is_dependent = types.get_type_by_id(lhs).is_dependent()
|| types.get_type_by_id(rhs).is_dependent();
// TODO check lhs and rhs type to see if they overlap
if is_dependent {
let constructor = crate::types::Constructor::CanonicalRelationOperator {
lhs,
operator: CanonicalEqualityAndInequality::StrictEqual,
rhs,
};
return Ok(types.register_type(crate::Type::Constructor(constructor)));
}
match attempt_constant_equality(lhs, rhs, types) {
Ok(ty) => Ok(ty),
Err(_) => {
unreachable!("should have been caught by above")
}
}
}
EqualityAndInequality::LessThan => {
fn attempt_less_than(
lhs: TypeId,
rhs: TypeId,
types: &mut TypeStore,
strict_casts: bool,
) -> Result<TypeId, ()> {
// Similar but reversed semantics to add
Ok(types.new_constant_type(
match (types.get_type_by_id(lhs), types.get_type_by_id(rhs)) {
(
Type::Constant(Constant::String(a)),
Type::Constant(Constant::String(b)),
) => Constant::Boolean(a < b),
(Type::Constant(c1), Type::Constant(c2)) => {
let lhs = cast_as_number(c1, strict_casts)?;
let rhs = cast_as_number(c2, strict_casts)?;
Constant::Boolean(lhs < rhs)
}
_ => return Err(()),
},
))
}
let is_dependent = types.get_type_by_id(lhs).is_dependent()
|| types.get_type_by_id(rhs).is_dependent();
if is_dependent {
let constructor = crate::types::Constructor::CanonicalRelationOperator {
lhs,
operator: CanonicalEqualityAndInequality::LessThan,
rhs,
};
return Ok(types.register_type(crate::Type::Constructor(constructor)));
}
attempt_less_than(lhs, rhs, types, strict_casts)
}
EqualityAndInequality::StrictNotEqual => {
let equality_result = evaluate_equality_inequality_operation(
rhs,
EqualityAndInequality::StrictEqual,
lhs,
types,
strict_casts,
)?;
evaluate_pure_unary_operator(
PureUnary::LogicalNot,
equality_result,
types,
strict_casts,
)
}
EqualityAndInequality::Equal => {
crate::utils::notify!("TODO equal operator");
Err(())
}
EqualityAndInequality::NotEqual => {
let equality_result = evaluate_equality_inequality_operation(
rhs,
EqualityAndInequality::Equal,
lhs,
types,
strict_casts,
)?;
evaluate_pure_unary_operator(
PureUnary::LogicalNot,
equality_result,
types,
strict_casts,
)
}
EqualityAndInequality::GreaterThan => evaluate_equality_inequality_operation(
rhs,
EqualityAndInequality::LessThan,
lhs,
types,
strict_casts,
),
EqualityAndInequality::LessThanEqual => {
let lhs = evaluate_equality_inequality_operation(
rhs,
EqualityAndInequality::StrictEqual,
lhs,
types,
strict_casts,
)?;
if lhs == TypeId::TRUE {
Ok(lhs)
} else if lhs == TypeId::FALSE {
evaluate_equality_inequality_operation(
rhs,
EqualityAndInequality::LessThan,
lhs,
types,
strict_casts,
)
} else {
let rhs = evaluate_equality_inequality_operation(
rhs,
EqualityAndInequality::LessThan,
lhs,
types,
strict_casts,
)?;
Ok(new_logical_or_type(lhs, rhs, types))
}
}
EqualityAndInequality::GreaterThanEqual => evaluate_equality_inequality_operation(
rhs,
EqualityAndInequality::LessThanEqual,
lhs,
types,
strict_casts,
),
}
}
#[derive(Clone, Debug)]
pub enum Logical {
And,
Or,
NullCoalescing,
}
/// TODO strict casts!
pub fn evaluate_logical_operation_with_expression<
T: crate::ReadFromFS,
M: crate::ASTImplementation,
>(
lhs: TypeId,
operator: Logical,
rhs: &M::Expression,
checking_data: &mut CheckingData<T, M>,
environment: &mut Environment,
) -> Result<TypeId, ()> {
enum TypeOrSynthesisable<'a, M: crate::ASTImplementation> {
Type(TypeId),
Expression(&'a M::Expression),
}
// impl<'a, M: crate::ASTImplementation> SynthesisableConditional<M> for TypeOrSynthesisable<'a, M> {
// type ExpressionResult = TypeId;
// fn synthesise_condition<T: crate::ReadFromFS>(
// self,
// environment: &mut Environment,
// checking_data: &mut CheckingData<T, M>,
// ) -> Self::ExpressionResult {
// match self {
// TypeOrSynthesisable::Type(ty) => ty,
// TypeOrSynthesisable::Expression(expr, _) => {
// M::synthesise_expression(expr, TypeId::ANY_TYPE, environment, checking_data)
// }
// }
// }
// fn conditional_expression_result(
// condition: TypeId,
// truthy_result: Self::ExpressionResult,
// falsy_result: Self::ExpressionResult,
// types: &mut TypeStore,
// ) -> Self::ExpressionResult {
// types.new_conditional_type(condition, truthy_result, falsy_result)
// }
// fn default_result() -> Self::ExpressionResult {
// unreachable!()
// }
// }
match operator {
Logical::And => Ok(environment.new_conditional_context(
lhs,
|env: &mut Environment, data: &mut CheckingData<T, M>| {
M::synthesise_expression(rhs, TypeId::ANY_TYPE, env, data)
},
Some(|_env: &mut Environment, _data: &mut CheckingData<T, M>| lhs),
checking_data,
)),
Logical::Or => Ok(environment.new_conditional_context(
lhs,
|_env: &mut Environment, _data: &mut CheckingData<T, M>| lhs,
Some(|env: &mut Environment, data: &mut CheckingData<T, M>| {
M::synthesise_expression(rhs, TypeId::ANY_TYPE, env, data)
}),
checking_data,
)),
Logical::NullCoalescing => {
let is_lhs_null = evaluate_equality_inequality_operation(
lhs,
EqualityAndInequality::StrictEqual,
TypeId::NULL_TYPE,
&mut checking_data.types,
checking_data.options.strict_casts,
)?;
Ok(environment.new_conditional_context(
is_lhs_null,
|env: &mut Environment, data: &mut CheckingData<T, M>| {
M::synthesise_expression(rhs, TypeId::ANY_TYPE, env, data)
},
Some(|_env: &mut Environment, _data: &mut CheckingData<T, M>| lhs),
checking_data,
))
}
}
}
#[derive(Clone, Debug, binary_serialize_derive::BinarySerializable)]
pub enum PureUnary {
LogicalNot,
Negation,
BitwiseNot,
}
pub fn evaluate_pure_unary_operator(
operator: PureUnary,
operand: TypeId,
types: &mut TypeStore,
strict_casts: bool,
) -> Result<TypeId, ()> {
match operator {
PureUnary::LogicalNot => {
if let Decidable::Known(value) = is_type_truthy_falsy(operand, types) {
if value {
Ok(TypeId::FALSE)
} else {
Ok(TypeId::TRUE)
}
} else {
Ok(types.new_logical_negation_type(operand))
}
}
PureUnary::Negation | PureUnary::BitwiseNot => {
if let Type::Constant(cst) = types.get_type_by_id(operand) {
let value = cast_as_number(cst, strict_casts)?;
let value = match operator {
PureUnary::LogicalNot => unreachable!(),
PureUnary::Negation => -value,
PureUnary::BitwiseNot => f64::from(!(value as i32)),
};
let value = ordered_float::NotNan::try_from(value);
Ok(match value {
Ok(value) => types.new_constant_type(Constant::Number(value)),
Err(_) => TypeId::NAN_TYPE,
})
} else {
Ok(types.register_type(Type::Constructor(
crate::types::Constructor::UnaryOperator { operator, operand },
)))
}
}
}
}
fn attempt_constant_equality(
lhs: TypeId,
rhs: TypeId,
types: &mut TypeStore,
) -> Result<TypeId, ()> {
let are_equal =
if lhs == rhs {
true
} else {
let lhs = types.get_type_by_id(lhs);
let rhs = types.get_type_by_id(rhs);
if let (Type::Constant(cst1), Type::Constant(cst2)) = (lhs, rhs) {
cst1 == cst2
} else if let (Type::Object(..) | Type::Function(..), _)
| (_, Type::Object(..) | Type::Function(..)) = (lhs, rhs)
{
// Same objects and functions always have same type id. Poly case doesn't occur here
false
}
// Temp fix for closures
else if let (
Type::Constructor(crate::types::Constructor::StructureGenerics(
StructureGenerics { on: on_lhs, .. },
)),
Type::Constructor(crate::types::Constructor::StructureGenerics(
StructureGenerics { on: on_rhs, .. },
)),
) = (lhs, rhs)
{
// TODO does this work?
return attempt_constant_equality(*on_lhs, *on_rhs, types);
} else {
crate::utils::notify!("{:?} === {:?} is apparently false", lhs, rhs);
return Err(());
}
};
Ok(types.new_constant_type(Constant::Boolean(are_equal)))
}