use std::collections::HashSet;
use std::sync::Arc;
use tabnas::{
ActionBinding, AltError, AltErrorWithMatch, AltMatch, AltSpec, Context, ContextAction, Rule,
RuleSnapshot, RuleSpec, StateAction, Tabnas, Token,
};
use crate::cst;
use crate::state::with_state;
#[derive(Debug, Clone, Default)]
pub struct LocalScope {
pub v_abs: usize,
pub failed: bool,
}
#[derive(Debug, Clone, Default)]
pub struct ExtDecl {
pub armed: bool,
pub failed: bool,
pub unknown: bool,
pub trailing: bool,
pub scanned: usize,
pub depth: i64,
pub terminated: bool,
pub just_closed: bool,
pub first: String,
pub scopes: Vec<LocalScope>,
pub open: Vec<usize>,
pub typedef_names: Option<Vec<String>>,
}
impl ExtDecl {
fn innermost(&self) -> Option<&LocalScope> {
self.open.last().and_then(|id| self.scopes.get(*id))
}
fn innermost_mut(&mut self) -> Option<&mut LocalScope> {
let id = *self.open.last()?;
self.scopes.get_mut(id)
}
}
pub fn with_ed<R>(body: impl FnOnce(&mut ExtDecl) -> R) -> Option<R> {
with_state(|state| state.ed.as_mut().map(body))
}
pub fn record_token(token: &Token) -> Option<usize> {
if token.name.as_str() == "#ZZ" {
return None;
}
let id = cst::intern_token(token);
with_state(|state| {
let start = state.tokens[id].span.start;
if let Some(last) = state.rec.last_mut() {
if state.tokens[*last].span.start == start {
*last = id;
return;
}
}
state.rec.push(id);
});
Some(id)
}
pub fn start_declaration(context: &Context) {
with_state(|state| {
let taken = context.v_abs.saturating_sub(state.rec_base);
if taken > 0 {
if taken >= state.rec.len() {
state.rec.clear();
} else {
state.rec.drain(0..taken);
}
}
state.rec_base = context.v_abs;
state.ed = Some(ExtDecl::default());
});
}
pub fn taken_tokens(context: &Context) -> Vec<usize> {
with_state(|state| {
let n = context
.v_abs
.saturating_sub(state.rec_base)
.min(state.rec.len());
state.rec[..n].to_vec()
})
}
pub fn tokens_since(context: &Context, v_abs: usize) -> Vec<usize> {
with_state(|state| {
let from = v_abs.saturating_sub(state.rec_base);
let to = context
.v_abs
.saturating_sub(state.rec_base)
.min(state.rec.len());
if from >= to {
return Vec::new();
}
state.rec[from..to].to_vec()
})
}
pub fn bracket_depth(tokens: &[usize]) -> i64 {
let mut depth = 0;
for token in tokens {
match cst::token_name(*token).as_str() {
"PUNC_LPAREN" | "PUNC_LBRACKET" => depth += 1,
"PUNC_RPAREN" | "PUNC_RBRACKET" => depth -= 1,
_ => {}
}
}
depth
}
pub fn reclassify_untaken(context: &Context, name: &str, from: &str, to: &str) {
with_state(|state| {
let taken = context.v_abs.saturating_sub(state.rec_base);
let ids: Vec<usize> = state.rec.iter().skip(taken).copied().collect();
for id in ids {
if let Some(token) = state.tokens.get_mut(id) {
if token.name == from && token.src == name {
token.name = to.to_string();
}
}
}
});
}
pub fn open_local(context: &Context) -> Option<usize> {
with_ed(|ed| {
let id = ed.scopes.len();
ed.scopes.push(LocalScope {
v_abs: context.v_abs,
failed: false,
});
ed.open.push(id);
id
})
}
pub fn close_local(id: usize) {
with_ed(|ed| {
if let Some(at) = ed.open.iter().rposition(|open| *open == id) {
ed.open.truncate(at);
}
});
}
pub fn scope(id: usize) -> Option<LocalScope> {
with_ed(|ed| ed.scopes.get(id).cloned()).flatten()
}
pub fn chomp_ended(context: &Context) -> bool {
let synced = with_state(|state| {
let n = context.v_abs as i64 - state.rec_base as i64;
let ed = state.ed.as_mut()?;
let upto = (n.max(0) as usize).min(state.rec.len());
for index in ed.scanned..upto {
let name = state.tokens[state.rec[index]].name.as_str();
if index == 0 {
ed.first = name.to_string();
}
ed.just_closed = false;
match name {
"PUNC_LBRACE" => ed.depth += 1,
"PUNC_RBRACE" => {
ed.depth -= 1;
if ed.depth <= 0 {
ed.just_closed = true;
}
}
"PUNC_SEMI" if ed.depth == 0 => ed.terminated = true,
"PP_NEWLINE" if ed.depth == 0 && ed.first == "PP_HASH" => ed.terminated = true,
_ => {}
}
}
ed.scanned = ed.scanned.max(upto);
Some((n, ed.terminated, ed.just_closed))
});
let Some((n, terminated, just_closed)) = synced else {
return false;
};
if n <= 0 {
return false;
}
if terminated {
return true;
}
just_closed && starts_new_declaration(context)
}
pub fn fenced(context: &Context) -> bool {
let armed = with_ed(|ed| ed.armed && !ed.failed).unwrap_or(false);
armed && chomp_ended(context)
}
const STORAGE_CLASS: &[&str] = &[
"KW_TYPEDEF",
"KW_EXTERN",
"KW_STATIC",
"KW_AUTO",
"KW_REGISTER",
"KW__THREAD_LOCAL",
"KW_THREAD_LOCAL",
"KW_CONSTEXPR",
"KW___THREAD",
];
const TYPE_SPEC_KEYWORD: &[&str] = &[
"KW_VOID",
"KW_CHAR",
"KW_SHORT",
"KW_INT",
"KW_LONG",
"KW_FLOAT",
"KW_DOUBLE",
"KW_SIGNED",
"KW_UNSIGNED",
"KW_BOOL",
"KW__BOOL",
"KW__COMPLEX",
"KW__IMAGINARY",
"KW___SIGNED__",
"KW___SIGNED",
"KW___INT8",
"KW___INT16",
"KW___INT32",
"KW___INT64",
"KW_STRUCT",
"KW_UNION",
"KW_ENUM",
"KW_TYPEOF",
"KW_TYPEOF_UNQUAL",
"KW___TYPEOF__",
"KW___TYPEOF",
"KW__BITINT",
];
const TYPE_QUALIFIER: &[&str] = &[
"KW_CONST",
"KW_VOLATILE",
"KW_RESTRICT",
"KW__ATOMIC",
"KW___CONST__",
"KW___CONST",
"KW___VOLATILE__",
"KW___VOLATILE",
"KW___RESTRICT__",
"KW___RESTRICT",
];
const FUNCTION_SPECIFIER: &[&str] = &["KW_INLINE", "KW___INLINE__", "KW___INLINE", "KW__NORETURN"];
pub fn starts_new_declaration(context: &Context) -> bool {
for token in context.t.iter() {
let name = token.name.as_str();
match name {
"#SP"
| "#LN"
| "#CM"
| "TRIVIA_LINE_COMMENT"
| "TRIVIA_BLOCK_COMMENT"
| "TRIVIA_LINE_CONT" => continue,
"#ZZ" | "PP_HASH" | "PUNC_HASH" => return true,
_ => {}
}
if STORAGE_CLASS.contains(&name)
|| TYPE_SPEC_KEYWORD.contains(&name)
|| TYPE_QUALIFIER.contains(&name)
|| FUNCTION_SPECIFIER.contains(&name)
{
return true;
}
return matches!(
name,
"KW___ATTRIBUTE__"
| "KW___ATTRIBUTE"
| "KW___DECLSPEC"
| "KW___EXTENSION__"
| "TYPEDEF_NAME"
);
}
false
}
pub fn bailing() -> bool {
with_ed(|ed| ed.failed || ed.innermost().is_some_and(|scope| scope.failed)).unwrap_or(false)
}
pub fn armed() -> bool {
with_ed(|ed| {
if ed.failed {
return false;
}
match ed.innermost() {
Some(scope) => !scope.failed,
None => ed.armed,
}
})
.unwrap_or(false)
}
pub fn fail() {
with_ed(|ed| match ed.innermost_mut() {
Some(scope) => scope.failed = true,
None => ed.failed = true,
});
}
#[derive(Debug, Default, Clone)]
pub struct Fallback {
pub used: HashSet<String>,
pub fenced: Vec<(String, String)>,
}
impl Fallback {
pub fn bails(&self, name: &str) -> bool {
self.used.contains(name)
&& ["-bo", "-ao", "-bc", "-ac"]
.iter()
.any(|phase| name.ends_with(phase))
}
}
const ABOVE: &[&str] = &[
"translation_unit",
"extdecl_loop",
"conditional_group",
"conditional_branch",
"external_declaration",
"unknown_declaration",
];
fn token_count(s: Option<&serde_json::Value>) -> i64 {
match s {
Some(serde_json::Value::Array(items)) => items.len() as i64,
Some(serde_json::Value::String(text)) => text.split_whitespace().count() as i64,
_ => 0,
}
}
fn takes_token(alt: &serde_json::Map<String, serde_json::Value>) -> bool {
let back = alt
.get("b")
.and_then(serde_json::Value::as_i64)
.unwrap_or(0);
token_count(alt.get("s")) - back > 0
}
pub fn with_fallback(document: &mut serde_json::Value) -> Fallback {
let mut out = Fallback::default();
let Some(rules) = document
.get_mut("rule")
.and_then(serde_json::Value::as_object_mut)
else {
return out;
};
for (name, spec) in rules.iter_mut() {
if ABOVE.contains(&name.as_str()) {
continue;
}
let Some(spec) = spec.as_object_mut() else {
continue;
};
for state in ["open", "close"] {
let Some(alts) = spec
.get_mut(state)
.and_then(serde_json::Value::as_array_mut)
else {
continue;
};
if alts.is_empty() {
continue;
}
for alt in alts.iter_mut() {
let Some(alt) = alt.as_object_mut() else {
continue;
};
for key in ["a", "c"] {
if let Some(serde_json::Value::String(text)) = alt.get(key) {
out.used.insert(text.clone());
}
}
if takes_token(alt) {
match alt.get("c") {
Some(serde_json::Value::String(cond)) => {
let fenced = format!("{cond}~fenced");
out.fenced.push((fenced.clone(), cond.clone()));
alt.insert("c".to_string(), serde_json::Value::String(fenced));
}
None | Some(serde_json::Value::Null) => {
alt.insert(
"c".to_string(),
serde_json::Value::String("@c-unfenced".to_string()),
);
}
_ => {}
}
}
}
let at = alts
.first()
.and_then(|alt| alt.get("g"))
.and_then(serde_json::Value::as_str)
.is_some_and(|group| group.starts_with("catch-")) as usize;
alts.insert(at, serde_json::json!({ "c": "@c-bailing", "g": "c-bail" }));
alts.push(serde_json::json!({ "c": "@c-armed", "a": "@c-fail", "g": "c-fail" }));
}
for phase in ["bo", "ao", "bc", "ac"] {
out.used.insert(format!("@{name}-{phase}"));
}
}
out.fenced.sort();
out.fenced.dedup();
out
}
pub fn with_rule_fallback(parser: &mut Tabnas, names: &[&str]) {
for name in names {
parser.define_rule(*name, |spec: &mut RuleSpec| {
for alts in [&mut spec.open, &mut spec.close] {
if alts.is_empty() {
continue;
}
for alt in alts.iter_mut() {
fence_alt(alt);
}
alts.insert(0, bail_alt());
alts.push(fail_alt());
}
bail_actions(
&spec.bo,
&mut spec.bo_fns,
&mut spec.bo_state_fns,
&mut spec.bo_order,
);
bail_actions(
&spec.ao,
&mut spec.ao_fns,
&mut spec.ao_state_fns,
&mut spec.ao_order,
);
bail_actions(
&spec.bc,
&mut spec.bc_fns,
&mut spec.bc_state_fns,
&mut spec.bc_order,
);
bail_actions(
&spec.ac,
&mut spec.ac_fns,
&mut spec.ac_state_fns,
&mut spec.ac_order,
);
});
}
}
fn fence_alt(alt: &mut AltSpec) {
if alt.s.len() > alt.b {
let inner = alt.c_fn.take();
alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
!fenced(context)
&& inner
.as_ref()
.is_none_or(|condition| condition(rule, context))
}));
}
if let Some(hook) = alt.e.take() {
let hook: AltError = hook;
alt.e = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
if armed() {
fail();
return None;
}
hook(rule, context)
}));
}
if let Some(hook) = alt.e_match.take() {
let hook: AltErrorWithMatch = hook;
alt.e_match = Some(Arc::new(
move |rule: &mut Rule, context: &mut Context, matched: &mut AltMatch| {
if armed() {
fail();
return None;
}
hook(rule, context, matched)
},
));
}
}
fn bail_alt() -> AltSpec {
let mut alt = AltSpec::new();
alt.c_fn = Some(Arc::new(|_rule: &mut Rule, _context: &mut Context| {
bailing()
}));
alt.g = "c-bail".to_string();
alt
}
fn fail_alt() -> AltSpec {
let mut alt = AltSpec::new();
alt.c_fn = Some(Arc::new(|_rule: &mut Rule, _context: &mut Context| armed()));
alt.add_action(|_rule: &mut Rule, _context: &mut Context| fail());
alt.g = "c-fail".to_string();
alt
}
fn order_matches(
named: &[String],
callbacks: &[ContextAction],
states: &[StateAction],
order: &[ActionBinding],
) -> bool {
if order.len() != named.len() + callbacks.len() + states.len() {
return false;
}
let (mut name, mut callback, mut state) = (0, 0, 0);
for binding in order {
match binding {
ActionBinding::Named(text) => {
if named.get(name) != Some(text) {
return false;
}
name += 1;
}
ActionBinding::Callback(action) => {
if !callbacks
.get(callback)
.is_some_and(|expected| Arc::ptr_eq(expected, action))
{
return false;
}
callback += 1;
}
ActionBinding::State(action) => {
if !states
.get(state)
.is_some_and(|expected| Arc::ptr_eq(expected, action))
{
return false;
}
state += 1;
}
}
}
true
}
fn bail_actions(
named: &[String],
callbacks: &mut Vec<ContextAction>,
states: &mut Vec<StateAction>,
order: &mut Vec<ActionBinding>,
) {
let bindings: Vec<ActionBinding> = if order_matches(named, callbacks, states, order) {
order.clone()
} else {
named
.iter()
.cloned()
.map(ActionBinding::Named)
.chain(callbacks.iter().cloned().map(ActionBinding::Callback))
.chain(states.iter().cloned().map(ActionBinding::State))
.collect()
};
let mut new_callbacks = Vec::new();
let mut new_states = Vec::new();
let mut new_order = Vec::new();
for binding in bindings {
match binding {
ActionBinding::Named(text) => new_order.push(ActionBinding::Named(text)),
ActionBinding::Callback(action) => {
let wrapped: ContextAction =
Arc::new(move |rule: &mut Rule, context: &mut Context| {
if bailing() {
return Ok(());
}
action(rule, context)
});
new_callbacks.push(wrapped.clone());
new_order.push(ActionBinding::Callback(wrapped));
}
ActionBinding::State(action) => {
let wrapped: StateAction = Arc::new(
move |rule: &mut Rule,
context: &mut Context,
next: Option<&RuleSnapshot>,
out: Option<Token>| {
if bailing() {
return Ok(None);
}
action(rule, context, next, out)
},
);
new_states.push(wrapped.clone());
new_order.push(ActionBinding::State(wrapped));
}
}
}
*callbacks = new_callbacks;
*states = new_states;
*order = new_order;
}