fluidattacks-blends-domain 0.6.1

Blends functional core: pure AST graph to syntax graph (no_std)
Documentation
use alloc::string::String;

use crate::query::{get_node_by_path, match_ast_group_d};
use crate::syntax::builders::expression_statement::build_expression_statement_node;
use crate::syntax::builders::variable_declaration::build_variable_declaration_node;
use crate::syntax::fields::javascript::{call_expression, variable_declarator};
use crate::syntax::{SyntaxGraphArgs, SyntaxGraphError};
use crate::utilities::text_nodes::node_to_str;
use crate::{CodeGraph, NodeId};

fn require_module_path(args: &SyntaxGraphArgs<'_>, value_id: NodeId) -> Option<String> {
    let graph = args.ast_graph;
    if graph.label_type(value_id) != Some("call_expression") {
        return None;
    }
    let func_id = args
        .required_field_alt(value_id, call_expression::FUNCTION)
        .ok()?;
    if node_to_str(graph, func_id) != "require" {
        return None;
    }
    let arguments_id = args
        .required_field_alt(value_id, call_expression::ARGUMENTS)
        .ok()?;
    let frag_id = get_node_by_path(graph, arguments_id, &["string", "string_fragment"])?;
    graph.nodes.get(&frag_id).and_then(|node| node.text.clone())
}

pub fn reader(
    args: &mut SyntaxGraphArgs<'_>,
    n_id: NodeId,
) -> Result<Option<NodeId>, SyntaxGraphError> {
    let var_ids = match_ast_group_d(args.ast_graph, n_id, "variable_declarator", Some(1));
    if let [declared_var] = var_ids.as_slice() {
        let declared_var = *declared_var;
        let var_id = args.required_field_alt(declared_var, variable_declarator::NAME)?;
        let var_name = node_to_str(args.ast_graph, var_id);
        let var_name = if var_name.starts_with('{') {
            let mut chars = var_name.chars();
            chars.next();
            chars.next_back();
            String::from(chars.as_str())
        } else {
            var_name
        };
        let value_id = args.optional_field_alt(declared_var, variable_declarator::VALUE);
        let has_require = value_id
            .and_then(|value_id| require_module_path(args, value_id))
            .is_some();

        if args.ast_graph.label_type(var_id) == Some("object_pattern") && has_require {
            return build_variable_declaration_node(
                args,
                n_id,
                var_name,
                None,
                value_id,
                Some(var_id),
                None,
            )
            .map(Some);
        }

        return build_variable_declaration_node(args, n_id, var_name, None, value_id, None, None)
            .map(Some);
    }

    build_expression_statement_node(args, n_id, &var_ids).map(Some)
}