pub mod bailout;
pub mod scope;
use std::collections::HashMap;
use rhai::Engine;
use crate::lex::Tok;
pub type Renames = HashMap<usize, String>;
#[derive(Debug, Default)]
pub struct Outcome {
pub renames: Renames,
pub renamed_bindings: usize,
pub declined: Vec<String>,
}
struct Names {
index: usize,
}
impl Names {
fn new() -> Self {
Self { index: 0 }
}
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;
if rhai::is_valid_function_name(&candidate) && !taken(&candidate) {
return candidate;
}
}
}
}
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() {
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);
if replacement.len() >= binding.name.len() {
continue;
}
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() {
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:?}"
);
}
assert!(generated.iter().any(|g| g.len() == 2));
}
}