use rhai::{Position, Token, TokenizeState};
use crate::lex::Tok;
use crate::rename::Renames;
use crate::stream::{LineIndex, StrStream};
#[derive(Debug, Clone)]
pub struct Options {
pub max_line_len: usize,
pub rename: bool,
pub max_expr_depth: Option<(usize, usize)>,
}
impl Default for Options {
fn default() -> Self {
Self {
max_line_len: 200,
rename: false,
max_expr_depth: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Mapping {
pub gen_line: u32,
pub gen_col: u32,
pub src_line: u32,
pub src_col: u32,
}
#[derive(Debug)]
pub struct Emitted {
pub text: String,
pub mappings: Vec<Mapping>,
}
pub fn significant(toks: &[Tok]) -> Vec<&Tok> {
let kept: Vec<&Tok> = toks.iter().filter(|t| !t.is_comment()).collect();
let is_semi = |t: &Tok| matches!(t.token, Token::SemiColon);
let mut out: Vec<&Tok> = Vec::with_capacity(kept.len());
for (i, tok) in kept.iter().enumerate() {
if is_semi(tok) {
if out.last().copied().is_some_and(is_semi) {
continue;
}
let opens_block = out
.last()
.is_some_and(|p| matches!(p.token, Token::LeftBrace | Token::MapStart));
if !opens_block {
let next = kept[i + 1..].iter().find(|k| !is_semi(k));
match next {
None => continue,
Some(k) if matches!(k.token, Token::RightBrace) => continue,
_ => (),
}
}
}
out.push(tok);
}
out
}
fn first_token_len(probe: &str) -> Option<usize> {
let mut stream = StrStream::new(probe);
let mut state = TokenizeState::default();
let mut pos = Position::START;
match rhai::get_next_token(&mut stream, &mut state, &mut pos) {
(Token::LexError(..), _) | (Token::EOF, _) => None,
_ => Some(stream.byte_offset()),
}
}
fn needs_separator(prev: &str, next: &str, lookahead: &str) -> bool {
if prev.is_empty() || next.is_empty() {
return false;
}
if prev.ends_with(|c: char| c.is_whitespace()) {
return false;
}
let mut probe = String::with_capacity(prev.len() + next.len() + lookahead.len());
probe.push_str(prev);
probe.push_str(next);
probe.push_str(lookahead);
first_token_len(&probe) != Some(prev.len())
}
pub fn emit(src: &str, toks: &[Tok], opts: &Options, renames: &Renames) -> Emitted {
let lines = LineIndex::new(src);
let kept = significant(toks);
let texts: Vec<&str> = kept
.iter()
.map(|t| {
renames
.get(&t.span.start)
.map_or_else(|| t.text(src), String::as_str)
})
.collect();
let mut text = String::with_capacity(src.len());
let mut mappings = Vec::with_capacity(kept.len());
let (mut gen_line, mut gen_col) = (0u32, 0u32);
let mut prev = "";
let mut prev_end: Option<usize> = None;
let mut prev_span_start: Option<usize> = None;
for (i, tok) in kept.iter().enumerate() {
let lookahead: String = texts[i + 1..]
.iter()
.flat_map(|s| s.chars())
.take(4)
.collect();
let width = texts[i].chars().take_while(|&c| c != '\n').count();
let untouched = !renames.contains_key(&tok.span.start)
&& !prev_span_start.is_some_and(|s| renames.contains_key(&s));
let contiguous = untouched && prev_end == Some(tok.span.start);
let overflows = !contiguous && gen_col > 0 && gen_col as usize + width > opts.max_line_len;
let separator = if overflows {
Some('\n')
} else if !contiguous && needs_separator(prev, texts[i], &lookahead) {
Some(' ')
} else {
None
};
if let Some(sep) = separator {
text.push(sep);
if sep == '\n' {
gen_line += 1;
gen_col = 0;
} else {
gen_col += 1;
}
}
let (src_line, src_col) = lines.line_col_of(src, tok.span.start);
mappings.push(Mapping {
gen_line,
gen_col,
src_line,
src_col,
});
text.push_str(texts[i]);
for ch in texts[i].chars() {
if ch == '\n' {
gen_line += 1;
gen_col = 0;
} else {
gen_col += 1;
}
}
prev = texts[i];
prev_end = Some(tok.span.end);
prev_span_start = Some(tok.span.start);
}
Emitted { text, mappings }
}