rsleigh 0.4.2

SLEIGH (.slaspec) parser and Rust decoder/P-code emitter codegen — Ghidra-compatible disassembly in pure Rust
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
use std::cell::RefCell;
use std::ops::Range;

use crate::execution::{DynamicValueType, ExprVarnodeDynamic};
use crate::semantic::disassembly;
use crate::semantic::execution::{
    BlockId, Build, RefTable, RefTokenField, ReferencedValue, VariableId,
};
use crate::semantic::inner::execution::{Block, ExprBitrange, ExprNumber, ExprTokenField, Unary};
use crate::semantic::inner::pattern::Pattern;
use crate::semantic::inner::pcode_macro::PcodeMacro;
use crate::semantic::inner::{GlobalScope, Sleigh};
use crate::semantic::{InstNext, InstStart, SpaceId, TableId};
use crate::{
    syntax, AttachVarnodeId, BitrangeId, ContextId, Number, NumberNonZeroUnsigned, NumberUnsigned,
    Span, TokenFieldId, VarSizeError, VarnodeId,
};

use super::{
    Assignment, AssignmentOp, AssignmentWrite, AssignmentWriteVariable, BranchCall, CpuBranch,
    Execution, ExecutionError, Export, Expr, ExprCPool, ExprDisVar, ExprElement, ExprIntDynamic,
    ExprNew, ExprUnaryOp, ExprValue, FieldSize, LocalGoto, MacroParamAssignment, MemoryLocation,
    Reference, Statement, TableExportType, UserCall,
};

#[derive(Clone, Debug)]
pub enum ReadScope {
    TokenField(TokenFieldId),
    InstStart,
    InstNext,
    Varnode(VarnodeId),
    Context(ContextId),
    Bitrange(BitrangeId),
    Table(TableId),
    DisVar(disassembly::VariableId),
    ExeVar(VariableId),
}

#[derive(Clone, Debug)]
pub(crate) enum WriteValue {
    Varnode(VarnodeId),
    Bitrange(BitrangeId),
    DynVarnode {
        value_id: DynamicValueType,
        attach_id: AttachVarnodeId,
    },
    // TODO Context translated into varnode
    TableExport(TableId),
    Local {
        id: VariableId,
        creation: bool,
    },
}

pub trait ExecutionBuilder {
    fn sleigh(&self) -> &Sleigh;
    fn pattern(&self) -> &Pattern;
    fn execution(&self) -> &Execution;
    fn execution_mut(&mut self) -> &mut Execution;
    fn read_scope(&mut self, name: &str, src: &Span) -> Result<ReadScope, Box<ExecutionError>>;
    fn write_scope(&mut self, name: &str, src: &Span) -> Result<WriteValue, Box<ExecutionError>>;
    fn table(&self, name: &str, src: &Span) -> Result<TableId, Box<ExecutionError>> {
        self.sleigh()
            .get_global(name)
            .ok_or_else(|| Box::new(ExecutionError::MissingRef(src.clone())))?
            .table()
            .ok_or_else(|| Box::new(ExecutionError::InvalidRef(src.clone())))
    }
    fn space(&self, name: &str, src: &Span) -> Result<SpaceId, Box<ExecutionError>> {
        self.sleigh()
            .get_global(name)
            .ok_or_else(|| Box::new(ExecutionError::MissingRef(src.clone())))?
            .space()
            .ok_or_else(|| Box::new(ExecutionError::InvalidRef(src.clone())))
    }
    fn current_block(&self) -> BlockId;
    //TODO rename this
    fn inner_set_curent_block(&mut self, block: BlockId);
    fn set_current_block(&mut self, block: BlockId) {
        let current_id = self.current_block();
        if let Some(old) = self
            .execution_mut()
            .block_mut(current_id)
            .next
            .replace(block)
        {
            panic!("multiple next, old: {old:?}")
        }
        self.inner_set_curent_block(block)
    }
    fn create_variable(
        &mut self,
        name: &str,
        src: &Span,
        size: Option<FieldSize>,
        explicit: bool,
    ) -> Result<VariableId, Box<ExecutionError>> {
        let var =
            self.execution_mut()
                .create_variable(name.to_owned(), src.clone(), size, explicit)?;
        // TODO only create a declare if explicit?
        self.insert_statement(Statement::Declare(var));
        Ok(var)
    }
    fn insert_statement(&mut self, statement: Statement) {
        let current_block_id = self.current_block();
        self.execution_mut()
            .block_mut(current_block_id)
            .statements
            .push(RefCell::new(statement));
    }
    fn extend(
        &mut self,
        input: syntax::block::execution::Execution,
    ) -> Result<(), Box<ExecutionError>> {
        //start by creating all the blocks
        for statement in input.statements.iter() {
            if let syntax::block::execution::Statement::Label(label) = statement {
                self.execution_mut()
                    .new_block(label.name.to_owned())
                    .ok_or_else(|| Box::new(ExecutionError::DuplicatedLabel(label.src.clone())))?;
            }
        }

        //convert all the other statements
        for statement in input.statements.into_iter() {
            match statement {
                syntax::block::execution::Statement::Label(x) => {
                    //finding label means changing block
                    let new_current_block = self.execution().block_by_name(&x.name).unwrap();
                    self.set_current_block(new_current_block);
                }
                syntax::block::execution::Statement::Delayslot(x) => {
                    self.insert_statement(Statement::Delayslot(x.0));
                }
                syntax::block::execution::Statement::Export(x) => {
                    let export = self.new_export(x)?;
                    self.insert_statement(Statement::Export(export));
                }
                syntax::block::execution::Statement::Build(x) => {
                    let build = self.new_build(x)?;
                    self.insert_statement(Statement::Build(build));
                }
                syntax::block::execution::Statement::Branch(x) => {
                    let label =
                        matches!(x.dst, syntax::block::execution::branch::BranchDst::Label(_));
                    if label {
                        let goto = self.new_local_goto(x)?;
                        self.insert_statement(Statement::LocalGoto(goto));
                    } else {
                        let branch = self.new_cpu_branch(x)?;
                        self.insert_statement(Statement::CpuBranch(branch));
                    }
                }
                syntax::block::execution::Statement::Call(x) => {
                    self.new_call_statement(x)?;
                }
                syntax::block::execution::Statement::Declare(x) => {
                    let size = x
                        .size
                        .map(|size| {
                            NumberNonZeroUnsigned::new(size.value)
                                .map(FieldSize::new_bytes)
                                .ok_or_else(|| Box::new(ExecutionError::InvalidVarLen(size.src)))
                        })
                        .transpose()?;
                    self.create_variable(&x.name, &x.src, size, true)?;
                }
                syntax::block::execution::Statement::Assignment(x) => {
                    let assignment = self.new_assignment(x)?;
                    self.insert_statement(assignment);
                }
                syntax::block::execution::Statement::MemWrite(x) => {
                    let assignment = self.new_mem_write(x)?;
                    self.insert_statement(Statement::Assignment(assignment));
                }
            }
        }
        //update blocks based on the last statement
        for block in &mut self.execution_mut().blocks {
            let Some(last_statement) = block.statements.last() else {
                continue;
            };
            let next = match &*last_statement.borrow() {
                //this block ends with unconditional local_jmp, this replace the
                //next block
                Statement::LocalGoto(LocalGoto { cond: None, dst }) => {
                    //remove the goto, the next block will tha it's place
                    Some(Some(*dst))
                }
                //If the last is export or unconditional cpu branch,
                //this becames an return block, so next is None
                Statement::Export(_) | Statement::CpuBranch(CpuBranch { cond: None, .. }) => {
                    Some(None)
                }
                _ => None,
            };
            if let Some(next_block) = next {
                block.next = next_block;
                if let Some(_block_id) = next_block {
                    block.statements.pop();
                }
            }
        }
        //find the return type for this execution
        let return_type = {
            let execution = self.execution();
            let mut iter = execution
                .blocks
                .iter()
                //only blocks with no next block can export
                .filter(|block| block.next.is_none())
                .filter_map(|block| block.statements.last())
                //if the last statement is export, convert to export size
                .filter_map(|statement| match &*statement.borrow() {
                    Statement::Export(exp) => {
                        Some(exp.return_type(self.sleigh(), self.execution()))
                    }
                    _ => None,
                });
            //FUTURE: replace this with try_reduce:
            //`.try_reduce(|acc, item| acc.combine(item));`
            match iter.next() {
                Some(first) => iter
                    .try_fold(first, |acc, item| acc.combine(item))
                    .map(Some),
                None => Some(None),
            }
        };
        self.execution_mut().return_value = match return_type {
            //short circuit, AKA invalid combination of return types
            None => return Err(Box::new(ExecutionError::InvalidExport)),
            //there are no returns
            Some(None) => TableExportType::None,
            //some return type
            Some(Some(ret)) => ret,
        };
        Ok(())
    }

    fn new_build(
        &mut self,
        input: syntax::block::execution::Build,
    ) -> Result<Build, Box<ExecutionError>> {
        let table_id = self.table(&input.table_name, &input.src)?;
        Ok(Build {
            table: table_id,
            location: input.src,
        })
    }
    fn new_export(
        &mut self,
        input: syntax::block::execution::export::Export,
    ) -> Result<Export, Box<ExecutionError>> {
        use syntax::block::execution::export::Export as RawExport;
        match input {
            RawExport::Value(value) => {
                let value = self.new_expr(value)?;
                Export::new_value(self.sleigh(), self.pattern(), self.execution(), value)
            }
            RawExport::Reference { space, addr } => {
                let addr = self.new_expr(addr)?;
                let deref = self.new_addr_derefence(&space)?;
                Export::new_reference(self.sleigh(), self.pattern(), self.execution(), addr, deref)
            }
            RawExport::Const { size, value, src } => {
                let read_scope = self.read_scope(&value, &src)?;
                Export::new_const(
                    self.sleigh(),
                    self.execution(),
                    self.pattern(),
                    read_scope,
                    size,
                    src,
                )
            }
        }
    }
    fn new_call_statement(
        &mut self,
        input: syntax::block::execution::UserCall,
    ) -> Result<(), Box<ExecutionError>> {
        let params = input
            .params
            .into_iter()
            .map(|param| self.new_expr(param))
            .collect::<Result<Vec<_>, _>>()?;
        let global = self
            .sleigh()
            .get_global(&input.name)
            .ok_or_else(|| ExecutionError::MissingRef(input.src.clone()))?;
        match global {
            GlobalScope::UserFunction(x) => {
                self.insert_statement(Statement::UserCall(UserCall::new(
                    self.sleigh(),
                    self.execution(),
                    params,
                    x,
                    input.src,
                )));
                Ok(())
            }
            GlobalScope::PcodeMacro(macro_id) => {
                // TODO create an alias system, so variable and block names
                // don't colide
                // TODO make pcode_macro use RefCell to avoid this clone
                let pmacro = self.sleigh().pcode_macro(macro_id).clone();

                // if the macro have more then one block, split blocks
                let (block_offset, next_block) = if pmacro.execution.blocks.len() == 1 {
                    (None, None)
                } else {
                    let current_block_name =
                        self.execution().block(self.current_block()).name.to_owned();
                    // block to go after the pmacro
                    let next_block = BlockId(self.execution().blocks.len());
                    self.execution_mut()
                        .blocks
                        .push(Block::new_empty(Some(current_block_name.unwrap_or_else(
                            || format!("{}_after", &pmacro.name).into_boxed_str(),
                        ))));

                    // mapping macro -> execution blocks
                    let block_offset = self.execution().blocks.len();
                    // create all the macro blocks
                    self.execution_mut()
                        .blocks
                        .extend(pmacro.execution.blocks.iter().map(|b| {
                            Block::new_empty(Some(b.name.clone().unwrap_or_else(|| {
                                format!("{}_entry", &pmacro.name).into_boxed_str()
                            })))
                        }));
                    (Some(block_offset), Some(next_block))
                };

                // mapping variable -> execution variable
                let variables_map = self.map_variables(&pmacro, &params);

                // assign the values to the params
                for (param_id, param) in params.iter().enumerate() {
                    let old_var_id = pmacro.params[param_id];
                    let new_var = &variables_map[old_var_id.0];
                    match new_var {
                        VariableAlias::Parameter(variable_id) => {
                            self.insert_statement(Statement::MacroParamAssignment(
                                MacroParamAssignment::new(*variable_id, param.clone()),
                            ))
                        }
                        VariableAlias::SubVarnode(_, _)
                        | VariableAlias::Alias(_)
                        | VariableAlias::NewVariable(_) => {}
                    }
                }

                // populate the blocks
                for (i, block) in pmacro.execution.blocks.as_slice().iter().enumerate() {
                    if let Some(block_offset) = block_offset {
                        let block_id = BlockId(i + block_offset);
                        self.set_current_block(block_id);
                    }

                    for statement in block.statements.iter() {
                        let statement = statement.borrow();
                        let new_statement = match &*statement {
                            Statement::LocalGoto(goto) => {
                                let block_id = BlockId(goto.dst.0 + block_offset.unwrap());
                                let cond = goto
                                    .cond
                                    .as_ref()
                                    .map(|cond| translate_expr(cond, &variables_map));
                                Statement::LocalGoto(LocalGoto {
                                    cond,
                                    dst: block_id,
                                })
                            }
                            Statement::CpuBranch(x) => Statement::CpuBranch(CpuBranch {
                                cond: x.cond.as_ref().map(|x| translate_expr(x, &variables_map)),
                                dst: translate_expr(&x.dst, &variables_map),
                                ..x.clone()
                            }),
                            Statement::UserCall(x) => Statement::UserCall(UserCall {
                                params: x
                                    .params
                                    .iter()
                                    .map(|x| translate_expr(x, &variables_map))
                                    .collect(),
                                ..x.clone()
                            }),
                            Statement::Assignment(x) => {
                                let var = translate_write(
                                    self.sleigh(),
                                    &x.var,
                                    &x.location,
                                    &variables_map,
                                )?;
                                Statement::Assignment(Assignment {
                                    right: translate_expr(&x.right, &variables_map),
                                    var,
                                    ..x.clone()
                                })
                            }
                            Statement::MacroParamAssignment(x) => {
                                let var = match variables_map[x.var.0] {
                                    // TODO error, can't assign a value to anything other then a variable
                                    VariableAlias::SubVarnode(_, _)
                                    | VariableAlias::Parameter(_)
                                    | VariableAlias::Alias(_) => panic!(),
                                    VariableAlias::NewVariable(id) => id,
                                };

                                Statement::MacroParamAssignment(MacroParamAssignment::new(
                                    var,
                                    translate_expr(&x.right, &variables_map),
                                ))
                            }
                            Statement::Declare(old_id) => match variables_map[old_id.0].clone() {
                                VariableAlias::SubVarnode(_, _)
                                | VariableAlias::Parameter(_)
                                | VariableAlias::Alias(_) => panic!(),
                                VariableAlias::NewVariable(id) => Statement::Declare(id),
                            },
                            x @ Statement::Delayslot(_) => x.clone(),
                            Statement::Export(_) | Statement::Build(_) => {
                                unreachable!()
                            }
                        };
                        self.insert_statement(new_statement);
                    }
                }
                // next block after the call is the previous block
                if let Some(next_block) = next_block {
                    self.set_current_block(next_block);
                }
                Ok(())
            }
            _ => Err(Box::new(ExecutionError::InvalidRef(input.src))),
        }
    }
    fn new_call_expr(
        &mut self,
        input: syntax::block::execution::UserCall,
    ) -> Result<ExprElement, Box<ExecutionError>> {
        let params = input
            .params
            .into_iter()
            .map(|param| self.new_expr(param))
            .collect::<Result<Vec<_>, _>>()?;
        let global = self
            .sleigh()
            .get_global(&input.name)
            .ok_or_else(|| ExecutionError::MissingRef(input.src.clone()))?;
        match global {
            GlobalScope::UserFunction(function) => Ok(ExprElement::UserCall(UserCall::new(
                self.sleigh(),
                self.execution(),
                params,
                function,
                input.src,
            ))),
            GlobalScope::PcodeMacro(x) => {
                let pmacro = self.sleigh().pcode_macro(x);
                todo!("user defined {} exports?", &pmacro.name)
            }
            _ => Err(Box::new(ExecutionError::InvalidRef(input.src))),
        }
    }

    fn new_assignment(
        &mut self,
        input: syntax::block::execution::assignment::Assignment,
    ) -> Result<Statement, Box<ExecutionError>> {
        let right = self.new_expr(input.right)?;
        let var = self.write_scope(&input.ident, &input.src).ok();
        match (var, input.local) {
            //variable don't exists, create it
            (None, local) => {
                //the var size is defined if ByteRangeLsb is present
                //add the var creation statement
                let size = match &input.op {
                    Some(syntax::block::execution::assignment::OpLeft::ByteRangeLsb(x)) => {
                        Some(FieldSize::new_bytes(x.value.try_into().unwrap()))
                    }
                    Some(_) => todo!("create var with this op?"),
                    None => None,
                };
                let new_var_id = self.create_variable(&input.ident, &input.src, size, local)?;
                Ok(Statement::Assignment(Assignment::new(
                    input.src.clone(),
                    AssignmentWrite::Variable {
                        value: AssignmentWriteVariable::Local {
                            id: new_var_id,
                            creation: local,
                        },
                        op: None,
                    },
                    input.src,
                    right,
                )))
            }
            //variable exists, with local is error
            (Some(_), true) => Err(Box::new(ExecutionError::InvalidVarDeclare(input.src))),
            //Assign to varnode
            (Some(WriteValue::Varnode(var)), false) => {
                let value = AssignmentWriteVariable::Varnode(var);
                let op = input.op.map(|op| self.new_truncate(op)).transpose()?;
                let addr = AssignmentWrite::Variable { value, op };
                Ok(Statement::Assignment(Assignment::new(
                    input.src.clone(),
                    addr,
                    input.src,
                    right,
                )))
            }
            // assign to table
            (Some(WriteValue::TableExport(table_id)), false) => {
                let table = self.sleigh().table(table_id);
                let table_export = *table.export.borrow();
                // TODO can we assign to table with op?
                let op = input.op.map(|op| self.new_truncate(op)).transpose()?;
                match table_export {
                    // assignment to the table export address
                    Some(TableExportType::Reference {
                        len: _,
                        space: _,
                        also_values: _,
                    }) => Ok(Statement::Assignment(Assignment::new(
                        input.src.clone(),
                        AssignmentWrite::TableExport { table_id, op },
                        input.src,
                        right,
                    ))),
                    // TODO is this required, if so where?
                    // Write to a table that exports a value — treat as TableExport write.
                    // The table's exported varnode becomes the write destination.
                    Some(TableExportType::Const(_)) | Some(TableExportType::Value(_)) => {
                        Ok(Statement::Assignment(Assignment::new(
                            input.src.clone(),
                            AssignmentWrite::TableExport { table_id, op },
                            input.src,
                            right,
                        )))
                    }
                    // table is unimpl or simply don't export
                    None | Some(TableExportType::None) => {
                        Err(Box::new(ExecutionError::WriteInvalidTable(input.src)))
                    }
                }
            }
            //variable exists, just return it
            (
                Some(
                    var @ (WriteValue::Bitrange(_)
                    | WriteValue::DynVarnode { .. }
                    | WriteValue::Local { .. }),
                ),
                false,
            ) => {
                let op = input.op.map(|op| self.new_truncate(op)).transpose()?;
                let value = match var {
                    WriteValue::Bitrange(bit) => AssignmentWriteVariable::Bitrange(bit),
                    WriteValue::DynVarnode {
                        value_id,
                        attach_id,
                    } => AssignmentWriteVariable::DynVarnode {
                        value_id,
                        attach_id,
                    },
                    WriteValue::Local { id, creation } => {
                        AssignmentWriteVariable::Local { creation, id }
                    }
                    WriteValue::Varnode(_) | WriteValue::TableExport(_) => {
                        unreachable!()
                    }
                };
                Ok(Statement::Assignment(Assignment::new(
                    input.src.clone(),
                    AssignmentWrite::Variable { value, op },
                    input.src,
                    right,
                )))
            }
        }
    }
    fn new_mem_write(
        &mut self,
        input: syntax::block::execution::assignment::MemWrite,
    ) -> Result<Assignment, Box<ExecutionError>> {
        let mem = self.new_addr_derefence(&input.mem)?;
        let addr = self.new_expr(input.addr)?;
        let location = addr.src().clone();
        let right = self.new_expr(input.right)?;
        let var = AssignmentWrite::Memory { mem, addr };
        Ok(Assignment::new(location, var, input.src, right))
    }
    fn new_truncate(
        &self,
        input: syntax::block::execution::assignment::OpLeft,
    ) -> Result<AssignmentOp, Box<ExecutionError>> {
        use syntax::block::execution::assignment::OpLeft;
        //TODO genertic error here
        let error = Box::new(ExecutionError::BitRangeZero);
        let ass = match input {
            OpLeft::BitRange(range) => {
                let size = NumberNonZeroUnsigned::new(range.n_bits).ok_or(error)?;
                AssignmentOp::BitRange(range.lsb_bit..range.lsb_bit + size.get())
            }
            OpLeft::ByteRangeMsb(msb) => AssignmentOp::TrunkLsb {
                bytes: msb.value,
                output_size: FieldSize::default(),
            },
            OpLeft::ByteRangeLsb(lsb) => AssignmentOp::TakeLsb(lsb.value.try_into().unwrap()),
        };
        Ok(ass)
    }
    fn new_cpu_branch_dst(
        &mut self,
        input: syntax::block::execution::branch::BranchDst,
    ) -> Result<(bool, Expr), Box<ExecutionError>> {
        use syntax::block::execution::branch::BranchDst::*;
        Ok(match input {
            Label(_) => unreachable!(),
            Cpu { direct, expr } => (direct, self.new_expr(expr)?),
        })
    }
    fn new_cpu_branch(
        &mut self,
        input: syntax::block::execution::branch::Branch,
    ) -> Result<CpuBranch, Box<ExecutionError>> {
        let cond = input.cond.map(|x| self.new_expr(x)).transpose()?;
        let call = input.call;
        let (direct, dst) = self.new_cpu_branch_dst(input.dst)?;

        Ok(CpuBranch::new(
            self.sleigh(),
            self.execution(),
            cond,
            call,
            direct,
            dst,
        ))
    }
    fn new_local_goto(
        &mut self,
        input: syntax::block::execution::branch::Branch,
    ) -> Result<LocalGoto, Box<ExecutionError>> {
        let cond = input.cond.map(|x| self.new_expr(x)).transpose()?;
        if !matches!(input.call, BranchCall::Goto) {
            return Err(Box::new(ExecutionError::InvalidLocalGoto));
        }
        let dst = match input.dst {
            syntax::block::execution::branch::BranchDst::Label(x) => self
                .execution()
                .block_by_name(&x.name)
                .ok_or_else(|| Box::new(ExecutionError::MissingLabel(x.src.clone())))?,
            _ => unreachable!(),
        };
        LocalGoto::new(self.sleigh(), self.execution(), cond, dst)
    }
    fn new_expr_element(
        &mut self,
        input: syntax::block::execution::expr::ExprElement,
    ) -> Result<ExprElement, Box<ExecutionError>> {
        use syntax::block::execution::expr::ExprElement as RawExprElement;
        match input {
            RawExprElement::Value(syntax::Value::Number(src, value)) => Ok(ExprElement::Value {
                location: src,
                value: ExprValue::Int(ExprNumber::new(value)),
            }),
            RawExprElement::Value(syntax::Value::Ident(src, value)) => {
                let value = self.read_scope(&value, &src)?;
                // HACK add auto trunk if inst_*
                match value {
                    value @ (ReadScope::InstStart | ReadScope::InstNext) => {
                        let mut size = FieldSize::new_unsized()
                            .set_min_bits(1.try_into().unwrap())
                            .unwrap();
                        if let Some(addr_bytes) = self.sleigh().addr_bytes() {
                            size = size
                                .set_max_bytes(addr_bytes)
                                .unwrap()
                                .set_possible_bytes(addr_bytes)
                                .unwrap();
                        }
                        Ok(ExprElement::new_op(
                            src.clone(),
                            Unary::TrunkLsb { trunk: 0, size },
                            Expr::Value(ExprElement::Value {
                                location: src.clone(),
                                value: ExprValue::from_read_scope(self.sleigh(), value),
                            }),
                        ))
                    }
                    value => Ok(ExprElement::Value {
                        location: src,
                        value: ExprValue::from_read_scope(self.sleigh(), value),
                    }),
                }
            }
            RawExprElement::Reference(src, size, value) => {
                let ref_bytes = size
                    .map(|x| {
                        //TODO non generic error here
                        NumberNonZeroUnsigned::new(x.value)
                            .ok_or_else(|| Box::new(ExecutionError::BitRangeZero))
                    })
                    .transpose()?;
                let value = reference_scope(
                    self.read_scope(&value, &src)?,
                    src,
                    ref_bytes,
                    self.sleigh(),
                )?;
                Ok(value)
            }
            RawExprElement::Op(src, raw_op, input) => {
                let input = self.new_expr(*input)?;
                self.new_op_unary(&raw_op, src, input)
            }
            RawExprElement::New(src, param0, param1) => {
                let param0 = self.new_expr(*param0).map(Box::new)?;
                let param1 = param1
                    .map(|param| self.new_expr(*param).map(Box::new))
                    .transpose()?;
                Ok(ExprElement::New(ExprNew {
                    location: src,
                    first: param0,
                    second: param1,
                }))
            }
            RawExprElement::CPool(src, params) => {
                let params = params
                    .into_iter()
                    .map(|param| self.new_expr(param))
                    .collect::<Result<_, _>>()?;
                Ok(ExprElement::CPool(ExprCPool {
                    location: src,
                    params,
                }))
            }
            RawExprElement::UserCall(call) => self.new_call_expr(call),
            RawExprElement::Ambiguous1 {
                name,
                param,
                param_src,
            } => {
                //can be one of two possibilities:
                if let Ok(value) = self.read_scope(&name, &param_src) {
                    //first: value with ByteRangeMsb operator
                    let value = Expr::Value(ExprElement::Value {
                        location: param_src.clone(),
                        value: ExprValue::from_read_scope(self.sleigh(), value),
                    });
                    Ok(ExprElement::new_trunk_lsb(param_src, param, value))
                } else {
                    //second: (user_?)function call with one parameter
                    //we know this is not a primitive function, macro
                    //probably never exports, so this can only be a
                    //user_function
                    self.new_call_expr(syntax::block::execution::UserCall::new(
                        name,
                        param_src.clone(),
                        vec![syntax::block::execution::expr::Expr::Value(
                            syntax::block::execution::expr::ExprElement::Value(
                                crate::syntax::Value::Number(param_src, Number::Positive(param)),
                            ),
                        )],
                    ))
                }
            }
        }
    }
    fn new_expr(
        &mut self,
        input: syntax::block::execution::expr::Expr,
    ) -> Result<Expr, Box<ExecutionError>> {
        use syntax::block::execution::expr::Expr as RawExpr;
        match input {
            RawExpr::Value(value) => self.new_expr_element(value).map(Expr::Value),
            RawExpr::Op(src, op, left, right) => {
                let left = self.new_expr(*left)?;
                let right = self.new_expr(*right)?;
                Ok(Expr::new_op(
                    self.sleigh(),
                    self.execution(),
                    src,
                    op,
                    left,
                    right,
                ))
            }
        }
    }
    fn new_op_unary(
        &self,
        input: &syntax::block::execution::op::Unary,
        src: Span,
        expr: Expr,
    ) -> Result<ExprElement, Box<ExecutionError>> {
        use syntax::block::execution::op::Unary as Op;
        let to_nonzero =
            //TODO generic error here
            |x: NumberUnsigned| NumberNonZeroUnsigned::new(x).ok_or_else(||Box::new(ExecutionError::BitRangeZero));
        let op = match input {
            Op::ByteRangeMsb(x) => return Ok(ExprElement::new_trunk_lsb(src, x.value, expr)),
            Op::ByteRangeLsb(x) => {
                let lsb_bits = NumberNonZeroUnsigned::new(x.value * 8).unwrap();
                let lsb_len = FieldSize::new_bits(lsb_bits);
                match expr {
                    // NOTE, Lsb on and Int/DisassemblyVar/TokenField/Bitrange just
                    // set the len
                    // except if TokenField have the value translated into a varnode
                    Expr::Value(ExprElement::Value {
                        location,
                        value:
                            ExprValue::Int(ExprNumber {
                                size: _,
                                number: value,
                            }),
                    }) => {
                        if u64::from(value.bits_required()) > lsb_bits.get() {
                            return Err(Box::new(ExecutionError::VarSize(
                                VarSizeError::TakeLsbTooSmall {
                                    lsb: x.value.try_into().unwrap(),
                                    input: lsb_len,
                                    location,
                                },
                            )));
                        }
                        return Ok(ExprElement::Value {
                            location,
                            value: ExprValue::Int(ExprNumber {
                                //TODO error
                                size: lsb_len,
                                number: value,
                            }),
                        });
                    }
                    Expr::Value(ExprElement::Value {
                        location,
                        value: ExprValue::DisVar(ExprDisVar { size: _, id }),
                    }) => {
                        return Ok(ExprElement::Value {
                            location,
                            value: ExprValue::DisVar(ExprDisVar { size: lsb_len, id }),
                        });
                    }
                    Expr::Value(ExprElement::Value {
                        location,
                        value: ExprValue::TokenField(ExprTokenField { size: _, id }),
                    }) => {
                        let tf = self.sleigh().token_field(id);
                        if let Some(crate::token::TokenFieldAttach::Varnode(att_var_id)) = tf.attach
                        {
                            let value = ExprValue::VarnodeDynamic(ExprVarnodeDynamic {
                                attach_id: att_var_id,
                                attach_value: DynamicValueType::TokenField(id),
                            });
                            return Ok(ExprElement::new_op(
                                x.src.clone(),
                                Unary::TakeLsb(x.value.try_into().unwrap()),
                                Expr::Value(ExprElement::Value { location, value }),
                            ));
                        } else if tf.bits.len() > lsb_bits {
                            // if tf is bigger then the lsb, this is a regular take_lsb op
                            return Ok(ExprElement::new_op(
                                x.src.clone(),
                                Unary::TakeLsb(x.value.try_into().unwrap()),
                                Expr::Value(ExprElement::Value {
                                    location,
                                    value: ExprValue::TokenField(ExprTokenField {
                                        size: FieldSize::new_unsized()
                                            .set_min_bits(tf.bits.len())
                                            .unwrap()
                                            .set_possible_min(),
                                        id,
                                    }),
                                }),
                            ));
                        } else {
                            // otherwise the lsb just define the tf size
                            let value = ExprValue::TokenField(ExprTokenField { size: lsb_len, id });
                            return Ok(ExprElement::Value { location, value });
                        }
                    }
                    Expr::Value(ExprElement::Value {
                        location,
                        value: ExprValue::Bitrange(ExprBitrange { size: _, id }),
                    }) => {
                        return Ok(ExprElement::Value {
                            location,
                            value: ExprValue::Bitrange(ExprBitrange { size: lsb_len, id }),
                        });
                    }
                    _ => {
                        return Ok(ExprElement::new_take_lsb(src, to_nonzero(x.value)?, expr));
                    }
                }
            }
            Op::BitRange(range) => {
                return Ok(ExprElement::new_bitrange(
                    src,
                    range.lsb_bit,
                    to_nonzero(range.n_bits)?,
                    expr,
                ))
            }
            Op::Dereference(x) => {
                return Ok(ExprElement::new_op(
                    src,
                    Unary::Dereference(self.new_addr_derefence(x)?),
                    expr,
                ))
            }
            Op::Negation => Unary::Negation,
            Op::BitNegation => Unary::BitNegation,
            Op::Negative => Unary::Negative,
            Op::FloatNegative => Unary::FloatNegative,
            Op::Popcount => Unary::Popcount(FieldSize::new_unsized()),
            Op::Lzcount => Unary::Lzcount(FieldSize::new_unsized()),
            Op::Zext => Unary::Zext(FieldSize::new_unsized()),
            Op::Sext => Unary::Sext(FieldSize::new_unsized()),
            Op::FloatNan => Unary::FloatNan(FieldSize::new_bool()),
            Op::FloatAbs => Unary::FloatAbs,
            Op::FloatSqrt => Unary::FloatSqrt,
            Op::Int2Float => Unary::Int2Float(FieldSize::new_unsized()),
            Op::Float2Float => Unary::Float2Float(FieldSize::new_unsized()),
            Op::SignTrunc => Unary::SignTrunc(FieldSize::new_unsized()),
            Op::FloatCeil => Unary::FloatCeil,
            Op::FloatFloor => Unary::FloatFloor,
            Op::FloatRound => Unary::FloatRound,
        };
        Ok(ExprElement::new_op(src, op, expr))
    }
    fn new_addr_derefence(
        &self,
        input: &syntax::block::execution::op::AddrDereference,
    ) -> Result<MemoryLocation, Box<ExecutionError>> {
        let space = input
            .space
            .as_ref()
            .map(|x| self.space(&x.name, &x.src))
            .unwrap_or_else(|| {
                self.sleigh()
                    .default_space()
                    .ok_or_else(|| Box::new(ExecutionError::DefaultSpace))
            })?;
        //size will be the lsb of size, if specified, otherwise  we can't know
        //the size directly
        let size = match input.size.as_ref() {
            Some(size) => FieldSize::new_bytes(
                NumberNonZeroUnsigned::new(size.value)
                    .ok_or_else(|| Box::new(ExecutionError::BitRangeZero))?,
            ),
            None => FieldSize::new_unsized(),
        };
        Ok(MemoryLocation {
            space,
            size,
            location: input.src.clone(),
        })
    }

    #[allow(private_interfaces)]
    fn map_variables<'a>(
        &mut self,
        pmacro: &PcodeMacro,
        params: &'a [Expr],
    ) -> Vec<VariableAlias<'a>> {
        pmacro
            .execution
            .variables
            .iter()
            .enumerate()
            .map(|(var_id, var)| {
                let var_id = VariableId(var_id);
                // if the variable is a parameter and the parameter is a value,
                // just make the variable an alias to the original value
                let param_id = pmacro
                    .params
                    .iter()
                    .position(|param_id| *param_id == var_id);
                if let Some(param_id) = param_id {
                    let param = &params[param_id];
                    // HACK if the parameter is a single value, the param is simply
                    // replaced
                    if let Expr::Value(ExprElement::Value { location: _, value }) = param {
                        return VariableAlias::Alias(value);
                    }

                    // a varnode with bitrange, became a bitrange assignment
                    if let Expr::Value(ExprElement::Op(ExprUnaryOp {
                        op: Unary::BitRange { range, .. },
                        input,
                        ..
                    })) = param
                    {
                        // NOTE this only apply to:
                        // * Varnode
                        // * TokenField that that translate to varnode
                        // * Table that export a memory location
                        match &**input {
                            Expr::Value(ExprElement::Value {
                                value: value @ ExprValue::Varnode(_),
                                ..
                            }) => return VariableAlias::SubVarnode(value, range.clone()),
                            Expr::Value(ExprElement::Value {
                                value: value @ ExprValue::TokenField(tf_expr),
                                ..
                            }) => {
                                let tf = self.sleigh().token_field(tf_expr.id);
                                if let Some(crate::token::TokenFieldAttach::Varnode(_)) = tf.attach
                                {
                                    return VariableAlias::SubVarnode(value, range.clone());
                                }
                            }
                            Expr::Value(ExprElement::Value {
                                value: value @ ExprValue::Table(table_id),
                                ..
                            }) => {
                                let table = self.sleigh().table(*table_id);
                                let table_export = table.export.borrow();
                                if let Some(TableExportType::Reference {
                                    len: _,
                                    space: _,
                                    also_values: _,
                                }) = &*table_export
                                {
                                    return VariableAlias::SubVarnode(value, range.clone());
                                }
                            }
                            // can't translate anything else into a writable bitrange
                            _ => {}
                        }
                    }

                    // otherwise just create a variable and assign the param value to it
                    let id = self
                        .execution_mut()
                        .create_variable(
                            format!("{}_{}", &pmacro.name, &var.name),
                            var.src.clone(),
                            Some(var.size.get()),
                            var.explicit,
                        )
                        .unwrap();
                    VariableAlias::Parameter(id)
                } else {
                    // if just a variable, create a new variable
                    let id = self
                        .execution_mut()
                        .create_variable(
                            format!("{}_{}", &pmacro.name, &var.name),
                            var.src.clone(),
                            Some(var.size.get()),
                            var.explicit,
                        )
                        .unwrap();
                    VariableAlias::NewVariable(id)
                }
            })
            .collect()
    }
}

fn reference_scope(
    read: ReadScope,
    src: Span,
    ref_bytes: Option<NumberNonZeroUnsigned>,
    sleigh: &Sleigh,
) -> Result<ExprElement, Box<ExecutionError>> {
    match read {
        // TODO only if token field translate into varnode? If not what does it means?
        // maybe the address for the pattern block...
        ReadScope::TokenField(id) => Ok(ExprElement::Reference(Reference {
            location: src.clone(),
            len: ref_bytes.map(FieldSize::new_bytes).unwrap_or_default(),
            value: ReferencedValue::TokenField(RefTokenField {
                location: src.clone(),
                id,
            }),
        })),
        //TODO What is a reference to inst_start/inst_next? Just the
        //value?
        ReadScope::InstStart => {
            let element = ExprElement::Value {
                location: src.clone(),
                value: ExprValue::InstStart(InstStart),
            };
            if let Some(ref_bytes) = ref_bytes {
                Ok(ExprElement::new_take_lsb(
                    src,
                    ref_bytes,
                    Expr::Value(element),
                ))
            } else {
                Ok(element)
            }
        }
        ReadScope::InstNext => {
            let element = ExprElement::Value {
                location: src.clone(),
                value: ExprValue::InstNext(InstNext),
            };
            if let Some(ref_bytes) = ref_bytes {
                Ok(ExprElement::new_take_lsb(
                    src,
                    ref_bytes,
                    Expr::Value(element),
                ))
            } else {
                Ok(element)
            }
        }
        ReadScope::Varnode(id) => {
            let varnode = sleigh.varnode(id);
            let size = ref_bytes.map(FieldSize::new_bytes).unwrap_or_else(|| {
                let space = sleigh.space(varnode.space);
                FieldSize::new_bytes(space.addr_bytes)
            });
            Ok(ExprElement::Value {
                location: src,
                value: ExprValue::Int(ExprNumber {
                    size,
                    number: Number::Positive(varnode.address),
                }),
            })
        }
        ReadScope::Table(id) => Ok(ExprElement::Reference(Reference {
            location: src.clone(),
            len: ref_bytes.map(FieldSize::new_bytes).unwrap_or_default(),
            value: ReferencedValue::Table(RefTable { location: src, id }),
        })),
        _ => Err(Box::new(ExecutionError::InvalidRef(src))),
    }
}

#[derive(Clone)]
enum VariableAlias<'a> {
    Alias(&'a ExprValue),
    SubVarnode(&'a ExprValue, Range<NumberUnsigned>),
    Parameter(VariableId),
    NewVariable(VariableId),
}

fn translate_expr(expr: &Expr, variables_map: &[VariableAlias<'_>]) -> Expr {
    match expr {
        Expr::Value(value) => Expr::Value(translate_expr_element(value, variables_map)),
        Expr::Op(op) => {
            let left = translate_expr(&op.left, variables_map);
            let right = translate_expr(&op.right, variables_map);
            Expr::Op(crate::semantic::inner::execution::ExprBinaryOp {
                location: op.location.clone(),
                output_size: op.output_size,
                op: op.op,
                left: Box::new(left),
                right: Box::new(right),
            })
        }
    }
}

fn translate_expr_element(expr: &ExprElement, variables_map: &[VariableAlias<'_>]) -> ExprElement {
    match expr {
        ExprElement::Value { location, value } => translate_value(location, value, variables_map),
        ExprElement::UserCall(call) => ExprElement::UserCall(UserCall {
            params: call
                .params
                .iter()
                .map(|x| translate_expr(x, variables_map))
                .collect(),
            ..call.clone()
        }),
        ExprElement::Op(x) => ExprElement::Op(super::ExprUnaryOp {
            input: Box::new(translate_expr(&x.input, variables_map)),
            ..x.clone()
        }),
        ExprElement::New(x) => ExprElement::New(ExprNew {
            first: Box::new(translate_expr(&x.first, variables_map)),
            second: x
                .second
                .as_ref()
                .map(|x| Box::new(translate_expr(x, variables_map))),
            location: x.location.clone(),
        }),
        ExprElement::CPool(x) => ExprElement::CPool(ExprCPool {
            location: x.location.clone(),
            params: x
                .params
                .iter()
                .map(|x| translate_expr(x, variables_map))
                .collect(),
        }),
        x @ ExprElement::Reference(_) => x.clone(),
    }
}

fn translate_value(
    location: &Span,
    expr: &ExprValue,
    variables_map: &[VariableAlias<'_>],
) -> ExprElement {
    match expr {
        ExprValue::TokenField(_) | ExprValue::Table(_) | ExprValue::DisVar(_) => unreachable!(),

        ExprValue::ExeVar(id) => match variables_map[id.0].clone() {
            VariableAlias::Alias(x) => ExprElement::Value {
                location: location.clone(),
                value: x.clone(),
            },
            VariableAlias::SubVarnode(varnode, bits) => ExprElement::Op(ExprUnaryOp {
                location: location.clone(),
                op: Unary::BitRange {
                    range: bits.clone(),
                    size: FieldSize::new_unsized()
                        .set_min_bits((bits.end - bits.start).try_into().unwrap())
                        .unwrap()
                        .set_possible_min(),
                },
                input: Box::new(Expr::Value(ExprElement::Value {
                    location: location.clone(),
                    value: varnode.clone(),
                })),
            }),
            VariableAlias::Parameter(id) | VariableAlias::NewVariable(id) => ExprElement::Value {
                location: location.clone(),
                value: ExprValue::ExeVar(id),
            },
        },

        x @ (ExprValue::Varnode(_)
        | ExprValue::Context(_)
        | ExprValue::Bitrange(_)
        | ExprValue::InstStart(_)
        | ExprValue::InstNext(_)
        | ExprValue::Int(_)) => ExprElement::Value {
            location: location.clone(),
            value: x.clone(),
        },
        ExprValue::IntDynamic(_) => todo!(),
        ExprValue::VarnodeDynamic(_) => todo!(),
    }
}

fn translate_write(
    sleigh: &Sleigh,
    expr: &AssignmentWrite,
    location: &Span,
    variables_map: &[VariableAlias<'_>],
) -> Result<AssignmentWrite, Box<ExecutionError>> {
    match expr {
        // TODO check the creation flag, it should only be used on local variables
        AssignmentWrite::Variable {
            value: AssignmentWriteVariable::Local { id, creation: _ },
            op,
        } => match (variables_map[id.0].clone(), op.to_owned()) {
            (VariableAlias::SubVarnode(ExprValue::Varnode(varnode), bits), None) => {
                let op = Some(AssignmentOp::BitRange(bits));
                let value = AssignmentWriteVariable::Varnode(*varnode);
                Ok(AssignmentWrite::Variable { op, value })
            }
            (VariableAlias::SubVarnode(ExprValue::TokenField(token_field_expr), bits), None) => {
                let token_field = sleigh.token_field(token_field_expr.id);
                let Some(crate::token::TokenFieldAttach::Varnode(attach_id)) = token_field.attach
                else {
                    todo!();
                };
                let op = Some(AssignmentOp::BitRange(bits));
                let value = AssignmentWriteVariable::DynVarnode {
                    value_id: DynamicValueType::TokenField(token_field_expr.id),
                    attach_id,
                };
                Ok(AssignmentWrite::Variable { op, value })
            }
            (VariableAlias::SubVarnode(ExprValue::Table(table_id), bits), None) => {
                table_write(sleigh, *table_id, location)?;
                Ok(AssignmentWrite::TableExport {
                    table_id: *table_id,
                    op: Some(AssignmentOp::BitRange(bits)),
                })
            }
            (VariableAlias::SubVarnode(_, _), None) => unreachable!(),
            (VariableAlias::SubVarnode(_, _), Some(_)) => {
                Err(Box::new(ExecutionError::MacroBuildInvalid))
            }
            (VariableAlias::Alias(value), op) => {
                match value {
                    // TODO verify those assumptions
                    ExprValue::Int(_)
                    | ExprValue::InstStart(_)
                    | ExprValue::InstNext(_)
                    | ExprValue::Context(_)
                    | ExprValue::Bitrange(_)
                    | ExprValue::DisVar(_) => panic!(),

                    ExprValue::ExeVar(id) => Ok(AssignmentWrite::Variable {
                        op,
                        value: AssignmentWriteVariable::Local {
                            id: *id,
                            creation: false,
                        },
                    }),
                    ExprValue::Varnode(id) => Ok(AssignmentWrite::Variable {
                        op,
                        value: AssignmentWriteVariable::Varnode(*id),
                    }),
                    ExprValue::TokenField(tf_expr) => {
                        let token_field = sleigh.token_field(tf_expr.id);
                        let Some(crate::token::TokenFieldAttach::Varnode(attach_id)) =
                            token_field.attach
                        else {
                            todo!();
                        };
                        Ok(AssignmentWrite::Variable {
                            op,
                            value: AssignmentWriteVariable::DynVarnode {
                                value_id: DynamicValueType::TokenField(tf_expr.id),
                                attach_id,
                            },
                        })
                    }
                    ExprValue::VarnodeDynamic(ExprVarnodeDynamic {
                        attach_id,
                        attach_value,
                    }) => Ok(AssignmentWrite::Variable {
                        op,
                        value: AssignmentWriteVariable::DynVarnode {
                            value_id: *attach_value,
                            attach_id: *attach_id,
                        },
                    }),
                    ExprValue::Table(id) => {
                        table_write(sleigh, *id, location)?;
                        Ok(AssignmentWrite::TableExport { table_id: *id, op })
                    }
                    ExprValue::IntDynamic(ExprIntDynamic { .. }) => {
                        panic!()
                    }
                }
            }
            (VariableAlias::Parameter(id) | VariableAlias::NewVariable(id), op) => {
                let value = AssignmentWriteVariable::Local {
                    id,
                    creation: false,
                };
                Ok(AssignmentWrite::Variable { op, value })
            }
        },
        AssignmentWrite::Variable {
            value: AssignmentWriteVariable::Bitrange(bitrange_id),
            op,
        } => {
            let value = AssignmentWriteVariable::Bitrange(*bitrange_id);
            Ok(AssignmentWrite::Variable {
                op: op.to_owned(),
                value,
            })
        }
        AssignmentWrite::Variable {
            value: AssignmentWriteVariable::Varnode(varnode_id),
            op,
        } => {
            let value = AssignmentWriteVariable::Varnode(*varnode_id);
            Ok(AssignmentWrite::Variable {
                op: op.to_owned(),
                value,
            })
        }
        AssignmentWrite::Variable { value, op } => Ok(AssignmentWrite::Variable {
            op: op.to_owned(),
            value: *value,
        }),
        AssignmentWrite::Memory { mem, addr } => {
            let addr = translate_expr(addr, variables_map);
            Ok(AssignmentWrite::Memory {
                mem: mem.clone(),
                addr,
            })
        }
        AssignmentWrite::TableExport { table_id, op } => Ok(AssignmentWrite::TableExport {
            table_id: *table_id,
            op: op.to_owned(),
        }),
        AssignmentWrite::TableReferenceExport { table_id, size } => {
            Ok(AssignmentWrite::TableReferenceExport {
                table_id: *table_id,
                size: *size,
            })
        }
    }
}

pub fn table_write(
    sleigh: &Sleigh,
    table_id: TableId,
    location: &Span,
) -> Result<(), Box<ExecutionError>> {
    let table = sleigh.table(table_id);
    let table = table.export.borrow();
    let Some(TableExportType::Reference {
        len: _,
        space: _,
        also_values: _,
    }) = &*table
    else {
        return Err(Box::new(ExecutionError::WriteInvalidTable(
            location.clone(),
        )));
    };
    Ok(())
}