fluidattacks-blends 0.4.0

Blends imperative shell: parsing, AST-graph construction, serialization
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
//! Top-level orchestration: a path to its set of graphs.

use std::path::Path;

use blends_domain::graph_set::GraphSet;

use crate::ast::get_ast_graph;
use crate::content::Content;
use crate::syntax::get_syntax_graph;

#[must_use]
pub fn get_graphs_from_path(
    path: &Path,
    with_cfg: Option<bool>,
    with_metadata: Option<bool>,
) -> GraphSet {
    let Some(content) = Content::from_path(path, None) else {
        return GraphSet::default();
    };

    let Some(ast) = get_ast_graph(&content) else {
        return GraphSet::default();
    };

    let Some(syntax) = get_syntax_graph(&ast, &content, with_cfg, with_metadata) else {
        return GraphSet {
            ast: Some(ast),
            syntax: None,
        };
    };

    GraphSet {
        ast: Some(ast),
        syntax: Some(syntax),
    }
}

#[cfg(test)]
mod tests {
    use super::get_graphs_from_path;
    use blends_domain::ast::AstGraph;
    use blends_domain::syntax::{
        FileInstanceData, FileStructData, FileStructValue, SyntaxEdge, SyntaxGraph, SyntaxNode,
    };
    use blends_domain::Ast;
    use blends_domain::NodeId;
    use serde_json::{Map, Value};
    use std::collections::{BTreeMap, BTreeSet};
    use std::fs;
    use std::path::{Path, PathBuf};
    use test_case::test_case;

    fn fixtures_dir() -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test/data/test_files/syntax_graph")
    }

    fn results_dir() -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test/data/results")
    }

    fn output_dir() -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test/data/output")
    }

    fn sorted_object(attrs: BTreeMap<String, Value>) -> Value {
        let mut map = Map::new();
        for (key, value) in attrs {
            map.insert(key, value);
        }
        Value::Object(map)
    }

    fn export_ast_graph_as_json(graph: &AstGraph) -> Value {
        let mut nodes = Map::new();
        for (id, node) in &graph.nodes {
            let mut attrs = BTreeMap::new();
            attrs.insert("label_l".to_owned(), Value::from(node.line.to_string()));
            attrs.insert("label_c".to_owned(), Value::from(node.col.to_string()));
            attrs.insert("label_type".to_owned(), Value::from(node.kind.clone()));
            if let Some(text) = &node.text {
                attrs.insert("label_text".to_owned(), Value::from(text.clone()));
            }
            for (name, child) in &node.fields {
                attrs.insert(name.clone(), Value::from(child.0));
            }
            nodes.insert(id.0.to_string(), sorted_object(attrs));
        }

        let mut edges = Map::new();
        for (from, targets) in &graph.edges {
            let mut inner = Map::new();
            for (to, edge) in targets {
                let mut attrs = BTreeMap::new();
                let Ast = edge.kind;
                attrs.insert("label_ast".to_owned(), Value::from("AST"));
                attrs.insert(
                    "label_index".to_owned(),
                    Value::from(edge.index.to_string()),
                );
                inner.insert(to.0.to_string(), sorted_object(attrs));
            }
            edges.insert(from.0.to_string(), Value::Object(inner));
        }

        let mut root = BTreeMap::new();
        root.insert("edges".to_owned(), Value::Object(edges));
        root.insert("nodes".to_owned(), Value::Object(nodes));
        sorted_object(root)
    }

    fn file_struct_to_json(data: &FileStructData) -> Value {
        let mut attrs = BTreeMap::new();
        attrs.insert("node".to_owned(), Value::from(data.node.0));
        attrs.insert("type".to_owned(), Value::from(data.kind.clone()));
        attrs.insert(
            "data".to_owned(),
            match &data.data {
                FileStructValue::MethodName(name) => Value::from(name.clone()),
                FileStructValue::Children(children) => struct_children_to_json(children),
            },
        );
        if let Some(node_range) = &data.node_range {
            attrs.insert(
                "node_range".to_owned(),
                Value::from(node_range.iter().map(|id| id.0).collect::<Vec<_>>()),
            );
        }
        sorted_object(attrs)
    }

    fn struct_children_to_json(children: &BTreeMap<String, FileStructData>) -> Value {
        let mut map = Map::new();
        for (name, data) in children {
            map.insert(name.clone(), file_struct_to_json(data));
        }
        Value::Object(map)
    }

    fn instances_to_json(
        instances: &BTreeMap<String, BTreeMap<String, FileInstanceData>>,
    ) -> Value {
        let mut classes = Map::new();
        for (class_name, class_instances) in instances {
            let mut variables = Map::new();
            for (variable_name, data) in class_instances {
                let mut fields = BTreeMap::new();
                fields.insert("object".to_owned(), Value::from(data.object.clone()));
                fields.insert("source".to_owned(), Value::from(data.source.clone()));
                fields.insert(
                    "source_type".to_owned(),
                    Value::from(data.source_type.clone()),
                );
                variables.insert(variable_name.clone(), sorted_object(fields));
            }
            classes.insert(class_name.clone(), Value::Object(variables));
        }
        Value::Object(classes)
    }

    #[allow(
        clippy::too_many_lines,
        reason = "exhaustive per-variant attribute export; grows with each migrated node type"
    )]
    fn syntax_node_attrs(node: &SyntaxNode) -> BTreeMap<String, Value> {
        let mut attrs = BTreeMap::new();
        attrs.insert("label_type".to_owned(), Value::from(node.label_type()));
        match node {
            SyntaxNode::Argument
            | SyntaxNode::ArgumentList
            | SyntaxNode::ArrayInitializer
            | SyntaxNode::Break
            | SyntaxNode::CatchDeclaration
            | SyntaxNode::ClassBody
            | SyntaxNode::Continue
            | SyntaxNode::DeclarationBlock
            | SyntaxNode::ExecutionBlock
            | SyntaxNode::ExpressionStatement
            | SyntaxNode::File
            | SyntaxNode::JsxElement
            | SyntaxNode::Modifiers
            | SyntaxNode::ParameterList
            | SyntaxNode::ParenthesizedExpression
            | SyntaxNode::SwitchBody => {}
            SyntaxNode::If {
                condition_id,
                true_id,
                false_id,
                initializer,
            } => {
                attrs.insert("condition_id".to_owned(), Value::from(condition_id.0));
                if let Some(true_id) = true_id {
                    attrs.insert("true_id".to_owned(), Value::from(true_id.0));
                }
                if let Some(false_id) = false_id {
                    attrs.insert("false_id".to_owned(), Value::from(false_id.0));
                }
                if let Some(initializer) = initializer {
                    attrs.insert("initializer_id".to_owned(), Value::from(initializer.0));
                }
            }
            SyntaxNode::ForStatement {
                block_id,
                initializer_id,
                condition_id,
                update_id,
            } => {
                attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                if let Some(initializer_id) = initializer_id {
                    attrs.insert("initializer_id".to_owned(), Value::from(initializer_id.0));
                }
                if let Some(condition_id) = condition_id {
                    attrs.insert("condition_id".to_owned(), Value::from(condition_id.0));
                }
                if let Some(update_id) = update_id {
                    attrs.insert("update_id".to_owned(), Value::from(update_id.0));
                }
            }
            SyntaxNode::ForEachStatement {
                variable_id,
                iterable_item_id,
                block_id,
            } => {
                attrs.insert("variable_id".to_owned(), Value::from(variable_id.0));
                attrs.insert(
                    "iterable_item_id".to_owned(),
                    Value::from(iterable_item_id.0),
                );
                if let Some(block_id) = block_id {
                    attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                }
            }
            SyntaxNode::SwitchStatement { block_id, value_id } => {
                attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                attrs.insert("value_id".to_owned(), Value::from(value_id.0));
            }
            SyntaxNode::TernaryOperation {
                condition_id,
                true_id,
                false_id,
            } => {
                attrs.insert("condition_id".to_owned(), Value::from(condition_id.0));
                attrs.insert("true_id".to_owned(), Value::from(true_id.0));
                attrs.insert("false_id".to_owned(), Value::from(false_id.0));
            }
            SyntaxNode::SwitchSection { case_expression } => {
                attrs.insert(
                    "case_expression".to_owned(),
                    Value::from(case_expression.clone()),
                );
            }
            SyntaxNode::DoStatement {
                block_id,
                condition_id,
            } => {
                attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                attrs.insert("condition_id".to_owned(), Value::from(condition_id.0));
            }
            SyntaxNode::MethodInvocation {
                expression,
                object,
                symbol_scope,
                expression_id,
                arguments_id,
                object_id,
                block_id,
                receiver_type_fqn,
            } => {
                attrs.insert("expression".to_owned(), Value::from(expression.clone()));
                if let Some(object) = object {
                    attrs.insert("object".to_owned(), Value::from(object.clone()));
                }
                if let Some(symbol_scope) = symbol_scope {
                    attrs.insert("symbol_scope".to_owned(), Value::from(symbol_scope.0));
                }
                if let Some(expression_id) = expression_id {
                    attrs.insert("expression_id".to_owned(), Value::from(expression_id.0));
                }
                if let Some(arguments_id) = arguments_id {
                    attrs.insert("arguments_id".to_owned(), Value::from(arguments_id.0));
                }
                if let Some(object_id) = object_id {
                    attrs.insert("object_id".to_owned(), Value::from(object_id.0));
                }
                if let Some(block_id) = block_id {
                    attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                }
                if let Some(receiver_type_fqn) = receiver_type_fqn {
                    attrs.insert(
                        "receiver_type_fqn".to_owned(),
                        Value::from(receiver_type_fqn.clone()),
                    );
                }
            }
            SyntaxNode::ReservedWord { value } | SyntaxNode::This { value } => {
                attrs.insert("value".to_owned(), Value::from(value.clone()));
            }
            SyntaxNode::Attribute { name } => {
                attrs.insert("name".to_owned(), Value::from(name.clone()));
            }
            SyntaxNode::Import {
                expression,
                alias,
                method_name,
                import_type,
            } => {
                if let Some(expression) = expression {
                    attrs.insert("expression".to_owned(), Value::from(expression.clone()));
                }
                if let Some(alias) = alias {
                    attrs.insert("label_alias".to_owned(), Value::from(alias.clone()));
                }
                if let Some(method_name) = method_name {
                    attrs.insert("method_name".to_owned(), Value::from(method_name.clone()));
                }
                if let Some(import_type) = import_type {
                    attrs.insert("import_type".to_owned(), Value::from(import_type.clone()));
                }
            }
            SyntaxNode::UsingStatement {
                block_id,
                declaration_id,
            } => {
                attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                if let Some(declaration_id) = declaration_id {
                    attrs.insert("declaration_id".to_owned(), Value::from(declaration_id.0));
                }
            }
            SyntaxNode::ObjectCreation {
                name,
                arguments_id,
                initializer_id,
            } => {
                attrs.insert("name".to_owned(), Value::from(name.clone()));
                if let Some(arguments_id) = arguments_id {
                    attrs.insert("arguments_id".to_owned(), Value::from(arguments_id.0));
                }
                if let Some(initializer_id) = initializer_id {
                    attrs.insert("initializer_id".to_owned(), Value::from(initializer_id.0));
                }
            }
            SyntaxNode::BinaryOperation {
                operator,
                left_id,
                right_id,
            } => {
                attrs.insert("operator".to_owned(), Value::from(operator.clone()));
                if let Some(left_id) = left_id {
                    attrs.insert("left_id".to_owned(), Value::from(left_id.0));
                }
                if let Some(right_id) = right_id {
                    attrs.insert("right_id".to_owned(), Value::from(right_id.0));
                }
            }
            SyntaxNode::NamedArgument {
                value_id,
                argument_name,
            } => {
                attrs.insert("value_id".to_owned(), Value::from(value_id.0));
                if let Some(argument_name) = argument_name {
                    attrs.insert(
                        "argument_name".to_owned(),
                        Value::from(argument_name.clone()),
                    );
                }
            }
            SyntaxNode::UnaryExpression {
                operator,
                operand_id,
            } => {
                attrs.insert("operator".to_owned(), Value::from(operator.clone()));
                attrs.insert("operand_id".to_owned(), Value::from(operand_id.0));
            }
            SyntaxNode::Assignment {
                variable_id,
                value_id,
                operator,
            } => {
                attrs.insert("variable_id".to_owned(), Value::from(variable_id.0));
                if let Some(value_id) = value_id {
                    attrs.insert("value_id".to_owned(), Value::from(value_id.0));
                }
                if let Some(operator) = operator {
                    attrs.insert("operator".to_owned(), Value::from(operator.clone()));
                }
            }
            SyntaxNode::MemberAccess {
                member,
                expression,
                expression_id,
                symbol_scope,
            } => {
                attrs.insert("member".to_owned(), Value::from(member.clone()));
                attrs.insert("expression".to_owned(), Value::from(expression.clone()));
                attrs.insert("expression_id".to_owned(), Value::from(expression_id.0));
                if let Some(symbol_scope) = symbol_scope {
                    attrs.insert("symbol_scope".to_owned(), Value::from(symbol_scope.0));
                }
            }
            SyntaxNode::ElementAccess {
                expression_id,
                arguments_id,
            } => {
                attrs.insert("expression_id".to_owned(), Value::from(expression_id.0));
                if let Some(arguments_id) = arguments_id {
                    attrs.insert("arguments_id".to_owned(), Value::from(arguments_id.0));
                }
            }
            SyntaxNode::AwaitExpression { expression_id } => {
                attrs.insert("expression_id".to_owned(), Value::from(expression_id.0));
            }
            SyntaxNode::Annotation { name, arguments_id } => {
                attrs.insert("name".to_owned(), Value::from(name.clone()));
                if let Some(arguments_id) = arguments_id {
                    attrs.insert("arguments_id".to_owned(), Value::from(arguments_id.0));
                }
            }
            SyntaxNode::Return { value_id } => {
                if let Some(value_id) = value_id {
                    attrs.insert("value_id".to_owned(), Value::from(value_id.0));
                }
            }
            SyntaxNode::ThrowStatement { expression_id } => {
                if let Some(expression_id) = expression_id {
                    attrs.insert("expression_id".to_owned(), Value::from(expression_id.0));
                }
            }
            SyntaxNode::WhileStatement {
                block_id,
                condition_id,
            } => {
                attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                if let Some(condition_id) = condition_id {
                    attrs.insert("condition_id".to_owned(), Value::from(condition_id.0));
                }
            }
            SyntaxNode::ElseClause { block_id } => {
                attrs.insert("block_id".to_owned(), Value::from(block_id.0));
            }
            SyntaxNode::RestPattern { value_id } | SyntaxNode::SpreadElement { value_id } => {
                attrs.insert("value_id".to_owned(), Value::from(value_id.0));
            }
            SyntaxNode::TryStatement {
                block_id,
                resources_id,
            } => {
                attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                if let Some(resources_id) = resources_id {
                    attrs.insert("resources_id".to_owned(), Value::from(resources_id.0));
                }
            }
            SyntaxNode::CatchClause {
                block_id,
                catch_declaration,
            } => {
                if let Some(block_id) = block_id {
                    attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                }
                if let Some(catch_declaration) = catch_declaration {
                    attrs.insert(
                        "catch_declaration".to_owned(),
                        Value::from(catch_declaration.0),
                    );
                }
            }
            SyntaxNode::FinallyClause { block_id } => {
                if let Some(block_id) = block_id {
                    attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                }
            }
            SyntaxNode::Class {
                name,
                block_id,
                modifiers_id,
                inherited_class,
                access_modifiers,
            } => {
                attrs.insert("name".to_owned(), Value::from(name.clone()));
                if let Some(block_id) = block_id {
                    attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                }
                if let Some(modifiers_id) = modifiers_id {
                    attrs.insert("modifiers_id".to_owned(), Value::from(modifiers_id.0));
                }
                if let Some(inherited_class) = inherited_class {
                    attrs.insert(
                        "inherited_class".to_owned(),
                        Value::from(inherited_class.clone()),
                    );
                }
                if let Some(access_modifiers) = access_modifiers {
                    attrs.insert(
                        "access_modifiers".to_owned(),
                        Value::from(access_modifiers.clone()),
                    );
                }
            }
            SyntaxNode::Comment { comment } => {
                attrs.insert("comment".to_owned(), Value::from(comment.clone()));
            }
            SyntaxNode::Literal { value, value_type } => {
                attrs.insert("value".to_owned(), Value::from(value.clone()));
                attrs.insert("value_type".to_owned(), Value::from(value_type.clone()));
            }
            SyntaxNode::Metadata {
                path,
                structure,
                instances,
                imports,
                package,
            } => {
                attrs.insert("path".to_owned(), Value::from(path.clone()));
                attrs.insert("structure".to_owned(), struct_children_to_json(structure));
                attrs.insert("instances".to_owned(), instances_to_json(instances));
                attrs.insert("imports".to_owned(), Value::from(imports.clone()));
                if let Some(package) = package {
                    attrs.insert("package".to_owned(), Value::from(package.clone()));
                }
            }
            SyntaxNode::MethodDeclaration {
                name,
                access_modifiers,
                block_id,
                modifiers_id,
                parameters_id,
            } => {
                if let Some(name) = name {
                    attrs.insert("name".to_owned(), Value::from(name.clone()));
                }
                if let Some(access_modifiers) = access_modifiers {
                    attrs.insert(
                        "access_modifiers".to_owned(),
                        Value::from(access_modifiers.clone()),
                    );
                }
                if let Some(block_id) = block_id {
                    attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                }
                if let Some(modifiers_id) = modifiers_id {
                    attrs.insert("modifiers_id".to_owned(), Value::from(modifiers_id.0));
                }
                if let Some(parameters_id) = parameters_id {
                    attrs.insert("parameters_id".to_owned(), Value::from(parameters_id.0));
                }
            }
            SyntaxNode::MissingNode { node_type } => {
                attrs.insert("node_type".to_owned(), Value::from(node_type.clone()));
            }
            SyntaxNode::Namespace { name, block_id } => {
                attrs.insert("name".to_owned(), Value::from(name.clone()));
                if let Some(block_id) = block_id {
                    attrs.insert("block_id".to_owned(), Value::from(block_id.0));
                }
            }
            SyntaxNode::NewExpression {
                constructor_id,
                arguments_id,
            } => {
                attrs.insert("constructor_id".to_owned(), Value::from(constructor_id.0));
                if let Some(arguments_id) = arguments_id {
                    attrs.insert("arguments_id".to_owned(), Value::from(arguments_id.0));
                }
            }
            SyntaxNode::Object { name, tf_reference } => {
                if let Some(name) = name {
                    attrs.insert("name".to_owned(), Value::from(name.clone()));
                }
                if let Some(tf_reference) = tf_reference {
                    attrs.insert("tf_reference".to_owned(), Value::from(tf_reference.clone()));
                }
            }
            SyntaxNode::Parameter {
                variable,
                variable_type,
                value_id,
                parameter_mode,
            } => {
                if let Some(variable) = variable {
                    attrs.insert("variable".to_owned(), Value::from(variable.clone()));
                }
                if let Some(variable_type) = variable_type {
                    attrs.insert(
                        "variable_type".to_owned(),
                        Value::from(variable_type.clone()),
                    );
                }
                if let Some(value_id) = value_id {
                    attrs.insert("value_id".to_owned(), Value::from(value_id.0));
                }
                if let Some(parameter_mode) = parameter_mode {
                    attrs.insert(
                        "parameter_mode".to_owned(),
                        Value::from(parameter_mode.clone()),
                    );
                }
            }
            SyntaxNode::VariableDeclaration {
                variable,
                variable_type,
                value_id,
                variable_id: _,
                access_modifier,
            } => {
                attrs.insert("variable".to_owned(), Value::from(variable.clone()));
                if let Some(variable_type) = variable_type {
                    attrs.insert(
                        "variable_type".to_owned(),
                        Value::from(variable_type.clone()),
                    );
                }
                if let Some(value_id) = value_id {
                    attrs.insert("value_id".to_owned(), Value::from(value_id.0));
                }
                if let Some(access_modifier) = access_modifier {
                    attrs.insert(
                        "access_modifier".to_owned(),
                        Value::from(access_modifier.clone()),
                    );
                }
            }
            SyntaxNode::Pair { key_id, value_id } => {
                attrs.insert("key_id".to_owned(), Value::from(key_id.0));
                attrs.insert("value_id".to_owned(), Value::from(value_id.0));
            }
            SyntaxNode::SymbolLookup {
                symbol,
                symbol_scope,
                value,
            } => {
                attrs.insert("symbol".to_owned(), Value::from(symbol.clone()));
                if let Some(scope) = symbol_scope {
                    attrs.insert("symbol_scope".to_owned(), Value::from(scope.0));
                }
                if let Some(value) = value {
                    attrs.insert("value".to_owned(), Value::from(value.clone()));
                }
            }
            SyntaxNode::ModuleImport { expression, alias } => {
                attrs.insert("expression".to_owned(), Value::from(expression.clone()));
                if let Some(alias) = alias {
                    attrs.insert("label_alias".to_owned(), Value::from(alias.clone()));
                }
            }
            other => panic!("syntax export not implemented for {}", other.label_type()),
        }
        attrs
    }

    fn syntax_edge_attrs(edge: SyntaxEdge) -> BTreeMap<String, Value> {
        let mut attrs = BTreeMap::new();
        if edge.ast.is_some() {
            attrs.insert("label_ast".to_owned(), Value::from("AST"));
        }
        if edge.cfg.is_some() {
            attrs.insert("label_cfg".to_owned(), Value::from("CFG"));
        }
        attrs
    }

    fn export_syntax_graph_as_json(graph: &SyntaxGraph) -> Value {
        let mut nodes = Map::new();
        for (id, node) in &graph.nodes {
            nodes.insert(id.0.to_string(), sorted_object(syntax_node_attrs(node)));
        }

        let mut edges = Map::new();
        for (from, targets) in &graph.edges {
            let mut inner = Map::new();
            for (to, edge) in targets {
                inner.insert(to.0.to_string(), sorted_object(syntax_edge_attrs(*edge)));
            }
            edges.insert(from.0.to_string(), Value::Object(inner));
        }

        let mut root = BTreeMap::new();
        root.insert("edges".to_owned(), Value::Object(edges));
        root.insert("nodes".to_owned(), Value::Object(nodes));
        sorted_object(root)
    }

    #[test]
    fn empty_set_for_unsupported_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.unknown");
        fs::write(&path, b"whatever").unwrap();

        assert!(get_graphs_from_path(&path, None, None).ast.is_none());
    }

    #[test]
    fn empty_set_for_malformed_supported_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.java");
        fs::write(&path, b"class A {").unwrap();

        assert!(get_graphs_from_path(&path, None, None).ast.is_none());
    }

    fn rename_field_key(key: &str) -> String {
        key.strip_prefix("label_field_")
            .map_or_else(|| key.to_owned(), |field| format!("{field}_id"))
    }

    fn rename_node_attrs(attrs: &Value) -> Value {
        let Some(attrs) = attrs.as_object() else {
            return attrs.clone();
        };
        let mut renamed = Map::new();
        for (key, value) in attrs {
            renamed.insert(rename_field_key(key), value.clone());
        }
        Value::Object(renamed)
    }

    // The python golden keys node fields as `label_field_<field>`; the Rust engine
    // keys them as `<field>_id`. Rewrite the golden's keys in memory so the two
    // graphs compare on content. The `results/` file on disk is untouched.
    fn normalize_field_keys(graph: &Value) -> Value {
        let mut nodes = Map::new();
        if let Some(original) = graph.get("nodes").and_then(Value::as_object) {
            for (id, attrs) in original {
                nodes.insert(id.clone(), rename_node_attrs(attrs));
            }
        }

        let mut result = Map::new();
        if let Some(edges) = graph.get("edges") {
            result.insert("edges".to_owned(), edges.clone());
        }
        result.insert("nodes".to_owned(), Value::Object(nodes));
        Value::Object(result)
    }

    fn write_rust_output(suffix: &str, relative: &str, ast: &Value, syntax: Option<&Value>) {
        let mut entry = Map::new();
        entry.insert("graph".to_owned(), ast.clone());
        if let Some(syntax) = syntax {
            entry.insert("syntax_graph".to_owned(), syntax.clone());
        }
        let mut by_path = Map::new();
        by_path.insert(relative.to_owned(), Value::Object(entry));
        let mut root = Map::new();
        root.insert("graphs".to_owned(), Value::Object(by_path));

        let pretty = serde_json::to_string_pretty(&Value::Object(root)).expect("serialize output");
        let dir = output_dir();
        fs::create_dir_all(&dir).expect("create output dir");
        fs::write(dir.join(format!("root-graph_{suffix}.json")), pretty).expect("write output");
    }

    fn section(graph: &Value, key: &str) -> Map<String, Value> {
        graph
            .get(key)
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default()
    }

    // The python golden dumps the ast after the syntax readers run, and some
    // readers overwrite `label_l` (c# class/method declaration take the line of
    // their identifier). Until those readers exist in rust, drop only `label_l`
    // on those node types from both sides, so just the mutated line is ignored
    // while every other attribute (line column, type, fields) is still compared.
    fn ignore_line_for(nodes: Map<String, Value>, skip_types: &[&str]) -> Map<String, Value> {
        nodes
            .into_iter()
            .map(|(id, mut attrs)| {
                let skip = attrs
                    .get("label_type")
                    .and_then(Value::as_str)
                    .is_some_and(|kind| skip_types.contains(&kind));
                if let Some(node) = attrs.as_object_mut().filter(|_| skip) {
                    node.remove("label_l");
                }
                (id, attrs)
            })
            .collect()
    }

    // Concise per-entry diff: only the ids whose content differs, rust vs python.
    fn diff_section(
        kind: &str,
        rust: &Map<String, Value>,
        python: &Map<String, Value>,
    ) -> Vec<String> {
        let mut diffs = Vec::new();
        for (id, rust_entry) in rust {
            match python.get(id) {
                None => diffs.push(format!(
                    "{kind} {id}: in rust output, missing in python golden"
                )),
                Some(python_entry) if python_entry != rust_entry => diffs.push(format!(
                    "{kind} {id} differs:\n  rust:   {rust_entry}\n  python: {python_entry}"
                )),
                Some(_) => {}
            }
        }
        for id in python.keys() {
            if !rust.contains_key(id) {
                diffs.push(format!(
                    "{kind} {id}: in python golden, missing in rust output"
                ));
            }
        }
        diffs
    }

    const MAX_REPORTED_DIFFS: usize = 30;

    // Fixture suffixes whose language has no rust syntax dispatcher yet.
    const SYNTAX_NOT_YET_MIGRATED: &[&str] = &[
        "elixir", "go", "hcl", "kotlin", "php", "ruby", "rust", "scala", "swift",
    ];

    // Fixture suffixes whose language dispatcher exists but still degrades
    // some node types to MissingNode: implemented nodes compare exactly,
    // diffs anchored at the missing placeholders are ignored.
    const SYNTAX_IN_PROGRESS: &[&str] = &["javascript", "typescript"];

    fn ast_diffs(rust_ast: &Value, golden: &Value, suffix: &str) -> Vec<String> {
        let expected = golden
            .get("graph")
            .map(normalize_field_keys)
            .expect("locate graph block in python golden");

        // c# alone has syntax readers that overwrite `label_l` on class/method
        // declarations; ignore that attribute only for c#, never other languages.
        let line_skip: &[&str] = match suffix {
            "c_sharp" => &["class_declaration", "method_declaration"],
            _ => &[],
        };
        let mut diffs = diff_section(
            "node",
            &ignore_line_for(section(rust_ast, "nodes"), line_skip),
            &ignore_line_for(section(&expected, "nodes"), line_skip),
        );
        diffs.extend(diff_section(
            "edge",
            &section(rust_ast, "edges"),
            &section(&expected, "edges"),
        ));
        diffs
    }

    fn syntax_diffs(generated_syntax: &Value, golden: &Value) -> Vec<String> {
        let expected = golden
            .get("syntax_graph")
            .cloned()
            .expect("locate syntax_graph block in python golden");

        let mut diffs = diff_section(
            "syntax node",
            &section(generated_syntax, "nodes"),
            &section(&expected, "nodes"),
        );
        diffs.extend(diff_section(
            "syntax edge",
            &section(generated_syntax, "edges"),
            &section(&expected, "edges"),
        ));
        diffs
    }

    // The ids the rust engine degraded to MissingNode: subtrees whose reader
    // is pending, plus punctuation children the python readers consumed
    // without creating a syntax node.
    fn missing_ids(generated_syntax: &Value) -> BTreeSet<String> {
        section(generated_syntax, "nodes")
            .into_iter()
            .filter(|(_, attrs)| {
                attrs.get("label_type").and_then(Value::as_str) == Some("MissingNode")
            })
            .map(|(id, _)| id)
            .collect()
    }

    fn edge_target_ids(edges: &Map<String, Value>, from: &str) -> Vec<String> {
        edges
            .get(from)
            .and_then(Value::as_object)
            .map(|targets| targets.keys().cloned().collect())
            .unwrap_or_default()
    }

    fn pending_subtree_ids(generated_syntax: &Value) -> BTreeSet<String> {
        let edges = section(generated_syntax, "edges");
        let mut skip = missing_ids(generated_syntax);
        let mut stack: Vec<String> = skip.iter().cloned().collect();
        while let Some(from) = stack.pop() {
            let fresh: Vec<String> = edge_target_ids(&edges, &from)
                .into_iter()
                .filter(|to| skip.insert(to.clone()))
                .collect();
            stack.extend(fresh);
        }
        skip
    }

    fn drop_missing_nodes(
        nodes: Map<String, Value>,
        skip: &BTreeSet<String>,
    ) -> Map<String, Value> {
        nodes
            .into_iter()
            .filter(|(id, _)| !skip.contains(id))
            .collect()
    }

    fn drop_missing_targets(targets: &Value, skip: &BTreeSet<String>) -> Map<String, Value> {
        targets
            .as_object()
            .cloned()
            .unwrap_or_default()
            .into_iter()
            .filter(|(to, _)| !skip.contains(to))
            .collect()
    }

    fn drop_missing_edges(
        edges: Map<String, Value>,
        skip: &BTreeSet<String>,
    ) -> Map<String, Value> {
        edges
            .into_iter()
            .filter(|(from, _)| !skip.contains(from))
            .map(|(from, targets)| (from, drop_missing_targets(&targets, skip)))
            .filter(|(_, kept)| !kept.is_empty())
            .map(|(from, kept)| (from, Value::Object(kept)))
            .collect()
    }

    // In-progress compare: everything not anchored at a MissingNode id must
    // match the golden exactly, on both sides — a golden-only entry between
    // implemented nodes is still a real diff.
    fn syntax_diffs_partial(generated_syntax: &Value, golden: &Value) -> Vec<String> {
        let expected = golden
            .get("syntax_graph")
            .cloned()
            .expect("locate syntax_graph block in python golden");
        let skip = pending_subtree_ids(generated_syntax);

        let mut diffs = diff_section(
            "syntax node",
            &drop_missing_nodes(section(generated_syntax, "nodes"), &skip),
            &drop_missing_nodes(section(&expected, "nodes"), &skip),
        );
        diffs.extend(diff_section(
            "syntax edge",
            &drop_missing_edges(section(generated_syntax, "edges"), &skip),
            &drop_missing_edges(section(&expected, "edges"), &skip),
        ));
        diffs
    }

    #[test_case("c_sharp.cs", "c_sharp")]
    #[test_case("elixir.ex", "elixir")]
    #[test_case("go.go", "go")]
    #[test_case("terraform.tf", "hcl")]
    #[test_case("java.java", "java")]
    #[test_case("javascript.js", "javascript")]
    #[test_case("json.json", "json")]
    #[test_case("kotlin.kt", "kotlin")]
    #[test_case("python.py", "python")]
    #[test_case("php.php", "php")]
    #[test_case("ruby.rb", "ruby")]
    #[test_case("rust.rs", "rust")]
    #[test_case("scala.scala", "scala")]
    #[test_case("swift.swift", "swift")]
    #[test_case("syntax_cfg.ts", "typescript")]
    #[test_case("yaml.yaml", "yaml")]
    #[test_case("templates/helm_configmap.yaml", "helm_configmap_yaml")]
    #[test_case("templates/helm_configmap.json", "helm_configmap_json")]
    #[test_case("flow_mapping.yaml", "flow_mapping")]
    #[test_case("flow_sequence.yaml", "flow_sequence")]
    fn graph_generation(test_file: &str, suffix: &str) {
        let path = fixtures_dir().join(test_file);
        let graph_set = get_graphs_from_path(&path, None, None);

        assert!(
            !(SYNTAX_NOT_YET_MIGRATED.contains(&suffix) && SYNTAX_IN_PROGRESS.contains(&suffix)),
            "suffix {suffix} cannot be pending and in progress at the same time"
        );
        assert_eq!(
            graph_set.syntax.is_none(),
            SYNTAX_NOT_YET_MIGRATED.contains(&suffix),
            "\n[Syntax Parity Error] Inconsistency detected for language extension: .{suffix}\n\
             - Was syntax graph generated (None)? -> {}\n\
             - Is it marked as pending in SYNTAX_NOT_YET_MIGRATED? -> {}\n\
             👉 Hint: If it was generated but is marked as pending, move '.{suffix}' to \
             SYNTAX_IN_PROGRESS (partial compare) or drop it from both lists (strict compare).\n\
             👉 Hint: If it is not pending but returned None, a regression occurred in the language dispatcher.",
            graph_set.syntax.is_none(),
            SYNTAX_NOT_YET_MIGRATED.contains(&suffix)
        );

        let generated_ast = graph_set
            .ast
            .as_ref()
            .map(export_ast_graph_as_json)
            .expect("AST graph should be built for the fixture");

        let generated_syntax = graph_set.syntax.as_ref().map(export_syntax_graph_as_json);

        let relative = format!("test/data/test_files/{test_file}");
        write_rust_output(suffix, &relative, &generated_ast, generated_syntax.as_ref());

        let python_results: Value = serde_json::from_str(
            &fs::read_to_string(results_dir().join(format!("root-graph_{suffix}.json")))
                .expect("read python golden"),
        )
        .expect("parse python golden");
        let golden = python_results
            .get("graphs")
            .and_then(|graphs| graphs.get(&relative))
            .expect("locate the fixture entry in python golden");

        let mut diffs = ast_diffs(&generated_ast, golden, suffix);
        if let Some(generated_syntax) = &generated_syntax {
            if SYNTAX_IN_PROGRESS.contains(&suffix) {
                diffs.extend(syntax_diffs_partial(generated_syntax, golden));
            } else {
                diffs.extend(syntax_diffs(generated_syntax, golden));
            }
        }

        assert_graph_parity(suffix, &diffs);
    }

    #[test_case("java.java", "java")]
    fn graph_generation_with_metadata(test_file: &str, suffix: &str) {
        let path = fixtures_dir().join(test_file);
        let mut graph_set = get_graphs_from_path(&path, None, Some(true));

        let relative_fixture = format!("test/data/test_files/syntax_graph/{test_file}");
        if let Some(syntax) = graph_set.syntax.as_mut() {
            if let Some(SyntaxNode::Metadata {
                path: metadata_path,
                ..
            }) = syntax.nodes.get_mut(&NodeId(0))
            {
                *metadata_path = relative_fixture;
            }
        }

        let generated_ast = graph_set
            .ast
            .as_ref()
            .map(export_ast_graph_as_json)
            .expect("AST graph should be built for the fixture");
        let generated_syntax = graph_set
            .syntax
            .as_ref()
            .map(export_syntax_graph_as_json)
            .expect("syntax graph should be built with metadata");

        let relative = format!("test/data/test_files/{test_file}");
        write_rust_output(
            &format!("metadata_{suffix}"),
            &relative,
            &generated_ast,
            Some(&generated_syntax),
        );

        let python_results: Value = serde_json::from_str(
            &fs::read_to_string(results_dir().join(format!("root-graph-metadata_{suffix}.json")))
                .expect("read python golden"),
        )
        .expect("parse python golden");
        let golden = python_results
            .get("graphs")
            .and_then(|graphs| graphs.get(&relative))
            .expect("locate the fixture entry in python golden");

        let mut diffs = ast_diffs(&generated_ast, golden, suffix);
        diffs.extend(syntax_diffs(&generated_syntax, golden));
        assert_graph_parity(suffix, &diffs);
    }

    fn assert_graph_parity(suffix: &str, diffs: &[String]) {
        let shown = diffs
            .iter()
            .take(MAX_REPORTED_DIFFS)
            .cloned()
            .collect::<Vec<_>>()
            .join("\n");
        let extra = diffs.len().saturating_sub(MAX_REPORTED_DIFFS);
        let more = if extra > 0 {
            format!("\n… and {extra} more differing entries")
        } else {
            String::new()
        };

        assert!(
            diffs.is_empty(),
            "graph parity mismatch for {suffix} ({} differing entries):\n{shown}{more}",
            diffs.len()
        );
    }
}