rhaiper 0.2.0

Minifier for Rhai scripts, with Source Map v3 output
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
//! Works out which identifier tokens are renameable local bindings, and which are not.
//!
//! Classification comes from rhai's AST, because the parser has already made the distinction that
//! matters most: it demotes `Expr::Variable` to `Expr::Property` inside dot-chains, so properties
//! and map keys — which are string data, not variables — are identified authoritatively rather than
//! guessed at from token context.
//!
//! Scope *structure* comes from the token stream instead. `StmtBlock` is the only AST type carrying
//! a real span, and it is missing exactly where it would be needed most: parameter positions are
//! collected by the parser and then discarded (`parser.rs:3687`), and an expression-bodied closure
//! reports no end position at all.
//!
//! `Stmt` and `Expr` are both `#[non_exhaustive]`, so no downstream crate can match them
//! exhaustively and a future rhai release may add nodes this code cannot see. That is handled by
//! [`Analysis::unclassified`]: every identifier token must be accounted for by some rule, and
//! anything left over blocks renaming for the whole script. Unknown syntax therefore costs
//! compression, never correctness.

use std::collections::{HashMap, HashSet};
use std::ops::Range;

use rhai::{ASTNode, Engine, Expr, Ident, Position, Stmt, Token};

use crate::lex::Tok;
use crate::stream::LineIndex;

/// A local binding that may be renamed, together with every token that refers to it.
#[derive(Debug, Clone)]
pub struct Binding {
    pub name: String,
    /// Byte offset of the declaring identifier token.
    pub decl: usize,
    /// Byte range within which the binding is visible.
    pub scope: Range<usize>,
    /// Byte offsets of the declaration and all of its references.
    pub sites: Vec<usize>,
}

#[derive(Debug, Default)]
pub struct Analysis {
    pub bindings: Vec<Binding>,
    /// Identifier tokens no rule could classify. Non-empty means renaming must be declined.
    pub unclassified: Vec<(usize, String)>,
    /// Names that appear anywhere and so must not be produced by the name allocator.
    pub taken: HashSet<String>,
}

/// Byte ranges of every `{`..`}` and `#{`..`}` pair, brace-matched over the token stream.
struct Blocks(Vec<Range<usize>>);

impl Blocks {
    fn new(toks: &[&Tok]) -> Self {
        let mut open: Vec<usize> = Vec::new();
        let mut ranges = Vec::new();
        for tok in toks {
            match tok.token {
                Token::LeftBrace | Token::MapStart => open.push(tok.span.start),
                Token::RightBrace => {
                    if let Some(start) = open.pop() {
                        ranges.push(start..tok.span.end);
                    }
                }
                _ => (),
            }
        }
        Self(ranges)
    }

    /// The innermost block containing `offset`, if any.
    fn innermost(&self, offset: usize) -> Option<&Range<usize>> {
        self.0
            .iter()
            .filter(|r| r.start < offset && offset < r.end)
            .max_by_key(|r| r.start)
    }

    fn containing(&self, offset: usize) -> Option<Range<usize>> {
        self.innermost(offset).cloned()
    }
}

/// Finds the body block introduced by a header starting at token index `from`.
///
/// Scans forward for the first `{` that is not nested inside brackets, parentheses or a map literal,
/// so `for x in #{a:1}.keys() { .. }` finds the loop body rather than the map.
///
/// Closers are ignored at depth zero, because callers start the scan inside the header — at a
/// parameter or the loop variable — so the header's own `)` would otherwise drive the depth negative
/// and no `{` would ever match.
fn body_block(toks: &[&Tok], from: usize, blocks: &Blocks) -> Option<Range<usize>> {
    let mut depth = 0i32;
    for tok in &toks[from..] {
        match tok.token {
            Token::LeftParen | Token::LeftBracket | Token::MapStart => depth += 1,
            Token::RightParen | Token::RightBracket | Token::RightBrace if depth > 0 => depth -= 1,
            Token::LeftBrace if depth == 0 => {
                return blocks.0.iter().find(|r| r.start == tok.span.start).cloned();
            }
            Token::LeftBrace => depth += 1,
            _ => (),
        }
    }
    None
}

#[derive(Default)]
struct FromAst {
    /// Declaration sites: byte offset of the name token.
    decls: Vec<(usize, String, DeclKind)>,
    /// Reference sites.
    refs: Vec<(usize, String)>,
    /// Offsets that are properties or map keys, which are string data and never renameable.
    blocked: HashSet<usize>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DeclKind {
    /// `let` or `const`; visible from the declaration to the end of its block.
    Var,
    /// A `for` loop variable or counter; visible in the loop body.
    Loop,
    /// A `catch` binding; visible in the catch block.
    Catch,
}

/// Collects declarations, references and blocked positions from the AST.
fn walk_ast(src: &str, lines: &LineIndex, engine: &Engine) -> Result<FromAst, String> {
    let ast = engine
        .compile(src)
        .map_err(|e| format!("input script does not parse: {e}"))?;
    let mut found = FromAst::default();

    let offset_of = |pos: Position| lines.byte_offset_of(src, pos);

    let visit = |node: &ASTNode, found: &mut FromAst| match node {
        ASTNode::Stmt(stmt) => match stmt {
            Stmt::Var(x, ..) => push_decl(&mut found.decls, &x.0, DeclKind::Var, &offset_of),
            Stmt::For(x, ..) => {
                push_decl(&mut found.decls, &x.0, DeclKind::Loop, &offset_of);
                if let Some(counter) = &x.1 {
                    push_decl(&mut found.decls, counter, DeclKind::Loop, &offset_of);
                }
            }
            Stmt::TryCatch(x, ..) => {
                // The catch binding is stashed in the flow control's `expr` slot, and `walk` does
                // not descend into it.
                if let Expr::Variable(v, .., pos) = &x.expr
                    && let Some(offset) = offset_of(*pos)
                {
                    found.decls.push((offset, v.1.to_string(), DeclKind::Catch));
                }
            }
            // Closure captures need no arm of their own. `Stmt::Share` and the `curry(...)` call
            // that accompanies it are built from the same list of externals, each carrying its
            // ident's position verbatim, and the two are siblings inside one `Expr::Stmt` block
            // (`parser.rs:3706-3773`). So the `Expr::Variable` arm below already sees every capture
            // — twice over, in fact, since the reference also appears inside the closure's own body.
            // Not naming `Stmt::Share` is what lets this crate compile under `no_closure`.
            _ => (),
        },
        ASTNode::Expr(expr) => match expr {
            Expr::Variable(x, .., pos) => {
                if let Some(offset) = offset_of(*pos) {
                    found.refs.push((offset, x.1.to_string()));
                }
            }
            Expr::Property(x, pos) => {
                if let Some(offset) = offset_of(*pos) {
                    found.blocked.insert(offset);
                }
                let _ = &x.2;
            }
            Expr::Map(x, ..) => {
                for (key, _) in x.0.iter() {
                    if let Some(offset) = offset_of(key.pos) {
                        found.blocked.insert(offset);
                    }
                }
            }
            _ => (),
        },
        _ => (),
    };

    let path = &mut Vec::new();
    for stmt in ast.statements() {
        stmt.walk(path, &mut |p| {
            if let Some(node) = p.last() {
                visit(node, &mut found);
            }
            true
        });
    }
    // Function bodies live in the shared library rather than as statements, and each is its own
    // scope root, so they are walked separately.
    //
    // Under `no_function` both `AST::iter_fn_def` and `ScriptFuncDef::body` are gone, and there is
    // nothing to walk anyway: with no functions and no closures every binding is top level, and top
    // level is never renamed.
    #[cfg(not(feature = "no_function"))]
    for func in ast.iter_fn_def() {
        for stmt in func.body.iter() {
            stmt.walk(path, &mut |p| {
                if let Some(node) = p.last() {
                    visit(node, &mut found);
                }
                true
            });
        }
    }
    Ok(found)
}

fn push_decl(
    out: &mut Vec<(usize, String, DeclKind)>,
    ident: &Ident,
    kind: DeclKind,
    offset_of: &impl Fn(Position) -> Option<usize>,
) {
    if let Some(offset) = offset_of(ident.pos) {
        out.push((offset, ident.name.to_string(), kind));
    }
}

/// Keywords whose `Token` variant is removed by a rhai feature, resolved through rhai's own table.
///
/// `Token::lookup_symbol_from_syntax` is ungated, but its entries are not — `("fn", Token::Fn)` is
/// `#[cfg(not(feature = "no_function"))]`, and likewise `?.` for `no_object` and `as` for
/// `no_module`. So each lookup yields `Some` exactly when the keyword exists in this build, and the
/// branches that test for it correctly go dead otherwise. Naming the variants directly would instead
/// stop the crate compiling.
///
/// Comparing `Token` values rather than source text matters: a token whose text happens to read `fn`
/// cannot be mistaken for the keyword.
mod keywords {
    use rhai::Token;

    fn lookup(syntax: &str) -> Option<Token> {
        Token::lookup_symbol_from_syntax(syntax)
    }

    /// `fn`, absent under `no_function`.
    pub fn fn_decl() -> Option<Token> {
        lookup("fn")
    }

    /// `as`, absent under `no_module`.
    pub fn module_alias() -> Option<Token> {
        lookup("as")
    }

    /// `?.`, absent under `no_object`.
    pub fn elvis() -> Option<Token> {
        lookup("?.")
    }
}

/// Whether `token` is the keyword `expected`, which may not exist in this build.
fn is_keyword(token: &Token, expected: &Option<Token>) -> bool {
    expected.as_ref() == Some(token)
}

/// Parameter lists, taken from the token stream because the AST does not keep their positions.
///
/// Named functions are found by their `fn NAME (` header; closures by `|`..`|`. A closure's declared
/// parameters are distinct from its synthesized capture parameters, which have no tokens at all —
/// captures are renamed, when they are renamed, through the outer binding they refer to.
fn parameter_lists(toks: &[&Tok], blocks: &Blocks) -> Parameters {
    let mut found = Parameters::default();
    let fn_decl = keywords::fn_decl();

    for (i, tok) in toks.iter().enumerate() {
        // fn NAME ( p, q ) { .. }, or `fn NAME() { .. }` where `()` is a single token.
        let header = if is_keyword(&tok.token, &fn_decl) {
            let mut j = i + 1;
            while j < toks.len() && !matches!(toks[j].token, Token::LeftParen | Token::Unit) {
                j += 1;
            }
            match toks.get(j).map(|t| &t.token) {
                Some(Token::Unit) => Some((Vec::new(), j)),
                Some(Token::LeftParen) => read_params(toks, j + 1, Token::RightParen),
                _ => None,
            }
        } else if matches!(tok.token, Token::Pipe) {
            // |p, q| body. A `|` is also bitwise-or, so this only counts as a parameter list if it
            // closes and holds nothing but names and commas.
            read_params(toks, i + 1, Token::Pipe)
        } else {
            continue;
        };
        let Some((params, after)) = header else {
            continue;
        };

        // Recognizing a parameter is enough to keep the coverage check satisfied, even when it
        // cannot be scoped. Scoping needs a block body: an expression-bodied closure such as
        // `|x| x + 1` reports no end position, so its parameters are left alone rather than guessed
        // at — the script still gets renamed everywhere else.
        found.known.extend(params.iter().copied());
        if let Some(body) = body_block(toks, after, blocks) {
            found.scoped.push((body, params));
        }
    }
    found
}

/// Byte offset just past the `;` that ends the statement starting at token index `from`.
///
/// Used to start a `let` binding's scope *after* its own initializer, since `let x = x + 1` must
/// read the outer `x`. Nesting is tracked so the `;` found is the statement's own and not one inside
/// a block or call in the initializer.
fn statement_end(toks: &[&Tok], from: usize) -> Option<usize> {
    let mut depth = 0i32;
    for tok in &toks[from..] {
        match tok.token {
            Token::LeftParen | Token::LeftBracket | Token::LeftBrace | Token::MapStart => {
                depth += 1
            }
            Token::RightParen | Token::RightBracket | Token::RightBrace if depth > 0 => depth -= 1,
            Token::SemiColon if depth == 0 => return Some(tok.span.end),
            _ => (),
        }
    }
    None
}

/// Reads a parameter list starting at token `from` and ending at `closer`.
///
/// Returns the parameter offsets and the index of the closing token, or `None` if the run is not a
/// parameter list — anything other than names and commas, or no closer at all. Without that guard a
/// bitwise-or `a | b` would be read as a closure header and every following identifier swallowed as
/// a parameter.
fn read_params(toks: &[&Tok], from: usize, closer: Token) -> Option<(Vec<usize>, usize)> {
    let mut params = Vec::new();
    for (offset, tok) in toks.iter().enumerate().skip(from) {
        match &tok.token {
            t if *t == closer => return Some((params, offset)),
            Token::Identifier(..) => params.push(tok.span.start),
            Token::Comma => (),
            _ => return None,
        }
    }
    None
}

#[derive(Default)]
struct Parameters {
    /// Every parameter token, whether or not it can be scoped.
    known: HashSet<usize>,
    /// Parameters that can be scoped to a block body, and so are renameable.
    scoped: Vec<(Range<usize>, Vec<usize>)>,
}

/// Identifier tokens that are function-call names or namespace segments.
///
/// An identifier directly before `(` names a function, never a variable — Rhai has no
/// call-an-expression form. Namespace segments sit either side of `::`.
fn syntactic_non_variables(toks: &[&Tok]) -> HashSet<usize> {
    let (fn_decl, module_alias, elvis) = (
        keywords::fn_decl(),
        keywords::module_alias(),
        keywords::elvis(),
    );

    let mut out = HashSet::new();
    for (i, tok) in toks.iter().enumerate() {
        if !matches!(tok.token, Token::Identifier(..)) {
            continue;
        }
        let next = toks.get(i + 1).map(|t| &t.token);
        let prev = i.checked_sub(1).and_then(|p| toks.get(p)).map(|t| &t.token);

        let is_call = matches!(next, Some(Token::LeftParen | Token::Unit | Token::Bang));
        let is_namespaced =
            matches!(next, Some(Token::DoubleColon)) || matches!(prev, Some(Token::DoubleColon));
        // The identifier after `.` or `?.`, which the AST also reports as a property but which is
        // worth covering here too for calls like `a.b()`.
        let is_member =
            matches!(prev, Some(Token::Period)) || prev.is_some_and(|p| is_keyword(p, &elvis));
        // A `fn` name, and a module alias in `import "m" as name` — neither is a variable.
        let follows_keyword =
            prev.is_some_and(|p| is_keyword(p, &fn_decl) || is_keyword(p, &module_alias));

        if is_call || is_namespaced || is_member || follows_keyword {
            out.insert(tok.span.start);
        }
    }
    out
}

/// Analyses `src`, returning renameable bindings and anything that blocks renaming.
pub fn analyse(engine: &Engine, src: &str, toks: &[Tok]) -> Result<Analysis, String> {
    let lines = LineIndex::new(src);
    let from_ast = walk_ast(src, &lines, engine)?;

    let significant: Vec<&Tok> = toks.iter().filter(|t| !t.is_comment()).collect();
    let blocks = Blocks::new(&significant);
    let non_variables = syntactic_non_variables(&significant);
    let params = parameter_lists(&significant, &blocks);

    let mut analysis = Analysis::default();

    // Every identifier in the script is off-limits as a generated name.
    for tok in &significant {
        if let Token::Identifier(name) = &tok.token {
            analysis.taken.insert(name.to_string());
        }
    }

    let ref_offsets: HashMap<usize, String> = from_ast.refs.iter().cloned().collect();
    let decl_offsets: HashMap<usize, (String, DeclKind)> = from_ast
        .decls
        .iter()
        .map(|(o, n, k)| (*o, (n.clone(), *k)))
        .collect();
    // Coverage check: any identifier token no rule explains blocks renaming entirely.
    for tok in &significant {
        if !matches!(tok.token, Token::Identifier(..)) {
            continue;
        }
        let at = tok.span.start;
        let explained = ref_offsets.contains_key(&at)
            || decl_offsets.contains_key(&at)
            || params.known.contains(&at)
            || from_ast.blocked.contains(&at)
            || non_variables.contains(&at);
        if !explained {
            analysis.unclassified.push((at, tok.text(src).to_string()));
        }
    }
    if !analysis.unclassified.is_empty() {
        return Ok(analysis);
    }

    // Build candidate bindings with their visible extent.
    let mut candidates: Vec<Binding> = Vec::new();

    for (offset, name, kind) in &from_ast.decls {
        let token_index = significant.iter().position(|t| t.span.start == *offset);
        let scope = match kind {
            // A `let` is visible from its declaration to the end of the enclosing block. A
            // declaration with no enclosing block is top level, where the host can reach it by name
            // through a `Scope`, so it is left alone.
            // Visible from just after its own initializer to the end of the enclosing block. A
            // declaration with no enclosing block is top level, where the host can reach it by name
            // through a `Scope`, so it is left alone.
            DeclKind::Var => match (blocks.containing(*offset), token_index) {
                (Some(block), Some(i)) => {
                    let start = statement_end(&significant, i)
                        .unwrap_or(*offset)
                        .min(block.end);
                    start..block.end
                }
                _ => continue,
            },
            // Loop and catch bindings are visible only in the body they introduce.
            DeclKind::Loop | DeclKind::Catch => {
                match token_index.and_then(|i| body_block(&significant, i, &blocks)) {
                    Some(body) => body,
                    None => continue,
                }
            }
        };
        candidates.push(Binding {
            name: name.clone(),
            decl: *offset,
            scope,
            sites: vec![*offset],
        });
    }

    for (body, offsets) in &params.scoped {
        for offset in offsets {
            let name = significant
                .iter()
                .find(|t| t.span.start == *offset)
                .map(|t| t.text(src).to_string());
            if let Some(name) = name {
                candidates.push(Binding {
                    name,
                    decl: *offset,
                    scope: body.clone(),
                    sites: vec![*offset],
                });
            }
        }
    }

    // Attach each reference to the innermost binding that covers it, so shadowing resolves the way
    // the parser would: among candidates whose scope contains the reference, the latest declaration
    // wins, since an inner scope always begins later.
    for (offset, name) in &from_ast.refs {
        let winner = candidates
            .iter()
            .enumerate()
            .filter(|(_, b)| &b.name == name && b.decl <= *offset && b.scope.contains(offset))
            .max_by_key(|(_, b)| b.decl)
            .map(|(i, _)| i);
        if let Some(i) = winner {
            candidates[i].sites.push(*offset);
        }
    }

    // A reference that resolved to no candidate refers to something outside our reach — a top-level
    // binding, or a host-supplied scope variable. Those names must stay untouched, and any candidate
    // sharing such a name would collide with it, so treat them as taken.
    for (offset, name) in &from_ast.refs {
        let covered = candidates
            .iter()
            .any(|b| b.sites.contains(offset) && &b.name == name);
        if !covered {
            analysis.taken.insert(name.clone());
        }
    }

    analysis.bindings = candidates;
    Ok(analysis)
}