rhaiper 0.2.0

Minifier for Rhai scripts, with Source Map v3 output
Documentation
//! Shortening local variable names.
//!
//! Off unless asked for, and declined automatically when [`bailout`] finds a construct that reads
//! names at runtime or when [`scope`] cannot account for every identifier in the script.

pub mod bailout;
pub mod scope;

use std::collections::HashMap;

use rhai::Engine;

use crate::lex::Tok;

/// Replacement text for identifier tokens, keyed by the token's starting byte offset.
pub type Renames = HashMap<usize, String>;

#[derive(Debug, Default)]
pub struct Outcome {
    pub renames: Renames,
    /// Number of bindings that were shortened.
    pub renamed_bindings: usize,
    /// Why renaming was declined, for reporting back to the caller.
    pub declined: Vec<String>,
}

/// Generates short names, skipping anything already used or not a legal Rhai name.
struct Names {
    index: usize,
}

impl Names {
    fn new() -> Self {
        Self { index: 0 }
    }

    /// `a`..`z`, then `aa`, `ab`, and so on.
    fn spell(mut index: usize) -> String {
        let mut out = Vec::new();
        loop {
            out.push(b'a' + (index % 26) as u8);
            index /= 26;
            if index == 0 {
                break;
            }
            index -= 1;
        }
        out.reverse();
        String::from_utf8(out).expect("ascii")
    }

    fn next(&mut self, taken: &impl Fn(&str) -> bool) -> String {
        loop {
            let candidate = Self::spell(self.index);
            self.index += 1;
            // `is_valid_function_name` is rhai's own check: a legal identifier that is neither a
            // reserved word nor an active keyword.
            if rhai::is_valid_function_name(&candidate) && !taken(&candidate) {
                return candidate;
            }
        }
    }
}

/// Decides the renames for `src`.
///
/// Every binding gets a distinct name that appears nowhere in the original. Reusing one short name
/// across disjoint scopes would compress better, but distinct names make shadowing impossible to get
/// wrong, which is the trade this makes deliberately.
/// Whether rhai reports source positions in this build.
///
/// Under `no_position` a `Position` is a unit struct whose `line()` is hardwired to `None`
/// (`types/position_none.rs:32`), so this is a runtime probe rather than a `#[cfg]` — which means no
/// mirror feature is needed to detect it.
///
/// Minification and source maps do not care, being derived from byte offsets. Renaming does: the AST
/// is the only place declaration and reference positions come from.
fn positions_available() -> bool {
    rhai::Position::START.line().is_some()
}

pub fn plan(engine: &Engine, src: &str, toks: &[Tok]) -> Outcome {
    let mut outcome = Outcome::default();

    if !positions_available() {
        // Checked explicitly so the reason is accurate. Renaming would decline anyway — every AST
        // position resolves to nothing, so the coverage check trips — but it would blame
        // unclassifiable identifiers instead of naming the real cause.
        outcome.declined.push(
            "rhai was built with `no_position`, so its AST carries no source positions for the \
             scope analysis to work from. Minification and source maps are unaffected."
                .into(),
        );
        return outcome;
    }

    let reasons = bailout::check(src, toks);
    if !reasons.is_empty() {
        outcome.declined = reasons.iter().map(ToString::to_string).collect();
        return outcome;
    }

    let analysis = match scope::analyse(engine, src, toks) {
        Ok(a) => a,
        Err(e) => {
            outcome.declined.push(e);
            return outcome;
        }
    };
    if !analysis.unclassified.is_empty() {
        let mut listed: Vec<String> = analysis
            .unclassified
            .iter()
            .take(3)
            .map(|(_, name)| format!("`{name}`"))
            .collect();
        if analysis.unclassified.len() > 3 {
            listed.push(format!("and {} more", analysis.unclassified.len() - 3));
        }
        outcome.declined.push(format!(
            "could not classify every identifier ({}), so names may be used in ways this tool \
             cannot see",
            listed.join(", ")
        ));
        return outcome;
    }

    let mut names = Names::new();
    let taken = |candidate: &str| analysis.taken.contains(candidate);

    let mut assigned: HashMap<String, usize> = HashMap::new();
    for binding in &analysis.bindings {
        let replacement = names.next(&taken);
        // Only worth doing when it actually saves bytes.
        if replacement.len() >= binding.name.len() {
            continue;
        }
        // Distinct names per binding are what make shadowing safe, so this must hold. A repeat would
        // mean an inner binding could capture an outer reference.
        if let Some(previous) = assigned.insert(replacement.clone(), binding.decl) {
            outcome.renames.clear();
            outcome.renamed_bindings = 0;
            outcome.declined.push(format!(
                "name `{replacement}` was allocated twice, to bindings at {previous} and {} \
                 (this is a bug in rhaiper)",
                binding.decl
            ));
            return outcome;
        }
        for site in &binding.sites {
            outcome.renames.insert(*site, replacement.clone());
        }
        outcome.renamed_bindings += 1;
    }
    outcome
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn spells_names_in_order() {
        assert_eq!(Names::spell(0), "a");
        assert_eq!(Names::spell(25), "z");
        assert_eq!(Names::spell(26), "aa");
        assert_eq!(Names::spell(51), "az");
        assert_eq!(Names::spell(52), "ba");
    }

    #[test]
    fn skips_taken_names() {
        let mut names = Names::new();
        let taken = |c: &str| c == "a" || c == "b";
        assert_eq!(names.next(&taken), "c");
    }

    #[test]
    fn never_generates_a_reserved_word() {
        // `in`, `if`, `fn` and friends are two letters and would otherwise come up.
        let mut names = Names::new();
        let none = |_: &str| false;
        let generated: Vec<String> = (0..800).map(|_| names.next(&none)).collect();
        for word in ["in", "if", "fn", "is", "as", "do", "go"] {
            assert!(
                !generated.iter().any(|g| g == word),
                "generated the reserved word {word:?}"
            );
        }
        // Sanity: the generator really did reach two-character names.
        assert!(generated.iter().any(|g| g.len() == 2));
    }
}