-
Notifications
You must be signed in to change notification settings - Fork 0
/
memory.rs
1554 lines (1395 loc) · 66 KB
/
memory.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 super::ast;
use super::flatten;
use super::parser::{emit_error, emit_warn, emit_debug};
use std::collections::HashMap;
use super::name::Name;
use super::ast::Tags;
use std::sync::atomic::{AtomicBool, Ordering};
static ABORT: AtomicBool = AtomicBool::new(false);
type Address = usize;
#[derive(Debug)]
enum Error {
Error {
message: String,
details: Vec<(ast::Location, String)>,
},
Untrackable(String),
}
impl Error {
pub fn new(message: String, details: Vec<(ast::Location, String)>) -> Self {
Self::Error {
message,
details,
}
}
}
#[derive(Clone)]
enum Value {
Void,
Uninitialized,
Untrackable(String),
Literal(String),
Address(Address),
Array(Vec<Address>),
Struct(HashMap<String, Address>),
Function {
name: Name,
ret: Option<(Address, ast::Typed)>,
args: Vec<ast::NamedArg>,
vararg: bool,
},
Moved{
moved_here: ast::Location,
},
Dropped {
stored_here: ast::Location,
dropped_here: ast::Location,
},
}
impl Value {
pub fn as_pointer(&self) -> usize {
match self {
Value::Address(u) => *u,
_ => panic!("ICE: not a pointer"),
}
}
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Value::Void => write!(f, "void"),
Value::Uninitialized => write!(f, "uninitialized"),
Value::Untrackable(s) => write!(f, "untrackable: {}", s),
Value::Literal(s) => write!(f, "literal({})", s),
Value::Struct(_) => write!(f, "struct"),
Value::Array(_) => write!(f, "array"),
Value::Address(to) => write!(f, "ptr->{}", to),
Value::Function {..} => write!(f, "function"),
Value::Moved{..} => write!(f, "moved"),
Value::Dropped{..} => write!(f, "dropped"),
}
}
}
#[derive(Clone)]
struct Storage {
name: Name,
typ: Option<ast::Typed>,
tags: Tags,
stored_here: ast::Location,
changed_here: Option<ast::Location>,
value: Value,
}
struct Scope {
name: String,
locals: HashMap<Name, usize>
}
#[derive(Default)]
struct Stack {
defs: HashMap<Name, ast::Def>,
storage: Vec<Storage>,
stack: Vec<Scope>,
current_return_ptr: Option<usize>,
must_move_before_ret: HashMap<usize, ast::Location>,
}
impl Stack {
fn push(&mut self, name: &str) {
debug!(" scope {}", name);
self.stack.push(Scope{
name: name.to_string(),
locals: HashMap::new(),
});
}
fn pop(&mut self, dropped_here: &ast::Location) {
let dead = self.stack.pop().unwrap();
let mut dead : Vec<usize> = dead.locals.iter().map(|(_,ptr)|*ptr).collect();
for d in dead.clone() {
let m = self.storage.get_mut(d).unwrap();
if let Value::Struct(ref fields) = m.value{
for (_,ar) in fields {
dead.push(*ar);
}
}
}
for d in dead {
let m = self.storage.get_mut(d).unwrap();
if !m.tags.contains_key("borrowed") {
if let Some(vals) = m.tags.get("marked") {
for (val,vloc) in vals {
emit_warn(format!("dropped local '{}' while still marked as '{}'", m.name, val), &[
(dropped_here.clone(), format!("'{}' will be dropped unclean", m.name)),
(vloc.clone(), format!("marked '{}' here. probably must call a related function to unset", val))
]);
}
}
}
m.value = Value::Dropped {
stored_here: m.stored_here.clone(),
dropped_here: dropped_here.clone(),
};
}
}
fn cur(&mut self) -> &mut Scope {
self.stack.last_mut().unwrap()
}
fn find(&self, name: &Name) -> Option<usize> {
for scope in self.stack.iter().rev() {
if let Some(v) = scope.locals.get(name) {
return Some(*v);
}
}
return None;
}
fn local(&mut self, typ: Option<ast::Typed>, name: Name, loc: ast::Location, tags: Tags) -> Address {
if let Some(_) = self.cur().locals.get(&name) {
emit_error(format!("redeclation of local name '{}'", name), &[
(loc.clone(), "this declaration would shadow a previous name")
]);
ABORT.store(true, Ordering::Relaxed);
}
let ptr = self.storage.len();
self.storage.push(Storage{
typ,
name: name.clone(),
stored_here: loc.clone(),
value: Value::Uninitialized,
tags: tags,
changed_here: None,
});
debug!(" let {} = {}", name, ptr);
self.cur().locals.insert(name, ptr);
self.initialize(ptr, &loc, false);
ptr
}
fn check_name(&mut self, name: &Name, used_here: &ast::Location) -> Result<Address, Error> {
match self.find(&name) {
None => {
return Err(Error::new(format!("undefined name '{}'", name), vec![
(used_here.clone(), format!("'{}' is not defined in this scope", name))
]));
},
Some(v) => Ok(v),
}
}
/*
fn read(&self, pointer: usize, used_here: &ast::Location) -> Result<SafeValue, Error> {
let storage = self.storage.get(pointer).expect("ICE: invalid pointer");
match &storage.value {
Value::Dropped{stored_here, dropped_here} => {
return Err(Error::new(format!("illegal read access to dropped value '{}'", storage.name), vec![
(used_here.clone(), "used here".to_string()),
(stored_here.clone(), "points at this storage location".to_string()),
(dropped_here.clone(), "which was dropped here".to_string()),
]));
},
_ => (),
}
if storage.tags.contains_key("unsafe") {
return Err(Error::new(format!("illegal read access to unsafe storage '{}'", storage.name), vec![
(used_here.clone(), "used here".to_string()),
(storage.stored_here.clone(), "suggestion: add a runtime check for this value and mark it safe".to_string()),
]));
}
match &storage.value {
Value::Uninitialized => {
return Err(Error::new(format!("illegal read access to unitialized local '{}'", storage.name), vec![
(used_here.clone(), "used here".to_string())
]));
}
Value::Moved{moved_here} => {
return Err(Error::new(format!("illegal read access of moved value '{}'", storage.name), vec![
(used_here.clone(), "use of moved value".to_string()),
(moved_here.clone(), "was moved here".to_string())
]));
}
Value::Address(p) => {
return Ok(SafeValue::Address(*p));
}
o => {
return Err(Error::new(format!("illegal read access of {} '{}'", o, storage.name), vec![
(used_here.clone(), "used in this context".to_string()),
]));
}
}
}
*/
fn write(&mut self, pointer: usize, val: Value, used_here: &ast::Location) {
let storage = self.storage.get_mut(pointer).expect("ICE: invalid pointer");
debug!(" {} {} <= {}", storage.name, pointer, val);
storage.value = val.clone();
storage.changed_here = Some(used_here.clone());
}
fn initialize(&mut self, to: usize, loc: &ast::Location, deep : bool) {
let storage = self.storage[to].clone();
if let Some(totyp) = storage.typ {
if totyp.ptr.len() > 0 {
if deep {
let mut depth = totyp.clone();
let ptrt = depth.ptr.pop().unwrap();
let mut tags = Tags::new();
tags.insert("unsafe".to_string(), String::new(), loc.clone());
let temp_ptr = self.local(Some(depth.clone()), Name::from(
&format!("safe mark of {} ({})", storage.name, self.storage.len())),
loc.clone(),
ptrt.tags.clone());
self.write(to, Value::Address(temp_ptr), loc);
}
return;
}
let def = self.defs.get(&totyp.name).cloned();
match def {
Some(ast::Def::Struct{fields,..}) => {
let mut value = HashMap::new();
for field in fields.iter() {
let temp_ptr = self.local(Some(field.typed.clone()), Name::from(
&format!("struct member {}.{} {}", totyp.name, field.name, self.storage.len())),
loc.clone(),
Tags::new());
self.initialize(temp_ptr, loc, true);
value.insert(field.name.clone(), temp_ptr);
if let Some(mut a) = field.array.clone() {
if let Some(a) = &mut a {
match self.check_expr(a) {
Err(_) => (),
Ok(a_ptr) => {
match &self.storage[a_ptr].value {
Value::Literal(a) => {
if let Ok(a) = a.parse::<u64>() {
let mut ar = Vec::new();
for _ in 0..a {
let temp_ptr2 = self.local(Some(field.typed.clone()), Name::from(
&format!("deep init array {}", self.storage.len())),
loc.clone(),
Tags::new());
ar.push(temp_ptr2);
}
self.write(temp_ptr, Value::Array(ar), loc);
}
},
_ => (),
}
}
}
}
}
}
self.write(to, Value::Struct(value), loc);
},
_ => {
if deep {
self.write(to, Value::Untrackable("deep init from safe assertion".to_string()), loc);
}
},
};
}
}
fn copy(&mut self, from: Address, to: Address, used_here: &ast::Location) -> Result<(), Error> {
emit_debug("copy",&[(used_here.clone(), format!("this will copy ({}|{})={} over ({}|{})={}",
from, self.storage[from].name, self.storage[from].value,
to, self.storage[to].name, self.storage[to].value,
))]);
let from = &mut self.storage[from].clone();
if from.tags.contains_key("unsafe") {
return Err(Error::new(format!("illegal read access to unsafe storage '{}'", from.name), vec![
(used_here.clone(), "used here".to_string()),
(from.stored_here.clone(), "suggestion: add a runtime check for this value and mark it safe".to_string()),
]));
}
match &from.value {
Value::Void => {
return Err(Error::new(format!("void is not a value: '{}'", from.name), vec![
(used_here.clone(), "used here".to_string())
]));
}
Value::Uninitialized => {
return Err(Error::new(format!("unsafe read access to possibly uninitialized local '{}'", from.name), vec![
(used_here.clone(), "used here".to_string())
]));
}
Value::Moved{ref moved_here} => {
return Err(Error::new(format!("illegal read access of moved value '{}'", from.name), vec![
(used_here.clone(), "use of moved value".to_string()),
(moved_here.clone(), "was moved here".to_string())
]));
}
Value::Function{..} => {
//return Err(Error::new(format!("function cannot be copied '{}'", from.name), vec![
// (used_here.clone(), "maybe you wanted to take the address instead".to_string()),
//]));
},
Value::Struct(_) => {
match self.storage[to].value.clone() {
Value::Array(_) => {
return Err(Error::new(format!("copying struct over array"), vec![
(used_here.clone(), "confusing assignment".to_string()),
]));
},
_ => (),
}
},
Value::Array(ref af) => {
match self.storage[to].value.clone() {
Value::Struct(fields) => {
for (i,f) in fields.keys().enumerate() {
if i < af.len() {
self.copy(af[i], fields[f], used_here)?;
} else {
self.write(fields[f], Value::Literal(String::from("0")), used_here);
}
}
return Ok(());
},
Value::Array(fields) => {
for (i,f) in fields.iter().enumerate() {
if i < af.len() {
self.copy(af[i], *f, used_here)?;
}
}
return Ok(());
}
_ => (),
}
}
_ => {
}
}
self.write(to, from.value.clone(), used_here);
Ok(())
}
fn deref(&mut self, address: usize, used_here: &ast::Location) -> Result<Address, Error> {
let storage = &self.storage[address];
if storage.tags.contains_key("unsafe") {
return Err(Error::new(format!("illegal deref of unsafe pointer '{}'", storage.name), vec![
(used_here.clone(), "used here".to_string()),
(storage.stored_here.clone(), "suggestion: add a runtime check for this storage and mark it safe".to_string()),
]));
}
match &storage.value {
Value::Address(to) => {
return Ok(*to);
}
Value::Uninitialized => {
return Err(Error::new(format!("unsafe deref of possibly uninitialized local '{}'", storage.name), vec![
(used_here.clone(), "used here".to_string())
]));
}
Value::Moved{moved_here} => {
return Err(Error::new(format!("illegal deref of moved value '{}'", storage.name), vec![
(used_here.clone(), "use of moved value".to_string()),
(moved_here.clone(), "was moved here".to_string())
]));
}
Value::Dropped{stored_here, dropped_here} => {
return Err(Error::new(format!("illegal deref of dropped value '{}'", storage.name), vec![
(used_here.clone(), "used here".to_string()),
(stored_here.clone(), "points at this storage location".to_string()),
(dropped_here.clone(), "which was dropped here".to_string()),
]));
},
x => {
return Err(Error::new(format!("illegal deref of {} '{}'", x, storage.name), vec![
(used_here.clone(), "used here".to_string())
]));
}
}
}
fn check_call_arg(&mut self, stack: &ast::NamedArg, callsite: &mut ast::Expression) -> Result<(), Error> {
let mut callsite_ptr = self.check_expr(callsite)?;
let mut callsite_storage = &mut self.storage[callsite_ptr];
let mut it = stack.typed.ptr.iter().rev().enumerate();
loop {
let (i, stack_ptr) = match it.next() {
Some(v) => v,
None => break,
};
// stack_ptr is now the last pointer in the functions stack argument
// i.e it is "mut*" if the arg was "int ** mut* a"
// we dig deeper into the callsite as we move right to left
callsite_ptr = match &callsite_storage.value {
Value::Address(to) => {
*to
},
Value::Untrackable(s) => {
return Err(Error::Untrackable(s.clone()));
}
Value::Struct{..} => {
return Err(Error::new("complex object passed by value".to_string(), vec![
(callsite.loc().clone(), "used as value here".to_string()),
(callsite_storage.stored_here.clone(), "but this expression is complex".to_string()),
]));
}
Value::Array{..} => {
// C has this weird semantic that passing an array by value will make it a pointer
callsite_ptr
},
Value::Void => {
return Err(Error::new("void used as value".to_string(), vec![
(callsite.loc().clone(), "used as value here".to_string()),
(callsite_storage.stored_here.clone(), "but this expression is void".to_string()),
]));
},
Value::Uninitialized => {
return Err(Error::new("uninitialized pointer arg passed as safe pointer".to_string(), vec![
(callsite.loc().clone(), "this pointer must be safe".to_string()),
(callsite_storage.stored_here.clone(), "but this value is possibly uninitialized".to_string()),
]));
},
Value::Dropped{stored_here, dropped_here} => {
return Err(Error::new(format!("passing dropped value '{}' as safe pointer", callsite_storage.name), vec![
(callsite.loc().clone(), "used here".to_string()),
(stored_here.clone(), "points at this storage location".to_string()),
(dropped_here.clone(), "which was dropped here".to_string()),
]));
},
Value::Moved{moved_here} => {
return Err(Error::new(format!("passing moved value '{}' as safe pointer", callsite_storage.name), vec![
(callsite.loc().clone(), "use of moved value".to_string()),
(moved_here.clone(), "was moved here".to_string())
]));
},
Value::Function{..} => {
return Err(Error::new(format!("ICE: trying to pass function as pointer"), vec![
(callsite.loc().clone(), "cannot determine lifetime of expression".to_string())
]));
},
Value::Literal(val) => {
if callsite_storage.tags.contains("safe") {
return Ok(());
}
match it.next() {
Some((i, stack_ptr)) => {
if stack_ptr.tags.contains("unsafe") {
return Ok(());
}
},
None => {
if stack.tags.contains("unsafe") {
return Ok(());
}
},
};
// string literal
if val.contains("\"") {
return Err(Error::Untrackable("string literals are weird".to_string()));
}
if let Some(change) = &callsite_storage.changed_here {
return Err(Error::new(format!("incompatible argument"), vec![
(callsite.loc().clone(), "this expression has a different pointer depth".to_string()),
(change.clone(), format!("{} might not be a safe pointer", val)),
(stack.typed.loc.clone(), format!("expected at depth {} here", i)),
]));
} else {
return Err(Error::new(format!("incompatible argument"), vec![
(callsite.loc().clone(), "this expression has a different pointer depth".to_string()),
(stack.typed.loc.clone(), format!("expected at depth {} here", i)),
]));
}
}
};
callsite_storage = &mut self.storage[callsite_ptr];
if stack_ptr.tags.contains_key("mutable") && !callsite_storage.tags.contains_key("mutable") {
return Err(Error::new("const pointer cannot be used as mut pointer in function call".to_string(), vec![
(callsite.loc().clone(), "this expression must yield a mutable pointer".to_string()),
(callsite_storage.stored_here.clone(), "suggestion: change this declaration to mutable".to_string()),
]));
}
if let Some(vals) = stack_ptr.tags.get("require") {
let mut missing = vals.clone();
if let Some(v) = callsite_storage.tags.get("marked") {
for (v,_) in v {
missing.remove(v);
}
}
for (val,_) in missing {
return Err(Error::new(format!("missing required type state '{}'", val), vec![
(callsite.loc().clone(), format!("argument here must be '{}'", val))
]));
}
}
if let Some(v) = stack_ptr.tags.get("unset") {
for (v,_) in v {
callsite_storage.tags.remove("marked", Some(v));
}
}
if let Some(vals) = callsite_storage.tags.get("marked") {
let mut missing = vals.clone();
if let Some(v) = stack_ptr.tags.get("require") {
for (v,_) in v {
missing.remove(v);
}
}
if let Some(v) = stack_ptr.tags.get("allow") {
for (v,_) in v {
missing.remove(v);
}
}
for (val,vloc) in missing {
return Err(Error::new(format!("cannot use marked local '{}'", callsite_storage.name), vec![
(callsite.loc().clone(), format!("argument here is not allowed to be '{}'", val)),
(vloc.clone(), format!("marked '{}' here. probably must call a related function to unset", val)),
]));
}
}
if let Some(tag) = stack_ptr.tags.get("set") {
if callsite_storage.tags.contains_key("borrowed") {
let mut taint_missing = tag.clone();
if let Some(tag2) = callsite_storage.tags.get("set") {
for (value,_) in tag2 {
taint_missing.remove(value);
}
}
for missing in taint_missing {
return Err(Error::new("call would mark borrowed callsite".to_string(), vec![
(callsite.loc().clone(),
format!("this expression would mark the callsite with undeclared mark '{}'",
missing.0)),
(callsite_storage.stored_here.clone(),
format!("try adding a set<{}> tag here",
missing.0)),
]));
}
}
for (val,_) in tag {
callsite_storage.tags.insert(
"marked".to_string(),
val.clone(),
callsite.loc().clone(),
);
}
}
if let Some(tag) = stack_ptr.tags.get("move") {
if callsite_storage.tags.contains_key("stack") {
return Err(Error::new("cannot move stack".to_string(), vec![
(callsite.loc().clone(),
format!("this expression would move '{}' out of scope, which is on the stack", callsite_storage.name)),
]));
}
if let Some(_) = callsite_storage.tags.get("borrowed") {
return Err(Error::new("cannot move borrowed pointer".to_string(), vec![
(callsite.loc().clone(),
format!("this expression would move '{}' out of scope", callsite_storage.name)),
(tag.iter().next().unwrap().1.clone(), "required because this call argument is move".to_string()),
(callsite_storage.stored_here.clone(), "try changing this declaration to move".to_string()),
]));
}
//TODO this will only move the rightmost value
callsite_storage.value = Value::Moved{
moved_here: callsite.loc().clone(),
};
return Ok(());
}
if stack_ptr.tags.contains_key("unsafe") {
return Ok(());
}
if !stack_ptr.tags.contains_key("unsafe") && callsite_storage.tags.contains_key("unsafe") {
return Err(Error::new("passing unsafe pointer to safe function call".to_string(), vec![
(callsite.loc().clone(), "this expression must be safe".to_string()),
(callsite_storage.stored_here.clone(), "suggestion: add a runtime check for this value and mark it safe".to_string()),
]));
}
}
/* this is broken. it should check rightmost pointer.
* and kind of useless because we assume all fn arguments are unsafe
match &callsite_storage.value {
Value::Uninitialized => {
return Err(Error::new(format!("uninitialized var {} passed as safe arg", callsite_storage.name), vec![
(callsite.loc().clone(), "this arg must be safe".to_string()),
(callsite_storage.stored_here.clone(), "but this value is uninitialized".to_string()),
]));
},
Value::Dropped{stored_here, dropped_here} => {
return Err(Error::new(format!("passing dropped value '{}' as safe pointer", callsite_storage.name), vec![
(callsite.loc().clone(),"used here".to_string()),
(stored_here.clone(), "points at this storage location".to_string()),
(dropped_here.clone(), "which was dropped here".to_string()),
]));
},
Value::Moved{moved_here} => {
return Err(Error::new(format!("passing moved value '{}' as safe pointer", callsite_storage.name), vec![
(callsite.loc().clone(), "use of moved value".to_string()),
(moved_here.clone(), "was moved here".to_string()),
]));
},
_ => (),
};
*/
Ok(())
}
fn check_expr(&mut self, expr: &mut ast::Expression) -> Result<Address, Error> {
let exprloc = expr.loc().clone();
match expr {
ast::Expression::Name(name) => {
if name.name.is_absolute() && name.name.0[1] == "ext" {
return Err(Error::Untrackable(format!("ext name {}", name.name)));
}
self.check_name(&name.name, &name.loc)
}
ast::Expression::MemberAccess {loc, lhs, rhs, op, ..} => {
let mut ptr = self.check_expr(lhs)?;
if op == "->" {
ptr = self.deref(ptr, &exprloc)?;
}
let mut storage = self.storage.get(ptr).unwrap().clone();
if storage.tags.contains_key("unsafe") {
return Err(Error::new(format!("illegal read access to unsafe storage '{}'", storage.name), vec![
(loc.clone(), "used here".to_string()),
(storage.stored_here.clone(), "suggestion: add a runtime check for this value and mark it safe".to_string()),
]));
}
let value = match &mut storage.value {
Value::Struct(fields) => fields,
Value::Untrackable(s) => {
return Err(Error::Untrackable(s.clone()));
},
Value::Uninitialized => {
return Err(Error::new(format!("unsafe member access to possibly uninitialized pointer '{}'", storage.name), vec![
(loc.clone(), "used here".to_string()),
]));
},
Value::Address(_) => {
return Err(Error::new(format!("member access to non struct pointer {}", storage.name), vec![
(loc.clone(), "this is not a struct".to_string()),
]));
},
o => {
return Err(Error::new(format!("illegal member access to {} {}", o, storage.name), vec![
(loc.clone(), "used here".to_string()),
]));
}
};
let typ = match &storage.typ {
None => {
return Err(Error::new("unknown type cannot be accessed".to_string(), vec![
(lhs.loc().clone(), format!("type of '{}' is not known", storage.name)),
]));
},
Some(t) => t,
};
if typ.name.0[1] == "ext" {
return Err(Error::Untrackable(format!("ext name {}", typ.name)));
}
let def = self.defs.get(&typ.name).cloned();
let fields = match def {
Some(ast::Def::Struct{fields,..}) => {
fields
},
_ => {
return Err(Error::new(format!("'{}' is not a struct", typ.name), vec![
(lhs.loc().clone(), format!("'{}' is not accessible as struct", typ.name))
]));
},
};
for field in &fields {
if &field.name == rhs {
if !value.contains_key(&field.name) {
let m_ptr = self.storage.len();
self.storage.push(Storage{
typ: Some(field.typed.clone()),
name: Name::from(
&format!("member access of {}@{}->{}", storage.name, ptr, field.name)
),
stored_here: field.loc.clone(),
value: Value::Uninitialized,
tags: field.tags.clone(),
changed_here: None,
});
value.insert(field.name.clone(), m_ptr);
}
return Ok(value[&field.name]);
}
}
return Err(Error::new(format!("struct '{}' has no member named '{}'", typ.name, rhs), vec![
(loc.clone(), format!("unresolveable member access of '{}' here", storage.name))
]));
}
ast::Expression::ArrayAccess {lhs, rhs, ..} => {
self.check_bounds(lhs, rhs, true)?;
let ptr_of_holder = self.check_expr(lhs)?;
let index_ptr = self.check_expr(rhs)?;
let index = match &self.storage[index_ptr].value {
Value::Literal(v) => {
if let Ok(v) = v.parse::<u64>() {
v.clone()
} else {
return Err(Error::Untrackable("array access with non static index".to_string()));
}
},
_ => {
return Err(Error::Untrackable("array access with non static index".to_string()));
}
};
match &self.storage[ptr_of_holder].value {
Value::Array(v) => {
Ok(*v.get(index as usize).expect("out of bound access should have been cought by check_bounds"))
},
Value::Address(to) => {
Ok(*to)
}
o => {
Err(Error::Untrackable(format!("index into {}", o)))
}
}
}
ast::Expression::Literal { loc, v } => {
let temp_ptr = self.local(None, Name::from(
&format!("literal {}", self.storage.len())),
loc.clone(),
Tags::new());
self.write(temp_ptr, Value::Literal(v.clone()), &expr.loc());
Ok(temp_ptr)
},
ast::Expression::Call { name, args: callargs, loc: callloc, .. } => {
match name.as_ref() {
&ast::Expression::Name(ref t) if t.name.0[0] == "len" => {
if callargs.len() != 1 {
return Err(Error::new("call argument count mismatch".to_string(), vec![
(name.loc().clone(), format!("builtin len() needs 1 argument, but you passed {}", callargs.len()))
]));
}
let to = self.check_expr(&mut callargs[0])?;
match self.storage[to].value.clone() {
Value::Array(s) => {
let temp_ptr = self.local(None, Name::from(
&format!("literal len of {} ({})", self.storage[to].name, self.storage.len())),
callloc.clone(),
Tags::new());
let lit = format!("{}", s.len());
*expr = ast::Expression::Literal{
loc: callloc.clone(),
v: lit.clone(),
};
self.write(temp_ptr, Value::Literal(lit.clone()), &expr.loc());
return Ok(temp_ptr);
},
o => {
return Err(Error::new(format!("len of {} {} is not known at compile time", o, self.storage[to].name), vec![
(callloc.clone(), "len on unsized object not valid here".to_string())
]));
}
}
}
_ => ()
};
let name_ptr = self.check_expr(name)?;
let (fname, ret, args, vararg) = match self.storage[name_ptr].value.clone() {
Value::Function{name: fname, ret, args, vararg} => {
(fname, ret, args, vararg)
}
Value::Untrackable(s) => {
return Err(Error::Untrackable(s.clone()));
},
_ => {
return Err(Error::new("call argument count mismatch".to_string(), vec![
(name.loc().clone(), format!("builtin len() needs 1 argument, but you passed {}", callargs.len()))
]));
}
};
debug!(" checking function call {}", fname);
let mut callargs_org = std::mem::replace(callargs, Vec::new());
// generated arguments
for i in 0..args.len() {
if let Some(cs) = args[i].tags.get("callsite_macro") {
let (v, loc) = cs.iter().next().unwrap();
let genarg = Box::new(ast::Expression::Literal{
loc: loc.clone(),
v: v.clone(),
});
callargs.push(genarg);
} else if let Some(_) = args[i].tags.get("tail") {
let mut prev = callargs.get_mut(i-1).expect("ICE: tail tag without previous arg");
let callptr = self.check_expr(&mut prev)?;
*prev = Box::new(ast::Expression::Cast {
into: args[i-1].typed.clone(),
expr: prev.clone(),
loc: args[i].loc.clone(),
});
match &self.storage[callptr].typ {
None => {
return Err(Error::new(format!("type of {} not known at compile time", self.storage[callptr].name), vec![
(name.loc().clone(), format!("used here in tail binding")),
]));
},
Some(t) => {
match &t.tail {
ast::Tail::Dynamic | ast::Tail::None | ast::Tail::Bind(_,_) => {
return Err(Error::new(format!("tail size of {} not known at compile time",
self.storage[callptr].name), vec![
(name.loc().clone(), format!("used here in tail binding")),
]));
},
ast::Tail::Static(v,loc) => {
let genarg = Box::new(ast::Expression::Literal{
loc: loc.clone(),
v: format!("{}", v),
});
callargs.push(genarg);
}
}
}
}
} else {
if callargs_org.len() > 0 {
callargs.push(callargs_org.remove(0));
}
}
}
callargs.extend(callargs_org);
if (!vararg && args.len() != callargs.len()) | (vararg && args.len() > callargs.len()) {
let mut es = vec![(name.loc().clone(), format!("function needs {} arguments, but you passed {}", args.len(),callargs.len() ))];
if let Some(typed) = &self.storage[name_ptr].typ {
es.push((typed.loc.clone(), format!("declared here")));
} else {
es.push((self.storage[name_ptr].stored_here.clone(),
format!("declaration tracking interrupted here in {}",
self.storage[name_ptr].name)));
}
return Err(Error::new("call argument count mismatch".to_string(), es));
}
let mut argpos: HashMap<String, usize> = HashMap::new();
for i in 0..args.len() {
argpos.insert(args[i].name.clone(),i);
// check value of expression, which will be copied into the functions scope
self.check_call_arg(&args[i], &mut callargs[i])?;
}
//double check callargs because with varargs, there might be more
for arg in callargs.iter_mut() {
let a = self.check_expr(arg)?;
}
//boundary checks
for i in 0..args.len() {
if let Some(bounds) = args[i].tags.get("bound") {
for (bound, loc) in bounds {
let bound_by = match argpos.get(bound) {
None => {
emit_error("bound to undeclared argument", &[
(loc.clone(), format!("{} is not an argument", bound))
]);
ABORT.store(true, Ordering::Relaxed);
continue;
}
Some(v) => *v,
};
self.check_bounds(&mut callargs[bound_by].clone(), &mut callargs[i], false)?;
}
}
}
return match ret {
Some(ret) => {
let (return_scope_ptr, ret_typ) = ret;
Ok(return_scope_ptr)
}
None => {
let temp_ptr = self.local(None, Name::from(
&format!("void function call return {} at {:?}", fname, exprloc.span.start_pos().line_col())),
exprloc.clone(),
Tags::new());
self.write(temp_ptr, Value::Void, &expr.loc());
Ok(temp_ptr)
},
}
}
ast::Expression::Infix { lhs, rhs, loc, op, ..} => {
let mut lhs_val = None;
let lhs = self.check_expr(lhs)?;
let lhs = match & self.storage[lhs].value {