Skip to main content

fluidattacks_blends_domain/syntax/
build_graph.rs

1//! Counterpart of `blends/syntax/build_graph.py`.
2
3use alloc::borrow::ToOwned;
4use alloc::collections::BTreeMap;
5use alloc::vec::Vec;
6
7use crate::ast::AstGraph;
8use crate::syntax::SyntaxGraph;
9use crate::syntax::SyntaxMetadata;
10use crate::syntax::SyntaxNode;
11use crate::syntax::{SyntaxGraphArgs, SyntaxGraphError};
12use crate::{Language, NodeId};
13
14pub fn build_syntax_graph(
15    ast_graph: &AstGraph,
16    path: &str,
17    language: Language,
18    with_metadata: bool,
19) -> Result<SyntaxGraph, SyntaxGraphError> {
20    let dispatcher = language
21        .syntax_dispatcher()
22        .ok_or(SyntaxGraphError::UnsupportedLanguage)?;
23
24    let (max_ast_id, _) = ast_graph
25        .nodes
26        .last_key_value()
27        .ok_or(SyntaxGraphError::EmptyAstGraph)?;
28
29    let root = NodeId(1);
30    if !ast_graph.nodes.contains_key(&root) {
31        return Err(SyntaxGraphError::MissingRootNode);
32    }
33
34    let mut syntax_graph = SyntaxGraph::new();
35    if with_metadata {
36        syntax_graph.add_node(
37            NodeId(0),
38            SyntaxNode::Metadata {
39                path: path.to_owned(),
40                structure: BTreeMap::new(),
41                instances: BTreeMap::new(),
42                imports: Vec::new(),
43                package: None,
44            },
45        );
46    }
47    let mut metadata = SyntaxMetadata::seeded(*max_ast_id);
48    let mut args = SyntaxGraphArgs::new(
49        language,
50        ast_graph,
51        &mut syntax_graph,
52        &mut metadata,
53        dispatcher,
54    );
55    args.generic(root)?;
56    Ok(syntax_graph)
57}