1use std::cell::RefCell;
22use std::collections::HashMap;
23
24use indexmap::IndexMap;
25use tabnas::Value;
26
27use crate::cst::{NodeData, TokenData};
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum ScopeKind {
33 File,
34 FnProto,
35 FnBody,
36 Block,
37 StructUnion,
38 Enum,
39 ForInit,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Binding {
46 Typedef,
47 Ordinary,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum TagKind {
53 Struct,
54 Union,
55 Enum,
56}
57
58#[derive(Debug, Clone)]
59pub struct Scope {
60 #[allow(dead_code)]
61 pub kind: ScopeKind,
62 pub bind: HashMap<String, Binding>,
63 pub tags: HashMap<String, TagKind>,
64}
65
66#[derive(Debug, Clone)]
68pub struct SymbolTable {
69 stack: Vec<Scope>,
70}
71
72impl Default for SymbolTable {
73 fn default() -> Self {
74 Self::new()
75 }
76}
77
78impl SymbolTable {
79 pub fn new() -> Self {
80 Self {
81 stack: vec![Scope {
82 kind: ScopeKind::File,
83 bind: HashMap::new(),
84 tags: HashMap::new(),
85 }],
86 }
87 }
88
89 pub fn enter(&mut self, kind: ScopeKind) {
90 self.stack.push(Scope {
91 kind,
92 bind: HashMap::new(),
93 tags: HashMap::new(),
94 });
95 }
96
97 pub fn exit(&mut self) {
98 if self.stack.len() <= 1 {
100 return;
101 }
102 self.stack.pop();
103 }
104
105 #[allow(dead_code)]
106 pub fn depth(&self) -> usize {
107 self.stack.len()
108 }
109
110 pub fn is_typedef(&self, name: &str) -> bool {
113 for scope in self.stack.iter().rev() {
114 if let Some(binding) = scope.bind.get(name) {
115 return *binding == Binding::Typedef;
116 }
117 }
118 false
119 }
120
121 pub fn is_bound(&self, name: &str) -> bool {
123 self.stack
124 .iter()
125 .rev()
126 .any(|scope| scope.bind.contains_key(name))
127 }
128
129 pub fn bind_typedef(&mut self, name: &str) {
130 if let Some(scope) = self.stack.last_mut() {
131 scope.bind.insert(name.to_string(), Binding::Typedef);
132 }
133 }
134
135 pub fn bind_ordinary(&mut self, name: &str) {
136 if let Some(scope) = self.stack.last_mut() {
137 scope.bind.insert(name.to_string(), Binding::Ordinary);
138 }
139 }
140
141 pub fn bind_tag(&mut self, name: &str, kind: TagKind) {
142 if let Some(scope) = self.stack.last_mut() {
143 scope.tags.insert(name.to_string(), kind);
144 }
145 }
146
147 pub fn typedef_names(&self) -> Vec<String> {
151 let mut names: Vec<String> = Vec::new();
152 let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
153 for scope in self.stack.iter().rev() {
154 for (name, binding) in &scope.bind {
155 if seen.insert(name.as_str()) && *binding == Binding::Typedef {
156 names.push(name.clone());
157 }
158 }
159 }
160 names.sort();
161 names
162 }
163
164 #[allow(dead_code)]
165 pub fn has_tag(&self, name: &str) -> bool {
166 self.stack
167 .iter()
168 .rev()
169 .any(|scope| scope.tags.contains_key(name))
170 }
171}
172
173#[derive(Debug, Clone, Default)]
177pub struct MacroDef {
178 #[allow(dead_code)]
179 pub name: String,
180 #[allow(dead_code)]
181 pub is_function_like: bool,
182 #[allow(dead_code)]
183 pub params: Vec<String>,
184 #[allow(dead_code)]
185 pub variadic: bool,
186}
187
188#[derive(Debug, Clone, Default)]
189pub struct MacroTable {
190 defs: IndexMap<String, MacroDef>,
191}
192
193impl MacroTable {
194 pub fn define(&mut self, def: MacroDef) {
195 self.defs.insert(def.name.clone(), def);
196 }
197
198 pub fn undefine(&mut self, name: &str) {
199 self.defs.shift_remove(name);
200 }
201
202 pub fn has(&self, name: &str) -> bool {
203 self.defs.contains_key(name)
204 }
205
206 pub fn names(&self) -> Vec<String> {
208 self.defs.keys().cloned().collect()
209 }
210}
211
212#[derive(Debug, Clone, Default)]
215pub struct LexMode {
216 pub in_directive: bool,
219 pub expect_header_name: bool,
222 pub directive_name: Option<String>,
224 pub pp_newline_end: Option<usize>,
228}
229
230#[derive(Debug, Default)]
232pub struct CState {
233 pub symbols: SymbolTable,
234 pub macros: MacroTable,
235 pub mode: LexMode,
236 pub mode_at: Option<(usize, LexMode)>,
240 pub pending_trivia: Vec<usize>,
243 pub nodes: Vec<NodeData>,
245 pub tokens: TokenArena,
247 pub lists: Vec<Vec<usize>>,
252 pub flags: HashMap<(usize, String), bool>,
257 pub no_token: Option<usize>,
260 pub active: bool,
263 pub gave_up: bool,
268 pub rec: Vec<usize>,
273 pub rec_base: usize,
274 pub ed: Option<crate::fallback::ExtDecl>,
275 pub fixed: std::collections::HashSet<usize>,
277 pub links: crate::expr_grammar::LinkState,
280 pub stream: bool,
284 pub loop_marks: HashMap<usize, (usize, usize)>,
288}
289
290#[derive(Debug, Default)]
297pub struct TokenArena {
298 base: usize,
299 items: Vec<TokenData>,
300 kept: HashMap<usize, TokenData>,
301}
302
303static GONE: TokenData = TokenData {
306 name: String::new(),
307 src: String::new(),
308 span: crate::cst::Span {
309 start: 0,
310 end: 0,
311 line: 1,
312 col: 1,
313 },
314 leading: Vec::new(),
315};
316
317impl TokenArena {
318 pub fn len(&self) -> usize {
320 self.base + self.items.len()
321 }
322
323 pub fn push(&mut self, token: TokenData) {
324 self.items.push(token);
325 }
326
327 pub fn get(&self, id: usize) -> Option<&TokenData> {
328 if id >= self.base {
329 self.items.get(id - self.base)
330 } else {
331 self.kept.get(&id)
332 }
333 }
334
335 pub fn get_mut(&mut self, id: usize) -> Option<&mut TokenData> {
336 if id >= self.base {
337 self.items.get_mut(id - self.base)
338 } else {
339 self.kept.get_mut(&id)
340 }
341 }
342
343 #[cfg(test)]
345 pub fn held(&self) -> usize {
346 self.items.len() + self.kept.len()
347 }
348
349 pub fn release_below(&mut self, from: usize, keep: &std::collections::HashSet<usize>) {
352 let from = from.min(self.len());
353 self.kept.retain(|id, _| keep.contains(id));
354 if from <= self.base {
355 return;
356 }
357 let gone = from - self.base;
358 for (offset, token) in self.items.drain(..gone).enumerate() {
359 let id = self.base + offset;
360 if keep.contains(&id) {
361 self.kept.insert(id, token);
362 }
363 }
364 self.base = from;
365 }
366}
367
368impl std::ops::Index<usize> for TokenArena {
369 type Output = TokenData;
370
371 fn index(&self, id: usize) -> &TokenData {
372 self.get(id).unwrap_or(&GONE)
373 }
374}
375
376impl CState {
377 fn fresh() -> Self {
378 Self {
379 symbols: SymbolTable::new(),
380 macros: MacroTable::default(),
381 mode: LexMode::default(),
382 mode_at: None,
383 pending_trivia: Vec::new(),
384 nodes: Vec::new(),
385 tokens: TokenArena::default(),
386 lists: Vec::new(),
387 flags: HashMap::new(),
388 no_token: None,
389 active: false,
390 gave_up: false,
391 rec: Vec::new(),
392 rec_base: 0,
393 ed: None,
394 fixed: std::collections::HashSet::new(),
395 links: crate::expr_grammar::LinkState::default(),
396 stream: false,
397 loop_marks: HashMap::new(),
398 }
399 }
400}
401
402thread_local! {
403 static STATE: RefCell<CState> = RefCell::new(CState::fresh());
404}
405
406pub fn with_state<R>(body: impl FnOnce(&mut CState) -> R) -> R {
409 STATE.with(|state| body(&mut state.borrow_mut()))
410}
411
412pub fn reclaim(container: usize, v_abs: usize) {
423 with_state(|state| {
424 if !state.stream {
425 return;
426 }
427 let Some(&(nodes, lists)) = state.loop_marks.get(&container) else {
428 let began = (state.nodes.len(), state.lists.len());
429 state.loop_marks.insert(container, began);
430 return;
431 };
432 if state.nodes.len() > nodes {
433 state.nodes.truncate(nodes);
434 state.flags.retain(|(node, _), _| *node < nodes);
435 state.fixed.retain(|node| *node < nodes);
436 state.loop_marks.retain(|node, _| *node < nodes);
437 }
438 state.lists.truncate(lists);
439
440 let taken = v_abs.saturating_sub(state.rec_base).min(state.rec.len());
444 let mut from = state.tokens.len();
445 let mut from_place = usize::MAX;
446 for id in state.rec[taken..].iter() {
447 from = from.min(*id);
448 if let Some(token) = state.tokens.get(*id) {
449 from_place = from_place.min(token.span.start);
450 for trivia in &token.leading {
451 from = from.min(*trivia);
452 }
453 }
454 }
455 for id in &state.pending_trivia {
456 from = from.min(*id);
457 }
458 let mut keep: std::collections::HashSet<usize> =
459 state.links.prune(from_place).into_iter().collect();
460 if let Some(id) = state.no_token {
461 keep.insert(id);
462 }
463 for list in &state.lists {
464 keep.extend(list.iter().copied());
465 }
466 let mut items: Vec<&crate::cst::Item> = Vec::new();
467 for node in &state.nodes {
468 items.extend(node.children.iter());
469 items.extend(node.leading.iter());
470 items.extend(node.trailing.iter());
471 items.extend(node.extras.values());
472 }
473 while let Some(item) = items.pop() {
474 match item {
475 crate::cst::Item::List(list) => items.extend(list.iter()),
476 other => {
477 if let Some(id) = other.as_token() {
478 if keep.insert(id) {
479 if let Some(token) = state.tokens.get(id) {
480 keep.extend(token.leading.iter().copied());
481 }
482 }
483 }
484 }
485 }
486 }
487 state.tokens.release_below(from, &keep);
488 });
489}
490
491pub fn reset() {
493 STATE.with(|state| {
494 let mut state = state.borrow_mut();
495 *state = CState::fresh();
496 state.active = true;
497 });
498 crate::rt::reset_lookahead();
499}
500
501pub fn node_handle(id: usize) -> Value {
503 let mut entries = IndexMap::new();
504 entries.insert(crate::cst::NODE_KEY.to_string(), Value::Number(id as f64));
505 Value::object(entries)
506}
507
508pub fn token_handle(id: usize) -> Value {
510 let mut entries = IndexMap::new();
511 entries.insert(crate::cst::TOKEN_KEY.to_string(), Value::Number(id as f64));
512 Value::object(entries)
513}
514
515pub fn handle_node(value: &Value) -> Option<usize> {
518 handle_id(value, crate::cst::NODE_KEY)
519}
520
521pub fn handle_token(value: &Value) -> Option<usize> {
523 handle_id(value, crate::cst::TOKEN_KEY)
524}
525
526fn handle_id(value: &Value, key: &str) -> Option<usize> {
527 let Value::Object(entries) = value else {
528 return None;
529 };
530 if entries.len() != 1 {
531 return None;
532 }
533 match entries.get(key) {
534 Some(Value::Number(id)) if *id >= 0.0 => Some(*id as usize),
535 _ => None,
536 }
537}