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    /// The position just past the last directive's newline: a `#` that a
225    /// window of the source begins just before, after space, starts a line
226    /// if a lone `\r` ended a directive there (`matchers::at_line_start`).
227    pub pp_newline_end: Option<usize>,
228}
229
230/// Everything a C parse keeps beside the engine's own state.
231#[derive(Debug, Default)]
232pub struct CState {
233    pub symbols: SymbolTable,
234    pub macros: MacroTable,
235    pub mode: LexMode,
236    /// Where `mode` last changed, as a position in the source, and what it
237    /// was there: a token the engine cuts again over a grown window is cut
238    /// from that mode (`matchers::mode_for`).
239    pub mode_at: Option<(usize, LexMode)>,
240    /// Trivia tokens emitted since the last non-trivia token, as arena
241    /// ids. The lex subscriber drains this onto the next token.
242    pub pending_trivia: Vec<usize>,
243    /// The concrete syntax tree under construction.
244    pub nodes: Vec<NodeData>,
245    /// Every token the parse has handed to a rule action.
246    pub tokens: TokenArena,
247    /// Token lists a rule keeps on its `k` bag. A JavaScript array is
248    /// shared by reference between a rule and the rules it pushes or
249    /// replaces into, and an engine `Value` is copied on write, so the
250    /// bag holds the id of a list kept here instead.
251    pub lists: Vec<Vec<usize>>,
252    /// Flags a handler sets on a node rather than on a rule. The
253    /// canonical handlers write a few of these onto a PARENT rule's `u`
254    /// bag; a parent reaches this port only as a snapshot, whose bags
255    /// are copies, so the flag rides on a node both rules can see.
256    pub flags: HashMap<(usize, String), bool>,
257    /// The arena id of the no-token sentinel, once something has asked
258    /// for it. See `cst::no_token`.
259    pub no_token: Option<usize>,
260    /// Set while a parse is running, so a nested parse (the grammar
261    /// document is itself parsed by jsonic) cannot reset the arena.
262    pub active: bool,
263    /// Set when a walk over the tree gave up rather than recursing
264    /// past what the stack holds. `crate::parse_with` reads it and
265    /// fails the parse instead of handing back a tree with a hole in
266    /// it. See `crate::REALIZE_DEPTH_CAP`.
267    pub gave_up: bool,
268    /// The record of the tokens the lexer gave the parser, as arena ids,
269    /// from the first the current external declaration has not taken
270    /// (`rec_base` is the count of tokens taken before it), and that
271    /// declaration's state: the armed fallback's (`crate::fallback`).
272    pub rec: Vec<usize>,
273    pub rec_base: usize,
274    pub ed: Option<crate::fallback::ExtDecl>,
275    /// The nodes already given their spans (`crate::cst::fix_spans`).
276    pub fixed: std::collections::HashSet<usize>,
277    /// The links between an expression's tokens
278    /// (`crate::expr_grammar::link_token`).
279    pub links: crate::expr_grammar::LinkState,
280    /// Set for a parse of the streaming parser (`crate::make_streaming`),
281    /// whose containers keep nothing of what has closed, and whose arena
282    /// lets a closed declaration's nodes and tokens go (`crate::reclaim`).
283    pub stream: bool,
284    /// For the streaming parser, where each container's items loop began:
285    /// the counts of nodes and lists made before its first item, by the
286    /// container's node id.
287    pub loop_marks: HashMap<usize, (usize, usize)>,
288}
289
290/// The tokens a parse has handed to a rule action, by arena id. An id
291/// names its token for the whole parse. The streaming parser lets the
292/// tokens of the declarations it has closed go (`crate::reclaim`): the
293/// arena then holds the ids from `base` on in `items`, and the few older
294/// tokens still named, those of the conditional lines open around the
295/// declaration being read, in `kept`.
296#[derive(Debug, Default)]
297pub struct TokenArena {
298    base: usize,
299    items: Vec<TokenData>,
300    kept: HashMap<usize, TokenData>,
301}
302
303/// What a token id no longer in the arena reads as: a token with no name
304/// and no text.
305static 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    /// The id the next token takes: one past every id given.
319    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    /// How many tokens the arena holds.
344    #[cfg(test)]
345    pub fn held(&self) -> usize {
346        self.items.len() + self.kept.len()
347    }
348
349    /// Let the tokens below `from` go, but those `keep` names: the ids
350    /// stay theirs.
351    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
406/// Run `body` with the parse state. Keep the closure short: the state
407/// is a `RefCell`, so a nested borrow panics.
408pub fn with_state<R>(body: impl FnOnce(&mut CState) -> R) -> R {
409    STATE.with(|state| body(&mut state.borrow_mut()))
410}
411
412/// For the streaming parser, as an external declaration of the items loop
413/// of `container` (the translation unit's node, or a conditional
414/// branch's) starts: let go of what the container's earlier items made,
415/// which a container of the streaming parser does not keep. The nodes and
416/// token lists made since the loop's first item go, and their ids with
417/// them; the tokens before the first one the parse has not taken (`v_abs`
418/// is the count taken) go, but those that a node or a token list still
419/// held names (a conditional line open around the declaration) and those
420/// an open bracket's links name, which keep their ids. The first item
421/// records where the loop began.
422pub 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        // The tokens lexed and not yet taken, and the comments before
441        // them, are the oldest a later step reads, but for those named
442        // below.
443        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
491/// Start a parse: clear everything the previous one left behind.
492pub 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
501/// The value that stands for a node in the engine's value tree.
502pub 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
508/// The value that stands for a token in the engine's value tree.
509pub 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
515/// The node id a handle names, or `None` when the value is something
516/// else.
517pub fn handle_node(value: &Value) -> Option<usize> {
518    handle_id(value, crate::cst::NODE_KEY)
519}
520
521/// The token id a handle names, or `None`.
522pub 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}