use crate::{
query::{adj_ast, label_text},
syntax::{
builders::unary_expression::build_unary_expression_node, SyntaxGraphArgs, SyntaxGraphError,
},
CodeGraph, NodeId,
};
use alloc::borrow::ToOwned;
pub fn reader(
args: &mut SyntaxGraphArgs<'_>,
n_id: NodeId,
) -> Result<Option<NodeId>, SyntaxGraphError> {
let graph = args.ast_graph;
let possible_operands = &[
"member_access_expression",
"variable_name",
"scoped_property_access_expression",
"subscript_expression",
];
let mut operand_n_id: Option<NodeId> = None;
let mut operator_n_id: Option<NodeId> = None;
let childs = adj_ast(graph, n_id, Some(1), &[]);
for &c_id in &childs {
if possible_operands.contains(&graph.label_type(c_id).unwrap_or("")) {
operand_n_id = Some(c_id);
} else {
operator_n_id = Some(c_id);
}
}
let (operator_id, operand_id) =
if let (Some(operand), Some(operator)) = (operand_n_id, operator_n_id) {
(operator, operand)
} else {
let operand = childs
.first()
.copied()
.ok_or(SyntaxGraphError::UnexpectedAstShape)?;
let operator = childs
.last()
.copied()
.ok_or(SyntaxGraphError::UnexpectedAstShape)?;
(operator, operand)
};
let operator = label_text(graph, operator_id).ok_or(SyntaxGraphError::UnexpectedAstShape)?;
build_unary_expression_node(args, n_id, operator.to_owned(), operand_id).map(Some)
}