use crate::query::{adj_ast, match_ast};
use crate::syntax::builders::for_each_statement::build_for_each_statement_node;
use crate::syntax::fields::javascript::for_in_statement;
use crate::syntax::{SyntaxGraphArgs, SyntaxGraphError};
use crate::{CodeGraph, NodeId};
pub fn reader(
args: &mut SyntaxGraphArgs<'_>,
n_id: NodeId,
) -> Result<Option<NodeId>, SyntaxGraphError> {
let graph = args.ast_graph;
let c_ids = adj_ast(graph, n_id, None, &[]);
let var_node = if let Ok(id) = args.required_field_alt(n_id, for_in_statement::LEFT) {
id
} else {
*c_ids.first().ok_or(SyntaxGraphError::UnexpectedAstShape)?
};
let iterable_item = if let Ok(id) = args.required_field_alt(n_id, for_in_statement::RIGHT) {
id
} else {
*c_ids.last().ok_or(SyntaxGraphError::UnexpectedAstShape)?
};
let mut block_id = args.required_field_alt(n_id, for_in_statement::BODY).ok();
if let Some(id) = block_id {
if graph.label_type(id) == Some("expression_statement") {
block_id = match_ast(graph, id, &[], None)
.get("__0__")
.copied()
.flatten();
}
}
build_for_each_statement_node(args, n_id, var_node, iterable_item, block_id).map(Some)
}