use std::sync::OnceLock;
use regex::Regex;
use tabnas::{Context, Lexer, Rule, RuleState, Tin, Token, Value, TIN_SP, TIN_VL};
use crate::daterange::{isodate_in_range, localtime_in_range};
use crate::values::{isodate_time, localtime_time};
pub(crate) fn isodate_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(concat!(
r"^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]",
r"([Tt ][0-9][0-9]:[0-9][0-9](:[0-9][0-9](\.[0-9]+)?)?",
r"([Zz]|[-+][0-9][0-9]:[0-9][0-9])?)?",
))
.expect("the isodate pattern is a literal and compiles")
})
}
pub(crate) fn localtime_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(r"^[0-9][0-9]:[0-9][0-9](:[0-9][0-9](\.[0-9]+)?)?")
.expect("the localtime pattern is a literal and compiles")
})
}
fn is_key_context(lexer: &Lexer<'_>, id_tin: Tin, rule: &Rule) -> bool {
let alts = if RuleState::Close == rule.state {
&rule.spec.close
} else {
&rule.spec.open
};
alts.iter().any(|alt| {
lexer.alt_enabled(alt) && alt.s.iter().any(|position| position.contains(&id_tin))
})
}
fn groups(found: ®ex::Captures<'_>) -> Vec<String> {
(0..found.len())
.map(|index| {
found
.get(index)
.map_or_else(String::new, |group| group.as_str().to_string())
})
.collect()
}
const DATE_LEAST: usize = 10;
const DATE_REACH: usize = 6;
fn captures_ahead(pattern: &Regex, lexer: &mut Lexer<'_>) -> Option<Vec<String>> {
let mut ahead = 32;
loop {
let more = lexer.fill(ahead);
let captured = pattern.captures(lexer.window()).map(|found| groups(&found));
if !lexer.windowed() || !more {
return captured;
}
let reads = captured
.as_ref()
.map_or(DATE_LEAST, |groups| groups[0].chars().count() + DATE_REACH);
if reads <= ahead {
return captured;
}
ahead = ahead.saturating_mul(2).max(reads);
}
}
fn date_matcher(
pattern: &'static Regex,
in_range: fn(&str) -> bool,
to_value: fn(&[String]) -> Value,
lexer: &mut Lexer<'_>,
rule: &mut Rule,
) -> Option<Token> {
let point = lexer.point();
let captured = captures_ahead(pattern, lexer)?;
let matched = captured.first().cloned().unwrap_or_default();
if matched.is_empty() {
return None;
}
let scalars = matched.chars().count();
let id_tin = lexer.token_tin("#ID");
let token = if is_key_context(lexer, id_tin, rule) {
lexer.token(
"#ID",
id_tin,
Value::String(matched.clone()),
matched,
point,
)
} else {
if !in_range(&matched) {
return Some(lexer.bad_span(
"invalid_datetime",
point.site.pos,
point.site.pos + scalars,
));
}
let value = to_value(&captured);
lexer.token("#VL", TIN_VL, value, matched, point)
};
lexer.advance_chars(scalars);
Some(token)
}
pub(crate) fn isodate_matcher(
lexer: &mut Lexer<'_>,
rule: &mut Rule,
_context: &mut Context,
) -> Option<Token> {
date_matcher(
isodate_re(),
isodate_in_range,
|groups| isodate_time(groups).to_value(),
lexer,
rule,
)
}
pub(crate) fn localtime_matcher(
lexer: &mut Lexer<'_>,
rule: &mut Rule,
_context: &mut Context,
) -> Option<Token> {
date_matcher(
localtime_re(),
localtime_in_range,
|groups| localtime_time(groups).to_value(),
lexer,
rule,
)
}
const BOM: char = '\u{feff}';
pub(crate) fn bom_matcher(
lexer: &mut Lexer<'_>,
_rule: &mut Rule,
_context: &mut Context,
) -> Option<Token> {
let point = lexer.point();
if 0 != point.site.pos {
return None;
}
lexer.fill(1);
if !lexer.window().starts_with(BOM) {
return None;
}
let token = lexer.token("#SP", TIN_SP, Value::Undefined, BOM.to_string(), point);
lexer.advance_chars(1);
Some(token)
}