-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathenvironment.rs
1320 lines (1214 loc) · 35.4 KB
/
environment.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use source_map::{SourceId, Span, SpanWithSource};
use std::collections::{HashMap, HashSet};
use crate::{
context::{get_on_ctx, information::ReturnState},
diagnostics::{
NotInLoopOrCouldNotFindLabel, PropertyRepresentation, TypeCheckError,
TypeStringRepresentation, TDZ,
},
events::{Event, FinalEvent, RootReference},
features::{
assignments::{
Assignable, AssignableArrayDestructuringField, AssignableObjectDestructuringField,
AssignmentKind, Reference,
},
modules::Exported,
objects::SpecialObject,
operations::{
evaluate_logical_operation_with_expression,
evaluate_pure_binary_operation_handle_errors, MathematicalAndBitwise,
},
variables::{VariableMutability, VariableOrImport, VariableWithValue},
},
subtyping::{type_is_subtype, type_is_subtype_object, State, SubTypeResult, SubTypingOptions},
types::{
printing,
properties::{AccessMode, PropertyKey, PropertyKind, PropertyValue, Publicity},
PolyNature, Type, TypeStore,
},
CheckingData, Instance, RootContext, TypeCheckOptions, TypeId,
};
use super::{
get_value_of_variable, information::InformationChain, invocation::CheckThings, AssignmentError,
ClosedOverReferencesInScope, Context, ContextType, Environment, GeneralContext,
SetPropertyError,
};
pub type ContextLocation = Option<String>;
#[derive(Debug)]
pub struct Syntax<'a> {
pub scope: Scope,
pub(crate) parent: GeneralContext<'a>,
/// Variables that this context pulls in from above (across a dynamic context). aka not from parameters of bound this
/// Not to be confused with `closed_over_references`
pub free_variables: HashSet<RootReference>,
/// Variables used in this scope which are closed over by functions. These need to be stored
/// Not to be confused with `used_parent_references`
pub closed_over_references: ClosedOverReferencesInScope,
/// TODO WIP! server, client, worker etc
pub location: ContextLocation,
/// Parameter inference requests
/// TODO RHS = Has Property
pub requests: Vec<(TypeId, TypeId)>,
}
/// Code under a dynamic boundary can run more than once
#[derive(Debug, Clone, Copy)]
pub enum DynamicBoundaryKind {
Loop,
Function,
}
impl DynamicBoundaryKind {
#[must_use]
pub fn can_use_variable_before_definition(self) -> bool {
matches!(self, Self::Function)
}
}
impl<'a> ContextType for Syntax<'a> {
fn as_general_context(et: &Context<Self>) -> GeneralContext<'_> {
GeneralContext::Syntax(et)
}
fn get_parent(&self) -> Option<&GeneralContext<'_>> {
Some(&self.parent)
}
fn as_syntax(&self) -> Option<&Syntax> {
Some(self)
}
fn get_closed_over_references_mut(&mut self) -> Option<&mut ClosedOverReferencesInScope> {
Some(&mut self.closed_over_references)
}
}
#[derive(Debug, Clone, Copy)]
pub enum ExpectedReturnType {
/// This may have a position in the future
Inferred(TypeId),
FromReturnAnnotation(TypeId, Span),
}
impl ExpectedReturnType {
pub(crate) fn get_type_and_position(self) -> (TypeId, Option<Span>) {
match self {
ExpectedReturnType::Inferred(ty) => (ty, None),
ExpectedReturnType::FromReturnAnnotation(ty, pos) => (ty, Some(pos)),
}
}
}
/// TODO better names
/// Decides whether `await` and `yield` are available and many others
///
/// `this` is the dependent type
#[derive(Debug, Clone)]
pub enum FunctionScope {
ArrowFunction {
// This always points to a poly free variable type
free_this_type: TypeId,
is_async: bool,
expected_return: Option<ExpectedReturnType>,
},
/// TODO does this need to gdistinguish class
MethodFunction {
// This always points to a poly free variable type
free_this_type: TypeId,
is_async: bool,
is_generator: bool,
expected_return: Option<ExpectedReturnType>,
},
// is new-able
Function {
is_generator: bool,
is_async: bool,
expected_return: Option<ExpectedReturnType>,
// This always points to a conditional type based on `new.target === undefined`
this_type: TypeId,
type_of_super: TypeId,
location: ContextLocation,
},
Constructor {
/// Can call `super`
extends: bool,
type_of_super: Option<TypeId>,
// This is always created, but may not be used (or have the relevant properties & prototype)
this_object_type: TypeId,
},
}
impl FunctionScope {
// TODO temp
pub(crate) fn get_expected_return_type_mut(&mut self) -> &mut Option<ExpectedReturnType> {
match self {
FunctionScope::ArrowFunction { expected_return, .. }
| FunctionScope::MethodFunction { expected_return, .. }
| FunctionScope::Function { expected_return, .. } => expected_return,
FunctionScope::Constructor { .. } => unreachable!(),
}
}
}
/// For labeled statements
pub type Label = Option<String>;
#[derive(Clone, Copy)]
pub enum Returnable<'a, A: crate::ASTImplementation> {
Statement(Option<&'a A::MultipleExpression<'a>>, Span),
ArrowFunctionBody(&'a A::Expression<'a>),
}
/// TODO name of structure
/// TODO conditionals should have conditional proofs (separate from the ones on context)
#[derive(Debug, Clone)]
pub enum Scope {
Function(FunctionScope),
InterfaceEnvironment {
this_constraint: TypeId,
},
DefaultFunctionParameter {},
FunctionAnnotation {},
/// For ifs, elses, or lazy operators
Conditional {
/// Something that is truthy for this to run
antecedent: TypeId,
is_switch: Option<Label>,
},
/// Variables here are dependent on the iteration,
Iteration {
label: Label, // TODO on: Proofs,
},
TryBlock {},
CatchBlock {},
FinallyBlock {},
// Just blocks and modules
Block {},
Module {
source: SourceId,
exported: Exported,
},
DefinitionModule {
source: SourceId,
},
/// For generic parameters
TypeAlias,
StaticBlock {
this_type: TypeId,
},
/// For repl only
PassThrough {
source: SourceId,
},
TypeAnnotationCondition {
infer_parameters: HashMap<String, TypeId>,
},
TypeAnnotationConditionResult,
}
impl Scope {
#[must_use]
pub fn is_dynamic_boundary(&self) -> Option<DynamicBoundaryKind> {
match self {
Scope::Function { .. } => Some(DynamicBoundaryKind::Function),
Scope::Iteration { .. } => Some(DynamicBoundaryKind::Loop),
_ => None,
}
}
#[must_use]
pub fn is_conditional(&self) -> bool {
matches!(self, Scope::Conditional { .. })
}
}
impl<'a> Environment<'a> {
/// Handles all assignments, including updates and destructuring
///
/// Will evaluate the expression with the right timing and conditions, including never if short circuit
///
/// TODO finish operator. Unify increment and decrement. The RHS span should be fine with [`Span::NULL ...?`] Maybe RHS type could be None to accommodate
pub fn assign_to_assignable_handle_errors<
'b,
T: crate::ReadFromFS,
A: crate::ASTImplementation,
>(
&mut self,
lhs: Assignable<A>,
operator: AssignmentKind,
// Can be `None` for increment and decrement
expression: Option<&'b A::Expression<'b>>,
assignment_span: Span,
checking_data: &mut CheckingData<T, A>,
) -> TypeId {
match lhs {
Assignable::Reference(reference) => {
match operator {
AssignmentKind::Assign => {
let rhs = A::synthesise_expression(
expression.unwrap(),
TypeId::ANY_TYPE,
self,
checking_data,
);
self.assign_to_reference_assign_handle_errors(
reference,
rhs,
checking_data,
assignment_span,
)
}
AssignmentKind::PureUpdate(operator) => {
// Order matters here
let reference_position = reference.get_position();
let existing = self.get_reference(
reference.clone(),
checking_data,
AccessMode::Regular,
);
let expression = expression.unwrap();
let expression_pos =
A::expression_position(expression).with_source(self.get_source());
let rhs = A::synthesise_expression(
expression,
TypeId::ANY_TYPE,
self,
checking_data,
);
let new = evaluate_pure_binary_operation_handle_errors(
(existing, reference_position),
operator.into(),
(rhs, expression_pos),
checking_data,
self,
);
let result = self.set_reference(reference, new, checking_data);
match result {
Ok(ty) => ty,
Err(error) => {
let error = set_property_error_to_type_check_error(
self,
error,
assignment_span.with_source(self.get_source()),
&checking_data.types,
new,
);
checking_data.diagnostics_container.add_error(error);
TypeId::ERROR_TYPE
}
}
}
AssignmentKind::IncrementOrDecrement(direction, return_kind) => {
// let value =
// self.get_variable_or_error(&name, &assignment_span, checking_data);
let span = reference.get_position();
let existing = self.get_reference(
reference.clone(),
checking_data,
AccessMode::Regular,
);
// TODO existing needs to be cast to number!!
let new = evaluate_pure_binary_operation_handle_errors(
(existing, span),
match direction {
crate::features::assignments::IncrementOrDecrement::Increment => {
MathematicalAndBitwise::Add
}
crate::features::assignments::IncrementOrDecrement::Decrement => {
MathematicalAndBitwise::Subtract
}
}
.into(),
(TypeId::ONE, source_map::Nullable::NULL),
checking_data,
self,
);
let result = self.set_reference(reference, new, checking_data);
match result {
Ok(new) => match return_kind {
crate::features::assignments::AssignmentReturnStatus::Previous => {
existing
}
crate::features::assignments::AssignmentReturnStatus::New => new,
},
Err(error) => {
let error = set_property_error_to_type_check_error(
self,
error,
assignment_span.with_source(self.get_source()),
&checking_data.types,
new,
);
checking_data.diagnostics_container.add_error(error);
TypeId::ERROR_TYPE
}
}
}
AssignmentKind::ConditionalUpdate(operator) => {
let existing = self.get_reference(
reference.clone(),
checking_data,
AccessMode::Regular,
);
let expression = expression.unwrap();
let new = evaluate_logical_operation_with_expression(
(existing, reference.get_position().without_source()),
operator,
expression,
checking_data,
self,
)
.unwrap();
let result = self.set_reference(reference, new, checking_data);
match result {
Ok(new) => new,
Err(error) => {
let error = set_property_error_to_type_check_error(
self,
error,
assignment_span.with_source(self.get_source()),
&checking_data.types,
new,
);
checking_data.diagnostics_container.add_error(error);
TypeId::ERROR_TYPE
}
}
}
}
}
Assignable::ObjectDestructuring(members, _spread) => {
debug_assert!(matches!(operator, AssignmentKind::Assign));
let rhs = A::synthesise_expression(
expression.unwrap(),
TypeId::ANY_TYPE,
self,
checking_data,
);
self.assign_to_object_destructure_handle_errors(
members,
rhs,
assignment_span,
checking_data,
)
}
Assignable::ArrayDestructuring(members, _spread) => {
debug_assert!(matches!(operator, AssignmentKind::Assign));
let rhs = A::synthesise_expression(
expression.unwrap(),
TypeId::ANY_TYPE,
self,
checking_data,
);
self.assign_to_array_destructure_handle_errors(
members,
rhs,
assignment_span,
checking_data,
)
}
}
}
fn assign_to_reference_assign_handle_errors<
T: crate::ReadFromFS,
A: crate::ASTImplementation,
>(
&mut self,
reference: Reference,
rhs: TypeId,
checking_data: &mut CheckingData<T, A>,
assignment_span: source_map::BaseSpan<()>,
) -> TypeId {
let result = self.set_reference(reference, rhs, checking_data);
match result {
Ok(ty) => ty,
Err(error) => {
let error = set_property_error_to_type_check_error(
self,
error,
assignment_span.with_source(self.get_source()),
&checking_data.types,
rhs,
);
checking_data.diagnostics_container.add_error(error);
TypeId::ERROR_TYPE
}
}
}
fn assign_to_assign_only_handle_errors<T: crate::ReadFromFS, A: crate::ASTImplementation>(
&mut self,
lhs: Assignable<A>,
rhs: TypeId,
assignment_span: Span,
checking_data: &mut CheckingData<T, A>,
) -> TypeId {
match lhs {
Assignable::Reference(reference) => self.assign_to_reference_assign_handle_errors(
reference,
rhs,
checking_data,
assignment_span,
),
Assignable::ObjectDestructuring(assignments, _spread) => self
.assign_to_object_destructure_handle_errors(
assignments,
rhs,
assignment_span,
checking_data,
),
Assignable::ArrayDestructuring(assignments, _spread) => self
.assign_to_array_destructure_handle_errors(
assignments,
rhs,
assignment_span,
checking_data,
),
}
}
fn assign_to_object_destructure_handle_errors<
T: crate::ReadFromFS,
A: crate::ASTImplementation,
>(
&mut self,
assignments: Vec<AssignableObjectDestructuringField<A>>,
rhs: TypeId,
assignment_span: Span,
checking_data: &mut CheckingData<T, A>,
) -> TypeId {
for assignment in assignments {
match assignment {
AssignableObjectDestructuringField::Mapped {
on,
name,
default_value,
position,
} => {
let value = self.get_property(
rhs,
Publicity::Public,
&on,
&mut checking_data.types,
None,
position,
&checking_data.options,
AccessMode::DoNotBindThis,
);
let rhs_value = if let Some((_, value)) = value {
value
} else if let Some(default_value) = default_value {
A::synthesise_expression(
default_value.as_ref(),
TypeId::ANY_TYPE,
self,
checking_data,
)
} else {
checking_data.diagnostics_container.add_error(
TypeCheckError::PropertyDoesNotExist {
property: match on {
PropertyKey::String(s) => {
PropertyRepresentation::StringKey(s.to_string())
}
PropertyKey::Type(t) => PropertyRepresentation::Type(
printing::print_type(t, &checking_data.types, self, false),
),
},
on: TypeStringRepresentation::from_type_id(
rhs,
self,
&checking_data.types,
false,
),
site: position,
},
);
TypeId::ERROR_TYPE
};
self.assign_to_assign_only_handle_errors(
name,
rhs_value,
assignment_span,
checking_data,
);
}
}
}
rhs
}
#[allow(clippy::needless_pass_by_value)]
fn assign_to_array_destructure_handle_errors<
T: crate::ReadFromFS,
A: crate::ASTImplementation,
>(
&mut self,
_assignments: Vec<AssignableArrayDestructuringField<A>>,
_rhs: TypeId,
assignment_span: Span,
checking_data: &mut CheckingData<T, A>,
) -> TypeId {
checking_data.raise_unimplemented_error(
"destructuring array (needs iterator)",
assignment_span.with_source(self.get_source()),
);
TypeId::ERROR_TYPE
}
fn get_reference<U: crate::ReadFromFS, A: crate::ASTImplementation>(
&mut self,
reference: Reference,
checking_data: &mut CheckingData<U, A>,
mode: AccessMode,
) -> TypeId {
match reference {
Reference::Variable(name, position) => {
self.get_variable_handle_error(&name, position, checking_data).unwrap().1
}
Reference::Property { on, with, publicity, span } => {
let get_property_handle_errors = self.get_property_handle_errors(
on,
publicity,
&with,
checking_data,
span,
mode,
);
match get_property_handle_errors {
Ok(i) => i.get_value(),
Err(()) => TypeId::ERROR_TYPE,
}
}
}
}
fn set_reference<U: crate::ReadFromFS, A: crate::ASTImplementation>(
&mut self,
reference: Reference,
rhs: TypeId,
checking_data: &mut CheckingData<U, A>,
) -> Result<TypeId, SetPropertyError> {
match reference {
Reference::Variable(name, position) => Ok(self.assign_to_variable_handle_errors(
name.as_str(),
position,
rhs,
checking_data,
)),
Reference::Property { on, with, publicity, span } => Ok(self
.set_property(
on,
publicity,
&with,
rhs,
&mut checking_data.types,
span,
&checking_data.options,
)?
.unwrap_or(rhs)),
}
}
pub fn assign_to_variable_handle_errors<T: crate::ReadFromFS, A: crate::ASTImplementation>(
&mut self,
variable_name: &str,
assignment_position: SpanWithSource,
new_type: TypeId,
checking_data: &mut CheckingData<T, A>,
) -> TypeId {
let result = self.assign_to_variable(
variable_name,
assignment_position,
new_type,
&mut checking_data.types,
);
match result {
Ok(ok) => ok,
Err(error) => {
checking_data
.diagnostics_container
.add_error(TypeCheckError::AssignmentError(error));
TypeId::ERROR_TYPE
}
}
}
/// This is top level variables, not properties.
pub fn assign_to_variable(
&mut self,
variable_name: &str,
assignment_position: SpanWithSource,
new_type: TypeId,
types: &mut TypeStore,
) -> Result<TypeId, AssignmentError> {
// Get without the effects
let variable_in_map = self.get_variable_unbound(variable_name);
if let Some((_, boundary, variable)) = variable_in_map {
match variable {
VariableOrImport::Variable {
mutability,
declared_at,
context: _,
allow_reregistration: _,
} => match mutability {
VariableMutability::Constant => Err(AssignmentError::Constant(*declared_at)),
VariableMutability::Mutable { reassignment_constraint } => {
let variable = variable.clone();
let variable_site = *declared_at;
let variable_id = variable.get_id();
if boundary.is_none()
&& !self
.get_chain_of_info()
.any(|info| info.variable_current_value.contains_key(&variable_id))
{
return Err(AssignmentError::TDZ(TDZ {
position: assignment_position,
variable_name: variable_name.to_owned(),
}));
}
if let Some(reassignment_constraint) = *reassignment_constraint {
let result = type_is_subtype_object(
reassignment_constraint,
new_type,
self,
types,
);
if let SubTypeResult::IsNotSubType(_mismatches) = result {
return Err(AssignmentError::DoesNotMeetConstraint {
variable_type: TypeStringRepresentation::from_type_id(
reassignment_constraint,
self,
types,
false,
),
value_type: TypeStringRepresentation::from_type_id(
new_type, self, types, false,
),
variable_site,
value_site: assignment_position,
});
}
}
self.info.events.push(Event::SetsVariable(
variable_id,
new_type,
assignment_position,
));
self.info.variable_current_value.insert(variable_id, new_type);
Ok(new_type)
}
},
VariableOrImport::MutableImport { .. }
| VariableOrImport::ConstantImport { .. } => {
Err(AssignmentError::Constant(assignment_position))
}
}
} else {
crate::utilities::notify!("Could say it is on the window here");
Err(AssignmentError::VariableNotFound {
variable: variable_name.to_owned(),
assignment_position,
})
}
}
pub(crate) fn get_root(&self) -> &RootContext {
match self.context_type.parent {
GeneralContext::Syntax(syntax) => syntax.get_root(),
GeneralContext::Root(root) => root,
}
}
#[must_use]
pub fn get_environment_type(&self) -> &Scope {
&self.context_type.scope
}
pub fn get_environment_type_mut(&mut self) -> &mut Scope {
&mut self.context_type.scope
}
/// `object_constraints` is LHS is constrained to RHS
pub fn add_parameter_constraint_request(
&mut self,
requests: impl Iterator<Item = (TypeId, TypeId)>,
) {
self.context_type.requests.extend(requests);
}
pub(crate) fn get_parent(&self) -> GeneralContext {
match self.context_type.parent {
GeneralContext::Syntax(syn) => GeneralContext::Syntax(syn),
GeneralContext::Root(rt) => GeneralContext::Root(rt),
}
}
#[allow(clippy::too_many_arguments)]
pub fn get_property(
&mut self,
on: TypeId,
publicity: Publicity,
property: &PropertyKey,
types: &mut TypeStore,
with: Option<TypeId>,
position: SpanWithSource,
options: &TypeCheckOptions,
mode: AccessMode,
) -> Option<(PropertyKind, TypeId)> {
crate::types::properties::get_property(
on,
publicity,
property,
with,
self,
&mut CheckThings { debug_types: options.debug_types },
types,
position,
mode,
)
}
pub fn get_property_handle_errors<U: crate::ReadFromFS, A: crate::ASTImplementation>(
&mut self,
on: TypeId,
publicity: Publicity,
key: &PropertyKey,
checking_data: &mut CheckingData<U, A>,
site: SpanWithSource,
mode: AccessMode,
) -> Result<Instance, ()> {
let get_property = self.get_property(
on,
publicity,
key,
&mut checking_data.types,
None,
site,
&checking_data.options,
mode,
);
if let Some((kind, result)) = get_property {
Ok(match kind {
PropertyKind::Getter => Instance::GValue(result),
// TODO instance.property...?
PropertyKind::Generic | PropertyKind::Direct | PropertyKind::Setter => {
Instance::RValue(result)
}
})
} else {
checking_data.diagnostics_container.add_error(TypeCheckError::PropertyDoesNotExist {
// TODO printing temp
property: match key {
PropertyKey::String(s) => PropertyRepresentation::StringKey(s.to_string()),
PropertyKey::Type(t) => PropertyRepresentation::Type(printing::print_type(
*t,
&checking_data.types,
self,
false,
)),
},
on: crate::diagnostics::TypeStringRepresentation::from_type_id(
on,
self,
&checking_data.types,
false,
),
site,
});
Err(())
}
}
pub fn get_variable_handle_error<U: crate::ReadFromFS, A: crate::ASTImplementation>(
&mut self,
name: &str,
position: SpanWithSource,
checking_data: &mut CheckingData<U, A>,
) -> Result<VariableWithValue, TypeId> {
let (in_root, crossed_boundary, og_var) = {
let variable_information = self.get_variable_unbound(name);
// crate::utilities::notify!("{:?} returned {:?}", name, variable_information);
if let Some((in_root, crossed_boundary, og_var)) = variable_information {
(in_root, crossed_boundary, og_var.clone())
} else {
checking_data.diagnostics_container.add_error(
TypeCheckError::CouldNotFindVariable {
variable: name,
// TODO
possibles: Default::default(),
position,
},
);
return Err(TypeId::ERROR_TYPE);
}
};
let reference = RootReference::Variable(og_var.get_id());
// TODO context checking here
// {
// if let VariableOrImport::Variable { context: Some(ref context), .. } = og_var {
// if let Some(ref current_context) = self.parents_iter().find_map(|a| {
// if let GeneralContext::Syntax(syn) = a {
// syn.context_type.location.clone()
// } else {
// None
// }
// }) {
// if current_context != context {
// checking_data.diagnostics_container.add_error(
// TypeCheckError::VariableNotDefinedInContext {
// variable: name,
// expected_context: context,
// current_context: current_context.clone(),
// position,
// },
// );
// return Err(TypeId::ERROR_TYPE);
// }
// }
// }
// }
// let treat_as_in_same_scope = (og_var.is_constant && self.is_immutable(current_value));
// TODO in_root temp fix to treat those as constant (so Math works in functions)
if let (Some(_boundary), false) = (crossed_boundary, in_root) {
let based_on = match og_var.get_mutability() {
VariableMutability::Constant => {
let constraint = checking_data
.local_type_mappings
.variables_to_constraints
.0
.get(&og_var.get_origin_variable_id());
// TODO temp
{
let current_value = get_value_of_variable(
self,
og_var.get_id(),
None::<
&crate::types::generics::substitution::SubstitutionArguments<
'static,
>,
>,
);
if let Some(current_value) = current_value {
let ty = checking_data.types.get_type_by_id(current_value);
// TODO temp
if let Type::SpecialObject(SpecialObject::Function(..)) = ty {
return Ok(VariableWithValue(og_var.clone(), current_value));
} else if let Type::RootPolyType(PolyNature::Open(_)) = ty {
crate::utilities::notify!(
"Open poly type '{}' treated as immutable free variable",
name
);
return Ok(VariableWithValue(og_var.clone(), current_value));
} else if let Type::Constant(_) = ty {
return Ok(VariableWithValue(og_var.clone(), current_value));
}
crate::utilities::notify!("Free variable with value!");
} else {
crate::utilities::notify!("Free variable with no current value");
}
}
// TODO is primitive, then can just use type
if let Some(constraint) = constraint {
*constraint
} else {
crate::utilities::notify!("TODO record that parent variable is `any` here");
TypeId::ANY_TYPE
}
}
VariableMutability::Mutable { reassignment_constraint } => {
// TODO is there a nicer way to do this
// Look for reassignments
let variable_id = og_var.get_id();
// `break`s here VERY IMPORTANT
for ctx in self.parents_iter() {
if let GeneralContext::Syntax(s) = ctx {
if s.possibly_mutated_variables.contains(&variable_id) {
break;
}
if let Some(value) =
get_on_ctx!(ctx.info.variable_current_value.get(&variable_id))
{
return Ok(VariableWithValue(og_var.clone(), *value));
}
if s.context_type.scope.is_dynamic_boundary().is_some() {
break;
}
}
}
if let Some(constraint) = reassignment_constraint {
constraint
} else {
crate::utilities::notify!("TODO record that parent variable is `any` here");
TypeId::ANY_TYPE
}
}
};
let mut reused_reference = None;
{
let mut reversed_events = self.info.events.iter().rev();
while let Some(event) = reversed_events.next() {