use std::collections::BTreeMap;
use std::fmt;
use std::io;
use std::path::Path;
use std::str::FromStr as _;
use crumbkit::{Failure, Recovery};
use proc_macro2::{Delimiter, Group, TokenStream, TokenTree};
use starmap::Name;
use crate::codes::SOURCE_UNREADABLE;
use crate::files;
#[cfg(test)]
mod tests;
const MAX_SOURCE_BYTES: usize = 1024 * 1024;
const READERS: &[&str] = &["var", "var_os", "starmap"];
pub(crate) type Reads = BTreeMap<Name, Vec<String>>;
pub(crate) fn scan(src: &Path) -> Result<Reads, SourceFailure> {
let paths = match files::rust_files(src) {
Ok(paths) => paths,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Reads::new()),
Err(error) => return Err(SourceFailure::new(src, format!("cannot be read: {error}"))),
};
let mut reads = Reads::new();
for path in paths.into_iter().filter(|path| !is_test_file(path)) {
let bytes = files::read_capped(&path, MAX_SOURCE_BYTES + 1)
.map_err(|error| SourceFailure::new(&path, format!("cannot be read: {error}")))?;
if bytes.len() > MAX_SOURCE_BYTES {
return Err(SourceFailure::too_large(&path));
}
let text = String::from_utf8(bytes)
.map_err(|_| SourceFailure::new(&path, "is not UTF-8 text".to_owned()))?;
let lines = lines_of_reads(&text).map_err(|error| {
let line = error.span().start().line;
SourceFailure::new(&path, format!("is not valid Rust at line {line}"))
})?;
for (name, line) in lines {
let place = format!("{}:{line}", path.display());
reads.entry(name).or_default().push(place);
}
}
Ok(reads)
}
fn lines_of_reads(text: &str) -> Result<Vec<(Name, usize)>, proc_macro2::LexError> {
let mut reads = Vec::new();
collect(TokenStream::from_str(text)?, &mut reads);
Ok(reads)
}
fn is_test_file(path: &Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name == "tests.rs" || name.ends_with("_tests.rs"))
}
fn collect(tokens: TokenStream, reads: &mut Vec<(Name, usize)>) {
let mut before_previous: Option<TokenTree> = None;
let mut previous: Option<TokenTree> = None;
let mut reader = None;
let mut in_test_item = false;
for token in tokens {
if in_test_item {
in_test_item = !ends_item(&token);
continue;
}
if let TokenTree::Group(group) = &token
&& is_cfg_test(group)
{
if is_punct(previous.as_ref(), '#') {
in_test_item = true;
previous = None;
continue;
}
if is_punct(previous.as_ref(), '!') && is_punct(before_previous.as_ref(), '#') {
return;
}
}
if let TokenTree::Group(group) = &token {
if let Some(line) = reader
&& group.delimiter() == Delimiter::Parenthesis
&& let Some(name) = literal_name(group.stream())
{
reads.push((name, line));
}
collect(group.stream(), reads);
}
reader = match &token {
TokenTree::Ident(word)
if READERS.iter().any(|reader| word == reader)
&& !is_punct(previous.as_ref(), '.') =>
{
Some(word.span().start().line)
}
_ => None,
};
before_previous = previous.replace(token);
}
}
fn is_punct(token: Option<&TokenTree>, character: char) -> bool {
matches!(token, Some(TokenTree::Punct(punct)) if punct.as_char() == character)
}
fn is_cfg_test(group: &Group) -> bool {
group.delimiter() == Delimiter::Bracket
&& group.stream().to_string().replace(' ', "") == "cfg(test)"
}
fn ends_item(token: &TokenTree) -> bool {
match token {
TokenTree::Group(group) => group.delimiter() == Delimiter::Brace,
TokenTree::Punct(punct) => matches!(punct.as_char(), ';' | ','),
TokenTree::Ident(_) | TokenTree::Literal(_) => false,
}
}
fn literal_name(tokens: TokenStream) -> Option<Name> {
let mut tokens = tokens.into_iter();
let Some(TokenTree::Literal(literal)) = tokens.next() else {
return None;
};
match tokens.next() {
None => {}
Some(TokenTree::Punct(comma)) if comma.as_char() == ',' && tokens.next().is_none() => {}
Some(_) => return None,
}
let written = literal.to_string();
let text = written
.strip_prefix('r')
.unwrap_or(&written)
.trim_matches('#');
let name = text.strip_prefix('"')?.strip_suffix('"')?;
Name::from_str(name).ok()
}
#[derive(Debug, Failure)]
#[failure(
code = SOURCE_UNREADABLE,
recovery = Recovery::Hint(next.clone()),
field(file = file.as_str()),
)]
pub(crate) struct SourceFailure {
file: String,
problem: String,
next: String,
}
impl SourceFailure {
fn new(path: &Path, problem: String) -> Self {
let file = path.display().to_string();
let next = format!("fix {file} so that cargo builds it, or move it out of src");
Self {
file,
problem,
next,
}
}
fn too_large(path: &Path) -> Self {
Self {
file: path.display().to_string(),
problem: "is over 1 MiB, so the scan does not read it".to_owned(),
next: "move generated code out of src".to_owned(),
}
}
}
impl fmt::Display for SourceFailure {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{} {}", self.file, self.problem)
}
}
impl std::error::Error for SourceFailure {}