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    const MAX_REPORTED_DIFFS: usize = 30;
238
239    // Fixture suffixes whose language has no rust syntax dispatcher yet.
240    const SYNTAX_NOT_YET_MIGRATED: &[&str] = &[
241        "elixir", "go", "hcl", "kotlin", "php", "ruby", "rust", "scala", "swift",
242    ];
243
244    // Fixture suffixes whose language dispatcher exists but still degrades
245    // some node types to MissingNode: implemented nodes compare exactly,
246    // diffs anchored at the missing placeholders are ignored.
247    const SYNTAX_IN_PROGRESS: &[&str] = &[];
248
249    fn ast_diffs(rust_ast: &Value, golden: &Value, suffix: &str) -> Vec<String> {
250        let expected = golden
251            .get("graph")
252            .map(normalize_field_keys)
253            .expect("locate graph block in python golden");
254
255        // c# alone has syntax readers that overwrite `label_l` on class/method
256        // declarations; ignore that attribute only for c#, never other languages.
257        let line_skip: &[&str] = match suffix {
258            "c_sharp" => &["class_declaration", "method_declaration"],
259            _ => &[],
260        };
261        let mut diffs = diff_section(
262            "node",
263            &ignore_line_for(section(rust_ast, "nodes"), line_skip),
264            &ignore_line_for(section(&expected, "nodes"), line_skip),
265        );
266        diffs.extend(diff_section(
267            "edge",
268            &section(rust_ast, "edges"),
269            &section(&expected, "edges"),
270        ));
271        diffs
272    }
273
274    fn syntax_diffs(generated_syntax: &Value, golden: &Value) -> Vec<String> {
275        let expected = golden
276            .get("syntax_graph")
277            .cloned()
278            .expect("locate syntax_graph block in python golden");
279
280        let mut diffs = diff_section(
281            "syntax node",
282            &section(generated_syntax, "nodes"),
283            &section(&expected, "nodes"),
284        );
285        diffs.extend(diff_section(
286            "syntax edge",
287            &section(generated_syntax, "edges"),
288            &section(&expected, "edges"),
289        ));
290        diffs
291    }
292
293    // The ids the rust engine degraded to MissingNode: subtrees whose reader
294    // is pending, plus punctuation children the python readers consumed
295    // without creating a syntax node.
296    fn missing_ids(generated_syntax: &Value) -> BTreeSet<String> {
297        section(generated_syntax, "nodes")
298            .into_iter()
299            .filter(|(_, attrs)| {
300                attrs.get("label_type").and_then(Value::as_str) == Some("MissingNode")
301            })
302            .map(|(id, _)| id)
303            .collect()
304    }
305
306    fn edge_target_ids(edges: &Map<String, Value>, from: &str) -> Vec<String> {
307        edges
308            .get(from)
309            .and_then(Value::as_object)
310            .map(|targets| targets.keys().cloned().collect())
311            .unwrap_or_default()
312    }
313
314    fn pending_subtree_ids(generated_syntax: &Value) -> BTreeSet<String> {
315        let edges = section(generated_syntax, "edges");
316        let mut skip = missing_ids(generated_syntax);
317        let mut stack: Vec<String> = skip.iter().cloned().collect();
318        while let Some(from) = stack.pop() {
319            let fresh: Vec<String> = edge_target_ids(&edges, &from)
320                .into_iter()
321                .filter(|to| skip.insert(to.clone()))
322                .collect();
323            stack.extend(fresh);
324        }
325        skip
326    }
327
328    fn drop_missing_nodes(
329        nodes: Map<String, Value>,
330        skip: &BTreeSet<String>,
331    ) -> Map<String, Value> {
332        nodes
333            .into_iter()
334            .filter(|(id, _)| !skip.contains(id))
335            .collect()
336    }
337
338    fn drop_missing_targets(targets: &Value, skip: &BTreeSet<String>) -> Map<String, Value> {
339        targets
340            .as_object()
341            .cloned()
342            .unwrap_or_default()
343            .into_iter()
344            .filter(|(to, _)| !skip.contains(to))
345            .collect()
346    }
347
348    fn drop_missing_edges(
349        edges: Map<String, Value>,
350        skip: &BTreeSet<String>,
351    ) -> Map<String, Value> {
352        edges
353            .into_iter()
354            .filter(|(from, _)| !skip.contains(from))
355            .map(|(from, targets)| (from, drop_missing_targets(&targets, skip)))
356            .filter(|(_, kept)| !kept.is_empty())
357            .map(|(from, kept)| (from, Value::Object(kept)))
358            .collect()
359    }
360
361    // In-progress compare: everything not anchored at a MissingNode id must
362    // match the golden exactly, on both sides — a golden-only entry between
363    // implemented nodes is still a real diff.
364    fn syntax_diffs_partial(generated_syntax: &Value, golden: &Value) -> Vec<String> {
365        let expected = golden
366            .get("syntax_graph")
367            .cloned()
368            .expect("locate syntax_graph block in python golden");
369        let skip = pending_subtree_ids(generated_syntax);
370
371        let mut diffs = diff_section(
372            "syntax node",
373            &drop_missing_nodes(section(generated_syntax, "nodes"), &skip),
374            &drop_missing_nodes(section(&expected, "nodes"), &skip),
375        );
376        diffs.extend(diff_section(
377            "syntax edge",
378            &drop_missing_edges(section(generated_syntax, "edges"), &skip),
379            &drop_missing_edges(section(&expected, "edges"), &skip),
380        ));
381        diffs
382    }
383
384    #[test_case("c_sharp.cs", "c_sharp")]
385    #[test_case("elixir.ex", "elixir")]
386    #[test_case("go.go", "go")]
387    #[test_case("terraform.tf", "hcl")]
388    #[test_case("java.java", "java")]
389    #[test_case("javascript.js", "javascript")]
390    #[test_case("json.json", "json")]
391    #[test_case("kotlin.kt", "kotlin")]
392    #[test_case("python.py", "python")]
393    #[test_case("php.php", "php")]
394    #[test_case("ruby.rb", "ruby")]
395    #[test_case("rust.rs", "rust")]
396    #[test_case("scala.scala", "scala")]
397    #[test_case("swift.swift", "swift")]
398    #[test_case("syntax_cfg.ts", "typescript")]
399    #[test_case("yaml.yaml", "yaml")]
400    #[test_case("templates/helm_configmap.yaml", "helm_configmap_yaml")]
401    #[test_case("templates/helm_configmap.json", "helm_configmap_json")]
402    #[test_case("flow_mapping.yaml", "flow_mapping")]
403    #[test_case("flow_sequence.yaml", "flow_sequence")]
404    fn graph_generation(test_file: &str, suffix: &str) {
405        let path = fixtures_dir().join(test_file);
406        let graph_set = get_graphs_from_path(&path, None, None);
407
408        assert!(
409            !(SYNTAX_NOT_YET_MIGRATED.contains(&suffix) && SYNTAX_IN_PROGRESS.contains(&suffix)),
410            "suffix {suffix} cannot be pending and in progress at the same time"
411        );
412        assert_eq!(
413            graph_set.syntax.is_none(),
414            SYNTAX_NOT_YET_MIGRATED.contains(&suffix),
415            "\n[Syntax Parity Error] Inconsistency detected for language extension: .{suffix}\n\
416             - Was syntax graph generated (None)? -> {}\n\
417             - Is it marked as pending in SYNTAX_NOT_YET_MIGRATED? -> {}\n\
418             šŸ‘‰ Hint: If it was generated but is marked as pending, move '.{suffix}' to \
419             SYNTAX_IN_PROGRESS (partial compare) or drop it from both lists (strict compare).\n\
420             šŸ‘‰ Hint: If it is not pending but returned None, a regression occurred in the language dispatcher.",
421            graph_set.syntax.is_none(),
422            SYNTAX_NOT_YET_MIGRATED.contains(&suffix)
423        );
424
425        let generated_ast = graph_set
426            .ast
427            .as_ref()
428            .map(export_ast_graph_as_json)
429            .expect("AST graph should be built for the fixture");
430
431        let generated_syntax = graph_set.syntax.as_ref().map(export_syntax_graph_as_json);
432
433        let relative = format!("test/data/test_files/{test_file}");
434        write_rust_output(suffix, &relative, &generated_ast, generated_syntax.as_ref());
435
436        let python_results: Value = serde_json::from_str(
437            &fs::read_to_string(results_dir().join(format!("root-graph_{suffix}.json")))
438                .expect("read python golden"),
439        )
440        .expect("parse python golden");
441        let golden = python_results
442            .get("graphs")
443            .and_then(|graphs| graphs.get(&relative))
444            .expect("locate the fixture entry in python golden");
445
446        let mut diffs = ast_diffs(&generated_ast, golden, suffix);
447        if let Some(generated_syntax) = &generated_syntax {
448            if SYNTAX_IN_PROGRESS.contains(&suffix) {
449                diffs.extend(syntax_diffs_partial(generated_syntax, golden));
450            } else {
451                diffs.extend(syntax_diffs(generated_syntax, golden));
452            }
453        }
454
455        assert_graph_parity(suffix, &diffs);
456    }
457
458    #[test_case("java.java", "java")]
459    fn graph_generation_with_metadata(test_file: &str, suffix: &str) {
460        let path = fixtures_dir().join(test_file);
461        let mut graph_set = get_graphs_from_path(&path, None, Some(true));
462
463        let relative_fixture = format!("test/data/test_files/syntax_graph/{test_file}");
464        if let Some(syntax) = graph_set.syntax.as_mut() {
465            if let Some(SyntaxNode::Metadata {
466                path: metadata_path,
467                ..
468            }) = syntax.nodes.get_mut(&NodeId(0))
469            {
470                *metadata_path = relative_fixture;
471            }
472        }
473
474        let generated_ast = graph_set
475            .ast
476            .as_ref()
477            .map(export_ast_graph_as_json)
478            .expect("AST graph should be built for the fixture");
479        let generated_syntax = graph_set
480            .syntax
481            .as_ref()
482            .map(export_syntax_graph_as_json)
483            .expect("syntax graph should be built with metadata");
484
485        let relative = format!("test/data/test_files/{test_file}");
486        write_rust_output(
487            &format!("metadata_{suffix}"),
488            &relative,
489            &generated_ast,
490            Some(&generated_syntax),
491        );
492
493        let python_results: Value = serde_json::from_str(
494            &fs::read_to_string(results_dir().join(format!("root-graph-metadata_{suffix}.json")))
495                .expect("read python golden"),
496        )
497        .expect("parse python golden");
498        let golden = python_results
499            .get("graphs")
500            .and_then(|graphs| graphs.get(&relative))
501            .expect("locate the fixture entry in python golden");
502
503        let mut diffs = ast_diffs(&generated_ast, golden, suffix);
504        diffs.extend(syntax_diffs(&generated_syntax, golden));
505        assert_graph_parity(suffix, &diffs);
506    }
507
508    fn assert_graph_parity(suffix: &str, diffs: &[String]) {
509        let shown = diffs
510            .iter()
511            .take(MAX_REPORTED_DIFFS)
512            .cloned()
513            .collect::<Vec<_>>()
514            .join("\n");
515        let extra = diffs.len().saturating_sub(MAX_REPORTED_DIFFS);
516        let more = if extra > 0 {
517            format!("\n… and {extra} more differing entries")
518        } else {
519            String::new()
520        };
521
522        assert!(
523            diffs.is_empty(),
524            "graph parity mismatch for {suffix} ({} differing entries):\n{shown}{more}",
525            diffs.len()
526        );
527    }
528}