Skip to main content

fluidattacks_blends/
graphs.rs

1//! Top-level orchestration: a path to its set of graphs.
2
3use std::path::Path;
4
5use blends_domain::graph_set::GraphSet;
6
7use crate::ast::get_ast_graph;
8use crate::content::Content;
9use crate::syntax::get_syntax_graph;
10
11#[must_use]
12pub fn get_graphs_from_path(
13    path: &Path,
14    with_cfg: Option<bool>,
15    with_metadata: Option<bool>,
16) -> GraphSet {
17    let Some(content) = Content::from_path(path, None) else {
18        return GraphSet::default();
19    };
20
21    let Some(ast) = get_ast_graph(&content) else {
22        return GraphSet::default();
23    };
24
25    let Some(syntax) = get_syntax_graph(&ast, &content, with_cfg, with_metadata) else {
26        return GraphSet {
27            ast: Some(ast),
28            syntax: None,
29        };
30    };
31
32    GraphSet {
33        ast: Some(ast),
34        syntax: Some(syntax),
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::get_graphs_from_path;
41    use crate::attrs::{
42        ast_edge_attrs, ast_node_attrs, sorted_object, syntax_edge_attrs, syntax_node_attrs,
43    };
44    use blends_domain::ast::AstGraph;
45    use blends_domain::syntax::{SyntaxGraph, SyntaxNode};
46    use blends_domain::NodeId;
47    use serde_json::{Map, Value};
48    use std::collections::{BTreeMap, BTreeSet};
49    use std::fs;
50    use std::path::{Path, PathBuf};
51    use test_case::test_case;
52
53    fn fixtures_dir() -> PathBuf {
54        Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test/data/test_files/syntax_graph")
55    }
56
57    fn results_dir() -> PathBuf {
58        Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test/data/results")
59    }
60
61    fn output_dir() -> PathBuf {
62        Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test/data/output")
63    }
64
65    fn export_ast_graph_as_json(graph: &AstGraph) -> Value {
66        let mut nodes = Map::new();
67        for (id, node) in &graph.nodes {
68            nodes.insert(id.0.to_string(), sorted_object(ast_node_attrs(node)));
69        }
70
71        let mut edges = Map::new();
72        for (from, targets) in &graph.edges {
73            let mut inner = Map::new();
74            for (to, edge) in targets {
75                inner.insert(to.0.to_string(), sorted_object(ast_edge_attrs(*edge)));
76            }
77            edges.insert(from.0.to_string(), Value::Object(inner));
78        }
79
80        let mut root = BTreeMap::new();
81        root.insert("edges".to_owned(), Value::Object(edges));
82        root.insert("nodes".to_owned(), Value::Object(nodes));
83        sorted_object(root)
84    }
85
86    fn export_syntax_graph_as_json(graph: &SyntaxGraph) -> Value {
87        let mut nodes = Map::new();
88        for (id, node) in &graph.nodes {
89            let attrs = syntax_node_attrs(node).unwrap_or_else(|| {
90                panic!("syntax export not implemented for {}", node.label_type())
91            });
92            nodes.insert(id.0.to_string(), sorted_object(attrs));
93        }
94
95        let mut edges = Map::new();
96        for (from, targets) in &graph.edges {
97            let mut inner = Map::new();
98            for (to, edge) in targets {
99                inner.insert(to.0.to_string(), sorted_object(syntax_edge_attrs(*edge)));
100            }
101            edges.insert(from.0.to_string(), Value::Object(inner));
102        }
103
104        let mut root = BTreeMap::new();
105        root.insert("edges".to_owned(), Value::Object(edges));
106        root.insert("nodes".to_owned(), Value::Object(nodes));
107        sorted_object(root)
108    }
109
110    #[test]
111    fn empty_set_for_unsupported_file() {
112        let dir = tempfile::tempdir().unwrap();
113        let path = dir.path().join("a.unknown");
114        fs::write(&path, b"whatever").unwrap();
115
116        assert!(get_graphs_from_path(&path, None, None).ast.is_none());
117    }
118
119    #[test]
120    fn empty_set_for_malformed_supported_file() {
121        let dir = tempfile::tempdir().unwrap();
122        let path = dir.path().join("a.java");
123        fs::write(&path, b"class A {").unwrap();
124
125        assert!(get_graphs_from_path(&path, None, None).ast.is_none());
126    }
127
128    fn rename_field_key(key: &str) -> String {
129        key.strip_prefix("label_field_")
130            .map_or_else(|| key.to_owned(), |field| format!("{field}_id"))
131    }
132
133    fn rename_node_attrs(attrs: &Value) -> Value {
134        let Some(attrs) = attrs.as_object() else {
135            return attrs.clone();
136        };
137        let mut renamed = Map::new();
138        for (key, value) in attrs {
139            renamed.insert(rename_field_key(key), value.clone());
140        }
141        Value::Object(renamed)
142    }
143
144    // The python golden keys node fields as `label_field_<field>`; the Rust engine
145    // keys them as `<field>_id`. Rewrite the golden's keys in memory so the two
146    // graphs compare on content. The `results/` file on disk is untouched.
147    fn normalize_field_keys(graph: &Value) -> Value {
148        let mut nodes = Map::new();
149        if let Some(original) = graph.get("nodes").and_then(Value::as_object) {
150            for (id, attrs) in original {
151                nodes.insert(id.clone(), rename_node_attrs(attrs));
152            }
153        }
154
155        let mut result = Map::new();
156        if let Some(edges) = graph.get("edges") {
157            result.insert("edges".to_owned(), edges.clone());
158        }
159        result.insert("nodes".to_owned(), Value::Object(nodes));
160        Value::Object(result)
161    }
162
163    fn write_rust_output(suffix: &str, relative: &str, ast: &Value, syntax: Option<&Value>) {
164        let mut entry = Map::new();
165        entry.insert("graph".to_owned(), ast.clone());
166        if let Some(syntax) = syntax {
167            entry.insert("syntax_graph".to_owned(), syntax.clone());
168        }
169        let mut by_path = Map::new();
170        by_path.insert(relative.to_owned(), Value::Object(entry));
171        let mut root = Map::new();
172        root.insert("graphs".to_owned(), Value::Object(by_path));
173
174        let pretty = serde_json::to_string_pretty(&Value::Object(root)).expect("serialize output");
175        let dir = output_dir();
176        fs::create_dir_all(&dir).expect("create output dir");
177        fs::write(dir.join(format!("root-graph_{suffix}.json")), pretty).expect("write output");
178    }
179
180    fn section(graph: &Value, key: &str) -> Map<String, Value> {
181        graph
182            .get(key)
183            .and_then(Value::as_object)
184            .cloned()
185            .unwrap_or_default()
186    }
187
188    // The python golden dumps the ast after the syntax readers run, and some
189    // readers overwrite `label_l` (c# class/method declaration take the line of
190    // their identifier). Until those readers exist in rust, drop only `label_l`
191    // on those node types from both sides, so just the mutated line is ignored
192    // while every other attribute (line column, type, fields) is still compared.
193    fn ignore_line_for(nodes: Map<String, Value>, skip_types: &[&str]) -> Map<String, Value> {
194        nodes
195            .into_iter()
196            .map(|(id, mut attrs)| {
197                let skip = attrs
198                    .get("label_type")
199                    .and_then(Value::as_str)
200                    .is_some_and(|kind| skip_types.contains(&kind));
201                if let Some(node) = attrs.as_object_mut().filter(|_| skip) {
202                    node.remove("label_l");
203                }
204                (id, attrs)
205            })
206            .collect()
207    }
208
209    // Concise per-entry diff: only the ids whose content differs, rust vs python.
210    fn diff_section(
211        kind: &str,
212        rust: &Map<String, Value>,
213        python: &Map<String, Value>,
214    ) -> Vec<String> {
215        let mut diffs = Vec::new();
216        for (id, rust_entry) in rust {
217            match python.get(id) {
218                None => diffs.push(format!(
219                    "{kind} {id}: in rust output, missing in python golden"
220                )),
221                Some(python_entry) if python_entry != rust_entry => diffs.push(format!(
222                    "{kind} {id} differs:\n  rust:   {rust_entry}\n  python: {python_entry}"
223                )),
224                Some(_) => {}
225            }
226        }
227        for id in python.keys() {
228            if !rust.contains_key(id) {
229                diffs.push(format!(
230                    "{kind} {id}: in python golden, missing in rust output"
231                ));
232            }
233        }
234        diffs
235    }
236
237    // `diff_section` is what makes every graph_generation parity assertion
238    // meaningful: if it stopped reporting a category of mismatch, the suite
239    // would keep passing while the rust and python graphs drifted apart.
240    // Passing fixtures agree, so the mismatch arms are only reachable here.
241    #[test_case(&[("n1", 1)], &[], "in rust output, missing in python golden" ; "only rust produced the entry")]
242    #[test_case(&[("n1", 1)], &[("n1", 2)], "node n1 differs" ; "both produced it with different content")]
243    #[test_case(&[], &[("n1", 1)], "in python golden, missing in rust output" ; "only the python golden has it")]
244    fn diff_section_reports_each_kind_of_mismatch(
245        rust_entries: &[(&str, i32)],
246        python_entries: &[(&str, i32)],
247        expected: &str,
248    ) {
249        let to_map = |entries: &[(&str, i32)]| -> Map<String, Value> {
250            entries
251                .iter()
252                .map(|(id, value)| ((*id).to_owned(), Value::from(*value)))
253                .collect()
254        };
255
256        let diffs = diff_section("node", &to_map(rust_entries), &to_map(python_entries));
257
258        let [only] = diffs.as_slice() else {
259            panic!("expected exactly one diff, got {diffs:?}");
260        };
261        assert!(
262            only.contains(expected),
263            "diff {only:?} does not report {expected:?}"
264        );
265    }
266
267    #[test]
268    fn diff_section_reports_nothing_when_both_graphs_agree() {
269        let mut entries = Map::new();
270        entries.insert("n1".to_owned(), Value::from(1));
271
272        assert!(diff_section("node", &entries, &entries).is_empty());
273    }
274
275    const MAX_REPORTED_DIFFS: usize = 30;
276
277    // Fixture suffixes whose language has no rust syntax dispatcher yet.
278    const SYNTAX_NOT_YET_MIGRATED: &[&str] = &["elixir", "hcl", "kotlin", "rust", "scala", "swift"];
279
280    // Fixture suffixes whose language dispatcher exists but still degrades
281    // some node types to MissingNode: implemented nodes compare exactly,
282    // diffs anchored at the missing placeholders are ignored.
283    const SYNTAX_IN_PROGRESS: &[&str] = &[];
284
285    fn ast_diffs(rust_ast: &Value, golden: &Value, suffix: &str) -> Vec<String> {
286        let expected = golden
287            .get("graph")
288            .map(normalize_field_keys)
289            .expect("locate graph block in python golden");
290
291        // c# alone has syntax readers that overwrite `label_l` on class/method
292        // declarations; ignore that attribute only for c#, never other languages.
293        let line_skip: &[&str] = match suffix {
294            "c_sharp" => &["class_declaration", "method_declaration"],
295            _ => &[],
296        };
297        let mut diffs = diff_section(
298            "node",
299            &ignore_line_for(section(rust_ast, "nodes"), line_skip),
300            &ignore_line_for(section(&expected, "nodes"), line_skip),
301        );
302        diffs.extend(diff_section(
303            "edge",
304            &section(rust_ast, "edges"),
305            &section(&expected, "edges"),
306        ));
307        diffs
308    }
309
310    fn syntax_diffs(generated_syntax: &Value, golden: &Value) -> Vec<String> {
311        let expected = golden
312            .get("syntax_graph")
313            .cloned()
314            .expect("locate syntax_graph block in python golden");
315
316        let mut diffs = diff_section(
317            "syntax node",
318            &section(generated_syntax, "nodes"),
319            &section(&expected, "nodes"),
320        );
321        diffs.extend(diff_section(
322            "syntax edge",
323            &section(generated_syntax, "edges"),
324            &section(&expected, "edges"),
325        ));
326        diffs
327    }
328
329    // The ids the rust engine degraded to MissingNode: subtrees whose reader
330    // is pending, plus punctuation children the python readers consumed
331    // without creating a syntax node.
332    fn missing_ids(generated_syntax: &Value) -> BTreeSet<String> {
333        section(generated_syntax, "nodes")
334            .into_iter()
335            .filter(|(_, attrs)| {
336                attrs.get("label_type").and_then(Value::as_str) == Some("MissingNode")
337            })
338            .map(|(id, _)| id)
339            .collect()
340    }
341
342    fn edge_target_ids(edges: &Map<String, Value>, from: &str) -> Vec<String> {
343        edges
344            .get(from)
345            .and_then(Value::as_object)
346            .map(|targets| targets.keys().cloned().collect())
347            .unwrap_or_default()
348    }
349
350    fn pending_subtree_ids(generated_syntax: &Value) -> BTreeSet<String> {
351        let edges = section(generated_syntax, "edges");
352        let mut skip = missing_ids(generated_syntax);
353        let mut stack: Vec<String> = skip.iter().cloned().collect();
354        while let Some(from) = stack.pop() {
355            let fresh: Vec<String> = edge_target_ids(&edges, &from)
356                .into_iter()
357                .filter(|to| skip.insert(to.clone()))
358                .collect();
359            stack.extend(fresh);
360        }
361        skip
362    }
363
364    fn drop_missing_nodes(
365        nodes: Map<String, Value>,
366        skip: &BTreeSet<String>,
367    ) -> Map<String, Value> {
368        nodes
369            .into_iter()
370            .filter(|(id, _)| !skip.contains(id))
371            .collect()
372    }
373
374    fn drop_missing_targets(targets: &Value, skip: &BTreeSet<String>) -> Map<String, Value> {
375        targets
376            .as_object()
377            .cloned()
378            .unwrap_or_default()
379            .into_iter()
380            .filter(|(to, _)| !skip.contains(to))
381            .collect()
382    }
383
384    fn drop_missing_edges(
385        edges: Map<String, Value>,
386        skip: &BTreeSet<String>,
387    ) -> Map<String, Value> {
388        edges
389            .into_iter()
390            .filter(|(from, _)| !skip.contains(from))
391            .map(|(from, targets)| (from, drop_missing_targets(&targets, skip)))
392            .filter(|(_, kept)| !kept.is_empty())
393            .map(|(from, kept)| (from, Value::Object(kept)))
394            .collect()
395    }
396
397    // In-progress compare: everything not anchored at a MissingNode id must
398    // match the golden exactly, on both sides — a golden-only entry between
399    // implemented nodes is still a real diff.
400    fn syntax_diffs_partial(generated_syntax: &Value, golden: &Value) -> Vec<String> {
401        let expected = golden
402            .get("syntax_graph")
403            .cloned()
404            .expect("locate syntax_graph block in python golden");
405        let skip = pending_subtree_ids(generated_syntax);
406
407        let mut diffs = diff_section(
408            "syntax node",
409            &drop_missing_nodes(section(generated_syntax, "nodes"), &skip),
410            &drop_missing_nodes(section(&expected, "nodes"), &skip),
411        );
412        diffs.extend(diff_section(
413            "syntax edge",
414            &drop_missing_edges(section(generated_syntax, "edges"), &skip),
415            &drop_missing_edges(section(&expected, "edges"), &skip),
416        ));
417        diffs
418    }
419
420    #[test_case("c_sharp.cs", "c_sharp")]
421    #[test_case("elixir.ex", "elixir")]
422    #[test_case("go.go", "go")]
423    #[test_case("terraform.tf", "hcl")]
424    #[test_case("java.java", "java")]
425    #[test_case("javascript.js", "javascript")]
426    #[test_case("json.json", "json")]
427    #[test_case("kotlin.kt", "kotlin")]
428    #[test_case("python.py", "python")]
429    #[test_case("php.php", "php")]
430    #[test_case("ruby.rb", "ruby")]
431    #[test_case("rust.rs", "rust")]
432    #[test_case("scala.scala", "scala")]
433    #[test_case("swift.swift", "swift")]
434    #[test_case("syntax_cfg.ts", "typescript")]
435    #[test_case("yaml.yaml", "yaml")]
436    #[test_case("templates/helm_configmap.yaml", "helm_configmap_yaml")]
437    #[test_case("templates/helm_configmap.json", "helm_configmap_json")]
438    #[test_case("flow_mapping.yaml", "flow_mapping")]
439    #[test_case("flow_sequence.yaml", "flow_sequence")]
440    fn graph_generation(test_file: &str, suffix: &str) {
441        let path = fixtures_dir().join(test_file);
442        let graph_set = get_graphs_from_path(&path, None, None);
443
444        assert!(
445            !(SYNTAX_NOT_YET_MIGRATED.contains(&suffix) && SYNTAX_IN_PROGRESS.contains(&suffix)),
446            "suffix {suffix} cannot be pending and in progress at the same time"
447        );
448        assert_eq!(
449            graph_set.syntax.is_none(),
450            SYNTAX_NOT_YET_MIGRATED.contains(&suffix),
451            "\n[Syntax Parity Error] Inconsistency detected for language extension: .{suffix}\n\
452             - Was syntax graph generated (None)? -> {}\n\
453             - Is it marked as pending in SYNTAX_NOT_YET_MIGRATED? -> {}\n\
454             šŸ‘‰ Hint: If it was generated but is marked as pending, move '.{suffix}' to \
455             SYNTAX_IN_PROGRESS (partial compare) or drop it from both lists (strict compare).\n\
456             šŸ‘‰ Hint: If it is not pending but returned None, a regression occurred in the language dispatcher.",
457            graph_set.syntax.is_none(),
458            SYNTAX_NOT_YET_MIGRATED.contains(&suffix)
459        );
460
461        let generated_ast = graph_set
462            .ast
463            .as_ref()
464            .map(export_ast_graph_as_json)
465            .expect("AST graph should be built for the fixture");
466
467        let generated_syntax = graph_set.syntax.as_ref().map(export_syntax_graph_as_json);
468
469        let relative = format!("test/data/test_files/{test_file}");
470        write_rust_output(suffix, &relative, &generated_ast, generated_syntax.as_ref());
471
472        let python_results: Value = serde_json::from_str(
473            &fs::read_to_string(results_dir().join(format!("root-graph_{suffix}.json")))
474                .expect("read python golden"),
475        )
476        .expect("parse python golden");
477        let golden = python_results
478            .get("graphs")
479            .and_then(|graphs| graphs.get(&relative))
480            .expect("locate the fixture entry in python golden");
481
482        let mut diffs = ast_diffs(&generated_ast, golden, suffix);
483        if let Some(generated_syntax) = &generated_syntax {
484            if SYNTAX_IN_PROGRESS.contains(&suffix) {
485                diffs.extend(syntax_diffs_partial(generated_syntax, golden));
486            } else {
487                diffs.extend(syntax_diffs(generated_syntax, golden));
488            }
489        }
490
491        assert_graph_parity(suffix, &diffs);
492    }
493
494    #[test_case("java.java", "java")]
495    fn graph_generation_with_metadata(test_file: &str, suffix: &str) {
496        let path = fixtures_dir().join(test_file);
497        let mut graph_set = get_graphs_from_path(&path, None, Some(true));
498
499        let relative_fixture = format!("test/data/test_files/syntax_graph/{test_file}");
500        if let Some(syntax) = graph_set.syntax.as_mut() {
501            if let Some(SyntaxNode::Metadata {
502                path: metadata_path,
503                ..
504            }) = syntax.nodes.get_mut(&NodeId(0))
505            {
506                *metadata_path = relative_fixture;
507            }
508        }
509
510        let generated_ast = graph_set
511            .ast
512            .as_ref()
513            .map(export_ast_graph_as_json)
514            .expect("AST graph should be built for the fixture");
515        let generated_syntax = graph_set
516            .syntax
517            .as_ref()
518            .map(export_syntax_graph_as_json)
519            .expect("syntax graph should be built with metadata");
520
521        let relative = format!("test/data/test_files/{test_file}");
522        write_rust_output(
523            &format!("metadata_{suffix}"),
524            &relative,
525            &generated_ast,
526            Some(&generated_syntax),
527        );
528
529        let python_results: Value = serde_json::from_str(
530            &fs::read_to_string(results_dir().join(format!("root-graph-metadata_{suffix}.json")))
531                .expect("read python golden"),
532        )
533        .expect("parse python golden");
534        let golden = python_results
535            .get("graphs")
536            .and_then(|graphs| graphs.get(&relative))
537            .expect("locate the fixture entry in python golden");
538
539        let mut diffs = ast_diffs(&generated_ast, golden, suffix);
540        diffs.extend(syntax_diffs(&generated_syntax, golden));
541        assert_graph_parity(suffix, &diffs);
542    }
543
544    fn assert_graph_parity(suffix: &str, diffs: &[String]) {
545        let shown = diffs
546            .iter()
547            .take(MAX_REPORTED_DIFFS)
548            .cloned()
549            .collect::<Vec<_>>()
550            .join("\n");
551        let extra = diffs.len().saturating_sub(MAX_REPORTED_DIFFS);
552        let more = if extra > 0 {
553            format!("\n… and {extra} more differing entries")
554        } else {
555            String::new()
556        };
557
558        assert!(
559            diffs.is_empty(),
560            "graph parity mismatch for {suffix} ({} differing entries):\n{shown}{more}",
561            diffs.len()
562        );
563    }
564}