1use weaveffi_ir::ir::{Module, TypeRef};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum DocCommentStyle {
24 TripleSlash,
26 Hash,
28 DoubleSlash,
31 Javadoc,
34}
35
36pub fn emit_doc(out: &mut String, doc: &Option<String>, indent: &str, style: DocCommentStyle) {
42 let Some(doc) = doc else {
43 return;
44 };
45 let doc = doc.trim();
46 if doc.is_empty() {
47 return;
48 }
49 match style {
50 DocCommentStyle::TripleSlash => emit_line_doc(out, doc, indent, "///"),
51 DocCommentStyle::Hash => emit_line_doc(out, doc, indent, "#"),
52 DocCommentStyle::DoubleSlash => emit_line_doc(out, doc, indent, "//"),
53 DocCommentStyle::Javadoc => emit_javadoc(out, doc, indent),
54 }
55}
56
57fn emit_line_doc(out: &mut String, doc: &str, indent: &str, marker: &str) {
58 for line in doc.lines() {
59 out.push_str(indent);
60 if line.is_empty() {
61 out.push_str(marker);
62 out.push('\n');
63 } else {
64 out.push_str(marker);
65 out.push(' ');
66 out.push_str(line);
67 out.push('\n');
68 }
69 }
70}
71
72fn emit_javadoc(out: &mut String, doc: &str, indent: &str) {
73 if doc.contains('\n') {
74 out.push_str(indent);
75 out.push_str("/**\n");
76 for line in doc.lines() {
77 out.push_str(indent);
78 if line.is_empty() {
79 out.push_str(" *\n");
80 } else {
81 out.push_str(" * ");
82 out.push_str(line);
83 out.push('\n');
84 }
85 }
86 out.push_str(indent);
87 out.push_str(" */\n");
88 } else {
89 out.push_str(indent);
90 out.push_str("/** ");
91 out.push_str(doc);
92 out.push_str(" */\n");
93 }
94}
95
96pub fn walk_modules<'a>(roots: &'a [Module]) -> impl Iterator<Item = &'a Module> {
103 let mut stack: Vec<&'a Module> = roots.iter().rev().collect();
104 std::iter::from_fn(move || {
105 let m = stack.pop()?;
106 for child in m.modules.iter().rev() {
107 stack.push(child);
108 }
109 Some(m)
110 })
111}
112
113pub fn walk_modules_with_path<'a>(
118 roots: &'a [Module],
119) -> impl Iterator<Item = (&'a Module, String)> {
120 let mut stack: Vec<(&'a Module, String)> =
121 roots.iter().rev().map(|m| (m, m.name.clone())).collect();
122 std::iter::from_fn(move || {
123 let (m, path) = stack.pop()?;
124 for child in m.modules.iter().rev() {
125 stack.push((child, format!("{path}_{}", child.name)));
126 }
127 Some((m, path))
128 })
129}
130
131pub fn is_c_pointer_type(ty: &TypeRef) -> bool {
143 matches!(
144 ty,
145 TypeRef::StringUtf8
146 | TypeRef::BorrowedStr
147 | TypeRef::Bytes
148 | TypeRef::BorrowedBytes
149 | TypeRef::Struct(_)
150 | TypeRef::Interface(_)
151 | TypeRef::TypedHandle(_)
152 | TypeRef::List(_)
153 | TypeRef::Map(_, _)
154 | TypeRef::Iterator(_)
155 )
156}
157
158pub fn pascal_case(s: &str) -> String {
167 s.split('_')
168 .map(|part| {
169 let mut chars = part.chars();
170 match chars.next() {
171 None => String::new(),
172 Some(first) => first.to_uppercase().chain(chars).collect::<String>(),
173 }
174 })
175 .collect()
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181 use weaveffi_ir::ir::Module;
182
183 fn leaf(name: &str) -> Module {
184 Module {
185 name: name.to_string(),
186 functions: vec![],
187 interfaces: vec![],
188 structs: vec![],
189 enums: vec![],
190 callbacks: vec![],
191 listeners: vec![],
192 errors: None,
193 modules: vec![],
194 }
195 }
196
197 fn with_children(name: &str, children: Vec<Module>) -> Module {
198 Module {
199 modules: children,
200 ..leaf(name)
201 }
202 }
203
204 #[test]
207 fn walk_modules_visits_pre_order() {
208 let roots = vec![
209 with_children("a", vec![leaf("a1"), leaf("a2")]),
210 with_children("b", vec![leaf("b1")]),
211 ];
212 let names: Vec<&str> = walk_modules(&roots).map(|m| m.name.as_str()).collect();
213 assert_eq!(names, vec!["a", "a1", "a2", "b", "b1"]);
214 }
215
216 #[test]
217 fn walk_modules_descends_to_arbitrary_depth() {
218 let roots = vec![with_children(
219 "a",
220 vec![with_children(
221 "b",
222 vec![with_children("c", vec![leaf("d")])],
223 )],
224 )];
225 let names: Vec<&str> = walk_modules(&roots).map(|m| m.name.as_str()).collect();
226 assert_eq!(names, vec!["a", "b", "c", "d"]);
227 }
228
229 #[test]
230 fn walk_modules_empty_input_yields_nothing() {
231 let roots: Vec<Module> = vec![];
232 assert_eq!(walk_modules(&roots).count(), 0);
233 }
234
235 #[test]
238 fn walk_modules_with_path_joins_with_underscore() {
239 let roots = vec![with_children(
240 "outer",
241 vec![with_children("inner", vec![leaf("leaf")])],
242 )];
243 let pairs: Vec<(String, String)> = walk_modules_with_path(&roots)
244 .map(|(m, p)| (m.name.clone(), p))
245 .collect();
246 assert_eq!(
247 pairs,
248 vec![
249 ("outer".into(), "outer".into()),
250 ("inner".into(), "outer_inner".into()),
251 ("leaf".into(), "outer_inner_leaf".into()),
252 ]
253 );
254 }
255
256 #[test]
257 fn walk_modules_with_path_independent_roots() {
258 let roots = vec![
259 with_children("a", vec![leaf("a1")]),
260 with_children("b", vec![leaf("b1")]),
261 ];
262 let paths: Vec<String> = walk_modules_with_path(&roots).map(|(_, p)| p).collect();
263 assert_eq!(paths, vec!["a", "a_a1", "b", "b_b1"]);
264 }
265
266 #[test]
269 fn emit_doc_none_writes_nothing() {
270 let mut out = String::new();
271 emit_doc(&mut out, &None, "", DocCommentStyle::TripleSlash);
272 assert!(out.is_empty());
273 }
274
275 #[test]
276 fn emit_doc_empty_string_writes_nothing() {
277 let mut out = String::new();
278 emit_doc(
279 &mut out,
280 &Some(" \n ".into()),
281 "",
282 DocCommentStyle::TripleSlash,
283 );
284 assert!(out.is_empty());
285 }
286
287 #[test]
288 fn emit_doc_triple_slash_single_line() {
289 let mut out = String::new();
290 emit_doc(
291 &mut out,
292 &Some("Hello, world.".into()),
293 " ",
294 DocCommentStyle::TripleSlash,
295 );
296 assert_eq!(out, " /// Hello, world.\n");
297 }
298
299 #[test]
300 fn emit_doc_triple_slash_multi_line_with_blank() {
301 let mut out = String::new();
302 emit_doc(
303 &mut out,
304 &Some("First line.\n\nThird line.".into()),
305 "",
306 DocCommentStyle::TripleSlash,
307 );
308 assert_eq!(out, "/// First line.\n///\n/// Third line.\n");
309 }
310
311 #[test]
312 fn emit_doc_hash_single_line() {
313 let mut out = String::new();
314 emit_doc(
315 &mut out,
316 &Some("ruby/python style".into()),
317 "",
318 DocCommentStyle::Hash,
319 );
320 assert_eq!(out, "# ruby/python style\n");
321 }
322
323 #[test]
324 fn emit_doc_double_slash_single_line() {
325 let mut out = String::new();
326 emit_doc(
327 &mut out,
328 &Some("Go-style line comment.".into()),
329 "",
330 DocCommentStyle::DoubleSlash,
331 );
332 assert_eq!(out, "// Go-style line comment.\n");
333 }
334
335 #[test]
336 fn emit_doc_double_slash_multi_line() {
337 let mut out = String::new();
338 emit_doc(
339 &mut out,
340 &Some("first\n\nsecond".into()),
341 "\t",
342 DocCommentStyle::DoubleSlash,
343 );
344 assert_eq!(out, "\t// first\n\t//\n\t// second\n");
345 }
346
347 #[test]
348 fn emit_doc_hash_multi_line() {
349 let mut out = String::new();
350 emit_doc(
351 &mut out,
352 &Some("one\n\ntwo".into()),
353 " ",
354 DocCommentStyle::Hash,
355 );
356 assert_eq!(out, " # one\n #\n # two\n");
357 }
358
359 #[test]
360 fn emit_doc_javadoc_single_line_collapses() {
361 let mut out = String::new();
362 emit_doc(
363 &mut out,
364 &Some("short".into()),
365 "",
366 DocCommentStyle::Javadoc,
367 );
368 assert_eq!(out, "/** short */\n");
369 }
370
371 #[test]
372 fn emit_doc_javadoc_multi_line_expands() {
373 let mut out = String::new();
374 emit_doc(
375 &mut out,
376 &Some("line one\n\nline three".into()),
377 " ",
378 DocCommentStyle::Javadoc,
379 );
380 assert_eq!(out, " /**\n * line one\n *\n * line three\n */\n");
381 }
382
383 #[test]
384 fn emit_doc_trims_outer_whitespace_before_decisions() {
385 let mut out = String::new();
390 emit_doc(
391 &mut out,
392 &Some("\n\nhello\n\n".into()),
393 "",
394 DocCommentStyle::Javadoc,
395 );
396 assert_eq!(out, "/** hello */\n");
397 }
398
399 #[test]
402 fn is_c_pointer_for_pointer_carrying_types() {
403 for ty in [
404 TypeRef::StringUtf8,
405 TypeRef::BorrowedStr,
406 TypeRef::Bytes,
407 TypeRef::BorrowedBytes,
408 TypeRef::Struct("X".into()),
409 TypeRef::TypedHandle("X".into()),
410 TypeRef::List(Box::new(TypeRef::I32)),
411 TypeRef::Map(Box::new(TypeRef::StringUtf8), Box::new(TypeRef::I32)),
412 TypeRef::Iterator(Box::new(TypeRef::StringUtf8)),
413 ] {
414 assert!(is_c_pointer_type(&ty), "expected pointer: {ty:?}");
415 }
416 }
417
418 #[test]
419 fn is_c_pointer_for_value_types_is_false() {
420 for ty in [
421 TypeRef::I32,
422 TypeRef::U32,
423 TypeRef::I64,
424 TypeRef::F64,
425 TypeRef::Bool,
426 TypeRef::Handle,
427 TypeRef::Enum("E".into()),
428 ] {
429 assert!(!is_c_pointer_type(&ty), "expected non-pointer: {ty:?}");
430 }
431 }
432
433 #[test]
434 fn is_c_pointer_does_not_recurse_into_optional() {
435 assert!(!is_c_pointer_type(&TypeRef::Optional(Box::new(
439 TypeRef::I32
440 ))));
441 assert!(!is_c_pointer_type(&TypeRef::Optional(Box::new(
442 TypeRef::StringUtf8
443 ))));
444 }
445
446 #[test]
449 fn pascal_case_snake_segments() {
450 assert_eq!(pascal_case("first_name"), "FirstName");
451 assert_eq!(pascal_case("name"), "Name");
452 assert_eq!(pascal_case("is_active"), "IsActive");
453 }
454
455 #[test]
456 fn pascal_case_preserves_interior_casing() {
457 assert_eq!(pascal_case("get_HTTP"), "GetHTTP");
459 assert_eq!(pascal_case("toJSON"), "ToJSON");
460 }
461
462 #[test]
463 fn pascal_case_empty_and_trailing_underscore() {
464 assert_eq!(pascal_case(""), "");
465 assert_eq!(pascal_case("a_"), "A");
466 }
467}