Skip to main content

tabnas_c/
state.rs

1/* Copyright (c) 2026 Richard Rodger and contributors, MIT License */
2
3//! Per-parse state: the symbol and macro tables, the lexer mode flags,
4//! the pending-trivia buffer, and the arena the concrete syntax tree is
5//! built in.
6//!
7//! Port of `ts/src/symbols.ts`, plus the arena this port needs and the
8//! other two do not. The canonical parser hangs all of this off
9//! `ctx.meta.cmeta` as live JavaScript objects that lex matchers and
10//! rule actions mutate through shared references. An engine `Value`
11//! here is copied on write and cannot hold a native handle, so the
12//! state lives in a thread local instead and the values that travel
13//! through the parse are HANDLES into it. This is the same device the
14//! `tabnas-expr` port uses for its expression nodes, for the same
15//! reason.
16//!
17//! A parse owns the thread local for its duration: `reset` runs from
18//! the engine's parse-prepare hook, and the tree is realized into plain
19//! engine values at the parse boundary (see [`crate::cst::realize`]).
20
21use std::cell::RefCell;
22use std::collections::HashMap;
23
24use indexmap::IndexMap;
25use tabnas::Value;
26
27use crate::cst::{NodeData, TokenData};
28
29/// The kind of scope a binding was made in. Inner scopes shadow outer
30/// ones, and lookups walk the stack outward.
31#[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/// What a name is bound to in a scope. Ordinary bindings matter because
43/// an inner non-typedef declaration of a name hides an outer typedef.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Binding {
46    Typedef,
47    Ordinary,
48}
49
50/// A struct, union or enum tag. Tags live in their own namespace in C.
51#[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/// The classic identifier / typedef-name disambiguation table.
67#[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        // The file scope is never popped.
99        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    /// True when `name` resolves to a typedef-name in any visible
111    /// scope, with the innermost binding winning.
112    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    /// True when `name` is bound at all, as a typedef or otherwise.
122    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    /// Every name bound as a typedef in any visible scope, innermost
148    /// binding winning, in no particular order. This is what a
149    /// [`crate::CMeta`] carries into a parse.
150    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/// A macro definition captured from a `#define` directive. Macros are
174/// not expanded: the table only says which names are macros, so a call
175/// site can be tagged.
176#[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    /// Every defined macro name, in definition order.
207    pub fn names(&self) -> Vec<String> {
208        self.defs.keys().cloned().collect()
209    }
210}
211
212/// Lex-mode flags the matchers read to know whether they are inside a
213/// preprocessor directive line.
214#[derive(Debug, Clone, Default)]
215pub struct LexMode {
216    /// True between the start-of-logical-line `#` and the terminating
217    /// newline.
218    pub in_directive: bool,
219    /// True when the next token inside a directive should be lexed as a
220    /// header name.
221    pub expect_header_name: bool,
222    /// The directive name currently being parsed, or `None`.
223    pub directive_name: Option<String>,
224}
225
226/// Everything a C parse keeps beside the engine's own state.
227#[derive(Debug, Default)]
228pub struct CState {
229    pub symbols: SymbolTable,
230    pub macros: MacroTable,
231    pub mode: LexMode,
232    /// Trivia tokens emitted since the last non-trivia token, as arena
233    /// ids. The lex subscriber drains this onto the next token.
234    pub pending_trivia: Vec<usize>,
235    /// The concrete syntax tree under construction.
236    pub nodes: Vec<NodeData>,
237    /// Every token the parse has handed to a rule action.
238    pub tokens: Vec<TokenData>,
239    /// Token lists a rule keeps on its `k` bag. A JavaScript array is
240    /// shared by reference between a rule and the rules it pushes or
241    /// replaces into, and an engine `Value` is copied on write, so the
242    /// bag holds the id of a list kept here instead.
243    pub lists: Vec<Vec<usize>>,
244    /// Flags a handler sets on a node rather than on a rule. The
245    /// canonical handlers write a few of these onto a PARENT rule's `u`
246    /// bag; a parent reaches this port only as a snapshot, whose bags
247    /// are copies, so the flag rides on a node both rules can see.
248    pub flags: HashMap<(usize, String), bool>,
249    /// The arena id of the no-token sentinel, once something has asked
250    /// for it. See `cst::no_token`.
251    pub no_token: Option<usize>,
252    /// Set while a parse is running, so a nested parse (the grammar
253    /// document is itself parsed by jsonic) cannot reset the arena.
254    pub active: bool,
255    /// Set when a walk over the tree gave up rather than recursing
256    /// past what the stack holds. `crate::parse_with` reads it and
257    /// fails the parse instead of handing back a tree with a hole in
258    /// it. See `crate::REALIZE_DEPTH_CAP`.
259    pub gave_up: bool,
260    /// The whole source as characters, with the address and length it
261    /// was built from.
262    ///
263    /// The canonical matchers index the source with `charCodeAt`, which
264    /// costs nothing. A Rust `&str` cannot be indexed by character, so
265    /// the matchers here work over a `[char]`, and building that per
266    /// call, for every matcher, at every token, made the parse cost grow
267    /// with the SQUARE of the input: 40 KB of C took a minute. It is
268    /// built once per parse instead and handed out as a shared slice.
269    ///
270    /// The key is the source's address and length. Two live sources
271    /// cannot share both, and `reset` clears this at the start of every
272    /// parse, so a stale entry cannot outlive the text it came from.
273    pub source_chars: Option<(usize, usize, std::rc::Rc<Vec<char>>)>,
274}
275
276impl CState {
277    fn fresh() -> Self {
278        Self {
279            symbols: SymbolTable::new(),
280            macros: MacroTable::default(),
281            mode: LexMode::default(),
282            pending_trivia: Vec::new(),
283            nodes: Vec::new(),
284            tokens: Vec::new(),
285            lists: Vec::new(),
286            flags: HashMap::new(),
287            no_token: None,
288            active: false,
289            gave_up: false,
290            source_chars: None,
291        }
292    }
293}
294
295thread_local! {
296    static STATE: RefCell<CState> = RefCell::new(CState::fresh());
297}
298
299/// Run `body` with the parse state. Keep the closure short: the state
300/// is a `RefCell`, so a nested borrow panics.
301pub fn with_state<R>(body: impl FnOnce(&mut CState) -> R) -> R {
302    STATE.with(|state| body(&mut state.borrow_mut()))
303}
304
305/// Start a parse: clear everything the previous one left behind.
306pub fn reset() {
307    STATE.with(|state| {
308        let mut state = state.borrow_mut();
309        *state = CState::fresh();
310        state.active = true;
311    });
312    crate::rt::reset_lookahead();
313}
314
315/// The value that stands for a node in the engine's value tree.
316pub fn node_handle(id: usize) -> Value {
317    let mut entries = IndexMap::new();
318    entries.insert(crate::cst::NODE_KEY.to_string(), Value::Number(id as f64));
319    Value::object(entries)
320}
321
322/// The value that stands for a token in the engine's value tree.
323pub fn token_handle(id: usize) -> Value {
324    let mut entries = IndexMap::new();
325    entries.insert(crate::cst::TOKEN_KEY.to_string(), Value::Number(id as f64));
326    Value::object(entries)
327}
328
329/// The node id a handle names, or `None` when the value is something
330/// else.
331pub fn handle_node(value: &Value) -> Option<usize> {
332    handle_id(value, crate::cst::NODE_KEY)
333}
334
335/// The token id a handle names, or `None`.
336pub fn handle_token(value: &Value) -> Option<usize> {
337    handle_id(value, crate::cst::TOKEN_KEY)
338}
339
340fn handle_id(value: &Value, key: &str) -> Option<usize> {
341    let Value::Object(entries) = value else {
342        return None;
343    };
344    if entries.len() != 1 {
345        return None;
346    }
347    match entries.get(key) {
348        Some(Value::Number(id)) if *id >= 0.0 => Some(*id as usize),
349        _ => None,
350    }
351}