use crate::query::{adj_ast, match_ast};
use crate::syntax::builders::if_statement::build_if_node;
use crate::syntax::fields::java::if_statement;
use crate::syntax::{SyntaxGraphArgs, SyntaxGraphError};
use crate::{CodeGraph, NodeId};
fn unwrap_expression_statement(
args: &SyntaxGraphArgs<'_>,
n_id: NodeId,
) -> Result<NodeId, SyntaxGraphError> {
if args.ast_graph.label_type(n_id) == Some("expression_statement") {
return adj_ast(args.ast_graph, n_id, None, &[])
.first()
.copied()
.ok_or(SyntaxGraphError::UnexpectedAstShape);
}
Ok(n_id)
}
pub fn reader(
args: &mut SyntaxGraphArgs<'_>,
n_id: NodeId,
) -> Result<Option<NodeId>, SyntaxGraphError> {
let graph = args.ast_graph;
let mut condition_id = args.required_field_alt(n_id, if_statement::CONDITION)?;
if graph.label_type(condition_id) == Some("parenthesized_expression") {
if let Some(inner) = match_ast(graph, condition_id, &[], None)
.get("__1__")
.copied()
.flatten()
{
condition_id = inner;
}
}
let true_id = unwrap_expression_statement(
args,
args.required_field_alt(n_id, if_statement::CONSEQUENCE)?,
)?;
let false_id = match args.optional_field_alt(n_id, if_statement::ALTERNATIVE) {
Some(alternative_id) => Some(unwrap_expression_statement(args, alternative_id)?),
None => None,
};
build_if_node(args, n_id, condition_id, Some(true_id), false_id, None).map(Some)
}