fluidattacks-blends-domain 0.17.0

Blends functional core: pure AST graph to syntax graph (no_std)
Documentation
//! Counterpart of `blends/syntax/builders/variable_declaration.py` (the
//! `StackGraph` binding wiring and import chain are excluded: the migration
//! covers only AST, Syntax and CFG).

use alloc::string::String;

use crate::query::pred_ast;
use crate::syntax::builders::utils::register_symbol_in_scope;
use crate::syntax::SyntaxNode;
use crate::syntax::{SyntaxGraphArgs, SyntaxGraphError};
use crate::{CodeGraph, NodeId};

/// Bindings inside a destructuring pattern hold no initializer of their own.
fn destructured_value_id(args: &SyntaxGraphArgs<'_>, n_id: NodeId) -> Option<NodeId> {
    let parent_ids = pred_ast(args.ast_graph, n_id, Some(3));
    let [pattern_id, declarator_id, declaration_id] = parent_ids.as_slice() else {
        return None;
    };

    if args.ast_graph.label_type(*pattern_id) != Some("object_pattern")
        || args.ast_graph.label_type(*declarator_id) != Some("variable_declarator")
    {
        return None;
    }

    args.syntax_graph
        .nodes
        .get(declaration_id)
        .and_then(SyntaxNode::value_id)
}

#[allow(
    clippy::too_many_arguments,
    reason = "mirrors the Python build_variable_declaration_node inputs"
)]
pub fn build_variable_declaration_node(
    args: &mut SyntaxGraphArgs<'_>,
    n_id: NodeId,
    variable_name: String,
    variable_type: Option<String>,
    value_id: Option<NodeId>,
    var_id: Option<NodeId>,
    access_modifier: Option<String>,
) -> Result<NodeId, SyntaxGraphError> {
    let child_id = value_id
        .map(|value_id| args.generic(value_id))
        .transpose()?;
    let declared_value_id = child_id.or_else(|| destructured_value_id(args, n_id));

    args.syntax_graph.add_node(
        n_id,
        SyntaxNode::VariableDeclaration {
            variable: variable_name.clone(),
            variable_type: variable_type.filter(|value| !value.is_empty()),
            value_id: declared_value_id,
            variable_id: var_id,
            access_modifier: access_modifier.filter(|value| !value.is_empty()),
        },
    );

    if let Some(child_id) = child_id {
        args.syntax_graph.add_ast_edge(n_id, child_id);
    }

    if let Some(var_id) = var_id {
        let built = args.generic(var_id)?;
        args.syntax_graph.add_ast_edge(n_id, built);
    }

    register_symbol_in_scope(args.syntax_graph, args.metadata, variable_name, n_id);

    Ok(n_id)
}