polyxml 0.39.2__tar.gz → 0.40.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. {polyxml-0.39.2 → polyxml-0.40.0}/Cargo.lock +6 -6
  2. {polyxml-0.39.2 → polyxml-0.40.0}/Cargo.toml +1 -1
  3. {polyxml-0.39.2 → polyxml-0.40.0}/PKG-INFO +1 -1
  4. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/cpp/mod.rs +10 -4
  5. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/csharp/mod.rs +51 -5
  6. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/go/mod.rs +65 -13
  7. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/java/codec.rs +101 -7
  8. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/java/mod.rs +81 -12
  9. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/mod.rs +92 -0
  10. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/python/aot.rs +2 -1
  11. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/python/mod.rs +46 -13
  12. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/rust/mod.rs +317 -15
  13. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/typescript/mod.rs +59 -11
  14. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/json.rs +107 -55
  15. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/parser.rs +4 -0
  16. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/schema_parser/mod.rs +4 -16
  17. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_core.rs +36 -0
  18. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_cpp_codegen.rs +31 -0
  19. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_csharp_codegen.rs +48 -0
  20. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_go_codegen.rs +43 -0
  21. polyxml-0.40.0/crates/polyxml-core/tests/test_issue_162.rs +56 -0
  22. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_java_codegen.rs +115 -0
  23. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_python_codegen.rs +28 -0
  24. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_rust_codegen.rs +153 -0
  25. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_transcoder.rs +117 -0
  26. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_ts_codegen.rs +40 -0
  27. {polyxml-0.39.2 → polyxml-0.40.0}/pyproject.toml +1 -1
  28. {polyxml-0.39.2 → polyxml-0.40.0}/README.md +0 -0
  29. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/Cargo.toml +0 -0
  30. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/README.md +0 -0
  31. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/benches/core_benchmarks.rs +0 -0
  32. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/benches/support/tag_dispatch_fixtures.rs +0 -0
  33. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/benches/tag_dispatch.rs +0 -0
  34. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/java/models.rs +0 -0
  35. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/converters.rs +0 -0
  36. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/error.rs +0 -0
  37. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/integer.rs +0 -0
  38. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/ir/chunker.rs +0 -0
  39. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/ir/mod.rs +0 -0
  40. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/ir/particle.rs +0 -0
  41. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/ir/tarjan.rs +0 -0
  42. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/lib.rs +0 -0
  43. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/pattern.rs +0 -0
  44. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/schema.rs +0 -0
  45. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/schema_parser/upa.rs +0 -0
  46. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/serializer.rs +0 -0
  47. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/transcoder.rs +0 -0
  48. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/src/value.rs +0 -0
  49. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/fixtures/lexical_union.xsd +0 -0
  50. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/fixtures/mixed_content.xsd +0 -0
  51. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/fixtures/ts_mixed_content_inheritance.xsd +0 -0
  52. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_adversarial_identifiers.rs +0 -0
  53. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_any_attribute.rs +0 -0
  54. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_any_element.rs +0 -0
  55. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_conformance.rs +0 -0
  56. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_corpus_regressions.rs +0 -0
  57. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_default_literal_codegen.rs +0 -0
  58. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_enum_literal_codegen.rs +0 -0
  59. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_inherited_simple_content.rs +0 -0
  60. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_inherited_text_codegen.rs +0 -0
  61. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_json.rs +0 -0
  62. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_lexical_lists.rs +0 -0
  63. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_lexical_union_codegen.rs +0 -0
  64. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_mixed_branch_lookup.rs +0 -0
  65. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_mixed_content.rs +0 -0
  66. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_mixed_nil.rs +0 -0
  67. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_namespace_entities.rs +0 -0
  68. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_pattern_codegen.rs +0 -0
  69. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_qualified_attributes.rs +0 -0
  70. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_runtime_fast_paths.rs +0 -0
  71. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_rust_codecs.rs +0 -0
  72. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_schema_attribute_entities.rs +0 -0
  73. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_schema_audit.rs +0 -0
  74. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_schema_ir.rs +0 -0
  75. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_security.rs +0 -0
  76. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_temporal_union.rs +0 -0
  77. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_ubl_csharp.rs +0 -0
  78. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_unbounded_choice.rs +0 -0
  79. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_upa.rs +0 -0
  80. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_value_constraints.rs +0 -0
  81. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_variant_registry.rs +0 -0
  82. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-core/tests/test_xsi_type.rs +0 -0
  83. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-python/Cargo.toml +0 -0
  84. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-python/README.md +0 -0
  85. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-python/benches/aot_vs_dataclass.py +0 -0
  86. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-python/src/lib.rs +0 -0
  87. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-python/tests/test_binary_fields.py +0 -0
  88. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-python/tests/test_conformance.py +0 -0
  89. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-python/tests/test_generated_models.py +0 -0
  90. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-python/tests/test_json.py +0 -0
  91. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-python/tests/test_mixed_content.py +0 -0
  92. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-python/tests/test_polyxml.py +0 -0
  93. {polyxml-0.39.2 → polyxml-0.40.0}/crates/polyxml-python/tests/test_xsi_type.py +0 -0
  94. {polyxml-0.39.2 → polyxml-0.40.0}/python/polyxml/AGENT_GUIDE.md +0 -0
  95. {polyxml-0.39.2 → polyxml-0.40.0}/python/polyxml/__init__.py +0 -0
  96. {polyxml-0.39.2 → polyxml-0.40.0}/python/polyxml/compat/__init__.py +0 -0
  97. {polyxml-0.39.2 → polyxml-0.40.0}/python/polyxml/compat/xsdata.py +0 -0
  98. {polyxml-0.39.2 → polyxml-0.40.0}/python/polyxml/py.typed +0 -0
@@ -610,7 +610,7 @@ dependencies = [
610
610
 
611
611
  [[package]]
612
612
  name = "polyxml"
613
- version = "0.39.2"
613
+ version = "0.40.0"
614
614
  dependencies = [
615
615
  "criterion",
616
616
  "heck",
@@ -631,14 +631,14 @@ dependencies = [
631
631
 
632
632
  [[package]]
633
633
  name = "polyxml-c"
634
- version = "0.39.2"
634
+ version = "0.40.0"
635
635
  dependencies = [
636
636
  "polyxml",
637
637
  ]
638
638
 
639
639
  [[package]]
640
640
  name = "polyxml-cli"
641
- version = "0.39.2"
641
+ version = "0.40.0"
642
642
  dependencies = [
643
643
  "clap",
644
644
  "glob",
@@ -652,7 +652,7 @@ dependencies = [
652
652
 
653
653
  [[package]]
654
654
  name = "polyxml-js"
655
- version = "0.39.2"
655
+ version = "0.40.0"
656
656
  dependencies = [
657
657
  "napi",
658
658
  "napi-build",
@@ -662,7 +662,7 @@ dependencies = [
662
662
 
663
663
  [[package]]
664
664
  name = "polyxml-python"
665
- version = "0.39.2"
665
+ version = "0.40.0"
666
666
  dependencies = [
667
667
  "base64",
668
668
  "hex",
@@ -674,7 +674,7 @@ dependencies = [
674
674
 
675
675
  [[package]]
676
676
  name = "polyxml-wasm"
677
- version = "0.39.2"
677
+ version = "0.40.0"
678
678
  dependencies = [
679
679
  "polyxml",
680
680
  "quick-xml",
@@ -3,7 +3,7 @@ resolver = "2"
3
3
  members = ["crates/polyxml-core", "crates/polyxml-python"]
4
4
 
5
5
  [workspace.package]
6
- version = "0.39.2"
6
+ version = "0.40.0"
7
7
  edition = "2021"
8
8
  rust-version = "1.80"
9
9
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: polyxml
3
- Version: 0.39.2
3
+ Version: 0.40.0
4
4
  Classifier: Development Status :: 4 - Beta
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: License :: OSI Approved :: MIT License
@@ -408,11 +408,13 @@ impl CppCodegen {
408
408
  CppMode::HeaderOnly => {
409
409
  files.push((format!("{}.hpp", stem), self.generate_header(ir)));
410
410
  if let Some(chunk_size) = self.split_units {
411
- let plan = ir.partition_topological_chunks(chunk_size);
411
+ let mut prepared = ir.clone();
412
+ self.order_with_forward_cuts(&mut prepared);
413
+ let plan = prepared.partition_topological_chunks(chunk_size);
412
414
  for chunk in &plan.chunks {
413
415
  files.push((
414
416
  format!("{}_{}.cpp", stem, chunk.name),
415
- self.generate_chunk_impl(ir, stem, &chunk.types),
417
+ self.generate_chunk_impl(&prepared, stem, &chunk.types),
416
418
  ));
417
419
  }
418
420
  }
@@ -448,8 +450,9 @@ impl CppCodegen {
448
450
  "// @generated by PolyXML Compiler (https://github.com/polyxml/PolyXML)"
449
451
  )
450
452
  .unwrap();
453
+ let ns = to_cpp_namespace(&self.options.namespace);
451
454
  writeln!(out, "#include \"{}.hpp\"\n", header_stem).unwrap();
452
- writeln!(out, "namespace {} {{\n", self.options.namespace).unwrap();
455
+ writeln!(out, "namespace {} {{\n", ns).unwrap();
453
456
 
454
457
  for qname in types {
455
458
  let Some(type_def) = ir.types.get(qname) else {
@@ -592,7 +595,7 @@ impl CppCodegen {
592
595
  }
593
596
  }
594
597
 
595
- writeln!(out, "\n}} // namespace {}", self.options.namespace).unwrap();
598
+ writeln!(out, "\n}} // namespace {}", ns).unwrap();
596
599
  out
597
600
  }
598
601
 
@@ -1295,6 +1298,9 @@ inline int polyxml_integer_compare(std::string_view a,std::string_view b) noexce
1295
1298
  | TypeRef::Primitive(PrimitiveType::NormalizedString) => {
1296
1299
  format!(" = {}", super::cpp_string_literal(v))
1297
1300
  }
1301
+ TypeRef::Primitive(_) if base_type == "std::string" => {
1302
+ format!(" = {}", super::cpp_string_literal(v))
1303
+ }
1298
1304
  TypeRef::Primitive(_) => format!(" = {}", v),
1299
1305
  TypeRef::Named(ref q) => {
1300
1306
  if let Some(TypeDef::Enum(enum_def)) = ir.types.get(q) {
@@ -997,7 +997,10 @@ impl CSharpCodegen {
997
997
  .patterns
998
998
  .iter()
999
999
  .map(|pattern| {
1000
- format!("Regex.IsMatch(value, {:?})", format!(r"\A(?:{pattern})\z"))
1000
+ let lit = crate::codegen::format_c_style_string_literal(&format!(
1001
+ r"\A(?:{pattern})\z"
1002
+ ));
1003
+ format!("Regex.IsMatch(value, {lit})")
1001
1004
  })
1002
1005
  .collect::<Vec<_>>()
1003
1006
  .join(" && ");
@@ -1524,6 +1527,18 @@ impl CSharpCodegen {
1524
1527
  }
1525
1528
 
1526
1529
  fn emit_struct(&self, out: &mut String, s: &StructDef, ir: &SchemaIR, indent: &str) {
1530
+ if self.options.use_records
1531
+ && self.options.record_kind == CSharpRecordKind::Struct
1532
+ && s.base_type
1533
+ .as_ref()
1534
+ .is_some_and(|b| matches!(ir.types.get(b), Some(TypeDef::Struct(_))))
1535
+ {
1536
+ let mut flat = s.clone();
1537
+ flat.fields = super::flatten_fields(s, ir).into_iter().cloned().collect();
1538
+ flat.base_type = None;
1539
+ self.emit_struct(out, &flat, ir, indent);
1540
+ return;
1541
+ }
1527
1542
  if ir.has_ordered_content(s) && s.base_type.is_some() {
1528
1543
  let fields = super::flatten_fields(s, ir);
1529
1544
  if fields.iter().any(|f| {
@@ -2045,7 +2060,8 @@ impl CSharpCodegen {
2045
2060
  indent: &str,
2046
2061
  ) {
2047
2062
  for pattern in &facets.patterns {
2048
- writeln!(out,"{indent}if(!System.Text.RegularExpressions.Regex.IsMatch({target},{:?})) yield return new System.ComponentModel.DataAnnotations.ValidationResult(\"Integer pattern violated\");",format!(r"\A(?:{pattern})\z")).unwrap();
2063
+ let lit = crate::codegen::format_c_style_string_literal(&format!(r"\A(?:{pattern})\z"));
2064
+ writeln!(out,"{indent}if(!System.Text.RegularExpressions.Regex.IsMatch({target},{lit})) yield return new System.ComponentModel.DataAnnotations.ValidationResult(\"Integer pattern violated\");").unwrap();
2049
2065
  }
2050
2066
  for (bound, op) in [
2051
2067
  (&facets.min_inclusive, "<"),
@@ -2086,7 +2102,10 @@ impl CSharpCodegen {
2086
2102
  for pattern in &facets.patterns {
2087
2103
  let escaped = format!(r"\A(?:{pattern})\z")
2088
2104
  .replace('\\', "\\\\")
2089
- .replace('"', "\\\"");
2105
+ .replace('"', "\\\"")
2106
+ .replace('\r', "\\r")
2107
+ .replace('\n', "\\n")
2108
+ .replace('\t', "\\t");
2090
2109
  writeln!(
2091
2110
  out,
2092
2111
  "{}if (!Regex.IsMatch({}.ToString() ?? \"\", \"{}\")) yield return new ValidationResult(\"{} does not match pattern {}\", [nameof({})]);",
@@ -2297,10 +2316,14 @@ impl CSharpCodegen {
2297
2316
  continue;
2298
2317
  }
2299
2318
  }
2319
+ let target_is_struct_record = self.options.use_records
2320
+ && self.options.record_kind == CSharpRecordKind::Struct
2321
+ && matches!(&elem.type_ref, TypeRef::Named(q) if matches!(ir.types.get(q), Some(TypeDef::Struct(_))));
2300
2322
  if self.options.use_records
2301
- && !matches!(&elem.type_ref, TypeRef::Named(q) if matches!(ir.types.get(q), Some(TypeDef::Struct(_) | TypeDef::Simple(_) | TypeDef::Union(_))))
2323
+ && (target_is_struct_record
2324
+ || !matches!(&elem.type_ref, TypeRef::Named(q) if matches!(ir.types.get(q), Some(TypeDef::Struct(_) | TypeDef::Simple(_) | TypeDef::Union(_)))))
2302
2325
  {
2303
- let xml_attr = if self.options.emit_xml_attributes {
2326
+ let xml_attr = if self.options.emit_xml_attributes && !target_is_struct_record {
2304
2327
  "[property: XmlText] "
2305
2328
  } else {
2306
2329
  ""
@@ -2336,3 +2359,26 @@ impl CSharpCodegen {
2336
2359
  writeln!(out, "{}/// </summary>", indent).unwrap();
2337
2360
  }
2338
2361
  }
2362
+
2363
+ #[cfg(test)]
2364
+ mod tests {
2365
+ use super::{CSharpCodegen, CSharpOptions};
2366
+ use crate::schema_parser::XsdParser;
2367
+
2368
+ #[test]
2369
+ fn pattern_facet_escapes_control_characters_in_csharp_strings() {
2370
+ let xsd = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
2371
+ <xs:simpleType name="QueryStringType">
2372
+ <xs:restriction base="xs:string">
2373
+ <xs:pattern value="(.|&#xA;|&#xD;|&#x9;){0,4096}"/>
2374
+ </xs:restriction>
2375
+ </xs:simpleType>
2376
+ </xs:schema>"#;
2377
+ let ir = XsdParser::new().parse_str(xsd).unwrap();
2378
+ let code = CSharpCodegen::new(CSharpOptions::default()).generate_module(&ir);
2379
+ assert!(
2380
+ code.contains(r#"\\A(?:(.|\n|\r|\t){0,4096})\\z"#),
2381
+ "expected escaped \\n, \\r, \\t in C# pattern literal, got:\n{code}"
2382
+ );
2383
+ }
2384
+ }
@@ -473,33 +473,33 @@ impl GoCodegen {
473
473
  imports.push(format!("polyxmlutils \"{utils_import}\""));
474
474
  }
475
475
  }
476
- if body.contains("big.") {
476
+ if go_code_uses_pkg(&body, "big.") {
477
477
  imports.push("\"math/big\"".to_string());
478
478
  }
479
- if body.contains("xml.") {
479
+ if go_code_uses_pkg(&body, "xml.") {
480
480
  imports.push("\"encoding/xml\"".to_string());
481
481
  }
482
- if body.contains("bytes.") {
482
+ if go_code_uses_pkg(&body, "bytes.") {
483
483
  imports.push("\"bytes\"".to_string());
484
484
  }
485
- if has_fmt || body.contains("fmt.") {
485
+ if has_fmt || go_code_uses_pkg(&body, "fmt.") {
486
486
  imports.push("\"fmt\"".to_string());
487
487
  }
488
- if has_io || body.contains("io.") {
488
+ if has_io || go_code_uses_pkg(&body, "io.") {
489
489
  imports.push("\"io\"".to_string());
490
490
  }
491
- if has_patterns || body.contains("regexp.") {
491
+ if has_patterns || go_code_uses_pkg(&body, "regexp.") {
492
492
  imports.push("\"regexp\"".to_string());
493
493
  }
494
494
  if ir
495
495
  .types
496
496
  .values()
497
497
  .any(|def| matches!(def, TypeDef::Union(u) if u.is_lexical()))
498
- && body.contains("strconv.")
498
+ && go_code_uses_pkg(&body, "strconv.")
499
499
  {
500
500
  imports.push("\"strconv\"".to_string());
501
501
  }
502
- if body.contains("strings.") {
502
+ if go_code_uses_pkg(&body, "strings.") {
503
503
  imports.push("\"strings\"".to_string());
504
504
  }
505
505
  if has_time && self.shared_utils_import.is_none() {
@@ -670,7 +670,9 @@ func (v {type_name}) MarshalText() ([]byte,error) {{ tokens:=make([]string,0,len
670
670
  if self.options.validate_facets && !simple.facets.patterns.is_empty() {
671
671
  writeln!(out, "func (s {}) Validate() error {{", type_name).unwrap();
672
672
  for pattern in &simple.facets.patterns {
673
- writeln!(out, " if matched, err := regexp.MatchString({:?}, fmt.Sprint(s)); err != nil || !matched {{ return fmt.Errorf(\"pattern constraint failed\") }}", format!("^(?:{pattern})$")).unwrap();
673
+ let lit =
674
+ crate::codegen::format_c_style_string_literal(&format!("^(?:{pattern})$"));
675
+ writeln!(out, " if matched, err := regexp.MatchString({}, fmt.Sprint(s)); err != nil || !matched {{ return fmt.Errorf(\"pattern constraint failed\") }}", lit).unwrap();
674
676
  }
675
677
  writeln!(out, " return nil\n}}\n").unwrap();
676
678
  if self
@@ -1889,7 +1891,8 @@ func (v {name}) MarshalXML(e *xml.Encoder,start xml.StartElement) error {{
1889
1891
  indent: &str,
1890
1892
  ) {
1891
1893
  for pattern in &facets.patterns {
1892
- writeln!(out,"{indent}if matched,err:=regexp.MatchString({:?},{target});err!=nil||!matched{{return fmt.Errorf(\"integer pattern violated\")}}",format!("^(?:{pattern})$")).unwrap();
1894
+ let lit = crate::codegen::format_c_style_string_literal(&format!("^(?:{pattern})$"));
1895
+ writeln!(out,"{indent}if matched,err:=regexp.MatchString({lit},{target});err!=nil||!matched{{return fmt.Errorf(\"integer pattern violated\")}}").unwrap();
1893
1896
  }
1894
1897
  for (i, (bound, op)) in [
1895
1898
  (&facets.min_inclusive, "<"),
@@ -1914,7 +1917,8 @@ func (v {name}) MarshalXML(e *xml.Encoder,start xml.StartElement) error {{
1914
1917
  indent: &str,
1915
1918
  ) {
1916
1919
  for pattern in &facets.patterns {
1917
- writeln!(out, "{}if matched, err := regexp.MatchString({:?}, fmt.Sprint({})); err != nil || !matched {{ return fmt.Errorf(\"pattern constraint failed\") }}", indent, format!("^(?:{pattern})$"), target).unwrap();
1920
+ let lit = crate::codegen::format_c_style_string_literal(&format!("^(?:{pattern})$"));
1921
+ writeln!(out, "{}if matched, err := regexp.MatchString({}, fmt.Sprint({})); err != nil || !matched {{ return fmt.Errorf(\"pattern constraint failed\") }}", indent, lit, target).unwrap();
1918
1922
  }
1919
1923
  if let Some(min_len) = facets.min_length {
1920
1924
  writeln!(
@@ -1987,9 +1991,14 @@ func (v {name}) MarshalXML(e *xml.Encoder,start xml.StartElement) error {{
1987
1991
  {
1988
1992
  let namespace = elem.qname.namespace.as_deref().unwrap_or("");
1989
1993
  writeln!(out, "type {} {}\n", elem_alias, target_type).unwrap();
1994
+ let conv_type = if target_type.starts_with('*') {
1995
+ format!("({target_type})")
1996
+ } else {
1997
+ target_type.clone()
1998
+ };
1990
1999
  if matches!(&elem.type_ref, TypeRef::Named(q) if matches!(ir.types.get(q), Some(TypeDef::Struct(s)) if s.is_abstract))
1991
2000
  {
1992
- writeln!(out, "func (r {elem_alias}) Selected() string {{ return {target_type}(r).Selected() }}\n").unwrap();
2001
+ writeln!(out, "func (r {elem_alias}) Selected() string {{ return {conv_type}(r).Selected() }}\n").unwrap();
1993
2002
  }
1994
2003
  writeln!(out, "func (r *{elem_alias}) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {{\n if start.Name.Local != {:?} || start.Name.Space != {:?} {{ return fmt.Errorf(\"unexpected root element: %v\", start.Name) }}\n return d.DecodeElement((*{target_type})(r), &start)\n}}\n", elem.qname.local, namespace).unwrap();
1995
2004
  let bind_name = if matches!(&elem.type_ref, TypeRef::Named(q) if matches!(ir.types.get(q), Some(TypeDef::Struct(_))))
@@ -1998,7 +2007,7 @@ func (v {name}) MarshalXML(e *xml.Encoder,start xml.StartElement) error {{
1998
2007
  } else {
1999
2008
  ""
2000
2009
  };
2001
- writeln!(out, "func (r {elem_alias}) MarshalXML(e *xml.Encoder, start xml.StartElement) error {{\n start.Name = xml.Name{{Local: {:?}, Space: {:?}}}\n value := {target_type}(r)\n{bind_name} return e.EncodeElement(value, start)\n}}\n", elem.qname.local, namespace).unwrap();
2010
+ writeln!(out, "func (r {elem_alias}) MarshalXML(e *xml.Encoder, start xml.StartElement) error {{\n start.Name = xml.Name{{Local: {:?}, Space: {:?}}}\n value := {conv_type}(r)\n{bind_name} return e.EncodeElement(value, start)\n}}\n", elem.qname.local, namespace).unwrap();
2002
2011
  } else {
2003
2012
  writeln!(out, "type {} = {}\n", elem_alias, target_type).unwrap();
2004
2013
  }
@@ -2007,6 +2016,49 @@ func (v {name}) MarshalXML(e *xml.Encoder,start xml.StartElement) error {{
2007
2016
  }
2008
2017
  }
2009
2018
 
2019
+ fn go_code_uses_pkg(body: &str, pkg_dot: &str) -> bool {
2020
+ let bytes = body.as_bytes();
2021
+ let needle = pkg_dot.as_bytes();
2022
+ let mut i = 0;
2023
+ while i < bytes.len() {
2024
+ if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'/') {
2025
+ while i < bytes.len() && bytes[i] != b'\n' {
2026
+ i += 1;
2027
+ }
2028
+ continue;
2029
+ }
2030
+ if bytes[i] == b'"' {
2031
+ i += 1;
2032
+ while i < bytes.len() {
2033
+ if bytes[i] == b'\\' {
2034
+ i += 2;
2035
+ continue;
2036
+ }
2037
+ if bytes[i] == b'"' {
2038
+ i += 1;
2039
+ break;
2040
+ }
2041
+ i += 1;
2042
+ }
2043
+ continue;
2044
+ }
2045
+ if bytes[i] == b'`' {
2046
+ i += 1;
2047
+ while i < bytes.len() && bytes[i] != b'`' {
2048
+ i += 1;
2049
+ }
2050
+ i += 1;
2051
+ continue;
2052
+ }
2053
+ let prev_is_ident = i > 0 && (bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_');
2054
+ if !prev_is_ident && bytes[i..].starts_with(needle) {
2055
+ return true;
2056
+ }
2057
+ i += 1;
2058
+ }
2059
+ false
2060
+ }
2061
+
2010
2062
  fn derives_from(ir: &SchemaIR, d: &StructDef, base: &QName) -> bool {
2011
2063
  let mut seen: HashSet<QName> = HashSet::new();
2012
2064
  let mut cur = d.base_type.as_ref();
@@ -155,15 +155,42 @@ impl JavaCodegen {
155
155
  while (reader.getEventType() != XMLStreamConstants.START_ELEMENT && reader.hasNext()) reader.next();
156
156
  if (reader.getEventType() != XMLStreamConstants.START_ELEMENT) throw new XMLStreamException("Expected start element");
157
157
  if (nil(reader)) {{ skip(reader); return null; }}
158
- if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type") != null)
159
- throw new XMLStreamException("Runtime xsi:type dispatch is not supported; select a concrete codec", reader.getLocation());
158
+ {xsi_check}
160
159
  try {{
161
160
  "#,
162
161
  local = root.local,
163
- ns = root.namespace.as_deref().unwrap_or("")
162
+ ns = root.namespace.as_deref().unwrap_or(""),
163
+ xsi_check = if self.options.xsi_type {
164
+ " String xsiType = reader.getAttributeValue(\"http://www.w3.org/2001/XMLSchema-instance\", \"type\");\n String localType = xsiType == null ? null : (xsiType.indexOf(':') >= 0 ? xsiType.substring(xsiType.indexOf(':') + 1) : xsiType);"
165
+ } else {
166
+ " if (reader.getAttributeValue(\"http://www.w3.org/2001/XMLSchema-instance\", \"type\") != null)\n throw new XMLStreamException(\"Runtime xsi:type dispatch is not supported; select a concrete codec\", reader.getLocation());"
167
+ }
164
168
  );
165
169
  match def {
166
- TypeDef::Struct(s) => self.emit_read_struct(&mut out, s, ir),
170
+ TypeDef::Struct(s) => {
171
+ if self.options.xsi_type {
172
+ if let Some(fam) = super::java_poly_family(&s.qname) {
173
+ for m in &fam.members {
174
+ if m == &s.qname {
175
+ continue;
176
+ }
177
+ let m_ident = type_ident(m);
178
+ let _ = writeln!(
179
+ out,
180
+ " if ({:?}.equals(localType)) return {m_ident}Codec.readXml(reader);",
181
+ m.local
182
+ );
183
+ }
184
+ if s.is_abstract {
185
+ let _ = writeln!(
186
+ out,
187
+ " if (localType != null) throw new XMLStreamException(\"Unknown xsi:type: \" + xsiType, reader.getLocation());"
188
+ );
189
+ }
190
+ }
191
+ }
192
+ self.emit_read_struct(&mut out, s, ir);
193
+ }
167
194
  TypeDef::Simple(s) => {
168
195
  let expr = self.parse_scalar(
169
196
  if s.facets.patterns.is_empty() {
@@ -202,19 +229,84 @@ impl JavaCodegen {
202
229
  }
203
230
  }
204
231
  out.push_str(" } catch (IllegalArgumentException | java.time.DateTimeException ex) { throw new XMLStreamException(\"Invalid XML value\", reader.getLocation(), ex); }\n }\n");
205
- let concrete_check = if !self.options.use_records && matches!(def, TypeDef::Struct(_)) {
232
+ let concrete_check = if !self.options.use_records
233
+ && !self.options.xsi_type
234
+ && matches!(def, TypeDef::Struct(_))
235
+ {
206
236
  format!(" if (value != null && value.getClass() != {name}.class) throw new XMLStreamException(\"Use the concrete type's codec to preserve derived fields\");\n")
207
237
  } else {
208
238
  String::new()
209
239
  };
210
240
  let is_union = matches!(def, TypeDef::Union(_));
241
+ let xsi_struct = if self.options.xsi_type {
242
+ match def {
243
+ TypeDef::Struct(s) => Some(s),
244
+ _ => None,
245
+ }
246
+ } else {
247
+ None
248
+ };
211
249
  if is_union {
212
250
  let _ = writeln!(out, " public static void writeXml({name} value, XMLStreamWriter writer, String local, String ns) throws XMLStreamException {{\n boolean hasLocal = local != null && !local.isEmpty();\n if (hasLocal) start(writer, local, ns);\n if (value == null) {{\n if (hasLocal) {{\n writer.writeNamespace(\"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\");\n writer.writeAttribute(\"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\", \"nil\", \"true\");\n writer.writeEndElement();\n }}\n return;\n }}");
251
+ } else if let Some(s) = xsi_struct {
252
+ let _ = writeln!(
253
+ out,
254
+ " public static void writeXml({name} value, XMLStreamWriter writer, String local, String ns) throws XMLStreamException {{\n writeXmlWithXsiType(value, writer, local, ns, null);\n }}\n public static void writeXmlWithXsiType({name} value, XMLStreamWriter writer, String local, String ns, String xsiType) throws XMLStreamException {{"
255
+ );
256
+ if let Some(fam) = super::java_poly_family(&s.qname) {
257
+ let mut derived: Vec<(&QName, usize)> = fam
258
+ .members
259
+ .iter()
260
+ .filter(|m| *m != &s.qname)
261
+ .filter_map(|m| {
262
+ let depth =
263
+ std::iter::successors(Some(m), |curr| match ir.find_type(curr) {
264
+ Some(TypeDef::Struct(st)) => st.base_type.as_ref(),
265
+ _ => None,
266
+ })
267
+ .take(32)
268
+ .count();
269
+ if !self.options.use_records || matches!(s.base_type, _) && s.is_abstract {
270
+ Some((m, depth))
271
+ } else {
272
+ // In record mode, a concrete base record cannot have `instanceof` subtypes.
273
+ None
274
+ }
275
+ })
276
+ .collect();
277
+ derived.sort_by_key(|a| std::cmp::Reverse(a.1));
278
+ if !derived.is_empty() {
279
+ out.push_str(" if (value != null) {\n");
280
+ for (m, _) in derived {
281
+ let m_ident = type_ident(m);
282
+ let _ = writeln!(
283
+ out,
284
+ " if (value instanceof {m_ident} derived) {{ {m_ident}Codec.writeXmlWithXsiType(derived, writer, local, ns, {:?}); return; }}",
285
+ m.local
286
+ );
287
+ }
288
+ out.push_str(" }\n");
289
+ }
290
+ }
291
+ let _ = writeln!(
292
+ out,
293
+ " start(writer, local, ns);\n if (value == null) {{\n writeNil(writer);\n writer.writeEndElement(); return;\n }}\n if (xsiType != null) {{\n writer.writeNamespace(\"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\");\n writer.writeAttribute(\"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\", \"type\", xsiType);\n }}"
294
+ );
213
295
  } else {
214
296
  let _=writeln!(out," public static void writeXml({name} value, XMLStreamWriter writer, String local, String ns) throws XMLStreamException {{\n{concrete_check} start(writer, local, ns);\n if (value == null) {{\n writer.writeNamespace(\"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\");\n writer.writeAttribute(\"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\", \"nil\", \"true\");\n writer.writeEndElement(); return;\n }}");
215
297
  }
216
298
  match def {
217
- TypeDef::Struct(s) => self.emit_write_struct(&mut out, s, ir),
299
+ TypeDef::Struct(s) => {
300
+ if self.options.xsi_type && s.is_abstract {
301
+ let _ = writeln!(
302
+ out,
303
+ " throw new XMLStreamException(\"Cannot serialize abstract XML type without concrete subtype: \" + {:?});",
304
+ name
305
+ );
306
+ } else {
307
+ self.emit_write_struct(&mut out, s, ir);
308
+ }
309
+ }
218
310
  TypeDef::Enum(_) => out.push_str(" writer.writeCharacters(value.getValue());\n"),
219
311
  TypeDef::Simple(s) => {
220
312
  let access = if self.options.use_records {
@@ -268,6 +360,8 @@ impl JavaCodegen {
268
360
  }
269
361
  if is_union {
270
362
  out.push_str(" if (hasLocal) writer.writeEndElement();\n }\n}\n");
363
+ } else if self.options.xsi_type && matches!(def, TypeDef::Struct(s) if s.is_abstract) {
364
+ out.push_str(" }\n}\n");
271
365
  } else {
272
366
  out.push_str(" writer.writeEndElement();\n }\n}\n");
273
367
  }
@@ -276,7 +370,7 @@ impl JavaCodegen {
276
370
 
277
371
  fn emit_read_struct(&self, out: &mut String, s: &StructDef, ir: &SchemaIR) {
278
372
  let name = type_ident(&s.qname);
279
- if s.is_abstract && !self.options.use_records {
373
+ if s.is_abstract && (!self.options.use_records || self.options.xsi_type) {
280
374
  out.push_str(" throw new XMLStreamException(\"Cannot instantiate abstract XML type without a concrete codec\");\n");
281
375
  return;
282
376
  }