use crate::query::match_ast_group_d;
use crate::syntax::builders::expression_statement::build_expression_statement_node;
use crate::syntax::builders::variable_declaration::build_variable_declaration_node;
use crate::syntax::fields::java::{
constant_declaration, local_variable_declaration, variable_declarator,
};
use crate::syntax::metadata::java::add_instance_to_metadata;
use crate::syntax::{SyntaxGraphArgs, SyntaxGraphError};
use crate::utilities::text_nodes::node_to_str;
use crate::{CodeGraph, NodeId};
pub fn reader(
args: &mut SyntaxGraphArgs<'_>,
n_id: NodeId,
) -> Result<Option<NodeId>, SyntaxGraphError> {
let declarator_ids = match_ast_group_d(args.ast_graph, n_id, "variable_declarator", None);
let &[declarator_id] = declarator_ids.as_slice() else {
return build_expression_statement_node(args, n_id, &declarator_ids).map(Some);
};
let var_type_id = match args.ast_graph.label_type(n_id) {
Some("constant_declaration") => {
args.required_field_alt(n_id, constant_declaration::TYPE)?
}
Some("local_variable_declaration") => {
args.required_field_alt(n_id, local_variable_declaration::TYPE)?
}
_ => return Err(SyntaxGraphError::UnexpectedAstShape),
};
let var_type = node_to_str(args.ast_graph, var_type_id);
let var_id = args.required_field_alt(declarator_id, variable_declarator::NAME)?;
let var_name = node_to_str(args.ast_graph, var_id);
let value_id = args.optional_field_alt(declarator_id, variable_declarator::VALUE);
if args.syntax_graph.nodes.contains_key(&NodeId(0)) {
add_instance_to_metadata(args, &var_type, &var_name, &[])?;
}
build_variable_declaration_node(args, n_id, var_name, Some(var_type), value_id, None, None)
.map(Some)
}