fluidattacks-blends-domain 0.17.1

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

use crate::query::{adj_ast, match_ast, match_ast_group_d, pred_ast};
use crate::syntax::builders::method_declaration::{
    build_method_declaration_node, MethodDirectChildren, MethodListChildren,
};
use crate::syntax::fields::Field;
use crate::syntax::{SyntaxGraphArgs, SyntaxGraphError};
use crate::utilities::text_nodes::node_to_str;
use crate::{CodeGraph, NodeId};

const NAME: Field<false> = Field::new("name_id");
const BODY: Field<false> = Field::new("body_id");
const PARAMETERS: Field<false> = Field::new("parameters_id");

/// Every decorator applied to a method, in source order. Javascript keeps them
/// as the method's own children; typescript hangs them off the class body,
/// ahead of the member they decorate.
fn decorator_ids(args: &SyntaxGraphArgs<'_>, n_id: NodeId) -> Vec<NodeId> {
    let graph = args.ast_graph;
    let own_decorators = match_ast_group_d(graph, n_id, "decorator", Some(1));
    if !own_decorators.is_empty() {
        return own_decorators;
    }

    let Some(class_body_id) = pred_ast(graph, n_id, None).first().copied() else {
        return Vec::new();
    };

    // Walks the preceding siblings picking up this method's decorators, until
    // it stops finding nodes of that type.
    let siblings = adj_ast(graph, class_body_id, Some(1), &[]);
    let Some(position) = siblings.iter().position(|c_id| *c_id == n_id) else {
        return Vec::new();
    };

    let mut preceding: Vec<_> = siblings
        .get(..position)
        .unwrap_or_default()
        .iter()
        .rev()
        .take_while(|&&c_id| graph.label_type(c_id) == Some("decorator"))
        .copied()
        .collect();

    preceding.reverse();

    preceding
}

pub fn reader(
    args: &mut SyntaxGraphArgs<'_>,
    n_id: NodeId,
) -> Result<Option<NodeId>, SyntaxGraphError> {
    let graph = args.ast_graph;

    let name = args
        .optional_field_alt(n_id, NAME)
        .map(|name_id| node_to_str(graph, name_id));
    let block_id = args.optional_field_alt(n_id, BODY);
    let parameters_id = args.optional_field_alt(n_id, PARAMETERS);

    let direct = MethodDirectChildren {
        block_id,
        modifiers_id: None,
        parameters_id: parameters_id
            .filter(|&params| match_ast(graph, params, &["(", ")"], None).contains_key("__0__")),
    };
    let list_children = MethodListChildren {
        modifiers_ids: decorator_ids(args, n_id),
        ..MethodListChildren::default()
    };

    build_method_declaration_node(args, n_id, name, &direct, &list_children, None).map(Some)
}