sway-core 0.33.1

Sway core language.
Documentation
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
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
use super::*;
use crate::{
    decl_engine::*,
    language::{parsed::TreeType, ty, CallPath, Visibility},
    type_system::TypeInfo,
    Engines, TypeEngine, TypeId,
};
use petgraph::{prelude::NodeIndex, visit::Dfs};
use std::collections::BTreeSet;
use sway_error::warning::{CompileWarning, Warning};
use sway_error::{error::CompileError, type_error::TypeError};
use sway_types::{span::Span, Ident, Spanned};

impl<'cfg> ControlFlowGraph<'cfg> {
    pub(crate) fn find_dead_code(&self, decl_engine: &DeclEngine) -> Vec<CompileWarning> {
        // Dead code is code that has no path from the entry point.
        // Collect all connected nodes by traversing from the entries.
        // The dead nodes are those we did not collect.
        let mut connected = BTreeSet::new();
        let mut dfs = Dfs::empty(&self.graph);
        for &entry in &self.entry_points {
            dfs.move_to(entry);
            while let Some(node) = dfs.next(&self.graph) {
                connected.insert(node);
            }
        }
        let dead_nodes: Vec<_> = self
            .graph
            .node_indices()
            .filter(|n| !connected.contains(n))
            .collect();

        let dead_function_contains_span = |span: &Span| -> bool {
            dead_nodes.iter().any(|x| {
                if let ControlFlowGraphNode::ProgramNode(ty::TyAstNode {
                    span: function_span,
                    content:
                        ty::TyAstNodeContent::Declaration(ty::TyDeclaration::FunctionDeclaration(_)),
                }) = &self.graph[*x]
                {
                    function_span.end() >= span.end() && function_span.start() <= span.start()
                } else {
                    false
                }
            })
        };

        let priv_enum_var_warn = |name: &Ident| CompileWarning {
            span: name.span(),
            warning_content: Warning::DeadEnumVariant {
                variant_name: name.clone(),
            },
        };
        let dead_enum_variant_warnings = dead_nodes
            .iter()
            .filter_map(|x| match &self.graph[*x] {
                ControlFlowGraphNode::EnumVariant {
                    variant_name,
                    is_public,
                } if !is_public => Some(priv_enum_var_warn(variant_name)),
                _ => None,
            })
            .collect::<Vec<_>>();

        let dead_ast_node_warnings = dead_nodes
            .iter()
            .filter_map(|x| match &self.graph[*x] {
                ControlFlowGraphNode::ProgramNode(node) => {
                    construct_dead_code_warning_from_node(decl_engine, node)
                }
                ControlFlowGraphNode::EnumVariant {
                    variant_name,
                    is_public,
                } if !is_public => Some(priv_enum_var_warn(variant_name)),
                ControlFlowGraphNode::EnumVariant { .. } => None,
                ControlFlowGraphNode::MethodDeclaration { span, .. } => Some(CompileWarning {
                    span: span.clone(),
                    warning_content: Warning::DeadMethod,
                }),
                ControlFlowGraphNode::StructField {
                    struct_field_name, ..
                } => Some(CompileWarning {
                    span: struct_field_name.span(),
                    warning_content: Warning::StructFieldNeverRead,
                }),
                ControlFlowGraphNode::StorageField { field_name, .. } => Some(CompileWarning {
                    span: field_name.span(),
                    warning_content: Warning::DeadStorageDeclaration,
                }),
                ControlFlowGraphNode::OrganizationalDominator(..) => None,
            })
            .collect::<Vec<_>>();

        let all_warnings = [dead_enum_variant_warnings, dead_ast_node_warnings].concat();
        // filter out any overlapping spans -- if a span is contained within another one,
        // remove it.
        all_warnings
            .clone()
            .into_iter()
            .filter(
                |CompileWarning {
                     span,
                     warning_content,
                 }| {
                    if let Warning::UnreachableCode = warning_content {
                        // If the unreachable code is within an unused function, filter it out
                        // since the dead function name is the only warning we want to show.
                        if dead_function_contains_span(span) {
                            return false;
                        }
                    }

                    // if any other warnings contain a span which completely covers this one, filter
                    // out this one.
                    !all_warnings.iter().any(
                        |CompileWarning {
                             span: other_span, ..
                         }| {
                            other_span.end() > span.end() && other_span.start() < span.start()
                        },
                    )
                },
            )
            .collect()
    }

    pub(crate) fn append_module_to_dead_code_graph<'eng: 'cfg>(
        engines: Engines<'eng>,
        module_nodes: &[ty::TyAstNode],
        tree_type: &TreeType,
        graph: &mut ControlFlowGraph<'cfg>,
        // the `Result` return is just to handle `Unimplemented` errors
    ) -> Result<(), CompileError> {
        // do a depth first traversal and cover individual inner ast nodes
        let decl_engine = engines.de();
        let mut leaves = vec![];
        let exit_node = Some(graph.add_node(engines, ("Program exit".to_string()).into()));
        for ast_entrypoint in module_nodes {
            let (l_leaves, _new_exit_node) = connect_node(
                engines,
                ast_entrypoint,
                graph,
                &leaves,
                exit_node,
                tree_type,
                NodeConnectionOptions {
                    force_struct_fields_connection: false,
                },
            )?;

            leaves = l_leaves;
        }
        graph.entry_points = entry_points(decl_engine, tree_type, &graph.graph)?;
        Ok(())
    }
}

/// Collect all entry points into the graph based on the tree type.
fn entry_points(
    decl_engine: &DeclEngine,
    tree_type: &TreeType,
    graph: &flow_graph::Graph,
) -> Result<Vec<flow_graph::EntryPoint>, CompileError> {
    let mut entry_points = vec![];
    match tree_type {
        TreeType::Predicate | TreeType::Script => {
            // Predicates and scripts have main and test functions as entry points.
            for i in graph.node_indices() {
                match &graph[i] {
                    ControlFlowGraphNode::OrganizationalDominator(_) => continue,
                    ControlFlowGraphNode::ProgramNode(ty::TyAstNode {
                        span,
                        content:
                            ty::TyAstNodeContent::Declaration(ty::TyDeclaration::FunctionDeclaration(
                                decl_id,
                            )),
                        ..
                    }) => {
                        let decl = decl_engine.get_function(decl_id.clone(), span)?;
                        if !decl.is_entry() {
                            continue;
                        }
                    }
                    _ => continue,
                };
                entry_points.push(i);
            }
        }
        TreeType::Contract | TreeType::Library { .. } => {
            for i in graph.node_indices() {
                let is_entry = match &graph[i] {
                    ControlFlowGraphNode::OrganizationalDominator(_) => continue,
                    ControlFlowGraphNode::ProgramNode(ty::TyAstNode {
                        content:
                            ty::TyAstNodeContent::Declaration(ty::TyDeclaration::FunctionDeclaration(
                                decl_id,
                            )),
                        ..
                    }) => {
                        let decl = decl_engine.get_function(decl_id.clone(), &decl_id.span())?;
                        decl.visibility == Visibility::Public || decl.is_test()
                    }
                    ControlFlowGraphNode::ProgramNode(ty::TyAstNode {
                        content:
                            ty::TyAstNodeContent::Declaration(ty::TyDeclaration::TraitDeclaration(
                                decl_id,
                            )),
                        ..
                    }) => decl_engine
                        .get_trait(decl_id.clone(), &decl_id.span())?
                        .visibility
                        .is_public(),
                    ControlFlowGraphNode::ProgramNode(ty::TyAstNode {
                        content:
                            ty::TyAstNodeContent::Declaration(ty::TyDeclaration::StructDeclaration(
                                decl_id,
                            )),
                        ..
                    }) => {
                        let struct_decl =
                            decl_engine.get_struct(decl_id.clone(), &decl_id.span())?;
                        struct_decl.visibility == Visibility::Public
                    }
                    ControlFlowGraphNode::ProgramNode(ty::TyAstNode {
                        content:
                            ty::TyAstNodeContent::Declaration(ty::TyDeclaration::ImplTrait { .. }),
                        ..
                    }) => true,
                    ControlFlowGraphNode::ProgramNode(ty::TyAstNode {
                        content:
                            ty::TyAstNodeContent::Declaration(ty::TyDeclaration::ConstantDeclaration(
                                decl_id,
                            )),
                        ..
                    }) => {
                        let decl = decl_engine.get_constant(decl_id.clone(), &decl_id.span())?;
                        decl.visibility.is_public()
                    }
                    _ => continue,
                };
                if is_entry {
                    entry_points.push(i);
                }
            }
        }
    }
    Ok(entry_points)
}

/// This struct is used to pass node connection further down the tree as
/// we are processing AST nodes.
#[derive(Clone, Copy)]
struct NodeConnectionOptions {
    /// When this is enabled, connect struct fields to the struct itself,
    /// thus making all struct fields considered as being used in the graph.
    force_struct_fields_connection: bool,
}

fn connect_node<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    node: &ty::TyAstNode,
    graph: &mut ControlFlowGraph<'cfg>,
    leaves: &[NodeIndex],
    exit_node: Option<NodeIndex>,
    tree_type: &TreeType,
    options: NodeConnectionOptions,
) -> Result<(Vec<NodeIndex>, Option<NodeIndex>), CompileError> {
    //    let mut graph = graph.clone();
    let span = node.span.clone();
    Ok(match &node.content {
        ty::TyAstNodeContent::ImplicitReturnExpression(expr) => {
            let this_index = graph.add_node(engines, node.into());
            for leaf_ix in leaves {
                graph.add_edge(*leaf_ix, this_index, "".into());
            }
            // evaluate the expression

            let return_contents = connect_expression(
                engines,
                &expr.expression,
                graph,
                &[this_index],
                exit_node,
                "",
                tree_type,
                expr.span.clone(),
                options,
            )?;

            for leaf in return_contents.clone() {
                graph.add_edge(this_index, leaf, "".into());
            }
            // connect return to the exit node
            if let Some(exit_node) = exit_node {
                graph.add_edge(this_index, exit_node, "return".into());
            }
            (return_contents, None)
        }
        ty::TyAstNodeContent::Expression(ty::TyExpression {
            expression: expr_variant,
            span,
            ..
        }) => {
            let entry = graph.add_node(engines, node.into());
            // insert organizational dominator node
            // connected to all current leaves
            for leaf in leaves {
                graph.add_edge(*leaf, entry, "".into());
            }

            (
                connect_expression(
                    engines,
                    expr_variant,
                    graph,
                    &[entry],
                    exit_node,
                    "",
                    tree_type,
                    span.clone(),
                    options,
                )?,
                exit_node,
            )
        }
        ty::TyAstNodeContent::SideEffect => (leaves.to_vec(), exit_node),
        ty::TyAstNodeContent::Declaration(decl) => {
            // all leaves connect to this node, then this node is the singular leaf
            let cfg_node: ControlFlowGraphNode = node.into();
            // check if node for this decl already exists
            let decl_node = match graph.get_node_from_decl(engines, &cfg_node) {
                Some(node) => node,
                None => graph.add_node(engines, cfg_node),
            };
            for leaf in leaves {
                graph.add_edge(*leaf, decl_node, "".into());
            }
            (
                connect_declaration(
                    engines, decl, graph, decl_node, span, exit_node, tree_type, leaves, options,
                )?,
                exit_node,
            )
        }
    })
}

#[allow(clippy::too_many_arguments)]
fn connect_declaration<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    decl: &ty::TyDeclaration,
    graph: &mut ControlFlowGraph<'cfg>,
    entry_node: NodeIndex,
    span: Span,
    exit_node: Option<NodeIndex>,
    tree_type: &TreeType,
    leaves: &[NodeIndex],
    options: NodeConnectionOptions,
) -> Result<Vec<NodeIndex>, CompileError> {
    use ty::TyDeclaration::*;
    let decl_engine = engines.de();
    match decl {
        VariableDeclaration(var_decl) => {
            let ty::TyVariableDeclaration { body, .. } = &**var_decl;
            connect_expression(
                engines,
                &body.expression,
                graph,
                &[entry_node],
                exit_node,
                "variable instantiation",
                tree_type,
                body.clone().span,
                options,
            )
        }
        ConstantDeclaration(decl_id) => {
            let ty::TyConstantDeclaration { name, value, .. } =
                decl_engine.get_constant(decl_id.clone(), &span)?;
            graph.namespace.insert_constant(name, entry_node);
            connect_expression(
                engines,
                &value.expression,
                graph,
                &[entry_node],
                exit_node,
                "constant declaration expression",
                tree_type,
                value.span.clone(),
                options,
            )
        }
        FunctionDeclaration(decl_id) => {
            let fn_decl = decl_engine.get_function(decl_id.clone(), &decl.span())?;
            connect_typed_fn_decl(
                engines, &fn_decl, graph, entry_node, span, exit_node, tree_type, options,
            )?;
            Ok(leaves.to_vec())
        }
        TraitDeclaration(decl_id) => {
            let trait_decl = decl_engine.get_trait(decl_id.clone(), &span)?;
            connect_trait_declaration(&trait_decl, graph, entry_node);
            Ok(leaves.to_vec())
        }
        AbiDeclaration(decl_id) => {
            let abi_decl = decl_engine.get_abi(decl_id.clone(), &span)?;
            connect_abi_declaration(engines, &abi_decl, graph, entry_node)?;
            Ok(leaves.to_vec())
        }
        StructDeclaration(decl_id) => {
            let struct_decl = decl_engine.get_struct(decl_id.clone(), &span)?;
            connect_struct_declaration(engines, &struct_decl, graph, entry_node, tree_type);
            Ok(leaves.to_vec())
        }
        EnumDeclaration(decl_id) => {
            let enum_decl = decl_engine.get_enum(decl_id.clone(), &span)?;
            connect_enum_declaration(engines, &enum_decl, graph, entry_node);
            Ok(leaves.to_vec())
        }
        ImplTrait(decl_id) => {
            let ty::TyImplTrait {
                trait_name,
                methods,
                ..
            } = decl_engine.get_impl_trait(decl_id.clone(), &span)?;

            connect_impl_trait(
                engines,
                &trait_name,
                graph,
                &methods,
                entry_node,
                tree_type,
                options,
            )?;
            Ok(leaves.to_vec())
        }
        StorageDeclaration(decl_id) => {
            let storage = decl_engine.get_storage(decl_id.clone(), &span)?;
            connect_storage_declaration(engines, &storage, graph, entry_node, tree_type);
            Ok(leaves.to_vec())
        }
        ErrorRecovery(_) | GenericTypeForFunctionScope { .. } => Ok(leaves.to_vec()),
    }
}

/// Connect each individual struct field, and when that field is accessed in a subfield expression,
/// connect that field.
fn connect_struct_declaration<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    struct_decl: &ty::TyStructDeclaration,
    graph: &mut ControlFlowGraph<'cfg>,
    entry_node: NodeIndex,
    tree_type: &TreeType,
) {
    let ty::TyStructDeclaration {
        name,
        fields,
        visibility,
        ..
    } = struct_decl;
    let field_nodes = fields
        .iter()
        .map(|field| (field.name.clone(), graph.add_node(engines, field.into())))
        .collect::<Vec<_>>();
    // If this is a library or smart contract, and if this is public, then we want to connect the
    // declaration node itself to the individual fields.
    //
    // this is important because if the struct is public, you want to be able to signal that all
    // fields are accessible by just adding an edge to the struct declaration node
    if matches!(tree_type, TreeType::Contract | TreeType::Library { .. })
        && *visibility == Visibility::Public
    {
        for (_name, node) in &field_nodes {
            graph.add_edge(entry_node, *node, "".into());
        }
    }

    // Now, populate the struct namespace with the location of this struct as well as the indexes
    // of the field names
    graph
        .namespace
        .insert_struct(name.as_str().to_string(), entry_node, field_nodes);
}

/// Implementations of traits are top-level things that are not conditional, so
/// we insert an edge from the function's starting point to the declaration to show
/// that the declaration was indeed at some point implemented.
/// Additionally, we insert the trait's methods into the method namespace in order to
/// track which exact methods are dead code.
fn connect_impl_trait<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    trait_name: &CallPath,
    graph: &mut ControlFlowGraph<'cfg>,
    methods: &[DeclId],
    entry_node: NodeIndex,
    tree_type: &TreeType,
    options: NodeConnectionOptions,
) -> Result<(), CompileError> {
    let decl_engine = engines.de();
    let trait_decl_node = graph.namespace.find_trait(trait_name).cloned();
    match trait_decl_node {
        None => {
            let node_ix = graph.add_node(engines, "External trait".into());
            graph.add_edge(entry_node, node_ix, "".into());
        }
        Some(trait_decl_node) => {
            graph.add_edge_from_entry(entry_node, "".into());
            graph.add_edge(entry_node, trait_decl_node, "".into());
        }
    };
    let mut methods_and_indexes = vec![];
    // insert method declarations into the graph
    for method_decl_id in methods {
        let fn_decl = decl_engine.get_function(method_decl_id.clone(), &trait_name.span())?;
        let fn_decl_entry_node = graph.add_node(
            engines,
            ControlFlowGraphNode::MethodDeclaration {
                span: fn_decl.span.clone(),
                method_name: fn_decl.name.clone(),
                method_decl_id: method_decl_id.clone(),
                engines,
            },
        );
        if matches!(tree_type, TreeType::Library { .. } | TreeType::Contract) {
            graph.add_edge(entry_node, fn_decl_entry_node, "".into());
        }
        // connect the impl declaration node to the functions themselves, as all trait functions are
        // public if the trait is in scope
        connect_typed_fn_decl(
            engines,
            &fn_decl,
            graph,
            fn_decl_entry_node,
            fn_decl.span.clone(),
            None,
            tree_type,
            options,
        )?;
        methods_and_indexes.push((fn_decl.name.clone(), fn_decl_entry_node));
    }
    // we also want to add an edge from the methods back to the trait, so if a method gets called,
    // the trait impl is considered used
    for (_, ix) in methods_and_indexes.iter() {
        graph.add_edge(*ix, entry_node, "".into());
    }

    // Now, insert the methods into the trait method namespace.
    graph
        .namespace
        .insert_trait_methods(trait_name.clone(), methods_and_indexes);

    Ok(())
}

/// The strategy here is to populate the trait namespace with just one singular trait
/// and if it is ever implemented, by virtue of type checking, we know all interface points
/// were met.
/// Upon implementation, we can populate the methods namespace and track dead functions that way.
/// TL;DR: At this point, we _only_ track the wholistic trait declaration and not the functions
/// contained within.
///
/// The trait node itself has already been added (as `entry_node`), so we just need to insert that
/// node index into the namespace for the trait.
fn connect_trait_declaration(
    decl: &ty::TyTraitDeclaration,
    graph: &mut ControlFlowGraph,
    entry_node: NodeIndex,
) {
    graph.namespace.add_trait(
        CallPath {
            prefixes: vec![],
            suffix: decl.name.clone(),
            is_absolute: false,
        },
        entry_node,
    );
}

/// See [connect_trait_declaration] for implementation details.
fn connect_abi_declaration(
    engines: Engines<'_>,
    decl: &ty::TyAbiDeclaration,
    graph: &mut ControlFlowGraph,
    entry_node: NodeIndex,
) -> Result<(), CompileError> {
    let type_engine = engines.te();
    let decl_engine = engines.de();

    graph.namespace.add_trait(
        CallPath {
            prefixes: vec![],
            suffix: decl.name.clone(),
            is_absolute: false,
        },
        entry_node,
    );

    // If a struct type is used as a return type in the interface surface
    // of the contract, then assume that any fields inside the struct can
    // be used outside of the contract.
    for fn_decl_id in decl.interface_surface.iter() {
        let fn_decl = decl_engine.get_trait_fn(fn_decl_id.clone(), &decl.span)?;
        if let Some(TypeInfo::Struct { name, .. }) =
            get_struct_type_info_from_type_id(type_engine, fn_decl.return_type)?
        {
            if let Some(ns) = graph.namespace.get_struct(&name).cloned() {
                for (_, field_ix) in ns.fields.iter() {
                    graph.add_edge(ns.struct_decl_ix, *field_ix, "".into());
                }
            }
        }
    }

    Ok(())
}

fn get_struct_type_info_from_type_id(
    type_engine: &TypeEngine,
    type_id: TypeId,
) -> Result<Option<TypeInfo>, TypeError> {
    let type_info = type_engine.to_typeinfo(type_id, &Span::dummy())?;
    match type_info {
        TypeInfo::Enum {
            type_parameters,
            variant_types,
            ..
        } => {
            for param in type_parameters.iter() {
                if let Ok(Some(type_info)) =
                    get_struct_type_info_from_type_id(type_engine, param.type_id)
                {
                    return Ok(Some(type_info));
                }
            }
            for var in variant_types.iter() {
                if let Ok(Some(type_info)) =
                    get_struct_type_info_from_type_id(type_engine, var.type_id)
                {
                    return Ok(Some(type_info));
                }
            }
            Ok(None)
        }
        TypeInfo::Tuple(type_args) => {
            for arg in type_args.iter() {
                if let Ok(Some(type_info)) =
                    get_struct_type_info_from_type_id(type_engine, arg.type_id)
                {
                    return Ok(Some(type_info));
                }
            }
            Ok(None)
        }
        TypeInfo::Custom { type_arguments, .. } => {
            if let Some(type_arguments) = type_arguments {
                for arg in type_arguments.iter() {
                    if let Ok(Some(type_info)) =
                        get_struct_type_info_from_type_id(type_engine, arg.type_id)
                    {
                        return Ok(Some(type_info));
                    }
                }
            }
            Ok(None)
        }
        TypeInfo::Struct { .. } => Ok(Some(type_info)),
        TypeInfo::Array(type_arg, _) => {
            get_struct_type_info_from_type_id(type_engine, type_arg.type_id)
        }
        _ => Ok(None),
    }
}

/// For an enum declaration, we want to make a declaration node for every individual enum
/// variant. When a variant is constructed, we can point an edge at that variant. This way,
/// we can see clearly, and thusly warn, when individual variants are not ever constructed.
fn connect_enum_declaration<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    enum_decl: &ty::TyEnumDeclaration,
    graph: &mut ControlFlowGraph<'cfg>,
    entry_node: NodeIndex,
) {
    graph
        .namespace
        .insert_enum(enum_decl.name.clone(), entry_node);

    // keep a mapping of each variant
    for variant in enum_decl.variants.iter() {
        let variant_index = graph.add_node(
            engines,
            ControlFlowGraphNode::from_enum_variant(
                variant.name.clone(),
                enum_decl.visibility != Visibility::Private,
            ),
        );

        graph.namespace.insert_enum_variant(
            enum_decl.name.clone(),
            entry_node,
            variant.name.clone(),
            variant_index,
        );
    }
}

/// When connecting a function declaration, we are inserting a new root node into the graph that
/// has no entry points, since it is just a declaration.
/// When something eventually calls it, it gets connected to the declaration.
#[allow(clippy::too_many_arguments)]
fn connect_typed_fn_decl<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    fn_decl: &ty::TyFunctionDeclaration,
    graph: &mut ControlFlowGraph<'cfg>,
    entry_node: NodeIndex,
    span: Span,
    exit_node: Option<NodeIndex>,
    tree_type: &TreeType,
    options: NodeConnectionOptions,
) -> Result<(), CompileError> {
    let type_engine = engines.te();
    let fn_exit_node = graph.add_node(
        engines,
        format!("\"{}\" fn exit", fn_decl.name.as_str()).into(),
    );
    let (_exit_nodes, _exit_node) = depth_first_insertion_code_block(
        engines,
        &fn_decl.body,
        graph,
        &[entry_node],
        Some(fn_exit_node),
        tree_type,
        options,
    )?;
    if let Some(exit_node) = exit_node {
        graph.add_edge(fn_exit_node, exit_node, "".into());
    }

    // not sure how correct it is to default to Unit here...
    // I think types should all be resolved by now.
    let ty = type_engine
        .to_typeinfo(fn_decl.return_type, &span)
        .unwrap_or_else(|_| TypeInfo::Tuple(Vec::new()));

    let namespace_entry = FunctionNamespaceEntry {
        entry_point: entry_node,
        exit_point: fn_exit_node,
        return_type: ty,
    };

    graph
        .namespace
        .insert_function(fn_decl.name.clone(), namespace_entry);

    connect_fn_params_struct_enums(engines, fn_decl, graph, entry_node)?;
    Ok(())
}

// Searches for any structs or enums types referenced by the function
// parameters from the passed function declaration and connects their
// corresponding struct/enum declaration to the function entry node, thus
// making sure they are considered used by the DCA pass.
fn connect_fn_params_struct_enums<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    fn_decl: &ty::TyFunctionDeclaration,
    graph: &mut ControlFlowGraph<'cfg>,
    fn_decl_entry_node: NodeIndex,
) -> Result<(), CompileError> {
    let type_engine = engines.te();
    for fn_param in &fn_decl.parameters {
        let ty = type_engine.to_typeinfo(fn_param.type_id, &fn_param.type_span)?;
        match ty {
            TypeInfo::Enum { name, .. } => {
                let ty_index = match graph.namespace.find_enum(&name) {
                    Some(ix) => *ix,
                    None => {
                        graph.add_node(engines, format!("External enum  {}", name.as_str()).into())
                    }
                };
                graph.add_edge(fn_decl_entry_node, ty_index, "".into());
            }
            TypeInfo::Struct { name, .. } => {
                let ty_index = match graph.namespace.find_struct_decl(name.as_str()) {
                    Some(ix) => *ix,
                    None => graph.add_node(
                        engines,
                        format!("External struct  {}", name.as_str()).into(),
                    ),
                };
                graph.add_edge(fn_decl_entry_node, ty_index, "".into());
            }
            _ => {}
        }
    }
    Ok(())
}

fn depth_first_insertion_code_block<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    node_content: &ty::TyCodeBlock,
    graph: &mut ControlFlowGraph<'cfg>,
    leaves: &[NodeIndex],
    exit_node: Option<NodeIndex>,
    tree_type: &TreeType,
    options: NodeConnectionOptions,
) -> Result<(Vec<NodeIndex>, Option<NodeIndex>), CompileError> {
    let mut leaves = leaves.to_vec();
    let mut exit_node = exit_node;
    for node in node_content.contents.iter() {
        let (this_node, l_exit_node) =
            connect_node(engines, node, graph, &leaves, exit_node, tree_type, options)?;
        leaves = this_node;
        exit_node = l_exit_node;
    }
    Ok((leaves, exit_node))
}

fn get_trait_fn_node_index<'a, 'cfg>(
    engines: Engines<'_>,
    function_decl_id: DeclId,
    expression_span: Span,
    graph: &'a ControlFlowGraph<'cfg>,
) -> Result<Option<&'a NodeIndex>, CompileError> {
    let decl_engine = engines.de();
    let fn_decl = decl_engine.get_function(function_decl_id, &expression_span)?;
    if let Some(implementing_type) = fn_decl.implementing_type {
        match implementing_type {
            ty::TyDeclaration::TraitDeclaration(decl) => {
                let trait_decl = decl_engine.get_trait(decl, &expression_span)?;
                Ok(graph
                    .namespace
                    .find_trait_method(&trait_decl.name.into(), &fn_decl.name))
            }
            ty::TyDeclaration::StructDeclaration(decl) => {
                let struct_decl = decl_engine.get_struct(decl, &expression_span)?;
                Ok(graph
                    .namespace
                    .find_trait_method(&struct_decl.name.into(), &fn_decl.name))
            }
            ty::TyDeclaration::ImplTrait(decl) => {
                let impl_trait = decl_engine.get_impl_trait(decl, &expression_span)?;
                Ok(graph
                    .namespace
                    .find_trait_method(&impl_trait.trait_name, &fn_decl.name))
            }
            ty::TyDeclaration::AbiDeclaration(decl) => {
                let abi_decl = decl_engine.get_abi(decl, &expression_span)?;
                Ok(graph
                    .namespace
                    .find_trait_method(&abi_decl.name.into(), &fn_decl.name))
            }
            _ => Err(CompileError::Internal(
                "Could not get node index for trait function",
                expression_span,
            )),
        }
    } else {
        Ok(None)
    }
}

/// connects any inner parts of an expression to the graph
/// note the main expression node has already been inserted
#[allow(clippy::too_many_arguments)]
fn connect_expression<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    expr_variant: &ty::TyExpressionVariant,
    graph: &mut ControlFlowGraph<'cfg>,
    leaves: &[NodeIndex],
    exit_node: Option<NodeIndex>,
    label: &'static str,
    tree_type: &TreeType,
    expression_span: Span,
    mut options: NodeConnectionOptions,
) -> Result<Vec<NodeIndex>, CompileError> {
    use ty::TyExpressionVariant::*;
    let type_engine = engines.te();
    let decl_engine = engines.de();
    match expr_variant {
        FunctionApplication {
            call_path: name,
            arguments,
            function_decl_id,
            ..
        } => {
            let fn_decl = decl_engine.get_function(function_decl_id.clone(), &expression_span)?;
            let mut is_external = false;
            // find the function in the namespace
            let (fn_entrypoint, fn_exit_point) = graph
                .namespace
                .get_function(&fn_decl.name)
                .cloned()
                .map(
                    |FunctionNamespaceEntry {
                         entry_point,
                         exit_point,
                         ..
                     }| (entry_point, exit_point),
                )
                .unwrap_or_else(|| {
                    let node_idx = graph.add_node(
                        engines,
                        format!("extern fn {}()", name.suffix.as_str()).into(),
                    );
                    is_external = true;
                    (
                        node_idx,
                        graph.add_node(
                            engines,
                            format!("extern fn {} exit", name.suffix.as_str()).into(),
                        ),
                    )
                });

            let trait_fn_node_idx =
                get_trait_fn_node_index(engines, function_decl_id.clone(), expression_span, graph)?;
            if let Some(trait_fn_node_idx) = trait_fn_node_idx {
                if fn_entrypoint != *trait_fn_node_idx {
                    graph.add_edge(fn_entrypoint, *trait_fn_node_idx, "".into());
                }
            }

            for leaf in leaves {
                graph.add_edge(*leaf, fn_entrypoint, label.into());
            }

            // save the existing options value to restore after handling the arguments
            let force_struct_fields_connection = options.force_struct_fields_connection;

            // if the function is external, assume that any struct that is being referenced
            // as an argument "consumes" all of the respective struct fields.
            // this could lead to false negatives but it is the best we can do at the moment
            // with our current DCA analysis architecture. revisit this once we switch
            // to an inter-procedural/module analysis approach.
            options.force_struct_fields_connection |= is_external;

            // we evaluate every one of the function arguments
            let mut current_leaf = vec![fn_entrypoint];
            for (_name, arg) in arguments {
                current_leaf = connect_expression(
                    engines,
                    &arg.expression,
                    graph,
                    &current_leaf,
                    exit_node,
                    "arg eval",
                    tree_type,
                    arg.clone().span,
                    options,
                )?;
            }
            options.force_struct_fields_connection = force_struct_fields_connection;

            // connect final leaf to fn exit
            for leaf in current_leaf {
                graph.add_edge(leaf, fn_exit_point, "".into());
            }
            // the exit points get connected to an exit node for the application
            if !is_external {
                if let Some(exit_node) = exit_node {
                    graph.add_edge(fn_exit_point, exit_node, "".into());
                    Ok(vec![exit_node])
                } else {
                    Ok(vec![fn_exit_point])
                }
            } else {
                Ok(vec![fn_entrypoint])
            }
        }
        LazyOperator { lhs, rhs, .. } => {
            let lhs_expr = connect_expression(
                engines,
                &lhs.expression,
                graph,
                leaves,
                exit_node,
                "",
                tree_type,
                lhs.span.clone(),
                options,
            )?;
            let rhs_expr = connect_expression(
                engines,
                &rhs.expression,
                graph,
                leaves,
                exit_node,
                "",
                tree_type,
                rhs.span.clone(),
                options,
            )?;
            Ok([lhs_expr, rhs_expr].concat())
        }
        Literal(_) => {
            let node = graph.add_node(engines, "Literal value".into());
            for leaf in leaves {
                graph.add_edge(*leaf, node, "".into());
            }
            Ok(vec![node])
        }
        VariableExpression { name, .. } => {
            // Variables may refer to global const declarations.
            Ok(graph
                .namespace
                .get_constant(name)
                .cloned()
                .map(|node| {
                    for leaf in leaves {
                        graph.add_edge(*leaf, node, "".into());
                    }
                    vec![node]
                })
                .unwrap_or_else(|| leaves.to_vec()))
        }
        EnumInstantiation {
            enum_decl,
            variant_name,
            contents,
            ..
        } => {
            // connect this particular instantiation to its variants declaration
            connect_enum_instantiation(
                engines,
                enum_decl,
                contents,
                variant_name,
                graph,
                leaves,
                exit_node,
                tree_type,
                options,
            )
        }
        IfExp {
            condition,
            then,
            r#else,
        } => {
            let condition_expr = connect_expression(
                engines,
                &condition.expression,
                graph,
                leaves,
                exit_node,
                "",
                tree_type,
                condition.span.clone(),
                options,
            )?;
            let then_expr = connect_expression(
                engines,
                &then.expression,
                graph,
                leaves,
                exit_node,
                "then branch",
                tree_type,
                then.span.clone(),
                options,
            )?;

            let else_expr = if let Some(else_expr) = r#else {
                connect_expression(
                    engines,
                    &else_expr.expression,
                    graph,
                    leaves,
                    exit_node,
                    "else branch",
                    tree_type,
                    else_expr.clone().span,
                    options,
                )?
            } else {
                vec![]
            };

            Ok([condition_expr, then_expr, else_expr].concat())
        }
        CodeBlock(a @ ty::TyCodeBlock { .. }) => {
            connect_code_block(engines, a, graph, leaves, exit_node, tree_type, options)
        }
        StructExpression {
            struct_name,
            fields,
            ..
        } => {
            let decl = match graph.namespace.find_struct_decl(struct_name.as_str()) {
                Some(ix) => *ix,
                None => graph.add_node(
                    engines,
                    format!("External struct  {}", struct_name.as_str()).into(),
                ),
            };
            let entry = graph.add_node(engines, "Struct declaration entry".into());
            let exit = graph.add_node(engines, "Struct declaration exit".into());
            // connect current leaves to the beginning of this expr
            for leaf in leaves {
                graph.add_edge(*leaf, entry, label.into());
            }
            // connect the entry to the decl, to denote that the struct has been constructed
            graph.add_edge(entry, decl, "".into());

            // connect the struct fields to the struct if its requested as an option
            if options.force_struct_fields_connection {
                if let Some(ns) = graph.namespace.get_struct(struct_name).cloned() {
                    for (_, field_ix) in ns.fields.iter() {
                        graph.add_edge(decl, *field_ix, "".into());
                    }
                }
            }

            let mut current_leaf = vec![entry];
            // for every field, connect its expression
            for ty::TyStructExpressionField { value, .. } in fields {
                current_leaf = connect_expression(
                    engines,
                    &value.expression,
                    graph,
                    &current_leaf,
                    exit_node,
                    "struct field instantiation",
                    tree_type,
                    value.clone().span,
                    options,
                )?;
            }

            // connect the final field to the exit
            for leaf in current_leaf {
                graph.add_edge(leaf, exit, "".into());
            }
            Ok(vec![exit])
        }
        StructFieldAccess {
            prefix,
            field_to_access,
            resolved_type_of_parent,
            field_instantiation_span,
            ..
        } => {
            connect_expression(
                engines,
                &prefix.expression,
                graph,
                leaves,
                exit_node,
                label,
                tree_type,
                field_instantiation_span.clone(),
                options,
            )?;

            let resolved_type_of_parent = type_engine
                .to_typeinfo(*resolved_type_of_parent, &field_to_access.span)
                .unwrap_or_else(|_| TypeInfo::Tuple(Vec::new()));

            assert!(matches!(resolved_type_of_parent, TypeInfo::Struct { .. }));
            let resolved_type_of_parent = match resolved_type_of_parent {
                TypeInfo::Struct { name, .. } => name,
                _ => panic!("Called subfield on a non-struct"),
            };
            let field_name = &field_to_access.name;
            // find the struct field index in the namespace
            let field_ix = match graph
                .namespace
                .find_struct_field_idx(resolved_type_of_parent.as_str(), field_name.as_str())
            {
                Some(ix) => *ix,
                None => graph.add_node(engines, "external struct".into()),
            };

            let this_ix = graph.add_node(
                engines,
                format!(
                    "Struct field access: {}.{}",
                    resolved_type_of_parent, field_name
                )
                .into(),
            );
            for leaf in leaves {
                graph.add_edge(*leaf, this_ix, "".into());
            }
            graph.add_edge(this_ix, field_ix, "".into());
            Ok(vec![this_ix])
        }
        AsmExpression { registers, .. } => {
            let asm_node_entry = graph.add_node(engines, "Inline asm entry".into());
            let asm_node_exit = graph.add_node(engines, "Inline asm exit".into());
            for leaf in leaves {
                graph.add_edge(*leaf, asm_node_entry, "".into());
            }

            let mut current_leaf = vec![asm_node_entry];
            for ty::TyAsmRegisterDeclaration { initializer, .. } in registers {
                current_leaf = match initializer {
                    Some(initializer) => connect_expression(
                        engines,
                        &initializer.expression,
                        graph,
                        &current_leaf,
                        exit_node,
                        "asm block argument initialization",
                        tree_type,
                        initializer.clone().span,
                        options,
                    )?,
                    None => current_leaf,
                }
            }

            // connect the final field to the exit
            for leaf in current_leaf {
                graph.add_edge(leaf, asm_node_exit, "".into());
            }

            Ok(vec![asm_node_exit])
        }
        Tuple { fields } => {
            let entry = graph.add_node(engines, "tuple entry".into());
            let exit = graph.add_node(engines, "tuple exit".into());
            // connect current leaves to the beginning of this expr
            for leaf in leaves {
                graph.add_edge(*leaf, entry, label.into());
            }

            let mut current_leaf = vec![entry];
            // for every field, connect its expression
            for value in fields {
                current_leaf = connect_expression(
                    engines,
                    &value.expression,
                    graph,
                    &current_leaf,
                    exit_node,
                    "tuple field instantiation",
                    tree_type,
                    value.clone().span,
                    options,
                )?;
            }

            // connect the final field to the exit
            for leaf in current_leaf {
                graph.add_edge(leaf, exit, "".into());
            }
            Ok(vec![exit])
        }
        AbiCast { address, .. } => connect_expression(
            engines,
            &address.expression,
            graph,
            leaves,
            exit_node,
            "abi cast address",
            tree_type,
            address.span.clone(),
            options,
        ),
        Array { contents } => {
            let nodes = contents
                .iter()
                .map(|elem| {
                    connect_expression(
                        engines,
                        &elem.expression,
                        graph,
                        leaves,
                        exit_node,
                        "",
                        tree_type,
                        elem.span.clone(),
                        options,
                    )
                })
                .collect::<Result<Vec<_>, _>>()?;
            Ok(nodes.concat())
        }
        ArrayIndex { prefix, index } => {
            let prefix_idx = connect_expression(
                engines,
                &prefix.expression,
                graph,
                leaves,
                exit_node,
                "",
                tree_type,
                prefix.span.clone(),
                options,
            )?;
            let index_idx = connect_expression(
                engines,
                &index.expression,
                graph,
                leaves,
                exit_node,
                "",
                tree_type,
                index.span.clone(),
                options,
            )?;
            Ok([prefix_idx, index_idx].concat())
        }
        TupleElemAccess { prefix, .. } => {
            let prefix_idx = connect_expression(
                engines,
                &prefix.expression,
                graph,
                leaves,
                exit_node,
                "",
                tree_type,
                prefix.span.clone(),
                options,
            )?;
            Ok(prefix_idx)
        }
        StorageAccess(fields) => {
            let storage_node = graph
                .namespace
                .storage
                .get(&fields.storage_field_name())
                .cloned();
            let this_ix = graph.add_node(
                engines,
                format!("storage field access: {}", fields.storage_field_name()).into(),
            );
            for leaf in leaves {
                storage_node.map(|x| graph.add_edge(*leaf, x, "".into()));
                graph.add_edge(*leaf, this_ix, "".into());
            }
            Ok(vec![this_ix])
        }
        IntrinsicFunction(kind) => {
            let prefix_idx =
                connect_intrinsic_function(engines, kind, graph, leaves, exit_node, tree_type)?;
            Ok(prefix_idx)
        }
        AbiName(abi_name) => {
            if let crate::type_system::AbiName::Known(abi_name) = abi_name {
                // abis are treated as traits here
                let decl = graph.namespace.find_trait(abi_name).cloned();
                if let Some(decl_node) = decl {
                    for leaf in leaves {
                        graph.add_edge(*leaf, decl_node, "".into());
                    }
                }
            }
            Ok(leaves.to_vec())
        }
        FunctionParameter => Ok(leaves.to_vec()),
        EnumTag { exp } => connect_expression(
            engines,
            &exp.expression,
            graph,
            leaves,
            exit_node,
            "enum tag exp",
            tree_type,
            exp.span.clone(),
            options,
        ),
        UnsafeDowncast { exp, .. } => connect_expression(
            engines,
            &exp.expression,
            graph,
            leaves,
            exit_node,
            "unsafe downcast exp",
            tree_type,
            exp.span.clone(),
            options,
        ),
        WhileLoop {
            body, condition, ..
        } => {
            // a while loop can loop back to the beginning,
            // or it can terminate.
            // so we connect the _end_ of the while loop _both_ to its beginning and the next node.
            // the loop could also be entirely skipped

            let entry = leaves[0];

            let while_loop_exit = graph.add_node(engines, "while loop exit".to_string().into());

            // it is possible for a whole while loop to be skipped so add edge from
            // beginning of while loop straight to exit
            graph.add_edge(
                entry,
                while_loop_exit,
                "condition is initially false".into(),
            );
            let mut leaves = vec![entry];

            // handle the condition of the loop
            connect_expression(
                engines,
                &condition.expression,
                graph,
                &leaves,
                exit_node,
                label,
                tree_type,
                Span::dummy(),
                options,
            )?;

            let (l_leaves, _l_exit_node) = depth_first_insertion_code_block(
                engines, body, graph, &leaves, exit_node, tree_type, options,
            )?;
            // insert edges from end of block back to beginning of it
            for leaf in &l_leaves {
                graph.add_edge(*leaf, entry, "loop repeats".into());
            }

            leaves = l_leaves;
            for leaf in leaves {
                graph.add_edge(leaf, while_loop_exit, "".into());
            }
            Ok(vec![while_loop_exit])
        }
        Break => {
            let break_node = graph.add_node(engines, "break".to_string().into());
            for leaf in leaves {
                graph.add_edge(*leaf, break_node, "".into());
            }
            Ok(vec![])
        }
        Continue => {
            let continue_node = graph.add_node(engines, "continue".to_string().into());
            for leaf in leaves {
                graph.add_edge(*leaf, continue_node, "".into());
            }
            Ok(vec![])
        }
        Reassignment(typed_reassignment) => connect_expression(
            engines,
            &typed_reassignment.rhs.expression,
            graph,
            leaves,
            exit_node,
            "variable reassignment",
            tree_type,
            typed_reassignment.rhs.clone().span,
            options,
        ),
        StorageReassignment(typed_storage_reassignment) => connect_expression(
            engines,
            &typed_storage_reassignment.rhs.expression,
            graph,
            leaves,
            exit_node,
            "variable reassignment",
            tree_type,
            typed_storage_reassignment.rhs.clone().span,
            options,
        ),
        Return(exp) => {
            let this_index = graph.add_node(engines, "return entry".into());
            for leaf in leaves {
                graph.add_edge(*leaf, this_index, "".into());
            }
            let return_contents = connect_expression(
                engines,
                &exp.expression,
                graph,
                &[this_index],
                exit_node,
                "",
                tree_type,
                exp.span.clone(),
                options,
            )?;
            // TODO: is this right? Shouldn't we connect the return_contents leaves to the exit
            // node?
            for leaf in return_contents {
                graph.add_edge(this_index, leaf, "".into());
            }
            if let Some(exit_node) = exit_node {
                graph.add_edge(this_index, exit_node, "return".into());
            }
            Ok(vec![])
        }
    }
}

fn connect_intrinsic_function<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    ty::TyIntrinsicFunctionKind {
        kind, arguments, ..
    }: &ty::TyIntrinsicFunctionKind,
    graph: &mut ControlFlowGraph<'cfg>,
    leaves: &[NodeIndex],
    exit_node: Option<NodeIndex>,
    tree_type: &TreeType,
) -> Result<Vec<NodeIndex>, CompileError> {
    let node = graph.add_node(engines, format!("Intrinsic {}", kind).into());
    for leaf in leaves {
        graph.add_edge(*leaf, node, "".into());
    }
    let mut result = vec![node];
    let _ = arguments.iter().try_fold(&mut result, |accum, exp| {
        let mut res = connect_expression(
            engines,
            &exp.expression,
            graph,
            leaves,
            exit_node,
            "intrinsic",
            tree_type,
            exp.span.clone(),
            NodeConnectionOptions {
                force_struct_fields_connection: true,
            },
        )?;
        accum.append(&mut res);
        Ok::<_, CompileError>(accum)
    })?;
    Ok(result)
}

fn connect_code_block<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    block: &ty::TyCodeBlock,
    graph: &mut ControlFlowGraph<'cfg>,
    leaves: &[NodeIndex],
    exit_node: Option<NodeIndex>,
    tree_type: &TreeType,
    options: NodeConnectionOptions,
) -> Result<Vec<NodeIndex>, CompileError> {
    let contents = &block.contents;
    let block_entry = graph.add_node(engines, "Code block entry".into());
    for leaf in leaves {
        graph.add_edge(*leaf, block_entry, "".into());
    }
    let mut current_leaf = vec![block_entry];
    for node in contents {
        current_leaf = connect_node(
            engines,
            node,
            graph,
            &current_leaf,
            exit_node,
            tree_type,
            options,
        )?
        .0;
    }

    let block_exit = graph.add_node(engines, "Code block exit".into());
    for leaf in current_leaf {
        graph.add_edge(leaf, block_exit, "".into());
    }
    Ok(vec![block_exit])
}

#[allow(clippy::too_many_arguments)]
fn connect_enum_instantiation<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    enum_decl: &ty::TyEnumDeclaration,
    contents: &Option<Box<ty::TyExpression>>,
    variant_name: &Ident,
    graph: &mut ControlFlowGraph<'cfg>,
    leaves: &[NodeIndex],
    exit_node: Option<NodeIndex>,
    tree_type: &TreeType,
    options: NodeConnectionOptions,
) -> Result<Vec<NodeIndex>, CompileError> {
    let enum_name = &enum_decl.name;
    let (decl_ix, variant_index) = graph
        .namespace
        .find_enum_variant_index(enum_name, variant_name)
        .unwrap_or_else(|| {
            let node_idx = graph.add_node(
                engines,
                format!(
                    "extern enum {}::{}",
                    enum_name.as_str(),
                    variant_name.as_str()
                )
                .into(),
            );
            (node_idx, node_idx)
        });

    // insert organizational nodes for instantiation of enum
    let enum_instantiation_entry_idx = graph.add_node(engines, "enum instantiation entry".into());
    let enum_instantiation_exit_idx = graph.add_node(engines, "enum instantiation exit".into());

    // connect to declaration node itself to show that the declaration is used
    graph.add_edge(enum_instantiation_entry_idx, decl_ix, "".into());
    for leaf in leaves {
        graph.add_edge(*leaf, enum_instantiation_entry_idx, "".into());
    }

    // add edge from the entry of the enum instantiation to the body of the instantiation
    if let Some(instantiator) = contents {
        let instantiator_contents = connect_expression(
            engines,
            &instantiator.expression,
            graph,
            &[enum_instantiation_entry_idx],
            exit_node,
            "",
            tree_type,
            enum_decl.span.clone(),
            options,
        )?;
        for leaf in instantiator_contents {
            graph.add_edge(leaf, enum_instantiation_exit_idx, "".into());
        }
    }

    graph.add_edge(decl_ix, variant_index, "".into());
    graph.add_edge(variant_index, enum_instantiation_exit_idx, "".into());

    Ok(vec![enum_instantiation_exit_idx])
}

/// Given a [ty::TyAstNode] that we know is not reached in the graph, construct a warning
/// representing its unreached status. For example, we want to say "this function is never called"
/// if the node is a function declaration, but "this trait is never used" if it is a trait
/// declaration.
fn construct_dead_code_warning_from_node(
    decl_engine: &DeclEngine,
    node: &ty::TyAstNode,
) -> Option<CompileWarning> {
    Some(match node {
        // if this is a function, struct, or trait declaration that is never called, then it is dead
        // code.
        ty::TyAstNode {
            content:
                ty::TyAstNodeContent::Declaration(ty::TyDeclaration::FunctionDeclaration(decl_id)),
            span,
        } => {
            let warning_span = match decl_engine.get_function(decl_id.clone(), span) {
                Ok(ty::TyFunctionDeclaration { name, .. }) => name.span(),
                Err(_) => span.clone(),
            };
            CompileWarning {
                span: warning_span,
                warning_content: Warning::DeadFunctionDeclaration,
            }
        }
        ty::TyAstNode {
            content:
                ty::TyAstNodeContent::Declaration(ty::TyDeclaration::StructDeclaration(decl_id)),
            span,
        } => {
            let warning_span = match decl_engine.get_struct(decl_id.clone(), span) {
                Ok(ty::TyStructDeclaration { name, .. }) => name.span(),
                Err(_) => span.clone(),
            };
            CompileWarning {
                span: warning_span,
                warning_content: Warning::DeadStructDeclaration,
            }
        }
        ty::TyAstNode {
            content: ty::TyAstNodeContent::Declaration(ty::TyDeclaration::EnumDeclaration(decl_id)),
            span,
        } => {
            let warning_span = match decl_engine.get_enum(decl_id.clone(), span) {
                Ok(ty::TyEnumDeclaration { name, .. }) => name.span(),
                Err(_) => span.clone(),
            };
            CompileWarning {
                span: warning_span,
                warning_content: Warning::DeadEnumDeclaration,
            }
        }
        ty::TyAstNode {
            content: ty::TyAstNodeContent::Declaration(ty::TyDeclaration::TraitDeclaration(decl_id)),
            span,
        } => {
            let warning_span = match decl_engine.get_trait(decl_id.clone(), span) {
                Ok(ty::TyTraitDeclaration { name, .. }) => name.span(),
                Err(_) => span.clone(),
            };
            CompileWarning {
                span: warning_span,
                warning_content: Warning::DeadTrait,
            }
        }
        ty::TyAstNode {
            content: ty::TyAstNodeContent::Declaration(ty::TyDeclaration::ImplTrait(decl_id)),
            span,
        } => match decl_engine.get_impl_trait(decl_id.clone(), span) {
            Ok(ty::TyImplTrait { methods, .. }) if methods.is_empty() => return None,
            _ => CompileWarning {
                span: span.clone(),
                warning_content: Warning::DeadDeclaration,
            },
        },
        ty::TyAstNode {
            content: ty::TyAstNodeContent::Declaration(ty::TyDeclaration::AbiDeclaration { .. }),
            ..
        } => return None,
        // We handle storage fields individually. There is no need to emit any warnings for the
        // storage declaration itself.
        ty::TyAstNode {
            content: ty::TyAstNodeContent::Declaration(ty::TyDeclaration::StorageDeclaration { .. }),
            ..
        } => return None,
        ty::TyAstNode {
            content: ty::TyAstNodeContent::Declaration(..),
            span,
        } => CompileWarning {
            span: span.clone(),
            warning_content: Warning::DeadDeclaration,
        },
        // Otherwise, this is unreachable.
        ty::TyAstNode {
            span,
            content:
                ty::TyAstNodeContent::ImplicitReturnExpression(_)
                | ty::TyAstNodeContent::Expression(_)
                | ty::TyAstNodeContent::SideEffect,
        } => CompileWarning {
            span: span.clone(),
            warning_content: Warning::UnreachableCode,
        },
    })
}

fn connect_storage_declaration<'eng: 'cfg, 'cfg>(
    engines: Engines<'eng>,
    decl: &ty::TyStorageDeclaration,
    graph: &mut ControlFlowGraph<'cfg>,
    _entry_node: NodeIndex,
    _tree_type: &TreeType,
) {
    let ty::TyStorageDeclaration { fields, .. } = decl;
    let field_nodes = fields
        .iter()
        .map(|field| (field.clone(), graph.add_node(engines, field.into())))
        .collect::<Vec<_>>();

    graph.namespace.insert_storage(field_nodes);
}