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>,
}
#[derive(Debug, Default)]
pub struct CState {
pub symbols: SymbolTable,
pub macros: MacroTable,
pub mode: LexMode,
pub pending_trivia: Vec<usize>,
pub nodes: Vec<NodeData>,
pub tokens: Vec<TokenData>,
pub lists: Vec<Vec<usize>>,
pub flags: HashMap<(usize, String), bool>,
pub no_token: Option<usize>,
pub active: bool,
pub gave_up: bool,
pub source_chars: Option<(usize, usize, std::rc::Rc<Vec<char>>)>,
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,
}
impl CState {
fn fresh() -> Self {
Self {
symbols: SymbolTable::new(),
macros: MacroTable::default(),
mode: LexMode::default(),
pending_trivia: Vec::new(),
nodes: Vec::new(),
tokens: Vec::new(),
lists: Vec::new(),
flags: HashMap::new(),
no_token: None,
active: false,
gave_up: false,
source_chars: None,
rec: Vec::new(),
rec_base: 0,
ed: None,
fixed: std::collections::HashSet::new(),
links: crate::expr_grammar::LinkState::default(),
}
}
}
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 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,
}
}