1use 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 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 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 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 #[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 const SYNTAX_NOT_YET_MIGRATED: &[&str] =
279 &["elixir", "hcl", "kotlin", "php", "rust", "scala", "swift"];
280
281 const SYNTAX_IN_PROGRESS: &[&str] = &[];
285
286 fn ast_diffs(rust_ast: &Value, golden: &Value, suffix: &str) -> Vec<String> {
287 let expected = golden
288 .get("graph")
289 .map(normalize_field_keys)
290 .expect("locate graph block in python golden");
291
292 let line_skip: &[&str] = match suffix {
295 "c_sharp" => &["class_declaration", "method_declaration"],
296 _ => &[],
297 };
298 let mut diffs = diff_section(
299 "node",
300 &ignore_line_for(section(rust_ast, "nodes"), line_skip),
301 &ignore_line_for(section(&expected, "nodes"), line_skip),
302 );
303 diffs.extend(diff_section(
304 "edge",
305 §ion(rust_ast, "edges"),
306 §ion(&expected, "edges"),
307 ));
308 diffs
309 }
310
311 fn syntax_diffs(generated_syntax: &Value, golden: &Value) -> Vec<String> {
312 let expected = golden
313 .get("syntax_graph")
314 .cloned()
315 .expect("locate syntax_graph block in python golden");
316
317 let mut diffs = diff_section(
318 "syntax node",
319 §ion(generated_syntax, "nodes"),
320 §ion(&expected, "nodes"),
321 );
322 diffs.extend(diff_section(
323 "syntax edge",
324 §ion(generated_syntax, "edges"),
325 §ion(&expected, "edges"),
326 ));
327 diffs
328 }
329
330 fn missing_ids(generated_syntax: &Value) -> BTreeSet<String> {
334 section(generated_syntax, "nodes")
335 .into_iter()
336 .filter(|(_, attrs)| {
337 attrs.get("label_type").and_then(Value::as_str) == Some("MissingNode")
338 })
339 .map(|(id, _)| id)
340 .collect()
341 }
342
343 fn edge_target_ids(edges: &Map<String, Value>, from: &str) -> Vec<String> {
344 edges
345 .get(from)
346 .and_then(Value::as_object)
347 .map(|targets| targets.keys().cloned().collect())
348 .unwrap_or_default()
349 }
350
351 fn pending_subtree_ids(generated_syntax: &Value) -> BTreeSet<String> {
352 let edges = section(generated_syntax, "edges");
353 let mut skip = missing_ids(generated_syntax);
354 let mut stack: Vec<String> = skip.iter().cloned().collect();
355 while let Some(from) = stack.pop() {
356 let fresh: Vec<String> = edge_target_ids(&edges, &from)
357 .into_iter()
358 .filter(|to| skip.insert(to.clone()))
359 .collect();
360 stack.extend(fresh);
361 }
362 skip
363 }
364
365 fn drop_missing_nodes(
366 nodes: Map<String, Value>,
367 skip: &BTreeSet<String>,
368 ) -> Map<String, Value> {
369 nodes
370 .into_iter()
371 .filter(|(id, _)| !skip.contains(id))
372 .collect()
373 }
374
375 fn drop_missing_targets(targets: &Value, skip: &BTreeSet<String>) -> Map<String, Value> {
376 targets
377 .as_object()
378 .cloned()
379 .unwrap_or_default()
380 .into_iter()
381 .filter(|(to, _)| !skip.contains(to))
382 .collect()
383 }
384
385 fn drop_missing_edges(
386 edges: Map<String, Value>,
387 skip: &BTreeSet<String>,
388 ) -> Map<String, Value> {
389 edges
390 .into_iter()
391 .filter(|(from, _)| !skip.contains(from))
392 .map(|(from, targets)| (from, drop_missing_targets(&targets, skip)))
393 .filter(|(_, kept)| !kept.is_empty())
394 .map(|(from, kept)| (from, Value::Object(kept)))
395 .collect()
396 }
397
398 fn syntax_diffs_partial(generated_syntax: &Value, golden: &Value) -> Vec<String> {
402 let expected = golden
403 .get("syntax_graph")
404 .cloned()
405 .expect("locate syntax_graph block in python golden");
406 let skip = pending_subtree_ids(generated_syntax);
407
408 let mut diffs = diff_section(
409 "syntax node",
410 &drop_missing_nodes(section(generated_syntax, "nodes"), &skip),
411 &drop_missing_nodes(section(&expected, "nodes"), &skip),
412 );
413 diffs.extend(diff_section(
414 "syntax edge",
415 &drop_missing_edges(section(generated_syntax, "edges"), &skip),
416 &drop_missing_edges(section(&expected, "edges"), &skip),
417 ));
418 diffs
419 }
420
421 #[test_case("c_sharp.cs", "c_sharp")]
422 #[test_case("elixir.ex", "elixir")]
423 #[test_case("go.go", "go")]
424 #[test_case("terraform.tf", "hcl")]
425 #[test_case("java.java", "java")]
426 #[test_case("javascript.js", "javascript")]
427 #[test_case("json.json", "json")]
428 #[test_case("kotlin.kt", "kotlin")]
429 #[test_case("python.py", "python")]
430 #[test_case("php.php", "php")]
431 #[test_case("ruby.rb", "ruby")]
432 #[test_case("rust.rs", "rust")]
433 #[test_case("scala.scala", "scala")]
434 #[test_case("swift.swift", "swift")]
435 #[test_case("syntax_cfg.ts", "typescript")]
436 #[test_case("yaml.yaml", "yaml")]
437 #[test_case("templates/helm_configmap.yaml", "helm_configmap_yaml")]
438 #[test_case("templates/helm_configmap.json", "helm_configmap_json")]
439 #[test_case("flow_mapping.yaml", "flow_mapping")]
440 #[test_case("flow_sequence.yaml", "flow_sequence")]
441 fn graph_generation(test_file: &str, suffix: &str) {
442 let path = fixtures_dir().join(test_file);
443 let graph_set = get_graphs_from_path(&path, None, None);
444
445 assert!(
446 !(SYNTAX_NOT_YET_MIGRATED.contains(&suffix) && SYNTAX_IN_PROGRESS.contains(&suffix)),
447 "suffix {suffix} cannot be pending and in progress at the same time"
448 );
449 assert_eq!(
450 graph_set.syntax.is_none(),
451 SYNTAX_NOT_YET_MIGRATED.contains(&suffix),
452 "\n[Syntax Parity Error] Inconsistency detected for language extension: .{suffix}\n\
453 - Was syntax graph generated (None)? -> {}\n\
454 - Is it marked as pending in SYNTAX_NOT_YET_MIGRATED? -> {}\n\
455 š Hint: If it was generated but is marked as pending, move '.{suffix}' to \
456 SYNTAX_IN_PROGRESS (partial compare) or drop it from both lists (strict compare).\n\
457 š Hint: If it is not pending but returned None, a regression occurred in the language dispatcher.",
458 graph_set.syntax.is_none(),
459 SYNTAX_NOT_YET_MIGRATED.contains(&suffix)
460 );
461
462 let generated_ast = graph_set
463 .ast
464 .as_ref()
465 .map(export_ast_graph_as_json)
466 .expect("AST graph should be built for the fixture");
467
468 let generated_syntax = graph_set.syntax.as_ref().map(export_syntax_graph_as_json);
469
470 let relative = format!("test/data/test_files/{test_file}");
471 write_rust_output(suffix, &relative, &generated_ast, generated_syntax.as_ref());
472
473 let python_results: Value = serde_json::from_str(
474 &fs::read_to_string(results_dir().join(format!("root-graph_{suffix}.json")))
475 .expect("read python golden"),
476 )
477 .expect("parse python golden");
478 let golden = python_results
479 .get("graphs")
480 .and_then(|graphs| graphs.get(&relative))
481 .expect("locate the fixture entry in python golden");
482
483 let mut diffs = ast_diffs(&generated_ast, golden, suffix);
484 if let Some(generated_syntax) = &generated_syntax {
485 if SYNTAX_IN_PROGRESS.contains(&suffix) {
486 diffs.extend(syntax_diffs_partial(generated_syntax, golden));
487 } else {
488 diffs.extend(syntax_diffs(generated_syntax, golden));
489 }
490 }
491
492 assert_graph_parity(suffix, &diffs);
493 }
494
495 #[test_case("java.java", "java")]
496 fn graph_generation_with_metadata(test_file: &str, suffix: &str) {
497 let path = fixtures_dir().join(test_file);
498 let mut graph_set = get_graphs_from_path(&path, None, Some(true));
499
500 let relative_fixture = format!("test/data/test_files/syntax_graph/{test_file}");
501 if let Some(syntax) = graph_set.syntax.as_mut() {
502 if let Some(SyntaxNode::Metadata {
503 path: metadata_path,
504 ..
505 }) = syntax.nodes.get_mut(&NodeId(0))
506 {
507 *metadata_path = relative_fixture;
508 }
509 }
510
511 let generated_ast = graph_set
512 .ast
513 .as_ref()
514 .map(export_ast_graph_as_json)
515 .expect("AST graph should be built for the fixture");
516 let generated_syntax = graph_set
517 .syntax
518 .as_ref()
519 .map(export_syntax_graph_as_json)
520 .expect("syntax graph should be built with metadata");
521
522 let relative = format!("test/data/test_files/{test_file}");
523 write_rust_output(
524 &format!("metadata_{suffix}"),
525 &relative,
526 &generated_ast,
527 Some(&generated_syntax),
528 );
529
530 let python_results: Value = serde_json::from_str(
531 &fs::read_to_string(results_dir().join(format!("root-graph-metadata_{suffix}.json")))
532 .expect("read python golden"),
533 )
534 .expect("parse python golden");
535 let golden = python_results
536 .get("graphs")
537 .and_then(|graphs| graphs.get(&relative))
538 .expect("locate the fixture entry in python golden");
539
540 let mut diffs = ast_diffs(&generated_ast, golden, suffix);
541 diffs.extend(syntax_diffs(&generated_syntax, golden));
542 assert_graph_parity(suffix, &diffs);
543 }
544
545 fn assert_graph_parity(suffix: &str, diffs: &[String]) {
546 let shown = diffs
547 .iter()
548 .take(MAX_REPORTED_DIFFS)
549 .cloned()
550 .collect::<Vec<_>>()
551 .join("\n");
552 let extra = diffs.len().saturating_sub(MAX_REPORTED_DIFFS);
553 let more = if extra > 0 {
554 format!("\n⦠and {extra} more differing entries")
555 } else {
556 String::new()
557 };
558
559 assert!(
560 diffs.is_empty(),
561 "graph parity mismatch for {suffix} ({} differing entries):\n{shown}{more}",
562 diffs.len()
563 );
564 }
565}