use std::cell::RefCell;
use std::collections::HashMap;
use indexmap::IndexMap;
use tabnas::Value;
use crate::cst::{NodeData, TokenData};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScopeKind {
File,
FnProto,
FnBody,
Block,
StructUnion,
Enum,
ForInit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Binding {
Typedef,
Ordinary,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TagKind {
Struct,
Union,
Enum,
}
#[derive(Debug, Clone)]
pub struct Scope {
#[allow(dead_code)]
pub kind: ScopeKind,
pub bind: HashMap<String, Binding>,
pub tags: HashMap<String, TagKind>,
}
#[derive(Debug, Clone)]
pub struct SymbolTable {
stack: Vec<Scope>,
}
impl Default for SymbolTable {
fn default() -> Self {
Self::new()
}
}
impl SymbolTable {
pub fn new() -> Self {
Self {
stack: vec![Scope {
kind: ScopeKind::File,
bind: HashMap::new(),
tags: HashMap::new(),
}],
}
}
pub fn enter(&mut self, kind: ScopeKind) {
self.stack.push(Scope {
kind,
bind: HashMap::new(),
tags: HashMap::new(),
});
}
pub fn exit(&mut self) {
if self.stack.len() <= 1 {
return;
}
self.stack.pop();
}
#[allow(dead_code)]
pub fn depth(&self) -> usize {
self.stack.len()
}
pub fn is_typedef(&self, name: &str) -> bool {
for scope in self.stack.iter().rev() {
if let Some(binding) = scope.bind.get(name) {
return *binding == Binding::Typedef;
}
}
false
}
pub fn is_bound(&self, name: &str) -> bool {
self.stack
.iter()
.rev()
.any(|scope| scope.bind.contains_key(name))
}
pub fn bind_typedef(&mut self, name: &str) {
if let Some(scope) = self.stack.last_mut() {
scope.bind.insert(name.to_string(), Binding::Typedef);
}
}
pub fn bind_ordinary(&mut self, name: &str) {
if let Some(scope) = self.stack.last_mut() {
scope.bind.insert(name.to_string(), Binding::Ordinary);
}
}
pub fn bind_tag(&mut self, name: &str, kind: TagKind) {
if let Some(scope) = self.stack.last_mut() {
scope.tags.insert(name.to_string(), kind);
}
}
pub fn typedef_names(&self) -> Vec<String> {
let mut names: Vec<String> = Vec::new();
let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
for scope in self.stack.iter().rev() {
for (name, binding) in &scope.bind {
if seen.insert(name.as_str()) && *binding == Binding::Typedef {
names.push(name.clone());
}
}
}
names.sort();
names
}
#[allow(dead_code)]
pub fn has_tag(&self, name: &str) -> bool {
self.stack
.iter()
.rev()
.any(|scope| scope.tags.contains_key(name))
}
}
#[derive(Debug, Clone, Default)]
pub struct MacroDef {
#[allow(dead_code)]
pub name: String,
#[allow(dead_code)]
pub is_function_like: bool,
#[allow(dead_code)]
pub params: Vec<String>,
#[allow(dead_code)]
pub variadic: bool,
}
#[derive(Debug, Clone, Default)]
pub struct MacroTable {
defs: IndexMap<String, MacroDef>,
}
impl MacroTable {
pub fn define(&mut self, def: MacroDef) {
self.defs.insert(def.name.clone(), def);
}
pub fn undefine(&mut self, name: &str) {
self.defs.shift_remove(name);
}
pub fn has(&self, name: &str) -> bool {
self.defs.contains_key(name)
}
pub fn names(&self) -> Vec<String> {
self.defs.keys().cloned().collect()
}
}
#[derive(Debug, Clone, Default)]
pub struct LexMode {
pub in_directive: bool,
pub expect_header_name: bool,
pub directive_name: Option<String>,
pub pp_newline_end: Option<usize>,
}
#[derive(Debug, Default)]
pub struct CState {
pub symbols: SymbolTable,
pub macros: MacroTable,
pub mode: LexMode,
pub mode_at: Option<(usize, LexMode)>,
pub pending_trivia: Vec<usize>,
pub nodes: Vec<NodeData>,
pub tokens: TokenArena,
pub lists: Vec<Vec<usize>>,
pub flags: HashMap<(usize, String), bool>,
pub no_token: Option<usize>,
pub active: bool,
pub gave_up: bool,
pub rec: Vec<usize>,
pub rec_base: usize,
pub ed: Option<crate::fallback::ExtDecl>,
pub fixed: std::collections::HashSet<usize>,
pub links: crate::expr_grammar::LinkState,
pub stream: bool,
pub loop_marks: HashMap<usize, (usize, usize)>,
}
#[derive(Debug, Default)]
pub struct TokenArena {
base: usize,
items: Vec<TokenData>,
kept: HashMap<usize, TokenData>,
}
static GONE: TokenData = TokenData {
name: String::new(),
src: String::new(),
span: crate::cst::Span {
start: 0,
end: 0,
line: 1,
col: 1,
},
leading: Vec::new(),
};
impl TokenArena {
pub fn len(&self) -> usize {
self.base + self.items.len()
}
pub fn push(&mut self, token: TokenData) {
self.items.push(token);
}
pub fn get(&self, id: usize) -> Option<&TokenData> {
if id >= self.base {
self.items.get(id - self.base)
} else {
self.kept.get(&id)
}
}
pub fn get_mut(&mut self, id: usize) -> Option<&mut TokenData> {
if id >= self.base {
self.items.get_mut(id - self.base)
} else {
self.kept.get_mut(&id)
}
}
#[cfg(test)]
pub fn held(&self) -> usize {
self.items.len() + self.kept.len()
}
pub fn release_below(&mut self, from: usize, keep: &std::collections::HashSet<usize>) {
let from = from.min(self.len());
self.kept.retain(|id, _| keep.contains(id));
if from <= self.base {
return;
}
let gone = from - self.base;
for (offset, token) in self.items.drain(..gone).enumerate() {
let id = self.base + offset;
if keep.contains(&id) {
self.kept.insert(id, token);
}
}
self.base = from;
}
}
impl std::ops::Index<usize> for TokenArena {
type Output = TokenData;
fn index(&self, id: usize) -> &TokenData {
self.get(id).unwrap_or(&GONE)
}
}
impl CState {
fn fresh() -> Self {
Self {
symbols: SymbolTable::new(),
macros: MacroTable::default(),
mode: LexMode::default(),
mode_at: None,
pending_trivia: Vec::new(),
nodes: Vec::new(),
tokens: TokenArena::default(),
lists: Vec::new(),
flags: HashMap::new(),
no_token: None,
active: false,
gave_up: false,
rec: Vec::new(),
rec_base: 0,
ed: None,
fixed: std::collections::HashSet::new(),
links: crate::expr_grammar::LinkState::default(),
stream: false,
loop_marks: HashMap::new(),
}
}
}
thread_local! {
static STATE: RefCell<CState> = RefCell::new(CState::fresh());
}
pub fn with_state<R>(body: impl FnOnce(&mut CState) -> R) -> R {
STATE.with(|state| body(&mut state.borrow_mut()))
}
pub fn reclaim(container: usize, v_abs: usize) {
with_state(|state| {
if !state.stream {
return;
}
let Some(&(nodes, lists)) = state.loop_marks.get(&container) else {
let began = (state.nodes.len(), state.lists.len());
state.loop_marks.insert(container, began);
return;
};
if state.nodes.len() > nodes {
state.nodes.truncate(nodes);
state.flags.retain(|(node, _), _| *node < nodes);
state.fixed.retain(|node| *node < nodes);
state.loop_marks.retain(|node, _| *node < nodes);
}
state.lists.truncate(lists);
let taken = v_abs.saturating_sub(state.rec_base).min(state.rec.len());
let mut from = state.tokens.len();
let mut from_place = usize::MAX;
for id in state.rec[taken..].iter() {
from = from.min(*id);
if let Some(token) = state.tokens.get(*id) {
from_place = from_place.min(token.span.start);
for trivia in &token.leading {
from = from.min(*trivia);
}
}
}
for id in &state.pending_trivia {
from = from.min(*id);
}
let mut keep: std::collections::HashSet<usize> =
state.links.prune(from_place).into_iter().collect();
if let Some(id) = state.no_token {
keep.insert(id);
}
for list in &state.lists {
keep.extend(list.iter().copied());
}
let mut items: Vec<&crate::cst::Item> = Vec::new();
for node in &state.nodes {
items.extend(node.children.iter());
items.extend(node.leading.iter());
items.extend(node.trailing.iter());
items.extend(node.extras.values());
}
while let Some(item) = items.pop() {
match item {
crate::cst::Item::List(list) => items.extend(list.iter()),
other => {
if let Some(id) = other.as_token() {
if keep.insert(id) {
if let Some(token) = state.tokens.get(id) {
keep.extend(token.leading.iter().copied());
}
}
}
}
}
}
state.tokens.release_below(from, &keep);
});
}
pub fn reset() {
STATE.with(|state| {
let mut state = state.borrow_mut();
*state = CState::fresh();
state.active = true;
});
crate::rt::reset_lookahead();
}
pub fn node_handle(id: usize) -> Value {
let mut entries = IndexMap::new();
entries.insert(crate::cst::NODE_KEY.to_string(), Value::Number(id as f64));
Value::object(entries)
}
pub fn token_handle(id: usize) -> Value {
let mut entries = IndexMap::new();
entries.insert(crate::cst::TOKEN_KEY.to_string(), Value::Number(id as f64));
Value::object(entries)
}
pub fn handle_node(value: &Value) -> Option<usize> {
handle_id(value, crate::cst::NODE_KEY)
}
pub fn handle_token(value: &Value) -> Option<usize> {
handle_id(value, crate::cst::TOKEN_KEY)
}
fn handle_id(value: &Value, key: &str) -> Option<usize> {
let Value::Object(entries) = value else {
return None;
};
if entries.len() != 1 {
return None;
}
match entries.get(key) {
Some(Value::Number(id)) if *id >= 0.0 => Some(*id as usize),
_ => None,
}
}