1use proc_macro::{Delimiter, Group, TokenStream, TokenTree};
11
12#[proc_macro_attribute]
13pub fn required(_attr: TokenStream, item: TokenStream) -> TokenStream {
14 let compact = compact_non_literal_tokens(item.clone());
15 let markers = non_literal_token_markers(item.clone());
16 let mut errors = Vec::new();
17
18 if !has_deterministic_seed_parameter(item.clone()) {
19 errors.push("#[determinism::required] requires a Deterministic<Seed> parameter");
20 }
21
22 for (needle, message) in AMBIENT_CALLS {
23 if contains_ambient_call(&compact, needle) {
24 errors.push(message);
25 }
26 }
27
28 if contains_domain_id_now(&compact) {
29 errors.push("use seeded ID helpers instead of ambient typed Id::now");
30 }
31 if contains_hash_collection_iteration(&markers, "HashMap") {
32 errors.push("sort HashMap entries before deterministic output");
33 }
34 if contains_hash_collection_iteration(&markers, "HashSet") {
35 errors.push("sort HashSet entries before deterministic output");
36 }
37
38 if let Some(message) = errors.first() {
39 return compile_error(message);
40 }
41
42 item
43}
44
45const AMBIENT_CALLS: &[(&str, &str)] = &[
46 (
47 "thread_rng(",
48 "use Deterministic<Seed> instead of rand::thread_rng",
49 ),
50 (
51 "rand::random(",
52 "use Deterministic<Seed> instead of rand::random",
53 ),
54 (
55 "rand::random<",
56 "use Deterministic<Seed> instead of rand::random",
57 ),
58 (
59 "random(",
60 "use Deterministic<Seed> instead of imported rand::random",
61 ),
62 (
63 "random<",
64 "use Deterministic<Seed> instead of imported rand::random",
65 ),
66 (
67 "getrandom::fill(",
68 "use Deterministic<Seed> instead of direct OS entropy",
69 ),
70 (
71 "ring::rand::SystemRandom::new(",
72 "use Deterministic<Seed> instead of ring::rand::SystemRandom",
73 ),
74 (
75 "SystemRandom::new(",
76 "use Deterministic<Seed> instead of ring::rand::SystemRandom",
77 ),
78 (
79 "Uuid::new_v4(",
80 "use DeterministicClock/seeded ID helpers instead of Uuid::new_v4",
81 ),
82 (
83 "uuid::Uuid::new_v4(",
84 "use DeterministicClock/seeded ID helpers instead of Uuid::new_v4",
85 ),
86 (
87 "Uuid::now_v7(",
88 "use DeterministicClock/seeded ID helpers instead of Uuid::now_v7",
89 ),
90 (
91 "uuid::Uuid::now_v7(",
92 "use DeterministicClock/seeded ID helpers instead of Uuid::now_v7",
93 ),
94 (
95 "Instant::now(",
96 "inject timing at the boundary instead of calling Instant::now",
97 ),
98 (
99 "SystemTime::now(",
100 "inject wall-clock time at the boundary instead of calling SystemTime::now",
101 ),
102 (
103 "Utc::now(",
104 "inject UTC timestamps at the boundary instead of calling Utc::now",
105 ),
106 (
107 "chrono::Utc::now(",
108 "inject UTC timestamps at the boundary instead of calling Utc::now",
109 ),
110 (
111 "Local::now(",
112 "inject local timestamps at the boundary instead of calling Local::now",
113 ),
114 (
115 "chrono::Local::now(",
116 "inject local timestamps at the boundary instead of calling Local::now",
117 ),
118 (
119 "std::env::var(",
120 "read env through the registered config boundary",
121 ),
122 (
123 "env::var(",
124 "read env through the registered config boundary",
125 ),
126 (
127 "std::env::var_os(",
128 "read optional env through the registered config boundary",
129 ),
130 (
131 "env::var_os(",
132 "read optional env through the registered config boundary",
133 ),
134 (
135 "std::env::vars(",
136 "iterate env only through a deterministic registered boundary",
137 ),
138 (
139 "env::vars(",
140 "iterate env only through a deterministic registered boundary",
141 ),
142 (
143 "std::env::vars_os(",
144 "iterate env only through a deterministic registered boundary",
145 ),
146 (
147 "env::vars_os(",
148 "iterate env only through a deterministic registered boundary",
149 ),
150 (
151 "std::env::args(",
152 "read process args through the registered CLI boundary",
153 ),
154 (
155 "env::args(",
156 "read process args through the registered CLI boundary",
157 ),
158 (
159 "std::env::args_os(",
160 "read process args through the registered CLI boundary",
161 ),
162 (
163 "env::args_os(",
164 "read process args through the registered CLI boundary",
165 ),
166 (
167 "std::env::current_dir(",
168 "inject current directory/workspace at the boundary instead of calling env::current_dir",
169 ),
170 (
171 "env::current_dir(",
172 "inject current directory/workspace at the boundary instead of calling env::current_dir",
173 ),
174 (
175 "std::env::temp_dir(",
176 "inject temp directory at the boundary instead of calling env::temp_dir",
177 ),
178 (
179 "env::temp_dir(",
180 "inject temp directory at the boundary instead of calling env::temp_dir",
181 ),
182 (
183 "std::fs::read_dir(",
184 "sort read_dir entries before deterministic output",
185 ),
186 (
187 "fs::read_dir(",
188 "sort read_dir entries before deterministic output",
189 ),
190 (
191 "std::process::id(",
192 "inject the host PID at the boundary instead of calling std::process::id",
193 ),
194 (
195 "process::id(",
196 "inject the host PID at the boundary instead of calling std::process::id",
197 ),
198 (
199 "std::thread::current(",
200 "inject the thread identifier at the boundary instead of std::thread::current",
201 ),
202 (
203 "thread::current(",
204 "inject the thread identifier at the boundary instead of std::thread::current",
205 ),
206];
207
208fn compact_non_literal_tokens(tokens: TokenStream) -> String {
209 let mut output = String::new();
210 append_non_literal_tokens(tokens, &mut output);
211 output
212}
213
214fn contains_ambient_call(compact: &str, needle: &str) -> bool {
215 if let Some(path) = needle.strip_suffix('(') {
216 return contains_path_invocation(compact, path, CallSyntax::Plain);
217 }
218 if let Some(path) = needle.strip_suffix('<') {
219 return contains_path_invocation(compact, path, CallSyntax::Turbofish);
220 }
221
222 compact.contains(needle)
223}
224
225#[derive(Clone, Copy, Debug, Eq, PartialEq)]
226enum CallSyntax {
227 Plain,
228 Turbofish,
229}
230
231fn contains_path_invocation(compact: &str, path: &str, syntax: CallSyntax) -> bool {
232 let mut search_start = 0;
233 while let Some(relative_index) = compact[search_start..].find(path) {
234 let index = search_start + relative_index;
235 let suffix_start = index + path.len();
236 if path_has_left_boundary(compact, index, path)
237 && match syntax {
238 CallSyntax::Plain => compact[suffix_start..].starts_with('('),
239 CallSyntax::Turbofish => compact[suffix_start..].starts_with("::<"),
240 }
241 {
242 return true;
243 }
244 search_start = suffix_start;
245 }
246
247 false
248}
249
250fn path_has_left_boundary(compact: &str, index: usize, path: &str) -> bool {
251 match compact[..index].chars().next_back() {
252 None => true,
253 Some(ch) if !is_identifier_char(ch) && ch != ':' => true,
254 Some(':') => {
255 path_starts_after_absolute_prefix(compact, index) || path_allows_qualified_suffix(path)
256 }
257 Some(_) => false,
258 }
259}
260
261fn path_starts_after_absolute_prefix(compact: &str, index: usize) -> bool {
262 if index < 2 || !compact[..index].ends_with("::") {
263 return false;
264 }
265 compact[..index - 2]
266 .chars()
267 .next_back()
268 .is_none_or(|ch| !is_identifier_char(ch) && ch != ':')
269}
270
271fn path_allows_qualified_suffix(path: &str) -> bool {
272 matches!(
273 path,
274 "thread_rng"
275 | "SystemRandom::new"
276 | "Uuid::new_v4"
277 | "Uuid::now_v7"
278 | "Instant::now"
279 | "SystemTime::now"
280 | "Utc::now"
281 | "Local::now"
282 )
283}
284
285fn has_deterministic_seed_parameter(tokens: TokenStream) -> bool {
286 let mut saw_function_keyword = false;
287
288 for token in tokens {
289 match token {
290 TokenTree::Ident(ident) if ident.to_string() == "fn" => {
291 saw_function_keyword = true;
292 }
293 TokenTree::Group(group)
294 if saw_function_keyword && group.delimiter() == Delimiter::Parenthesis =>
295 {
296 return contains_deterministic_seed_type(group.stream());
297 }
298 _ => {}
299 }
300 }
301
302 false
303}
304
305#[derive(Clone, Debug, Eq, PartialEq)]
306enum NonLiteralToken {
307 Ident(String),
308 Punct(char),
309}
310
311fn non_literal_token_markers(tokens: TokenStream) -> Vec<NonLiteralToken> {
312 let mut markers = Vec::new();
313 collect_non_literal_token_markers(tokens, &mut markers);
314 markers
315}
316
317fn contains_deterministic_seed_type(tokens: TokenStream) -> bool {
318 markers_contain_deterministic_seed_type(&non_literal_token_markers(tokens))
319}
320
321fn collect_non_literal_token_markers(tokens: TokenStream, output: &mut Vec<NonLiteralToken>) {
322 for token in tokens {
323 match token {
324 TokenTree::Group(group) => {
325 let delimiter = group.delimiter();
326 if let Some((open, _)) = delimiter_markers(delimiter) {
327 output.push(NonLiteralToken::Punct(open));
328 }
329 collect_non_literal_token_markers(group.stream(), output);
330 if let Some((_, close)) = delimiter_markers(delimiter) {
331 output.push(NonLiteralToken::Punct(close));
332 }
333 }
334 TokenTree::Ident(ident) => output.push(NonLiteralToken::Ident(ident.to_string())),
335 TokenTree::Punct(punct) => output.push(NonLiteralToken::Punct(punct.as_char())),
336 TokenTree::Literal(_) => {}
337 }
338 }
339}
340
341fn delimiter_markers(delimiter: Delimiter) -> Option<(char, char)> {
342 match delimiter {
343 Delimiter::Parenthesis => Some(('(', ')')),
344 Delimiter::Brace => Some(('{', '}')),
345 Delimiter::Bracket => Some(('[', ']')),
346 Delimiter::None => None,
347 }
348}
349
350fn markers_contain_deterministic_seed_type(markers: &[NonLiteralToken]) -> bool {
351 markers.windows(4).any(|window| {
352 matches!(
353 window,
354 [
355 NonLiteralToken::Ident(type_name),
356 NonLiteralToken::Punct('<'),
357 NonLiteralToken::Ident(seed_name),
358 NonLiteralToken::Punct('>'),
359 ] if type_name == "Deterministic" && seed_name == "Seed"
360 )
361 })
362}
363
364fn append_non_literal_tokens(tokens: TokenStream, output: &mut String) {
365 for token in tokens {
366 match token {
367 TokenTree::Group(group) => append_group(group, output),
368 TokenTree::Ident(ident) => output.push_str(&ident.to_string()),
369 TokenTree::Punct(punct) => output.push(punct.as_char()),
370 TokenTree::Literal(_) => {}
371 }
372 }
373}
374
375fn append_group(group: Group, output: &mut String) {
376 match group.delimiter() {
377 Delimiter::Parenthesis => output.push('('),
378 Delimiter::Brace => output.push('{'),
379 Delimiter::Bracket => output.push('['),
380 Delimiter::None => {}
381 }
382 append_non_literal_tokens(group.stream(), output);
383 match group.delimiter() {
384 Delimiter::Parenthesis => output.push(')'),
385 Delimiter::Brace => output.push('}'),
386 Delimiter::Bracket => output.push(']'),
387 Delimiter::None => {}
388 }
389}
390
391fn contains_domain_id_now(compact: &str) -> bool {
392 let mut search_start = 0;
393 while let Some(relative_index) = compact[search_start..].find("::now(") {
394 let now_index = search_start + relative_index;
395 let prefix = &compact[..now_index];
396 let type_name = prefix
397 .rsplit(|ch: char| !is_identifier_char(ch))
398 .next()
399 .unwrap_or_default();
400 if type_name.ends_with("Id") {
401 return true;
402 }
403 search_start = now_index + "::now(".len();
404 }
405 false
406}
407
408fn contains_hash_collection_iteration(markers: &[NonLiteralToken], type_name: &str) -> bool {
409 hash_collection_bindings_from_markers(markers, type_name)
410 .iter()
411 .any(|binding| hash_collection_iteration_call(markers, binding))
412 || hash_collection_direct_iteration_call(markers, type_name)
413}
414
415fn hash_collection_bindings_from_markers(
416 markers: &[NonLiteralToken],
417 type_name: &str,
418) -> Vec<String> {
419 let mut bindings = Vec::new();
420 for colon_index in markers.iter().enumerate().filter_map(|(index, marker)| {
421 (marker == &NonLiteralToken::Punct(':')
422 && !matches!(
423 markers.get(index.saturating_sub(1)),
424 Some(NonLiteralToken::Punct(':'))
425 )
426 && !matches!(markers.get(index + 1), Some(NonLiteralToken::Punct(':'))))
427 .then_some(index)
428 }) {
429 if !markers_match_hash_collection_type(markers, colon_index + 1, type_name) {
430 continue;
431 }
432 if let Some(binding) = binding_name_before_colon(markers, colon_index) {
433 push_unique_binding(&mut bindings, binding);
434 }
435 }
436
437 for equals_index in markers
438 .iter()
439 .enumerate()
440 .filter_map(|(index, marker)| (marker == &NonLiteralToken::Punct('=')).then_some(index))
441 {
442 if !markers_match_hash_collection_constructor(markers, equals_index + 1, type_name) {
443 continue;
444 }
445 if let Some(binding) = binding_name_before_equals(markers, equals_index) {
446 push_unique_binding(&mut bindings, binding);
447 }
448 }
449 bindings
450}
451
452fn push_unique_binding(bindings: &mut Vec<String>, binding: String) {
453 if !bindings.iter().any(|existing| existing == &binding) {
454 bindings.push(binding);
455 }
456}
457
458fn markers_match_hash_collection_constructor(
459 markers: &[NonLiteralToken],
460 start: usize,
461 type_name: &str,
462) -> bool {
463 let Some(path_end) = hash_collection_type_path_end(markers, start, type_name) else {
464 return false;
465 };
466 let Some(method_path_start) = hash_collection_constructor_method_start(markers, path_end)
467 else {
468 return false;
469 };
470 matches!(
471 ident_at(markers, method_path_start),
472 Some("new" | "with_capacity" | "from" | "default")
473 )
474}
475
476fn hash_collection_constructor_method_start(
477 markers: &[NonLiteralToken],
478 path_end: usize,
479) -> Option<usize> {
480 let mut double_colon_index = path_end;
481 if double_colon_at(markers, double_colon_index)
482 && matches!(
483 markers.get(double_colon_index + 2),
484 Some(NonLiteralToken::Punct('<'))
485 )
486 {
487 double_colon_index = skip_angle_group(markers, double_colon_index + 2)?;
488 } else if matches!(
489 markers.get(double_colon_index),
490 Some(NonLiteralToken::Punct('<'))
491 ) {
492 double_colon_index = skip_angle_group(markers, double_colon_index)?;
493 }
494 double_colon_at(markers, double_colon_index).then_some(double_colon_index + 2)
495}
496
497fn skip_angle_group(markers: &[NonLiteralToken], start: usize) -> Option<usize> {
498 let mut depth = 0_usize;
499 for (index, marker) in markers.iter().enumerate().skip(start) {
500 match marker {
501 NonLiteralToken::Punct('<') => depth += 1,
502 NonLiteralToken::Punct('>') => {
503 depth = depth.saturating_sub(1);
504 if depth == 0 {
505 return Some(index + 1);
506 }
507 }
508 _ => {}
509 }
510 }
511 None
512}
513
514fn markers_match_hash_collection_type(
515 markers: &[NonLiteralToken],
516 start: usize,
517 type_name: &str,
518) -> bool {
519 let Some(path_end) = hash_collection_type_path_end(markers, start, type_name) else {
520 return false;
521 };
522 matches!(markers.get(path_end), Some(NonLiteralToken::Punct('<')))
523}
524
525fn hash_collection_type_path_end(
526 markers: &[NonLiteralToken],
527 mut start: usize,
528 type_name: &str,
529) -> Option<usize> {
530 if double_colon_at(markers, start) {
531 start += 2;
532 }
533 if ident_at(markers, start) == Some(type_name) {
534 return Some(start + 1);
535 }
536 if ident_at(markers, start) == Some("std")
537 && double_colon_at(markers, start + 1)
538 && ident_at(markers, start + 3) == Some("collections")
539 && double_colon_at(markers, start + 4)
540 && ident_at(markers, start + 6) == Some(type_name)
541 {
542 return Some(start + 7);
543 }
544 None
545}
546
547fn binding_name_before_colon(markers: &[NonLiteralToken], colon_index: usize) -> Option<String> {
548 let binding = ident_at(markers, colon_index.checked_sub(1)?)?;
549 if matches!(binding, "let" | "mut" | "ref" | "_") {
550 None
551 } else {
552 Some(binding.to_owned())
553 }
554}
555
556fn binding_name_before_equals(markers: &[NonLiteralToken], equals_index: usize) -> Option<String> {
557 let binding_index = equals_index.checked_sub(1)?;
558 let binding = ident_at(markers, binding_index)?;
559 if binding == "_" {
560 return None;
561 }
562
563 if binding_index
564 .checked_sub(1)
565 .and_then(|index| ident_at(markers, index))
566 == Some("let")
567 {
568 return Some(binding.to_owned());
569 }
570
571 if binding_index
572 .checked_sub(1)
573 .and_then(|index| ident_at(markers, index))
574 == Some("mut")
575 && binding_index
576 .checked_sub(2)
577 .and_then(|index| ident_at(markers, index))
578 == Some("let")
579 {
580 return Some(binding.to_owned());
581 }
582
583 None
584}
585
586fn hash_collection_iteration_call(markers: &[NonLiteralToken], binding: &str) -> bool {
587 ["iter", "keys", "values", "into_iter", "drain"]
588 .iter()
589 .any(|method| contains_receiver_method_call(markers, binding, method))
590}
591
592fn hash_collection_direct_iteration_call(markers: &[NonLiteralToken], type_name: &str) -> bool {
593 let mut start = 0;
594 while start < markers.len() {
595 let Some(path_end) = hash_collection_type_path_end(markers, start, type_name) else {
596 start += 1;
597 continue;
598 };
599 let Some(method_path_start) = hash_collection_constructor_method_start(markers, path_end)
600 else {
601 start = path_end.max(start + 1);
602 continue;
603 };
604 if !matches!(
605 ident_at(markers, method_path_start),
606 Some("new" | "with_capacity" | "from" | "default")
607 ) {
608 start = method_path_start + 1;
609 continue;
610 }
611 if constructor_chain_has_iteration(markers, method_path_start) {
612 return true;
613 }
614 start = method_path_start + 1;
615 }
616
617 false
618}
619
620fn constructor_chain_has_iteration(markers: &[NonLiteralToken], method_index: usize) -> bool {
621 let Some(mut index) = constructor_invocation_end(markers, method_index) else {
622 return false;
623 };
624
625 while matches!(markers.get(index), Some(NonLiteralToken::Punct('.'))) {
626 let method_name_index = index + 1;
627 if matches!(
628 ident_at(markers, method_name_index),
629 Some("iter" | "keys" | "values" | "into_iter" | "drain")
630 ) {
631 return true;
632 }
633
634 index = method_name_index + 1;
635 if double_colon_at(markers, index)
636 && matches!(markers.get(index + 2), Some(NonLiteralToken::Punct('<')))
637 {
638 let Some(next_index) = skip_angle_group(markers, index + 2) else {
639 return false;
640 };
641 index = next_index;
642 }
643 if matches!(markers.get(index), Some(NonLiteralToken::Punct('('))) {
644 let Some(next_index) = skip_balanced_punct_group(markers, index, '(', ')') else {
645 return false;
646 };
647 index = next_index;
648 }
649 }
650
651 false
652}
653
654fn constructor_invocation_end(markers: &[NonLiteralToken], method_index: usize) -> Option<usize> {
655 let mut cursor = method_index + 1;
656 if double_colon_at(markers, cursor)
657 && matches!(markers.get(cursor + 2), Some(NonLiteralToken::Punct('<')))
658 {
659 cursor = skip_angle_group(markers, cursor + 2)?;
660 }
661
662 match markers.get(cursor) {
663 Some(NonLiteralToken::Punct('(')) => skip_balanced_punct_group(markers, cursor, '(', ')'),
664 _ => None,
665 }
666}
667
668fn skip_balanced_punct_group(
669 markers: &[NonLiteralToken],
670 start: usize,
671 open: char,
672 close: char,
673) -> Option<usize> {
674 let mut depth = 0_usize;
675 for (index, marker) in markers.iter().enumerate().skip(start) {
676 match marker {
677 NonLiteralToken::Punct(ch) if *ch == open => depth += 1,
678 NonLiteralToken::Punct(ch) if *ch == close => {
679 depth = depth.checked_sub(1)?;
680 if depth == 0 {
681 return Some(index + 1);
682 }
683 }
684 _ => {}
685 }
686 }
687
688 None
689}
690
691fn contains_receiver_method_call(
692 markers: &[NonLiteralToken],
693 receiver: &str,
694 method: &str,
695) -> bool {
696 markers.windows(3).any(|window| {
697 matches!(
698 window,
699 [
700 NonLiteralToken::Ident(candidate_receiver),
701 NonLiteralToken::Punct('.'),
702 NonLiteralToken::Ident(candidate_method),
703 ] if candidate_receiver == receiver && candidate_method == method
704 )
705 })
706}
707
708fn ident_at(markers: &[NonLiteralToken], index: usize) -> Option<&str> {
709 match markers.get(index) {
710 Some(NonLiteralToken::Ident(value)) => Some(value),
711 _ => None,
712 }
713}
714
715fn double_colon_at(markers: &[NonLiteralToken], index: usize) -> bool {
716 matches!(
717 (markers.get(index), markers.get(index + 1)),
718 (
719 Some(NonLiteralToken::Punct(':')),
720 Some(NonLiteralToken::Punct(':'))
721 )
722 )
723}
724
725fn is_identifier_char(ch: char) -> bool {
726 ch == '_' || ch.is_ascii_alphanumeric()
727}
728
729fn compile_error(message: &str) -> TokenStream {
730 format!("compile_error!({message:?});")
731 .parse()
732 .expect("compile_error token stream")
733}
734
735#[cfg(test)]
736mod tests {
737 use super::{
738 NonLiteralToken, contains_ambient_call, contains_hash_collection_iteration,
739 hash_collection_bindings_from_markers, markers_contain_deterministic_seed_type,
740 };
741
742 fn ident(value: &str) -> NonLiteralToken {
743 NonLiteralToken::Ident(value.to_owned())
744 }
745
746 fn punct(value: char) -> NonLiteralToken {
747 NonLiteralToken::Punct(value)
748 }
749
750 #[test]
751 fn exact_deterministic_seed_parameter_shapes_are_accepted() {
752 assert!(markers_contain_deterministic_seed_type(&[
753 punct('&'),
754 ident("Deterministic"),
755 punct('<'),
756 ident("Seed"),
757 punct('>'),
758 ]));
759 assert!(markers_contain_deterministic_seed_type(&[
760 punct('&'),
761 ident("mut"),
762 ident("Deterministic"),
763 punct('<'),
764 ident("Seed"),
765 punct('>'),
766 ]));
767 assert!(markers_contain_deterministic_seed_type(&[
768 ident("ee"),
769 punct(':'),
770 punct(':'),
771 ident("runtime"),
772 punct(':'),
773 punct(':'),
774 ident("determinism"),
775 punct(':'),
776 punct(':'),
777 ident("Deterministic"),
778 punct('<'),
779 ident("Seed"),
780 punct('>'),
781 ]));
782 assert!(markers_contain_deterministic_seed_type(&[
783 ident("Option"),
784 punct('<'),
785 punct('&'),
786 ident("Deterministic"),
787 punct('<'),
788 ident("Seed"),
789 punct('>'),
790 punct('>'),
791 ]));
792 }
793
794 #[test]
795 fn similarly_named_seed_parameter_shapes_are_rejected() {
796 assert!(!markers_contain_deterministic_seed_type(&[
797 punct('&'),
798 ident("NonDeterministic"),
799 punct('<'),
800 ident("Seed"),
801 punct('>'),
802 ]));
803 assert!(!markers_contain_deterministic_seed_type(&[
804 punct('&'),
805 ident("NotDeterministic"),
806 punct('<'),
807 ident("Seed"),
808 punct('>'),
809 ]));
810 assert!(!markers_contain_deterministic_seed_type(&[
811 punct('&'),
812 ident("Deterministic"),
813 punct('<'),
814 ident("Seeded"),
815 punct('>'),
816 ]));
817 assert!(!markers_contain_deterministic_seed_type(&[
818 punct('&'),
819 ident("Deterministic"),
820 punct('<'),
821 ident("Seed"),
822 punct(','),
823 ident("Other"),
824 punct('>'),
825 ]));
826 }
827
828 #[test]
829 fn ambient_random_detection_catches_plain_and_turbofish_calls() {
830 assert!(contains_ambient_call(
831 "fnf(){let_=rand::thread_rng();}",
832 "thread_rng("
833 ));
834 assert!(contains_ambient_call(
835 "fnf(){let_=rand::random();}",
836 "rand::random("
837 ));
838 assert!(contains_ambient_call(
839 "fnf(){let_=rand::random::<u64>();}",
840 "rand::random<"
841 ));
842 assert!(contains_ambient_call("fnf(){let_=random();}", "random("));
843 assert!(contains_ambient_call(
844 "fnf(){let_=random::<u64>();}",
845 "random<"
846 ));
847 assert!(contains_ambient_call(
848 "fnf(){let_=std::time::Instant::now();}",
849 "Instant::now("
850 ));
851 assert!(contains_ambient_call(
852 "fnf(){let_=std::time::SystemTime::now();}",
853 "SystemTime::now("
854 ));
855 }
856
857 #[test]
858 fn ambient_call_detection_ignores_identifier_suffixes() {
859 assert!(!contains_ambient_call(
860 "fnf(){let_=not_random();}",
861 "random("
862 ));
863 assert!(!contains_ambient_call(
864 "fnf(){let_=deterministic_random::<u64>();}",
865 "random<"
866 ));
867 assert!(!contains_ambient_call(
868 "fnf(){let_=deterministic::random();}",
869 "random("
870 ));
871 assert!(!contains_ambient_call(
872 "fnf(){let_=deterministic::random::<u64>();}",
873 "random<"
874 ));
875 assert!(!contains_ambient_call("fnf(){let_=random<x;}", "random<"));
876 assert!(!contains_ambient_call(
877 "fnf(){let_=my_env::var();}",
878 "env::var("
879 ));
880 assert!(!contains_ambient_call(
881 "fnf(){let_=my::env::var();}",
882 "env::var("
883 ));
884 assert!(!contains_ambient_call(
885 "fnf(){let_=my::process::id();}",
886 "process::id("
887 ));
888 assert!(!contains_ambient_call(
889 "fnf(){let_=my::thread::current();}",
890 "thread::current("
891 ));
892 assert!(!contains_ambient_call(
893 "fnf(){let_=my::fs::read_dir();}",
894 "fs::read_dir("
895 ));
896 assert!(!contains_ambient_call(
897 "fnf(){let_=my::getrandom::fill(&mut bytes);}",
898 "getrandom::fill("
899 ));
900 }
901
902 #[test]
903 fn ambient_call_detection_catches_exact_qualified_module_paths() {
904 assert!(contains_ambient_call(
905 "fnf(){let_=std::env::var(\"EE_SEED\");}",
906 "std::env::var("
907 ));
908 assert!(contains_ambient_call(
909 "fnf(){let_=std::process::id();}",
910 "std::process::id("
911 ));
912 assert!(contains_ambient_call(
913 "fnf(){let_=std::thread::current();}",
914 "std::thread::current("
915 ));
916 assert!(contains_ambient_call(
917 "fnf(){let_=std::fs::read_dir(\".\");}",
918 "std::fs::read_dir("
919 ));
920 }
921
922 #[test]
923 fn ambient_call_detection_catches_absolute_module_paths() {
924 assert!(contains_ambient_call(
925 "fnf(){let_=::std::env::var(\"EE_SEED\");}",
926 "std::env::var("
927 ));
928 assert!(contains_ambient_call(
929 "fnf(){let_=::rand::random::<u64>();}",
930 "rand::random<"
931 ));
932 }
933
934 #[test]
935 fn ambient_call_detection_ignores_prefixed_exact_module_paths() {
936 assert!(!contains_ambient_call(
937 "fnf(){let_=my::std::env::var(\"EE_SEED\");}",
938 "std::env::var("
939 ));
940 assert!(!contains_ambient_call(
941 "fnf(){let_=my::rand::random::<u64>();}",
942 "rand::random<"
943 ));
944 }
945
946 #[test]
947 fn hash_collection_iteration_detection_catches_typed_bindings() {
948 let markers = [
949 ident("map"),
950 punct(':'),
951 ident("HashMap"),
952 punct('<'),
953 ident("String"),
954 punct('>'),
955 ident("set"),
956 punct(':'),
957 ident("std"),
958 punct(':'),
959 punct(':'),
960 ident("collections"),
961 punct(':'),
962 punct(':'),
963 ident("HashSet"),
964 punct('<'),
965 ident("String"),
966 punct('>'),
967 ];
968
969 assert_eq!(
970 hash_collection_bindings_from_markers(&markers, "HashMap"),
971 vec!["map".to_owned()]
972 );
973 assert_eq!(
974 hash_collection_bindings_from_markers(&markers, "HashSet"),
975 vec!["set".to_owned()]
976 );
977 let mut map_iteration = markers.to_vec();
978 map_iteration.extend([ident("map"), punct('.'), ident("iter")]);
979 let mut set_iteration = markers.to_vec();
980 set_iteration.extend([ident("set"), punct('.'), ident("into_iter")]);
981
982 assert!(contains_hash_collection_iteration(
983 &map_iteration,
984 "HashMap"
985 ));
986 assert!(contains_hash_collection_iteration(
987 &set_iteration,
988 "HashSet"
989 ));
990 }
991
992 #[test]
993 fn hash_collection_iteration_detection_catches_inferred_constructor_bindings() {
994 let markers = [
995 ident("let"),
996 ident("mut"),
997 ident("map"),
998 punct('='),
999 ident("HashMap"),
1000 punct(':'),
1001 punct(':'),
1002 ident("new"),
1003 ident("let"),
1004 ident("set"),
1005 punct('='),
1006 ident("std"),
1007 punct(':'),
1008 punct(':'),
1009 ident("collections"),
1010 punct(':'),
1011 punct(':'),
1012 ident("HashSet"),
1013 punct(':'),
1014 punct(':'),
1015 ident("with_capacity"),
1016 ident("let"),
1017 ident("typed_map"),
1018 punct('='),
1019 ident("HashMap"),
1020 punct(':'),
1021 punct(':'),
1022 punct('<'),
1023 ident("String"),
1024 punct(','),
1025 ident("String"),
1026 punct('>'),
1027 punct(':'),
1028 punct(':'),
1029 ident("default"),
1030 ];
1031
1032 assert_eq!(
1033 hash_collection_bindings_from_markers(&markers, "HashMap"),
1034 vec!["map".to_owned(), "typed_map".to_owned()]
1035 );
1036 assert_eq!(
1037 hash_collection_bindings_from_markers(&markers, "HashSet"),
1038 vec!["set".to_owned()]
1039 );
1040
1041 let mut map_iteration = markers.to_vec();
1042 map_iteration.extend([ident("map"), punct('.'), ident("iter")]);
1043 let mut set_iteration = markers.to_vec();
1044 set_iteration.extend([ident("set"), punct('.'), ident("drain")]);
1045 let mut typed_map_iteration = markers.to_vec();
1046 typed_map_iteration.extend([ident("typed_map"), punct('.'), ident("values")]);
1047
1048 assert!(contains_hash_collection_iteration(
1049 &map_iteration,
1050 "HashMap"
1051 ));
1052 assert!(contains_hash_collection_iteration(
1053 &set_iteration,
1054 "HashSet"
1055 ));
1056 assert!(contains_hash_collection_iteration(
1057 &typed_map_iteration,
1058 "HashMap"
1059 ));
1060 }
1061
1062 #[test]
1063 fn hash_collection_iteration_detection_catches_direct_constructor_chains() {
1064 let direct_map_iteration = [
1065 ident("HashMap"),
1066 punct(':'),
1067 punct(':'),
1068 punct('<'),
1069 ident("String"),
1070 punct(','),
1071 ident("String"),
1072 punct('>'),
1073 punct(':'),
1074 punct(':'),
1075 ident("from"),
1076 punct('('),
1077 ident("entries"),
1078 punct('.'),
1079 ident("values"),
1080 punct('('),
1081 punct(')'),
1082 punct(')'),
1083 punct('.'),
1084 ident("iter"),
1085 ];
1086 let direct_set_iteration = [
1087 ident("std"),
1088 punct(':'),
1089 punct(':'),
1090 ident("collections"),
1091 punct(':'),
1092 punct(':'),
1093 ident("HashSet"),
1094 punct(':'),
1095 punct(':'),
1096 ident("default"),
1097 punct('('),
1098 punct(')'),
1099 punct('.'),
1100 ident("into_iter"),
1101 ];
1102
1103 assert!(contains_hash_collection_iteration(
1104 &direct_map_iteration,
1105 "HashMap"
1106 ));
1107 assert!(contains_hash_collection_iteration(
1108 &direct_set_iteration,
1109 "HashSet"
1110 ));
1111 }
1112
1113 #[test]
1114 fn hash_collection_direct_constructor_detection_stops_at_statement_boundary() {
1115 let markers = [
1116 ident("HashMap"),
1117 punct(':'),
1118 punct(':'),
1119 ident("new"),
1120 punct('('),
1121 punct(')'),
1122 punct(';'),
1123 ident("map"),
1124 punct('.'),
1125 ident("iter"),
1126 ];
1127
1128 assert!(!contains_hash_collection_iteration(&markers, "HashMap"));
1129 }
1130
1131 #[test]
1132 fn hash_collection_direct_constructor_detection_ignores_argument_iteration() {
1133 let constructor_from_iterator = [
1134 ident("HashMap"),
1135 punct(':'),
1136 punct(':'),
1137 ident("from"),
1138 punct('('),
1139 ident("entries"),
1140 punct('.'),
1141 ident("iter"),
1142 punct('('),
1143 punct(')'),
1144 punct(')'),
1145 punct('.'),
1146 ident("len"),
1147 punct('('),
1148 punct(')'),
1149 ];
1150 let sibling_iteration_after_constructor_argument = [
1151 ident("consume"),
1152 punct('('),
1153 ident("HashSet"),
1154 punct(':'),
1155 punct(':'),
1156 ident("new"),
1157 punct('('),
1158 punct(')'),
1159 punct(','),
1160 ident("items"),
1161 punct('.'),
1162 ident("iter"),
1163 punct('('),
1164 punct(')'),
1165 punct(')'),
1166 ];
1167
1168 assert!(!contains_hash_collection_iteration(
1169 &constructor_from_iterator,
1170 "HashMap"
1171 ));
1172 assert!(!contains_hash_collection_iteration(
1173 &sibling_iteration_after_constructor_argument,
1174 "HashSet"
1175 ));
1176 }
1177
1178 #[test]
1179 fn hash_collection_binding_detection_ignores_wildcard_typed_parameters() {
1180 let markers = [
1181 ident("fn"),
1182 ident("ambient"),
1183 punct('('),
1184 ident("previous"),
1185 punct(':'),
1186 ident("Vec"),
1187 punct('<'),
1188 ident("String"),
1189 punct('>'),
1190 punct(','),
1191 ident("_"),
1192 punct(':'),
1193 ident("HashMap"),
1194 punct('<'),
1195 ident("String"),
1196 punct(','),
1197 ident("String"),
1198 punct('>'),
1199 punct(')'),
1200 ident("previous"),
1201 punct('.'),
1202 ident("iter"),
1203 ];
1204
1205 assert!(hash_collection_bindings_from_markers(&markers, "HashMap").is_empty());
1206 assert!(!contains_hash_collection_iteration(&markers, "HashMap"));
1207 }
1208
1209 #[test]
1210 fn hash_collection_iteration_detection_ignores_receiver_suffixes() {
1211 let markers = [
1212 ident("map"),
1213 punct(':'),
1214 ident("HashMap"),
1215 punct('<'),
1216 ident("String"),
1217 punct('>'),
1218 ];
1219
1220 let mut suffixed_receiver = markers.to_vec();
1221 suffixed_receiver.extend([ident("notmap"), punct('.'), ident("iter")]);
1222 let mut non_iteration_method = markers.to_vec();
1223 non_iteration_method.extend([ident("map"), punct('.'), ident("len")]);
1224
1225 assert!(!contains_hash_collection_iteration(
1226 &suffixed_receiver,
1227 "HashMap"
1228 ));
1229 assert!(!contains_hash_collection_iteration(
1230 &non_iteration_method,
1231 "HashMap"
1232 ));
1233 }
1234
1235 #[test]
1236 fn hash_collection_binding_detection_ignores_value_expressions() {
1237 let markers = [
1238 ident("field"),
1239 punct(':'),
1240 ident("HashMap"),
1241 punct(':'),
1242 punct(':'),
1243 ident("new"),
1244 ];
1245
1246 assert!(hash_collection_bindings_from_markers(&markers, "HashMap").is_empty());
1247 }
1248
1249 #[test]
1250 fn hash_collection_binding_detection_ignores_non_let_constructor_assignments() {
1251 let markers = [
1252 ident("field"),
1253 punct('='),
1254 ident("HashMap"),
1255 punct(':'),
1256 punct(':'),
1257 ident("new"),
1258 ident("field"),
1259 punct('.'),
1260 ident("iter"),
1261 ident("let"),
1262 ident("_"),
1263 punct('='),
1264 ident("HashMap"),
1265 punct(':'),
1266 punct(':'),
1267 ident("new"),
1268 ];
1269
1270 assert!(hash_collection_bindings_from_markers(&markers, "HashMap").is_empty());
1271 assert!(!contains_hash_collection_iteration(&markers, "HashMap"));
1272 }
1273}