use crate::query::{adj_ast, match_ast};
use crate::syntax::builders::while_statement::build_while_statement_node;
use crate::syntax::readers::constants::PARENTHESIZED_EXPRESSION_CHILDREN_COUNT;
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 match_childs = match_ast(
graph,
n_id,
&["parenthesized_expression", "statement_block"],
None,
);
let mut block_id = match match_childs.get("statement_block").copied().flatten() {
Some(id) => id,
None => *adj_ast(graph, n_id, None, &[])
.last()
.ok_or(SyntaxGraphError::UnexpectedAstShape)?,
};
if graph.label_type(block_id) == Some("expression_statement") {
block_id = *adj_ast(graph, block_id, None, &[])
.first()
.ok_or(SyntaxGraphError::UnexpectedAstShape)?;
}
let mut conditional_id = match_childs
.get("parenthesized_expression")
.copied()
.flatten();
if let Some(cond) = conditional_id {
let adj_nodes = adj_ast(graph, cond, None, &[]);
conditional_id = if adj_nodes.len() == PARENTHESIZED_EXPRESSION_CHILDREN_COUNT {
adj_nodes.get(1).copied()
} else {
adj_nodes.first().copied()
};
}
build_while_statement_node(args, n_id, block_id, conditional_id).map(Some)
}