use proc_macro::{Delimiter, Group, TokenStream, TokenTree};
#[proc_macro_attribute]
pub fn required(_attr: TokenStream, item: TokenStream) -> TokenStream {
let compact = compact_non_literal_tokens(item.clone());
let markers = non_literal_token_markers(item.clone());
let mut errors = Vec::new();
if !has_deterministic_seed_parameter(item.clone()) {
errors.push("#[determinism::required] requires a Deterministic<Seed> parameter");
}
for (needle, message) in AMBIENT_CALLS {
if contains_ambient_call(&compact, needle) {
errors.push(message);
}
}
if contains_domain_id_now(&compact) {
errors.push("use seeded ID helpers instead of ambient typed Id::now");
}
if contains_hash_collection_iteration(&markers, "HashMap") {
errors.push("sort HashMap entries before deterministic output");
}
if contains_hash_collection_iteration(&markers, "HashSet") {
errors.push("sort HashSet entries before deterministic output");
}
if let Some(message) = errors.first() {
return compile_error(message);
}
item
}
const AMBIENT_CALLS: &[(&str, &str)] = &[
(
"thread_rng(",
"use Deterministic<Seed> instead of rand::thread_rng",
),
(
"rand::random(",
"use Deterministic<Seed> instead of rand::random",
),
(
"rand::random<",
"use Deterministic<Seed> instead of rand::random",
),
(
"random(",
"use Deterministic<Seed> instead of imported rand::random",
),
(
"random<",
"use Deterministic<Seed> instead of imported rand::random",
),
(
"getrandom::fill(",
"use Deterministic<Seed> instead of direct OS entropy",
),
(
"ring::rand::SystemRandom::new(",
"use Deterministic<Seed> instead of ring::rand::SystemRandom",
),
(
"SystemRandom::new(",
"use Deterministic<Seed> instead of ring::rand::SystemRandom",
),
(
"Uuid::new_v4(",
"use DeterministicClock/seeded ID helpers instead of Uuid::new_v4",
),
(
"uuid::Uuid::new_v4(",
"use DeterministicClock/seeded ID helpers instead of Uuid::new_v4",
),
(
"Uuid::now_v7(",
"use DeterministicClock/seeded ID helpers instead of Uuid::now_v7",
),
(
"uuid::Uuid::now_v7(",
"use DeterministicClock/seeded ID helpers instead of Uuid::now_v7",
),
(
"Instant::now(",
"inject timing at the boundary instead of calling Instant::now",
),
(
"SystemTime::now(",
"inject wall-clock time at the boundary instead of calling SystemTime::now",
),
(
"Utc::now(",
"inject UTC timestamps at the boundary instead of calling Utc::now",
),
(
"chrono::Utc::now(",
"inject UTC timestamps at the boundary instead of calling Utc::now",
),
(
"Local::now(",
"inject local timestamps at the boundary instead of calling Local::now",
),
(
"chrono::Local::now(",
"inject local timestamps at the boundary instead of calling Local::now",
),
(
"std::env::var(",
"read env through the registered config boundary",
),
(
"env::var(",
"read env through the registered config boundary",
),
(
"std::env::var_os(",
"read optional env through the registered config boundary",
),
(
"env::var_os(",
"read optional env through the registered config boundary",
),
(
"std::env::vars(",
"iterate env only through a deterministic registered boundary",
),
(
"env::vars(",
"iterate env only through a deterministic registered boundary",
),
(
"std::env::vars_os(",
"iterate env only through a deterministic registered boundary",
),
(
"env::vars_os(",
"iterate env only through a deterministic registered boundary",
),
(
"std::env::args(",
"read process args through the registered CLI boundary",
),
(
"env::args(",
"read process args through the registered CLI boundary",
),
(
"std::env::args_os(",
"read process args through the registered CLI boundary",
),
(
"env::args_os(",
"read process args through the registered CLI boundary",
),
(
"std::env::current_dir(",
"inject current directory/workspace at the boundary instead of calling env::current_dir",
),
(
"env::current_dir(",
"inject current directory/workspace at the boundary instead of calling env::current_dir",
),
(
"std::env::temp_dir(",
"inject temp directory at the boundary instead of calling env::temp_dir",
),
(
"env::temp_dir(",
"inject temp directory at the boundary instead of calling env::temp_dir",
),
(
"std::fs::read_dir(",
"sort read_dir entries before deterministic output",
),
(
"fs::read_dir(",
"sort read_dir entries before deterministic output",
),
(
"std::process::id(",
"inject the host PID at the boundary instead of calling std::process::id",
),
(
"process::id(",
"inject the host PID at the boundary instead of calling std::process::id",
),
(
"std::thread::current(",
"inject the thread identifier at the boundary instead of std::thread::current",
),
(
"thread::current(",
"inject the thread identifier at the boundary instead of std::thread::current",
),
];
fn compact_non_literal_tokens(tokens: TokenStream) -> String {
let mut output = String::new();
append_non_literal_tokens(tokens, &mut output);
output
}
fn contains_ambient_call(compact: &str, needle: &str) -> bool {
if let Some(path) = needle.strip_suffix('(') {
return contains_path_invocation(compact, path, CallSyntax::Plain);
}
if let Some(path) = needle.strip_suffix('<') {
return contains_path_invocation(compact, path, CallSyntax::Turbofish);
}
compact.contains(needle)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum CallSyntax {
Plain,
Turbofish,
}
fn contains_path_invocation(compact: &str, path: &str, syntax: CallSyntax) -> bool {
let mut search_start = 0;
while let Some(relative_index) = compact[search_start..].find(path) {
let index = search_start + relative_index;
let suffix_start = index + path.len();
if path_has_left_boundary(compact, index, path)
&& match syntax {
CallSyntax::Plain => compact[suffix_start..].starts_with('('),
CallSyntax::Turbofish => compact[suffix_start..].starts_with("::<"),
}
{
return true;
}
search_start = suffix_start;
}
false
}
fn path_has_left_boundary(compact: &str, index: usize, path: &str) -> bool {
match compact[..index].chars().next_back() {
None => true,
Some(ch) if !is_identifier_char(ch) && ch != ':' => true,
Some(':') => {
path_starts_after_absolute_prefix(compact, index) || path_allows_qualified_suffix(path)
}
Some(_) => false,
}
}
fn path_starts_after_absolute_prefix(compact: &str, index: usize) -> bool {
if index < 2 || !compact[..index].ends_with("::") {
return false;
}
compact[..index - 2]
.chars()
.next_back()
.is_none_or(|ch| !is_identifier_char(ch) && ch != ':')
}
fn path_allows_qualified_suffix(path: &str) -> bool {
matches!(
path,
"thread_rng"
| "SystemRandom::new"
| "Uuid::new_v4"
| "Uuid::now_v7"
| "Instant::now"
| "SystemTime::now"
| "Utc::now"
| "Local::now"
)
}
fn has_deterministic_seed_parameter(tokens: TokenStream) -> bool {
let mut saw_function_keyword = false;
for token in tokens {
match token {
TokenTree::Ident(ident) if ident.to_string() == "fn" => {
saw_function_keyword = true;
}
TokenTree::Group(group)
if saw_function_keyword && group.delimiter() == Delimiter::Parenthesis =>
{
return contains_deterministic_seed_type(group.stream());
}
_ => {}
}
}
false
}
#[derive(Clone, Debug, Eq, PartialEq)]
enum NonLiteralToken {
Ident(String),
Punct(char),
}
fn non_literal_token_markers(tokens: TokenStream) -> Vec<NonLiteralToken> {
let mut markers = Vec::new();
collect_non_literal_token_markers(tokens, &mut markers);
markers
}
fn contains_deterministic_seed_type(tokens: TokenStream) -> bool {
markers_contain_deterministic_seed_type(&non_literal_token_markers(tokens))
}
fn collect_non_literal_token_markers(tokens: TokenStream, output: &mut Vec<NonLiteralToken>) {
for token in tokens {
match token {
TokenTree::Group(group) => {
let delimiter = group.delimiter();
if let Some((open, _)) = delimiter_markers(delimiter) {
output.push(NonLiteralToken::Punct(open));
}
collect_non_literal_token_markers(group.stream(), output);
if let Some((_, close)) = delimiter_markers(delimiter) {
output.push(NonLiteralToken::Punct(close));
}
}
TokenTree::Ident(ident) => output.push(NonLiteralToken::Ident(ident.to_string())),
TokenTree::Punct(punct) => output.push(NonLiteralToken::Punct(punct.as_char())),
TokenTree::Literal(_) => {}
}
}
}
fn delimiter_markers(delimiter: Delimiter) -> Option<(char, char)> {
match delimiter {
Delimiter::Parenthesis => Some(('(', ')')),
Delimiter::Brace => Some(('{', '}')),
Delimiter::Bracket => Some(('[', ']')),
Delimiter::None => None,
}
}
fn markers_contain_deterministic_seed_type(markers: &[NonLiteralToken]) -> bool {
markers.windows(4).any(|window| {
matches!(
window,
[
NonLiteralToken::Ident(type_name),
NonLiteralToken::Punct('<'),
NonLiteralToken::Ident(seed_name),
NonLiteralToken::Punct('>'),
] if type_name == "Deterministic" && seed_name == "Seed"
)
})
}
fn append_non_literal_tokens(tokens: TokenStream, output: &mut String) {
for token in tokens {
match token {
TokenTree::Group(group) => append_group(group, output),
TokenTree::Ident(ident) => output.push_str(&ident.to_string()),
TokenTree::Punct(punct) => output.push(punct.as_char()),
TokenTree::Literal(_) => {}
}
}
}
fn append_group(group: Group, output: &mut String) {
match group.delimiter() {
Delimiter::Parenthesis => output.push('('),
Delimiter::Brace => output.push('{'),
Delimiter::Bracket => output.push('['),
Delimiter::None => {}
}
append_non_literal_tokens(group.stream(), output);
match group.delimiter() {
Delimiter::Parenthesis => output.push(')'),
Delimiter::Brace => output.push('}'),
Delimiter::Bracket => output.push(']'),
Delimiter::None => {}
}
}
fn contains_domain_id_now(compact: &str) -> bool {
let mut search_start = 0;
while let Some(relative_index) = compact[search_start..].find("::now(") {
let now_index = search_start + relative_index;
let prefix = &compact[..now_index];
let type_name = prefix
.rsplit(|ch: char| !is_identifier_char(ch))
.next()
.unwrap_or_default();
if type_name.ends_with("Id") {
return true;
}
search_start = now_index + "::now(".len();
}
false
}
fn contains_hash_collection_iteration(markers: &[NonLiteralToken], type_name: &str) -> bool {
hash_collection_bindings_from_markers(markers, type_name)
.iter()
.any(|binding| hash_collection_iteration_call(markers, binding))
|| hash_collection_direct_iteration_call(markers, type_name)
}
fn hash_collection_bindings_from_markers(
markers: &[NonLiteralToken],
type_name: &str,
) -> Vec<String> {
let mut bindings = Vec::new();
for colon_index in markers.iter().enumerate().filter_map(|(index, marker)| {
(marker == &NonLiteralToken::Punct(':')
&& !matches!(
markers.get(index.saturating_sub(1)),
Some(NonLiteralToken::Punct(':'))
)
&& !matches!(markers.get(index + 1), Some(NonLiteralToken::Punct(':'))))
.then_some(index)
}) {
if !markers_match_hash_collection_type(markers, colon_index + 1, type_name) {
continue;
}
if let Some(binding) = binding_name_before_colon(markers, colon_index) {
push_unique_binding(&mut bindings, binding);
}
}
for equals_index in markers
.iter()
.enumerate()
.filter_map(|(index, marker)| (marker == &NonLiteralToken::Punct('=')).then_some(index))
{
if !markers_match_hash_collection_constructor(markers, equals_index + 1, type_name) {
continue;
}
if let Some(binding) = binding_name_before_equals(markers, equals_index) {
push_unique_binding(&mut bindings, binding);
}
}
bindings
}
fn push_unique_binding(bindings: &mut Vec<String>, binding: String) {
if !bindings.iter().any(|existing| existing == &binding) {
bindings.push(binding);
}
}
fn markers_match_hash_collection_constructor(
markers: &[NonLiteralToken],
start: usize,
type_name: &str,
) -> bool {
let Some(path_end) = hash_collection_type_path_end(markers, start, type_name) else {
return false;
};
let Some(method_path_start) = hash_collection_constructor_method_start(markers, path_end)
else {
return false;
};
matches!(
ident_at(markers, method_path_start),
Some("new" | "with_capacity" | "from" | "default")
)
}
fn hash_collection_constructor_method_start(
markers: &[NonLiteralToken],
path_end: usize,
) -> Option<usize> {
let mut double_colon_index = path_end;
if double_colon_at(markers, double_colon_index)
&& matches!(
markers.get(double_colon_index + 2),
Some(NonLiteralToken::Punct('<'))
)
{
double_colon_index = skip_angle_group(markers, double_colon_index + 2)?;
} else if matches!(
markers.get(double_colon_index),
Some(NonLiteralToken::Punct('<'))
) {
double_colon_index = skip_angle_group(markers, double_colon_index)?;
}
double_colon_at(markers, double_colon_index).then_some(double_colon_index + 2)
}
fn skip_angle_group(markers: &[NonLiteralToken], start: usize) -> Option<usize> {
let mut depth = 0_usize;
for (index, marker) in markers.iter().enumerate().skip(start) {
match marker {
NonLiteralToken::Punct('<') => depth += 1,
NonLiteralToken::Punct('>') => {
depth = depth.saturating_sub(1);
if depth == 0 {
return Some(index + 1);
}
}
_ => {}
}
}
None
}
fn markers_match_hash_collection_type(
markers: &[NonLiteralToken],
start: usize,
type_name: &str,
) -> bool {
let Some(path_end) = hash_collection_type_path_end(markers, start, type_name) else {
return false;
};
matches!(markers.get(path_end), Some(NonLiteralToken::Punct('<')))
}
fn hash_collection_type_path_end(
markers: &[NonLiteralToken],
mut start: usize,
type_name: &str,
) -> Option<usize> {
if double_colon_at(markers, start) {
start += 2;
}
if ident_at(markers, start) == Some(type_name) {
return Some(start + 1);
}
if ident_at(markers, start) == Some("std")
&& double_colon_at(markers, start + 1)
&& ident_at(markers, start + 3) == Some("collections")
&& double_colon_at(markers, start + 4)
&& ident_at(markers, start + 6) == Some(type_name)
{
return Some(start + 7);
}
None
}
fn binding_name_before_colon(markers: &[NonLiteralToken], colon_index: usize) -> Option<String> {
let binding = ident_at(markers, colon_index.checked_sub(1)?)?;
if matches!(binding, "let" | "mut" | "ref" | "_") {
None
} else {
Some(binding.to_owned())
}
}
fn binding_name_before_equals(markers: &[NonLiteralToken], equals_index: usize) -> Option<String> {
let binding_index = equals_index.checked_sub(1)?;
let binding = ident_at(markers, binding_index)?;
if binding == "_" {
return None;
}
if binding_index
.checked_sub(1)
.and_then(|index| ident_at(markers, index))
== Some("let")
{
return Some(binding.to_owned());
}
if binding_index
.checked_sub(1)
.and_then(|index| ident_at(markers, index))
== Some("mut")
&& binding_index
.checked_sub(2)
.and_then(|index| ident_at(markers, index))
== Some("let")
{
return Some(binding.to_owned());
}
None
}
fn hash_collection_iteration_call(markers: &[NonLiteralToken], binding: &str) -> bool {
["iter", "keys", "values", "into_iter", "drain"]
.iter()
.any(|method| contains_receiver_method_call(markers, binding, method))
}
fn hash_collection_direct_iteration_call(markers: &[NonLiteralToken], type_name: &str) -> bool {
let mut start = 0;
while start < markers.len() {
let Some(path_end) = hash_collection_type_path_end(markers, start, type_name) else {
start += 1;
continue;
};
let Some(method_path_start) = hash_collection_constructor_method_start(markers, path_end)
else {
start = path_end.max(start + 1);
continue;
};
if !matches!(
ident_at(markers, method_path_start),
Some("new" | "with_capacity" | "from" | "default")
) {
start = method_path_start + 1;
continue;
}
if constructor_chain_has_iteration(markers, method_path_start) {
return true;
}
start = method_path_start + 1;
}
false
}
fn constructor_chain_has_iteration(markers: &[NonLiteralToken], method_index: usize) -> bool {
let Some(mut index) = constructor_invocation_end(markers, method_index) else {
return false;
};
while matches!(markers.get(index), Some(NonLiteralToken::Punct('.'))) {
let method_name_index = index + 1;
if matches!(
ident_at(markers, method_name_index),
Some("iter" | "keys" | "values" | "into_iter" | "drain")
) {
return true;
}
index = method_name_index + 1;
if double_colon_at(markers, index)
&& matches!(markers.get(index + 2), Some(NonLiteralToken::Punct('<')))
{
let Some(next_index) = skip_angle_group(markers, index + 2) else {
return false;
};
index = next_index;
}
if matches!(markers.get(index), Some(NonLiteralToken::Punct('('))) {
let Some(next_index) = skip_balanced_punct_group(markers, index, '(', ')') else {
return false;
};
index = next_index;
}
}
false
}
fn constructor_invocation_end(markers: &[NonLiteralToken], method_index: usize) -> Option<usize> {
let mut cursor = method_index + 1;
if double_colon_at(markers, cursor)
&& matches!(markers.get(cursor + 2), Some(NonLiteralToken::Punct('<')))
{
cursor = skip_angle_group(markers, cursor + 2)?;
}
match markers.get(cursor) {
Some(NonLiteralToken::Punct('(')) => skip_balanced_punct_group(markers, cursor, '(', ')'),
_ => None,
}
}
fn skip_balanced_punct_group(
markers: &[NonLiteralToken],
start: usize,
open: char,
close: char,
) -> Option<usize> {
let mut depth = 0_usize;
for (index, marker) in markers.iter().enumerate().skip(start) {
match marker {
NonLiteralToken::Punct(ch) if *ch == open => depth += 1,
NonLiteralToken::Punct(ch) if *ch == close => {
depth = depth.checked_sub(1)?;
if depth == 0 {
return Some(index + 1);
}
}
_ => {}
}
}
None
}
fn contains_receiver_method_call(
markers: &[NonLiteralToken],
receiver: &str,
method: &str,
) -> bool {
markers.windows(3).any(|window| {
matches!(
window,
[
NonLiteralToken::Ident(candidate_receiver),
NonLiteralToken::Punct('.'),
NonLiteralToken::Ident(candidate_method),
] if candidate_receiver == receiver && candidate_method == method
)
})
}
fn ident_at(markers: &[NonLiteralToken], index: usize) -> Option<&str> {
match markers.get(index) {
Some(NonLiteralToken::Ident(value)) => Some(value),
_ => None,
}
}
fn double_colon_at(markers: &[NonLiteralToken], index: usize) -> bool {
matches!(
(markers.get(index), markers.get(index + 1)),
(
Some(NonLiteralToken::Punct(':')),
Some(NonLiteralToken::Punct(':'))
)
)
}
fn is_identifier_char(ch: char) -> bool {
ch == '_' || ch.is_ascii_alphanumeric()
}
fn compile_error(message: &str) -> TokenStream {
format!("compile_error!({message:?});")
.parse()
.expect("compile_error token stream")
}
#[cfg(test)]
mod tests {
use super::{
NonLiteralToken, contains_ambient_call, contains_hash_collection_iteration,
hash_collection_bindings_from_markers, markers_contain_deterministic_seed_type,
};
fn ident(value: &str) -> NonLiteralToken {
NonLiteralToken::Ident(value.to_owned())
}
fn punct(value: char) -> NonLiteralToken {
NonLiteralToken::Punct(value)
}
#[test]
fn exact_deterministic_seed_parameter_shapes_are_accepted() {
assert!(markers_contain_deterministic_seed_type(&[
punct('&'),
ident("Deterministic"),
punct('<'),
ident("Seed"),
punct('>'),
]));
assert!(markers_contain_deterministic_seed_type(&[
punct('&'),
ident("mut"),
ident("Deterministic"),
punct('<'),
ident("Seed"),
punct('>'),
]));
assert!(markers_contain_deterministic_seed_type(&[
ident("ee"),
punct(':'),
punct(':'),
ident("runtime"),
punct(':'),
punct(':'),
ident("determinism"),
punct(':'),
punct(':'),
ident("Deterministic"),
punct('<'),
ident("Seed"),
punct('>'),
]));
assert!(markers_contain_deterministic_seed_type(&[
ident("Option"),
punct('<'),
punct('&'),
ident("Deterministic"),
punct('<'),
ident("Seed"),
punct('>'),
punct('>'),
]));
}
#[test]
fn similarly_named_seed_parameter_shapes_are_rejected() {
assert!(!markers_contain_deterministic_seed_type(&[
punct('&'),
ident("NonDeterministic"),
punct('<'),
ident("Seed"),
punct('>'),
]));
assert!(!markers_contain_deterministic_seed_type(&[
punct('&'),
ident("NotDeterministic"),
punct('<'),
ident("Seed"),
punct('>'),
]));
assert!(!markers_contain_deterministic_seed_type(&[
punct('&'),
ident("Deterministic"),
punct('<'),
ident("Seeded"),
punct('>'),
]));
assert!(!markers_contain_deterministic_seed_type(&[
punct('&'),
ident("Deterministic"),
punct('<'),
ident("Seed"),
punct(','),
ident("Other"),
punct('>'),
]));
}
#[test]
fn ambient_random_detection_catches_plain_and_turbofish_calls() {
assert!(contains_ambient_call(
"fnf(){let_=rand::thread_rng();}",
"thread_rng("
));
assert!(contains_ambient_call(
"fnf(){let_=rand::random();}",
"rand::random("
));
assert!(contains_ambient_call(
"fnf(){let_=rand::random::<u64>();}",
"rand::random<"
));
assert!(contains_ambient_call("fnf(){let_=random();}", "random("));
assert!(contains_ambient_call(
"fnf(){let_=random::<u64>();}",
"random<"
));
assert!(contains_ambient_call(
"fnf(){let_=std::time::Instant::now();}",
"Instant::now("
));
assert!(contains_ambient_call(
"fnf(){let_=std::time::SystemTime::now();}",
"SystemTime::now("
));
}
#[test]
fn ambient_call_detection_ignores_identifier_suffixes() {
assert!(!contains_ambient_call(
"fnf(){let_=not_random();}",
"random("
));
assert!(!contains_ambient_call(
"fnf(){let_=deterministic_random::<u64>();}",
"random<"
));
assert!(!contains_ambient_call(
"fnf(){let_=deterministic::random();}",
"random("
));
assert!(!contains_ambient_call(
"fnf(){let_=deterministic::random::<u64>();}",
"random<"
));
assert!(!contains_ambient_call("fnf(){let_=random<x;}", "random<"));
assert!(!contains_ambient_call(
"fnf(){let_=my_env::var();}",
"env::var("
));
assert!(!contains_ambient_call(
"fnf(){let_=my::env::var();}",
"env::var("
));
assert!(!contains_ambient_call(
"fnf(){let_=my::process::id();}",
"process::id("
));
assert!(!contains_ambient_call(
"fnf(){let_=my::thread::current();}",
"thread::current("
));
assert!(!contains_ambient_call(
"fnf(){let_=my::fs::read_dir();}",
"fs::read_dir("
));
assert!(!contains_ambient_call(
"fnf(){let_=my::getrandom::fill(&mut bytes);}",
"getrandom::fill("
));
}
#[test]
fn ambient_call_detection_catches_exact_qualified_module_paths() {
assert!(contains_ambient_call(
"fnf(){let_=std::env::var(\"EE_SEED\");}",
"std::env::var("
));
assert!(contains_ambient_call(
"fnf(){let_=std::process::id();}",
"std::process::id("
));
assert!(contains_ambient_call(
"fnf(){let_=std::thread::current();}",
"std::thread::current("
));
assert!(contains_ambient_call(
"fnf(){let_=std::fs::read_dir(\".\");}",
"std::fs::read_dir("
));
}
#[test]
fn ambient_call_detection_catches_absolute_module_paths() {
assert!(contains_ambient_call(
"fnf(){let_=::std::env::var(\"EE_SEED\");}",
"std::env::var("
));
assert!(contains_ambient_call(
"fnf(){let_=::rand::random::<u64>();}",
"rand::random<"
));
}
#[test]
fn ambient_call_detection_ignores_prefixed_exact_module_paths() {
assert!(!contains_ambient_call(
"fnf(){let_=my::std::env::var(\"EE_SEED\");}",
"std::env::var("
));
assert!(!contains_ambient_call(
"fnf(){let_=my::rand::random::<u64>();}",
"rand::random<"
));
}
#[test]
fn hash_collection_iteration_detection_catches_typed_bindings() {
let markers = [
ident("map"),
punct(':'),
ident("HashMap"),
punct('<'),
ident("String"),
punct('>'),
ident("set"),
punct(':'),
ident("std"),
punct(':'),
punct(':'),
ident("collections"),
punct(':'),
punct(':'),
ident("HashSet"),
punct('<'),
ident("String"),
punct('>'),
];
assert_eq!(
hash_collection_bindings_from_markers(&markers, "HashMap"),
vec!["map".to_owned()]
);
assert_eq!(
hash_collection_bindings_from_markers(&markers, "HashSet"),
vec!["set".to_owned()]
);
let mut map_iteration = markers.to_vec();
map_iteration.extend([ident("map"), punct('.'), ident("iter")]);
let mut set_iteration = markers.to_vec();
set_iteration.extend([ident("set"), punct('.'), ident("into_iter")]);
assert!(contains_hash_collection_iteration(
&map_iteration,
"HashMap"
));
assert!(contains_hash_collection_iteration(
&set_iteration,
"HashSet"
));
}
#[test]
fn hash_collection_iteration_detection_catches_inferred_constructor_bindings() {
let markers = [
ident("let"),
ident("mut"),
ident("map"),
punct('='),
ident("HashMap"),
punct(':'),
punct(':'),
ident("new"),
ident("let"),
ident("set"),
punct('='),
ident("std"),
punct(':'),
punct(':'),
ident("collections"),
punct(':'),
punct(':'),
ident("HashSet"),
punct(':'),
punct(':'),
ident("with_capacity"),
ident("let"),
ident("typed_map"),
punct('='),
ident("HashMap"),
punct(':'),
punct(':'),
punct('<'),
ident("String"),
punct(','),
ident("String"),
punct('>'),
punct(':'),
punct(':'),
ident("default"),
];
assert_eq!(
hash_collection_bindings_from_markers(&markers, "HashMap"),
vec!["map".to_owned(), "typed_map".to_owned()]
);
assert_eq!(
hash_collection_bindings_from_markers(&markers, "HashSet"),
vec!["set".to_owned()]
);
let mut map_iteration = markers.to_vec();
map_iteration.extend([ident("map"), punct('.'), ident("iter")]);
let mut set_iteration = markers.to_vec();
set_iteration.extend([ident("set"), punct('.'), ident("drain")]);
let mut typed_map_iteration = markers.to_vec();
typed_map_iteration.extend([ident("typed_map"), punct('.'), ident("values")]);
assert!(contains_hash_collection_iteration(
&map_iteration,
"HashMap"
));
assert!(contains_hash_collection_iteration(
&set_iteration,
"HashSet"
));
assert!(contains_hash_collection_iteration(
&typed_map_iteration,
"HashMap"
));
}
#[test]
fn hash_collection_iteration_detection_catches_direct_constructor_chains() {
let direct_map_iteration = [
ident("HashMap"),
punct(':'),
punct(':'),
punct('<'),
ident("String"),
punct(','),
ident("String"),
punct('>'),
punct(':'),
punct(':'),
ident("from"),
punct('('),
ident("entries"),
punct('.'),
ident("values"),
punct('('),
punct(')'),
punct(')'),
punct('.'),
ident("iter"),
];
let direct_set_iteration = [
ident("std"),
punct(':'),
punct(':'),
ident("collections"),
punct(':'),
punct(':'),
ident("HashSet"),
punct(':'),
punct(':'),
ident("default"),
punct('('),
punct(')'),
punct('.'),
ident("into_iter"),
];
assert!(contains_hash_collection_iteration(
&direct_map_iteration,
"HashMap"
));
assert!(contains_hash_collection_iteration(
&direct_set_iteration,
"HashSet"
));
}
#[test]
fn hash_collection_direct_constructor_detection_stops_at_statement_boundary() {
let markers = [
ident("HashMap"),
punct(':'),
punct(':'),
ident("new"),
punct('('),
punct(')'),
punct(';'),
ident("map"),
punct('.'),
ident("iter"),
];
assert!(!contains_hash_collection_iteration(&markers, "HashMap"));
}
#[test]
fn hash_collection_direct_constructor_detection_ignores_argument_iteration() {
let constructor_from_iterator = [
ident("HashMap"),
punct(':'),
punct(':'),
ident("from"),
punct('('),
ident("entries"),
punct('.'),
ident("iter"),
punct('('),
punct(')'),
punct(')'),
punct('.'),
ident("len"),
punct('('),
punct(')'),
];
let sibling_iteration_after_constructor_argument = [
ident("consume"),
punct('('),
ident("HashSet"),
punct(':'),
punct(':'),
ident("new"),
punct('('),
punct(')'),
punct(','),
ident("items"),
punct('.'),
ident("iter"),
punct('('),
punct(')'),
punct(')'),
];
assert!(!contains_hash_collection_iteration(
&constructor_from_iterator,
"HashMap"
));
assert!(!contains_hash_collection_iteration(
&sibling_iteration_after_constructor_argument,
"HashSet"
));
}
#[test]
fn hash_collection_binding_detection_ignores_wildcard_typed_parameters() {
let markers = [
ident("fn"),
ident("ambient"),
punct('('),
ident("previous"),
punct(':'),
ident("Vec"),
punct('<'),
ident("String"),
punct('>'),
punct(','),
ident("_"),
punct(':'),
ident("HashMap"),
punct('<'),
ident("String"),
punct(','),
ident("String"),
punct('>'),
punct(')'),
ident("previous"),
punct('.'),
ident("iter"),
];
assert!(hash_collection_bindings_from_markers(&markers, "HashMap").is_empty());
assert!(!contains_hash_collection_iteration(&markers, "HashMap"));
}
#[test]
fn hash_collection_iteration_detection_ignores_receiver_suffixes() {
let markers = [
ident("map"),
punct(':'),
ident("HashMap"),
punct('<'),
ident("String"),
punct('>'),
];
let mut suffixed_receiver = markers.to_vec();
suffixed_receiver.extend([ident("notmap"), punct('.'), ident("iter")]);
let mut non_iteration_method = markers.to_vec();
non_iteration_method.extend([ident("map"), punct('.'), ident("len")]);
assert!(!contains_hash_collection_iteration(
&suffixed_receiver,
"HashMap"
));
assert!(!contains_hash_collection_iteration(
&non_iteration_method,
"HashMap"
));
}
#[test]
fn hash_collection_binding_detection_ignores_value_expressions() {
let markers = [
ident("field"),
punct(':'),
ident("HashMap"),
punct(':'),
punct(':'),
ident("new"),
];
assert!(hash_collection_bindings_from_markers(&markers, "HashMap").is_empty());
}
#[test]
fn hash_collection_binding_detection_ignores_non_let_constructor_assignments() {
let markers = [
ident("field"),
punct('='),
ident("HashMap"),
punct(':'),
punct(':'),
ident("new"),
ident("field"),
punct('.'),
ident("iter"),
ident("let"),
ident("_"),
punct('='),
ident("HashMap"),
punct(':'),
punct(':'),
ident("new"),
];
assert!(hash_collection_bindings_from_markers(&markers, "HashMap").is_empty());
assert!(!contains_hash_collection_iteration(&markers, "HashMap"));
}
}