1use ahash::AHashSet;
2use alef_core::ir::{ErrorDef, ErrorVariant};
3
4use crate::conversions::is_tuple_variant;
5
6fn error_variant_wildcard_pattern(rust_path: &str, variant: &ErrorVariant) -> String {
9 if variant.is_unit {
10 format!("{rust_path}::{}", variant.name)
11 } else if is_tuple_variant(&variant.fields) {
12 format!("{rust_path}::{}(..)", variant.name)
13 } else {
14 format!("{rust_path}::{} {{ .. }}", variant.name)
15 }
16}
17
18const PYTHON_BUILTIN_EXCEPTIONS: &[&str] = &[
20 "ConnectionError",
21 "TimeoutError",
22 "PermissionError",
23 "FileNotFoundError",
24 "ValueError",
25 "TypeError",
26 "RuntimeError",
27 "OSError",
28 "IOError",
29 "KeyError",
30 "IndexError",
31 "AttributeError",
32 "ImportError",
33 "MemoryError",
34 "OverflowError",
35 "StopIteration",
36 "RecursionError",
37 "SystemError",
38 "ReferenceError",
39 "BufferError",
40 "EOFError",
41 "LookupError",
42 "ArithmeticError",
43 "AssertionError",
44 "BlockingIOError",
45 "BrokenPipeError",
46 "ChildProcessError",
47 "FileExistsError",
48 "InterruptedError",
49 "IsADirectoryError",
50 "NotADirectoryError",
51 "ProcessLookupError",
52 "UnicodeError",
53];
54
55fn error_base_prefix(error_name: &str) -> &str {
58 error_name.strip_suffix("Error").unwrap_or(error_name)
59}
60
61pub fn python_exception_name(variant_name: &str, error_name: &str) -> String {
67 let candidate = if variant_name.ends_with("Error") {
68 variant_name.to_string()
69 } else {
70 format!("{}Error", variant_name)
71 };
72
73 if PYTHON_BUILTIN_EXCEPTIONS.contains(&candidate.as_str()) {
74 let prefix = error_base_prefix(error_name);
75 if candidate.starts_with(prefix) {
77 candidate
78 } else {
79 format!("{}{}", prefix, candidate)
80 }
81 } else {
82 candidate
83 }
84}
85
86pub fn gen_pyo3_error_types(error: &ErrorDef, module_name: &str, seen_exceptions: &mut AHashSet<String>) -> String {
90 let mut lines = Vec::with_capacity(error.variants.len() + 2);
91 lines.push("// Error types".to_string());
92
93 for variant in &error.variants {
95 let variant_name = python_exception_name(&variant.name, &error.name);
96 if seen_exceptions.insert(variant_name.clone()) {
97 lines.push(format!(
98 "pyo3::create_exception!({module_name}, {}, pyo3::exceptions::PyException);",
99 variant_name
100 ));
101 }
102 }
103
104 if seen_exceptions.insert(error.name.clone()) {
106 lines.push(format!(
107 "pyo3::create_exception!({module_name}, {}, pyo3::exceptions::PyException);",
108 error.name
109 ));
110 }
111
112 lines.join("\n")
113}
114
115pub fn gen_pyo3_error_converter(error: &ErrorDef, core_import: &str) -> String {
118 let rust_path = if error.rust_path.is_empty() {
119 format!("{core_import}::{}", error.name)
120 } else {
121 let normalized = error.rust_path.replace('-', "_");
122 let segments: Vec<&str> = normalized.split("::").collect();
126 if segments.len() > 2 {
127 let crate_name = segments[0];
128 let error_name = segments[segments.len() - 1];
129 format!("{crate_name}::{error_name}")
130 } else {
131 normalized
132 }
133 };
134
135 let fn_name = format!("{}_to_py_err", to_snake_case(&error.name));
136
137 let mut lines = Vec::new();
138 lines.push(format!("/// Convert a `{rust_path}` error to a Python exception."));
139 lines.push(format!("fn {fn_name}(e: {rust_path}) -> pyo3::PyErr {{"));
140 lines.push(" let msg = e.to_string();".to_string());
141 lines.push(" #[allow(unreachable_patterns)]".to_string());
142 lines.push(" match &e {".to_string());
143
144 for variant in &error.variants {
145 let pattern = error_variant_wildcard_pattern(&rust_path, variant);
146 let variant_exc_name = python_exception_name(&variant.name, &error.name);
147 lines.push(format!(" {pattern} => {}::new_err(msg),", variant_exc_name));
148 }
149
150 lines.push(format!(" _ => {}::new_err(msg),", error.name));
152 lines.push(" }".to_string());
153 lines.push("}".to_string());
154 lines.join("\n")
155}
156
157pub fn gen_pyo3_error_registration(error: &ErrorDef, seen_registrations: &mut AHashSet<String>) -> Vec<String> {
161 let mut registrations = Vec::with_capacity(error.variants.len() + 1);
162
163 for variant in &error.variants {
164 let variant_exc_name = python_exception_name(&variant.name, &error.name);
165 if seen_registrations.insert(variant_exc_name.clone()) {
166 registrations.push(format!(
167 " m.add(\"{}\", m.py().get_type::<{}>())?;",
168 variant_exc_name, variant_exc_name
169 ));
170 }
171 }
172
173 if seen_registrations.insert(error.name.clone()) {
175 registrations.push(format!(
176 " m.add(\"{}\", m.py().get_type::<{}>())?;",
177 error.name, error.name
178 ));
179 }
180
181 registrations
182}
183
184pub fn converter_fn_name(error: &ErrorDef) -> String {
186 format!("{}_to_py_err", to_snake_case(&error.name))
187}
188
189fn to_snake_case(s: &str) -> String {
191 let mut result = String::with_capacity(s.len() + 4);
192 for (i, c) in s.chars().enumerate() {
193 if c.is_uppercase() {
194 if i > 0 {
195 result.push('_');
196 }
197 result.push(c.to_ascii_lowercase());
198 } else {
199 result.push(c);
200 }
201 }
202 result
203}
204
205pub fn gen_napi_error_types(error: &ErrorDef) -> String {
211 let mut lines = Vec::with_capacity(error.variants.len() + 4);
212 lines.push("// Error variant name constants".to_string());
213 for variant in &error.variants {
214 lines.push(format!(
215 "pub const {}_ERROR_{}: &str = \"{}\";",
216 to_screaming_snake(&error.name),
217 to_screaming_snake(&variant.name),
218 variant.name,
219 ));
220 }
221 lines.join("\n")
222}
223
224pub fn gen_napi_error_converter(error: &ErrorDef, core_import: &str) -> String {
226 let rust_path = if error.rust_path.is_empty() {
227 format!("{core_import}::{}", error.name)
228 } else {
229 error.rust_path.replace('-', "_")
230 };
231
232 let fn_name = format!("{}_to_napi_err", to_snake_case(&error.name));
233
234 let mut lines = Vec::new();
235 lines.push(format!("/// Convert a `{rust_path}` error to a NAPI error."));
236 lines.push("#[allow(dead_code)]".to_string());
237 lines.push(format!("fn {fn_name}(e: {rust_path}) -> napi::Error {{"));
238 lines.push(" let msg = e.to_string();".to_string());
239 lines.push(" #[allow(unreachable_patterns)]".to_string());
240 lines.push(" match &e {".to_string());
241
242 for variant in &error.variants {
243 let pattern = error_variant_wildcard_pattern(&rust_path, variant);
244 lines.push(format!(
245 " {pattern} => napi::Error::new(napi::Status::GenericFailure, format!(\"[{}] {{}}\", msg)),",
246 variant.name,
247 ));
248 }
249
250 lines.push(" _ => napi::Error::new(napi::Status::GenericFailure, msg),".to_string());
252 lines.push(" }".to_string());
253 lines.push("}".to_string());
254 lines.join("\n")
255}
256
257pub fn napi_converter_fn_name(error: &ErrorDef) -> String {
259 format!("{}_to_napi_err", to_snake_case(&error.name))
260}
261
262pub fn gen_wasm_error_converter(error: &ErrorDef, core_import: &str) -> String {
270 let rust_path = if error.rust_path.is_empty() {
271 format!("{core_import}::{}", error.name)
272 } else {
273 error.rust_path.replace('-', "_")
274 };
275
276 let fn_name = format!("{}_to_js_value", to_snake_case(&error.name));
277 let code_fn_name = format!("{}_error_code", to_snake_case(&error.name));
278
279 let mut lines = Vec::new();
280
281 lines.push(format!("/// Return the error code string for a `{rust_path}` variant."));
283 lines.push("#[allow(dead_code)]".to_string());
284 lines.push(format!("fn {code_fn_name}(e: &{rust_path}) -> &'static str {{"));
285 lines.push(" #[allow(unreachable_patterns)]".to_string());
286 lines.push(" match e {".to_string());
287 for variant in &error.variants {
288 let pattern = error_variant_wildcard_pattern(&rust_path, variant);
289 let code = to_snake_case(&variant.name);
290 lines.push(format!(" {pattern} => \"{code}\","));
291 }
292 lines.push(format!(" _ => \"{}\",", to_snake_case(&error.name)));
293 lines.push(" }".to_string());
294 lines.push("}".to_string());
295
296 lines.push(String::new());
297
298 lines.push(format!(
300 "/// Convert a `{rust_path}` error to a `JsValue` object with `code` and `message` fields."
301 ));
302 lines.push("#[allow(dead_code)]".to_string());
303 lines.push(format!("fn {fn_name}(e: {rust_path}) -> wasm_bindgen::JsValue {{"));
304 lines.push(format!(" let code = {code_fn_name}(&e);"));
305 lines.push(" let message = e.to_string();".to_string());
306 lines.push(" let obj = js_sys::Object::new();".to_string());
307 lines.push(" js_sys::Reflect::set(&obj, &\"code\".into(), &code.into()).ok();".to_string());
308 lines.push(" js_sys::Reflect::set(&obj, &\"message\".into(), &message.into()).ok();".to_string());
309 lines.push(" obj.into()".to_string());
310 lines.push("}".to_string());
311
312 lines.join("\n")
313}
314
315pub fn wasm_converter_fn_name(error: &ErrorDef) -> String {
317 format!("{}_to_js_value", to_snake_case(&error.name))
318}
319
320pub fn gen_php_error_converter(error: &ErrorDef, core_import: &str) -> String {
326 let rust_path = if error.rust_path.is_empty() {
327 format!("{core_import}::{}", error.name)
328 } else {
329 error.rust_path.replace('-', "_")
330 };
331
332 let fn_name = format!("{}_to_php_err", to_snake_case(&error.name));
333
334 let mut lines = Vec::new();
335 lines.push(format!("/// Convert a `{rust_path}` error to a PHP exception."));
336 lines.push("#[allow(dead_code)]".to_string());
337 lines.push(format!(
338 "fn {fn_name}(e: {rust_path}) -> ext_php_rs::exception::PhpException {{"
339 ));
340 lines.push(" let msg = e.to_string();".to_string());
341 lines.push(" #[allow(unreachable_patterns)]".to_string());
342 lines.push(" match &e {".to_string());
343
344 for variant in &error.variants {
345 let pattern = error_variant_wildcard_pattern(&rust_path, variant);
346 lines.push(format!(
347 " {pattern} => ext_php_rs::exception::PhpException::default(format!(\"[{}] {{}}\", msg)),",
348 variant.name,
349 ));
350 }
351
352 lines.push(" _ => ext_php_rs::exception::PhpException::default(msg),".to_string());
354 lines.push(" }".to_string());
355 lines.push("}".to_string());
356 lines.join("\n")
357}
358
359pub fn php_converter_fn_name(error: &ErrorDef) -> String {
361 format!("{}_to_php_err", to_snake_case(&error.name))
362}
363
364pub fn gen_magnus_error_converter(error: &ErrorDef, core_import: &str) -> String {
370 let rust_path = if error.rust_path.is_empty() {
371 format!("{core_import}::{}", error.name)
372 } else {
373 error.rust_path.replace('-', "_")
374 };
375
376 let fn_name = format!("{}_to_magnus_err", to_snake_case(&error.name));
377
378 let mut lines = Vec::new();
379 lines.push(format!("/// Convert a `{rust_path}` error to a Magnus runtime error."));
380 lines.push("#[allow(dead_code)]".to_string());
381 lines.push(format!("fn {fn_name}(e: {rust_path}) -> magnus::Error {{"));
382 lines.push(" let msg = e.to_string();".to_string());
383 lines.push(
384 " magnus::Error::new(unsafe { magnus::Ruby::get_unchecked() }.exception_runtime_error(), msg)".to_string(),
385 );
386 lines.push("}".to_string());
387 lines.join("\n")
388}
389
390pub fn magnus_converter_fn_name(error: &ErrorDef) -> String {
392 format!("{}_to_magnus_err", to_snake_case(&error.name))
393}
394
395pub fn gen_rustler_error_converter(error: &ErrorDef, core_import: &str) -> String {
401 let rust_path = if error.rust_path.is_empty() {
402 format!("{core_import}::{}", error.name)
403 } else {
404 error.rust_path.replace('-', "_")
405 };
406
407 let fn_name = format!("{}_to_rustler_err", to_snake_case(&error.name));
408
409 let mut lines = Vec::new();
410 lines.push(format!("/// Convert a `{rust_path}` error to a Rustler error string."));
411 lines.push("#[allow(dead_code)]".to_string());
412 lines.push(format!("fn {fn_name}(e: {rust_path}) -> String {{"));
413 lines.push(" e.to_string()".to_string());
414 lines.push("}".to_string());
415 lines.join("\n")
416}
417
418pub fn rustler_converter_fn_name(error: &ErrorDef) -> String {
420 format!("{}_to_rustler_err", to_snake_case(&error.name))
421}
422
423pub fn gen_ffi_error_codes(error: &ErrorDef) -> String {
432 let prefix = to_screaming_snake(&error.name);
433 let prefix_lower = to_snake_case(&error.name);
434
435 let mut lines = Vec::new();
436 lines.push(format!("/// Error codes for `{}`.", error.name));
437 lines.push("typedef enum {".to_string());
438 lines.push(format!(" {}_NONE = 0,", prefix));
439
440 for (i, variant) in error.variants.iter().enumerate() {
441 let variant_screaming = to_screaming_snake(&variant.name);
442 lines.push(format!(" {}_{} = {},", prefix, variant_screaming, i + 1));
443 }
444
445 lines.push(format!("}} {}_t;\n", prefix_lower));
446
447 lines.push(format!(
449 "/// Return a static string describing the error code.\nconst char* {}_error_message({}_t code);",
450 prefix_lower, prefix_lower
451 ));
452
453 lines.join("\n")
454}
455
456pub fn gen_go_error_types(error: &ErrorDef, pkg_name: &str) -> String {
467 let mut lines = Vec::new();
468
469 lines.push("var (".to_string());
471 for variant in &error.variants {
472 let err_name = format!("Err{}", variant.name);
473 let msg = variant_display_message(variant);
474 lines.push(format!("\t// {} is returned when {}.", err_name, msg));
476 lines.push(format!("\t{} = errors.New(\"{}\")", err_name, msg));
477 }
478 lines.push(")\n".to_string());
479
480 let go_type_name = strip_package_prefix(&error.name, pkg_name);
483
484 lines.push(format!("// {} is a structured error type.", go_type_name));
486 lines.push(format!("type {} struct {{", go_type_name));
487 lines.push("\tCode string".to_string());
488 lines.push("\tMessage string".to_string());
489 lines.push("}\n".to_string());
490
491 lines.push(format!(
492 "func (e *{}) Error() string {{ return e.Message }}",
493 go_type_name
494 ));
495
496 lines.join("\n")
497}
498
499fn strip_package_prefix(type_name: &str, pkg_name: &str) -> String {
511 let type_lower = type_name.to_lowercase();
512 let pkg_lower = pkg_name.to_lowercase();
513 if type_lower.starts_with(&pkg_lower) && type_lower.len() > pkg_lower.len() {
514 type_name[pkg_lower.len()..].to_string()
516 } else {
517 type_name.to_string()
518 }
519}
520
521pub fn gen_java_error_types(error: &ErrorDef, package: &str) -> Vec<(String, String)> {
531 let mut files = Vec::with_capacity(error.variants.len() + 1);
532
533 let base_name = format!("{}Exception", error.name);
535 let mut base = String::with_capacity(512);
536 base.push_str(&format!(
537 "// DO NOT EDIT - auto-generated by alef\npackage {};\n\n",
538 package
539 ));
540 if !error.doc.is_empty() {
541 let doc = error.doc.trim_end_matches('.');
542 base.push_str(&format!("/** {}. */\n", doc));
543 }
544 base.push_str(&format!("public class {} extends Exception {{\n", base_name));
545 base.push_str(&format!(
546 " /** Creates a new {} with the given message. */\n public {}(final String message) {{\n super(message);\n }}\n\n",
547 base_name, base_name
548 ));
549 base.push_str(&format!(
550 " /** Creates a new {} with the given message and cause. */\n public {}(final String message, final Throwable cause) {{\n super(message, cause);\n }}\n",
551 base_name, base_name
552 ));
553 base.push_str("}\n");
554 files.push((base_name.clone(), base));
555
556 for variant in &error.variants {
558 let class_name = format!("{}Exception", variant.name);
559 let mut content = String::with_capacity(512);
560 content.push_str(&format!(
561 "// DO NOT EDIT - auto-generated by alef\npackage {};\n\n",
562 package
563 ));
564 if !variant.doc.is_empty() {
565 let doc = variant.doc.trim_end_matches('.');
566 content.push_str(&format!("/** {}. */\n", doc));
567 }
568 content.push_str(&format!("public class {} extends {} {{\n", class_name, base_name));
569 content.push_str(&format!(
570 " /** Creates a new {} with the given message. */\n public {}(final String message) {{\n super(message);\n }}\n\n",
571 class_name, class_name
572 ));
573 content.push_str(&format!(
574 " /** Creates a new {} with the given message and cause. */\n public {}(final String message, final Throwable cause) {{\n super(message, cause);\n }}\n",
575 class_name, class_name
576 ));
577 content.push_str("}\n");
578 files.push((class_name, content));
579 }
580
581 files
582}
583
584pub fn gen_csharp_error_types(error: &ErrorDef, namespace: &str) -> Vec<(String, String)> {
594 let mut files = Vec::with_capacity(error.variants.len() + 1);
595
596 let base_name = format!("{}Exception", error.name);
597
598 {
600 let mut out = String::with_capacity(512);
601 out.push_str("// This file is auto-generated by alef. DO NOT EDIT.\nusing System;\n\n");
602 out.push_str(&format!("namespace {};\n\n", namespace));
603 if !error.doc.is_empty() {
604 out.push_str("/// <summary>\n");
605 for line in error.doc.lines() {
606 out.push_str(&format!("/// {}\n", line));
607 }
608 out.push_str("/// </summary>\n");
609 }
610 out.push_str(&format!("public class {} : Exception\n{{\n", base_name));
611 out.push_str(&format!(
612 " public {}(string message) : base(message) {{ }}\n\n",
613 base_name
614 ));
615 out.push_str(&format!(
616 " public {}(string message, Exception innerException) : base(message, innerException) {{ }}\n",
617 base_name
618 ));
619 out.push_str("}\n");
620 files.push((base_name.clone(), out));
621 }
622
623 for variant in &error.variants {
625 let class_name = format!("{}Exception", variant.name);
626 let mut out = String::with_capacity(512);
627 out.push_str("// This file is auto-generated by alef. DO NOT EDIT.\nusing System;\n\n");
628 out.push_str(&format!("namespace {};\n\n", namespace));
629 if !variant.doc.is_empty() {
630 out.push_str("/// <summary>\n");
631 for line in variant.doc.lines() {
632 out.push_str(&format!("/// {}\n", line));
633 }
634 out.push_str("/// </summary>\n");
635 }
636 out.push_str(&format!("public class {} : {}\n{{\n", class_name, base_name));
637 out.push_str(&format!(
638 " public {}(string message) : base(message) {{ }}\n\n",
639 class_name
640 ));
641 out.push_str(&format!(
642 " public {}(string message, Exception innerException) : base(message, innerException) {{ }}\n",
643 class_name
644 ));
645 out.push_str("}\n");
646 files.push((class_name, out));
647 }
648
649 files
650}
651
652fn to_screaming_snake(s: &str) -> String {
658 let mut result = String::with_capacity(s.len() + 4);
659 for (i, c) in s.chars().enumerate() {
660 if c.is_uppercase() {
661 if i > 0 {
662 result.push('_');
663 }
664 result.push(c.to_ascii_uppercase());
665 } else {
666 result.push(c.to_ascii_uppercase());
667 }
668 }
669 result
670}
671
672fn variant_display_message(variant: &ErrorVariant) -> String {
677 if let Some(tmpl) = &variant.message_template {
678 let msg = tmpl
680 .replace("{0}", "")
681 .replace("{source}", "")
682 .trim_end_matches(": ")
683 .trim()
684 .to_string();
685 if msg.is_empty() {
686 to_snake_case(&variant.name).replace('_', " ")
687 } else {
688 msg
689 }
690 } else {
691 to_snake_case(&variant.name).replace('_', " ")
692 }
693}
694
695#[cfg(test)]
696mod tests {
697 use super::*;
698 use alef_core::ir::{ErrorDef, ErrorVariant};
699
700 use alef_core::ir::{CoreWrapper, FieldDef, TypeRef};
701
702 fn tuple_field(index: usize) -> FieldDef {
704 FieldDef {
705 name: format!("_{index}"),
706 ty: TypeRef::String,
707 optional: false,
708 default: None,
709 doc: String::new(),
710 sanitized: false,
711 is_boxed: false,
712 type_rust_path: None,
713 cfg: None,
714 typed_default: None,
715 core_wrapper: CoreWrapper::None,
716 vec_inner_core_wrapper: CoreWrapper::None,
717 newtype_wrapper: None,
718 }
719 }
720
721 fn named_field(name: &str) -> FieldDef {
723 FieldDef {
724 name: name.to_string(),
725 ty: TypeRef::String,
726 optional: false,
727 default: None,
728 doc: String::new(),
729 sanitized: false,
730 is_boxed: false,
731 type_rust_path: None,
732 cfg: None,
733 typed_default: None,
734 core_wrapper: CoreWrapper::None,
735 vec_inner_core_wrapper: CoreWrapper::None,
736 newtype_wrapper: None,
737 }
738 }
739
740 fn sample_error() -> ErrorDef {
741 ErrorDef {
742 name: "ConversionError".to_string(),
743 rust_path: "html_to_markdown_rs::ConversionError".to_string(),
744 original_rust_path: String::new(),
745 variants: vec![
746 ErrorVariant {
747 name: "ParseError".to_string(),
748 message_template: Some("HTML parsing error: {0}".to_string()),
749 fields: vec![tuple_field(0)],
750 has_source: false,
751 has_from: false,
752 is_unit: false,
753 doc: String::new(),
754 },
755 ErrorVariant {
756 name: "IoError".to_string(),
757 message_template: Some("I/O error: {0}".to_string()),
758 fields: vec![tuple_field(0)],
759 has_source: false,
760 has_from: true,
761 is_unit: false,
762 doc: String::new(),
763 },
764 ErrorVariant {
765 name: "Other".to_string(),
766 message_template: Some("Conversion error: {0}".to_string()),
767 fields: vec![tuple_field(0)],
768 has_source: false,
769 has_from: false,
770 is_unit: false,
771 doc: String::new(),
772 },
773 ],
774 doc: "Error type for conversion operations.".to_string(),
775 }
776 }
777
778 #[test]
779 fn test_gen_error_types() {
780 let error = sample_error();
781 let output = gen_pyo3_error_types(&error, "_module", &mut AHashSet::new());
782 assert!(output.contains("pyo3::create_exception!(_module, ParseError, pyo3::exceptions::PyException);"));
783 assert!(output.contains("pyo3::create_exception!(_module, IoError, pyo3::exceptions::PyException);"));
784 assert!(output.contains("pyo3::create_exception!(_module, OtherError, pyo3::exceptions::PyException);"));
785 assert!(output.contains("pyo3::create_exception!(_module, ConversionError, pyo3::exceptions::PyException);"));
786 }
787
788 #[test]
789 fn test_gen_error_converter() {
790 let error = sample_error();
791 let output = gen_pyo3_error_converter(&error, "html_to_markdown_rs");
792 assert!(
793 output.contains("fn conversion_error_to_py_err(e: html_to_markdown_rs::ConversionError) -> pyo3::PyErr {")
794 );
795 assert!(output.contains("html_to_markdown_rs::ConversionError::ParseError(..) => ParseError::new_err(msg),"));
796 assert!(output.contains("html_to_markdown_rs::ConversionError::IoError(..) => IoError::new_err(msg),"));
797 }
798
799 #[test]
800 fn test_gen_error_registration() {
801 let error = sample_error();
802 let regs = gen_pyo3_error_registration(&error, &mut AHashSet::new());
803 assert_eq!(regs.len(), 4); assert!(regs[0].contains("\"ParseError\""));
805 assert!(regs[3].contains("\"ConversionError\""));
806 }
807
808 #[test]
809 fn test_unit_variant_pattern() {
810 let error = ErrorDef {
811 name: "MyError".to_string(),
812 rust_path: "my_crate::MyError".to_string(),
813 original_rust_path: String::new(),
814 variants: vec![ErrorVariant {
815 name: "NotFound".to_string(),
816 message_template: Some("not found".to_string()),
817 fields: vec![],
818 has_source: false,
819 has_from: false,
820 is_unit: true,
821 doc: String::new(),
822 }],
823 doc: String::new(),
824 };
825 let output = gen_pyo3_error_converter(&error, "my_crate");
826 assert!(output.contains("my_crate::MyError::NotFound => NotFoundError::new_err(msg),"));
827 assert!(!output.contains("NotFound(..)"));
829 }
830
831 #[test]
832 fn test_struct_variant_pattern() {
833 let error = ErrorDef {
834 name: "MyError".to_string(),
835 rust_path: "my_crate::MyError".to_string(),
836 original_rust_path: String::new(),
837 variants: vec![ErrorVariant {
838 name: "Parsing".to_string(),
839 message_template: Some("parsing error: {message}".to_string()),
840 fields: vec![named_field("message")],
841 has_source: false,
842 has_from: false,
843 is_unit: false,
844 doc: String::new(),
845 }],
846 doc: String::new(),
847 };
848 let output = gen_pyo3_error_converter(&error, "my_crate");
849 assert!(
850 output.contains("my_crate::MyError::Parsing { .. } => ParsingError::new_err(msg),"),
851 "Struct variants must use {{ .. }} pattern, got:\n{output}"
852 );
853 assert!(!output.contains("Parsing(..)"));
855 }
856
857 #[test]
862 fn test_gen_napi_error_types() {
863 let error = sample_error();
864 let output = gen_napi_error_types(&error);
865 assert!(output.contains("CONVERSION_ERROR_ERROR_PARSE_ERROR"));
866 assert!(output.contains("CONVERSION_ERROR_ERROR_IO_ERROR"));
867 assert!(output.contains("CONVERSION_ERROR_ERROR_OTHER"));
868 }
869
870 #[test]
871 fn test_gen_napi_error_converter() {
872 let error = sample_error();
873 let output = gen_napi_error_converter(&error, "html_to_markdown_rs");
874 assert!(
875 output
876 .contains("fn conversion_error_to_napi_err(e: html_to_markdown_rs::ConversionError) -> napi::Error {")
877 );
878 assert!(output.contains("napi::Error::new(napi::Status::GenericFailure,"));
879 assert!(output.contains("[ParseError]"));
880 assert!(output.contains("[IoError]"));
881 assert!(output.contains("#[allow(dead_code)]"));
882 }
883
884 #[test]
885 fn test_napi_unit_variant() {
886 let error = ErrorDef {
887 name: "MyError".to_string(),
888 rust_path: "my_crate::MyError".to_string(),
889 original_rust_path: String::new(),
890 variants: vec![ErrorVariant {
891 name: "NotFound".to_string(),
892 message_template: None,
893 fields: vec![],
894 has_source: false,
895 has_from: false,
896 is_unit: true,
897 doc: String::new(),
898 }],
899 doc: String::new(),
900 };
901 let output = gen_napi_error_converter(&error, "my_crate");
902 assert!(output.contains("my_crate::MyError::NotFound =>"));
903 assert!(!output.contains("NotFound(..)"));
904 }
905
906 #[test]
911 fn test_gen_wasm_error_converter() {
912 let error = sample_error();
913 let output = gen_wasm_error_converter(&error, "html_to_markdown_rs");
914 assert!(output.contains(
916 "fn conversion_error_to_js_value(e: html_to_markdown_rs::ConversionError) -> wasm_bindgen::JsValue {"
917 ));
918 assert!(output.contains("js_sys::Object::new()"));
920 assert!(output.contains("js_sys::Reflect::set(&obj, &\"code\".into(), &code.into()).ok()"));
921 assert!(output.contains("js_sys::Reflect::set(&obj, &\"message\".into(), &message.into()).ok()"));
922 assert!(output.contains("obj.into()"));
923 assert!(
925 output
926 .contains("fn conversion_error_error_code(e: &html_to_markdown_rs::ConversionError) -> &'static str {")
927 );
928 assert!(output.contains("\"parse_error\""));
929 assert!(output.contains("\"io_error\""));
930 assert!(output.contains("\"other\""));
931 assert!(output.contains("#[allow(dead_code)]"));
932 }
933
934 #[test]
939 fn test_gen_php_error_converter() {
940 let error = sample_error();
941 let output = gen_php_error_converter(&error, "html_to_markdown_rs");
942 assert!(output.contains("fn conversion_error_to_php_err(e: html_to_markdown_rs::ConversionError) -> ext_php_rs::exception::PhpException {"));
943 assert!(output.contains("PhpException::default(format!(\"[ParseError] {}\", msg))"));
944 assert!(output.contains("#[allow(dead_code)]"));
945 }
946
947 #[test]
952 fn test_gen_magnus_error_converter() {
953 let error = sample_error();
954 let output = gen_magnus_error_converter(&error, "html_to_markdown_rs");
955 assert!(
956 output.contains(
957 "fn conversion_error_to_magnus_err(e: html_to_markdown_rs::ConversionError) -> magnus::Error {"
958 )
959 );
960 assert!(
961 output.contains(
962 "magnus::Error::new(unsafe { magnus::Ruby::get_unchecked() }.exception_runtime_error(), msg)"
963 )
964 );
965 assert!(output.contains("#[allow(dead_code)]"));
966 }
967
968 #[test]
973 fn test_gen_rustler_error_converter() {
974 let error = sample_error();
975 let output = gen_rustler_error_converter(&error, "html_to_markdown_rs");
976 assert!(
977 output.contains("fn conversion_error_to_rustler_err(e: html_to_markdown_rs::ConversionError) -> String {")
978 );
979 assert!(output.contains("e.to_string()"));
980 assert!(output.contains("#[allow(dead_code)]"));
981 }
982
983 #[test]
988 fn test_to_screaming_snake() {
989 assert_eq!(to_screaming_snake("ConversionError"), "CONVERSION_ERROR");
990 assert_eq!(to_screaming_snake("IoError"), "IO_ERROR");
991 assert_eq!(to_screaming_snake("Other"), "OTHER");
992 }
993
994 #[test]
999 fn test_gen_ffi_error_codes() {
1000 let error = sample_error();
1001 let output = gen_ffi_error_codes(&error);
1002 assert!(output.contains("CONVERSION_ERROR_NONE = 0"));
1003 assert!(output.contains("CONVERSION_ERROR_PARSE_ERROR = 1"));
1004 assert!(output.contains("CONVERSION_ERROR_IO_ERROR = 2"));
1005 assert!(output.contains("CONVERSION_ERROR_OTHER = 3"));
1006 assert!(output.contains("conversion_error_t;"));
1007 assert!(output.contains("conversion_error_error_message(conversion_error_t code)"));
1008 }
1009
1010 #[test]
1015 fn test_gen_go_error_types() {
1016 let error = sample_error();
1017 let output = gen_go_error_types(&error, "mylib");
1019 assert!(output.contains("ErrParseError = errors.New("));
1020 assert!(output.contains("ErrIoError = errors.New("));
1021 assert!(output.contains("ErrOther = errors.New("));
1022 assert!(output.contains("type ConversionError struct {"));
1023 assert!(output.contains("Code string"));
1024 assert!(output.contains("func (e *ConversionError) Error() string"));
1025 assert!(output.contains("// ErrParseError is returned when"));
1027 assert!(output.contains("// ErrIoError is returned when"));
1028 assert!(output.contains("// ErrOther is returned when"));
1029 }
1030
1031 #[test]
1032 fn test_gen_go_error_types_stutter_strip() {
1033 let error = sample_error();
1034 let output = gen_go_error_types(&error, "conversion");
1037 assert!(
1038 output.contains("type Error struct {"),
1039 "expected stutter strip, got:\n{output}"
1040 );
1041 assert!(
1042 output.contains("func (e *Error) Error() string"),
1043 "expected stutter strip, got:\n{output}"
1044 );
1045 assert!(output.contains("ErrParseError = errors.New("));
1047 }
1048
1049 #[test]
1054 fn test_gen_java_error_types() {
1055 let error = sample_error();
1056 let files = gen_java_error_types(&error, "dev.kreuzberg.test");
1057 assert_eq!(files.len(), 4);
1059 assert_eq!(files[0].0, "ConversionErrorException");
1061 assert!(
1062 files[0]
1063 .1
1064 .contains("public class ConversionErrorException extends Exception")
1065 );
1066 assert!(files[0].1.contains("package dev.kreuzberg.test;"));
1067 assert_eq!(files[1].0, "ParseErrorException");
1069 assert!(
1070 files[1]
1071 .1
1072 .contains("public class ParseErrorException extends ConversionErrorException")
1073 );
1074 assert_eq!(files[2].0, "IoErrorException");
1075 assert_eq!(files[3].0, "OtherException");
1076 }
1077
1078 #[test]
1083 fn test_gen_csharp_error_types() {
1084 let error = sample_error();
1085 let files = gen_csharp_error_types(&error, "Kreuzberg.Test");
1086 assert_eq!(files.len(), 4);
1088 assert_eq!(files[0].0, "ConversionErrorException");
1090 assert!(files[0].1.contains("public class ConversionErrorException : Exception"));
1091 assert!(files[0].1.contains("namespace Kreuzberg.Test;"));
1092 assert_eq!(files[1].0, "ParseErrorException");
1094 assert!(
1095 files[1]
1096 .1
1097 .contains("public class ParseErrorException : ConversionErrorException")
1098 );
1099 assert_eq!(files[2].0, "IoErrorException");
1100 assert_eq!(files[3].0, "OtherException");
1101 }
1102
1103 #[test]
1108 fn test_python_exception_name_no_conflict() {
1109 assert_eq!(python_exception_name("ParseError", "ConversionError"), "ParseError");
1111 assert_eq!(python_exception_name("Other", "ConversionError"), "OtherError");
1113 }
1114
1115 #[test]
1116 fn test_python_exception_name_shadows_builtin() {
1117 assert_eq!(
1119 python_exception_name("Connection", "CrawlError"),
1120 "CrawlConnectionError"
1121 );
1122 assert_eq!(python_exception_name("Timeout", "CrawlError"), "CrawlTimeoutError");
1124 assert_eq!(
1126 python_exception_name("ConnectionError", "CrawlError"),
1127 "CrawlConnectionError"
1128 );
1129 }
1130
1131 #[test]
1132 fn test_python_exception_name_no_double_prefix() {
1133 assert_eq!(
1135 python_exception_name("CrawlConnectionError", "CrawlError"),
1136 "CrawlConnectionError"
1137 );
1138 }
1139}