use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use crate::dialect::TheLabelOfACommand;
pub(crate) fn the_label_of_the_command(name: &str) -> Option<TheLabelOfACommand> {
if name.eq_ignore_ascii_case("GroupAdd") {
return Some(TheLabelOfACommand::Label(3));
}
if name.eq_ignore_ascii_case("Hotkey") {
return Some(TheLabelOfACommand::LabelOrFunction(1));
}
if name.eq_ignore_ascii_case("SetTimer") {
return Some(TheLabelOfACommand::LabelOrFunction(0));
}
None
}
pub(crate) fn the_refusal_of_a_goto(
name: &str,
chain: &[crate::parser::TheBlock],
labels: &[(String, Vec<crate::parser::TheBlock>)],
) -> Option<String> {
let Some((_, chain_of_the_label)) = labels
.iter()
.find(|(label, _)| label.eq_ignore_ascii_case(name))
else {
return Some(format!(
"Target label does not exist.\n Specifically: {name}"
));
};
if !the_chain_of_the_label_is_the_beginning(chain_of_the_label, chain) {
return Some(
"A Goto/Gosub must not jump into a block that doesn't enclose it.".to_string(),
);
}
let function = chain
.iter()
.rev()
.find(|block| block.function)
.map(|block| block.id);
if let Some(function) = function {
let inside = chain_of_the_label
.iter()
.any(|block| block.function && block.id == function);
if !inside {
return Some("Cannot jump from inside a function to outside.".to_string());
}
}
None
}
fn the_chain_of_the_label_is_the_beginning(
chain_of_the_label: &[crate::parser::TheBlock],
chain_of_the_goto: &[crate::parser::TheBlock],
) -> bool {
if chain_of_the_label.len() > chain_of_the_goto.len() {
return false;
}
chain_of_the_label
.iter()
.zip(chain_of_the_goto.iter())
.all(|(label, jump)| label.id == jump.id)
}