fluidattacks-blends-domain 0.6.1

Blends functional core: pure AST graph to syntax graph (no_std)
Documentation
//! Counterpart of `blends/syntax/build_graph.py`.

use alloc::borrow::ToOwned;
use alloc::collections::BTreeMap;
use alloc::vec::Vec;

use crate::ast::AstGraph;
use crate::syntax::SyntaxGraph;
use crate::syntax::SyntaxMetadata;
use crate::syntax::SyntaxNode;
use crate::syntax::{SyntaxGraphArgs, SyntaxGraphError};
use crate::{Language, NodeId};

pub fn build_syntax_graph(
    ast_graph: &AstGraph,
    path: &str,
    language: Language,
    with_metadata: bool,
) -> Result<SyntaxGraph, SyntaxGraphError> {
    let dispatcher = language
        .syntax_dispatcher()
        .ok_or(SyntaxGraphError::UnsupportedLanguage)?;

    let (max_ast_id, _) = ast_graph
        .nodes
        .last_key_value()
        .ok_or(SyntaxGraphError::EmptyAstGraph)?;

    let root = NodeId(1);
    if !ast_graph.nodes.contains_key(&root) {
        return Err(SyntaxGraphError::MissingRootNode);
    }

    let mut syntax_graph = SyntaxGraph::new();
    if with_metadata {
        syntax_graph.add_node(
            NodeId(0),
            SyntaxNode::Metadata {
                path: path.to_owned(),
                structure: BTreeMap::new(),
                instances: BTreeMap::new(),
                imports: Vec::new(),
                package: None,
            },
        );
    }
    let mut metadata = SyntaxMetadata::seeded(*max_ast_id);
    let mut args = SyntaxGraphArgs::new(
        language,
        ast_graph,
        &mut syntax_graph,
        &mut metadata,
        dispatcher,
    );
    args.generic(root)?;
    Ok(syntax_graph)
}