use std::collections::BTreeMap;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
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_all(dirs: &[PathBuf]) -> Result<Reads, SourceFailure> {
let mut reads = Reads::new();
for dir in dirs {
for (name, places) in scan(dir)? {
reads.entry(name).or_default().extend(places);
}
}
Ok(reads)
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Dirs<'a>(pub(crate) &'a [PathBuf]);
impl Dirs<'_> {
pub(crate) fn is_empty(self) -> bool {
self.0.is_empty()
}
pub(crate) fn verb(self, one: &'static str, several: &'static str) -> &'static str {
if self.0.len() == 1 { one } else { several }
}
}
impl fmt::Display for Dirs<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let names: Vec<String> = self.0.iter().map(|dir| dir.display().to_string()).collect();
match names.split_last() {
None => formatter.write_str("no source directory"),
Some((last, [])) => formatter.write_str(last),
Some((last, rest)) => write!(formatter, "{} and {last}", rest.join(", ")),
}
}
}
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)]
pub(crate) enum SourceFailure {
#[failure(
code = SOURCE_UNREADABLE,
hint = "fix {file} so that cargo builds it",
alternative = Recovery::Hint(format!("move {file} out of src")),
field(file = file.as_str()),
)]
Unbuildable {
file: String,
problem: String,
},
#[failure(
code = SOURCE_UNREADABLE,
hint = "move generated code out of src",
field(file = file.as_str()),
)]
TooLarge {
file: String,
},
}
impl SourceFailure {
fn new(path: &Path, problem: String) -> Self {
Self::Unbuildable {
file: path.display().to_string(),
problem,
}
}
fn too_large(path: &Path) -> Self {
Self::TooLarge {
file: path.display().to_string(),
}
}
}
impl fmt::Display for SourceFailure {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unbuildable { file, problem } => write!(formatter, "{file} {problem}"),
Self::TooLarge { file } => {
write!(
formatter,
"{file} is over 1 MiB, so the scan does not read it"
)
}
}
}
}
impl std::error::Error for SourceFailure {}