pub fn balanced(text: &str) -> bool {
let b = text.as_bytes();
let mut depth = 0i32;
let mut i = 0;
while i < b.len() {
match b[i] {
b'#' => {
while i < b.len() && b[i] != b'\n' {
i += 1;
}
}
q @ (b'"' | b'\'') => {
let long = b[i..].starts_with(&[q, q, q]);
i += if long { 3 } else { 1 };
loop {
if i >= b.len() {
return false;
}
if b[i] == b'\\' {
i += 2;
continue;
}
if long && b[i..].starts_with(&[q, q, q]) {
i += 2;
break;
}
if !long && b[i] == q {
break;
}
if !long && b[i] == b'\n' {
return false;
}
i += 1;
}
}
b'<' => {
if let Some(end) = b[i + 1..].iter().position(|c| {
matches!(
c,
b'>' | b' ' | b'\t' | b'\n' | b'\r' | b'<' | b'"' | b'{' | b'}'
)
}) {
if b[i + 1 + end] == b'>' {
i += end + 1;
}
}
}
b'(' | b'[' | b'{' => depth += 1,
b')' | b']' | b'}' => depth -= 1,
_ => {}
}
i += 1;
}
depth <= 0
}
pub fn complete(
text: &str,
single_line: bool,
line_empty: bool,
parses: impl Fn(&str) -> bool,
) -> bool {
let t = text.trim();
if t.is_empty() || !balanced(t) {
return false;
}
t.ends_with(';') || line_empty || (single_line && parses(t))
}
pub fn strip_terminator(text: &str) -> &str {
text.trim()
.trim_end_matches(|c: char| c == ';' || c.is_whitespace())
}
pub fn is_update(text: &str) -> bool {
const UPDATES: &[&str] = &[
"INSERT", "DELETE", "LOAD", "CLEAR", "CREATE", "DROP", "COPY", "MOVE", "ADD", "WITH",
];
crate::studio::scanner::scan(text, None)
.tokens
.iter()
.find_map(|t| match &t.kind {
crate::studio::scanner::Kind::Word(w)
if !w.eq_ignore_ascii_case("PREFIX") && !w.eq_ignore_ascii_case("BASE") =>
{
Some(UPDATES.iter().any(|u| w.eq_ignore_ascii_case(u)))
}
_ => None,
})
.unwrap_or(false)
}