tabnas-c 0.6.1

C23 concrete-syntax-tree grammar plugin for the tabnas parsing engine, over the jsonic base grammar
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
/* Copyright (c) 2026 Richard Rodger and contributors, MIT License */

//! The armed fallback: how an external declaration the rules cannot
//! parse becomes an unknown declaration, where the parser up to 0.5
//! handed it to a structurer that took any token run. Port of
//! `ts/src/fallback.ts`, which has the design.
//!
//! `external_declaration` dispatches on its head (`c-grammar.jsonic`). A
//! route the parser has always held to the rules is strict: a
//! declaration the rules cannot parse there is refused. Every other
//! route is armed. An armed declaration is the token run the 0.5
//! parser's chomp absorbed, and that run ends where the chomp ended it:
//! after a `;` at brace depth 0, after the newline that ends a `#` line,
//! after a `}` back to depth 0 when the next token starts a declaration
//! (`starts_new_declaration`), or at the end. Inside it every rule below
//! `external_declaration` has a bail (the first alternate of each state,
//! which ends the state once the declaration has failed) and a catch-all
//! (the last, which fails the declaration where no other alternate
//! matches), and every alternate that takes a token is fenced at the
//! chomp's end. The plugin records the tokens it lexes (the sub-lex hook
//! in `crate::trivia`), and the engine's count of the tokens taken
//! (`context.v_abs`) says how many of them the declaration holds.
//!
//! TypeScript catches what a ref throws in an armed declaration, and Go
//! recovers what one panics, and fails the declaration; over the 16,916
//! documents of the conformance sweep (`docs/rules.md`) no ref throws, and
//! this port leaves a panic a panic.

use std::collections::HashSet;
use std::sync::Arc;

use tabnas::{
    ActionBinding, AltError, AltErrorWithMatch, AltMatch, AltSpec, Context, ContextAction, Rule,
    RuleSnapshot, RuleSpec, StateAction, Tabnas, Token,
};

use crate::cst;
use crate::state::with_state;

/// A rule that catches a failure below it (`asm_operand`).
#[derive(Debug, Clone, Default)]
pub struct LocalScope {
    pub v_abs: usize,
    pub failed: bool,
}

/// The state of the external declaration being parsed.
#[derive(Debug, Clone, Default)]
pub struct ExtDecl {
    /// The route is armed, not strict.
    pub armed: bool,
    /// An armed declaration the rules failed on: every state bails.
    pub failed: bool,
    /// The declaration is an unknown one: its children are its tokens.
    pub unknown: bool,
    /// The rules ended an armed declaration before the chomp's end: the
    /// rest of the run follows what they built, flat.
    pub trailing: bool,
    /// The chomp's state over the tokens taken so far.
    pub scanned: usize,
    pub depth: i64,
    pub terminated: bool,
    pub just_closed: bool,
    pub first: String,
    /// Every local scope opened in the declaration, by id, and the open
    /// ones, innermost last. A failure inside an open one fails the
    /// scope, not the declaration.
    pub scopes: Vec<LocalScope>,
    pub open: Vec<usize>,
    /// The names a strict typedef declaration's rules found, bound when
    /// the declaration ends.
    pub typedef_names: Option<Vec<String>>,
}

impl ExtDecl {
    fn innermost(&self) -> Option<&LocalScope> {
        self.open.last().and_then(|id| self.scopes.get(*id))
    }

    fn innermost_mut(&mut self) -> Option<&mut LocalScope> {
        let id = *self.open.last()?;
        self.scopes.get_mut(id)
    }
}

/// Run `body` with the external declaration being parsed, when there is
/// one.
pub fn with_ed<R>(body: impl FnOnce(&mut ExtDecl) -> R) -> Option<R> {
    with_state(|state| state.ed.as_mut().map(body))
}

/// Record a token the lexer gave the parser, and answer its arena id.
/// Called from the sub-lex hook for every token that is not trivia; the
/// engine takes them in the order they are lexed.
pub fn record_token(token: &Token) -> Option<usize> {
    if token.name.as_str() == "#ZZ" {
        return None;
    }
    let id = cst::intern_token(token);
    with_state(|state| {
        let start = state.tokens[id].span.start;
        // A re-announced token (the engine's relex undo) replaces the last.
        if let Some(last) = state.rec.last_mut() {
            if state.tokens[*last].span.start == start {
                *last = id;
                return;
            }
        }
        state.rec.push(id);
    });
    Some(id)
}

/// Start an external declaration: drop the record's tokens the previous
/// ones took, and reset the state.
pub fn start_declaration(context: &Context) {
    with_state(|state| {
        let taken = context.v_abs.saturating_sub(state.rec_base);
        if taken > 0 {
            if taken >= state.rec.len() {
                state.rec.clear();
            } else {
                state.rec.drain(0..taken);
            }
        }
        state.rec_base = context.v_abs;
        state.ed = Some(ExtDecl::default());
    });
}

/// The tokens the declaration has taken, in order, as arena ids.
pub fn taken_tokens(context: &Context) -> Vec<usize> {
    with_state(|state| {
        let n = context
            .v_abs
            .saturating_sub(state.rec_base)
            .min(state.rec.len());
        state.rec[..n].to_vec()
    })
}

/// The tokens taken since a count of tokens taken.
pub fn tokens_since(context: &Context, v_abs: usize) -> Vec<usize> {
    with_state(|state| {
        let from = v_abs.saturating_sub(state.rec_base);
        let to = context
            .v_abs
            .saturating_sub(state.rec_base)
            .min(state.rec.len());
        if from >= to {
            return Vec::new();
        }
        state.rec[from..to].to_vec()
    })
}

/// The depth of `(` and `[` a run of tokens leaves open.
pub fn bracket_depth(tokens: &[usize]) -> i64 {
    let mut depth = 0;
    for token in tokens {
        match cst::token_name(*token).as_str() {
            "PUNC_LPAREN" | "PUNC_LBRACKET" => depth += 1,
            "PUNC_RPAREN" | "PUNC_RBRACKET" => depth -= 1,
            _ => {}
        }
    }
    depth
}

/// The tokens lexed but not yet taken, which a reclassification of the
/// lookahead renames, as the canonical's record holds the lookahead's
/// own token objects.
pub fn reclassify_untaken(context: &Context, name: &str, from: &str, to: &str) {
    with_state(|state| {
        let taken = context.v_abs.saturating_sub(state.rec_base);
        let ids: Vec<usize> = state.rec.iter().skip(taken).copied().collect();
        for id in ids {
            if let Some(token) = state.tokens.get_mut(id) {
                if token.name == from && token.src == name {
                    token.name = to.to_string();
                }
            }
        }
    });
}

/// Open a local scope at the tokens taken so far, and answer its id.
pub fn open_local(context: &Context) -> Option<usize> {
    with_ed(|ed| {
        let id = ed.scopes.len();
        ed.scopes.push(LocalScope {
            v_abs: context.v_abs,
            failed: false,
        });
        ed.open.push(id);
        id
    })
}

/// Close a local scope (and any left open inside it).
pub fn close_local(id: usize) {
    with_ed(|ed| {
        if let Some(at) = ed.open.iter().rposition(|open| *open == id) {
            ed.open.truncate(at);
        }
    });
}

/// The scope `id`: the count of tokens taken when it opened, and whether
/// it has failed.
pub fn scope(id: usize) -> Option<LocalScope> {
    with_ed(|ed| ed.scopes.get(id).cloned()).flatten()
}

/// True when the chomp would end the declaration after the tokens taken,
/// given the next token (`context.t[0]`, which the caller has fetched).
pub fn chomp_ended(context: &Context) -> bool {
    let synced = with_state(|state| {
        let n = context.v_abs as i64 - state.rec_base as i64;
        let ed = state.ed.as_mut()?;
        let upto = (n.max(0) as usize).min(state.rec.len());
        for index in ed.scanned..upto {
            let name = state.tokens[state.rec[index]].name.as_str();
            if index == 0 {
                ed.first = name.to_string();
            }
            ed.just_closed = false;
            match name {
                "PUNC_LBRACE" => ed.depth += 1,
                "PUNC_RBRACE" => {
                    ed.depth -= 1;
                    if ed.depth <= 0 {
                        ed.just_closed = true;
                    }
                }
                "PUNC_SEMI" if ed.depth == 0 => ed.terminated = true,
                "PP_NEWLINE" if ed.depth == 0 && ed.first == "PP_HASH" => ed.terminated = true,
                _ => {}
            }
        }
        ed.scanned = ed.scanned.max(upto);
        Some((n, ed.terminated, ed.just_closed))
    });
    let Some((n, terminated, just_closed)) = synced else {
        return false;
    };
    if n <= 0 {
        return false;
    }
    if terminated {
        return true;
    }
    just_closed && starts_new_declaration(context)
}

/// The fence: an armed declaration that has reached the chomp's end takes
/// no more tokens.
pub fn fenced(context: &Context) -> bool {
    let armed = with_ed(|ed| ed.armed && !ed.failed).unwrap_or(false);
    armed && chomp_ended(context)
}

/// Token-name sets of the chomp's own test, unchanged from 0.5.
const STORAGE_CLASS: &[&str] = &[
    "KW_TYPEDEF",
    "KW_EXTERN",
    "KW_STATIC",
    "KW_AUTO",
    "KW_REGISTER",
    "KW__THREAD_LOCAL",
    "KW_THREAD_LOCAL",
    "KW_CONSTEXPR",
    "KW___THREAD",
];
const TYPE_SPEC_KEYWORD: &[&str] = &[
    "KW_VOID",
    "KW_CHAR",
    "KW_SHORT",
    "KW_INT",
    "KW_LONG",
    "KW_FLOAT",
    "KW_DOUBLE",
    "KW_SIGNED",
    "KW_UNSIGNED",
    "KW_BOOL",
    "KW__BOOL",
    "KW__COMPLEX",
    "KW__IMAGINARY",
    "KW___SIGNED__",
    "KW___SIGNED",
    "KW___INT8",
    "KW___INT16",
    "KW___INT32",
    "KW___INT64",
    "KW_STRUCT",
    "KW_UNION",
    "KW_ENUM",
    "KW_TYPEOF",
    "KW_TYPEOF_UNQUAL",
    "KW___TYPEOF__",
    "KW___TYPEOF",
    "KW__BITINT",
];
const TYPE_QUALIFIER: &[&str] = &[
    "KW_CONST",
    "KW_VOLATILE",
    "KW_RESTRICT",
    "KW__ATOMIC",
    "KW___CONST__",
    "KW___CONST",
    "KW___VOLATILE__",
    "KW___VOLATILE",
    "KW___RESTRICT__",
    "KW___RESTRICT",
];
const FUNCTION_SPECIFIER: &[&str] = &["KW_INLINE", "KW___INLINE__", "KW___INLINE", "KW__NORETURN"];

/// True when the next token is one that starts an external declaration.
/// The chomp asked this after a `}` back to depth 0, to tell a function
/// body's end from a struct body's.
pub fn starts_new_declaration(context: &Context) -> bool {
    for token in context.t.iter() {
        let name = token.name.as_str();
        match name {
            "#SP"
            | "#LN"
            | "#CM"
            | "TRIVIA_LINE_COMMENT"
            | "TRIVIA_BLOCK_COMMENT"
            | "TRIVIA_LINE_CONT" => continue,
            "#ZZ" | "PP_HASH" | "PUNC_HASH" => return true,
            _ => {}
        }
        if STORAGE_CLASS.contains(&name)
            || TYPE_SPEC_KEYWORD.contains(&name)
            || TYPE_QUALIFIER.contains(&name)
            || FUNCTION_SPECIFIER.contains(&name)
        {
            return true;
        }
        return matches!(
            name,
            "KW___ATTRIBUTE__"
                | "KW___ATTRIBUTE"
                | "KW___DECLSPEC"
                | "KW___EXTENSION__"
                | "TYPEDEF_NAME"
        );
    }
    false
}

/// Is the declaration being parsed, or its innermost scope, failed? A
/// lifecycle action does nothing then.
pub fn bailing() -> bool {
    with_ed(|ed| ed.failed || ed.innermost().is_some_and(|scope| scope.failed)).unwrap_or(false)
}

/// The catch-all's condition: the declaration is armed, or a scope is
/// open, and neither has failed.
pub fn armed() -> bool {
    with_ed(|ed| {
        if ed.failed {
            return false;
        }
        match ed.innermost() {
            Some(scope) => !scope.failed,
            None => ed.armed,
        }
    })
    .unwrap_or(false)
}

/// The catch-all's action: fail the innermost scope, or the declaration.
pub fn fail() {
    with_ed(|ed| match ed.innermost_mut() {
        Some(scope) => scope.failed = true,
        None => ed.failed = true,
    });
}

/// What the fallback did to the grammar document: the refs whose
/// lifecycle actions bail once a declaration has failed, and each fenced
/// condition with the condition it fences.
#[derive(Debug, Default, Clone)]
pub struct Fallback {
    pub used: HashSet<String>,
    pub fenced: Vec<(String, String)>,
}

impl Fallback {
    /// Does a lifecycle action of this name bail?
    pub fn bails(&self, name: &str) -> bool {
        self.used.contains(name)
            && ["-bo", "-ao", "-bc", "-ac"]
                .iter()
                .any(|phase| name.ends_with(phase))
    }
}

/// The rules above the fallback: they are not given the bail and the
/// catch-all, and their refs are not wrapped.
const ABOVE: &[&str] = &[
    "translation_unit",
    "extdecl_loop",
    "conditional_group",
    "conditional_branch",
    "external_declaration",
    "unknown_declaration",
];

fn token_count(s: Option<&serde_json::Value>) -> i64 {
    match s {
        Some(serde_json::Value::Array(items)) => items.len() as i64,
        Some(serde_json::Value::String(text)) => text.split_whitespace().count() as i64,
        _ => 0,
    }
}

/// An alternate takes a token when it matches more tokens than it gives
/// back.
fn takes_token(alt: &serde_json::Map<String, serde_json::Value>) -> bool {
    let back = alt
        .get("b")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(0);
    token_count(alt.get("s")) - back > 0
}

/// Give every rule below `external_declaration` the bail and the
/// catch-all, and put the fence on every alternate that takes a token, in
/// the grammar document; answer the refs it uses and the fenced
/// conditions, which `crate::refs` binds.
pub fn with_fallback(document: &mut serde_json::Value) -> Fallback {
    let mut out = Fallback::default();
    let Some(rules) = document
        .get_mut("rule")
        .and_then(serde_json::Value::as_object_mut)
    else {
        return out;
    };
    for (name, spec) in rules.iter_mut() {
        if ABOVE.contains(&name.as_str()) {
            continue;
        }
        let Some(spec) = spec.as_object_mut() else {
            continue;
        };
        for state in ["open", "close"] {
            let Some(alts) = spec
                .get_mut(state)
                .and_then(serde_json::Value::as_array_mut)
            else {
                continue;
            };
            if alts.is_empty() {
                continue;
            }
            for alt in alts.iter_mut() {
                let Some(alt) = alt.as_object_mut() else {
                    continue;
                };
                for key in ["a", "c"] {
                    if let Some(serde_json::Value::String(text)) = alt.get(key) {
                        out.used.insert(text.clone());
                    }
                }
                if takes_token(alt) {
                    match alt.get("c") {
                        Some(serde_json::Value::String(cond)) => {
                            let fenced = format!("{cond}~fenced");
                            out.fenced.push((fenced.clone(), cond.clone()));
                            alt.insert("c".to_string(), serde_json::Value::String(fenced));
                        }
                        None | Some(serde_json::Value::Null) => {
                            alt.insert(
                                "c".to_string(),
                                serde_json::Value::String("@c-unfenced".to_string()),
                            );
                        }
                        _ => {}
                    }
                }
            }
            // A rule that catches a failure below it has its catch first,
            // and the bail after it.
            let at = alts
                .first()
                .and_then(|alt| alt.get("g"))
                .and_then(serde_json::Value::as_str)
                .is_some_and(|group| group.starts_with("catch-")) as usize;
            alts.insert(at, serde_json::json!({ "c": "@c-bailing", "g": "c-bail" }));
            alts.push(serde_json::json!({ "c": "@c-armed", "a": "@c-fail", "g": "c-fail" }));
        }
        for phase in ["bo", "ao", "bc", "ac"] {
            out.used.insert(format!("@{name}-{phase}"));
        }
    }
    out.fenced.sort();
    out.fenced.dedup();
    out
}

/// [`with_fallback`] for rules a plugin installs below the grammar, whose
/// alternates and actions are closures rather than refs: expr's `val`,
/// `expr`, `paren` and `ternary`, over which C's expressions are read, and
/// the jsonic rules expr pushes. Each state gets the bail first and the
/// catch-all last; an alternate that takes a token gets the fence; an
/// alternate's error hook, in an armed declaration, fails it rather than
/// refusing the document; and a lifecycle closure does nothing once the
/// declaration has failed, as a ref's does. Port of `withRuleFallback` in
/// `ts/src/fallback.ts`.
///
/// A lifecycle action jsonic's rules name, rather than hold, is the
/// engine's to resolve and is left as it is: the bail ends each state
/// before any alternate pushes one of those rules in a failed declaration.
pub fn with_rule_fallback(parser: &mut Tabnas, names: &[&str]) {
    for name in names {
        parser.define_rule(*name, |spec: &mut RuleSpec| {
            for alts in [&mut spec.open, &mut spec.close] {
                if alts.is_empty() {
                    continue;
                }
                for alt in alts.iter_mut() {
                    fence_alt(alt);
                }
                alts.insert(0, bail_alt());
                alts.push(fail_alt());
            }
            bail_actions(
                &spec.bo,
                &mut spec.bo_fns,
                &mut spec.bo_state_fns,
                &mut spec.bo_order,
            );
            bail_actions(
                &spec.ao,
                &mut spec.ao_fns,
                &mut spec.ao_state_fns,
                &mut spec.ao_order,
            );
            bail_actions(
                &spec.bc,
                &mut spec.bc_fns,
                &mut spec.bc_state_fns,
                &mut spec.bc_order,
            );
            bail_actions(
                &spec.ac,
                &mut spec.ac_fns,
                &mut spec.ac_state_fns,
                &mut spec.ac_order,
            );
        });
    }
}

/// Put the fence on an alternate that takes a token, and make its error
/// hooks fail an armed declaration rather than refuse the document.
fn fence_alt(alt: &mut AltSpec) {
    if alt.s.len() > alt.b {
        let inner = alt.c_fn.take();
        alt.c_fn = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
            !fenced(context)
                && inner
                    .as_ref()
                    .is_none_or(|condition| condition(rule, context))
        }));
    }
    if let Some(hook) = alt.e.take() {
        let hook: AltError = hook;
        alt.e = Some(Arc::new(move |rule: &mut Rule, context: &mut Context| {
            if armed() {
                fail();
                return None;
            }
            hook(rule, context)
        }));
    }
    if let Some(hook) = alt.e_match.take() {
        let hook: AltErrorWithMatch = hook;
        alt.e_match = Some(Arc::new(
            move |rule: &mut Rule, context: &mut Context, matched: &mut AltMatch| {
                if armed() {
                    fail();
                    return None;
                }
                hook(rule, context, matched)
            },
        ));
    }
}

/// The bail: the first alternate of a state, which ends it once the
/// declaration (or its innermost scope) has failed.
fn bail_alt() -> AltSpec {
    let mut alt = AltSpec::new();
    alt.c_fn = Some(Arc::new(|_rule: &mut Rule, _context: &mut Context| {
        bailing()
    }));
    alt.g = "c-bail".to_string();
    alt
}

/// The catch-all: the last alternate of a state, which fails an armed
/// declaration where no other alternate matched.
fn fail_alt() -> AltSpec {
    let mut alt = AltSpec::new();
    alt.c_fn = Some(Arc::new(|_rule: &mut Rule, _context: &mut Context| armed()));
    alt.add_action(|_rule: &mut Rule, _context: &mut Context| fail());
    alt.g = "c-fail".to_string();
    alt
}

/// Whether a lifecycle's bindings are the order it runs in: the named
/// actions, the callbacks and the state callbacks, each in its own order
/// (the engine's own test, which it falls back from when they are not).
fn order_matches(
    named: &[String],
    callbacks: &[ContextAction],
    states: &[StateAction],
    order: &[ActionBinding],
) -> bool {
    if order.len() != named.len() + callbacks.len() + states.len() {
        return false;
    }
    let (mut name, mut callback, mut state) = (0, 0, 0);
    for binding in order {
        match binding {
            ActionBinding::Named(text) => {
                if named.get(name) != Some(text) {
                    return false;
                }
                name += 1;
            }
            ActionBinding::Callback(action) => {
                if !callbacks
                    .get(callback)
                    .is_some_and(|expected| Arc::ptr_eq(expected, action))
                {
                    return false;
                }
                callback += 1;
            }
            ActionBinding::State(action) => {
                if !states
                    .get(state)
                    .is_some_and(|expected| Arc::ptr_eq(expected, action))
                {
                    return false;
                }
                state += 1;
            }
        }
    }
    true
}

/// Make each lifecycle closure of a phase do nothing once the declaration
/// has failed, keeping the order the phase runs them in.
fn bail_actions(
    named: &[String],
    callbacks: &mut Vec<ContextAction>,
    states: &mut Vec<StateAction>,
    order: &mut Vec<ActionBinding>,
) {
    let bindings: Vec<ActionBinding> = if order_matches(named, callbacks, states, order) {
        order.clone()
    } else {
        named
            .iter()
            .cloned()
            .map(ActionBinding::Named)
            .chain(callbacks.iter().cloned().map(ActionBinding::Callback))
            .chain(states.iter().cloned().map(ActionBinding::State))
            .collect()
    };
    let mut new_callbacks = Vec::new();
    let mut new_states = Vec::new();
    let mut new_order = Vec::new();
    for binding in bindings {
        match binding {
            ActionBinding::Named(text) => new_order.push(ActionBinding::Named(text)),
            ActionBinding::Callback(action) => {
                let wrapped: ContextAction =
                    Arc::new(move |rule: &mut Rule, context: &mut Context| {
                        if bailing() {
                            return Ok(());
                        }
                        action(rule, context)
                    });
                new_callbacks.push(wrapped.clone());
                new_order.push(ActionBinding::Callback(wrapped));
            }
            ActionBinding::State(action) => {
                let wrapped: StateAction = Arc::new(
                    move |rule: &mut Rule,
                          context: &mut Context,
                          next: Option<&RuleSnapshot>,
                          out: Option<Token>| {
                        if bailing() {
                            return Ok(None);
                        }
                        action(rule, context, next, out)
                    },
                );
                new_states.push(wrapped.clone());
                new_order.push(ActionBinding::State(wrapped));
            }
        }
    }
    *callbacks = new_callbacks;
    *states = new_states;
    *order = new_order;
}