1use std::collections::HashSet;
21use std::path::Path;
22
23#[must_use]
28pub fn unasserted(src: &Path) -> Vec<String> {
29 let mut files = Vec::new();
30 collect(src, src, &mut files);
31 files.sort();
32 check(&files)
33}
34
35fn check(files: &[(String, String)]) -> Vec<String> {
38 let mut declared = Vec::new();
39 let mut asserted = HashSet::new();
40 for (module, text) in files {
41 scan(module, text, &mut declared, &mut asserted);
42 }
43 declared.retain(|p| !asserted.contains(p));
44 declared
45}
46
47fn collect(root: &Path, dir: &Path, out: &mut Vec<(String, String)>) {
48 let mut entries: Vec<_> = std::fs::read_dir(dir)
49 .unwrap_or_else(|e| panic!("{}: {e}", dir.display()))
50 .map(|e| {
51 e.unwrap_or_else(|e| panic!("{}: {e}", dir.display()))
52 .path()
53 })
54 .collect();
55 entries.sort();
56 for path in entries {
57 if path.is_dir() {
58 collect(root, &path, out);
59 } else if path.extension().is_some_and(|e| e == "rs") {
60 let text = std::fs::read_to_string(&path)
61 .unwrap_or_else(|e| panic!("{}: {e}", path.display()));
62 out.push((module_of(root, &path), text));
63 }
64 }
65}
66
67fn module_of(root: &Path, file: &Path) -> String {
70 let rel = file.strip_prefix(root).unwrap_or(file).with_extension("");
71 let mut parts: Vec<String> = rel
72 .components()
73 .map(|c| c.as_os_str().to_string_lossy().into_owned())
74 .collect();
75 if matches!(
76 parts.last().map(String::as_str),
77 Some("lib" | "main" | "mod")
78 ) {
79 parts.pop();
80 }
81 parts.join("::")
82}
83
84fn join(module: &str, name: &str) -> String {
85 if module.is_empty() {
86 name.to_owned()
87 } else {
88 format!("{module}::{name}")
89 }
90}
91
92fn ident(s: &str) -> String {
93 s.chars()
94 .take_while(|c| c.is_alphanumeric() || *c == '_')
95 .collect()
96}
97
98struct Inline {
100 indent: usize,
101 name: String,
102 public: bool,
103}
104
105fn code_only(text: &str) -> String {
111 let chars: Vec<char> = text.chars().collect();
112 let mut out = String::with_capacity(text.len());
113 let at = |i: usize| chars.get(i).copied();
114 let mut i = 0;
115 while let Some(c) = at(i) {
116 if c == '/' && at(i + 1) == Some('/') {
117 while at(i).is_some_and(|c| c != '\n') {
118 i += 1;
119 }
120 } else if c == '/' && at(i + 1) == Some('*') {
121 let mut depth = 0usize;
122 while let Some(c) = at(i) {
123 if c == '/' && at(i + 1) == Some('*') {
124 depth += 1;
125 i += 2;
126 } else if c == '*' && at(i + 1) == Some('/') {
127 depth -= 1;
128 i += 2;
129 if depth == 0 {
130 break;
131 }
132 } else {
133 if c == '\n' {
134 out.push('\n');
135 }
136 i += 1;
137 }
138 }
139 } else if c == 'r' && matches!(at(i + 1), Some('"' | '#')) && {
140 let mut j = i + 1;
141 while at(j) == Some('#') {
142 j += 1;
143 }
144 at(j) == Some('"')
145 } {
146 let mut hashes = 0;
147 i += 1;
148 while at(i) == Some('#') {
149 hashes += 1;
150 i += 1;
151 }
152 i += 1;
153 out.push_str("\"\"");
154 while let Some(c) = at(i) {
155 if c == '"' && (1..=hashes).all(|k| at(i + k) == Some('#')) {
156 i += 1 + hashes;
157 break;
158 }
159 if c == '\n' {
160 out.push('\n');
161 }
162 i += 1;
163 }
164 } else if c == '"' {
165 i += 1;
166 out.push_str("\"\"");
167 while let Some(c) = at(i) {
168 i += 1;
169 match c {
170 '\\' => i += 1,
171 '"' => break,
172 '\n' => out.push('\n'),
173 _ => {}
174 }
175 }
176 } else if c == '\'' && (at(i + 2) == Some('\'') || at(i + 1) == Some('\\')) {
177 i += 1;
179 if at(i) == Some('\\') {
180 i += 1;
181 }
182 i += 1;
183 while at(i).is_some_and(|c| c != '\'' && c != '\n') {
184 i += 1;
185 }
186 i += 1;
187 out.push_str("' '");
188 } else {
189 out.push(c);
190 i += 1;
191 }
192 }
193 out
194}
195
196fn scan(file_module: &str, text: &str, declared: &mut Vec<String>, asserted: &mut HashSet<String>) {
197 let mut stack: Vec<Inline> = Vec::new();
198 let text = code_only(text);
199 for line in text.lines() {
200 let trimmed = line.trim_start();
201 let indent = line.len() - trimmed.len();
202 if trimmed.starts_with("//") {
203 continue;
204 }
205 if trimmed == "}" && stack.last().is_some_and(|m| m.indent == indent) {
206 stack.pop();
207 continue;
208 }
209 let module = stack
210 .iter()
211 .fold(file_module.to_owned(), |m, i| join(&m, &i.name));
212 for (kw, public) in [
213 ("pub mod ", true),
214 ("pub(crate) mod ", false),
215 ("mod ", false),
216 ] {
217 if let Some(rest) = trimmed.strip_prefix(kw)
218 && trimmed.ends_with('{')
219 {
220 stack.push(Inline {
221 indent,
222 name: ident(rest),
223 public,
224 });
225 }
226 }
227 if stack.iter().all(|m| m.public) {
228 for kw in [
229 "pub struct ",
230 "pub enum ",
231 "pub union ",
232 "pub trait ",
233 "pub type ",
234 ] {
235 if let Some(rest) = trimmed.strip_prefix(kw) {
236 declared.push(join(&module, &ident(rest)));
237 }
238 }
239 }
240 let mut rest = line;
241 while let Some(at) = rest.find("send_sync::<") {
242 rest = &rest[at + "send_sync::<".len()..];
243 let Some(end) = rest.rfind(">()") else { break };
244 let path = rest[..end].trim();
245 let path = path.strip_prefix("dyn ").unwrap_or(path);
246 let path = path.split(['<', '+']).next().unwrap_or(path).trim();
248 let full = match path.strip_prefix("crate::") {
249 Some(abs) => abs.to_owned(),
250 None => join(&module, path),
251 };
252 asserted.insert(full);
253 rest = &rest[end..];
254 }
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::{HashSet, check, scan};
261
262 fn run(module: &str, text: &str) -> (Vec<String>, HashSet<String>) {
263 let mut d = Vec::new();
264 let mut a = HashSet::new();
265 scan(module, text, &mut d, &mut a);
266 (d, a)
267 }
268
269 #[test]
270 fn types_are_named_by_their_full_path() {
271 let (d, a) = run(
272 "env::resource",
273 "pub struct Permit(pub std::rc::Rc<u8>);\n\
274 pub mod inner {\n pub enum E {}\n}\n\
275 mod tests {\n pub struct Hidden;\n}\n\
276 const _: () = crate::send_sync::<Ok>();\n",
277 );
278 assert_eq!(d, ["env::resource::Permit", "env::resource::inner::E"]);
279 assert!(a.contains("env::resource::Ok"));
280 }
281
282 #[test]
283 fn a_trait_object_is_named_without_its_bounds() {
284 let (_, a) = run(
285 "walk",
286 "const _: () = crate::send_sync::<dyn emit::Elements + Send + Sync>();\n",
287 );
288 assert!(a.contains("walk::emit::Elements"), "{a:?}");
289 }
290
291 #[test]
292 fn aliases_and_unions_are_public_types_too() {
293 let files = [
296 (
297 String::new(),
298 "const _: () = send_sync::<value::ListIx>();\n".to_owned(),
299 ),
300 (
301 "value".to_owned(),
302 "pub type ListIx = u32;\npub type NotShareable = std::rc::Rc<u8>;\npub union Bits { a: u32, b: f32 }\npub type Cell<T> = std::sync::OnceLock<T>;\n".to_owned(),
303 ),
304 ];
305 assert_eq!(
306 check(&files),
307 ["value::NotShareable", "value::Bits", "value::Cell"]
308 );
309 }
310
311 #[test]
312 fn a_type_that_shares_an_asserted_name_is_still_unasserted() {
313 let files = [
316 (
317 String::new(),
318 "const _: () = send_sync::<budget::Permit>();\n".to_owned(),
319 ),
320 ("budget".to_owned(), "pub struct Permit;\n".to_owned()),
321 (
322 "env::resource".to_owned(),
323 "pub struct Permit(pub std::rc::Rc<u8>);\n".to_owned(),
324 ),
325 ];
326 assert_eq!(check(&files), ["env::resource::Permit"]);
327 }
328
329 #[test]
330 fn an_assertion_in_a_comment_or_a_string_asserts_nothing() {
331 let (d, a) = run(
334 "",
335 "pub struct Local(std::rc::Rc<u8>); // send_sync::<Local>()
336 /* send_sync::<InBlock>() /* nested */ send_sync::<AfterNested>() */
337 const S: &str = \"send_sync::<InString>()\";
338 const R: &str = r#\"send_sync::<InRaw>() \" still\"#;
339 const C: char = '\"';
340 fn f<'a>(x: &'a u8) -> &'a u8 { x }
341 const _: () = send_sync::<Real>();
342",
343 );
344 assert_eq!(d, ["Local"]);
345 let mut a: Vec<_> = a.into_iter().collect();
346 a.sort();
347 assert_eq!(a, ["Real"]);
348 }
349
350 #[test]
351 fn assertions_resolve_crate_and_relative_paths() {
352 let (_, a) = run(
353 "",
354 " send_sync::<budget::DecodeBuf>();\n\
355 \x20 send_sync::<dyn env::Fetch>();\n\
356 \x20 send_sync::<walk::ReadCtx<'static>>();\n\
357 \x20 send_sync::<crate::x::Y>();\n",
358 );
359 for p in ["budget::DecodeBuf", "env::Fetch", "walk::ReadCtx", "x::Y"] {
360 assert!(a.contains(p), "{p}: {a:?}");
361 }
362 }
363}