use crate::query::adj_ast;
use crate::syntax::builders::do_statement::build_do_statement_node;
use crate::syntax::readers::constants::{C_SHARP_EXPRESSION, C_SHARP_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, Some(1), &[]);
let mut body_id = c_ids
.iter()
.copied()
.rfind(|c_id| {
graph
.label_type(*c_id)
.is_some_and(|kind| C_SHARP_STATEMENT.contains(&kind))
})
.ok_or(SyntaxGraphError::UnexpectedAstShape)?;
if graph.label_type(body_id) == Some("expression_statement") {
body_id = adj_ast(graph, body_id, Some(1), &[])
.first()
.copied()
.ok_or(SyntaxGraphError::UnexpectedAstShape)?;
}
let condition_id = c_ids
.iter()
.copied()
.rfind(|c_id| {
graph
.label_type(*c_id)
.is_some_and(|kind| C_SHARP_EXPRESSION.contains(&kind))
})
.ok_or(SyntaxGraphError::UnexpectedAstShape)?;
build_do_statement_node(args, n_id, body_id, condition_id).map(Some)
}