polyxml 0.39.3__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.3 → polyxml-0.40.0}/Cargo.lock +6 -6
  2. {polyxml-0.39.3 → polyxml-0.40.0}/Cargo.toml +1 -1
  3. {polyxml-0.39.3 → polyxml-0.40.0}/PKG-INFO +1 -1
  4. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/csharp/mod.rs +33 -3
  5. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/go/mod.rs +7 -3
  6. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/java/codec.rs +101 -7
  7. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/java/mod.rs +78 -10
  8. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/mod.rs +92 -0
  9. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/python/aot.rs +1 -0
  10. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/python/mod.rs +1 -1
  11. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/rust/mod.rs +306 -13
  12. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/json.rs +107 -55
  13. polyxml-0.40.0/crates/polyxml-core/tests/test_issue_162.rs +56 -0
  14. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_java_codegen.rs +115 -0
  15. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_rust_codegen.rs +115 -0
  16. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_transcoder.rs +117 -0
  17. {polyxml-0.39.3 → polyxml-0.40.0}/pyproject.toml +1 -1
  18. {polyxml-0.39.3 → polyxml-0.40.0}/README.md +0 -0
  19. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/Cargo.toml +0 -0
  20. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/README.md +0 -0
  21. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/benches/core_benchmarks.rs +0 -0
  22. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/benches/support/tag_dispatch_fixtures.rs +0 -0
  23. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/benches/tag_dispatch.rs +0 -0
  24. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/cpp/mod.rs +0 -0
  25. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/java/models.rs +0 -0
  26. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/codegen/typescript/mod.rs +0 -0
  27. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/converters.rs +0 -0
  28. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/error.rs +0 -0
  29. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/integer.rs +0 -0
  30. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/ir/chunker.rs +0 -0
  31. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/ir/mod.rs +0 -0
  32. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/ir/particle.rs +0 -0
  33. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/ir/tarjan.rs +0 -0
  34. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/lib.rs +0 -0
  35. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/parser.rs +0 -0
  36. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/pattern.rs +0 -0
  37. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/schema.rs +0 -0
  38. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/schema_parser/mod.rs +0 -0
  39. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/schema_parser/upa.rs +0 -0
  40. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/serializer.rs +0 -0
  41. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/transcoder.rs +0 -0
  42. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/src/value.rs +0 -0
  43. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/fixtures/lexical_union.xsd +0 -0
  44. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/fixtures/mixed_content.xsd +0 -0
  45. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/fixtures/ts_mixed_content_inheritance.xsd +0 -0
  46. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_adversarial_identifiers.rs +0 -0
  47. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_any_attribute.rs +0 -0
  48. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_any_element.rs +0 -0
  49. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_conformance.rs +0 -0
  50. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_core.rs +0 -0
  51. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_corpus_regressions.rs +0 -0
  52. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_cpp_codegen.rs +0 -0
  53. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_csharp_codegen.rs +0 -0
  54. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_default_literal_codegen.rs +0 -0
  55. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_enum_literal_codegen.rs +0 -0
  56. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_go_codegen.rs +0 -0
  57. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_inherited_simple_content.rs +0 -0
  58. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_inherited_text_codegen.rs +0 -0
  59. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_json.rs +0 -0
  60. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_lexical_lists.rs +0 -0
  61. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_lexical_union_codegen.rs +0 -0
  62. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_mixed_branch_lookup.rs +0 -0
  63. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_mixed_content.rs +0 -0
  64. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_mixed_nil.rs +0 -0
  65. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_namespace_entities.rs +0 -0
  66. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_pattern_codegen.rs +0 -0
  67. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_python_codegen.rs +0 -0
  68. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_qualified_attributes.rs +0 -0
  69. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_runtime_fast_paths.rs +0 -0
  70. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_rust_codecs.rs +0 -0
  71. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_schema_attribute_entities.rs +0 -0
  72. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_schema_audit.rs +0 -0
  73. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_schema_ir.rs +0 -0
  74. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_security.rs +0 -0
  75. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_temporal_union.rs +0 -0
  76. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_ts_codegen.rs +0 -0
  77. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_ubl_csharp.rs +0 -0
  78. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_unbounded_choice.rs +0 -0
  79. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_upa.rs +0 -0
  80. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_value_constraints.rs +0 -0
  81. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_variant_registry.rs +0 -0
  82. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-core/tests/test_xsi_type.rs +0 -0
  83. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-python/Cargo.toml +0 -0
  84. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-python/README.md +0 -0
  85. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-python/benches/aot_vs_dataclass.py +0 -0
  86. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-python/src/lib.rs +0 -0
  87. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-python/tests/test_binary_fields.py +0 -0
  88. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-python/tests/test_conformance.py +0 -0
  89. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-python/tests/test_generated_models.py +0 -0
  90. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-python/tests/test_json.py +0 -0
  91. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-python/tests/test_mixed_content.py +0 -0
  92. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-python/tests/test_polyxml.py +0 -0
  93. {polyxml-0.39.3 → polyxml-0.40.0}/crates/polyxml-python/tests/test_xsi_type.py +0 -0
  94. {polyxml-0.39.3 → polyxml-0.40.0}/python/polyxml/AGENT_GUIDE.md +0 -0
  95. {polyxml-0.39.3 → polyxml-0.40.0}/python/polyxml/__init__.py +0 -0
  96. {polyxml-0.39.3 → polyxml-0.40.0}/python/polyxml/compat/__init__.py +0 -0
  97. {polyxml-0.39.3 → polyxml-0.40.0}/python/polyxml/compat/xsdata.py +0 -0
  98. {polyxml-0.39.3 → 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.3"
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.3"
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.3"
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.3"
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.3"
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.3"
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.3"
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.3
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
@@ -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(" && ");
@@ -2057,7 +2060,8 @@ impl CSharpCodegen {
2057
2060
  indent: &str,
2058
2061
  ) {
2059
2062
  for pattern in &facets.patterns {
2060
- 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();
2061
2065
  }
2062
2066
  for (bound, op) in [
2063
2067
  (&facets.min_inclusive, "<"),
@@ -2098,7 +2102,10 @@ impl CSharpCodegen {
2098
2102
  for pattern in &facets.patterns {
2099
2103
  let escaped = format!(r"\A(?:{pattern})\z")
2100
2104
  .replace('\\', "\\\\")
2101
- .replace('"', "\\\"");
2105
+ .replace('"', "\\\"")
2106
+ .replace('\r', "\\r")
2107
+ .replace('\n', "\\n")
2108
+ .replace('\t', "\\t");
2102
2109
  writeln!(
2103
2110
  out,
2104
2111
  "{}if (!Regex.IsMatch({}.ToString() ?? \"\", \"{}\")) yield return new ValidationResult(\"{} does not match pattern {}\", [nameof({})]);",
@@ -2352,3 +2359,26 @@ impl CSharpCodegen {
2352
2359
  writeln!(out, "{}/// </summary>", indent).unwrap();
2353
2360
  }
2354
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
+ }
@@ -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!(
@@ -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
  }
@@ -1,21 +1,38 @@
1
1
  mod codec;
2
2
  mod models;
3
3
 
4
- use std::collections::HashSet;
4
+ use std::collections::{HashMap, HashSet};
5
5
  use std::fmt::Write as FmtWrite;
6
6
 
7
7
  use heck::{AsLowerCamelCase, AsPascalCase, AsShoutySnakeCase};
8
8
  use serde::{Deserialize, Serialize};
9
9
 
10
10
  use crate::codegen::{
11
- build_type_name_map, lookup_type_name, normalize_symbol_name, sanitize_keyword,
12
- set_type_name_map, LanguageContext,
11
+ build_type_name_map, compute_poly_families, lookup_type_name, normalize_symbol_name,
12
+ sanitize_keyword, set_type_name_map, LanguageContext, PolyFamily,
13
13
  };
14
14
  use crate::ir::{
15
15
  EnumDef, PrimitiveType, QName, RestrictionFacets, SchemaIR, SimpleTypeDef, StructDef, TypeDef,
16
16
  TypeRef, UnionBranch, UnionDef,
17
17
  };
18
18
 
19
+ thread_local! {
20
+ static JAVA_POLY_FAMILIES: std::cell::RefCell<HashMap<QName, PolyFamily>> =
21
+ std::cell::RefCell::new(HashMap::new());
22
+ }
23
+
24
+ pub(super) fn set_java_poly_families(families: HashMap<QName, PolyFamily>) {
25
+ JAVA_POLY_FAMILIES.with(|m| *m.borrow_mut() = families);
26
+ }
27
+
28
+ pub(super) fn java_poly_family(q: &QName) -> Option<PolyFamily> {
29
+ JAVA_POLY_FAMILIES.with(|m| m.borrow().get(q).cloned())
30
+ }
31
+
32
+ pub(super) fn is_java_abstract_poly_base(q: &QName) -> bool {
33
+ JAVA_POLY_FAMILIES.with(|m| m.borrow().get(q).is_some_and(|f| f.base_abstract))
34
+ }
35
+
19
36
  /// Target backend for Java code emission.
20
37
  #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
21
38
  pub enum JavaBackend {
@@ -65,6 +82,9 @@ pub struct JavaOptions {
65
82
  pub bean_validation: bool,
66
83
  /// Emit top-level aliases for root elements (default: true)
67
84
  pub emit_root_aliases: bool,
85
+ /// Emit `xsi:type` polymorphic dispatch on direct StAX codecs (default: false)
86
+ #[serde(default)]
87
+ pub xsi_type: bool,
68
88
  /// Custom header text to prepend to generated files (default: None)
69
89
  pub custom_header: Option<String>,
70
90
  }
@@ -80,6 +100,7 @@ impl Default for JavaOptions {
80
100
  validate_facets: true,
81
101
  bean_validation: false,
82
102
  emit_root_aliases: true,
103
+ xsi_type: false,
83
104
  custom_header: None,
84
105
  }
85
106
  }
@@ -302,6 +323,11 @@ impl JavaCodegen {
302
323
  /// Generate individual compilation units (`{TypeName}.java`), one for each schema type.
303
324
  pub fn generate_files(&self, ir: &SchemaIR) -> Vec<(String, String)> {
304
325
  set_type_name_map(build_type_name_map(ir, to_java_type_name));
326
+ set_java_poly_families(if self.options.xsi_type {
327
+ compute_poly_families(ir)
328
+ } else {
329
+ HashMap::new()
330
+ });
305
331
  let mut files = Vec::new();
306
332
 
307
333
  for type_def in ir.emitted_types() {
@@ -322,6 +348,11 @@ impl JavaCodegen {
322
348
  /// Generate a single outer class (`{outer_class_name}.java`) enclosing all types as static members.
323
349
  pub fn generate_module(&self, ir: &SchemaIR, outer_class_name: &str) -> String {
324
350
  set_type_name_map(build_type_name_map(ir, to_java_type_name));
351
+ set_java_poly_families(if self.options.xsi_type {
352
+ compute_poly_families(ir)
353
+ } else {
354
+ HashMap::new()
355
+ });
325
356
  let mut out = String::new();
326
357
 
327
358
  self.emit_file_header(&mut out);
@@ -487,6 +518,27 @@ impl JavaCodegen {
487
518
  self.emit_pojo(out, s, java_name, indent, ir);
488
519
  return;
489
520
  }
521
+ if self.options.xsi_type && s.is_abstract && is_java_abstract_poly_base(&s.qname) {
522
+ if let Some(ref doc) = s.documentation {
523
+ self.emit_docstring(out, doc, indent);
524
+ }
525
+ let static_kw = if indent.is_empty() { "" } else { "static " };
526
+ let extends = s
527
+ .base_type
528
+ .as_ref()
529
+ .filter(|q| is_java_abstract_poly_base(q))
530
+ .map(|q| format!(" extends {}", type_ident(q)))
531
+ .unwrap_or_default();
532
+ let _ = writeln!(
533
+ out,
534
+ "{indent}public {static_kw}interface {java_name}{extends} {{"
535
+ );
536
+ for (field, field_id) in self.model_fields(s, ir) {
537
+ let _ = writeln!(out, "{indent} {} {field_id}();", self.field_type(field));
538
+ }
539
+ let _ = writeln!(out, "{indent}}}");
540
+ return;
541
+ }
490
542
  if let Some(ref doc) = s.documentation {
491
543
  self.emit_docstring(out, doc, indent);
492
544
  }
@@ -585,9 +637,22 @@ impl JavaCodegen {
585
637
  } else {
586
638
  "public static "
587
639
  };
640
+ let impl_clause = if self.options.xsi_type {
641
+ s.base_type
642
+ .as_ref()
643
+ .filter(|q| is_java_abstract_poly_base(q))
644
+ .map(|q| format!(" implements {}", type_ident(q)))
645
+ .unwrap_or_default()
646
+ } else {
647
+ String::new()
648
+ };
588
649
 
589
650
  if components.is_empty() && !self.options.emit_builder {
590
- let _ = writeln!(out, "{}{}record {}() {{}}", indent, modifier, java_name);
651
+ let _ = writeln!(
652
+ out,
653
+ "{}{}record {}(){impl_clause} {{}}",
654
+ indent, modifier, java_name
655
+ );
591
656
  return;
592
657
  }
593
658
 
@@ -596,7 +661,7 @@ impl JavaCodegen {
596
661
  let comma = if i + 1 < components.len() { "," } else { "" };
597
662
  let _ = writeln!(out, "{} {}{}", indent, comp, comma);
598
663
  }
599
- let _ = writeln!(out, "{}) {{", indent);
664
+ let _ = writeln!(out, "{}){impl_clause} {{", indent);
600
665
 
601
666
  if !validation_checks.is_empty() {
602
667
  let _ = writeln!(out, "{} public {} {{", indent, java_name);
@@ -934,8 +999,9 @@ impl JavaCodegen {
934
999
  }
935
1000
  if is_string && !is_optional {
936
1001
  for pattern in &facets.patterns {
1002
+ let lit = crate::codegen::format_c_style_string_literal(pattern);
937
1003
  annotations.push(format!(
938
- "@jakarta.validation.constraints.Pattern(regexp = {pattern:?})"
1004
+ "@jakarta.validation.constraints.Pattern(regexp = {lit})"
939
1005
  ));
940
1006
  }
941
1007
  }
@@ -1076,9 +1142,10 @@ impl JavaCodegen {
1076
1142
  ));
1077
1143
  }
1078
1144
  for pat in &facets.patterns {
1145
+ let lit = crate::codegen::format_c_style_string_literal(pat);
1079
1146
  checks.push(format!(
1080
- "{}.ifPresent(v -> {{ if (!Pattern.compile({:?}).matcher(v).matches()) throw new IllegalArgumentException(\"{} does not match pattern: \" + {:?}); }});",
1081
- var_name, pat, var_name, pat
1147
+ "{}.ifPresent(v -> {{ if (!Pattern.compile({}).matcher(v).matches()) throw new IllegalArgumentException(\"{} does not match pattern: \" + {}); }});",
1148
+ var_name, lit, var_name, lit
1082
1149
  ));
1083
1150
  }
1084
1151
  } else {
@@ -1105,9 +1172,10 @@ impl JavaCodegen {
1105
1172
  ));
1106
1173
  }
1107
1174
  for pat in &facets.patterns {
1175
+ let lit = crate::codegen::format_c_style_string_literal(pat);
1108
1176
  checks.push(format!(
1109
- "if (!Pattern.compile({:?}).matcher({}).matches()) throw new IllegalArgumentException(\"{} does not match pattern: \" + {:?});",
1110
- pat, var_name, var_name, pat
1177
+ "if (!Pattern.compile({}).matcher({}).matches()) throw new IllegalArgumentException(\"{} does not match pattern: \" + {});",
1178
+ lit, var_name, var_name, lit
1111
1179
  ));
1112
1180
  }
1113
1181
  }
@@ -809,3 +809,95 @@ pub(crate) fn unbounded_integer(
809
809
  },
810
810
  }
811
811
  }
812
+
813
+ /// Format a double-quoted string literal using escapes valid across Python, Go, Java, and C#
814
+ /// (avoiding Rust's `\u{...}` debug escape syntax).
815
+ pub(crate) fn format_c_style_string_literal(s: &str) -> String {
816
+ let mut out = String::with_capacity(s.len() + 2);
817
+ out.push('"');
818
+ for ch in s.chars() {
819
+ match ch {
820
+ '\\' => out.push_str("\\\\"),
821
+ '"' => out.push_str("\\\""),
822
+ '\n' => out.push_str("\\n"),
823
+ '\r' => out.push_str("\\r"),
824
+ '\t' => out.push_str("\\t"),
825
+ c if c.is_control() && (c as u32) <= 0xFFFF => {
826
+ use std::fmt::Write as _;
827
+ let _ = write!(out, "\\u{:04x}", c as u32);
828
+ }
829
+ c => out.push(c),
830
+ }
831
+ }
832
+ out.push('"');
833
+ out
834
+ }
835
+
836
+ /// A polymorphic type family for `--feature xsi-type`: a complex type that
837
+ /// other complex types derive from (or an abstract base), plus every concrete
838
+ /// transitive derivation.
839
+ #[derive(Debug, Clone)]
840
+ pub(crate) struct PolyFamily {
841
+ pub(crate) base: crate::ir::QName,
842
+ pub(crate) base_abstract: bool,
843
+ /// Concrete dispatchable members in deterministic order (includes `base` first when `!base_abstract`).
844
+ pub(crate) members: Vec<crate::ir::QName>,
845
+ }
846
+
847
+ pub(crate) fn compute_poly_families(
848
+ ir: &crate::ir::SchemaIR,
849
+ ) -> HashMap<crate::ir::QName, PolyFamily> {
850
+ use crate::ir::{QName, TypeDef};
851
+ let mut derived_of: HashMap<QName, Vec<QName>> = HashMap::new();
852
+ for (qname, td) in &ir.types {
853
+ let TypeDef::Struct(s) = td else { continue };
854
+ if ir.is_external_type(qname) || s.is_abstract {
855
+ continue;
856
+ }
857
+ let mut seen = HashSet::new();
858
+ let mut current = s.base_type.clone();
859
+ while let Some(base) = current {
860
+ if base == s.qname || !seen.insert(base.clone()) {
861
+ break;
862
+ }
863
+ match ir.find_type(&base) {
864
+ Some(TypeDef::Struct(parent)) => {
865
+ derived_of
866
+ .entry(base.clone())
867
+ .or_default()
868
+ .push(s.qname.clone());
869
+ current = parent.base_type.clone();
870
+ }
871
+ _ => break,
872
+ }
873
+ }
874
+ }
875
+ let mut families = HashMap::new();
876
+ for (qname, td) in &ir.types {
877
+ let TypeDef::Struct(b) = td else { continue };
878
+ if ir.is_external_type(qname) {
879
+ continue;
880
+ }
881
+ let derived_opt = derived_of.remove(qname);
882
+ if !b.is_abstract && derived_opt.is_none() {
883
+ continue;
884
+ }
885
+ let mut derived = derived_opt.unwrap_or_default();
886
+ derived.sort();
887
+ derived.dedup();
888
+ let mut members = Vec::new();
889
+ if !b.is_abstract {
890
+ members.push(qname.clone());
891
+ }
892
+ members.extend(derived);
893
+ families.insert(
894
+ qname.clone(),
895
+ PolyFamily {
896
+ base: qname.clone(),
897
+ base_abstract: b.is_abstract,
898
+ members,
899
+ },
900
+ );
901
+ }
902
+ families
903
+ }
@@ -144,6 +144,7 @@ restored_json = {module_name}.<ModelName>.from_json(json_data)
144
144
  emit_codecs: true,
145
145
  emit_rkyv: false,
146
146
  phf: false,
147
+ xsi_type: false,
147
148
  pyo3: true,
148
149
  pyo3_module_name: Some(module_name.clone()),
149
150
  custom_header: self.options.custom_header.clone(),
@@ -513,7 +513,7 @@ impl PythonCodegen {
513
513
  .facets
514
514
  .patterns
515
515
  .iter()
516
- .map(|pattern| format!("{:?}", pattern))
516
+ .map(|pattern| crate::codegen::format_c_style_string_literal(pattern))
517
517
  .collect::<Vec<_>>()
518
518
  .join(", ");
519
519
  let _ = writeln!(