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>>;
#[derive(Debug, Default)]
pub(crate) struct Scanned {
pub(crate) reads: Reads,
pub(crate) checks: BTreeMap<Name, String>,
pub(crate) families: Reads,
pub(crate) unresolved: Vec<String>,
pub(crate) rust: Vec<PathBuf>,
}
#[derive(Debug)]
enum Target {
Variable(Name),
Family(Name),
Unresolved,
}
#[derive(Debug)]
struct Read {
target: Target,
line: usize,
checked: bool,
}
pub(crate) fn scan_all(dirs: &[PathBuf]) -> Result<Scanned, SourceFailure> {
let mut all = Scanned::default();
for dir in dirs {
let scanned = scan(dir)?;
for (name, places) in scanned.reads {
all.reads.entry(name).or_default().extend(places);
}
for (name, at) in scanned.checks {
all.checks.entry(name).or_insert(at);
}
for (prefix, places) in scanned.families {
all.families.entry(prefix).or_default().extend(places);
}
all.unresolved.extend(scanned.unresolved);
all.rust.extend(scanned.rust);
}
Ok(all)
}
#[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<Scanned, SourceFailure> {
let paths = match files::rust_files(src) {
Ok(paths) => paths,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Scanned::default()),
Err(error) => return Err(SourceFailure::new(src, format!("cannot be read: {error}"))),
};
let mut scanned = Scanned::default();
for path in paths.into_iter().filter(|path| !is_test_file(path)) {
let dir = path.parent().unwrap_or(src);
if !scanned.rust.iter().any(|found| found == dir) {
scanned.rust.push(dir.to_path_buf());
}
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 Read {
target,
line,
checked,
} in lines
{
let place = format!("{}:{line}", path.display());
match target {
Target::Variable(name) => {
if checked {
scanned
.checks
.entry(name.clone())
.or_insert_with(|| place.clone());
}
scanned.reads.entry(name).or_default().push(place);
}
Target::Family(prefix) => {
scanned.families.entry(prefix).or_default().push(place);
}
Target::Unresolved => scanned.unresolved.push(place),
}
}
}
Ok(scanned)
}
fn lines_of_reads(text: &str) -> Result<Vec<Read>, 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<Read>) {
let mut before_previous: Option<TokenTree> = None;
let mut previous: Option<TokenTree> = None;
let mut reader = None;
let mut bare_env = 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;
bare_env = 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, attribute)) = reader
&& group.delimiter() == Delimiter::Parenthesis
&& let Some((target, checked)) = read_in(group.stream(), attribute)
{
reads.push(Read {
target,
line,
checked,
});
}
if group.delimiter() == Delimiter::Bracket
&& is_punct(previous.as_ref(), '#')
&& let Some((env, line)) = clap_env(group.stream())
{
match env {
ClapEnv::Named(name) => reads.push(Read {
target: Target::Variable(name),
line,
checked: false,
}),
ClapEnv::Field => bare_env = Some(line),
}
}
collect(group.stream(), reads);
}
if let Some(line) = bare_env {
match &token {
TokenTree::Ident(word) if word != "pub" => {
bare_env = None;
if let Some(name) = field_env(&word.to_string()) {
reads.push(Read {
target: Target::Variable(name),
line,
checked: false,
});
}
}
TokenTree::Ident(_) | TokenTree::Group(_) => {}
TokenTree::Punct(punct) if punct.as_char() == '#' => {}
TokenTree::Punct(_) | TokenTree::Literal(_) => bare_env = None,
}
}
reader = match &token {
TokenTree::Ident(word)
if READERS.iter().any(|reader| word == reader)
&& !is_punct(previous.as_ref(), '.') =>
{
Some((word.span().start().line, word == "starmap"))
}
_ => None,
};
before_previous = previous.replace(token);
}
}
enum ClapEnv {
Named(Name),
Field,
}
fn clap_env(attribute: TokenStream) -> Option<(ClapEnv, usize)> {
let mut attribute = attribute.into_iter();
let (Some(TokenTree::Ident(word)), Some(TokenTree::Group(arguments)), None) =
(attribute.next(), attribute.next(), attribute.next())
else {
return None;
};
if !(word == "arg" || word == "clap") || arguments.delimiter() != Delimiter::Parenthesis {
return None;
}
let mut tokens = arguments.stream().into_iter().peekable();
let mut starts_argument = true;
while let Some(token) = tokens.next() {
if starts_argument
&& let TokenTree::Ident(key) = &token
&& key == "env"
{
let line = key.span().start().line;
if tokens.peek().is_none() || is_punct(tokens.peek(), ',') {
return Some((ClapEnv::Field, line));
}
let (Some(TokenTree::Punct(equals)), Some(TokenTree::Literal(literal))) =
(tokens.next(), tokens.next())
else {
return None;
};
if equals.as_char() != '=' || !(tokens.peek().is_none() || is_punct(tokens.peek(), ','))
{
return None;
}
let written = literal.to_string();
return Name::from_str(string_text(&written)?)
.ok()
.map(|name| (ClapEnv::Named(name), line));
}
starts_argument = is_punct(Some(&token), ',');
}
None
}
fn field_env(field: &str) -> Option<Name> {
let field = field.strip_prefix("r#").unwrap_or(field);
Name::from_str(&field.to_uppercase()).ok()
}
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 read_in(tokens: TokenStream, attribute: bool) -> Option<(Target, bool)> {
if let Some((name, checked)) = literal_name(tokens.clone(), attribute) {
return Some((Target::Variable(name), checked));
}
if attribute {
return None;
}
formatted(tokens).map(|target| (target, false))
}
fn formatted(tokens: TokenStream) -> Option<Target> {
let mut tokens = tokens.into_iter().peekable();
if is_punct(tokens.peek(), '&') {
tokens.next();
}
let mut last = None;
loop {
match tokens.next()? {
TokenTree::Ident(word) => last = Some(word),
TokenTree::Punct(punct) if punct.as_char() == ':' => {}
TokenTree::Punct(punct) if punct.as_char() == '!' => break,
_ => return None,
}
}
if !last.is_some_and(|word| word == "format") {
return None;
}
let Some(TokenTree::Group(arguments)) = tokens.next() else {
return None;
};
match (tokens.next(), tokens.next()) {
(None, _) => {}
(Some(TokenTree::Punct(comma)), None) if comma.as_char() == ',' => {}
_ => return None,
}
let Some(TokenTree::Literal(literal)) = arguments.stream().into_iter().next() else {
return None;
};
let text = string_text(&literal.to_string())?.to_owned();
Some(target_of(&text))
}
fn target_of(text: &str) -> Target {
let Some((literal, placeholders)) = pattern(text) else {
return Target::Unresolved;
};
let resolved = match placeholders.as_slice() {
[] => Name::from_str(&literal).ok().map(Target::Variable),
[at] if *at == literal.len() => literal
.strip_suffix('_')
.and_then(|prefix| Name::from_str(prefix).ok())
.map(Target::Family),
_ => None,
};
resolved.unwrap_or(Target::Unresolved)
}
fn pattern(text: &str) -> Option<(String, Vec<usize>)> {
let mut literal = String::new();
let mut placeholders = Vec::new();
let mut chars = text.chars().peekable();
while let Some(character) = chars.next() {
match character {
'{' if chars.peek() == Some(&'{') => {
chars.next();
literal.push('{');
}
'{' => {
chars.by_ref().find(|&inner| inner == '}')?;
placeholders.push(literal.len());
}
'}' if chars.next_if_eq(&'}').is_some() => literal.push('}'),
'}' => return None,
other => literal.push(other),
}
}
Some((literal, placeholders))
}
fn string_text(written: &str) -> Option<&str> {
let text = written
.strip_prefix('r')
.unwrap_or(written)
.trim_matches('#');
text.strip_prefix('"')?.strip_suffix('"')
}
fn literal_name(tokens: TokenStream, attribute: bool) -> Option<(Name, bool)> {
let mut tokens = tokens.into_iter();
let Some(TokenTree::Literal(literal)) = tokens.next() else {
return None;
};
let checked = match (tokens.next(), tokens.next()) {
(None, _) => false,
(Some(TokenTree::Punct(comma)), None) if comma.as_char() == ',' => false,
(Some(TokenTree::Punct(comma)), Some(TokenTree::Ident(key)))
if attribute && comma.as_char() == ',' && key == "check" =>
{
true
}
_ => return None,
};
let name = string_text(&literal.to_string())?.to_owned();
Name::from_str(&name).ok().map(|name| (name, checked))
}
#[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 {}