use super::{control_end, next, select, word, Statement, Token, TokenWithSpan};
pub(super) fn peel(
tokens: &[Token],
original: Option<&[TokenWithSpan]>,
mut at: usize,
procedural: bool,
out: &mut Vec<(Statement, bool)>,
) -> Option<usize> {
loop {
if tokens.get(at).is_some_and(|token| {
["IF", "ELSIF", "ELSEIF"]
.iter()
.any(|kind| word(token, kind))
}) {
let then = control_end(tokens, at + 1, "THEN")?;
if let Some(condition) = select(
&tokens[at + 1..then],
original.map(|tokens| &tokens[at + 1..then]),
true,
procedural,
) {
out.push((condition, true));
}
at = next(tokens, then + 1);
} else if procedural {
let Some(action) = start(tokens, at) else {
break;
};
at = action;
} else {
break;
}
if !procedural {
break;
}
}
Some(at)
}
pub(super) fn skip_empty_declarations(tokens: &[Token], at: usize) -> usize {
if tokens.get(at).is_some_and(|token| word(token, "DECLARE")) {
let tail = next(tokens, at + 1);
if tokens.get(tail).is_some_and(|token| word(token, "BEGIN")) {
return tail;
}
}
at
}
pub(super) fn start(tokens: &[Token], at: usize) -> Option<usize> {
let unlabeled = super::loop_header::skip_label(tokens, at);
let begin = skip_empty_declarations(tokens, unlabeled);
if tokens.get(begin).is_some_and(|token| word(token, "BEGIN")) {
let action = next(tokens, begin + 1);
return (unlabeled == at || super::loop_header::valid_control(&tokens[at..action]))
.then_some(action);
}
let first = tokens.get(at)?;
if word(first, "ELSE") {
return Some(next(tokens, at + 1));
}
let when = if word(first, "CASE") || word(first, "EXCEPTION") {
control_end(tokens, at + 1, "WHEN")?
} else {
word(first, "WHEN").then_some(at)?
};
control_end(tokens, when + 1, "THEN").map(|then| next(tokens, then + 1))
}